barndog 0.0.0-stage → 0.1.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.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -2
  3. package/dist/cli.js +40 -0
  4. package/dist/commands/add.js +99 -0
  5. package/dist/commands/auth.js +25 -0
  6. package/dist/commands/availability.js +87 -0
  7. package/dist/commands/capabilities.js +488 -0
  8. package/dist/commands/collaboration.js +203 -0
  9. package/dist/commands/context.js +1 -0
  10. package/dist/commands/environment.js +416 -0
  11. package/dist/commands/init.js +20 -0
  12. package/dist/commands/origin.js +48 -0
  13. package/dist/commands/status.js +66 -0
  14. package/dist/commands/sync.js +30 -0
  15. package/dist/commands/workspace.js +84 -0
  16. package/dist/config/build.js +2 -0
  17. package/dist/config/environment.js +41 -0
  18. package/dist/config/settings.js +127 -0
  19. package/dist/config/state.js +70 -0
  20. package/dist/errors.js +154 -0
  21. package/dist/features/asset-selection/index.js +212 -0
  22. package/dist/features/asset-selection/types.js +1 -0
  23. package/dist/features/auth/credentials.js +62 -0
  24. package/dist/features/auth/session.js +120 -0
  25. package/dist/features/auth/transport.js +44 -0
  26. package/dist/features/capabilities/index.js +106 -0
  27. package/dist/features/catalog/index.js +102 -0
  28. package/dist/features/collaboration/domain.js +90 -0
  29. package/dist/features/collaboration/index.js +254 -0
  30. package/dist/features/collaboration/remote.js +121 -0
  31. package/dist/features/collaboration/workspace-git.js +362 -0
  32. package/dist/features/collaboration/workspace-github.js +130 -0
  33. package/dist/features/collaboration/workspace-store.js +256 -0
  34. package/dist/features/collaboration/workspace.js +391 -0
  35. package/dist/features/discovery/index.js +66 -0
  36. package/dist/features/doctor/index.js +154 -0
  37. package/dist/features/environment/auto-sync.js +96 -0
  38. package/dist/features/environment/cloud-source.js +27 -0
  39. package/dist/features/environment/installed.js +124 -0
  40. package/dist/features/environment/names.js +153 -0
  41. package/dist/features/environment/operations.js +277 -0
  42. package/dist/features/environment/packages.js +120 -0
  43. package/dist/features/environment/remote.js +71 -0
  44. package/dist/features/environment/source.js +1 -0
  45. package/dist/features/environment/sync.js +547 -0
  46. package/dist/features/environment/transaction.js +284 -0
  47. package/dist/features/environment/workspace-source.js +19 -0
  48. package/dist/features/git-hosts/index.js +148 -0
  49. package/dist/features/git-workspace/assets.js +71 -0
  50. package/dist/features/git-workspace/format.js +310 -0
  51. package/dist/features/git-workspace/git.js +135 -0
  52. package/dist/features/git-workspace/migrate.js +188 -0
  53. package/dist/features/git-workspace/move.js +337 -0
  54. package/dist/features/git-workspace/overlay.js +131 -0
  55. package/dist/features/git-workspace/publish.js +172 -0
  56. package/dist/features/git-workspace/setup.js +135 -0
  57. package/dist/features/git-workspace/snapshot.js +105 -0
  58. package/dist/features/git-workspace/source.js +159 -0
  59. package/dist/features/git-workspace/startup.js +16 -0
  60. package/dist/features/hooks/adapt.js +103 -0
  61. package/dist/features/hooks/divergence.js +38 -0
  62. package/dist/features/hooks/test.js +114 -0
  63. package/dist/features/imports/discover.js +249 -0
  64. package/dist/features/imports/folder.js +52 -0
  65. package/dist/features/imports/local.js +242 -0
  66. package/dist/features/imports/mcp.js +219 -0
  67. package/dist/features/imports/remote.js +85 -0
  68. package/dist/features/inspection/index.js +42 -0
  69. package/dist/features/inventory/index.js +224 -0
  70. package/dist/features/knowledge/index.js +118 -0
  71. package/dist/features/knowledge/startup.js +25 -0
  72. package/dist/features/mcps/index.js +102 -0
  73. package/dist/features/native/adapters.js +143 -0
  74. package/dist/features/native/configuration.js +196 -0
  75. package/dist/features/native/mcp-launch.js +57 -0
  76. package/dist/features/onboarding/environment.js +160 -0
  77. package/dist/features/onboarding/setup.js +123 -0
  78. package/dist/features/repositories/context.js +55 -0
  79. package/dist/features/skills/install.js +25 -0
  80. package/dist/features/skills/remote.js +177 -0
  81. package/dist/features/skills/sync.js +121 -0
  82. package/dist/features/skills/validation.js +34 -0
  83. package/dist/harnesses/claude.js +57 -0
  84. package/dist/harnesses/codex.js +46 -0
  85. package/dist/harnesses/cursor.js +44 -0
  86. package/dist/harnesses/detect.js +61 -0
  87. package/dist/harnesses/registry.js +16 -0
  88. package/dist/harnesses/types.js +1 -0
  89. package/dist/program.js +272 -0
  90. package/dist/ui/add-asset.js +440 -0
  91. package/dist/ui/asset-list.js +50 -0
  92. package/dist/ui/assets.js +142 -0
  93. package/dist/ui/auth.js +138 -0
  94. package/dist/ui/clash.js +43 -0
  95. package/dist/ui/collaboration.js +142 -0
  96. package/dist/ui/connection.js +102 -0
  97. package/dist/ui/environment-onboarding.js +125 -0
  98. package/dist/ui/format.js +154 -0
  99. package/dist/ui/hook-compatibility.js +33 -0
  100. package/dist/ui/mcp.js +40 -0
  101. package/dist/ui/move.js +22 -0
  102. package/dist/ui/onboarding.js +293 -0
  103. package/dist/ui/output.js +155 -0
  104. package/dist/ui/pick.js +153 -0
  105. package/dist/ui/scope-install.js +47 -0
  106. package/dist/ui/selection.js +51 -0
  107. package/dist/ui/theme.js +37 -0
  108. package/dist/version.js +12 -0
  109. package/package.json +73 -4
@@ -0,0 +1,48 @@
1
+ import { CliError } from "../errors.js";
2
+ import { pickOne } from "../ui/pick.js";
3
+ import { clean, originLabel } from "../ui/format.js";
4
+ const nouns = {
5
+ skill: "Skill",
6
+ hook: "Hook",
7
+ mcp: "MCP server",
8
+ };
9
+ const groups = {
10
+ skill: "skills",
11
+ hook: "hooks",
12
+ mcp: "mcp",
13
+ };
14
+ /**
15
+ * Names are unique only within a scope, so `--origin` picks between scopes
16
+ * that share one. When only one scope has the name, as in a local folder
17
+ * with its single scope, the name alone identifies the asset.
18
+ */
19
+ export async function resolveOrigin(context, kind, name, origin, usage) {
20
+ if (origin)
21
+ return origin;
22
+ const rows = (await context.searchCatalog(kind)).filter((row) => row.name === name || row.id === name);
23
+ if (!rows.length)
24
+ throw new CliError(`No ${nouns[kind]} named ${name} is available to you.`, `barndog ${groups[kind]} search ${name}`);
25
+ const labels = [...new Set(rows.map((row) => originLabel(row.origin)))];
26
+ if (labels.length === 1)
27
+ return labels[0];
28
+ if (!context.mode.interactive)
29
+ throw new CliError(`${name} exists in several scopes: ${labels.join(", ")}. Choose one with --origin.`, `${usage} --origin ${labels[0]}`);
30
+ return pickOne(`${name} exists in several scopes. Which one?`, labels.map((label) => ({
31
+ value: label,
32
+ name: label,
33
+ hint: clean(rows.find((row) => originLabel(row.origin) === label).version
34
+ .description),
35
+ })));
36
+ }
37
+ /** Lets the person choose an installed asset when the command was given no name. */
38
+ export async function pickInstalled(context, kind, usage) {
39
+ if (!context.mode.interactive)
40
+ throw new CliError(`Name the ${nouns[kind]} to use, or run this in a terminal to choose from a list.`, usage);
41
+ const items = (await context.inventory()).items.filter((item) => item.kind === kind && item.origin !== "—");
42
+ const item = await pickOne(`Choose a ${nouns[kind]}`, items.map((item) => ({
43
+ value: item,
44
+ name: item.installedName,
45
+ hint: `${item.origin} · ${item.state}`,
46
+ })), { empty: `No ${nouns[kind]}s are installed on this machine.` });
47
+ return { name: item.name, origin: item.origin };
48
+ }
@@ -0,0 +1,66 @@
1
+ import { harnessNames, inventoryHints, kindLabels, renderInventory, } from "../ui/assets.js";
2
+ import { renderCollaboration } from "../ui/collaboration.js";
3
+ import { dim, fields, heading, hint, json, ok, plural } from "../ui/format.js";
4
+ export function registerStatus(program, context) {
5
+ program
6
+ .command("status")
7
+ .description("Show what's installed on this machine and where (inside a working copy, its edits first)")
8
+ .option("--paths", "Show installed folders and configuration files")
9
+ .action(async (options) => {
10
+ const working = (await context.collaborate("status", {}));
11
+ const inventory = await context.inventory();
12
+ if (context.mode.json)
13
+ return context.write(json(working.mode === "environment"
14
+ ? inventory
15
+ : { workingCopy: working, ...inventory }));
16
+ if (working.mode !== "environment") {
17
+ for (const line of renderCollaboration("status", working))
18
+ context.write(line);
19
+ context.write("");
20
+ }
21
+ context.write(`${heading("status")}\n`);
22
+ for (const line of fields([
23
+ ["Workspace", inventory.server ?? dim("local only")],
24
+ [
25
+ "Coding tools",
26
+ harnessNames(inventory.harnesses) || dim("none selected"),
27
+ ],
28
+ [
29
+ "Knowledge",
30
+ inventory.server
31
+ ? inventory.knowledge
32
+ ? ok("listed at session start")
33
+ : dim("off")
34
+ : undefined,
35
+ ],
36
+ ]))
37
+ context.write(line);
38
+ if (inventory.offline)
39
+ context.write(dim(`\nShowing local state only: ${inventory.offline}`));
40
+ for (const kind of ["skill", "mcp", "hook"]) {
41
+ const items = inventory.items.filter((item) => item.kind === kind);
42
+ context.write("");
43
+ if (!items.length) {
44
+ context.write(`${kindLabels[kind].title} ${dim("(0)")}`);
45
+ context.write(dim(` None. ${`barndog ${kindLabels[kind].group} install`} to add some.`));
46
+ continue;
47
+ }
48
+ for (const line of renderInventory(items, {
49
+ heading: kindLabels[kind].title,
50
+ paths: options.paths,
51
+ }))
52
+ context.write(line);
53
+ }
54
+ const hints = inventoryHints(inventory.items);
55
+ context.write("");
56
+ if (hints.length)
57
+ for (const line of hints)
58
+ context.write(line);
59
+ // Without the workspace, BarnDog only knows what is installed, not whether it's current.
60
+ else if (inventory.offline)
61
+ context.write(`${plural(inventory.items.length, "asset")} installed. ${dim("Couldn't check for updates; run barndog sync once the workspace is reachable.")}`);
62
+ else
63
+ context.write(`${ok("✔")} ${plural(inventory.items.length, "asset")} up to date.` +
64
+ (options.paths ? "" : ` ${hint("barndog status --paths", "Tip")}`));
65
+ });
66
+ }
@@ -0,0 +1,30 @@
1
+ import { resolve } from "node:path";
2
+ import { renderSyncOutput } from "../ui/output.js";
3
+ import { json } from "../ui/format.js";
4
+ import { autoSync } from "../features/environment/auto-sync.js";
5
+ export function registerSync(program, context) {
6
+ program
7
+ .command("sync")
8
+ .description("Apply your selection to every coding tool: install, update and remove Skills, MCP servers, Hooks and knowledge")
9
+ .option("--dry-run", "Show what would change without changing anything")
10
+ .option("-v, --verbose", "Also list what is already up to date, including BarnDog's own entries")
11
+ .option("--config <path>", "Use an explicit configuration file once")
12
+ .option("--auto", "Quiet background sync used at session start")
13
+ .action(async (options) => {
14
+ // Runs detached at session start: nobody is watching, so it never reports.
15
+ if (options.auto) {
16
+ await autoSync(() => context.synchronize(undefined, { refresh: "auto", prompt: false })).catch(() => undefined);
17
+ return;
18
+ }
19
+ const configPath = options.config === undefined ? undefined : resolve(options.config);
20
+ const events = await context.synchronize(configPath, options.dryRun ? { dryRun: true } : undefined);
21
+ if (context.mode.json)
22
+ return context.write(json(events));
23
+ for (const line of renderSyncOutput(events, {
24
+ title: options.dryRun ? "sync --dry-run" : "sync",
25
+ preview: options.dryRun,
26
+ verbose: options.verbose,
27
+ }))
28
+ context.write(line);
29
+ });
30
+ }
@@ -0,0 +1,84 @@
1
+ import { bold, dim, heading, json, ok, plural, table, warn, } from "../ui/format.js";
2
+ import { renderMove } from "../ui/move.js";
3
+ export function registerWorkspace(program, context) {
4
+ program
5
+ .command("validate [directory]")
6
+ .description("Check a BarnDog workspace folder, for example in a repo's CI")
7
+ .action(async (directory) => {
8
+ const result = (await context.capability("validate", { directory }));
9
+ if (context.mode.json)
10
+ return context.write(json(result));
11
+ context.write(`${ok("✔")} ${bold(result.workspace)} is valid · ${plural(result.assets, "asset")}, ${plural(result.knowledge, "knowledge document")}`);
12
+ });
13
+ const local = program
14
+ .command("local")
15
+ .description("See and share the assets kept in this machine's folder");
16
+ local
17
+ .command("list")
18
+ .description("List local assets and whether they've been moved")
19
+ .action(async () => {
20
+ const result = (await context.capability("local-list", {}));
21
+ if (context.mode.json)
22
+ return context.write(json(result));
23
+ context.write(dim(result.folder));
24
+ if (!result.assets.length)
25
+ return context.write(dim("No local assets."));
26
+ for (const line of table(result.assets.map((asset) => [
27
+ bold(asset.name),
28
+ dim(asset.kind),
29
+ asset.state === "invalid" ? warn(asset.state) : asset.state,
30
+ dim(asset.path),
31
+ ]), { header: ["Name", "Kind", "State", "Path"] }))
32
+ context.write(line);
33
+ });
34
+ local
35
+ .command("move [names...]")
36
+ .description("Copy local assets into your Git or Cloud workspace")
37
+ .option("--to <origin>", "Destination, such as me, org or team/web. Defaults to me in cloud, org in Git")
38
+ .option("--as <name>", "New name, for moving one asset whose name is taken")
39
+ .option("--repo <url>", "Send to this Git repo; this machine stays as it is")
40
+ .option("--server <url>", "Send to this Cloud Workspace; this machine stays as it is")
41
+ .action(async (names, options) => {
42
+ const result = (await context.capability("local-move", {
43
+ names,
44
+ to: options.to,
45
+ as: options.as,
46
+ repo: options.repo,
47
+ server: options.server,
48
+ }));
49
+ if (context.mode.json)
50
+ return context.write(json(result));
51
+ for (const line of renderMove(result))
52
+ context.write(line);
53
+ });
54
+ program
55
+ .command("migrate")
56
+ .description("Move a Git repo or local workspace to a BarnDog Cloud Workspace")
57
+ .requiredOption("--to <server>", "Cloud or self-hosted server URL")
58
+ .option("--dry-run", "Show what would move without changing anything")
59
+ .action(async (options) => {
60
+ const result = (await context.capability("migrate", {
61
+ server: options.to,
62
+ dryRun: options.dryRun,
63
+ }));
64
+ if (context.mode.json)
65
+ return context.write(json(result));
66
+ context.write(`\n${heading(options.dryRun ? "migrate --dry-run" : "migrate")}\n`);
67
+ for (const line of table(result.rows.map((row) => [
68
+ row.action === "publish"
69
+ ? ok(row.action)
70
+ : row.action === "exists"
71
+ ? dim(row.action)
72
+ : warn(row.action),
73
+ dim(row.kind),
74
+ bold(row.name),
75
+ row.origin,
76
+ dim(row.detail ?? ""),
77
+ ]), { header: ["Action", "Kind", "Name", "Origin", ""] }))
78
+ context.write(line);
79
+ context.write("");
80
+ context.write(result.migrated
81
+ ? `${ok("✔")} This machine now uses ${result.server}. Only current content moved; older versions stay in your repo.`
82
+ : dim("Nothing was changed."));
83
+ });
84
+ }
@@ -0,0 +1,2 @@
1
+ /** Offered when setup or login asks for a server. BARNDOG_DEFAULT_SERVER replaces it at build time. */
2
+ export const defaultServer = "https://barndog.dev";
@@ -0,0 +1,41 @@
1
+ import { z } from "zod";
2
+ import { upgradeSettings } from "./settings.js";
3
+ const id = z.uuidv4().transform((value) => value.toLowerCase());
4
+ export const selectionStateSchema = z
5
+ .object({
6
+ subscriptions: z.array(z
7
+ .object({
8
+ scope: z.object({ type: z.enum(["org", "team", "repo"]), id }),
9
+ mode: z.enum(["recommended", "optional", "all"]),
10
+ enabled: z.boolean(),
11
+ })
12
+ .strict()),
13
+ individualAssetIds: z.array(id),
14
+ excludedAssetIds: z.array(id),
15
+ disabledAssetIds: z.array(id),
16
+ })
17
+ .strict();
18
+ export function selectionState(settings) {
19
+ const next = upgradeSettings(settings);
20
+ return (next.environment ?? {
21
+ subscriptions: [],
22
+ individualAssetIds: next.skills
23
+ .filter((s) => s.kind === "api")
24
+ .map((s) => s.id),
25
+ excludedAssetIds: [],
26
+ disabledAssetIds: next.skills
27
+ .filter((s) => s.kind === "api" && !s.enabled)
28
+ .map((s) => s.id),
29
+ });
30
+ }
31
+ export function withSelection(settings, environment) {
32
+ return {
33
+ ...upgradeSettings(settings),
34
+ skills: upgradeSettings(settings).skills.filter((s) => s.kind === "local"),
35
+ environment: selectionStateSchema.parse(environment),
36
+ };
37
+ }
38
+ export function hasRemoteSelections(settings) {
39
+ const state = selectionState(settings);
40
+ return !!(state.subscriptions.length || state.individualAssetIds.length);
41
+ }
@@ -0,0 +1,127 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { parse, stringify } from "yaml";
6
+ import { selectionStateSchema } from "./environment.js";
7
+ import { isHarness } from "../harnesses/registry.js";
8
+ export class SetupRequiredError extends Error {
9
+ constructor() {
10
+ super("Harness selection is not configured.");
11
+ this.name = "SetupRequiredError";
12
+ }
13
+ }
14
+ export function upgradeSettings(settings) {
15
+ return settings.version === 2
16
+ ? settings
17
+ : {
18
+ ...settings,
19
+ version: 2,
20
+ skills: settings.skills.map((skill) => ({ ...skill, kind: "local" })),
21
+ };
22
+ }
23
+ export function settingsPath(home = homedir()) {
24
+ return join(home, ".barndog", "config.yaml");
25
+ }
26
+ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
27
+ function validate(value) {
28
+ if (typeof value !== "object" ||
29
+ value === null ||
30
+ !("version" in value) ||
31
+ (value.version !== 1 && value.version !== 2) ||
32
+ !("harnesses" in value) ||
33
+ !Array.isArray(value.harnesses) ||
34
+ !value.harnesses.every(isHarness) ||
35
+ new Set(value.harnesses).size !== value.harnesses.length ||
36
+ !("skills" in value) ||
37
+ !Array.isArray(value.skills)) {
38
+ throw new Error("Invalid user settings: expected version: 1 or 2, a unique harnesses list (claude, codex, cursor), and a skills array");
39
+ }
40
+ if (value.version === 2) {
41
+ if ("environment" in value)
42
+ selectionStateSchema.parse(value.environment);
43
+ if ("knowledge" in value && typeof value.knowledge !== "boolean")
44
+ throw new Error("Invalid knowledge integration setting");
45
+ if ("localNames" in value &&
46
+ (typeof value.localNames !== "object" ||
47
+ value.localNames === null ||
48
+ Array.isArray(value.localNames) ||
49
+ Object.entries(value.localNames).some(([id, name]) => !uuidPattern.test(id) ||
50
+ typeof name !== "string" ||
51
+ !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) ||
52
+ name.length > 64)))
53
+ throw new Error("Invalid user settings: localNames maps asset IDs to lowercase hyphenated names");
54
+ for (const skill of value.skills) {
55
+ if (!skill ||
56
+ typeof skill !== "object" ||
57
+ !["local", "api"].includes(skill.kind) ||
58
+ typeof skill.id !== "string" ||
59
+ !uuidPattern.test(skill.id) ||
60
+ typeof skill.enabled !== "boolean" ||
61
+ (skill.kind === "local" &&
62
+ (typeof skill.source !== "string" || !skill.source.trim())))
63
+ throw new Error("Invalid user settings: invalid skill selection");
64
+ }
65
+ if (new Set(value.skills.map((skill) => skill.id.toLowerCase())).size !==
66
+ value.skills.length)
67
+ throw new Error("Invalid user settings: duplicate Skill ID");
68
+ const connection = "connection" in value ? value.connection : undefined;
69
+ if (connection &&
70
+ (typeof connection.server !== "string" ||
71
+ !/^https?:\/\//.test(connection.server) ||
72
+ typeof connection.organizationId !== "string" ||
73
+ typeof connection.developerId !== "string"))
74
+ throw new Error("Invalid user settings: invalid server connection");
75
+ const git = "gitWorkspace" in value
76
+ ? value.gitWorkspace
77
+ : undefined;
78
+ const local = "localWorkspace" in value
79
+ ? value.localWorkspace
80
+ : undefined;
81
+ if (git &&
82
+ (typeof git.url !== "string" ||
83
+ !git.url ||
84
+ git.url.startsWith("-") ||
85
+ typeof git.branch !== "string" ||
86
+ !git.branch ||
87
+ !uuidPattern.test(git.workspaceId)))
88
+ throw new Error("Invalid user settings: invalid Git workspace");
89
+ if (local &&
90
+ (typeof local.path !== "string" ||
91
+ !isAbsolute(local.path) ||
92
+ !uuidPattern.test(local.workspaceId)))
93
+ throw new Error("Invalid user settings: invalid local workspace");
94
+ if (connection && git)
95
+ throw new Error("Invalid user settings: use only one of connection and gitWorkspace");
96
+ if (value.skills.some((skill) => skill.kind === "api") && !connection)
97
+ throw new Error("Invalid user settings: API selections require a connection");
98
+ if ("environment" in value &&
99
+ (() => {
100
+ const state = selectionStateSchema.parse(value.environment);
101
+ return state.subscriptions.length || state.individualAssetIds.length;
102
+ })() &&
103
+ !connection &&
104
+ !git &&
105
+ !local)
106
+ throw new Error("Invalid user settings: API selections require a connection");
107
+ }
108
+ return value;
109
+ }
110
+ export async function readSettings(home = homedir(), path = settingsPath(home)) {
111
+ try {
112
+ return validate(parse(await readFile(path, "utf8")));
113
+ }
114
+ catch (error) {
115
+ if (error.code === "ENOENT")
116
+ return null;
117
+ throw error;
118
+ }
119
+ }
120
+ export async function saveSettings(settings, home = homedir()) {
121
+ validate(settings);
122
+ const path = settingsPath(home);
123
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
124
+ const temporary = `${path}.${randomUUID()}.tmp`;
125
+ await writeFile(temporary, stringify(settings), { mode: 0o600 });
126
+ await rename(temporary, path);
127
+ }
@@ -0,0 +1,70 @@
1
+ import { readFile, readlink, rename, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute } from "node:path";
3
+ import { isHarness, skillDirectory, } from "../harnesses/registry.js";
4
+ import { treeFingerprint } from "../features/environment/installed.js";
5
+ import { isRecord, uuid, skillName } from "../features/skills/validation.js";
6
+ /**
7
+ * Older versions could record two assets at one target. Only one can be real, so
8
+ * keep the link the target actually points to, then the one whose copy is on disk.
9
+ */
10
+ async function withoutRepeatedLinks(links, installed) {
11
+ const records = Array.isArray(installed) ? installed.filter(isRecord) : [];
12
+ const score = async (link) => {
13
+ if (typeof link.target !== "string" || typeof link.source !== "string")
14
+ return 0;
15
+ const actual = await readlink(link.target).catch(() => null);
16
+ const entry = records.find((item) => item.id === link.id && item.path === link.source);
17
+ return ((actual === link.source ? 2 : 0) +
18
+ (entry?.fingerprint === (await treeFingerprint(link.source)) ? 1 : 0));
19
+ };
20
+ const kept = [];
21
+ for (const link of links) {
22
+ const index = isRecord(link) && typeof link.target === "string"
23
+ ? kept.findIndex((other) => isRecord(other) && other.target === link.target)
24
+ : -1;
25
+ if (index < 0) {
26
+ kept.push(link);
27
+ continue;
28
+ }
29
+ const held = kept[index];
30
+ if ((await score(link)) > (await score(held)))
31
+ kept[index] = link;
32
+ }
33
+ return kept;
34
+ }
35
+ export async function readState(path, home) {
36
+ let value;
37
+ try {
38
+ value = JSON.parse(await readFile(path, "utf8"));
39
+ }
40
+ catch (error) {
41
+ if (isRecord(error) && error.code === "ENOENT")
42
+ return { version: 1, links: [] };
43
+ throw error;
44
+ }
45
+ if (!isRecord(value) || value.version !== 1 || !Array.isArray(value.links))
46
+ throw new Error("Invalid installation state");
47
+ const links = await withoutRepeatedLinks(value.links, value.installed);
48
+ const targets = new Set();
49
+ for (const link of links) {
50
+ if (!isRecord(link) ||
51
+ typeof link.id !== "string" ||
52
+ !uuid.test(link.id) ||
53
+ !isHarness(link.harness) ||
54
+ typeof link.source !== "string" ||
55
+ !isAbsolute(link.source) ||
56
+ typeof link.target !== "string" ||
57
+ dirname(link.target) !== skillDirectory(link.harness, home) ||
58
+ !skillName.test(basename(link.target)) ||
59
+ targets.has(link.target)) {
60
+ throw new Error("Invalid installation state; refusing to modify harness files");
61
+ }
62
+ targets.add(link.target);
63
+ }
64
+ return { ...value, links };
65
+ }
66
+ export async function saveState(path, state) {
67
+ const temp = `${path}.${process.pid}.tmp`;
68
+ await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
69
+ await rename(temp, path);
70
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,154 @@
1
+ import { ApiError } from "@barndog-ai/api-contract";
2
+ import { z } from "zod";
3
+ /** A user-facing failure with an optional command that fixes it. */
4
+ export class CliError extends Error {
5
+ hint;
6
+ constructor(message, hint, options) {
7
+ super(message, options);
8
+ this.name = "CliError";
9
+ this.hint = hint;
10
+ }
11
+ }
12
+ /** Ends a command early when there is nothing to choose; not a failure. */
13
+ export class NothingToDoError extends CliError {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "NothingToDoError";
17
+ }
18
+ }
19
+ const packageMessages = {
20
+ INVALID_SKILL_MD: "SKILL.md needs front matter with a lowercase hyphenated name and a description",
21
+ MISSING_SKILL_MD: "This folder has no SKILL.md",
22
+ GITHUB_APP_NOT_CONFIGURED: "GitHub isn't set up on this BarnDog server",
23
+ GITHUB_USER_AUTHORIZATION_REQUIRED: "Link your GitHub account first with barndog github auth",
24
+ IDEMPOTENCY_KEY_REUSED: "That retry key was already used for different content. Use a new --key",
25
+ ORGANIZATION_ADMIN_REQUIRED: "Only organization admins can do that",
26
+ UNSAFE_PACKAGE_ENTRY: "It contains a link or an unsafe file path",
27
+ CONFLICTING_PACKAGE_PATHS: "A file and a folder share the same path",
28
+ PACKAGE_TOO_LARGE: "It's too large to package",
29
+ EMPTY_HOOK_EVENTS: "hook.yaml lists no events for one of its coding tools",
30
+ CURSOR_COMMAND_HANDLER_REQUIRED: "Cursor events in hook.yaml list commands directly, without a nested hooks list",
31
+ NATIVE_MATCHER_GROUP_REQUIRED: "Claude Code and Codex events in hook.yaml need a nested hooks list",
32
+ HOOK_COMMAND_MUST_REFERENCE_DECLARED_SCRIPT: "Each command in hook.yaml must run a declared script through ${BARNDOG_HOOK_ROOT}/",
33
+ };
34
+ /** Server refusals people run into, with what to do next when there is something to do. */
35
+ const serverProblems = {
36
+ APPROVALS_REQUIRED: {
37
+ message: "This change needs more approvals before it can merge",
38
+ fix: "barndog changes list",
39
+ },
40
+ CHANGE_AUTHOR_REQUIRED: {
41
+ message: "Only the author of this change can revise it",
42
+ fix: "barndog push --new",
43
+ },
44
+ CHANGE_CLOSED: {
45
+ message: "This change is closed",
46
+ fix: "barndog push --new",
47
+ },
48
+ CHANGE_CLOSE_FORBIDDEN: {
49
+ message: "Only its author or an admin can close this change",
50
+ },
51
+ CHANGES_REQUESTED: {
52
+ message: "A reviewer requested changes, so this can't merge yet",
53
+ fix: "barndog changes list",
54
+ },
55
+ MCP_NOT_FOUND: {
56
+ message: "No MCP server matches that name and origin",
57
+ fix: "barndog mcp search",
58
+ },
59
+ MERGE_ADMIN_REQUIRED: { message: "Only admins can merge changes here" },
60
+ MERGE_MEMBERSHIP_REQUIRED: {
61
+ message: "Only members of this team or repository can merge its changes",
62
+ },
63
+ NO_CHANGES: {
64
+ message: "Nothing differs from the published version",
65
+ fix: "barndog status",
66
+ },
67
+ OUTDATED_SUGGESTION: {
68
+ message: "That suggestion no longer applies to the current revision",
69
+ fix: "barndog changes list",
70
+ },
71
+ PERSONAL_OWNER_REQUIRED: { message: "Only its owner can do that" },
72
+ PUBLICATION_FORBIDDEN: {
73
+ message: "You can't publish here directly. Propose it for review instead",
74
+ fix: "barndog push",
75
+ },
76
+ REVIEW_MEMBERSHIP_REQUIRED: {
77
+ message: "Only members of this team or repository can review its changes",
78
+ },
79
+ SCOPE_ADMIN_REQUIRED: { message: "Only an admin of this scope can do that" },
80
+ SCOPE_MEMBERSHIP_REQUIRED: { message: "You aren't a member of this scope" },
81
+ SCOPE_NOT_FOUND: {
82
+ message: "No scope matches that origin",
83
+ fix: "barndog sets list",
84
+ },
85
+ SELF_REVIEW_FORBIDDEN: {
86
+ message: "You can't review your own change. Ask a teammate to review it",
87
+ },
88
+ SKILL_NOT_FOUND: {
89
+ message: "No Skill matches that name and origin",
90
+ fix: "barndog skills search",
91
+ },
92
+ STALE_CHANGE_REVISION: {
93
+ message: "This change has a newer revision. Review it, then retry",
94
+ fix: "barndog changes list",
95
+ },
96
+ STALE_SKILL_VERSION: {
97
+ message: "A newer version was published after this change was made",
98
+ fix: "barndog pull",
99
+ },
100
+ SUGGESTION_CONTENT_MISMATCH: {
101
+ message: "--expected-file doesn't match those lines in this revision. Suggestions also need --side new",
102
+ fix: "barndog changes list",
103
+ },
104
+ THREAD_ACTION_FORBIDDEN: {
105
+ message: "Only the discussion's author or an admin can do that",
106
+ },
107
+ };
108
+ /** The next command for a server refusal or a CliError, when one is known. */
109
+ export function friendlyHint(error) {
110
+ if (error instanceof CliError)
111
+ return error.hint;
112
+ if (error instanceof ApiError)
113
+ return serverProblems[error.message]?.fix;
114
+ return undefined;
115
+ }
116
+ /** Turns internal codes and validation errors into something a person can act on. */
117
+ export function friendlyMessage(error) {
118
+ if (!(error instanceof Error))
119
+ return String(error);
120
+ if (error instanceof z.ZodError)
121
+ return error.issues
122
+ .map((issue) => {
123
+ const text = issue.code === "invalid_format" && issue.format === "uuid"
124
+ ? "That isn't a valid ID. IDs look like 123e4567-e89b-42d3-a456-426614174000."
125
+ : issue.message;
126
+ return issue.path.length ? `${issue.path.join(".")}: ${text}` : text;
127
+ })
128
+ .join("; ");
129
+ if (error instanceof ApiError && serverProblems[error.message])
130
+ return `${serverProblems[error.message].message}.`;
131
+ const code = error.code;
132
+ const path = error.path;
133
+ if (code === "ENOENT" && path)
134
+ return `Can't find ${path}.`;
135
+ if (code === "EACCES" && path)
136
+ return `No permission to read ${path}.`;
137
+ if (code === "EISDIR" && path)
138
+ return `${path} is a folder, not a file.`;
139
+ if (code === "EEXIST" && path)
140
+ return `${path} already exists. Choose another folder or remove it first.`;
141
+ const [prefix, detail] = error.message.split(/: (.*)/s);
142
+ if (prefix === "MISSING_HOOK_SCRIPT")
143
+ return `hook.yaml declares a script that isn't in the folder: ${detail}`;
144
+ if (prefix === "MISSING_PACKAGE_MANIFEST")
145
+ return `This folder has no ${detail}`;
146
+ if (prefix === "UNSAFE_PACKAGE_ENTRY" && detail)
147
+ return detail;
148
+ if (packageMessages[prefix])
149
+ return packageMessages[prefix];
150
+ // Server codes such as KNOWLEDGE_NOT_FOUND still read as a sentence.
151
+ if (/^[A-Z][A-Z0-9_]+$/.test(error.message))
152
+ return `${error.message[0]}${error.message.slice(1).toLowerCase().replace(/_/g, " ")}.`;
153
+ return error.message;
154
+ }