@behavioral-agentic-design-system/core 0.49.0 → 0.49.1-beta-20261119021055

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@behavioral-agentic-design-system/core",
3
- "version": "0.49.0",
3
+ "version": "0.49.1-beta-20261119021055",
4
4
  "description": "BADS core — tokens, shadcn/ui components, and the BADS template shell (app routes, customize tab, theme hooks). Forks consume this and re-export, keeping client repos to ~30 lines of glue.",
5
5
  "license": "MIT",
6
6
  "author": "Matthew Stephens <work@matthewstephens.com> (https://github.com/matthewlarn)",
@@ -48,6 +48,7 @@
48
48
  "bads-check-sync": "scripts/check-sync.mjs",
49
49
  "bads-components": "scripts/bads-components.mjs",
50
50
  "bads-deal-directions": "scripts/deal-directions.mjs",
51
+ "bads": "scripts/bads.mjs",
51
52
  "bads-doctor": "scripts/bads-doctor.mjs",
52
53
  "bads-ds-advisory": "scripts/design-system-advisory/run.mjs",
53
54
  "bads-fix-stories": "scripts/fix-stories.mjs",
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bads: the umbrella command for BADS forks. One subcommand today.
4
+ *
5
+ * npx bads connect wire the BADS MCP server and a rules file into every agent tool found
6
+ * npx bads connect --dry-run print every change and write nothing
7
+ * npx bads connect --list show the tools, the files connect would write, and what is wired now
8
+ * npx bads connect --check start each wired MCP server and ask it a question
9
+ * npx bads connect --remove undo exactly what connect wrote
10
+ *
11
+ * Full reference: docs/connect.md. The other bads-* commands (bads-doctor, bads-sync, the lints) keep their names.
12
+ */
13
+ import { readFileSync, realpathSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import { createInterface } from "node:readline/promises";
16
+ import { fileURLToPath } from "node:url";
17
+ import { apply, detectTools, displayPath, makeContext, plan, readEntry, remove, selectTools, targetPath, targetStatus } from "./lib/connect/connect.mjs";
18
+ import { probeContracts, probeServer } from "./lib/connect/check.mjs";
19
+ import { unifiedDiff } from "./lib/connect/edits.mjs";
20
+ import { TOOL_IDS } from "./lib/connect/tools.mjs";
21
+ import { checkForUpdate } from "./lib/connect/update-check.mjs";
22
+
23
+ const here = dirname(fileURLToPath(import.meta.url));
24
+ const VERSION = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")).version;
25
+
26
+ const HELP = `Usage: bads connect [options]
27
+
28
+ Wires the BADS MCP server and a short rules file into the agent tools in this project.
29
+ By default it writes only inside the project directory.
30
+
31
+ Options:
32
+ --dry-run Print every change as a diff. Write nothing.
33
+ --list Show each tool, whether it was found, its files, and what is wired now.
34
+ --check Start each wired MCP server and call guide or get_contract.
35
+ --remove Undo what connect wrote, using its manifest in .bads/connect/.
36
+ --tools <ids> Only these tools, comma-separated: ${TOOL_IDS.join(", ")}.
37
+ --all Every tool, found or not.
38
+ --global Also write user-level files (home directory, Claude Desktop). Shows the diff and asks first.
39
+ --unverified Also write formats the tool's docs did not confirm. Off by default.
40
+ --yes Answer yes to the --global question (for scripts).
41
+ -h, --help Show this help.
42
+
43
+ Environment:
44
+ BADS_NO_UPDATE_CHECK=1 Skip the version check (the only network call, which sends nothing from the project).
45
+
46
+ Docs: docs/connect.md`;
47
+
48
+ export function parseArgs(argv) {
49
+ const opts = { tools: null, all: false, global: false, unverified: false, dryRun: false, yes: false, mode: "write" };
50
+ for (let i = 0; i < argv.length; i += 1) {
51
+ const a = argv[i];
52
+ if (a === "--dry-run") opts.dryRun = true;
53
+ else if (a === "--list") opts.mode = "list";
54
+ else if (a === "--check") opts.mode = "check";
55
+ else if (a === "--remove") opts.mode = "remove";
56
+ else if (a === "--all") opts.all = true;
57
+ else if (a === "--global") opts.global = true;
58
+ else if (a === "--unverified") opts.unverified = true;
59
+ else if (a === "--yes" || a === "-y") opts.yes = true;
60
+ else if (a === "-h" || a === "--help") opts.mode = "help";
61
+ else if (a === "--tools") opts.tools = (argv[++i] ?? "").split(",").filter(Boolean);
62
+ else if (a.startsWith("--tools=")) opts.tools = a.slice(8).split(",").filter(Boolean);
63
+ else throw new Error(`Unknown option: ${a}`);
64
+ }
65
+ return opts;
66
+ }
67
+
68
+ async function confirm(question, { yes, io }) {
69
+ if (yes) return true;
70
+ if (!io.stdin.isTTY) {
71
+ io.log("Not written: no terminal to ask. Run again with --yes to accept the diff above.");
72
+ return false;
73
+ }
74
+ const rl = createInterface({ input: io.stdin, output: io.stdout });
75
+ const answer = await rl.question(`${question} [y/N] `);
76
+ rl.close();
77
+ return /^y(es)?$/i.test(answer.trim());
78
+ }
79
+
80
+ function printSkipped(skipped, log) {
81
+ if (!skipped.length) return;
82
+ log("\nNot written:");
83
+ for (const s of skipped) log(` ${s.path} (${s.tool}): ${s.reason}`);
84
+ }
85
+
86
+ async function runWrite(ctx, opts, io) {
87
+ const { log } = io;
88
+ const p = plan(ctx, opts);
89
+ if (!p.selected.length) {
90
+ log("No agent tools found in this project or on this machine.");
91
+ log(`Name them with --tools <ids> (${TOOL_IDS.join(", ")}) or use --all. Run --list to see what connect looks for.`);
92
+ return 0;
93
+ }
94
+ log(`Tools: ${p.selected.join(", ")}`);
95
+ if (ctx.identity.components === "client") log(`Client-owned components: the rules point agents at ${ctx.identity.clientLibrary ?? "the client library"}.`);
96
+ if (!ctx.server) log("No BADS MCP server in this project, so connect writes the rules files only.");
97
+ const project = p.changes.filter((c) => c.scope === "project");
98
+ const global = p.changes.filter((c) => c.scope === "global");
99
+ for (const u of p.unchanged) log(` unchanged ${u.display}`);
100
+ if (opts.dryRun) {
101
+ for (const c of p.changes) log(`\n${unifiedDiff(c.before, c.after, c.display)}`);
102
+ printSkipped(p.skipped, log);
103
+ log(`\nDry run: ${p.changes.length} file(s) would change. Nothing was written.`);
104
+ return 0;
105
+ }
106
+ apply(ctx, p, { onlyScopes: ["project"] });
107
+ for (const c of project) log(` ${c.before == null ? "created" : "updated"} ${c.display} (${c.tools.join(", ")})`);
108
+ if (global.length) {
109
+ log("\nUser-level files, outside this project. This is the exact change:");
110
+ for (const c of global) log(`\n${unifiedDiff(c.before, c.after, c.display)}`);
111
+ if (await confirm(`\nWrite these ${global.length} user-level file(s)?`, { yes: opts.yes, io })) {
112
+ apply(ctx, p, { onlyScopes: ["global"] });
113
+ for (const c of global) log(` ${c.before == null ? "created" : "updated"} ${c.display} (backup kept beside it)`);
114
+ } else log("User-level files left as they were.");
115
+ }
116
+ printSkipped(p.skipped, log);
117
+ if (p.changes.length) log("\nUndo with `bads connect --remove`. Test the wiring with `bads connect --check`.");
118
+ else log("\nNothing to change: everything is already wired.");
119
+ return 0;
120
+ }
121
+
122
+ function runList(ctx, opts, io) {
123
+ const { log } = io;
124
+ log(`Project: ${ctx.root}`);
125
+ log(`MCP server: ${ctx.server ? ctx.server.rel : "none found (rules only)"}`);
126
+ log(`Components: ${ctx.identity.components === "client" ? `client-owned (${ctx.identity.clientLibrary ?? "library not named"})` : "BADS"}`);
127
+ const shown = opts.tools?.length || opts.all ? selectTools(ctx, opts) : detectTools(ctx);
128
+ for (const d of shown) {
129
+ const where = [...d.project, ...d.machine];
130
+ log(`\n${d.tool.name} (${d.tool.id}): ${d.detected ? `found (${where.join(", ")})` : "not found"}`);
131
+ for (const t of d.tool.targets) {
132
+ const flags = [t.scope === "global" ? "needs --global" : "project", t.verified ? "verified" : "unverified, off by default"].join(", ");
133
+ log(` ${t.role.padEnd(5)} ${displayPath(ctx, targetPath(ctx, t)).padEnd(42)} ${targetStatus(ctx, t).padEnd(8)} ${flags}`);
134
+ }
135
+ }
136
+ return 0;
137
+ }
138
+
139
+ async function runCheck(ctx, opts, io) {
140
+ const { log } = io;
141
+ const seen = new Map();
142
+ for (const { tool } of selectTools(ctx, { ...opts, all: opts.all || !opts.tools })) {
143
+ for (const t of tool.targets) {
144
+ if (t.role !== "mcp" || (t.scope === "global" && !opts.global)) continue;
145
+ const entry = readEntry(ctx, t);
146
+ if (!entry) continue;
147
+ const key = `${targetPath(ctx, t)}#${(t.keyPath ?? []).join(".")}`;
148
+ if (!seen.has(key)) seen.set(key, { display: displayPath(ctx, targetPath(ctx, t)), tools: [], entry });
149
+ seen.get(key).tools.push(tool.id);
150
+ }
151
+ }
152
+ let failed = 0;
153
+ if (!seen.size && !ctx.contracts) {
154
+ log("Nothing is wired yet. Run `bads connect` first.");
155
+ return 1;
156
+ }
157
+ for (const s of seen.values()) {
158
+ const r = await probeServer(s.entry, { root: ctx.root });
159
+ if (!r.ok) failed += 1;
160
+ log(`${r.ok ? "pass" : "FAIL"} ${s.display} (${s.tools.join(", ")}): ${r.detail}`);
161
+ }
162
+ if (ctx.contracts && (!ctx.server || ctx.identity.components === "client")) {
163
+ const r = probeContracts(ctx);
164
+ if (!r.ok) failed += 1;
165
+ log(`${r.ok ? "pass" : "FAIL"} contracts command: ${r.detail}`);
166
+ }
167
+ log(failed ? `\n${failed} check(s) failed.` : "\nEvery wired tool answered.");
168
+ return failed ? 1 : 0;
169
+ }
170
+
171
+ async function runRemove(ctx, opts, io) {
172
+ const { log } = io;
173
+ if (opts.global && !opts.dryRun) {
174
+ const preview = remove(ctx, { global: true, dryRun: true });
175
+ const globals = preview.diffs.filter((d) => d.scope === "global");
176
+ if (globals.length) {
177
+ log("User-level files, outside this project. This is the exact change:");
178
+ for (const d of globals) log(`\n${unifiedDiff(d.before, d.after, d.display)}`);
179
+ if (!(await confirm("\nUndo these user-level changes?", { yes: opts.yes, io }))) {
180
+ log("Nothing removed.");
181
+ return 0;
182
+ }
183
+ }
184
+ }
185
+ const r = remove(ctx, opts);
186
+ if (opts.dryRun) {
187
+ for (const d of r.diffs) log(`\n${unifiedDiff(d.before, d.after, d.display)}`);
188
+ log("\nDry run: nothing was removed.");
189
+ return 0;
190
+ }
191
+ for (const f of r.restored) log(` restored ${f} (byte for byte from the backup)`);
192
+ for (const f of r.deleted) log(` deleted ${f} (connect created it)`);
193
+ for (const f of r.stripped) log(` edited ${f} (changed since connect wrote it, so only connect's part was taken out)`);
194
+ for (const f of r.missing) log(` missing ${f} (already gone)`);
195
+ for (const f of r.kept) log(` kept ${f} (user-level: run --remove --global to undo it)`);
196
+ if (![r.restored, r.deleted, r.stripped, r.missing, r.kept].some((l) => l.length)) log("Nothing to remove: connect has not written anything here.");
197
+ return 0;
198
+ }
199
+
200
+ export async function main(argv, { cwd = process.cwd(), env = process.env, io = { log: console.log, stdin: process.stdin, stdout: process.stdout } } = {}) {
201
+ const [cmd, ...rest] = argv;
202
+ if (!cmd || cmd === "-h" || cmd === "--help" || cmd === "help") {
203
+ io.log(HELP);
204
+ return cmd ? 0 : 2;
205
+ }
206
+ if (cmd !== "connect") {
207
+ io.log(`Unknown command: ${cmd}\n\n${HELP}`);
208
+ return 2;
209
+ }
210
+ let opts;
211
+ try {
212
+ opts = parseArgs(rest);
213
+ } catch (e) {
214
+ io.log(`${e.message}\n\n${HELP}`);
215
+ return 2;
216
+ }
217
+ if (opts.mode === "help") {
218
+ io.log(HELP);
219
+ return 0;
220
+ }
221
+ const ctx = makeContext({ cwd, env });
222
+ let code;
223
+ try {
224
+ if (opts.mode === "list") code = runList(ctx, opts, io);
225
+ else if (opts.mode === "check") code = await runCheck(ctx, opts, io);
226
+ else if (opts.mode === "remove") code = await runRemove(ctx, opts, io);
227
+ else code = await runWrite(ctx, opts, io);
228
+ } catch (e) {
229
+ io.log(`bads connect: ${e.message}`);
230
+ return 1;
231
+ }
232
+ const latest = await checkForUpdate(VERSION, { env });
233
+ if (latest) io.log(`\nA newer @behavioral-agentic-design-system/core is out: ${latest} (you have ${VERSION}).`);
234
+ return code;
235
+ }
236
+
237
+ // Run when started as a command. The bin is a symlink in node_modules/.bin, so compare real paths.
238
+ const invokedPath = (() => {
239
+ try {
240
+ return process.argv[1] ? realpathSync(process.argv[1]) : null;
241
+ } catch {
242
+ return null;
243
+ }
244
+ })();
245
+ if (invokedPath && realpathSync(fileURLToPath(import.meta.url)) === invokedPath) {
246
+ process.exitCode = await main(process.argv.slice(2));
247
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `bads connect --check`: start each wired MCP server exactly as its config says and ask it a question.
3
+ *
4
+ * Speaks MCP over stdio by hand (newline-delimited JSON-RPC 2.0, https://modelcontextprotocol.io/specification),
5
+ * so the core package needs no MCP SDK: initialize, notifications/initialized, tools/list, then one tools/call to
6
+ * `guide` when the server has it, otherwise `get_contract`. A server that answers the call passes, even when the
7
+ * answer is "no such component", because the question was whether the wiring works.
8
+ */
9
+ import { spawn, spawnSync } from "node:child_process";
10
+ import { isAbsolute, resolve } from "node:path";
11
+
12
+ const PROTOCOL_VERSION = "2025-06-18";
13
+
14
+ /** Replace ${workspaceFolder} the way Cursor and VS Code do, so the probe starts what the editor would start. */
15
+ export function resolveEntry(entry, root) {
16
+ const sub = (s) => (typeof s === "string" ? s.split("${workspaceFolder}").join(root) : s);
17
+ const cwd = entry.cwd ? (isAbsolute(sub(entry.cwd)) ? sub(entry.cwd) : resolve(root, sub(entry.cwd))) : root;
18
+ return {
19
+ command: sub(entry.command),
20
+ args: (entry.args ?? []).map(sub),
21
+ env: Object.fromEntries(Object.entries(entry.env ?? {}).map(([k, v]) => [k, sub(v)])),
22
+ cwd,
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Start the server and ask it one question. Resolves to { ok, tool, detail, tools } and never rejects.
28
+ * `probeName` is the component asked about when the server has no `guide` tool.
29
+ */
30
+ export function probeServer(entry, { root, probeName = "Button", timeoutMs = 20000, env = process.env } = {}) {
31
+ const r = resolveEntry(entry, root);
32
+ return new Promise((done) => {
33
+ let settled = false;
34
+ let stderr = "";
35
+ let buf = "";
36
+ const pending = new Map();
37
+ const child = spawn(r.command, r.args, { cwd: r.cwd, env: { ...env, ...r.env }, stdio: ["pipe", "pipe", "pipe"] });
38
+ const finish = (result) => {
39
+ if (settled) return;
40
+ settled = true;
41
+ clearTimeout(timer);
42
+ child.kill();
43
+ done(result);
44
+ };
45
+ const timer = setTimeout(() => finish({ ok: false, detail: `no answer in ${timeoutMs / 1000}s${stderr ? `: ${stderr.trim().split("\n").pop()}` : ""}` }), timeoutMs);
46
+ child.on("error", (e) => finish({ ok: false, detail: `could not start \`${r.command}\`: ${e.message}` }));
47
+ child.on("exit", (code) => finish({ ok: false, detail: `the server exited (code ${code})${stderr ? `: ${stderr.trim().split("\n").pop()}` : ""}` }));
48
+ child.stderr.on("data", (d) => {
49
+ stderr += d;
50
+ });
51
+ child.stdout.on("data", (d) => {
52
+ buf += d;
53
+ let nl;
54
+ while ((nl = buf.indexOf("\n")) !== -1) {
55
+ const line = buf.slice(0, nl).trim();
56
+ buf = buf.slice(nl + 1);
57
+ if (!line) continue;
58
+ let msg;
59
+ try {
60
+ msg = JSON.parse(line);
61
+ } catch {
62
+ continue;
63
+ }
64
+ const waiter = pending.get(msg.id);
65
+ if (waiter) {
66
+ pending.delete(msg.id);
67
+ waiter(msg);
68
+ }
69
+ }
70
+ });
71
+ let nextId = 1;
72
+ const request = (method, params) =>
73
+ new Promise((res) => {
74
+ const id = nextId++;
75
+ pending.set(id, res);
76
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
77
+ });
78
+ (async () => {
79
+ const init = await request("initialize", { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "bads-connect-check", version: "1" } });
80
+ if (init.error) return finish({ ok: false, detail: `initialize failed: ${init.error.message}` });
81
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
82
+ const list = await request("tools/list", {});
83
+ if (list.error) return finish({ ok: false, detail: `tools/list failed: ${list.error.message}` });
84
+ const tools = (list.result?.tools ?? []).map((t) => t.name);
85
+ const tool = tools.includes("guide") ? "guide" : tools.includes("get_contract") ? "get_contract" : null;
86
+ if (!tool) return finish({ ok: false, tools, detail: `the server has neither guide nor get_contract (${tools.length} tools)` });
87
+ const call = await request("tools/call", { name: tool, arguments: tool === "guide" ? {} : { name: probeName } });
88
+ if (call.error) return finish({ ok: false, tool, tools, detail: `${tool} failed: ${call.error.message}` });
89
+ const text = call.result?.content?.find((c) => c.type === "text")?.text ?? "";
90
+ const found = call.result?.isError ? "answered (not found)" : "answered";
91
+ finish({ ok: true, tool, tools, detail: `${tools.length} tools, ${tool}${tool === "get_contract" ? `(${probeName})` : ""} ${found}, ${text.length} chars` });
92
+ })().catch((e) => finish({ ok: false, detail: e.message }));
93
+ });
94
+ }
95
+
96
+ /** Run the fork's own contract command once, for a client fork with no BADS MCP server. */
97
+ export function probeContracts(ctx) {
98
+ const [cmd, args] = ctx.contracts.argv;
99
+ const r = spawnSync(cmd, [...args, "components", "--json"], { cwd: ctx.root, encoding: "utf8", timeout: 60000, shell: process.platform === "win32" });
100
+ if (r.error) return { ok: false, detail: `could not run ${cmd}: ${r.error.message}` };
101
+ return r.status === 0 ? { ok: true, detail: "the contracts command answered `components`" } : { ok: false, detail: `the contracts command exited ${r.status}: ${(r.stderr || r.stdout || "").trim().split("\n").pop()}` };
102
+ }