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
@@ -1,144 +1,110 @@
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;
26
- }
41
+ return ((await readJsonIfExists(localWorkspaceFiles(folder).sources, sourcesSchema)) ?? { imports: [] });
27
42
  }
28
- const writeSources = (folder, sources) => writeFile(join(folder, SOURCES_FILE), JSON.stringify(sources, null, 2) + "\n");
43
+ const writeSources = (folder, sources) => writeAtomic(localWorkspaceFiles(folder).sources, JSON.stringify(sources, null, 2) + "\n", { mode: POSIX_MODE.regularFile });
29
44
  /** The repository an asset still follows, or null for a fork or one made here. */
30
- export async function importedFrom(kind, name, home = homedir()) {
45
+ export async function importedFrom(kind, name, runtime) {
46
+ const { home } = runtime;
31
47
  const settings = await readSettings(home);
32
- if (settings?.version !== 2 || !settings.localWorkspace)
48
+ if (!settings || !settings.localWorkspace) {
33
49
  return null;
50
+ }
34
51
  const { imports } = await readSources(settings.localWorkspace.path);
35
52
  return imports.find((e) => e.kind === kind && e.name === name) ?? null;
36
53
  }
37
54
  /** Adding always lands in the local folder, creating it on first use. */
38
- export async function ensureLocalWorkspace(home) {
55
+ export async function ensureLocalWorkspace(runtime) {
56
+ const { home } = runtime;
39
57
  const settings = await readSettings(home);
40
- if (!settings)
58
+ if (!settings) {
41
59
  throw new SetupRequiredError();
42
- if (settings.version === 2 && settings.localWorkspace)
60
+ }
61
+ if (settings.localWorkspace) {
43
62
  return settings.localWorkspace;
44
- const workspace = await localWorkspace(home);
45
- const kept = await localRepoSource(workspace, home).model();
63
+ }
64
+ const workspace = await localWorkspace(runtime);
65
+ const kept = await localRepoSource(workspace, runtime).model();
46
66
  const next = {
47
- ...upgradeSettings(settings),
67
+ ...settings,
48
68
  localWorkspace: workspace,
49
69
  };
50
70
  await saveSettings(withSelection(next, withLocalSubscription(selectionState(next), kept)), home);
51
71
  return workspace;
52
72
  }
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
73
  function folderFor(kind, name) {
117
- assertAssetName(name, `barndog ${kind === "skill" ? "skills" : "hooks"} add <source> --as <new-name>`);
118
- return assetFolder("org", kind, name);
74
+ assertAssetName(name, `barndog ${assetKinds[kind].command} add <source> --as <new-name>`);
75
+ return assetPath("org", kind, name);
119
76
  }
120
77
  async function assertFree(root, kind, name) {
121
78
  try {
122
- if (!(await readdir(root)).length)
79
+ if (!(await readdir(root)).length) {
123
80
  return;
81
+ }
124
82
  }
125
83
  catch (error) {
126
- const { code } = error;
127
- if (code === "ENOENT")
84
+ const code = errorCode(error);
85
+ if (code === "ENOENT") {
128
86
  return;
129
- if (code !== "ENOTDIR")
87
+ }
88
+ if (code !== "ENOTDIR") {
130
89
  throw error;
90
+ }
131
91
  }
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>`);
92
+ throw new CliError(`A local ${assetKinds[kind].one} named ${name} already exists at ${root}.`, `barndog ${assetKinds[kind].command} add <source> --as <new-name>`);
133
93
  }
134
- export async function saveImported(input, home = homedir()) {
94
+ /**
95
+ * Writes imported package files into the local workspace and records upstream
96
+ * tracking unless the mode is fork.
97
+ */
98
+ export async function saveImported(input, runtime) {
135
99
  const relative = folderFor(input.kind, input.name);
136
- const workspace = await ensureLocalWorkspace(home);
100
+ const workspace = await ensureLocalWorkspace(runtime);
137
101
  const target = join(workspace.path, relative);
138
102
  await assertFree(target, input.kind, input.name);
139
103
  await mkdir(target, { recursive: true });
140
104
  await rm(target, { recursive: true, force: true });
141
- await writePackage(target, input.entries);
105
+ await writePackage(target, input.entries, runtime);
106
+ // Read back, so Windows (no executable bits) records what an update will see.
107
+ const fingerprint = packageFingerprint(await readDirectory(target, runtime));
142
108
  if (input.mode !== "fork") {
143
109
  const sources = await readSources(workspace.path);
144
110
  sources.imports = sources.imports.filter((entry) => !(entry.kind === input.kind && entry.name === input.name));
@@ -151,7 +117,7 @@ export async function saveImported(input, home = homedir()) {
151
117
  root: input.root,
152
118
  commit: input.remote.commit,
153
119
  ...(input.files ? { files: input.files } : {}),
154
- fingerprint: packageFingerprint(input.entries),
120
+ fingerprint,
155
121
  });
156
122
  await writeSources(workspace.path, sources);
157
123
  }
@@ -164,14 +130,13 @@ export function renamedSkill(skill, name) {
164
130
  }
165
131
  function latestEntries(record, remote, current) {
166
132
  const all = folderEntries(remote, record.root);
167
- if (!all.length)
133
+ if (!all.length) {
168
134
  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
- ];
135
+ }
136
+ const { files } = record;
137
+ if (files) {
138
+ const manifest = defined(current.find((entry) => entry.path === "hook.yaml"), `${record.name} has no hook.yaml`);
139
+ return [...all.filter((entry) => files.includes(entry.path)), manifest];
175
140
  }
176
141
  if (record.kind === "skill") {
177
142
  const manifestName = /^name:\s*(\S+)/m.exec(all.find((entry) => entry.path === "SKILL.md")?.data.toString("utf8") ??
@@ -183,59 +148,73 @@ function latestEntries(record, remote, current) {
183
148
  return all;
184
149
  }
185
150
  async function applyUpdate(folder, sources, record, options) {
151
+ const { runtime } = options;
186
152
  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`);
153
+ const current = await readDirectory(target, runtime);
154
+ if (packageFingerprint(current) !== record.fingerprint && !options.force) {
155
+ throw new CliError(`${record.name} was edited locally, so updating would lose those edits.`, `barndog ${assetKinds[record.kind].command} update ${record.name} --force`);
156
+ }
190
157
  return fetchRemote({ url: record.url, rest: null, ref: record.ref, path: record.root }, { allowPrompt: options.allowPrompt }, async (remote) => {
191
158
  const next = latestEntries(record, remote, current);
192
159
  const changes = await diffEntries(current, next);
193
160
  if (changes.length && !options.dryRun) {
194
161
  await rm(target, { recursive: true, force: true });
195
- await writePackage(target, next);
162
+ await writePackage(target, next, runtime);
196
163
  record.commit = remote.commit;
197
- record.fingerprint = packageFingerprint(next);
164
+ record.fingerprint = packageFingerprint(await readDirectory(target, runtime));
198
165
  await writeSources(folder, sources);
199
166
  }
200
167
  return { name: record.name, commit: remote.commit, changes };
201
- });
168
+ }, runtime);
202
169
  }
203
170
  /** `barndog skills update`: brings imported assets up to their source on request. */
204
- export async function updateImported(kind, name, options, home = homedir()) {
171
+ export async function updateImported(kind, name, options, runtime) {
172
+ const { home } = runtime;
205
173
  const settings = await readSettings(home);
206
- if (settings?.version !== 2 || !settings.localWorkspace)
174
+ if (!settings || !settings.localWorkspace) {
207
175
  throw new CliError("This machine has no assets added from a repo.");
176
+ }
208
177
  const folder = settings.localWorkspace.path;
209
178
  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)
179
+ const records = sources.imports.filter((entry) => entry.kind === kind && (!name || entry.name === name));
180
+ if (name && !records.length) {
214
181
  throw new CliError(`${name} wasn't added from a repo, so it has nothing to update from.`);
182
+ }
215
183
  const results = [];
216
- for (const record of records)
184
+ for (const record of records) {
217
185
  results.push(await applyUpdate(folder, sources, record, {
218
- ...options,
219
- allowPrompt: true,
186
+ ...{
187
+ ...options,
188
+ allowPrompt: true,
189
+ },
190
+ runtime,
220
191
  }));
192
+ }
221
193
  return results;
222
194
  }
223
- const FOLLOW_INTERVAL_MS = 5 * 60 * 1000;
195
+ /** Background refresh policy: check at most every five minutes (milliseconds). */
196
+ const FOLLOW_INTERVAL_MS = 300000;
224
197
  /** Runs before sync. A repo that fails or was edited locally never blocks delivery. */
225
- export async function followImports(folder, policy) {
198
+ export async function followImports(folder, policy, runtime) {
226
199
  const sources = await readSources(folder);
227
200
  const followed = sources.imports.filter((entry) => entry.mode === "auto");
228
201
  const notices = [];
229
- if (!followed.length || policy === "none")
202
+ if (!followed.length || policy === "none") {
230
203
  return notices;
204
+ }
231
205
  if (policy === "auto" &&
232
206
  sources.checkedAt &&
233
- Date.now() - Date.parse(sources.checkedAt) < FOLLOW_INTERVAL_MS)
207
+ Date.now() - Date.parse(sources.checkedAt) < FOLLOW_INTERVAL_MS) {
234
208
  return notices;
235
- for (const record of followed)
236
- await applyUpdate(folder, sources, record, { allowPrompt: false }).catch((error) => {
209
+ }
210
+ for (const record of followed) {
211
+ await applyUpdate(folder, sources, record, {
212
+ allowPrompt: false,
213
+ runtime,
214
+ }).catch((error) => {
237
215
  notices.push(`${record.name} wasn't updated from its repo: ${error.message}`);
238
216
  });
217
+ }
239
218
  sources.checkedAt = new Date().toISOString();
240
219
  await writeSources(folder, sources);
241
220
  return notices;
@@ -1,55 +1,71 @@
1
+ import { POSIX_MODE } from "../../shared/constants.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { mkdir, rm } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  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";
7
+ import { checkRepositoryUrl, git, GitError, gitReason, gitText, parseLsRemote, } from "../workspace/git.js";
8
+ import { GIT_OBJECT_ID } from "../../shared/patterns.js";
9
+ import { gitSnapshot, isBlob } from "../workspace/snapshot.js";
10
+ /** GitHub shorthand, `<owner>/<repo>`: `anthropics/skills`. */
11
+ const GITHUB_SHORTHAND = /^([\da-z][\da-z-]*)\/([\w.-]+)$/i;
12
+ /**
13
+ * A link to a folder or file in a repository's web view, on GitHub
14
+ * (`https://github.com/o/r/tree/main/skills/x`) or GitLab
15
+ * (`https://gitlab.com/o/r/-/blob/v1/hook.yaml`). Groups: host, owner, repo,
16
+ * then everything after `tree/` or `blob/`.
17
+ */
18
+ const WEB_TREE_URL = /^https?:\/\/([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?\/(?:-\/)?(?:tree|blob)\/(.+?)\/?$/;
19
+ /** Reads what someone pasted: a GitHub shorthand, a web link into a repository, or a clone URL. */
8
20
  export function parseLocation(input) {
9
21
  const value = input.trim();
10
- const short = /^([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9._-]+)$/.exec(value);
11
- if (short)
22
+ const short = GITHUB_SHORTHAND.exec(value);
23
+ if (short) {
12
24
  return {
13
25
  url: `https://github.com/${short[1]}/${short[2]}.git`,
14
26
  rest: null,
15
27
  };
16
- const web = /^https?:\/\/([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?\/(?:-\/)?(tree|blob)\/(.+?)\/?$/.exec(value);
17
- if (web)
28
+ }
29
+ const [, host, owner, repo, rest] = WEB_TREE_URL.exec(value) ?? [];
30
+ if (rest !== undefined) {
18
31
  return {
19
- url: checkRepositoryUrl(`https://${web[1]}/${web[2]}/${web[3]}.git`),
20
- rest: decodeURIComponent(web[5]),
32
+ url: checkRepositoryUrl(`https://${host}/${owner}/${repo}.git`),
33
+ rest: decodeURIComponent(rest),
21
34
  };
35
+ }
22
36
  return { url: checkRepositoryUrl(value.replace(/\/$/, "")), rest: null };
23
37
  }
24
38
  /** Splits `<ref>/<path>` against the refs that really exist on the remote. */
25
- async function resolveRest(url, rest, allowPrompt) {
26
- if (!rest)
39
+ async function resolveRest(url, rest, allowPrompt, runtime) {
40
+ if (!rest) {
27
41
  return { ref: null, path: "" };
28
- const first = rest.split("/")[0];
29
- if (/^[0-9a-f]{40}$/.test(first))
42
+ }
43
+ const [first = ""] = rest.split("/");
44
+ if (GIT_OBJECT_ID.test(first)) {
30
45
  return { ref: first, path: rest.slice(first.length + 1) };
31
- const listing = await gitText(["ls-remote", "--heads", "--tags", "--", url], {
46
+ }
47
+ const listing = await gitText(["ls-remote", "--heads", "--tags", "--", url], runtime, {
32
48
  allowPrompt,
33
49
  });
34
- const refs = listing
35
- .split("\n")
36
- .map((line) => line.split("\t")[1]?.replace(/^refs\/(heads|tags)\//, "") ?? "")
50
+ const refs = parseLsRemote(listing)
51
+ .map(({ ref }) => ref.replace(/^refs\/(?:heads|tags)\//, ""))
37
52
  .filter(Boolean)
38
53
  .sort((a, b) => b.length - a.length);
39
54
  const ref = refs.find((name) => rest === name || rest.startsWith(`${name}/`));
40
- if (!ref)
55
+ if (!ref) {
41
56
  throw new CliError(`Can't find that branch or tag in ${url}.`);
57
+ }
42
58
  return { ref, path: rest.slice(ref.length + 1) };
43
59
  }
44
60
  /** Fetches just one commit into a throwaway bare repo; nothing is checked out or run. */
45
- export async function fetchRemote(location, options, use) {
61
+ export async function fetchRemote(location, options, use, runtime) {
46
62
  const repo = join(tmpdir(), `barndog-import-${randomUUID()}.git`);
47
- await mkdir(repo, { recursive: true, mode: 0o700 });
63
+ await mkdir(repo, { recursive: true, mode: POSIX_MODE.privateDirectory });
48
64
  try {
49
- await git(["init", "--quiet", "--bare", "."], { repo });
65
+ await git(["init", "--quiet", "--bare", "."], runtime, { repo });
50
66
  const resolved = location.ref !== undefined
51
67
  ? { ref: location.ref, path: location.path ?? "" }
52
- : await resolveRest(location.url, location.rest, options.allowPrompt);
68
+ : await resolveRest(location.url, location.rest, options.allowPrompt, runtime);
53
69
  await git([
54
70
  "fetch",
55
71
  "--quiet",
@@ -59,9 +75,11 @@ export async function fetchRemote(location, options, use) {
59
75
  "--",
60
76
  location.url,
61
77
  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);
78
+ ], runtime, { repo, allowPrompt: options.allowPrompt });
79
+ const commit = await gitText(["rev-parse", "FETCH_HEAD"], runtime, {
80
+ repo,
81
+ });
82
+ const snapshot = await gitSnapshot(repo, commit, runtime);
65
83
  const blobs = await snapshot.readBlobs(snapshot.entries
66
84
  .filter((entry) => isBlob(entry.mode))
67
85
  .map((entry) => entry.hash));
@@ -75,8 +93,9 @@ export async function fetchRemote(location, options, use) {
75
93
  });
76
94
  }
77
95
  catch (error) {
78
- if (error instanceof GitError)
96
+ if (error instanceof GitError) {
79
97
  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 });
98
+ }
80
99
  throw error;
81
100
  }
82
101
  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
  }