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,221 @@
1
+ import { fixSteps, gitAccessCommand } from "../../platform.js";
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { stat } from "node:fs/promises";
4
+ import { CliError } from "../../errors.js";
5
+ import { errorCode } from "../../shared/values.js";
6
+ import { GIT_OBJECT_ID } from "../../shared/patterns.js";
7
+ /** CLI policy permits up to 512 MiB of Git plumbing output. */
8
+ const GIT_OUTPUT_LIMIT_MIB = 512;
9
+ /** IEC binary units use 1024 bytes per KiB. */
10
+ const BYTES_PER_KIB = 1024;
11
+ /** CLI policy bounds Git subprocesses to three minutes. */
12
+ const GIT_TIMEOUT_MS = 180_000;
13
+ /** The prefix Git puts on a failure line: `fatal: `, `error: ` or `remote: `. */
14
+ const FAILURE_PREFIX = /^(?:fatal|error|remote):\s*/;
15
+ /**
16
+ * The line of Git's stderr that says what went wrong, without its prefix:
17
+ * `fatal: repository 'x' not found` → `repository 'x' not found`. Falls back to
18
+ * the last line when none has a prefix.
19
+ */
20
+ export function gitReason(stderr) {
21
+ const lines = stderr
22
+ .split("\n")
23
+ .map((line) => line.trim())
24
+ .filter(Boolean);
25
+ const line = lines.find((text) => FAILURE_PREFIX.test(text)) ?? lines.at(-1) ?? "";
26
+ return line.replace(FAILURE_PREFIX, "");
27
+ }
28
+ /** Git can't read the repository with what this machine has set up. */
29
+ export class RepositoryAccessError extends CliError {
30
+ }
31
+ /**
32
+ * Git command failure retaining stderr and exit status for actionable
33
+ * diagnostics.
34
+ */
35
+ export class GitError extends Error {
36
+ stderr;
37
+ exitCode;
38
+ constructor(message, stderr, exitCode) {
39
+ super(message);
40
+ this.stderr = stderr;
41
+ this.exitCode = exitCode;
42
+ this.name = "GitError";
43
+ }
44
+ }
45
+ // A caller running inside a Git hook passes these, and they would redirect every command.
46
+ const inherited = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX"];
47
+ /** Runs system Git with repository hooks and the arbitrary-command transport disabled. */
48
+ export function git(args, runtime, options = {}) {
49
+ const env = { ...runtime.env };
50
+ for (const name of inherited) {
51
+ delete env[name];
52
+ }
53
+ if (!options.allowPrompt) {
54
+ env.GIT_TERMINAL_PROMPT = "0";
55
+ }
56
+ return new Promise((resolve, reject) => {
57
+ const child = execFile("git", [
58
+ ...(options.repo ? ["-C", options.repo] : []),
59
+ "-c",
60
+ "core.hooksPath=/dev/null",
61
+ "-c",
62
+ "protocol.ext.allow=never",
63
+ ...args,
64
+ ], {
65
+ encoding: "buffer",
66
+ cwd: runtime.cwd,
67
+ windowsHide: true,
68
+ env: { ...env, ...options.env },
69
+ maxBuffer: GIT_OUTPUT_LIMIT_MIB * BYTES_PER_KIB * BYTES_PER_KIB,
70
+ timeout: options.timeoutMs ?? GIT_TIMEOUT_MS,
71
+ }, (error, stdout, stderr) => {
72
+ if (!error) {
73
+ return resolve(stdout);
74
+ }
75
+ const code = errorCode(error) ?? null;
76
+ if (code === "ENOENT") {
77
+ return reject(new CliError("Git isn't installed or isn't on your PATH. Git repo workspaces need it."));
78
+ }
79
+ const text = stderr.toString("utf8").trim();
80
+ reject(new GitError(text || error.message, text, code));
81
+ });
82
+ child.stdin?.end(options.input);
83
+ });
84
+ }
85
+ /** Runs Git attached to the terminal, so its own prompts and errors reach the developer. */
86
+ export function gitInTerminal(args, runtime) {
87
+ const env = { ...runtime.env };
88
+ for (const name of inherited) {
89
+ delete env[name];
90
+ }
91
+ return new Promise((resolve, reject) => {
92
+ const child = spawn("git", [
93
+ "-c",
94
+ "core.hooksPath=/dev/null",
95
+ "-c",
96
+ "protocol.ext.allow=never",
97
+ ...args,
98
+ ], { env, cwd: runtime.cwd, stdio: "inherit", windowsHide: true });
99
+ child.once("error", reject);
100
+ child.once("exit", (code) => code === 0
101
+ ? resolve()
102
+ : reject(new GitError(`git exited with ${code}`, "", code)));
103
+ });
104
+ }
105
+ /**
106
+ * Runs Git with the supplied arguments and returns UTF-8 stdout with
107
+ * surrounding whitespace removed.
108
+ */
109
+ export const gitText = async (args, runtime, options) => (await git(args, runtime, options)).toString("utf8").trim();
110
+ /** Lets `--repo` name a clone on disk: the workspace is the remote it came from. */
111
+ export async function cloneOrigin(value, runtime) {
112
+ try {
113
+ if (!(await stat(value.trim())).isDirectory()) {
114
+ return value;
115
+ }
116
+ return await gitText(["config", "--get", "remote.origin.url"], runtime, {
117
+ repo: value.trim(),
118
+ });
119
+ }
120
+ catch {
121
+ return value;
122
+ }
123
+ }
124
+ /** Git's `ext::` and `fd::` remote helpers, which run commands or read file descriptors. */
125
+ const UNSAFE_TRANSPORT = /^(?:ext|fd)::/i;
126
+ /** A URL with a password or token in it: `https://user:secret@host/repo.git`. */
127
+ const URL_WITH_PASSWORD = /^[a-z][\d+.a-z-]*:\/\/[^/:@]*:[^/@]*@/i;
128
+ /** Refuses URLs Git would read as options, helpers, or stored passwords. */
129
+ export function checkRepositoryUrl(value) {
130
+ const url = value.trim();
131
+ if (!url || url.startsWith("-") || UNSAFE_TRANSPORT.test(url)) {
132
+ throw new CliError(`That isn't a Git repository URL: ${url || "(empty)"}`);
133
+ }
134
+ if (URL_WITH_PASSWORD.test(url)) {
135
+ throw new CliError("Remove the password or token from the URL. BarnDog uses your own Git credentials and never stores them.");
136
+ }
137
+ return url;
138
+ }
139
+ /**
140
+ * The lines of `git ls-remote` output, `<object name>\t<ref>`:
141
+ *
142
+ * ```text
143
+ * 3f786850e387550fdab836ed7e6dc881de23001b\trefs/heads/main
144
+ * ```
145
+ */
146
+ export function parseLsRemote(output) {
147
+ return output
148
+ .split("\n")
149
+ .map((line) => line.split("\t"))
150
+ .filter((fields) => fields.length === 2)
151
+ .map(([commit = "", ref = ""]) => ({ commit, ref }));
152
+ }
153
+ /** `ref: refs/heads/main\tHEAD` in `git ls-remote --symref <url> HEAD` output. */
154
+ const SYMREF_LINE = /^ref: refs\/heads\/(\S+)\s+HEAD$/m;
155
+ /** `<object name>\tHEAD` in `git ls-remote` output, in any hash length. */
156
+ const HEAD_LINE = /^([\da-f]+)\s+HEAD$/m;
157
+ /**
158
+ * Reads the default branch from `git ls-remote --symref <url> HEAD`:
159
+ *
160
+ * ```text
161
+ * ref: refs/heads/main\tHEAD
162
+ * 3f786850e387550fdab836ed7e6dc881de23001b\tHEAD
163
+ * ```
164
+ *
165
+ * Empty output means an empty repository (null). Fails for SHA-256 repositories
166
+ * and when either line is missing.
167
+ *
168
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
169
+ */
170
+ export function parseRemoteHead(output, url) {
171
+ if (!output) {
172
+ return null;
173
+ }
174
+ const branch = SYMREF_LINE.exec(output)?.[1];
175
+ const commit = HEAD_LINE.exec(output)?.[1];
176
+ if (commit && !GIT_OBJECT_ID.test(commit)) {
177
+ throw new CliError("This repository uses SHA-256 object names, which BarnDog doesn't support yet.");
178
+ }
179
+ if (!branch || !commit) {
180
+ throw new CliError(`Can't find the default branch of ${url}.`);
181
+ }
182
+ return { branch, commit };
183
+ }
184
+ /** Reads a remote's default branch; null means the repository is empty. */
185
+ export async function remoteHead(url, runtime, allowPrompt = false) {
186
+ let output;
187
+ try {
188
+ output = await gitText(["ls-remote", "--symref", "--", url, "HEAD"], runtime, {
189
+ allowPrompt,
190
+ timeoutMs: 60_000,
191
+ });
192
+ }
193
+ catch (error) {
194
+ if (error instanceof GitError) {
195
+ throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, gitAccessCommand(url, runtime.platform), { cause: error });
196
+ }
197
+ throw error;
198
+ }
199
+ return parseRemoteHead(output, url);
200
+ }
201
+ /**
202
+ * Git's stderr when a commit has no author: `*** Please tell me who you are.`
203
+ * followed by the `git config` commands to run.
204
+ *
205
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
206
+ */
207
+ export const UNKNOWN_IDENTITY = /tell me who you are/i;
208
+ /** Git's "who are you" failure is common on new machines and has one clear fix. */
209
+ export function explainIdentity(error, platform) {
210
+ if (error instanceof GitError && UNKNOWN_IDENTITY.test(error.stderr)) {
211
+ // Git needs both; double quotes read the same in Bash, zsh and PowerShell.
212
+ throw new CliError("Git doesn't know who you are, so BarnDog can't make a commit.", "Tell Git your name and email for every repository, then try again", {
213
+ cause: error,
214
+ command: fixSteps([
215
+ 'git config --global user.name "Your Name"',
216
+ 'git config --global user.email "you@example.com"',
217
+ ], platform),
218
+ });
219
+ }
220
+ throw error;
221
+ }
@@ -0,0 +1,92 @@
1
+ import { assertPackagePaths } from "../../platform.js";
2
+ import { POSIX_MODE } from "../../shared/constants.js";
3
+ import { chmod, lstat, mkdir, readdir, rm, rmdir } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { readTree } from "./tree.js";
6
+ import { setYamlName, splitFrontMatter } from "../../shared/patterns.js";
7
+ import { writeAtomic } from "../../shared/files.js";
8
+ import { barndogPaths } from "../../config/paths.js";
9
+ export function installedPath(runtime, kind, name) {
10
+ const { home } = runtime;
11
+ return join(barndogPaths(home).installed(kind), name);
12
+ }
13
+ /** Points SKILL.md's name at the installed folder name; harnesses require them to match. */
14
+ export function renameSkillEntries(entries, name) {
15
+ return entries.map((entry) => {
16
+ if (entry.path !== "SKILL.md") {
17
+ return entry;
18
+ }
19
+ const parts = splitFrontMatter(entry.data.toString("utf8"));
20
+ if (!parts) {
21
+ return entry;
22
+ }
23
+ const { open, yaml, close, body } = parts;
24
+ return {
25
+ ...entry,
26
+ data: Buffer.from(`${open}${setYamlName(yaml, name)}${close}${body}`),
27
+ };
28
+ });
29
+ }
30
+ /**
31
+ * Reads package files from a source folder and optionally rewrites Skill
32
+ * metadata for an installed alias.
33
+ */
34
+ export async function desiredEntries(source, rename, runtime) {
35
+ const entries = await readTree(source, runtime);
36
+ return rename ? renameSkillEntries(entries, rename) : entries;
37
+ }
38
+ async function removeEmptyDirectories(directory) {
39
+ for (const child of await readdir(directory)) {
40
+ const path = join(directory, child);
41
+ if ((await lstat(path)).isDirectory()) {
42
+ await removeEmptyDirectories(path);
43
+ if (!(await readdir(path)).length) {
44
+ await rmdir(path);
45
+ }
46
+ }
47
+ }
48
+ }
49
+ /**
50
+ * Mirrors entries into an existing folder file by file. The folder itself is never
51
+ * replaced, so harness file watchers observe edits instead of a vanished directory.
52
+ */
53
+ export async function mirrorTree(directory, entries, runtime) {
54
+ assertPackagePaths(entries, runtime.platform);
55
+ await mkdir(directory, { recursive: true, mode: POSIX_MODE.executableFile });
56
+ const wanted = new Map(entries.map((entry) => [entry.path, entry]));
57
+ let current = [];
58
+ try {
59
+ current = await readTree(directory, runtime);
60
+ }
61
+ catch {
62
+ await rm(directory, { recursive: true, force: true });
63
+ await mkdir(directory, {
64
+ recursive: true,
65
+ mode: POSIX_MODE.executableFile,
66
+ });
67
+ }
68
+ for (const existing of current) {
69
+ if (!wanted.has(existing.path)) {
70
+ await rm(join(directory, existing.path), { force: true });
71
+ }
72
+ }
73
+ // Emptied folders must go first: a new file may take one's exact path.
74
+ await removeEmptyDirectories(directory);
75
+ for (const entry of entries) {
76
+ const path = join(directory, entry.path);
77
+ const existing = current.find((item) => item.path === entry.path);
78
+ const mode = entry.executable
79
+ ? POSIX_MODE.executableFile
80
+ : POSIX_MODE.regularFile;
81
+ if (existing?.data.equals(entry.data)) {
82
+ if (existing.executable !== entry.executable) {
83
+ await chmod(path, mode);
84
+ }
85
+ continue;
86
+ }
87
+ await writeAtomic(path, entry.data, {
88
+ mode,
89
+ directoryMode: POSIX_MODE.executableFile,
90
+ });
91
+ }
92
+ }
@@ -1,31 +1,58 @@
1
- import { readFile, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { resolveAssets } from "../asset-selection/index.js";
4
- import { localRepoSource } from "./source.js";
1
+ import { localRepoSource } from "./repo-source.js";
2
+ import { z } from "zod";
3
+ import { localWorkspaceFiles } from "../../config/paths.js";
4
+ import { readJsonIfExists, writeAtomic } from "../../shared/files.js";
5
+ import { POSIX_MODE } from "../../shared/constants.js";
6
+ import { rm } from "node:fs/promises";
5
7
  /** How assets in the kept local folder are addressed next to a shared workspace. */
6
8
  export const LOCAL_ORIGIN = "local";
7
- const MOVED_FILE = ".barndog-moved.json";
9
+ const movedSchema = z.array(z.looseObject({
10
+ kind: z.string(),
11
+ path: z.string(),
12
+ name: z.string(),
13
+ /** Scope it was moved to; knowledge has none. */
14
+ originId: z.string().optional(),
15
+ /**
16
+ * The local version that was moved, so an edit made since keeps the local
17
+ * copy. Moves recorded before this was kept have none.
18
+ */
19
+ version: z.string().optional(),
20
+ /** Where it went, as `local list` names it: a scope or a repository. */
21
+ target: z.string().optional(),
22
+ /** The pull request it waits for, when the move needs a review. */
23
+ url: z.string().nullable().optional(),
24
+ }));
25
+ /** Where a move is going, as people read it: its pull request, else the destination. */
26
+ export const moveDestination = (entry) => entry.url ?? entry.target ?? "the shared workspace";
27
+ /**
28
+ * Reads and validates movement records in a workspace folder; an absent file
29
+ * means nothing is moving.
30
+ */
8
31
  export async function readMoved(folder) {
9
- try {
10
- return JSON.parse(await readFile(join(folder, MOVED_FILE), "utf8"));
11
- }
12
- catch (error) {
13
- if (error.code === "ENOENT")
14
- return [];
15
- throw error;
16
- }
32
+ return ((await readJsonIfExists(localWorkspaceFiles(folder).moved, movedSchema)) ??
33
+ []);
17
34
  }
18
- export async function recordMoved(folder, added) {
19
- const kept = (await readMoved(folder)).filter((entry) => !added.some((asset) => asset.path === entry.path));
20
- await writeFile(join(folder, MOVED_FILE), JSON.stringify([...kept, ...added], null, 2) + "\n");
35
+ /**
36
+ * Writes movement records in the folder, replacing prior entries with the same
37
+ * local path and dropping the `finished` ones.
38
+ */
39
+ export async function recordMoved(folder, added, finished = []) {
40
+ const kept = (await readMoved(folder)).filter((entry) => !finished.includes(entry.path) &&
41
+ !added.some((asset) => asset.path === entry.path));
42
+ const next = [...kept, ...added];
43
+ if (!next.length) {
44
+ await rm(localWorkspaceFiles(folder).moved, { force: true });
45
+ return;
46
+ }
47
+ await writeAtomic(localWorkspaceFiles(folder).moved, JSON.stringify(next, null, 2) + "\n", { mode: POSIX_MODE.regularFile });
21
48
  }
22
49
  /** The local folder, when it runs alongside a Git or Cloud workspace. */
23
- export function localOverlay(settings, home) {
24
- if (settings.version !== 2 ||
25
- !settings.localWorkspace ||
26
- (!settings.connection && !settings.gitWorkspace))
50
+ export function localOverlay(settings, runtime) {
51
+ if (!settings.localWorkspace ||
52
+ (!settings.connection && !settings.gitWorkspace)) {
27
53
  return undefined;
28
- return localRepoSource(settings.localWorkspace, home);
54
+ }
55
+ return localRepoSource(settings.localWorkspace, runtime);
29
56
  }
30
57
  /** Local copies step aside once what was moved exists in the shared workspace. */
31
58
  export async function activeLocal(overlay, shared) {
@@ -42,6 +69,10 @@ export async function activeLocal(overlay, shared) {
42
69
  knowledge: model.knowledge.filter((doc) => !retired("knowledge", doc.path)),
43
70
  };
44
71
  }
72
+ /**
73
+ * Adds active local assets and their recommended distribution to a shared
74
+ * catalog without mutating the input.
75
+ */
45
76
  export async function mergeLocalCatalog(catalog, overlay) {
46
77
  const { model, assets } = await activeLocal(overlay, [...catalog.assets]);
47
78
  const local = assets.map((asset) => ({
@@ -70,30 +101,6 @@ export async function mergeLocalCatalog(catalog, overlay) {
70
101
  ],
71
102
  };
72
103
  }
73
- /** Once a moved asset exists in the shared workspace, this machine uses that copy. */
74
- export async function adoptMoved(overlay, catalog, state, persist) {
75
- const moved = await readMoved(overlay.label);
76
- const selected = new Set(resolveAssets(catalog, state).assets.map((entry) => entry.asset.id));
77
- const ids = [...state.individualAssetIds];
78
- const adopted = [];
79
- for (const entry of moved) {
80
- if (entry.adopted || !entry.originId)
81
- continue;
82
- const asset = catalog.assets.find((a) => a.kind === entry.kind &&
83
- a.name === entry.name &&
84
- a.origin.id === entry.originId);
85
- if (!asset)
86
- continue;
87
- if (!selected.has(asset.id))
88
- ids.push(asset.id);
89
- adopted.push({ ...entry, adopted: true });
90
- }
91
- if (persist && adopted.length)
92
- await recordMoved(overlay.label, adopted);
93
- return ids.length === state.individualAssetIds.length
94
- ? state
95
- : { ...state, individualAssetIds: ids };
96
- }
97
104
  /** Keeps every local asset selected, including ones added to the folder later. */
98
105
  export function withLocalSubscription(state, model) {
99
106
  return state.subscriptions.some((s) => s.scope.id === model.organizationId)
@@ -120,7 +127,7 @@ export function withOverlay(primary, overlay) {
120
127
  extraCacheKeys: [overlay.cacheKey],
121
128
  journal: primary.journal,
122
129
  catalog: async () => mergeLocalCatalog(await primary.catalog(), overlay),
123
- skillOrHookPackage: async (kind, reference) => (await owner(reference)).skillOrHookPackage(kind, reference),
130
+ packageFolder: async (kind, reference) => (await owner(reference)).packageFolder(kind, reference),
124
131
  mcpDefinition: async (reference) => (await owner(reference)).mcpDefinition(reference),
125
132
  invalidAssets: async () => new Map([
126
133
  ...(await primary.invalidAssets()),
@@ -0,0 +1,173 @@
1
+ import { directoryFingerprint, writePackage } from "./directory.js";
2
+ import { fixSteps, removeCommand } from "../../platform.js";
3
+ import { POSIX_MODE } from "../../shared/constants.js";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { mkdir, readdir, rename, rm, lstat } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { z } from "zod";
8
+ import { defaultLimits, parsePackage, } from "@barndog-ai/api-contract/package";
9
+ import { ApiError } from "@barndog-ai/api-contract";
10
+ import { apiClient } from "../auth/transport.js";
11
+ import { assetKinds, metadata } from "../asset-kinds/index.js";
12
+ import { assetFolders, packageKindList, } from "../../config/selection.js";
13
+ import { GIT_OBJECT_ID, UUID_V4 } from "../../shared/patterns.js";
14
+ import { CliError, PackageError } from "../../errors.js";
15
+ import { barndogPaths, packageManifest } from "../../config/paths.js";
16
+ import { ifExists, readIfExists, writeAtomic } from "../../shared/files.js";
17
+ /** One identity's cache partition: server, organization and developer never mix. */
18
+ /** `text` parsed as JSON, or undefined when it is missing or not JSON. */
19
+ function jsonOrUndefined(text) {
20
+ if (text === null) {
21
+ return undefined;
22
+ }
23
+ try {
24
+ return JSON.parse(text);
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ export function cacheKey(conn) {
31
+ const server = createHash("sha256").update(conn.server).digest("hex");
32
+ return join(server, conn.organizationId, conn.developerId);
33
+ }
34
+ /**
35
+ * Deletes cached versions nothing installs any more. Every cached version was
36
+ * downloaded from the workspace, so an older one can always be fetched again.
37
+ * Other identities' caches are left alone.
38
+ */
39
+ export async function pruneCache(key, runtime, keep) {
40
+ const { home } = runtime;
41
+ const root = barndogPaths(home).packageCache(key);
42
+ let removed = 0;
43
+ const children = async (path) => (await ifExists(readdir(path))) ?? [];
44
+ for (const parent of packageKindList.map((kind) => join(root, assetFolders[kind]))) {
45
+ for (const asset of await children(parent)) {
46
+ if (!UUID_V4.test(asset)) {
47
+ continue;
48
+ }
49
+ const directory = join(parent, asset);
50
+ for (const revision of await children(directory)) {
51
+ const path = join(directory, revision);
52
+ if (keep.has(path)) {
53
+ continue;
54
+ }
55
+ if (!GIT_OBJECT_ID.test(revision) && !revision.startsWith(".stage-")) {
56
+ continue;
57
+ }
58
+ await rm(path, { recursive: true, force: true });
59
+ removed++;
60
+ }
61
+ if (!(await children(directory)).length) {
62
+ await rm(directory, { recursive: true, force: true });
63
+ }
64
+ }
65
+ }
66
+ return removed;
67
+ }
68
+ /** Returns the immutable cached folder for a revision, loading it only when absent. */
69
+ export async function storePackage(kind, asset, { key, runtime }, load) {
70
+ const { home } = runtime;
71
+ const parent = join(barndogPaths(home).packageCache(key), assetFolders[kind], asset.id);
72
+ await mkdir(parent, { recursive: true, mode: POSIX_MODE.privateDirectory });
73
+ const check = async (root) => {
74
+ // A missing or unreadable manifest means the same as a wrong fingerprint.
75
+ const saved = z
76
+ .object({ fingerprint: z.string() })
77
+ .safeParse(jsonOrUndefined(await readIfExists(packageManifest(root))));
78
+ if (!saved.success ||
79
+ (await directoryFingerprint(join(root, asset.name), runtime)) !==
80
+ saved.data.fingerprint) {
81
+ throw new CliError(`The downloaded copy of ${asset.name} in ${root} was changed on this machine, so BarnDog won't use it.`, "Delete that folder; the next sync downloads it again.", {
82
+ command: fixSteps([removeCommand(root, runtime.platform), "barndog sync"], runtime.platform),
83
+ });
84
+ }
85
+ };
86
+ for (const revision of await readdir(parent)) {
87
+ if (GIT_OBJECT_ID.test(revision)) {
88
+ await check(join(parent, revision));
89
+ }
90
+ }
91
+ const target = join(parent, asset.revision);
92
+ if (await ifExists(lstat(target))) {
93
+ await check(target);
94
+ return join(target, asset.name);
95
+ }
96
+ const entries = await load();
97
+ const stage = join(parent, `.stage-${randomUUID()}`);
98
+ try {
99
+ await writePackage(join(stage, asset.name), entries, runtime);
100
+ // Read back, so Windows (no executable bits) records what `check` will see.
101
+ await writeAtomic(packageManifest(stage), JSON.stringify({
102
+ fingerprint: await directoryFingerprint(join(stage, asset.name), runtime),
103
+ }));
104
+ await rename(stage, target);
105
+ }
106
+ finally {
107
+ await rm(stage, { recursive: true, force: true });
108
+ }
109
+ return join(target, asset.name);
110
+ }
111
+ /**
112
+ * Reads and unpacks a package download within the package size limits. With
113
+ * `commit`, refuses a package whose ETag names another revision. `subject`
114
+ * names the package in errors.
115
+ */
116
+ export async function unpackDownload(download, options) {
117
+ const { kind, commit, subject, fix } = options;
118
+ let response;
119
+ try {
120
+ ({ response } = await download);
121
+ }
122
+ catch (error) {
123
+ if (error instanceof ApiError) {
124
+ throw new CliError(`Downloading ${subject} failed (${error.status}). Try again.`, fix, { cause: error });
125
+ }
126
+ throw error;
127
+ }
128
+ if (commit && response.headers.get("etag") !== `"${commit}"`) {
129
+ throw new CliError(`The server changed ${subject} while it was downloading. Try again.`, fix);
130
+ }
131
+ if (!response.body) {
132
+ throw new Error("The server sent a package download with no body");
133
+ }
134
+ let size = 0;
135
+ const chunks = [];
136
+ for await (const chunk of response.body) {
137
+ size += chunk.length;
138
+ if (size > defaultLimits.compressed) {
139
+ throw new PackageError("PACKAGE_TOO_LARGE");
140
+ }
141
+ chunks.push(chunk);
142
+ }
143
+ return parsePackage(Buffer.concat(chunks), defaultLimits, assetKinds[kind].manifest);
144
+ }
145
+ /** The published-package route of each kind. */
146
+ const packageDownloads = {
147
+ skill: (client, asset) => client.GET("/v1/skills/{id}/versions/{version}/package", {
148
+ params: { path: { id: asset.id, version: asset.version.number } },
149
+ parseAs: "stream",
150
+ }),
151
+ hook: (client, asset) => client.GET("/v1/hooks/{id}/versions/{version}/package", {
152
+ params: { path: { id: asset.id, version: asset.version.number } },
153
+ parseAs: "stream",
154
+ }),
155
+ };
156
+ /**
157
+ * Returns a cached package or downloads and validates its revision, size and
158
+ * metadata before storing it.
159
+ */
160
+ export async function cachedPackage(kind, asset, conn, runtime) {
161
+ return storePackage(kind, { id: asset.id, name: asset.name, revision: asset.version.commit }, { key: cacheKey(conn), runtime }, async () => {
162
+ const entries = await unpackDownload(packageDownloads[kind](apiClient(conn.server, runtime), asset), {
163
+ kind,
164
+ commit: asset.version.commit,
165
+ subject: asset.name,
166
+ fix: "barndog sync",
167
+ });
168
+ if (metadata(entries, kind).name !== asset.name) {
169
+ throw new Error(`The server sent a package whose name isn't ${asset.name}`);
170
+ }
171
+ return entries;
172
+ });
173
+ }