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,55 @@
1
+ import { hookSchema } from "@barndog-ai/api-contract";
2
+ import { readSettings } from "../../config/settings.js";
3
+ import { selectAsset } from "../server/catalog.js";
4
+ import { repoForOrigin, selectRepoAsset } from "../workspace/assets.js";
5
+ import { runtimeRequirements } from "../native/adapters.js";
6
+ import { hookHarnesses } from "../../harnesses/registry.js";
7
+ import { hookMetadata } from "@barndog-ai/api-contract/package";
8
+ /**
9
+ * What a Hook's current version declares for each coding tool BarnDog manages
10
+ * here, and whether this machine has what each implementation needs to run.
11
+ */
12
+ export async function hookCompatibility(name, origin, runtime) {
13
+ const { home } = runtime;
14
+ const settings = await readSettings(home);
15
+ const managed = (result) => settings
16
+ ? {
17
+ ...result,
18
+ compatibility: result.compatibility.filter((row) => settings.harnesses.includes(row.harness)),
19
+ }
20
+ : result;
21
+ const repo = settings && repoForOrigin(settings, runtime, origin);
22
+ if (repo) {
23
+ return managed(await repoHookCompatibility(selectRepoAsset(await repo.model(), "hook", name, origin), runtime));
24
+ }
25
+ const selected = await selectAsset("hook", name, origin, runtime);
26
+ const asset = hookSchema.parse(selected.asset);
27
+ return managed({
28
+ version: asset.version.number,
29
+ compatibility: await Promise.all(asset.compatibility.map(async (row) => ({
30
+ ...row,
31
+ runtimeIssue: row.implementation
32
+ ? await runtimeRequirements(row.harness, row.implementation.requirements, runtime)
33
+ : "No implementation for this harness",
34
+ }))),
35
+ });
36
+ }
37
+ /** What a Git or local workspace Hook declares for each coding tool, and what this machine lacks. */
38
+ async function repoHookCompatibility(asset, runtime) {
39
+ const manifest = hookMetadata(asset.entries);
40
+ return {
41
+ version: asset.publishedVersion,
42
+ compatibility: await Promise.all(hookHarnesses.map(async (harness) => {
43
+ const implementation = manifest.implementations[harness] ?? null;
44
+ return {
45
+ harness,
46
+ status: implementation?.compatibility ?? "unsupported",
47
+ declared: true,
48
+ implementation,
49
+ runtimeIssue: implementation
50
+ ? await runtimeRequirements(harness, implementation.requirements, runtime)
51
+ : "No implementation for this harness",
52
+ };
53
+ })),
54
+ };
55
+ }
@@ -1,21 +1,43 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
- import { divergentHookTools, hookManifestSchema, } from "@barndog-ai/api-contract";
4
+ import { hookManifestSchema, } from "@barndog-ai/api-contract";
5
5
  import { parse } from "yaml";
6
- import { adapters, harnesses } from "../../harnesses/registry.js";
6
+ import { hookHarnesses } from "../../harnesses/registry.js";
7
+ import { toolNames } from "./adapt.js";
8
+ /**
9
+ * Tools grouped by the script files they run, largest group first. A tool
10
+ * whose commands run no script file of the Hook's has nothing to keep in step,
11
+ * so it's left out.
12
+ */
13
+ function scriptGroups(implementations) {
14
+ const groups = new Map();
15
+ for (const harness of hookHarnesses) {
16
+ const scripts = [...new Set(implementations[harness]?.scripts)].sort();
17
+ if (scripts.length) {
18
+ const key = scripts.join("\0");
19
+ groups.set(key, [...(groups.get(key) ?? []), harness]);
20
+ }
21
+ }
22
+ return [...groups.values()].sort((a, b) => b.length - a.length);
23
+ }
24
+ const inToolOrder = (tools) => hookHarnesses.filter((harness) => tools.includes(harness));
7
25
  /**
8
26
  * A caution for Hooks whose coding tools run different scripts: changing one
9
- * tool's scripts leaves the others as they were. Null when all share one set.
27
+ * tool's scripts leaves the others as they were. Null when they all share one
28
+ * set, or when at most one tool runs scripts at all.
10
29
  */
11
- export function divergenceWarning(implementations) {
12
- const divergent = divergentHookTools(implementations);
13
- if (!divergent.length)
30
+ function divergenceWarning(implementations) {
31
+ const [shared, ...rest] = scriptGroups(implementations);
32
+ if (!shared || !rest.length) {
14
33
  return null;
15
- const names = harnesses
16
- .filter((harness) => divergent.includes(harness))
17
- .map((harness) => adapters[harness].name);
18
- return `${names.slice(0, -1).join(", ")} and ${names.at(-1)} run different scripts in this Hook. When you change it for one, check whether the others need the same change.`;
34
+ }
35
+ if (shared.length === 1) {
36
+ const tools = inToolOrder([shared, ...rest].flat());
37
+ return `${toolNames(tools)} each run their own scripts in this Hook. When you change one, check whether the ${tools.length === 2 ? "other needs" : "others need"} the same change.`;
38
+ }
39
+ const odd = inToolOrder(rest.flat());
40
+ return `${toolNames(odd)} ${odd.length === 1 ? "runs" : "run"} different scripts from ${toolNames(shared)} in this Hook. When you change one set, check whether the other needs the same change.`;
19
41
  }
20
42
  /** The same caution for a Hook folder on disk; null when it has no readable hook.yaml. */
21
43
  export async function folderDivergence(folder) {
@@ -30,9 +52,11 @@ export async function folderDivergence(folder) {
30
52
  /** The Hook working copy a folder sits in, however deep; null outside one. */
31
53
  export function nearestHookFolder(from) {
32
54
  for (let folder = from;; folder = dirname(folder)) {
33
- if (existsSync(join(folder, "hook.yaml")))
55
+ if (existsSync(join(folder, "hook.yaml"))) {
34
56
  return folder;
35
- if (folder === dirname(folder))
57
+ }
58
+ if (folder === dirname(folder)) {
36
59
  return null;
60
+ }
37
61
  }
38
62
  }
@@ -1,94 +1,118 @@
1
+ import { isWindows, localPath, stopProcessTree } from "../../platform.js";
2
+ import { MILLISECONDS_PER_SECOND } from "../../shared/constants.js";
1
3
  import { readFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import { spawn } from "node:child_process";
5
6
  import { parse } from "yaml";
6
7
  import { hookManifestSchema, hookSchema } from "@barndog-ai/api-contract";
7
- import { selectAsset } from "../environment/remote.js";
8
- import { cachedPackage } from "../environment/packages.js";
9
- import { hookCommand, runtimeRequirements } from "../native/adapters.js";
8
+ import { selectAsset } from "../server/catalog.js";
9
+ import { cachedPackage } from "../workspace/packages.js";
10
+ import { runtimeRequirements } from "../native/adapters.js";
11
+ import { hookInvocation } from "../native/hook-shell.js";
10
12
  import { readSettings } from "../../config/settings.js";
11
- import { repoForOrigin, selectRepoAsset } from "../git-workspace/assets.js";
12
- async function hookPackage(name, origin, home) {
13
+ import { repoForOrigin, selectRepoAsset } from "../workspace/assets.js";
14
+ import { CliError } from "../../errors.js";
15
+ import { inputFile } from "../../shared/files.js";
16
+ /** CLI hook test policy caps each input/output stream at one MiB. */
17
+ const HOOK_IO_LIMIT_BYTES = 1048576;
18
+ /** CLI hook test policy defaults to ten seconds. */
19
+ const DEFAULT_HOOK_TIMEOUT_SECONDS = 10;
20
+ /** CLI hook test policy caps execution at ten minutes. */
21
+ const MAX_HOOK_TIMEOUT_SECONDS = 600;
22
+ async function hookPackage(name, origin, runtime) {
23
+ const { home } = runtime;
13
24
  const settings = await readSettings(home);
14
- const repo = settings && repoForOrigin(settings, home, origin);
25
+ const repo = settings && repoForOrigin(settings, runtime, origin);
15
26
  if (repo) {
16
27
  const asset = selectRepoAsset(await repo.model(), "hook", name, origin);
17
- return repo.skillOrHookPackage("hook", asset);
28
+ return repo.packageFolder("hook", asset);
18
29
  }
19
- const selected = await selectAsset("hook", name, origin, home), asset = hookSchema.parse(selected.asset);
20
- return cachedPackage("hook", asset, selected.connection, home);
30
+ const selected = await selectAsset("hook", name, origin, runtime);
31
+ const asset = hookSchema.parse(selected.asset);
32
+ return cachedPackage("hook", asset, selected.connection, runtime);
21
33
  }
22
- export async function testHook(name, origin, options, home = homedir(), cwd = process.cwd()) {
23
- if (process.platform === "win32")
24
- throw new Error("Command Hook testing currently requires a POSIX shell");
25
- const root = await hookPackage(name, origin, home);
34
+ /**
35
+ * Executes the selected Hook command in a POSIX shell with supplied native
36
+ * input, enforcing runtime and output limits.
37
+ */
38
+ export async function testHook(name, origin, options, runtime) {
39
+ const { cwd } = runtime;
40
+ const root = await hookPackage(name, origin, runtime);
26
41
  const manifest = hookManifestSchema.parse(parse(await readFile(join(root, "hook.yaml"), "utf8")));
27
42
  const implementation = manifest.implementations[options.harness];
28
- if (!implementation)
29
- throw new Error(`No ${options.harness} implementation`);
30
- const unmet = await runtimeRequirements(options.harness, implementation.requirements);
31
- if (unmet)
32
- throw new Error(unmet);
43
+ if (!implementation) {
44
+ throw new CliError(`${name} has no ${options.harness} implementation.`, `barndog hooks test ${name} --harness <claude|codex|cursor>`);
45
+ }
46
+ const unmet = await runtimeRequirements(options.harness, implementation.requirements, runtime);
47
+ if (unmet) {
48
+ throw new CliError(unmet);
49
+ }
33
50
  const event = options.event ??
34
51
  (Object.keys(implementation.events).length === 1
35
52
  ? Object.keys(implementation.events)[0]
36
53
  : undefined);
37
- if (!event || !implementation.events[event])
38
- throw new Error(`Choose --event from: ${Object.keys(implementation.events).join(", ")}`);
54
+ if (!event || !implementation.events[event]) {
55
+ throw new CliError(`Choose an event with --event: ${Object.keys(implementation.events).join(", ")}.`);
56
+ }
39
57
  const handlers = implementation.events[event].flatMap((h) => "hooks" in h ? h.hooks : [h]);
40
- if (handlers.length > 1 && options.handler === undefined)
41
- throw new Error("Choose --handler <number> to explicitly select a command");
58
+ if (handlers.length > 1 && options.handler === undefined) {
59
+ throw new CliError("This event runs several commands. Choose one with --handler <number>.");
60
+ }
42
61
  const handler = handlers[(options.handler ?? 1) - 1];
43
- if (!handler)
44
- throw new Error("Unknown Hook handler");
45
- const input = await readFile(options.input);
46
- if (input.length > 1048576)
47
- throw new Error("Hook input exceeds 1 MiB");
48
- JSON.parse(input.toString("utf8"));
49
- const timeout = options.timeout ?? handler.timeout ?? 10;
50
- if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 600)
51
- throw new Error("Hook test timeout must be between 0 and 600 seconds");
52
- const child = spawn("/bin/sh", ["-c", hookCommand(root, handler.command, options.harness)], {
62
+ if (!handler) {
63
+ throw new CliError(`This event has no command ${options.handler}. Choose 1 to ${handlers.length}.`);
64
+ }
65
+ const inputPath = localPath(options.input, runtime);
66
+ const input = await inputFile(inputPath);
67
+ if (input.length > HOOK_IO_LIMIT_BYTES) {
68
+ throw new CliError("The --input file is over 1 MiB.");
69
+ }
70
+ try {
71
+ JSON.parse(input.toString("utf8"));
72
+ }
73
+ catch (error) {
74
+ throw new CliError(`${inputPath} isn't valid JSON. --input takes the JSON event the tool would send the Hook.`, undefined, { cause: error });
75
+ }
76
+ const timeout = options.timeout ?? handler.timeout ?? DEFAULT_HOOK_TIMEOUT_SECONDS;
77
+ if (!Number.isFinite(timeout) ||
78
+ timeout <= 0 ||
79
+ timeout > MAX_HOOK_TIMEOUT_SECONDS) {
80
+ throw new CliError("--timeout must be more than 0 and at most 600 seconds.");
81
+ }
82
+ const shell = await hookInvocation(root, handler.command, options.harness, runtime);
83
+ const child = spawn(shell.command, shell.args, {
53
84
  cwd,
54
85
  stdio: ["pipe", "pipe", "pipe"],
55
- detached: true,
86
+ env: { ...runtime.env },
87
+ detached: !isWindows(runtime.platform),
88
+ windowsHide: true,
56
89
  });
57
- let stdout = "", stderr = "", length = 0, timedOut = false;
58
- const stop = () => {
59
- if (child.pid)
60
- try {
61
- process.kill(-child.pid, "SIGKILL");
62
- }
63
- catch {
64
- /* exited */
65
- }
66
- };
90
+ let timedOut = false;
91
+ let overLimit = false;
92
+ const stop = () => stopProcessTree(child, runtime);
67
93
  const timer = setTimeout(() => {
68
94
  timedOut = true;
69
95
  stop();
70
- }, timeout * 1000);
71
- for (const [stream, append] of [
72
- [
73
- child.stdout,
74
- (text) => {
75
- stdout += text;
76
- },
77
- ],
78
- [
79
- child.stderr,
80
- (text) => {
81
- stderr += text;
82
- },
83
- ],
84
- ])
96
+ }, timeout * MILLISECONDS_PER_SECOND);
97
+ // Bytes are kept and decoded once at the end, so a character split across
98
+ // chunks survives; each stream has its own limit.
99
+ const collect = (stream) => {
100
+ const chunks = [];
101
+ let length = 0;
85
102
  stream.on("data", (chunk) => {
86
103
  length += chunk.length;
87
- if (length > 1048576)
104
+ if (length > HOOK_IO_LIMIT_BYTES) {
105
+ overLimit = true;
88
106
  stop();
89
- else
90
- append(chunk.toString());
107
+ }
108
+ else {
109
+ chunks.push(chunk);
110
+ }
91
111
  });
112
+ return () => Buffer.concat(chunks).toString("utf8");
113
+ };
114
+ const stdout = collect(child.stdout);
115
+ const stderr = collect(child.stderr);
92
116
  child.stdin.on("error", () => undefined);
93
117
  child.stdin.end(input);
94
118
  try {
@@ -96,15 +120,16 @@ export async function testHook(name, origin, options, home = homedir(), cwd = pr
96
120
  child.once("error", reject);
97
121
  child.once("close", (code) => resolve(code ?? 1));
98
122
  });
99
- if (length > 1048576)
100
- throw new Error("Hook test output exceeds 1 MiB");
123
+ if (overLimit) {
124
+ throw new CliError("The Hook printed more than 1 MiB to stdout or stderr.");
125
+ }
101
126
  return {
102
127
  harness: options.harness,
103
128
  event,
104
129
  exitCode,
105
130
  timedOut,
106
- stdout,
107
- stderr,
131
+ stdout: stdout(),
132
+ stderr: stderr(),
108
133
  };
109
134
  }
110
135
  finally {
@@ -0,0 +1 @@
1
+ export {};
@@ -1,11 +1,17 @@
1
+ import { GIT_MODE, isBlob } from "../workspace/snapshot.js";
1
2
  import { hookImplementationSchema, } from "@barndog-ai/api-contract";
2
3
  import { hookMetadata, packageMetadata, validatePackageEntries, } from "@barndog-ai/api-contract/package";
3
4
  import { parse as parseJsonc } from "jsonc-parser";
4
5
  import { parse as parseToml } from "smol-toml";
5
6
  import { stringify } from "yaml";
6
- import { friendlyMessage } from "../../errors.js";
7
- import { adapters, harnesses } from "../../harnesses/registry.js";
8
- import { isBlob } from "../git-workspace/snapshot.js";
7
+ import { CliError, friendlyMessage } from "../../errors.js";
8
+ import { adapters, hookHarnesses, hookSettingsOwner, } from "../../harnesses/registry.js";
9
+ import { defined } from "../../shared/lookup.js";
10
+ import { asRecord, isRecord } from "../../shared/values.js";
11
+ /**
12
+ * What imported Hook commands use for the installed package folder; BarnDog
13
+ * binds it when installing.
14
+ */
9
15
  export const ROOT_TOKEN = "${BARNDOG_HOOK_ROOT}";
10
16
  /** A link to a folder or file narrows everything to it; the rest of the repo is ignored. */
11
17
  const inScope = (remote, path) => !remote.path || path === remote.path || path.startsWith(`${remote.path}/`);
@@ -18,25 +24,35 @@ export function folderEntries(remote, root) {
18
24
  .filter((entry) => entry.path.startsWith(prefix) && isBlob(entry.mode))
19
25
  .map((entry) => ({
20
26
  path: entry.path.slice(prefix.length),
21
- data: remote.blobs.get(entry.hash),
22
- executable: entry.mode === "100755",
27
+ data: blobOf(remote, entry),
28
+ executable: entry.mode === GIT_MODE.executable,
23
29
  }));
24
30
  }
31
+ /** Every blob in a fetched snapshot was read with it. */
32
+ const blobOf = (remote, entry) => defined(remote.blobs.get(entry.hash), `Git object ${entry.hash} wasn't read`);
25
33
  const hasLink = (remote, root) => remote.snapshot.entries.some((entry) => entry.path.startsWith(root ? `${root}/` : "") &&
26
- (entry.mode === "120000" || entry.mode === "160000"));
34
+ (entry.mode === GIT_MODE.symlink || entry.mode === GIT_MODE.submodule));
27
35
  const parentOf = (path) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
36
+ /**
37
+ * Every valid Skill folder (one holding `SKILL.md`) in the linked part of a
38
+ * fetched repository. Folders with symbolic links or invalid packages are
39
+ * skipped with a reason.
40
+ */
28
41
  export function discoverSkills(remote) {
29
42
  const skills = [];
30
43
  const skipped = [];
31
44
  for (const entry of remote.snapshot.entries) {
32
- if (!/(^|\/)SKILL\.md$/.test(entry.path) || !isBlob(entry.mode))
45
+ if (fileName(entry.path) !== "SKILL.md" || !isBlob(entry.mode)) {
33
46
  continue;
47
+ }
34
48
  const root = parentOf(entry.path);
35
- if (!inScope(remote, root) && !inScope(remote, entry.path))
49
+ if (!inScope(remote, root) && !inScope(remote, entry.path)) {
36
50
  continue;
51
+ }
37
52
  try {
38
- if (hasLink(remote, root))
39
- throw new Error("It contains a symbolic link");
53
+ if (hasLink(remote, root)) {
54
+ throw new CliError("It contains a symbolic link");
55
+ }
40
56
  const entries = validatePackageEntries(folderEntries(remote, root));
41
57
  const metadata = packageMetadata(entries);
42
58
  skills.push({ ...metadata, root, entries });
@@ -47,72 +63,125 @@ export function discoverSkills(remote) {
47
63
  }
48
64
  return { skills, skipped };
49
65
  }
50
- const scriptLike = /\.(sh|bash|zsh|py|js|mjs|cjs|ts|rb|pl)$/;
51
- const interpreter = (script) => /\.py$/.test(script)
52
- ? "python3 "
53
- : /\.(m|c)?js$/.test(script)
54
- ? "node "
55
- : /\.rb$/.test(script)
56
- ? "ruby "
57
- : /\.pl$/.test(script)
58
- ? "perl "
59
- : "";
66
+ /** The last segment of a repository path: `hooks/lint/hook.yaml` → `hook.yaml`. */
67
+ const fileName = (path) => path.slice(path.lastIndexOf("/") + 1);
68
+ /** `.py` from `hooks/check.py`; "" when the file name has no extension. */
69
+ const extensionOf = (path) => {
70
+ const name = fileName(path);
71
+ const dot = name.lastIndexOf(".");
72
+ return dot > 0 ? name.slice(dot) : "";
73
+ };
74
+ /** What a script without its executable bit is run with, by extension. */
75
+ const interpreters = {
76
+ ".py": "python3 ",
77
+ ".js": "node ",
78
+ ".mjs": "node ",
79
+ ".cjs": "node ",
80
+ ".rb": "ruby ",
81
+ ".pl": "perl ",
82
+ };
83
+ const scriptExtensions = new Set([
84
+ ".sh",
85
+ ".bash",
86
+ ".zsh",
87
+ ".ts",
88
+ ...Object.keys(interpreters),
89
+ ]);
90
+ /**
91
+ * Whether a repository file looks like a hook script: `hooks/check.sh`, `lint.mjs`.
92
+ *
93
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
94
+ */
95
+ export const scriptLike = (path) => scriptExtensions.has(extensionOf(path));
96
+ /**
97
+ * A command that runs `script` from the package: `@@check.sh` when it is
98
+ * executable, else through its interpreter, `python3 @@check.py`.
99
+ */
60
100
  export function plainCommand(script, executable) {
61
- return `${executable ? "" : interpreter(script)}@@${script}`;
101
+ const interpreter = executable
102
+ ? ""
103
+ : (interpreters[extensionOf(script)] ?? "");
104
+ return `${interpreter}@@${script}`;
62
105
  }
63
106
  function nativeHooks(entry, text) {
64
107
  const parsed = entry.path.endsWith(".toml")
65
108
  ? parseToml(text)
66
109
  : parseJsonc(text);
67
- const hooks = parsed?.hooks;
68
110
  const found = [];
69
- for (const [event, groups] of Object.entries(hooks ?? {})) {
70
- if (!Array.isArray(groups))
111
+ for (const [event, groups] of Object.entries(asRecord(asRecord(parsed).hooks))) {
112
+ if (!Array.isArray(groups)) {
71
113
  continue;
72
- for (const group of groups) {
114
+ }
115
+ for (const group of groups.filter(isRecord)) {
73
116
  const matcher = typeof group.matcher === "string" && group.matcher
74
117
  ? group.matcher
75
118
  : undefined;
76
119
  const handlers = Array.isArray(group.hooks)
77
- ? group.hooks
120
+ ? group.hooks.filter(isRecord)
78
121
  : [group];
79
- for (const handler of handlers)
122
+ for (const handler of handlers) {
80
123
  if (typeof handler.command === "string" &&
81
- (handler.type ?? "command") === "command")
124
+ (handler.type ?? "command") === "command") {
82
125
  found.push({ event, matcher, command: handler.command });
126
+ }
127
+ }
83
128
  }
84
129
  }
85
130
  return found;
86
131
  }
87
- const settingsOwner = (path) => harnesses.find((harness) => adapters[harness].hooks.settings.some((pattern) => pattern.test(path)));
88
- const pathNoise = /^(\$\{?[A-Z_]+\}?\/|\$\(git rev-parse --show-toplevel\)\/|~\/|\.\/)+/;
132
+ /**
133
+ * Leading folders a native command uses to find its repository, which don't
134
+ * exist in the package: `$CLAUDE_PROJECT_DIR/`, `${CLAUDE_PLUGIN_ROOT}/`,
135
+ * `$(git rev-parse --show-toplevel)/`, `~/` and `./`, in any combination.
136
+ */
137
+ const ROOT_PREFIXES = /^(?:\$\{?[A-Z_]+\}?\/|\$\(git rev-parse --show-toplevel\)\/|~\/|\.\/)+/;
138
+ /** Surrounding quotes on one word of a command: `"./run.sh"` → `./run.sh`. */
139
+ const QUOTES = /^["']|["']$/g;
140
+ /**
141
+ * The repository-relative path one word of a native hook command may name:
142
+ * `"$CLAUDE_PROJECT_DIR/.claude/hooks/check.sh"` → `.claude/hooks/check.sh`.
143
+ *
144
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
145
+ */
146
+ export function scriptPath(token) {
147
+ return token.replace(QUOTES, "").replace(ROOT_PREFIXES, "");
148
+ }
89
149
  /** Points a native command at the repo's script, or says why it can't be carried over. */
90
150
  function rewriteCommand(command, blobs, scope) {
91
151
  for (const token of command.split(/\s+/)) {
92
- const clean = token.replace(/^["']|["']$/g, "");
93
- const relative = clean.replace(pathNoise, "");
94
- if (!relative || !relative.includes("."))
152
+ const relative = scriptPath(token);
153
+ if (!relative || !relative.includes(".")) {
95
154
  continue;
155
+ }
96
156
  const script = blobs.find((path) => path === relative) ??
97
157
  blobs.find((path) => scope && path === `${scope}/${relative}`) ??
98
158
  blobs.find((path) => path.endsWith(`/${relative}`));
99
- if (script)
100
- return { script, command: command.replace(token, `@@${script}`) };
159
+ if (script) {
160
+ return { script, command: command.replace(token, () => `@@${script}`) };
161
+ }
101
162
  }
102
163
  return null;
103
164
  }
165
+ /**
166
+ * The Hook packages in the linked part of a fetched repository. When there are
167
+ * none, builds one draft from the harness settings files it finds (named
168
+ * `fallbackName`), so a repository of plain hook scripts can still be imported.
169
+ */
104
170
  export function discoverHooks(remote, fallbackName) {
105
171
  const packages = [];
106
172
  const skipped = [];
107
173
  for (const entry of remote.snapshot.entries) {
108
- if (!/(^|\/)hook\.yaml$/.test(entry.path) || !isBlob(entry.mode))
174
+ if (fileName(entry.path) !== "hook.yaml" || !isBlob(entry.mode)) {
109
175
  continue;
176
+ }
110
177
  const root = parentOf(entry.path);
111
- if (!inScope(remote, root) && !inScope(remote, entry.path))
178
+ if (!inScope(remote, root) && !inScope(remote, entry.path)) {
112
179
  continue;
180
+ }
113
181
  try {
114
- if (hasLink(remote, root))
115
- throw new Error("It contains a symbolic link");
182
+ if (hasLink(remote, root)) {
183
+ throw new CliError("It contains a symbolic link");
184
+ }
116
185
  const entries = validatePackageEntries(folderEntries(remote, root), undefined, "hook.yaml");
117
186
  const manifest = hookMetadata(entries);
118
187
  packages.push({
@@ -127,35 +196,39 @@ export function discoverHooks(remote, fallbackName) {
127
196
  skipped.push({ path: entry.path, reason: friendlyMessage(error) });
128
197
  }
129
198
  }
130
- if (packages.length)
199
+ if (packages.length) {
131
200
  return { candidates: packages, skipped };
201
+ }
132
202
  const blobEntries = remote.snapshot.entries.filter((e) => isBlob(e.mode) && inScope(remote, e.path));
133
203
  const blobPaths = blobEntries.map((e) => e.path);
134
204
  const implementations = {};
135
205
  for (const entry of blobEntries) {
136
- const harness = settingsOwner(entry.path);
137
- if (!harness)
206
+ const harness = hookSettingsOwner(entry.path);
207
+ if (!harness) {
138
208
  continue;
209
+ }
139
210
  let hooks = [];
140
211
  try {
141
- hooks = nativeHooks(entry, remote.blobs.get(entry.hash).toString("utf8"));
212
+ hooks = nativeHooks(entry, blobOf(remote, entry).toString("utf8"));
142
213
  }
143
214
  catch (error) {
144
215
  skipped.push({ path: entry.path, reason: friendlyMessage(error) });
145
216
  }
146
217
  for (const hook of hooks) {
147
218
  const rewritten = rewriteCommand(hook.command, blobPaths, remote.path);
148
- if (!rewritten)
219
+ if (!rewritten) {
149
220
  skipped.push({
150
221
  path: entry.path,
151
222
  reason: `${hook.event}: "${hook.command}" doesn't run a script in this ${remote.path ? "folder" : "repo"}`,
152
223
  });
153
- else
224
+ }
225
+ else {
154
226
  (implementations[harness] ??= []).push({
155
227
  event: hook.event,
156
228
  matcher: hook.matcher,
157
229
  ...rewritten,
158
230
  });
231
+ }
159
232
  }
160
233
  }
161
234
  const scripts = [
@@ -164,12 +237,13 @@ export function discoverHooks(remote, fallbackName) {
164
237
  .flat()
165
238
  .map((d) => d.script),
166
239
  ...blobEntries
167
- .filter((e) => scriptLike.test(e.path) || e.mode === "100755")
240
+ .filter((e) => scriptLike(e.path) || e.mode === GIT_MODE.executable)
168
241
  .map((e) => e.path),
169
242
  ]),
170
243
  ];
171
- if (!scripts.length)
244
+ if (!scripts.length) {
172
245
  return { candidates: [], skipped };
246
+ }
173
247
  return {
174
248
  candidates: [
175
249
  {
@@ -187,10 +261,12 @@ const commonFolder = (paths) => {
187
261
  const parts = paths.map((path) => path.split("/").slice(0, -1));
188
262
  const first = parts[0] ?? [];
189
263
  let length = first.length;
190
- for (const other of parts)
264
+ for (const other of parts) {
191
265
  while (length &&
192
- other.slice(0, length).join("/") !== first.slice(0, length).join("/"))
266
+ other.slice(0, length).join("/") !== first.slice(0, length).join("/")) {
193
267
  length--;
268
+ }
269
+ }
194
270
  return first.slice(0, length).join("/");
195
271
  };
196
272
  /** Turns the choices made in the picker into a Hook package in BarnDog's format. */
@@ -207,22 +283,19 @@ export function buildHookPackage(remote, input) {
207
283
  folders.some((folder) => folder && entry.path.startsWith(`${folder}/`))))
208
284
  .map((entry) => ({
209
285
  path: relative(entry.path),
210
- data: remote.blobs.get(entry.hash),
211
- executable: entry.mode === "100755" || scripts.includes(entry.path),
286
+ data: blobOf(remote, entry),
287
+ executable: entry.mode === GIT_MODE.executable || scripts.includes(entry.path),
212
288
  }));
213
289
  const implementations = {};
214
- for (const [harness, events] of Object.entries(input.implementations)) {
215
- if (!events.length)
290
+ for (const harness of hookHarnesses) {
291
+ const events = input.implementations[harness] ?? [];
292
+ if (!events.length) {
216
293
  continue;
294
+ }
217
295
  const byEvent = {};
218
296
  for (const draft of events) {
219
- const command = draft.command.replace(new RegExp(`@@${draft.script.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), `${ROOT_TOKEN}/${relative(draft.script)}`);
220
- (byEvent[draft.event] ??= []).push(harness === "cursor"
221
- ? { command, ...(draft.matcher ? { matcher: draft.matcher } : {}) }
222
- : {
223
- ...(draft.matcher ? { matcher: draft.matcher } : {}),
224
- hooks: [{ type: "command", command }],
225
- });
297
+ const command = draft.command.replace(`@@${draft.script}`, () => `${ROOT_TOKEN}/${relative(draft.script)}`);
298
+ (byEvent[draft.event] ??= []).push(adapters[harness].hooks.entry(command, draft.matcher));
226
299
  }
227
300
  implementations[harness] = {
228
301
  compatibility: "supported",