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
@@ -1,33 +1,65 @@
1
+ import { localPath } from "../../platform.js";
1
2
  import { existsSync } from "node:fs";
2
3
  import { rm, rmdir, stat } from "node:fs/promises";
3
- import { homedir } from "node:os";
4
- import { dirname, join, parse, resolve } from "node:path";
4
+ import { dirname, join, parse } from "node:path";
5
5
  import { CliError } from "../../errors.js";
6
- import { folderSnapshot, isBlob } from "../git-workspace/snapshot.js";
6
+ import { folderSnapshot, isBlob } from "../workspace/snapshot.js";
7
+ /**
8
+ * `~`, `~/…` or `~\…` at the start of a path, which a POSIX shell would
9
+ * expand to the home folder; Windows shells pass it to BarnDog unexpanded.
10
+ */
11
+ const HOME_PREFIX = /^~(?=[\\/]|$)/;
12
+ /**
13
+ * `~/skills` → `/Users/me/skills`; other paths are unchanged.
14
+ *
15
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
16
+ */
17
+ export const expandHome = (path, runtime) => {
18
+ const { home } = runtime;
19
+ return path.replace(HOME_PREFIX, () => home);
20
+ };
21
+ /**
22
+ * Text that can only mean a folder on this machine, never a repository URL:
23
+ * `/abs`, `.`, `..`, `./x`, `../x`, `~` or `~/x`, and on Windows also `\x`,
24
+ * `C:\x` or `C:/x`, `.\x`, `..\x` and `~\x`.
25
+ */
26
+ const LOCAL_PATH = /^(?:[\\/]|[a-z]:|\.{1,2}(?:[\\/]|$)|~(?:[\\/]|$))/i;
27
+ /**
28
+ * Recognizes path-like import inputs after trimming whitespace; does not check
29
+ * filesystem existence.
30
+ *
31
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
32
+ */
33
+ export const looksLocal = (source) => LOCAL_PATH.test(source.trim());
7
34
  /** The plain folder a source points at; Git repos return null and are fetched instead. */
8
- export async function plainFolder(source) {
35
+ export async function plainFolder(source, runtime) {
9
36
  const value = source.trim();
10
- const path = resolve(value.replace(/^~(?=\/|$)/, homedir()));
37
+ const path = localPath(expandHome(value, runtime), runtime);
11
38
  const directory = await stat(path).then((info) => info.isDirectory(), () => false);
12
- if (!directory)
39
+ if (!directory) {
13
40
  return null;
41
+ }
14
42
  const isRepo = existsSync(join(path, ".git")) ||
15
43
  (existsSync(join(path, "HEAD")) && existsSync(join(path, "objects")));
16
44
  return isRepo ? null : path;
17
45
  }
18
46
  /** Git can't help with a path that isn't there, so say so instead of suggesting a clone. */
19
- export function assertSourceExists(source) {
47
+ export function assertSourceExists(source, runtime) {
20
48
  const value = source.trim();
21
- if (!/^(\/|\.{1,2}(\/|$)|~(\/|$))/.test(value))
49
+ if (!looksLocal(value)) {
22
50
  return;
23
- if (!existsSync(resolve(value.replace(/^~(?=\/|$)/, homedir()))))
51
+ }
52
+ if (!existsSync(localPath(expandHome(value, runtime), runtime))) {
24
53
  throw new CliError(`Can't find ${value}.`);
54
+ }
25
55
  }
26
56
  /** Presents a folder the way a fetched repo looks, so discovery treats both alike. */
27
- export async function readFolder(path) {
28
- if (path === homedir() || path === parse(path).root)
57
+ export async function readFolder(path, runtime) {
58
+ const { home } = runtime;
59
+ if (path === home || path === parse(path).root) {
29
60
  throw new CliError(`${path} is too broad to search. Point at the folder holding the Skill.`);
30
- const snapshot = await folderSnapshot(path);
61
+ }
62
+ const snapshot = await folderSnapshot(path, runtime);
31
63
  const blobs = await snapshot.readBlobs(snapshot.entries
32
64
  .filter((entry) => isBlob(entry.mode))
33
65
  .map((entry) => entry.hash));
@@ -42,11 +74,13 @@ export async function removeImported(root, entries) {
42
74
  for (const entry of entries) {
43
75
  const file = join(root, entry.path);
44
76
  await rm(file, { force: true });
45
- for (let dir = dirname(file); dir !== root; dir = dirname(dir))
77
+ for (let dir = dirname(file); dir !== root; dir = dirname(dir)) {
46
78
  folders.add(dir);
79
+ }
47
80
  }
48
81
  const deepestFirst = [...folders].sort((a, b) => b.length - a.length);
49
- for (const folder of deepestFirst)
82
+ for (const folder of deepestFirst) {
50
83
  await rmdir(folder).catch(() => { });
84
+ }
51
85
  return !existsSync(root);
52
86
  }
@@ -1,147 +1,124 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { dirname, join, resolve } from "node:path";
4
- import { packageFingerprint, writePackage, } from "@barndog-ai/api-contract/package";
5
- import { diffEntries, readDirectory, } from "@barndog-ai/api-contract/collaboration";
1
+ import { writePackage, readDirectory } from "../workspace/directory.js";
2
+ import { mkdir, readdir, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { packageFingerprint, } from "@barndog-ai/api-contract/package";
5
+ import { diffEntries, } from "@barndog-ai/api-contract/collaboration";
6
6
  import { selectionState, withSelection } from "../../config/environment.js";
7
- import { readSettings, saveSettings, settingsPath, SetupRequiredError, upgradeSettings, } from "../../config/settings.js";
8
- import { CliError, friendlyMessage } from "../../errors.js";
9
- import { renameSkillEntries } from "../environment/installed.js";
10
- import { assertAssetName, assetFolder, validAssetName, } from "../git-workspace/format.js";
11
- import { withLocalSubscription } from "../git-workspace/overlay.js";
12
- import { localWorkspace } from "../git-workspace/setup.js";
13
- import { localRepoSource } from "../git-workspace/source.js";
14
- import { discoverSkills, folderEntries, } from "./discover.js";
15
- import { readFolder } from "./folder.js";
7
+ import { readSettings, saveSettings, SetupRequiredError, } from "../../config/settings.js";
8
+ import { CliError } from "../../errors.js";
9
+ import { errorCode } from "../../shared/values.js";
10
+ import { renameSkillEntries } from "../workspace/installed.js";
11
+ import { assertAssetName, assetPath } from "../workspace/format.js";
12
+ import { withLocalSubscription } from "../workspace/overlay.js";
13
+ import { localWorkspace } from "../workspace/setup.js";
14
+ import { localRepoSource } from "../workspace/repo-source.js";
15
+ import { folderEntries } from "./discover.js";
16
16
  import { fetchRemote } from "./remote.js";
17
- const SOURCES_FILE = ".barndog-sources.json";
17
+ import { assetKinds } from "../asset-kinds/index.js";
18
+ import { packageKindList } from "../../config/selection.js";
19
+ import { defined } from "../../shared/lookup.js";
20
+ import { z } from "zod";
21
+ import { localWorkspaceFiles } from "../../config/paths.js";
22
+ import { readJsonIfExists, writeAtomic } from "../../shared/files.js";
23
+ import { POSIX_MODE } from "../../shared/constants.js";
24
+ const importRecordSchema = z.looseObject({
25
+ kind: z.enum(packageKindList),
26
+ name: z.string(),
27
+ mode: z.enum(["manual", "auto"]),
28
+ url: z.string(),
29
+ ref: z.string().nullable(),
30
+ root: z.string(),
31
+ commit: z.string(),
32
+ /** Set for Hooks built by the picker: only these files come from the repo. */
33
+ files: z.array(z.string()).optional(),
34
+ fingerprint: z.string(),
35
+ });
36
+ const sourcesSchema = z.looseObject({
37
+ checkedAt: z.string().optional(),
38
+ imports: z.array(importRecordSchema),
39
+ });
18
40
  async function readSources(folder) {
19
- try {
20
- return JSON.parse(await readFile(join(folder, SOURCES_FILE), "utf8"));
21
- }
22
- catch (error) {
23
- if (error.code === "ENOENT")
24
- return { imports: [] };
25
- throw error;
41
+ return ((await readJsonIfExists(localWorkspaceFiles(folder).sources, sourcesSchema)) ?? { imports: [] });
42
+ }
43
+ const writeSources = (folder, sources) => writeAtomic(localWorkspaceFiles(folder).sources, JSON.stringify(sources, null, 2) + "\n", { mode: POSIX_MODE.regularFile });
44
+ /** Stops following a repository for an asset whose local folder is gone. */
45
+ export async function forgetImport(folder, kind, name) {
46
+ const sources = await readSources(folder);
47
+ const kept = sources.imports.filter((entry) => entry.kind !== kind || entry.name !== name);
48
+ if (kept.length !== sources.imports.length) {
49
+ await writeSources(folder, { ...sources, imports: kept });
26
50
  }
27
51
  }
28
- const writeSources = (folder, sources) => writeFile(join(folder, SOURCES_FILE), JSON.stringify(sources, null, 2) + "\n");
29
52
  /** The repository an asset still follows, or null for a fork or one made here. */
30
- export async function importedFrom(kind, name, home = homedir()) {
53
+ export async function importedFrom(kind, name, runtime) {
54
+ const { home } = runtime;
31
55
  const settings = await readSettings(home);
32
- if (settings?.version !== 2 || !settings.localWorkspace)
56
+ if (!settings || !settings.localWorkspace) {
33
57
  return null;
58
+ }
34
59
  const { imports } = await readSources(settings.localWorkspace.path);
35
60
  return imports.find((e) => e.kind === kind && e.name === name) ?? null;
36
61
  }
37
62
  /** Adding always lands in the local folder, creating it on first use. */
38
- export async function ensureLocalWorkspace(home) {
63
+ export async function ensureLocalWorkspace(runtime) {
64
+ const { home } = runtime;
39
65
  const settings = await readSettings(home);
40
- if (!settings)
66
+ if (!settings) {
41
67
  throw new SetupRequiredError();
42
- if (settings.version === 2 && settings.localWorkspace)
68
+ }
69
+ if (settings.localWorkspace) {
43
70
  return settings.localWorkspace;
44
- const workspace = await localWorkspace(home);
45
- const kept = await localRepoSource(workspace, home).model();
71
+ }
72
+ const workspace = await localWorkspace(runtime);
73
+ const kept = await localRepoSource(workspace, runtime).model();
46
74
  const next = {
47
- ...upgradeSettings(settings),
75
+ ...settings,
48
76
  localWorkspace: workspace,
49
77
  };
50
78
  await saveSettings(withSelection(next, withLocalSubscription(selectionState(next), kept)), home);
51
79
  return workspace;
52
80
  }
53
- /**
54
- * Brings Skills linked from outside folders into the workspace, so every asset on
55
- * this machine lives in one place. The originals are left alone.
56
- */
57
- export async function adoptLinkedFolders(home) {
58
- const settings = await readSettings(home);
59
- if (!settings)
60
- return [];
61
- const linked = upgradeSettings(settings).skills.filter((skill) => skill.kind === "local");
62
- if (!linked.length)
63
- return [];
64
- const notices = [];
65
- const adopted = [];
66
- for (const entry of linked) {
67
- const source = resolve(dirname(settingsPath(home)), entry.source);
68
- try {
69
- const remote = await readFolder(source);
70
- const { skills, skipped } = discoverSkills(remote);
71
- const skill = skills.find((s) => s.root === "");
72
- if (!skill)
73
- throw new CliError(skipped[0]?.reason ?? "It has no valid SKILL.md.");
74
- await saveImported({
75
- kind: "skill",
76
- name: skill.name,
77
- entries: skill.entries,
78
- mode: "fork",
79
- remote,
80
- root: "",
81
- }, home);
82
- adopted.push({ id: entry.id, name: skill.name, enabled: entry.enabled });
83
- notices.push(`Copied ${skill.name} into your workspace. The original folder wasn't changed.`);
84
- }
85
- catch (error) {
86
- notices.push(`Couldn't copy ${source} into your workspace, so it stays linked for now: ${friendlyMessage(error)}`);
87
- }
88
- }
89
- if (!adopted.length)
90
- return notices;
91
- const current = upgradeSettings((await readSettings(home)));
92
- const ids = new Set(adopted.map((skill) => skill.id));
93
- const skills = current.skills.filter((skill) => !ids.has(skill.id));
94
- const off = new Set(adopted.filter((s) => !s.enabled).map((s) => s.name));
95
- const selection = selectionState(current);
96
- const assets = off.size
97
- ? (await localRepoSource(current.localWorkspace, home).model()).assets
98
- : [];
99
- await saveSettings(off.size
100
- ? {
101
- ...current,
102
- skills,
103
- environment: {
104
- ...selection,
105
- disabledAssetIds: [
106
- ...selection.disabledAssetIds,
107
- ...assets
108
- .filter((a) => a.kind === "skill" && off.has(a.name))
109
- .map((a) => a.id),
110
- ],
111
- },
112
- }
113
- : { ...current, skills }, home);
114
- return notices;
115
- }
116
81
  function folderFor(kind, name) {
117
- assertAssetName(name, `barndog ${kind === "skill" ? "skills" : "hooks"} add <source> --as <new-name>`);
118
- return assetFolder("org", kind, name);
82
+ assertAssetName(name, `barndog ${assetKinds[kind].command} add <source> --as <new-name>`);
83
+ return assetPath("org", kind, name);
119
84
  }
120
85
  async function assertFree(root, kind, name) {
121
86
  try {
122
- if (!(await readdir(root)).length)
87
+ if (!(await readdir(root)).length) {
123
88
  return;
89
+ }
124
90
  }
125
91
  catch (error) {
126
- const { code } = error;
127
- if (code === "ENOENT")
92
+ const code = errorCode(error);
93
+ if (code === "ENOENT") {
128
94
  return;
129
- if (code !== "ENOTDIR")
95
+ }
96
+ if (code !== "ENOTDIR") {
130
97
  throw error;
98
+ }
131
99
  }
132
- throw new CliError(`A local ${kind === "skill" ? "Skill" : "Hook"} named ${name} already exists at ${root}.`, `barndog ${kind === "skill" ? "skills" : "hooks"} add <source> --as <new-name>`);
100
+ throw new CliError(`A local ${assetKinds[kind].one} named ${name} already exists at ${root}.`, `barndog ${assetKinds[kind].command} add <source> --as <new-name>`);
133
101
  }
134
- export async function saveImported(input, home = homedir()) {
102
+ /**
103
+ * Writes imported package files into the local workspace and records upstream
104
+ * tracking unless the mode is fork.
105
+ */
106
+ export async function saveImported(input, runtime) {
135
107
  const relative = folderFor(input.kind, input.name);
136
- const workspace = await ensureLocalWorkspace(home);
108
+ const workspace = await ensureLocalWorkspace(runtime);
137
109
  const target = join(workspace.path, relative);
138
110
  await assertFree(target, input.kind, input.name);
139
111
  await mkdir(target, { recursive: true });
140
112
  await rm(target, { recursive: true, force: true });
141
- await writePackage(target, input.entries);
113
+ await writePackage(target, input.entries, runtime);
114
+ // Read back, so Windows (no executable bits) records what an update will see.
115
+ const fingerprint = packageFingerprint(await readDirectory(target, runtime));
116
+ // A record left by an earlier import of this name goes either way: a fork
117
+ // stops following its repository.
118
+ const sources = await readSources(workspace.path);
119
+ const before = sources.imports.length;
120
+ sources.imports = sources.imports.filter((entry) => !(entry.kind === input.kind && entry.name === input.name));
142
121
  if (input.mode !== "fork") {
143
- const sources = await readSources(workspace.path);
144
- sources.imports = sources.imports.filter((entry) => !(entry.kind === input.kind && entry.name === input.name));
145
122
  sources.imports.push({
146
123
  kind: input.kind,
147
124
  name: input.name,
@@ -151,8 +128,10 @@ export async function saveImported(input, home = homedir()) {
151
128
  root: input.root,
152
129
  commit: input.remote.commit,
153
130
  ...(input.files ? { files: input.files } : {}),
154
- fingerprint: packageFingerprint(input.entries),
131
+ fingerprint,
155
132
  });
133
+ }
134
+ if (sources.imports.length !== before || input.mode !== "fork") {
156
135
  await writeSources(workspace.path, sources);
157
136
  }
158
137
  return { path: target };
@@ -164,14 +143,13 @@ export function renamedSkill(skill, name) {
164
143
  }
165
144
  function latestEntries(record, remote, current) {
166
145
  const all = folderEntries(remote, record.root);
167
- if (!all.length)
146
+ if (!all.length) {
168
147
  throw new CliError(`${record.root || "That folder"} no longer exists in ${record.url}.`);
169
- if (record.files) {
170
- const manifest = current.find((entry) => entry.path === "hook.yaml");
171
- return [
172
- ...all.filter((entry) => record.files.includes(entry.path)),
173
- manifest,
174
- ];
148
+ }
149
+ const { files } = record;
150
+ if (files) {
151
+ const manifest = defined(current.find((entry) => entry.path === "hook.yaml"), `${record.name} has no hook.yaml`);
152
+ return [...all.filter((entry) => files.includes(entry.path)), manifest];
175
153
  }
176
154
  if (record.kind === "skill") {
177
155
  const manifestName = /^name:\s*(\S+)/m.exec(all.find((entry) => entry.path === "SKILL.md")?.data.toString("utf8") ??
@@ -183,59 +161,73 @@ function latestEntries(record, remote, current) {
183
161
  return all;
184
162
  }
185
163
  async function applyUpdate(folder, sources, record, options) {
164
+ const { runtime } = options;
186
165
  const target = join(folder, folderFor(record.kind, record.name));
187
- const current = await readDirectory(target);
188
- if (packageFingerprint(current) !== record.fingerprint && !options.force)
189
- throw new CliError(`${record.name} was edited locally, so updating would lose those edits.`, `barndog ${record.kind === "skill" ? "skills" : "hooks"} update ${record.name} --force`);
166
+ const current = await readDirectory(target, runtime);
167
+ if (packageFingerprint(current) !== record.fingerprint && !options.force) {
168
+ throw new CliError(`${record.name} was edited locally, so updating would lose those edits.`, `barndog ${assetKinds[record.kind].command} update ${record.name} --force`);
169
+ }
190
170
  return fetchRemote({ url: record.url, rest: null, ref: record.ref, path: record.root }, { allowPrompt: options.allowPrompt }, async (remote) => {
191
171
  const next = latestEntries(record, remote, current);
192
172
  const changes = await diffEntries(current, next);
193
173
  if (changes.length && !options.dryRun) {
194
174
  await rm(target, { recursive: true, force: true });
195
- await writePackage(target, next);
175
+ await writePackage(target, next, runtime);
196
176
  record.commit = remote.commit;
197
- record.fingerprint = packageFingerprint(next);
177
+ record.fingerprint = packageFingerprint(await readDirectory(target, runtime));
198
178
  await writeSources(folder, sources);
199
179
  }
200
180
  return { name: record.name, commit: remote.commit, changes };
201
- });
181
+ }, runtime);
202
182
  }
203
183
  /** `barndog skills update`: brings imported assets up to their source on request. */
204
- export async function updateImported(kind, name, options, home = homedir()) {
184
+ export async function updateImported(kind, name, options, runtime) {
185
+ const { home } = runtime;
205
186
  const settings = await readSettings(home);
206
- if (settings?.version !== 2 || !settings.localWorkspace)
187
+ if (!settings || !settings.localWorkspace) {
207
188
  throw new CliError("This machine has no assets added from a repo.");
189
+ }
208
190
  const folder = settings.localWorkspace.path;
209
191
  const sources = await readSources(folder);
210
- const records = sources.imports.filter((entry) => entry.kind === kind &&
211
- // Older versions could record a name sync ignores; it mustn't stop the others.
212
- (name ? entry.name === name : validAssetName(entry.name)));
213
- if (name && !records.length)
192
+ const records = sources.imports.filter((entry) => entry.kind === kind && (!name || entry.name === name));
193
+ if (name && !records.length) {
214
194
  throw new CliError(`${name} wasn't added from a repo, so it has nothing to update from.`);
195
+ }
215
196
  const results = [];
216
- for (const record of records)
197
+ for (const record of records) {
217
198
  results.push(await applyUpdate(folder, sources, record, {
218
- ...options,
219
- allowPrompt: true,
199
+ ...{
200
+ ...options,
201
+ allowPrompt: true,
202
+ },
203
+ runtime,
220
204
  }));
205
+ }
221
206
  return results;
222
207
  }
223
- const FOLLOW_INTERVAL_MS = 5 * 60 * 1000;
208
+ /** Background refresh policy: check at most every five minutes (milliseconds). */
209
+ const FOLLOW_INTERVAL_MS = 300000;
224
210
  /** Runs before sync. A repo that fails or was edited locally never blocks delivery. */
225
- export async function followImports(folder, policy) {
211
+ export async function followImports(folder, policy, runtime) {
226
212
  const sources = await readSources(folder);
227
213
  const followed = sources.imports.filter((entry) => entry.mode === "auto");
228
214
  const notices = [];
229
- if (!followed.length || policy === "none")
215
+ if (!followed.length || policy === "none") {
230
216
  return notices;
217
+ }
231
218
  if (policy === "auto" &&
232
219
  sources.checkedAt &&
233
- Date.now() - Date.parse(sources.checkedAt) < FOLLOW_INTERVAL_MS)
220
+ Date.now() - Date.parse(sources.checkedAt) < FOLLOW_INTERVAL_MS) {
234
221
  return notices;
235
- for (const record of followed)
236
- await applyUpdate(folder, sources, record, { allowPrompt: false }).catch((error) => {
222
+ }
223
+ for (const record of followed) {
224
+ await applyUpdate(folder, sources, record, {
225
+ allowPrompt: false,
226
+ runtime,
227
+ }).catch((error) => {
237
228
  notices.push(`${record.name} wasn't updated from its repo: ${error.message}`);
238
229
  });
230
+ }
239
231
  sources.checkedAt = new Date().toISOString();
240
232
  await writeSources(folder, sources);
241
233
  return notices;
@@ -1,55 +1,72 @@
1
+ import { gitAccessCommand } from "../../platform.js";
2
+ import { POSIX_MODE } from "../../shared/constants.js";
1
3
  import { randomUUID } from "node:crypto";
2
4
  import { mkdir, rm } from "node:fs/promises";
3
5
  import { tmpdir } from "node:os";
4
6
  import { join } from "node:path";
5
7
  import { CliError } from "../../errors.js";
6
- import { checkRepositoryUrl, git, GitError, gitReason, gitText, } from "../git-workspace/git.js";
7
- import { gitSnapshot, isBlob, } from "../git-workspace/snapshot.js";
8
+ import { checkRepositoryUrl, git, GitError, gitReason, gitText, parseLsRemote, } from "../workspace/git.js";
9
+ import { GIT_OBJECT_ID } from "../../shared/patterns.js";
10
+ import { gitSnapshot, isBlob } from "../workspace/snapshot.js";
11
+ /** GitHub shorthand, `<owner>/<repo>`: `anthropics/skills`. */
12
+ const GITHUB_SHORTHAND = /^([\da-z][\da-z-]*)\/([\w.-]+)$/i;
13
+ /**
14
+ * A link to a folder or file in a repository's web view, on GitHub
15
+ * (`https://github.com/o/r/tree/main/skills/x`) or GitLab
16
+ * (`https://gitlab.com/o/r/-/blob/v1/hook.yaml`). Groups: host, owner, repo,
17
+ * then everything after `tree/` or `blob/`.
18
+ */
19
+ const WEB_TREE_URL = /^https?:\/\/([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?\/(?:-\/)?(?:tree|blob)\/(.+?)\/?$/;
20
+ /** Reads what someone pasted: a GitHub shorthand, a web link into a repository, or a clone URL. */
8
21
  export function parseLocation(input) {
9
22
  const value = input.trim();
10
- const short = /^([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9._-]+)$/.exec(value);
11
- if (short)
23
+ const short = GITHUB_SHORTHAND.exec(value);
24
+ if (short) {
12
25
  return {
13
26
  url: `https://github.com/${short[1]}/${short[2]}.git`,
14
27
  rest: null,
15
28
  };
16
- const web = /^https?:\/\/([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?\/(?:-\/)?(tree|blob)\/(.+?)\/?$/.exec(value);
17
- if (web)
29
+ }
30
+ const [, host, owner, repo, rest] = WEB_TREE_URL.exec(value) ?? [];
31
+ if (rest !== undefined) {
18
32
  return {
19
- url: checkRepositoryUrl(`https://${web[1]}/${web[2]}/${web[3]}.git`),
20
- rest: decodeURIComponent(web[5]),
33
+ url: checkRepositoryUrl(`https://${host}/${owner}/${repo}.git`),
34
+ rest: decodeURIComponent(rest),
21
35
  };
36
+ }
22
37
  return { url: checkRepositoryUrl(value.replace(/\/$/, "")), rest: null };
23
38
  }
24
39
  /** Splits `<ref>/<path>` against the refs that really exist on the remote. */
25
- async function resolveRest(url, rest, allowPrompt) {
26
- if (!rest)
40
+ async function resolveRest(url, rest, allowPrompt, runtime) {
41
+ if (!rest) {
27
42
  return { ref: null, path: "" };
28
- const first = rest.split("/")[0];
29
- if (/^[0-9a-f]{40}$/.test(first))
43
+ }
44
+ const [first = ""] = rest.split("/");
45
+ if (GIT_OBJECT_ID.test(first)) {
30
46
  return { ref: first, path: rest.slice(first.length + 1) };
31
- const listing = await gitText(["ls-remote", "--heads", "--tags", "--", url], {
47
+ }
48
+ const listing = await gitText(["ls-remote", "--heads", "--tags", "--", url], runtime, {
32
49
  allowPrompt,
33
50
  });
34
- const refs = listing
35
- .split("\n")
36
- .map((line) => line.split("\t")[1]?.replace(/^refs\/(heads|tags)\//, "") ?? "")
51
+ const refs = parseLsRemote(listing)
52
+ .map(({ ref }) => ref.replace(/^refs\/(?:heads|tags)\//, ""))
37
53
  .filter(Boolean)
38
54
  .sort((a, b) => b.length - a.length);
39
55
  const ref = refs.find((name) => rest === name || rest.startsWith(`${name}/`));
40
- if (!ref)
56
+ if (!ref) {
41
57
  throw new CliError(`Can't find that branch or tag in ${url}.`);
58
+ }
42
59
  return { ref, path: rest.slice(ref.length + 1) };
43
60
  }
44
61
  /** Fetches just one commit into a throwaway bare repo; nothing is checked out or run. */
45
- export async function fetchRemote(location, options, use) {
62
+ export async function fetchRemote(location, options, use, runtime) {
46
63
  const repo = join(tmpdir(), `barndog-import-${randomUUID()}.git`);
47
- await mkdir(repo, { recursive: true, mode: 0o700 });
64
+ await mkdir(repo, { recursive: true, mode: POSIX_MODE.privateDirectory });
48
65
  try {
49
- await git(["init", "--quiet", "--bare", "."], { repo });
66
+ await git(["init", "--quiet", "--bare", "."], runtime, { repo });
50
67
  const resolved = location.ref !== undefined
51
68
  ? { ref: location.ref, path: location.path ?? "" }
52
- : await resolveRest(location.url, location.rest, options.allowPrompt);
69
+ : await resolveRest(location.url, location.rest, options.allowPrompt, runtime);
53
70
  await git([
54
71
  "fetch",
55
72
  "--quiet",
@@ -59,9 +76,11 @@ export async function fetchRemote(location, options, use) {
59
76
  "--",
60
77
  location.url,
61
78
  resolved.ref ?? "HEAD",
62
- ], { repo, allowPrompt: options.allowPrompt });
63
- const commit = await gitText(["rev-parse", "FETCH_HEAD"], { repo });
64
- const snapshot = await gitSnapshot(repo, commit);
79
+ ], runtime, { repo, allowPrompt: options.allowPrompt });
80
+ const commit = await gitText(["rev-parse", "FETCH_HEAD"], runtime, {
81
+ repo,
82
+ });
83
+ const snapshot = await gitSnapshot(repo, commit, runtime);
65
84
  const blobs = await snapshot.readBlobs(snapshot.entries
66
85
  .filter((entry) => isBlob(entry.mode))
67
86
  .map((entry) => entry.hash));
@@ -75,8 +94,9 @@ export async function fetchRemote(location, options, use) {
75
94
  });
76
95
  }
77
96
  catch (error) {
78
- if (error instanceof GitError)
79
- throw new CliError(`Can't read ${location.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine.`, `git clone ${location.url}`, { cause: error });
97
+ if (error instanceof GitError) {
98
+ throw new CliError(`Can't read ${location.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine.`, gitAccessCommand(location.url, runtime.platform), { cause: error });
99
+ }
80
100
  throw error;
81
101
  }
82
102
  finally {
@@ -1,15 +1,15 @@
1
- import { homedir } from "node:os";
2
1
  import { normalizeRepositoryRemote } from "@barndog-ai/api-contract";
3
2
  import { authStatus } from "../auth/session.js";
4
3
  import { readSettings } from "../../config/settings.js";
5
4
  import { repositoryContext, localRepository } from "../repositories/context.js";
6
- import { openRepoSource } from "../environment/workspace-source.js";
5
+ import { openRepoSource } from "../workspace/workspace-source.js";
6
+ import { only } from "../../shared/lookup.js";
7
7
  /** The barndog.yaml answer to "which repository scope is this folder?". */
8
- async function repoStatus(model, cwd) {
9
- const local = await localRepository(cwd);
8
+ async function declaredRepository(model, cwd, runtime) {
9
+ const local = await localRepository({ ...runtime, cwd });
10
10
  const matches = Object.entries(model.config.repositories).filter(([, repository]) => repository.gitRemote &&
11
11
  local.remotes.includes(normalizeRepositoryRemote(repository.gitRemote) ?? ""));
12
- const [slug, declared] = matches.length === 1 ? matches[0] : [];
12
+ const [slug, declared] = only(matches) ?? [];
13
13
  const scope = (type, name) => model.scopes.find((s) => s.type === type && s.slug === name);
14
14
  const repository = slug ? scope("repo", slug) : undefined;
15
15
  const team = scope("team", declared?.team);
@@ -26,17 +26,17 @@ async function repoStatus(model, cwd) {
26
26
  ],
27
27
  };
28
28
  }
29
- export async function inspect(action, home = homedir(), cwd = process.cwd()) {
30
- if (action === "whoami")
31
- return authStatus(home);
32
- if (action === "open")
33
- return { url: (await authStatus(home)).server };
34
- if (action === "repo-status") {
35
- const settings = await readSettings(home);
36
- const repo = settings && openRepoSource(settings, home, { refresh: "auto" });
37
- if (repo)
38
- return repoStatus(await repo.model(), cwd);
39
- return repositoryContext(home, cwd);
29
+ /** The workspace's web address: the server this machine is signed in to. */
30
+ export async function workspaceUrl(runtime) {
31
+ return (await authStatus(runtime)).server;
32
+ }
33
+ /** How the Git repository in `cwd` maps to a BarnDog repository and its team. */
34
+ export async function repoStatus(runtime) {
35
+ const { home, cwd } = runtime;
36
+ const settings = await readSettings(home);
37
+ const repo = settings && openRepoSource(settings, runtime, { refresh: "auto" });
38
+ if (repo) {
39
+ return declaredRepository(await repo.model(), cwd, runtime);
40
40
  }
41
- throw new Error(`Unknown inspection: ${action}`);
41
+ return repositoryContext(runtime);
42
42
  }