bees-agentic 0.0.0-stage → 0.1.0-alpha.0

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/cli.js ADDED
@@ -0,0 +1,270 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { CONFIG_FILE, LOCK_FILE, TOOLS, TOOL_LABELS, loadConfig, readConfigDocument, validateConfig, writeConfig } from "./config.js";
5
+ import { detectProject, detectTools } from "./detect.js";
6
+ import { findRegion } from "./markers.js";
7
+ import { listPacks, loadPack, loadPacks } from "./packs.js";
8
+ import { applyPlan, computePlan } from "./sync.js";
9
+ import { askList, banner, c, isInteractive, log, printChanges } from "./ui.js";
10
+ import { BeesError, isDir, readText, writeText } from "./util.js";
11
+
12
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
13
+
14
+ const HELP = `${c.honey("bees")} ${VERSION}: one hive, every agent.
15
+
16
+ Usage: bees <command> [options]
17
+
18
+ Commands
19
+ init Detect the stack, pick tools and packs, write bees.yaml, generate configs
20
+ sync Re-generate configs from bees.yaml (idempotent, keeps your edits)
21
+ sync --check Exit 1 if generated configs are stale (use in CI)
22
+ add <pack...> Enable packs and sync
23
+ remove <pack...> Disable packs and sync (removes the files they generated)
24
+ list List available packs
25
+ doctor Diagnose config, drift and broken markers
26
+
27
+ Options
28
+ -C, --cwd <dir> Run as if started in <dir>
29
+ --tools <list> init: comma-separated tools (${TOOLS.join(", ")})
30
+ --packs <list> init: comma-separated packs (default: core)
31
+ -y, --yes init: accept detected defaults, no prompts
32
+ --force init: overwrite an existing bees.yaml
33
+ --dry-run init/sync/add/remove: show changes without writing
34
+ -h, --help Show this help
35
+ -v, --version Show the version
36
+
37
+ Docs: https://github.com/nciross/bees-agentic-template`;
38
+
39
+ const OPTIONS = {
40
+ cwd: { type: "string", short: "C" },
41
+ tools: { type: "string" },
42
+ packs: { type: "string" },
43
+ yes: { type: "boolean", short: "y" },
44
+ force: { type: "boolean" },
45
+ check: { type: "boolean" },
46
+ "dry-run": { type: "boolean" },
47
+ help: { type: "boolean", short: "h" },
48
+ version: { type: "boolean", short: "v" },
49
+ };
50
+
51
+ const splitList = (s) => [...new Set(String(s).split(/[\s,]+/).filter(Boolean))];
52
+
53
+ function loadProject(cwd) {
54
+ const available = listPacks();
55
+ const { config, warnings } = loadConfig(cwd, available);
56
+ return { config, warnings, packs: loadPacks(config.packs) };
57
+ }
58
+
59
+ /** Run a sync and report it. Returns the exit code. */
60
+ function runSync(cwd, { check = false, dryRun = false, quiet = false } = {}) {
61
+ const { config, warnings, packs } = loadProject(cwd);
62
+ for (const w of warnings) log.warn(w);
63
+ const plan = computePlan(cwd, { config, packs });
64
+ for (const w of plan.warnings) log.warn(w);
65
+
66
+ if (check) {
67
+ if (plan.changes.length === 0) {
68
+ log.ok(`Generated configs are up to date (${plan.outputs.length} files, tools: ${config.tools.join(", ")}).`);
69
+ return 0;
70
+ }
71
+ log.error(`Generated configs are stale: ${plan.changes.length} file(s) differ from ${CONFIG_FILE}.`);
72
+ printChanges(plan.changes, { prefix: " " });
73
+ log.info(c.dim(" Run `bees sync` and commit the result."));
74
+ return 1;
75
+ }
76
+ if (plan.changes.length === 0) {
77
+ if (!quiet) log.ok("Already up to date.");
78
+ return 0;
79
+ }
80
+ printChanges(plan.changes, { prefix: " " });
81
+ if (dryRun) {
82
+ log.info(c.dim(` Dry run: ${plan.changes.length} change(s) not written.`));
83
+ return 0;
84
+ }
85
+ applyPlan(cwd, plan);
86
+ log.ok(`Synced ${plan.changes.length} file(s).`);
87
+ return 0;
88
+ }
89
+
90
+ async function cmdInit(cwd, opts) {
91
+ if (!isDir(cwd)) throw new BeesError(`Directory not found: ${cwd}`);
92
+ if (existsSync(join(cwd, CONFIG_FILE)) && !opts.force) {
93
+ throw new BeesError(`${CONFIG_FILE} already exists.`, { hint: "Run `bees sync` to regenerate, or `bees init --force` to start over." });
94
+ }
95
+ banner();
96
+ const project = detectProject(cwd);
97
+ log.step(`Project ${c.bold(project.name)}${project.stack.length ? ` · ${project.stack.join(", ")}` : c.dim(" · stack not detected")}`);
98
+
99
+ const available = listPacks();
100
+ const detected = detectTools(cwd);
101
+ const defaultTools = detected.length ? detected : TOOLS;
102
+ const defaultPacks = available.includes("core") ? ["core"] : [];
103
+ const prompt = isInteractive() && !opts.yes;
104
+
105
+ let tools = opts.tools ? splitList(opts.tools) : prompt ? await askList("Which AI tools does your team use?", TOOLS, defaultTools) : defaultTools;
106
+ let packs = opts.packs ? splitList(opts.packs) : prompt ? await askList("Which packs?", available, defaultPacks) : defaultPacks;
107
+
108
+ const { config, errors } = validateConfig({ version: 1, tools, packs }, available);
109
+ if (errors.length) throw new BeesError(errors.join("\n"));
110
+ tools = config.tools;
111
+ packs = config.packs;
112
+ log.step(`Tools: ${tools.map((t) => TOOL_LABELS[t]).join(", ")}`);
113
+ log.step(`Packs: ${packs.join(", ") || "(none)"}`);
114
+
115
+ if (opts["dry-run"]) {
116
+ log.info(c.dim(`Dry run: would write ${CONFIG_FILE} and generate configs.`));
117
+ return 0;
118
+ }
119
+ writeConfig(cwd, { project, tools, packs });
120
+ log.ok(`Wrote ${CONFIG_FILE}`);
121
+ runSync(cwd);
122
+ log.info(`
123
+ ${c.bold("Next steps")}
124
+ 1. Review ${CONFIG_FILE} (check the detected project commands).
125
+ 2. Commit ${CONFIG_FILE}, ${LOCK_FILE} and the generated files listed above.
126
+ 3. In CI, run ${c.dim("bees sync --check")} so generated configs never go stale (see docs/install.md).`);
127
+ return 0;
128
+ }
129
+
130
+ function editPacks(cwd, names, mode, opts) {
131
+ if (!names.length) throw new BeesError(`Usage: bees ${mode} <pack...>`);
132
+ const available = listPacks();
133
+ const { file, doc } = readConfigDocument(cwd);
134
+ const current = doc.toJS()?.packs ?? [];
135
+ if (mode === "add") {
136
+ const unknown = names.filter((n) => !available.includes(n));
137
+ if (unknown.length) throw new BeesError(`Unknown pack(s): ${unknown.join(", ")}.`, { hint: `Available: ${available.join(", ")}` });
138
+ for (const n of names) loadPack(n); // validate before touching bees.yaml
139
+ }
140
+ const next = mode === "add" ? [...current, ...names.filter((n) => !current.includes(n))] : current.filter((n) => !names.includes(n));
141
+ if (next.length === current.length) {
142
+ log.ok(mode === "add" ? "Already enabled." : "None of those packs are enabled.");
143
+ return 0;
144
+ }
145
+ doc.set("packs", next);
146
+ if (opts["dry-run"]) {
147
+ log.info(c.dim(`Dry run: packs would become ${next.join(", ") || "(none)"}`));
148
+ return 0;
149
+ }
150
+ writeText(file, doc.toString());
151
+ log.ok(`${mode === "add" ? "Enabled" : "Disabled"} ${names.join(", ")} in ${CONFIG_FILE}`);
152
+ return runSync(cwd);
153
+ }
154
+
155
+ function cmdList(cwd) {
156
+ let enabled = [];
157
+ try {
158
+ enabled = readConfigDocument(cwd).doc.toJS()?.packs ?? [];
159
+ } catch {
160
+ /* not initialised: just list */
161
+ }
162
+ for (const name of listPacks()) {
163
+ const pack = loadPack(name);
164
+ const mark = enabled.includes(name) ? c.green("●") : c.dim("○");
165
+ log.info(`${mark} ${c.bold(name)} ${c.dim(pack.version)} ${pack.description}`);
166
+ }
167
+ return 0;
168
+ }
169
+
170
+ function cmdDoctor(cwd) {
171
+ let problems = 0;
172
+ const fail = (m) => (problems++, log.error(m));
173
+ const [major] = process.versions.node.split(".").map(Number);
174
+ major >= 22 ? log.ok(`Node.js ${process.versions.node}`) : fail(`Node.js ${process.versions.node} is too old; bees needs 22+.`);
175
+
176
+ let project;
177
+ try {
178
+ project = loadProject(cwd);
179
+ log.ok(`${CONFIG_FILE} is valid (tools: ${project.config.tools.join(", ")}; packs: ${project.config.packs.join(", ") || "none"})`);
180
+ for (const w of project.warnings) log.warn(w);
181
+ } catch (err) {
182
+ fail(err.message);
183
+ if (err.hint) log.info(c.dim(` ${err.hint}`));
184
+ return 1;
185
+ }
186
+
187
+ existsSync(join(cwd, LOCK_FILE)) ? log.ok(`${LOCK_FILE} present`) : fail(`${LOCK_FILE} is missing. Run \`bees sync\`.`);
188
+
189
+ for (const file of ["AGENTS.md", "CLAUDE.md", ".github/copilot-instructions.md"]) {
190
+ const text = readText(join(cwd, file));
191
+ if (text == null) continue;
192
+ try {
193
+ if (!findRegion(text, file)) fail(`${file} has no bees markers. Run \`bees sync\` to add them.`);
194
+ } catch (err) {
195
+ fail(err.message);
196
+ }
197
+ }
198
+
199
+ try {
200
+ const plan = computePlan(cwd, project);
201
+ if (plan.changes.length) {
202
+ fail(`${plan.changes.length} generated file(s) are stale. Run \`bees sync\`.`);
203
+ printChanges(plan.changes, { prefix: " " });
204
+ } else log.ok(`All ${plan.outputs.length} generated files are up to date`);
205
+ for (const w of plan.warnings) log.warn(w);
206
+ } catch (err) {
207
+ fail(err.message);
208
+ }
209
+
210
+ const { tools } = project.config;
211
+ if (tools.includes("codex") && project.packs.some((p) => p.commands.length)) {
212
+ log.warn("Codex has no project-scope custom prompts; pack commands are available to the other tools only.");
213
+ }
214
+ if (tools.includes("cursor") && project.packs.some((p) => p.agents.length)) {
215
+ log.warn("Cursor has no sub-agents; pack agents are listed as roles in AGENTS.md instead.");
216
+ }
217
+
218
+ if (problems) log.error(`${problems} problem(s) found.`);
219
+ else log.ok("The hive is healthy. 🍯");
220
+ return problems ? 1 : 0;
221
+ }
222
+
223
+ export async function main(argv = process.argv.slice(2)) {
224
+ let parsed;
225
+ try {
226
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
227
+ } catch (err) {
228
+ log.error(err.message);
229
+ log.info(c.dim("Run `bees --help` for usage."));
230
+ return 2;
231
+ }
232
+ const { values: opts, positionals } = parsed;
233
+ const [command, ...rest] = positionals;
234
+ const cwd = resolve(opts.cwd ?? process.cwd());
235
+
236
+ if (opts.version) return log.info(VERSION), 0;
237
+ if (opts.help || !command || command === "help") {
238
+ if (!command) banner();
239
+ log.info(HELP);
240
+ return 0;
241
+ }
242
+
243
+ try {
244
+ switch (command) {
245
+ case "init":
246
+ return await cmdInit(cwd, opts);
247
+ case "sync":
248
+ return runSync(cwd, { check: opts.check, dryRun: opts["dry-run"] });
249
+ case "add":
250
+ return editPacks(cwd, rest, "add", opts);
251
+ case "remove":
252
+ return editPacks(cwd, rest, "remove", opts);
253
+ case "list":
254
+ return cmdList(cwd);
255
+ case "doctor":
256
+ return cmdDoctor(cwd);
257
+ default:
258
+ log.error(`Unknown command "${command}".`);
259
+ log.info(c.dim("Run `bees --help` for usage."));
260
+ return 2;
261
+ }
262
+ } catch (err) {
263
+ if (err instanceof BeesError) {
264
+ log.error(err.message);
265
+ if (err.hint) log.info(c.dim(` ${err.hint}`));
266
+ return err.exitCode;
267
+ }
268
+ throw err;
269
+ }
270
+ }
package/src/config.js ADDED
@@ -0,0 +1,105 @@
1
+ import { join } from "node:path";
2
+ import YAML from "yaml";
3
+ import { BeesError, readText, writeText } from "./util.js";
4
+
5
+ export const CONFIG_FILE = "bees.yaml";
6
+ export const LOCK_FILE = "bees.lock";
7
+ export const TOOLS = ["claude", "copilot", "cursor", "codex"];
8
+ export const TOOL_LABELS = { claude: "Claude Code", copilot: "GitHub Copilot", cursor: "Cursor", codex: "Codex" };
9
+ export const PACK_NAME = /^[a-z0-9][a-z0-9-]*$/;
10
+ const COMMAND_KEYS = ["install", "dev", "build", "test", "lint"];
11
+
12
+ /** Validate raw parsed YAML. Returns { config, errors, warnings }. */
13
+ export function validateConfig(raw, availablePacks) {
14
+ const errors = [];
15
+ const warnings = [];
16
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
17
+ return { config: null, errors: [`${CONFIG_FILE} must be a YAML mapping.`], warnings };
18
+ }
19
+ if (raw.version !== 1) errors.push(`\`version\` must be 1 (found ${JSON.stringify(raw.version)}).`);
20
+
21
+ const list = (key) => {
22
+ const v = raw[key];
23
+ if (v == null) return [];
24
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) {
25
+ errors.push(`\`${key}\` must be a list of names.`);
26
+ return [];
27
+ }
28
+ return [...new Set(v)];
29
+ };
30
+ const tools = list("tools");
31
+ const packs = list("packs");
32
+ for (const t of tools) if (!TOOLS.includes(t)) errors.push(`Unknown tool "${t}". Supported: ${TOOLS.join(", ")}.`);
33
+ if (tools.length === 0) errors.push("`tools` must list at least one tool.");
34
+ for (const p of packs) {
35
+ if (!PACK_NAME.test(p)) errors.push(`Invalid pack name "${p}".`);
36
+ else if (availablePacks && !availablePacks.includes(p)) {
37
+ errors.push(`Unknown pack "${p}". Available: ${availablePacks.join(", ") || "none"}.`);
38
+ }
39
+ }
40
+ if (!packs.includes("core")) warnings.push("The `core` pack is not enabled; AGENTS.md will only contain project facts.");
41
+
42
+ const p = raw.project ?? {};
43
+ if (typeof p !== "object" || Array.isArray(p)) errors.push("`project` must be a mapping.");
44
+ const commands = {};
45
+ for (const k of COMMAND_KEYS) if (typeof p.commands?.[k] === "string" && p.commands[k].trim()) commands[k] = p.commands[k].trim();
46
+ const project = {
47
+ name: typeof p.name === "string" ? p.name : undefined,
48
+ description: typeof p.description === "string" ? p.description : undefined,
49
+ stack: Array.isArray(p.stack) ? p.stack.map(String) : [],
50
+ packageManager: typeof p.packageManager === "string" ? p.packageManager : undefined,
51
+ commands,
52
+ };
53
+
54
+ const known = new Set(["version", "project", "tools", "packs", "team", "overrides"]);
55
+ for (const k of Object.keys(raw)) if (!known.has(k)) warnings.push(`Unknown key \`${k}\` in ${CONFIG_FILE} is ignored.`);
56
+
57
+ return { config: { version: 1, project, tools: TOOLS.filter((t) => tools.includes(t)), packs }, errors, warnings };
58
+ }
59
+
60
+ export function readConfigDocument(cwd) {
61
+ const file = join(cwd, CONFIG_FILE);
62
+ const text = readText(file);
63
+ if (text == null) {
64
+ throw new BeesError(`No ${CONFIG_FILE} found in ${cwd}.`, { hint: "Run `bees init` to set bees up in this project." });
65
+ }
66
+ const doc = YAML.parseDocument(text);
67
+ if (doc.errors.length) throw new BeesError(`${CONFIG_FILE} is not valid YAML: ${doc.errors[0].message}`);
68
+ return { file, doc };
69
+ }
70
+
71
+ /** Load and validate bees.yaml; throws a BeesError listing every problem. */
72
+ export function loadConfig(cwd, availablePacks) {
73
+ const { doc } = readConfigDocument(cwd);
74
+ const result = validateConfig(doc.toJS(), availablePacks);
75
+ if (result.errors.length) {
76
+ throw new BeesError(`${CONFIG_FILE} has ${result.errors.length} problem(s):\n${result.errors.map((e) => ` - ${e}`).join("\n")}`);
77
+ }
78
+ return result;
79
+ }
80
+
81
+ export function renderConfig({ project, tools, packs }) {
82
+ const commands = Object.fromEntries(COMMAND_KEYS.filter((k) => project.commands?.[k]).map((k) => [k, project.commands[k]]));
83
+ const data = {
84
+ version: 1,
85
+ project: {
86
+ name: project.name,
87
+ ...(project.stack?.length ? { stack: project.stack } : {}),
88
+ ...(project.packageManager ? { packageManager: project.packageManager } : {}),
89
+ ...(Object.keys(commands).length ? { commands } : {}),
90
+ },
91
+ tools,
92
+ packs,
93
+ };
94
+ const header = [
95
+ "# bees.yaml: your project's shared agentic dev environment.",
96
+ "# Commit this file. After editing it, run `bees sync` (CI runs `bees sync --check`).",
97
+ "# Docs: https://github.com/nciross/bees-agentic-template",
98
+ "",
99
+ ].join("\n");
100
+ return header + YAML.stringify(data, { lineWidth: 0, flowCollectionPadding: true });
101
+ }
102
+
103
+ export function writeConfig(cwd, config) {
104
+ writeText(join(cwd, CONFIG_FILE), renderConfig(config));
105
+ }
package/src/detect.js ADDED
@@ -0,0 +1,145 @@
1
+ // Best-effort stack detection for `bees init`. The result is written into
2
+ // bees.yaml under `project:` so the team can review and correct it.
3
+ import { existsSync, readdirSync } from "node:fs";
4
+ import { basename, join } from "node:path";
5
+ import { readText } from "./util.js";
6
+
7
+ const has = (cwd, file) => existsSync(join(cwd, file));
8
+ const readJson = (cwd, file) => {
9
+ try {
10
+ return JSON.parse(readText(join(cwd, file)) ?? "null");
11
+ } catch {
12
+ return null;
13
+ }
14
+ };
15
+
16
+ function detectNode(cwd, out) {
17
+ const pkg = readJson(cwd, "package.json");
18
+ if (!pkg) return;
19
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
20
+ out.name ??= pkg.name;
21
+ out.stack.push("Node.js");
22
+ if (has(cwd, "tsconfig.json") || deps.typescript) out.stack.push("TypeScript");
23
+ const frameworks = [
24
+ ["next", "Next.js"], ["@nestjs/core", "NestJS"], ["@angular/core", "Angular"], ["nuxt", "Nuxt"],
25
+ ["@sveltejs/kit", "SvelteKit"], ["svelte", "Svelte"], ["vue", "Vue"], ["react", "React"],
26
+ ["express", "Express"], ["fastify", "Fastify"], ["hono", "Hono"], ["vite", "Vite"],
27
+ ];
28
+ for (const [dep, label] of frameworks) if (deps[dep]) out.stack.push(label);
29
+
30
+ let pm = "npm";
31
+ const declared = typeof pkg.packageManager === "string" ? pkg.packageManager.split("@")[0] : null;
32
+ if (declared) pm = declared;
33
+ else if (has(cwd, "pnpm-lock.yaml")) pm = "pnpm";
34
+ else if (has(cwd, "yarn.lock")) pm = "yarn";
35
+ else if (has(cwd, "bun.lock") || has(cwd, "bun.lockb")) pm = "bun";
36
+ out.packageManager ??= pm;
37
+
38
+ const scripts = pkg.scripts ?? {};
39
+ const run = (s) => (pm === "npm" && ["test", "start"].includes(s) ? `npm ${s}` : `${pm} run ${s}`);
40
+ out.commands.install ??= `${pm} install`;
41
+ if (scripts.test && !/no test specified/.test(scripts.test)) out.commands.test ??= run("test");
42
+ if (scripts.build) out.commands.build ??= run("build");
43
+ if (scripts.lint) out.commands.lint ??= run("lint");
44
+ if (scripts.dev) out.commands.dev ??= run("dev");
45
+ else if (scripts.start) out.commands.dev ??= run("start");
46
+ }
47
+
48
+ function detectPython(cwd, out) {
49
+ const pyproject = readText(join(cwd, "pyproject.toml"));
50
+ const requirements = readText(join(cwd, "requirements.txt"));
51
+ if (pyproject == null && requirements == null && !has(cwd, "setup.py")) return;
52
+ const text = `${pyproject ?? ""}\n${requirements ?? ""}`.toLowerCase();
53
+ out.stack.push("Python");
54
+ for (const [dep, label] of [["django", "Django"], ["fastapi", "FastAPI"], ["flask", "Flask"]]) {
55
+ if (new RegExp(`\\b${dep}\\b`).test(text)) out.stack.push(label);
56
+ }
57
+ const nameMatch = pyproject?.match(/^\s*name\s*=\s*["']([^"']+)["']/m);
58
+ if (nameMatch) out.name ??= nameMatch[1];
59
+
60
+ let pm = "pip";
61
+ if (has(cwd, "uv.lock")) pm = "uv";
62
+ else if (has(cwd, "poetry.lock") || /\[tool\.poetry\]/.test(pyproject ?? "")) pm = "poetry";
63
+ out.packageManager ??= pm;
64
+ const prefix = pm === "uv" ? "uv run " : pm === "poetry" ? "poetry run " : "";
65
+ out.commands.install ??= pm === "uv" ? "uv sync" : pm === "poetry" ? "poetry install" : requirements != null ? "pip install -r requirements.txt" : "pip install -e .";
66
+ if (/\bpytest\b/.test(text) || has(cwd, "tests") || has(cwd, "pytest.ini")) out.commands.test ??= `${prefix}pytest`;
67
+ if (/\bruff\b/.test(text)) out.commands.lint ??= `${prefix}ruff check .`;
68
+ }
69
+
70
+ function detectOthers(cwd, out) {
71
+ const gomod = readText(join(cwd, "go.mod"));
72
+ if (gomod != null) {
73
+ out.stack.push("Go");
74
+ out.name ??= gomod.match(/^module\s+(\S+)/m)?.[1]?.split("/").pop();
75
+ out.packageManager ??= "go";
76
+ out.commands.test ??= "go test ./...";
77
+ out.commands.build ??= "go build ./...";
78
+ out.commands.lint ??= "go vet ./...";
79
+ }
80
+ const cargo = readText(join(cwd, "Cargo.toml"));
81
+ if (cargo != null) {
82
+ out.stack.push("Rust");
83
+ out.name ??= cargo.match(/^\s*name\s*=\s*"([^"]+)"/m)?.[1];
84
+ out.packageManager ??= "cargo";
85
+ out.commands.test ??= "cargo test";
86
+ out.commands.build ??= "cargo build";
87
+ out.commands.lint ??= "cargo clippy";
88
+ }
89
+ if (has(cwd, "pom.xml")) {
90
+ out.stack.push("Java", "Maven");
91
+ out.packageManager ??= "maven";
92
+ const mvn = has(cwd, "mvnw") ? "./mvnw" : "mvn";
93
+ out.commands.test ??= `${mvn} test`;
94
+ out.commands.build ??= `${mvn} package`;
95
+ } else if (has(cwd, "build.gradle") || has(cwd, "build.gradle.kts")) {
96
+ out.stack.push(has(cwd, "build.gradle.kts") ? "Kotlin" : "Java", "Gradle");
97
+ out.packageManager ??= "gradle";
98
+ const gradle = has(cwd, "gradlew") ? "./gradlew" : "gradle";
99
+ out.commands.test ??= `${gradle} test`;
100
+ out.commands.build ??= `${gradle} build`;
101
+ }
102
+ let entries = [];
103
+ try {
104
+ entries = readdirSync(cwd);
105
+ } catch {
106
+ /* unreadable dir: nothing to detect */
107
+ }
108
+ if (entries.some((f) => /\.(sln|csproj|fsproj)$/.test(f))) {
109
+ out.stack.push(".NET");
110
+ out.packageManager ??= "dotnet";
111
+ out.commands.test ??= "dotnet test";
112
+ out.commands.build ??= "dotnet build";
113
+ }
114
+ if (has(cwd, "Gemfile")) {
115
+ out.stack.push("Ruby");
116
+ if (/\brails\b/.test(readText(join(cwd, "Gemfile")) ?? "")) out.stack.push("Rails");
117
+ out.packageManager ??= "bundler";
118
+ out.commands.install ??= "bundle install";
119
+ }
120
+ if (has(cwd, "composer.json")) {
121
+ out.stack.push("PHP");
122
+ out.packageManager ??= "composer";
123
+ out.commands.install ??= "composer install";
124
+ }
125
+ }
126
+
127
+ /** Tools the project already uses, judged by their config files. */
128
+ export function detectTools(cwd) {
129
+ const tools = [];
130
+ if (has(cwd, ".claude") || has(cwd, "CLAUDE.md")) tools.push("claude");
131
+ if (has(cwd, ".github/copilot-instructions.md") || has(cwd, ".github/prompts")) tools.push("copilot");
132
+ if (has(cwd, ".cursor") || has(cwd, ".cursorrules")) tools.push("cursor");
133
+ if (has(cwd, ".codex") || has(cwd, ".agents")) tools.push("codex");
134
+ return tools;
135
+ }
136
+
137
+ export function detectProject(cwd) {
138
+ const out = { name: undefined, stack: [], packageManager: undefined, commands: {} };
139
+ detectNode(cwd, out);
140
+ detectPython(cwd, out);
141
+ detectOthers(cwd, out);
142
+ out.name ??= basename(cwd);
143
+ out.stack = [...new Set(out.stack)];
144
+ return out;
145
+ }
@@ -0,0 +1,20 @@
1
+ import YAML from "yaml";
2
+ import { normalizeEol } from "./util.js";
3
+
4
+ const FENCE = /^---\n([\s\S]*?)\n---\n?/;
5
+
6
+ /** Split a Markdown file into YAML front matter and body. */
7
+ export function parseFrontmatter(text) {
8
+ const src = normalizeEol(text);
9
+ const m = src.match(FENCE);
10
+ if (!m) return { data: {}, body: src };
11
+ const data = YAML.parse(m[1]) ?? {};
12
+ return { data, body: src.slice(m[0].length) };
13
+ }
14
+
15
+ /** Join front matter and body. Keys with undefined values are dropped. */
16
+ export function stringifyFrontmatter(data, body) {
17
+ const clean = Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined));
18
+ const head = Object.keys(clean).length ? `---\n${YAML.stringify(clean, { lineWidth: 0 }).trimEnd()}\n---\n\n` : "";
19
+ return head + body.replace(/^\s+/, "").replace(/\s*$/, "\n");
20
+ }
package/src/markers.js ADDED
@@ -0,0 +1,50 @@
1
+ // Managed regions: bees only ever rewrites text between these two markers,
2
+ // so anything a team writes outside them survives every `bees sync`.
3
+ import { BeesError } from "./util.js";
4
+
5
+ export const BEGIN = "<!-- bees:begin -->";
6
+ export const END = "<!-- bees:end -->";
7
+ const NOTICE = "<!-- Managed by bees: edit bees.yaml and run `bees sync`. Text between these markers is overwritten; write your own notes outside them. -->";
8
+
9
+ const eolOf = (text) => (text && text.includes("\r\n") ? "\r\n" : "\n");
10
+
11
+ export function renderRegion(body) {
12
+ return [BEGIN, NOTICE, "", body.trim(), END].join("\n");
13
+ }
14
+
15
+ /** Locate the managed region. Returns null when absent; throws when the markers are broken. */
16
+ export function findRegion(text, file = "file") {
17
+ const begin = text.indexOf(BEGIN);
18
+ const end = text.indexOf(END);
19
+ if (begin === -1 && end === -1) return null;
20
+ const broken =
21
+ begin === -1 ||
22
+ end === -1 ||
23
+ end < begin ||
24
+ text.indexOf(BEGIN, begin + 1) !== -1 ||
25
+ text.indexOf(END, end + 1) !== -1;
26
+ if (broken) {
27
+ throw new BeesError(`${file}: the bees markers are broken (expected exactly one ${BEGIN} followed by one ${END}).`, {
28
+ hint: "Fix or delete the markers by hand, then run `bees sync` again.",
29
+ });
30
+ }
31
+ return { start: begin, end: end + END.length };
32
+ }
33
+
34
+ /** Insert or replace the managed region in `existing` (null = new file), keeping the file's line endings. */
35
+ export function upsertRegion(existing, body, file) {
36
+ const eol = eolOf(existing);
37
+ const region = renderRegion(body).replace(/\n/g, eol);
38
+ if (existing == null || existing.trim() === "") return region + eol;
39
+ const found = findRegion(existing, file);
40
+ if (found) return existing.slice(0, found.start) + region + existing.slice(found.end);
41
+ return existing.replace(/\s*$/, "") + eol + eol + region + eol;
42
+ }
43
+
44
+ /** Remove the managed region. Returns null when nothing else is left in the file. */
45
+ export function removeRegion(existing, file) {
46
+ const found = findRegion(existing, file);
47
+ if (!found) return existing;
48
+ const rest = (existing.slice(0, found.start).replace(/\s*$/, "") + "\n\n" + existing.slice(found.end).replace(/^\s*/, "")).trim();
49
+ return rest ? rest + eolOf(existing) : null;
50
+ }
package/src/packs.js ADDED
@@ -0,0 +1,84 @@
1
+ // A pack is a folder: pack.yaml plus any of
2
+ // rules/<name>.md → sections of the shared AGENTS.md
3
+ // skills/<name>/SKILL.md → Agent Skills (plus any supporting files)
4
+ // commands/<name>.md → slash commands / prompts
5
+ // agents/<name>.md → sub-agents
6
+ import { join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import YAML from "yaml";
9
+ import { parseFrontmatter } from "./frontmatter.js";
10
+ import { PACK_NAME } from "./config.js";
11
+ import { BeesError, isDir, listFilesRecursive, readText } from "./util.js";
12
+
13
+ export const BUILTIN_PACKS_DIR = fileURLToPath(new URL("../packs/", import.meta.url));
14
+ export const packsDir = () => process.env.BEES_PACKS_DIR || BUILTIN_PACKS_DIR;
15
+
16
+ export function listPacks(dir = packsDir()) {
17
+ return listFilesRecursive(dir)
18
+ .filter((f) => /^[^/]+\/pack\.yaml$/.test(f))
19
+ .map((f) => f.split("/")[0])
20
+ .filter((name) => PACK_NAME.test(name));
21
+ }
22
+
23
+ const mdFiles = (dir) => listFilesRecursive(dir).filter((f) => /^[^/]+\.md$/.test(f));
24
+ const baseName = (f) => f.replace(/\.md$/, "");
25
+
26
+ export function loadPack(name, dir = packsDir()) {
27
+ if (!PACK_NAME.test(name)) throw new BeesError(`Invalid pack name "${name}".`);
28
+ const root = join(dir, name);
29
+ const manifestText = readText(join(root, "pack.yaml"));
30
+ if (manifestText == null) throw new BeesError(`Pack "${name}" not found in ${dir}.`);
31
+ const manifest = YAML.parse(manifestText) ?? {};
32
+ const problems = [];
33
+ if (manifest.name !== name) problems.push(`pack.yaml name must be "${name}"`);
34
+ if (typeof manifest.version !== "string") problems.push("pack.yaml needs a version string");
35
+ if (typeof manifest.description !== "string") problems.push("pack.yaml needs a description");
36
+
37
+ const rules = mdFiles(join(root, "rules")).map((f) => ({
38
+ name: baseName(f),
39
+ content: readText(join(root, "rules", f)).replace(/\r\n/g, "\n").trim(),
40
+ }));
41
+
42
+ const skillsRoot = join(root, "skills");
43
+ const skillNames = [...new Set(listFilesRecursive(skillsRoot).map((f) => f.split("/")[0]))];
44
+ const skills = skillNames.map((skill) => {
45
+ const skillDir = join(skillsRoot, skill);
46
+ const files = listFilesRecursive(skillDir).map((rel) => ({ rel, content: readText(join(skillDir, rel)) }));
47
+ const main = files.find((f) => f.rel === "SKILL.md");
48
+ if (!main) {
49
+ problems.push(`skill "${skill}" has no SKILL.md`);
50
+ return { name: skill, description: "", files };
51
+ }
52
+ const { data } = parseFrontmatter(main.content);
53
+ if (data.name !== skill) problems.push(`skill "${skill}": front matter name must be "${skill}"`);
54
+ if (!data.description) problems.push(`skill "${skill}": front matter needs a description`);
55
+ return { name: skill, description: data.description ?? "", files };
56
+ });
57
+
58
+ const loadDocs = (sub) =>
59
+ isDir(join(root, sub))
60
+ ? mdFiles(join(root, sub)).map((f) => {
61
+ const { data, body } = parseFrontmatter(readText(join(root, sub, f)));
62
+ if (!data.description) problems.push(`${sub}/${f}: front matter needs a description`);
63
+ return { name: baseName(f), description: data.description ?? "", data, body: body.trim() };
64
+ })
65
+ : [];
66
+
67
+ if (problems.length) throw new BeesError(`Pack "${name}" is invalid:\n${problems.map((p) => ` - ${p}`).join("\n")}`);
68
+
69
+ return {
70
+ name,
71
+ version: manifest.version,
72
+ description: manifest.description,
73
+ license: manifest.license,
74
+ permissions: { deny: manifest.permissions?.deny ?? [] },
75
+ rules,
76
+ skills,
77
+ commands: loadDocs("commands"),
78
+ agents: loadDocs("agents"),
79
+ };
80
+ }
81
+
82
+ export function loadPacks(names, dir = packsDir()) {
83
+ return names.map((n) => loadPack(n, dir));
84
+ }