barndog 0.1.1 → 0.2.1

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 (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -0,0 +1,24 @@
1
+ /** The largest page the server's list routes return. */
2
+ export const PAGE_SIZE = 100;
3
+ /**
4
+ * Every item of a cursor-paginated list, fetching pages until the server stops
5
+ * returning a cursor. A cursor the server already returned means it would loop
6
+ * forever, so that fails as a broken server response.
7
+ */
8
+ export async function allPages(fetchPage) {
9
+ const items = [];
10
+ const seen = new Set();
11
+ let cursor;
12
+ do {
13
+ const page = await fetchPage(cursor);
14
+ items.push(...page.items);
15
+ if (page.nextCursor && seen.has(page.nextCursor)) {
16
+ throw new Error("The server sent an invalid page of results");
17
+ }
18
+ if (page.nextCursor) {
19
+ seen.add(page.nextCursor);
20
+ }
21
+ cursor = page.nextCursor ?? undefined;
22
+ } while (cursor);
23
+ return items;
24
+ }
@@ -0,0 +1,42 @@
1
+ import { contextSchema, listOutputSchema, } from "@barndog-ai/api-contract";
2
+ import { apiClient } from "../auth/transport.js";
3
+ import { CliError } from "../../errors.js";
4
+ import { allPages } from "../server/pages.js";
5
+ /**
6
+ * Every published Skill the developer can see, page by page. Throws when the
7
+ * server now reports another organization or developer than `connection`, or
8
+ * answers with a broken page.
9
+ */
10
+ export async function publishedSkills(connection, runtime) {
11
+ const client = apiClient(connection.server, runtime);
12
+ const context = contextSchema.parse((await client.GET("/v1/context")).data);
13
+ if (context.organization.id !== connection.organizationId ||
14
+ context.developer.id !== connection.developerId) {
15
+ throw new CliError("The server's organization or developer changed since this machine was set up.", "barndog init");
16
+ }
17
+ const skills = await allPages(async (cursor) => {
18
+ const page = listOutputSchema.parse((await client.GET("/v1/skills", {
19
+ params: { query: { cursor, limit: 100 } },
20
+ })).data);
21
+ if (page.skills.some((skill) => skill.organizationId !== connection.organizationId)) {
22
+ throw new Error("The server sent a catalog page for another organization");
23
+ }
24
+ return { items: page.skills, nextCursor: page.nextCursor };
25
+ });
26
+ if (new Set(skills.map((skill) => skill.id)).size !== skills.length) {
27
+ throw new Error("The server sent the same Skill twice in its catalog");
28
+ }
29
+ return skills;
30
+ }
31
+ export async function skillCatalog(connection, runtime) {
32
+ return (await publishedSkills(connection, runtime)).map((skill) => ({
33
+ id: skill.id,
34
+ kind: "skill",
35
+ name: skill.name,
36
+ origin: skill.origin,
37
+ version: {
38
+ number: skill.version.number,
39
+ description: skill.version.description,
40
+ },
41
+ }));
42
+ }
@@ -0,0 +1,57 @@
1
+ import { localPath } from "../../platform.js";
2
+ import { hookMetadata } from "@barndog-ai/api-contract/package";
3
+ import { CliError } from "../../errors.js";
4
+ import { matchesOrigin } from "../server/origin.js";
5
+ import { originLabel } from "../server/origin.js";
6
+ import { loadWorkspace, } from "./format.js";
7
+ import { folderSnapshot } from "./snapshot.js";
8
+ import { openRepoSource } from "./workspace-source.js";
9
+ import { LOCAL_ORIGIN, localOverlay } from "./overlay.js";
10
+ import { assetNotFound } from "../asset-kinds/index.js";
11
+ import { only } from "../../shared/lookup.js";
12
+ /** The repo-backed source that answers for an origin, if any. */
13
+ export function repoForOrigin(settings, runtime, origin) {
14
+ const overlay = localOverlay(settings, runtime);
15
+ return origin === LOCAL_ORIGIN && overlay
16
+ ? overlay
17
+ : openRepoSource(settings, runtime, { refresh: "auto" });
18
+ }
19
+ /** Finds one asset by name and origin, the way cloud commands address assets. */
20
+ export function selectRepoAsset(model, kind, name, origin) {
21
+ const matches = model.assets.filter((asset) => asset.kind === kind &&
22
+ (asset.id === name || asset.name === name) &&
23
+ (origin === LOCAL_ORIGIN || matchesOrigin(asset.origin, origin, model)));
24
+ const asset = only(matches);
25
+ if (!asset) {
26
+ throw assetNotFound(kind, name, origin);
27
+ }
28
+ if (asset.invalid) {
29
+ throw new CliError(`${asset.path} is invalid: ${asset.invalid}`);
30
+ }
31
+ return asset;
32
+ }
33
+ export function showRepoAsset(asset) {
34
+ return {
35
+ id: asset.id,
36
+ kind: asset.kind,
37
+ name: asset.name,
38
+ origin: originLabel(asset.origin),
39
+ path: asset.path,
40
+ version: asset.publishedVersion,
41
+ description: asset.description,
42
+ ...(asset.definition ? { definition: asset.definition } : {}),
43
+ ...(asset.kind === "hook" ? { manifest: hookMetadata(asset.entries) } : {}),
44
+ };
45
+ }
46
+ /** Checks a workspace folder without installing anything, for use in repo CI. */
47
+ export async function validateFolder(directory, runtime) {
48
+ const model = await loadWorkspace(await folderSnapshot(localPath(directory, runtime), runtime));
49
+ if (model.problems.length) {
50
+ throw new CliError(`${model.problems.length} problem${model.problems.length === 1 ? "" : "s"} found:\n${model.problems.map((problem) => ` ${problem.path}: ${problem.reason}`).join("\n")}`, "Fix the files listed, then validate again");
51
+ }
52
+ return {
53
+ workspace: model.config.name,
54
+ assets: model.assets.length,
55
+ knowledge: model.knowledge.length,
56
+ };
57
+ }
@@ -0,0 +1,34 @@
1
+ import { mcpSchema } from "@barndog-ai/api-contract";
2
+ import { assetKinds } from "../asset-kinds/index.js";
3
+ import { cacheKey, cachedPackage } from "./packages.js";
4
+ import { environmentCatalog, getAsset } from "../server/catalog.js";
5
+ import { CliError } from "../../errors.js";
6
+ async function currentAsset(kind, reference, conn, runtime) {
7
+ const data = await getAsset(kind, reference.id, conn, runtime);
8
+ if (data.id !== reference.id ||
9
+ data.version.id !== reference.publishedVersion ||
10
+ data.name !== reference.name ||
11
+ data.organizationId !== conn.organizationId) {
12
+ throw new CliError("The catalog changed while syncing.", "barndog sync");
13
+ }
14
+ return data;
15
+ }
16
+ /**
17
+ * Adapts an authenticated cloud connection to lazy catalog, package-cache and
18
+ * MCP reads for synchronization.
19
+ */
20
+ export function cloudSource(conn, runtime) {
21
+ return {
22
+ cacheKey: cacheKey(conn),
23
+ journal: conn,
24
+ catalog: async () => (await environmentCatalog(runtime, conn)).catalog,
25
+ packageFolder: async (kind, reference) => {
26
+ const data = await currentAsset(kind, reference, conn, runtime);
27
+ return cachedPackage(kind, assetKinds[kind].schema.parse(data), conn, runtime);
28
+ },
29
+ mcpDefinition: async (reference) => mcpSchema.parse(await currentAsset("mcp", reference, conn, runtime))
30
+ .version.definition,
31
+ invalidAssets: () => Promise.resolve(new Map()),
32
+ notices: () => [],
33
+ };
34
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Package folders on disk: reading one to submit, writing one BarnDog
3
+ * fetched. Package paths always use `/`; local paths only appear at the
4
+ * filesystem calls.
5
+ */
6
+ import { lstat } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { readDirectory as readPackageDirectory } from "@barndog-ai/api-contract/collaboration";
9
+ import { writePackage as writePackageFiles, packageFingerprint, } from "@barndog-ai/api-contract/package";
10
+ import { assertPackagePaths, fileExecutable, isWindows, } from "../../platform.js";
11
+ import { readTree } from "./tree.js";
12
+ /**
13
+ * A package folder's files. Windows keeps no executable bit, so there a
14
+ * file's flag comes from the same path in `known`, the files BarnDog last wrote
15
+ * here (see `fileExecutable()`).
16
+ */
17
+ export async function readDirectory(directory, runtime, known = []) {
18
+ const entries = await readPackageDirectory(directory);
19
+ if (!isWindows(runtime.platform)) {
20
+ return entries;
21
+ }
22
+ const flags = new Map(known.map((entry) => [entry.path, entry.executable]));
23
+ return Promise.all(entries.map(async (entry) => {
24
+ const path = join(directory, entry.path);
25
+ return {
26
+ ...entry,
27
+ executable: await fileExecutable(path, (await lstat(path)).mode, runtime, flags.get(entry.path)),
28
+ };
29
+ }));
30
+ }
31
+ export async function writePackage(directory, entries, runtime) {
32
+ assertPackagePaths(entries, runtime.platform);
33
+ await writePackageFiles(directory, entries);
34
+ }
35
+ /** What `readTree()` sees in the folder, so compare it only with another one. */
36
+ export async function directoryFingerprint(directory, runtime) {
37
+ return packageFingerprint(await readTree(directory, runtime));
38
+ }
@@ -3,16 +3,47 @@ import { knowledgeContentSchema, mcpDefinitionSchema, } from "@barndog-ai/api-co
3
3
  import { hookMetadata, packageMetadata, validatePackageEntries, } from "@barndog-ai/api-contract/package";
4
4
  import { parse, stringify } from "yaml";
5
5
  import { z } from "zod";
6
- import { CliError, friendlyMessage } from "../../errors.js";
7
- import { isBlob, TREE_MODE, } from "./snapshot.js";
6
+ import { CliError, friendlyMessage, PackageError } from "../../errors.js";
7
+ import { isBlob, GIT_MODE, } from "./snapshot.js";
8
+ import { assetKinds } from "../asset-kinds/index.js";
9
+ import { defined } from "../../shared/lookup.js";
10
+ import { NAME, splitFrontMatter, validAssetName, } from "../../shared/patterns.js";
11
+ /** BarnDog workspace configuration allows display names up to 200 characters. */
12
+ const MAX_WORKSPACE_NAME_LENGTH = 200;
13
+ /** RFC 9562 UUIDs contain 128 bits, or sixteen bytes. */
14
+ const UUID_BYTE_LENGTH = 16;
15
+ /** RFC 9562 places the version nibble in byte six (zero based). */
16
+ const UUID_VERSION_BYTE = 6;
17
+ /** RFC 9562 preserves the low nibble when setting the UUID version. */
18
+ const UUID_VERSION_PAYLOAD_MASK = 0x0f;
19
+ /** RFC 9562 version four occupies the high nibble. */
20
+ const UUID_V4_BITS = 0x40;
21
+ /** RFC 9562 places the variant bits in byte eight (zero based). */
22
+ const UUID_VARIANT_BYTE = 8;
23
+ /** RFC 9562 preserves six payload bits for the IETF variant. */
24
+ const UUID_VARIANT_PAYLOAD_MASK = 0x3f;
25
+ /** RFC 9562 IETF variant starts with binary 10. */
26
+ const UUID_IETF_VARIANT_BITS = 0x80;
27
+ /** RFC 9562 hexadecimal UUID first group ends at character eight. */
28
+ const UUID_FIRST_GROUP_END = 8;
29
+ /** RFC 9562 hexadecimal UUID third group ends at character sixteen. */
30
+ const UUID_THIRD_GROUP_END = 16;
31
+ /** RFC 9562 hexadecimal UUID group boundary (8-4-4-4-12). */
32
+ const UUID_SECOND_GROUP_END = 12;
33
+ /** RFC 9562 hexadecimal UUID fourth group ends at character twenty. */
34
+ const UUID_FOURTH_GROUP_END = 20;
35
+ /**
36
+ * The file at a Git or local workspace's root naming the workspace and
37
+ * declaring its teams and repositories.
38
+ */
8
39
  export const CONFIG_FILE = "barndog.yaml";
9
40
  export const NAME_RULE = "Names use lowercase letters, numbers and single hyphens";
10
- const slug = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
41
+ const slug = z.string().regex(NAME);
11
42
  const configSchema = z
12
43
  .object({
13
44
  version: z.literal(1),
14
45
  workspaceId: z.uuidv4(),
15
- name: z.string().trim().min(1).max(200),
46
+ name: z.string().trim().min(1).max(MAX_WORKSPACE_NAME_LENGTH),
16
47
  teams: z
17
48
  .record(slug, z.object({ name: z.string().min(1) }).strict())
18
49
  .default({}),
@@ -28,7 +59,11 @@ const configSchema = z
28
59
  optional: z.array(z.string()).default([]),
29
60
  })
30
61
  .strict();
31
- export function renderConfig(config) {
62
+ /**
63
+ * The `barndog.yaml` a new workspace starts with: format version 1, its ID and
64
+ * name, and no teams or repositories yet.
65
+ */
66
+ function renderConfig(config) {
32
67
  return stringify({
33
68
  version: 1,
34
69
  workspaceId: config.workspaceId,
@@ -38,10 +73,19 @@ export function renderConfig(config) {
38
73
  optional: [],
39
74
  });
40
75
  }
76
+ /** Parses barndog.yaml; malformed YAML and invalid fields are a CliError. */
41
77
  export function parseConfig(text) {
42
- const parsed = configSchema.safeParse(parse(text));
43
- if (!parsed.success)
78
+ let value;
79
+ try {
80
+ value = parse(text);
81
+ }
82
+ catch (error) {
83
+ throw new CliError(`${CONFIG_FILE} isn't valid YAML: ${friendlyMessage(error)}`, `Fix the YAML in ${CONFIG_FILE}, then try again`, { cause: error });
84
+ }
85
+ const parsed = configSchema.safeParse(value);
86
+ if (!parsed.success) {
44
87
  throw new CliError(`${CONFIG_FILE} is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "file"}: ${issue.message}`).join("; ")}`);
88
+ }
45
89
  return parsed.data;
46
90
  }
47
91
  /** A hash formatted as UUIDv4, so IDs need no stored record and cannot merge-conflict. */
@@ -49,21 +93,22 @@ export function stableId(...parts) {
49
93
  const bytes = createHash("sha256")
50
94
  .update(parts.join("\0"))
51
95
  .digest()
52
- .subarray(0, 16);
53
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
54
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
96
+ .subarray(0, UUID_BYTE_LENGTH);
97
+ // A 16-byte digest always has these bytes; set the UUID version and variant bits.
98
+ bytes.writeUInt8((bytes.readUInt8(UUID_VERSION_BYTE) & UUID_VERSION_PAYLOAD_MASK) |
99
+ UUID_V4_BITS, UUID_VERSION_BYTE);
100
+ bytes.writeUInt8((bytes.readUInt8(UUID_VARIANT_BYTE) & UUID_VARIANT_PAYLOAD_MASK) |
101
+ UUID_IETF_VARIANT_BITS, UUID_VARIANT_BYTE);
55
102
  const hex = bytes.toString("hex");
56
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
103
+ return `${hex.slice(0, UUID_FIRST_GROUP_END)}-${hex.slice(UUID_FIRST_GROUP_END, UUID_SECOND_GROUP_END)}-${hex.slice(UUID_SECOND_GROUP_END, UUID_THIRD_GROUP_END)}-${hex.slice(UUID_THIRD_GROUP_END, UUID_FOURTH_GROUP_END)}-${hex.slice(UUID_FOURTH_GROUP_END)}`;
57
104
  }
58
105
  const hidden = (name) => name.startsWith(".");
59
106
  function frontMatter(text) {
60
- const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
61
- if (!match)
62
- throw new Error("Missing front matter");
63
- return {
64
- metadata: parse(match[1]),
65
- body: text.slice(match[0].length),
66
- };
107
+ const parts = splitFrontMatter(text);
108
+ if (!parts) {
109
+ throw new CliError("It has no front matter");
110
+ }
111
+ return { metadata: parse(parts.yaml), body: parts.body };
67
112
  }
68
113
  function knowledgeContent(name, text) {
69
114
  const { metadata, body } = frontMatter(text);
@@ -76,23 +121,27 @@ function knowledgeContent(name, text) {
76
121
  })
77
122
  .strict()
78
123
  .parse(metadata);
79
- if (fields.name !== undefined && fields.name !== name)
80
- throw new Error(`name must match the file name (${name})`);
124
+ if (fields.name !== undefined && fields.name !== name) {
125
+ throw new CliError(`name must match the file name (${name})`);
126
+ }
81
127
  return knowledgeContentSchema.parse({ ...fields, name, markdown: body });
82
128
  }
83
129
  /** Turns a snapshot into the same catalog cloud returns, reporting what cannot install. */
84
130
  export async function loadWorkspace(snapshot, expectedId, options = {}) {
85
131
  const byPath = new Map(snapshot.entries.map((entry) => [entry.path, entry]));
86
132
  const configEntry = byPath.get(CONFIG_FILE);
87
- if (!configEntry || !isBlob(configEntry.mode))
133
+ if (!configEntry || !isBlob(configEntry.mode)) {
88
134
  throw new CliError(`This isn't a BarnDog workspace: it has no ${CONFIG_FILE}.`);
135
+ }
89
136
  const blobs = await snapshot.readBlobs(snapshot.entries
90
137
  .filter((entry) => isBlob(entry.mode))
91
138
  .map((entry) => entry.hash));
92
- const text = (entry) => blobs.get(entry.hash).toString("utf8");
139
+ const blob = (entry) => defined(blobs.get(entry.hash), `Git object ${entry.hash} wasn't read`);
140
+ const text = (entry) => blob(entry).toString("utf8");
93
141
  const config = parseConfig(text(configEntry));
94
- if (expectedId && config.workspaceId !== expectedId)
142
+ if (expectedId && config.workspaceId !== expectedId) {
95
143
  throw new CliError(`${CONFIG_FILE} now names a different workspace. Run setup again if this is intended.`, "barndog init");
144
+ }
96
145
  const id = (...parts) => stableId(config.workspaceId, ...parts);
97
146
  const children = new Map();
98
147
  for (const entry of snapshot.entries) {
@@ -106,7 +155,7 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
106
155
  .filter(({ name }) => !hidden(name))
107
156
  .sort((a, b) => a.name.localeCompare(b.name));
108
157
  const folders = (path) => under(path)
109
- .filter(({ entry }) => entry.mode === TREE_MODE)
158
+ .filter(({ entry }) => entry.mode === GIT_MODE.tree)
110
159
  .map(({ name }) => name);
111
160
  const organizationId = id("scope", "org");
112
161
  const scopes = [
@@ -123,10 +172,10 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
123
172
  for (const [type, root, declared] of [
124
173
  ["team", "teams", config.teams],
125
174
  ["repo", "repos", config.repositories],
126
- ])
175
+ ]) {
127
176
  for (const name of [
128
177
  ...new Set([...Object.keys(declared), ...folders(root)]),
129
- ].sort())
178
+ ].sort()) {
130
179
  scopes.push({
131
180
  type,
132
181
  id: id("scope", type, name),
@@ -135,27 +184,32 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
135
184
  canPublish: true,
136
185
  path: `${root}/${name}`,
137
186
  });
187
+ }
188
+ }
138
189
  const problems = [];
139
190
  const assets = [];
140
191
  const knowledge = [];
141
192
  const invalidKnowledge = [];
142
- const named = (path, name) => {
143
- if (validAssetName(name))
193
+ const named = (path, name, rule = { validName: validAssetName, nameRule: NAME_RULE }) => {
194
+ if (rule.validName(name)) {
144
195
  return true;
145
- problems.push({ path, reason: NAME_RULE });
196
+ }
197
+ problems.push({ path, reason: rule.nameRule, badName: true });
146
198
  return false;
147
199
  };
148
200
  function packageEntries(root) {
149
201
  const entries = [];
150
202
  for (const entry of snapshot.entries) {
151
- if (!entry.path.startsWith(`${root}/`) || entry.mode === TREE_MODE)
203
+ if (!entry.path.startsWith(`${root}/`) || entry.mode === GIT_MODE.tree) {
152
204
  continue;
153
- if (!isBlob(entry.mode))
154
- throw new Error(`UNSAFE_PACKAGE_ENTRY: ${entry.path.slice(root.length + 1)} is a link`);
205
+ }
206
+ if (!isBlob(entry.mode)) {
207
+ throw new PackageError("UNSAFE_PACKAGE_ENTRY", entry.path.slice(root.length + 1));
208
+ }
155
209
  entries.push({
156
210
  path: entry.path.slice(root.length + 1),
157
- data: blobs.get(entry.hash),
158
- executable: entry.mode === "100755",
211
+ data: blob(entry),
212
+ executable: entry.mode === GIT_MODE.executable,
159
213
  });
160
214
  }
161
215
  return entries;
@@ -180,52 +234,61 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
180
234
  }
181
235
  };
182
236
  for (const { entry, name } of under(`${scope.path}/skills`)) {
183
- if (entry.mode !== TREE_MODE || !named(entry.path, name))
237
+ if (entry.mode !== GIT_MODE.tree || !named(entry.path, name)) {
184
238
  continue;
239
+ }
185
240
  add("skill", name, entry, () => {
186
241
  const entries = validatePackageEntries(packageEntries(entry.path));
187
242
  const metadata = packageMetadata(entries);
188
- if (metadata.name !== name)
189
- throw new Error(`SKILL.md name must match the folder name (${name})`);
243
+ if (metadata.name !== name) {
244
+ throw new CliError(`SKILL.md name must match the folder name (${name})`);
245
+ }
190
246
  return { description: metadata.description, entries };
191
247
  });
192
248
  }
193
249
  for (const { entry, name } of under(`${scope.path}/hooks`)) {
194
- if (entry.mode !== TREE_MODE || !named(entry.path, name))
250
+ if (entry.mode !== GIT_MODE.tree || !named(entry.path, name)) {
195
251
  continue;
252
+ }
196
253
  add("hook", name, entry, () => {
197
254
  const entries = validatePackageEntries(packageEntries(entry.path), undefined, "hook.yaml");
198
255
  const manifest = hookMetadata(entries);
199
- if (manifest.name !== name)
200
- throw new Error(`hook.yaml name must match the folder name (${name})`);
256
+ if (manifest.name !== name) {
257
+ throw new CliError(`hook.yaml name must match the folder name (${name})`);
258
+ }
201
259
  return { description: manifest.description, entries };
202
260
  });
203
261
  }
204
262
  for (const { entry, name: file } of under(`${scope.path}/mcp`)) {
205
- if (!isBlob(entry.mode) || !/\.ya?ml$/.test(file))
263
+ if (!isBlob(entry.mode) || !/\.ya?ml$/.test(file)) {
206
264
  continue;
265
+ }
207
266
  const name = file.replace(/\.ya?ml$/, "");
208
- if (!named(entry.path, name))
267
+ if (!named(entry.path, name, assetKinds.mcp)) {
209
268
  continue;
269
+ }
210
270
  add("mcp", name, entry, () => {
211
271
  const definition = mcpDefinitionSchema.parse(parse(text(entry)));
212
272
  return { description: definition.description, entries: [], definition };
213
273
  });
214
274
  }
215
275
  if (scope.type !== "org") {
216
- if (under(`${scope.path}/knowledge`).length)
276
+ if (under(`${scope.path}/knowledge`).length) {
217
277
  problems.push({
218
278
  path: `${scope.path}/knowledge`,
219
279
  reason: "Knowledge is organization-wide; move it to org/knowledge",
220
280
  });
281
+ }
221
282
  continue;
222
283
  }
223
284
  for (const { entry, name: file } of under(`${scope.path}/knowledge`)) {
224
- if (!isBlob(entry.mode) || !file.endsWith(".md"))
285
+ if (!isBlob(entry.mode) || !file.endsWith(".md")) {
225
286
  continue;
287
+ }
226
288
  const name = file.replace(/\.md$/, "");
227
- if (!named(entry.path, name))
289
+ if (!named(entry.path, name)) {
228
290
  continue;
291
+ }
229
292
  try {
230
293
  knowledge.push({
231
294
  id: id("knowledge", name),
@@ -242,12 +305,14 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
242
305
  }
243
306
  }
244
307
  const optional = new Set(config.optional);
245
- for (const path of optional)
246
- if (!assets.some((asset) => asset.path === path || asset.path === `${path}.yaml`))
308
+ for (const path of optional) {
309
+ if (!assets.some((asset) => asset.path === path || asset.path === `${path}.yaml`)) {
247
310
  problems.push({
248
311
  path: CONFIG_FILE,
249
312
  reason: `optional names a missing asset: ${path}`,
250
313
  });
314
+ }
315
+ }
251
316
  const distributions = scopes.map((scope) => ({
252
317
  scope: { type: scope.type, id: scope.id },
253
318
  assets: assets
@@ -272,17 +337,19 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
272
337
  problems,
273
338
  };
274
339
  }
275
- export function validAssetName(name) {
276
- return slug.safeParse(name).success && name.length <= 64;
277
- }
278
340
  /** Names become folder and file names, so check them before touching the disk. */
279
341
  export function assertAssetName(name, fix) {
280
- if (!validAssetName(name))
342
+ if (!validAssetName(name)) {
281
343
  throw new CliError(`${name} can't be used as a name. ${NAME_RULE}.`, fix);
344
+ }
282
345
  }
283
- /** Where a new asset of this kind belongs inside a scope. */
284
- export function assetFolder(scopePath, kind, name) {
285
- return `${scopePath}/${kind === "skill" ? "skills" : "hooks"}/${name}`;
346
+ /** Where a new asset belongs inside a scope: a folder per package, a file per MCP server. */
347
+ export function assetPath(scopePath, kind, name) {
348
+ const folder = `${scopePath}/${assetKinds[kind].folder}`;
349
+ if (kind === "mcp") {
350
+ return `${folder}/${name}.yaml`;
351
+ }
352
+ return `${folder}/${name}`;
286
353
  }
287
354
  const WELCOME = `# BarnDog workspace
288
355