barndog 0.1.0 → 0.2.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 (173) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +24 -11
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -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,15 @@ export function renderConfig(config) {
38
73
  optional: [],
39
74
  });
40
75
  }
76
+ /**
77
+ * Parses barndog.yaml and reports schema-invalid fields in a CliError.
78
+ * Malformed YAML can throw a parser error before schema validation.
79
+ */
41
80
  export function parseConfig(text) {
42
81
  const parsed = configSchema.safeParse(parse(text));
43
- if (!parsed.success)
82
+ if (!parsed.success) {
44
83
  throw new CliError(`${CONFIG_FILE} is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "file"}: ${issue.message}`).join("; ")}`);
84
+ }
45
85
  return parsed.data;
46
86
  }
47
87
  /** A hash formatted as UUIDv4, so IDs need no stored record and cannot merge-conflict. */
@@ -49,21 +89,22 @@ export function stableId(...parts) {
49
89
  const bytes = createHash("sha256")
50
90
  .update(parts.join("\0"))
51
91
  .digest()
52
- .subarray(0, 16);
53
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
54
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
92
+ .subarray(0, UUID_BYTE_LENGTH);
93
+ // A 16-byte digest always has these bytes; set the UUID version and variant bits.
94
+ bytes.writeUInt8((bytes.readUInt8(UUID_VERSION_BYTE) & UUID_VERSION_PAYLOAD_MASK) |
95
+ UUID_V4_BITS, UUID_VERSION_BYTE);
96
+ bytes.writeUInt8((bytes.readUInt8(UUID_VARIANT_BYTE) & UUID_VARIANT_PAYLOAD_MASK) |
97
+ UUID_IETF_VARIANT_BITS, UUID_VARIANT_BYTE);
55
98
  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)}`;
99
+ 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
100
  }
58
101
  const hidden = (name) => name.startsWith(".");
59
102
  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
- };
103
+ const parts = splitFrontMatter(text);
104
+ if (!parts) {
105
+ throw new CliError("It has no front matter");
106
+ }
107
+ return { metadata: parse(parts.yaml), body: parts.body };
67
108
  }
68
109
  function knowledgeContent(name, text) {
69
110
  const { metadata, body } = frontMatter(text);
@@ -76,23 +117,27 @@ function knowledgeContent(name, text) {
76
117
  })
77
118
  .strict()
78
119
  .parse(metadata);
79
- if (fields.name !== undefined && fields.name !== name)
80
- throw new Error(`name must match the file name (${name})`);
120
+ if (fields.name !== undefined && fields.name !== name) {
121
+ throw new CliError(`name must match the file name (${name})`);
122
+ }
81
123
  return knowledgeContentSchema.parse({ ...fields, name, markdown: body });
82
124
  }
83
125
  /** Turns a snapshot into the same catalog cloud returns, reporting what cannot install. */
84
126
  export async function loadWorkspace(snapshot, expectedId, options = {}) {
85
127
  const byPath = new Map(snapshot.entries.map((entry) => [entry.path, entry]));
86
128
  const configEntry = byPath.get(CONFIG_FILE);
87
- if (!configEntry || !isBlob(configEntry.mode))
129
+ if (!configEntry || !isBlob(configEntry.mode)) {
88
130
  throw new CliError(`This isn't a BarnDog workspace: it has no ${CONFIG_FILE}.`);
131
+ }
89
132
  const blobs = await snapshot.readBlobs(snapshot.entries
90
133
  .filter((entry) => isBlob(entry.mode))
91
134
  .map((entry) => entry.hash));
92
- const text = (entry) => blobs.get(entry.hash).toString("utf8");
135
+ const blob = (entry) => defined(blobs.get(entry.hash), `Git object ${entry.hash} wasn't read`);
136
+ const text = (entry) => blob(entry).toString("utf8");
93
137
  const config = parseConfig(text(configEntry));
94
- if (expectedId && config.workspaceId !== expectedId)
138
+ if (expectedId && config.workspaceId !== expectedId) {
95
139
  throw new CliError(`${CONFIG_FILE} now names a different workspace. Run setup again if this is intended.`, "barndog init");
140
+ }
96
141
  const id = (...parts) => stableId(config.workspaceId, ...parts);
97
142
  const children = new Map();
98
143
  for (const entry of snapshot.entries) {
@@ -106,7 +151,7 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
106
151
  .filter(({ name }) => !hidden(name))
107
152
  .sort((a, b) => a.name.localeCompare(b.name));
108
153
  const folders = (path) => under(path)
109
- .filter(({ entry }) => entry.mode === TREE_MODE)
154
+ .filter(({ entry }) => entry.mode === GIT_MODE.tree)
110
155
  .map(({ name }) => name);
111
156
  const organizationId = id("scope", "org");
112
157
  const scopes = [
@@ -123,10 +168,10 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
123
168
  for (const [type, root, declared] of [
124
169
  ["team", "teams", config.teams],
125
170
  ["repo", "repos", config.repositories],
126
- ])
171
+ ]) {
127
172
  for (const name of [
128
173
  ...new Set([...Object.keys(declared), ...folders(root)]),
129
- ].sort())
174
+ ].sort()) {
130
175
  scopes.push({
131
176
  type,
132
177
  id: id("scope", type, name),
@@ -135,27 +180,32 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
135
180
  canPublish: true,
136
181
  path: `${root}/${name}`,
137
182
  });
183
+ }
184
+ }
138
185
  const problems = [];
139
186
  const assets = [];
140
187
  const knowledge = [];
141
188
  const invalidKnowledge = [];
142
189
  const named = (path, name) => {
143
- if (validAssetName(name))
190
+ if (validAssetName(name)) {
144
191
  return true;
192
+ }
145
193
  problems.push({ path, reason: NAME_RULE });
146
194
  return false;
147
195
  };
148
196
  function packageEntries(root) {
149
197
  const entries = [];
150
198
  for (const entry of snapshot.entries) {
151
- if (!entry.path.startsWith(`${root}/`) || entry.mode === TREE_MODE)
199
+ if (!entry.path.startsWith(`${root}/`) || entry.mode === GIT_MODE.tree) {
152
200
  continue;
153
- if (!isBlob(entry.mode))
154
- throw new Error(`UNSAFE_PACKAGE_ENTRY: ${entry.path.slice(root.length + 1)} is a link`);
201
+ }
202
+ if (!isBlob(entry.mode)) {
203
+ throw new PackageError("UNSAFE_PACKAGE_ENTRY", entry.path.slice(root.length + 1));
204
+ }
155
205
  entries.push({
156
206
  path: entry.path.slice(root.length + 1),
157
- data: blobs.get(entry.hash),
158
- executable: entry.mode === "100755",
207
+ data: blob(entry),
208
+ executable: entry.mode === GIT_MODE.executable,
159
209
  });
160
210
  }
161
211
  return entries;
@@ -180,52 +230,61 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
180
230
  }
181
231
  };
182
232
  for (const { entry, name } of under(`${scope.path}/skills`)) {
183
- if (entry.mode !== TREE_MODE || !named(entry.path, name))
233
+ if (entry.mode !== GIT_MODE.tree || !named(entry.path, name)) {
184
234
  continue;
235
+ }
185
236
  add("skill", name, entry, () => {
186
237
  const entries = validatePackageEntries(packageEntries(entry.path));
187
238
  const metadata = packageMetadata(entries);
188
- if (metadata.name !== name)
189
- throw new Error(`SKILL.md name must match the folder name (${name})`);
239
+ if (metadata.name !== name) {
240
+ throw new CliError(`SKILL.md name must match the folder name (${name})`);
241
+ }
190
242
  return { description: metadata.description, entries };
191
243
  });
192
244
  }
193
245
  for (const { entry, name } of under(`${scope.path}/hooks`)) {
194
- if (entry.mode !== TREE_MODE || !named(entry.path, name))
246
+ if (entry.mode !== GIT_MODE.tree || !named(entry.path, name)) {
195
247
  continue;
248
+ }
196
249
  add("hook", name, entry, () => {
197
250
  const entries = validatePackageEntries(packageEntries(entry.path), undefined, "hook.yaml");
198
251
  const manifest = hookMetadata(entries);
199
- if (manifest.name !== name)
200
- throw new Error(`hook.yaml name must match the folder name (${name})`);
252
+ if (manifest.name !== name) {
253
+ throw new CliError(`hook.yaml name must match the folder name (${name})`);
254
+ }
201
255
  return { description: manifest.description, entries };
202
256
  });
203
257
  }
204
258
  for (const { entry, name: file } of under(`${scope.path}/mcp`)) {
205
- if (!isBlob(entry.mode) || !/\.ya?ml$/.test(file))
259
+ if (!isBlob(entry.mode) || !/\.ya?ml$/.test(file)) {
206
260
  continue;
261
+ }
207
262
  const name = file.replace(/\.ya?ml$/, "");
208
- if (!named(entry.path, name))
263
+ if (!named(entry.path, name)) {
209
264
  continue;
265
+ }
210
266
  add("mcp", name, entry, () => {
211
267
  const definition = mcpDefinitionSchema.parse(parse(text(entry)));
212
268
  return { description: definition.description, entries: [], definition };
213
269
  });
214
270
  }
215
271
  if (scope.type !== "org") {
216
- if (under(`${scope.path}/knowledge`).length)
272
+ if (under(`${scope.path}/knowledge`).length) {
217
273
  problems.push({
218
274
  path: `${scope.path}/knowledge`,
219
275
  reason: "Knowledge is organization-wide; move it to org/knowledge",
220
276
  });
277
+ }
221
278
  continue;
222
279
  }
223
280
  for (const { entry, name: file } of under(`${scope.path}/knowledge`)) {
224
- if (!isBlob(entry.mode) || !file.endsWith(".md"))
281
+ if (!isBlob(entry.mode) || !file.endsWith(".md")) {
225
282
  continue;
283
+ }
226
284
  const name = file.replace(/\.md$/, "");
227
- if (!named(entry.path, name))
285
+ if (!named(entry.path, name)) {
228
286
  continue;
287
+ }
229
288
  try {
230
289
  knowledge.push({
231
290
  id: id("knowledge", name),
@@ -242,12 +301,14 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
242
301
  }
243
302
  }
244
303
  const optional = new Set(config.optional);
245
- for (const path of optional)
246
- if (!assets.some((asset) => asset.path === path || asset.path === `${path}.yaml`))
304
+ for (const path of optional) {
305
+ if (!assets.some((asset) => asset.path === path || asset.path === `${path}.yaml`)) {
247
306
  problems.push({
248
307
  path: CONFIG_FILE,
249
308
  reason: `optional names a missing asset: ${path}`,
250
309
  });
310
+ }
311
+ }
251
312
  const distributions = scopes.map((scope) => ({
252
313
  scope: { type: scope.type, id: scope.id },
253
314
  assets: assets
@@ -272,17 +333,19 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
272
333
  problems,
273
334
  };
274
335
  }
275
- export function validAssetName(name) {
276
- return slug.safeParse(name).success && name.length <= 64;
277
- }
278
336
  /** Names become folder and file names, so check them before touching the disk. */
279
337
  export function assertAssetName(name, fix) {
280
- if (!validAssetName(name))
338
+ if (!validAssetName(name)) {
281
339
  throw new CliError(`${name} can't be used as a name. ${NAME_RULE}.`, fix);
340
+ }
282
341
  }
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}`;
342
+ /** Where a new asset belongs inside a scope: a folder per package, a file per MCP server. */
343
+ export function assetPath(scopePath, kind, name) {
344
+ const folder = `${scopePath}/${assetKinds[kind].folder}`;
345
+ if (kind === "mcp") {
346
+ return `${folder}/${name}.yaml`;
347
+ }
348
+ return `${folder}/${name}`;
286
349
  }
287
350
  const WELCOME = `# BarnDog workspace
288
351
 
@@ -0,0 +1,214 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { stat } from "node:fs/promises";
3
+ import { CliError } from "../../errors.js";
4
+ import { errorCode } from "../../shared/values.js";
5
+ import { GIT_OBJECT_ID } from "../../shared/patterns.js";
6
+ /** CLI policy permits up to 512 MiB of Git plumbing output. */
7
+ const GIT_OUTPUT_LIMIT_MIB = 512;
8
+ /** IEC binary units use 1024 bytes per KiB. */
9
+ const BYTES_PER_KIB = 1024;
10
+ /** CLI policy bounds Git subprocesses to three minutes. */
11
+ const GIT_TIMEOUT_MS = 180_000;
12
+ /** The prefix Git puts on a failure line: `fatal: `, `error: ` or `remote: `. */
13
+ const FAILURE_PREFIX = /^(?:fatal|error|remote):\s*/;
14
+ /**
15
+ * The line of Git's stderr that says what went wrong, without its prefix:
16
+ * `fatal: repository 'x' not found` → `repository 'x' not found`. Falls back to
17
+ * the last line when none has a prefix.
18
+ */
19
+ export function gitReason(stderr) {
20
+ const lines = stderr
21
+ .split("\n")
22
+ .map((line) => line.trim())
23
+ .filter(Boolean);
24
+ const line = lines.find((text) => FAILURE_PREFIX.test(text)) ?? lines.at(-1) ?? "";
25
+ return line.replace(FAILURE_PREFIX, "");
26
+ }
27
+ /** Git can't read the repository with what this machine has set up. */
28
+ export class RepositoryAccessError extends CliError {
29
+ }
30
+ /**
31
+ * Git command failure retaining stderr and exit status for actionable
32
+ * diagnostics.
33
+ */
34
+ export class GitError extends Error {
35
+ stderr;
36
+ exitCode;
37
+ constructor(message, stderr, exitCode) {
38
+ super(message);
39
+ this.stderr = stderr;
40
+ this.exitCode = exitCode;
41
+ this.name = "GitError";
42
+ }
43
+ }
44
+ // A caller running inside a Git hook passes these, and they would redirect every command.
45
+ const inherited = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX"];
46
+ /** Runs system Git with repository hooks and the arbitrary-command transport disabled. */
47
+ export function git(args, runtime, options = {}) {
48
+ const env = { ...runtime.env };
49
+ for (const name of inherited) {
50
+ delete env[name];
51
+ }
52
+ if (!options.allowPrompt) {
53
+ env.GIT_TERMINAL_PROMPT = "0";
54
+ }
55
+ return new Promise((resolve, reject) => {
56
+ const child = execFile("git", [
57
+ ...(options.repo ? ["-C", options.repo] : []),
58
+ "-c",
59
+ "core.hooksPath=/dev/null",
60
+ "-c",
61
+ "protocol.ext.allow=never",
62
+ ...args,
63
+ ], {
64
+ encoding: "buffer",
65
+ cwd: runtime.cwd,
66
+ windowsHide: true,
67
+ env: { ...env, ...options.env },
68
+ maxBuffer: GIT_OUTPUT_LIMIT_MIB * BYTES_PER_KIB * BYTES_PER_KIB,
69
+ timeout: options.timeoutMs ?? GIT_TIMEOUT_MS,
70
+ }, (error, stdout, stderr) => {
71
+ if (!error) {
72
+ return resolve(stdout);
73
+ }
74
+ const code = errorCode(error) ?? null;
75
+ if (code === "ENOENT") {
76
+ return reject(new CliError("Git isn't installed or isn't on your PATH. Git repo workspaces need it."));
77
+ }
78
+ const text = stderr.toString("utf8").trim();
79
+ reject(new GitError(text || error.message, text, code));
80
+ });
81
+ child.stdin?.end(options.input);
82
+ });
83
+ }
84
+ /** Runs Git attached to the terminal, so its own prompts and errors reach the developer. */
85
+ export function gitInTerminal(args, runtime) {
86
+ const env = { ...runtime.env };
87
+ for (const name of inherited) {
88
+ delete env[name];
89
+ }
90
+ return new Promise((resolve, reject) => {
91
+ const child = spawn("git", [
92
+ "-c",
93
+ "core.hooksPath=/dev/null",
94
+ "-c",
95
+ "protocol.ext.allow=never",
96
+ ...args,
97
+ ], { env, cwd: runtime.cwd, stdio: "inherit", windowsHide: true });
98
+ child.once("error", reject);
99
+ child.once("exit", (code) => code === 0
100
+ ? resolve()
101
+ : reject(new GitError(`git exited with ${code}`, "", code)));
102
+ });
103
+ }
104
+ /**
105
+ * Runs Git with the supplied arguments and returns UTF-8 stdout with
106
+ * surrounding whitespace removed.
107
+ */
108
+ export const gitText = async (args, runtime, options) => (await git(args, runtime, options)).toString("utf8").trim();
109
+ /** Lets `--repo` name a clone on disk: the workspace is the remote it came from. */
110
+ export async function cloneOrigin(value, runtime) {
111
+ try {
112
+ if (!(await stat(value.trim())).isDirectory()) {
113
+ return value;
114
+ }
115
+ return await gitText(["config", "--get", "remote.origin.url"], runtime, {
116
+ repo: value.trim(),
117
+ });
118
+ }
119
+ catch {
120
+ return value;
121
+ }
122
+ }
123
+ /** Git's `ext::` and `fd::` remote helpers, which run commands or read file descriptors. */
124
+ const UNSAFE_TRANSPORT = /^(?:ext|fd)::/i;
125
+ /** A URL with a password or token in it: `https://user:secret@host/repo.git`. */
126
+ const URL_WITH_PASSWORD = /^[a-z][\d+.a-z-]*:\/\/[^/:@]*:[^/@]*@/i;
127
+ /** Refuses URLs Git would read as options, helpers, or stored passwords. */
128
+ export function checkRepositoryUrl(value) {
129
+ const url = value.trim();
130
+ if (!url || url.startsWith("-") || UNSAFE_TRANSPORT.test(url)) {
131
+ throw new CliError(`That isn't a Git repository URL: ${url || "(empty)"}`);
132
+ }
133
+ if (URL_WITH_PASSWORD.test(url)) {
134
+ throw new CliError("Remove the password or token from the URL. BarnDog uses your own Git credentials and never stores them.");
135
+ }
136
+ return url;
137
+ }
138
+ /**
139
+ * The lines of `git ls-remote` output, `<object name>\t<ref>`:
140
+ *
141
+ * ```text
142
+ * 3f786850e387550fdab836ed7e6dc881de23001b\trefs/heads/main
143
+ * ```
144
+ */
145
+ export function parseLsRemote(output) {
146
+ return output
147
+ .split("\n")
148
+ .map((line) => line.split("\t"))
149
+ .filter((fields) => fields.length === 2)
150
+ .map(([commit = "", ref = ""]) => ({ commit, ref }));
151
+ }
152
+ /** `ref: refs/heads/main\tHEAD` in `git ls-remote --symref <url> HEAD` output. */
153
+ const SYMREF_LINE = /^ref: refs\/heads\/(\S+)\s+HEAD$/m;
154
+ /** `<object name>\tHEAD` in `git ls-remote` output, in any hash length. */
155
+ const HEAD_LINE = /^([\da-f]+)\s+HEAD$/m;
156
+ /**
157
+ * Reads the default branch from `git ls-remote --symref <url> HEAD`:
158
+ *
159
+ * ```text
160
+ * ref: refs/heads/main\tHEAD
161
+ * 3f786850e387550fdab836ed7e6dc881de23001b\tHEAD
162
+ * ```
163
+ *
164
+ * Empty output means an empty repository (null). Fails for SHA-256 repositories
165
+ * and when either line is missing.
166
+ *
167
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
168
+ */
169
+ export function parseRemoteHead(output, url) {
170
+ if (!output) {
171
+ return null;
172
+ }
173
+ const branch = SYMREF_LINE.exec(output)?.[1];
174
+ const commit = HEAD_LINE.exec(output)?.[1];
175
+ if (commit && !GIT_OBJECT_ID.test(commit)) {
176
+ throw new CliError("This repository uses SHA-256 object names, which BarnDog doesn't support yet.");
177
+ }
178
+ if (!branch || !commit) {
179
+ throw new CliError(`Can't find the default branch of ${url}.`);
180
+ }
181
+ return { branch, commit };
182
+ }
183
+ /** Reads a remote's default branch; null means the repository is empty. */
184
+ export async function remoteHead(url, runtime, allowPrompt = false) {
185
+ let output;
186
+ try {
187
+ output = await gitText(["ls-remote", "--symref", "--", url, "HEAD"], runtime, {
188
+ allowPrompt,
189
+ timeoutMs: 60_000,
190
+ });
191
+ }
192
+ catch (error) {
193
+ if (error instanceof GitError) {
194
+ throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, `git clone ${url}`, { cause: error });
195
+ }
196
+ throw error;
197
+ }
198
+ return parseRemoteHead(output, url);
199
+ }
200
+ const identityHint = 'git config --global user.email "you@example.com"';
201
+ /**
202
+ * Git's stderr when a commit has no author: `*** Please tell me who you are.`
203
+ * followed by the `git config` commands to run.
204
+ *
205
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
206
+ */
207
+ export const UNKNOWN_IDENTITY = /tell me who you are/i;
208
+ /** Git's "who are you" failure is common on new machines and has one clear fix. */
209
+ export function explainIdentity(error) {
210
+ if (error instanceof GitError && UNKNOWN_IDENTITY.test(error.stderr)) {
211
+ throw new CliError("Git doesn't know who you are, so BarnDog can't make a commit.", identityHint, { cause: error });
212
+ }
213
+ throw error;
214
+ }
@@ -0,0 +1,92 @@
1
+ import { assertPackagePaths } from "../../platform.js";
2
+ import { POSIX_MODE } from "../../shared/constants.js";
3
+ import { chmod, lstat, mkdir, readdir, rm, rmdir } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { readTree } from "./tree.js";
6
+ import { setYamlName, splitFrontMatter } from "../../shared/patterns.js";
7
+ import { writeAtomic } from "../../shared/files.js";
8
+ import { barndogPaths } from "../../config/paths.js";
9
+ export function installedPath(runtime, kind, name) {
10
+ const { home } = runtime;
11
+ return join(barndogPaths(home).installed(kind), name);
12
+ }
13
+ /** Points SKILL.md's name at the installed folder name; harnesses require them to match. */
14
+ export function renameSkillEntries(entries, name) {
15
+ return entries.map((entry) => {
16
+ if (entry.path !== "SKILL.md") {
17
+ return entry;
18
+ }
19
+ const parts = splitFrontMatter(entry.data.toString("utf8"));
20
+ if (!parts) {
21
+ return entry;
22
+ }
23
+ const { open, yaml, close, body } = parts;
24
+ return {
25
+ ...entry,
26
+ data: Buffer.from(`${open}${setYamlName(yaml, name)}${close}${body}`),
27
+ };
28
+ });
29
+ }
30
+ /**
31
+ * Reads package files from a source folder and optionally rewrites Skill
32
+ * metadata for an installed alias.
33
+ */
34
+ export async function desiredEntries(source, rename, runtime) {
35
+ const entries = await readTree(source, runtime);
36
+ return rename ? renameSkillEntries(entries, rename) : entries;
37
+ }
38
+ async function removeEmptyDirectories(directory) {
39
+ for (const child of await readdir(directory)) {
40
+ const path = join(directory, child);
41
+ if ((await lstat(path)).isDirectory()) {
42
+ await removeEmptyDirectories(path);
43
+ if (!(await readdir(path)).length) {
44
+ await rmdir(path);
45
+ }
46
+ }
47
+ }
48
+ }
49
+ /**
50
+ * Mirrors entries into an existing folder file by file. The folder itself is never
51
+ * replaced, so harness file watchers observe edits instead of a vanished directory.
52
+ */
53
+ export async function mirrorTree(directory, entries, runtime) {
54
+ assertPackagePaths(entries, runtime.platform);
55
+ await mkdir(directory, { recursive: true, mode: POSIX_MODE.executableFile });
56
+ const wanted = new Map(entries.map((entry) => [entry.path, entry]));
57
+ let current = [];
58
+ try {
59
+ current = await readTree(directory, runtime);
60
+ }
61
+ catch {
62
+ await rm(directory, { recursive: true, force: true });
63
+ await mkdir(directory, {
64
+ recursive: true,
65
+ mode: POSIX_MODE.executableFile,
66
+ });
67
+ }
68
+ for (const existing of current) {
69
+ if (!wanted.has(existing.path)) {
70
+ await rm(join(directory, existing.path), { force: true });
71
+ }
72
+ }
73
+ // Emptied folders must go first: a new file may take one's exact path.
74
+ await removeEmptyDirectories(directory);
75
+ for (const entry of entries) {
76
+ const path = join(directory, entry.path);
77
+ const existing = current.find((item) => item.path === entry.path);
78
+ const mode = entry.executable
79
+ ? POSIX_MODE.executableFile
80
+ : POSIX_MODE.regularFile;
81
+ if (existing?.data.equals(entry.data)) {
82
+ if (existing.executable !== entry.executable) {
83
+ await chmod(path, mode);
84
+ }
85
+ continue;
86
+ }
87
+ await writeAtomic(path, entry.data, {
88
+ mode,
89
+ directoryMode: POSIX_MODE.executableFile,
90
+ });
91
+ }
92
+ }