barndog 0.2.0 → 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 (93) hide show
  1. package/README.md +29 -27
  2. package/dist/commands/add.js +1 -0
  3. package/dist/commands/adopt.js +91 -0
  4. package/dist/commands/asset-install.js +1 -0
  5. package/dist/commands/asset-list.js +7 -2
  6. package/dist/commands/availability.js +25 -8
  7. package/dist/commands/capabilities.js +8 -2
  8. package/dist/commands/collaboration.js +22 -2
  9. package/dist/commands/harnesses.js +74 -0
  10. package/dist/commands/mcp-env.js +78 -0
  11. package/dist/commands/mcp.js +4 -2
  12. package/dist/commands/status.js +2 -1
  13. package/dist/commands/sync.js +2 -1
  14. package/dist/commands/workspace.js +43 -5
  15. package/dist/config/paths.js +19 -0
  16. package/dist/config/settings.js +5 -3
  17. package/dist/config/state.js +18 -6
  18. package/dist/features/adoption/adopt.js +234 -0
  19. package/dist/features/adoption/copies.js +29 -0
  20. package/dist/features/adoption/originals.js +116 -0
  21. package/dist/features/adoption/record.js +120 -0
  22. package/dist/features/adoption/restore.js +28 -0
  23. package/dist/features/adoption/scan.js +482 -0
  24. package/dist/features/adoption/undo.js +42 -0
  25. package/dist/features/asset-kinds/index.js +9 -0
  26. package/dist/features/auth/credentials.js +7 -14
  27. package/dist/features/auth/session.js +4 -5
  28. package/dist/features/auth/transport.js +3 -2
  29. package/dist/features/collaboration/workspace-git.js +13 -7
  30. package/dist/features/collaboration/workspace-github.js +2 -1
  31. package/dist/features/collaboration/workspace-store.js +23 -3
  32. package/dist/features/collaboration/workspace.js +22 -2
  33. package/dist/features/doctor/index.js +24 -2
  34. package/dist/features/environment/harnesses.js +36 -0
  35. package/dist/features/environment/moves.js +171 -0
  36. package/dist/features/environment/names.js +10 -6
  37. package/dist/features/environment/operations.js +7 -7
  38. package/dist/features/environment/stage.js +25 -1
  39. package/dist/features/environment/sync.js +17 -6
  40. package/dist/features/environment/writes.js +55 -8
  41. package/dist/features/hooks/compatibility.js +11 -5
  42. package/dist/features/hooks/divergence.js +30 -9
  43. package/dist/features/hooks/test.js +25 -25
  44. package/dist/features/imports/discover.js +1 -1
  45. package/dist/features/imports/local.js +15 -2
  46. package/dist/features/imports/remote.js +2 -1
  47. package/dist/features/inventory/index.js +13 -2
  48. package/dist/features/inventory/show.js +74 -0
  49. package/dist/features/mcps/import.js +74 -21
  50. package/dist/features/mcps/index.js +12 -7
  51. package/dist/features/mcps/values.js +33 -0
  52. package/dist/features/migration/move.js +72 -17
  53. package/dist/features/migration/promote.js +2 -0
  54. package/dist/features/native/adapters.js +20 -6
  55. package/dist/features/native/configuration.js +8 -4
  56. package/dist/features/native/secret-values.js +74 -0
  57. package/dist/features/secrets/index.js +77 -0
  58. package/dist/features/workspace/format.js +13 -9
  59. package/dist/features/workspace/git.js +11 -4
  60. package/dist/features/workspace/overlay.js +23 -36
  61. package/dist/features/workspace/packages.js +16 -3
  62. package/dist/features/workspace/publish.js +1 -1
  63. package/dist/features/workspace/repo-source.js +4 -3
  64. package/dist/features/workspace/setup.js +12 -3
  65. package/dist/features/workspace/snapshot.js +7 -1
  66. package/dist/harnesses/claude.js +2 -2
  67. package/dist/harnesses/codex.js +19 -9
  68. package/dist/harnesses/cursor.js +2 -2
  69. package/dist/harnesses/formats.js +12 -5
  70. package/dist/harnesses/opencode.js +3 -6
  71. package/dist/platform.js +39 -11
  72. package/dist/program.js +51 -3
  73. package/dist/shared/files.js +35 -0
  74. package/dist/shared/lock.js +87 -23
  75. package/dist/shared/patterns.js +8 -0
  76. package/dist/shared/shell.js +0 -2
  77. package/dist/ui/add-hook.js +8 -2
  78. package/dist/ui/add-mcp.js +69 -6
  79. package/dist/ui/add-skills.js +7 -5
  80. package/dist/ui/adopt.js +197 -0
  81. package/dist/ui/assets.js +5 -3
  82. package/dist/ui/auth.js +2 -1
  83. package/dist/ui/clash.js +2 -3
  84. package/dist/ui/connection.js +7 -2
  85. package/dist/ui/harness-picker.js +18 -0
  86. package/dist/ui/move.js +48 -2
  87. package/dist/ui/onboarding.js +40 -27
  88. package/dist/ui/output.js +3 -1
  89. package/dist/ui/package-details.js +34 -0
  90. package/dist/ui/scope-install.js +4 -1
  91. package/dist/ui/secret-input.js +19 -0
  92. package/dist/ui/selection.js +3 -1
  93. package/package.json +1 -1
@@ -0,0 +1,77 @@
1
+ import { chmod, lstat, mkdir, readFile } from "node:fs/promises";
2
+ import { z } from "zod";
3
+ import { barndogPaths } from "../../config/paths.js";
4
+ import { CliError } from "../../errors.js";
5
+ import { privatePermissions, protectPrivate, removeCommand, } from "../../platform.js";
6
+ import { POSIX_MODE } from "../../shared/constants.js";
7
+ import { ifExists, writeAtomic } from "../../shared/files.js";
8
+ import { withPidLock } from "../../shared/lock.js";
9
+ import { VARIABLE_NAME } from "../../shared/patterns.js";
10
+ import { posixQuote } from "../../shared/shell.js";
11
+ const variable = z.string().regex(new RegExp(`^${VARIABLE_NAME.source}$`));
12
+ const secretsSchema = z.strictObject({
13
+ version: z.literal(1),
14
+ values: z.record(variable, z.string()),
15
+ });
16
+ /** The kept values; empty when there's no file yet. */
17
+ export async function readSecrets(runtime) {
18
+ const path = barndogPaths(runtime.home).secrets;
19
+ const info = await ifExists(lstat(path));
20
+ if (!info) {
21
+ return {};
22
+ }
23
+ if (!info.isFile()) {
24
+ throw new CliError(`${path} isn't a regular file, so BarnDog can't read the MCP values it keeps.`, "Delete it, then set the values again with barndog mcp env set.", { command: removeCommand(path, runtime.platform) });
25
+ }
26
+ // Always passes on Windows, where the ACL set on every write keeps it private.
27
+ if (!privatePermissions(info.mode, runtime.platform)) {
28
+ throw new CliError(`${path} can be read by other users on this machine.`, "Make it readable and writable only by you.", { command: `chmod 600 ${posixQuote(path)}` });
29
+ }
30
+ const parsed = secretsSchema.safeParse(parseJson(await readFile(path, "utf8")));
31
+ if (!parsed.success) {
32
+ throw new CliError(`${path} is damaged, so BarnDog can't read the MCP values it keeps.`, "Delete it, then set the values again with barndog mcp env set.", { command: removeCommand(path, runtime.platform) });
33
+ }
34
+ return parsed.data.values;
35
+ }
36
+ function parseJson(text) {
37
+ try {
38
+ return JSON.parse(text);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /** Saves `changes` (a value, or null to forget it) under a lock; returns the file's path. */
45
+ export async function updateSecrets(changes, runtime) {
46
+ const paths = barndogPaths(runtime.home);
47
+ for (const name of Object.keys(changes)) {
48
+ if (!variable.safeParse(name).success) {
49
+ throw new CliError(`${name} isn't an environment variable name.`, "Use letters, digits and underscores, not starting with a digit.");
50
+ }
51
+ }
52
+ await mkdir(paths.root, {
53
+ recursive: true,
54
+ mode: POSIX_MODE.privateDirectory,
55
+ });
56
+ await chmod(paths.root, POSIX_MODE.privateDirectory);
57
+ await protectPrivate(paths.root, runtime);
58
+ await withPidLock(paths.secretsLock, {
59
+ starting: "Another change to the kept MCP values is starting. Wait for it to finish, then try again.",
60
+ running: "Another change to the kept MCP values is running. Wait for it to finish, then try again.",
61
+ }, async () => {
62
+ const values = {
63
+ ...(await readSecrets(runtime)),
64
+ };
65
+ for (const [name, value] of Object.entries(changes)) {
66
+ if (value === null) {
67
+ delete values[name];
68
+ }
69
+ else {
70
+ values[name] = value;
71
+ }
72
+ }
73
+ await writeAtomic(paths.secrets, JSON.stringify({ version: 1, values }, null, 2) + "\n");
74
+ await protectPrivate(paths.secrets, runtime);
75
+ });
76
+ return paths.secrets;
77
+ }
@@ -73,12 +73,16 @@ function renderConfig(config) {
73
73
  optional: [],
74
74
  });
75
75
  }
76
- /**
77
- * Parses barndog.yaml and reports schema-invalid fields in a CliError.
78
- * Malformed YAML can throw a parser error before schema validation.
79
- */
76
+ /** Parses barndog.yaml; malformed YAML and invalid fields are a CliError. */
80
77
  export function parseConfig(text) {
81
- const parsed = configSchema.safeParse(parse(text));
78
+ let value;
79
+ try {
80
+ value = parse(text);
81
+ }
82
+ catch (error) {
83
+ throw new CliError(`${CONFIG_FILE} isn't valid YAML: ${friendlyMessage(error)}`, `Fix the YAML in ${CONFIG_FILE}, then try again`, { cause: error });
84
+ }
85
+ const parsed = configSchema.safeParse(value);
82
86
  if (!parsed.success) {
83
87
  throw new CliError(`${CONFIG_FILE} is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "file"}: ${issue.message}`).join("; ")}`);
84
88
  }
@@ -186,11 +190,11 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
186
190
  const assets = [];
187
191
  const knowledge = [];
188
192
  const invalidKnowledge = [];
189
- const named = (path, name) => {
190
- if (validAssetName(name)) {
193
+ const named = (path, name, rule = { validName: validAssetName, nameRule: NAME_RULE }) => {
194
+ if (rule.validName(name)) {
191
195
  return true;
192
196
  }
193
- problems.push({ path, reason: NAME_RULE });
197
+ problems.push({ path, reason: rule.nameRule, badName: true });
194
198
  return false;
195
199
  };
196
200
  function packageEntries(root) {
@@ -260,7 +264,7 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
260
264
  continue;
261
265
  }
262
266
  const name = file.replace(/\.ya?ml$/, "");
263
- if (!named(entry.path, name)) {
267
+ if (!named(entry.path, name, assetKinds.mcp)) {
264
268
  continue;
265
269
  }
266
270
  add("mcp", name, entry, () => {
@@ -1,3 +1,4 @@
1
+ import { fixSteps, gitAccessCommand } from "../../platform.js";
1
2
  import { execFile, spawn } from "node:child_process";
2
3
  import { stat } from "node:fs/promises";
3
4
  import { CliError } from "../../errors.js";
@@ -191,13 +192,12 @@ export async function remoteHead(url, runtime, allowPrompt = false) {
191
192
  }
192
193
  catch (error) {
193
194
  if (error instanceof GitError) {
194
- throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, `git clone ${url}`, { cause: error });
195
+ throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, gitAccessCommand(url, runtime.platform), { cause: error });
195
196
  }
196
197
  throw error;
197
198
  }
198
199
  return parseRemoteHead(output, url);
199
200
  }
200
- const identityHint = 'git config --global user.email "you@example.com"';
201
201
  /**
202
202
  * Git's stderr when a commit has no author: `*** Please tell me who you are.`
203
203
  * followed by the `git config` commands to run.
@@ -206,9 +206,16 @@ const identityHint = 'git config --global user.email "you@example.com"';
206
206
  */
207
207
  export const UNKNOWN_IDENTITY = /tell me who you are/i;
208
208
  /** Git's "who are you" failure is common on new machines and has one clear fix. */
209
- export function explainIdentity(error) {
209
+ export function explainIdentity(error, platform) {
210
210
  if (error instanceof GitError && UNKNOWN_IDENTITY.test(error.stderr)) {
211
- throw new CliError("Git doesn't know who you are, so BarnDog can't make a commit.", identityHint, { cause: error });
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
+ });
212
219
  }
213
220
  throw error;
214
221
  }
@@ -1,9 +1,9 @@
1
- import { resolveAssets } from "../asset-selection/index.js";
2
1
  import { localRepoSource } from "./repo-source.js";
3
2
  import { z } from "zod";
4
3
  import { localWorkspaceFiles } from "../../config/paths.js";
5
4
  import { readJsonIfExists, writeAtomic } from "../../shared/files.js";
6
5
  import { POSIX_MODE } from "../../shared/constants.js";
6
+ import { rm } from "node:fs/promises";
7
7
  /** How assets in the kept local folder are addressed next to a shared workspace. */
8
8
  export const LOCAL_ORIGIN = "local";
9
9
  const movedSchema = z.array(z.looseObject({
@@ -12,12 +12,21 @@ const movedSchema = z.array(z.looseObject({
12
12
  name: z.string(),
13
13
  /** Scope it was moved to; knowledge has none. */
14
14
  originId: z.string().optional(),
15
- /** Set once the shared copy was selected, so removing it later sticks. */
16
- adopted: z.boolean().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(),
17
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";
18
27
  /**
19
28
  * Reads and validates movement records in a workspace folder; an absent file
20
- * means nothing has moved.
29
+ * means nothing is moving.
21
30
  */
22
31
  export async function readMoved(folder) {
23
32
  return ((await readJsonIfExists(localWorkspaceFiles(folder).moved, movedSchema)) ??
@@ -25,11 +34,17 @@ export async function readMoved(folder) {
25
34
  }
26
35
  /**
27
36
  * Writes movement records in the folder, replacing prior entries with the same
28
- * local path.
37
+ * local path and dropping the `finished` ones.
29
38
  */
30
- export async function recordMoved(folder, added) {
31
- const kept = (await readMoved(folder)).filter((entry) => !added.some((asset) => asset.path === entry.path));
32
- await writeAtomic(localWorkspaceFiles(folder).moved, JSON.stringify([...kept, ...added], null, 2) + "\n", { mode: POSIX_MODE.regularFile });
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 });
33
48
  }
34
49
  /** The local folder, when it runs alongside a Git or Cloud workspace. */
35
50
  export function localOverlay(settings, runtime) {
@@ -86,34 +101,6 @@ export async function mergeLocalCatalog(catalog, overlay) {
86
101
  ],
87
102
  };
88
103
  }
89
- /** Once a moved asset exists in the shared workspace, this machine uses that copy. */
90
- export async function adoptMoved(overlay, catalog, state, persist) {
91
- const moved = await readMoved(overlay.label);
92
- const selected = new Set(resolveAssets(catalog, state).assets.map((entry) => entry.asset.id));
93
- const ids = [...state.individualAssetIds];
94
- const adopted = [];
95
- for (const entry of moved) {
96
- if (entry.adopted || !entry.originId) {
97
- continue;
98
- }
99
- const asset = catalog.assets.find((a) => a.kind === entry.kind &&
100
- a.name === entry.name &&
101
- a.origin.id === entry.originId);
102
- if (!asset) {
103
- continue;
104
- }
105
- if (!selected.has(asset.id)) {
106
- ids.push(asset.id);
107
- }
108
- adopted.push({ ...entry, adopted: true });
109
- }
110
- if (persist && adopted.length) {
111
- await recordMoved(overlay.label, adopted);
112
- }
113
- return ids.length === state.individualAssetIds.length
114
- ? state
115
- : { ...state, individualAssetIds: ids };
116
- }
117
104
  /** Keeps every local asset selected, including ones added to the folder later. */
118
105
  export function withLocalSubscription(state, model) {
119
106
  return state.subscriptions.some((s) => s.scope.id === model.organizationId)
@@ -2,7 +2,7 @@ import { directoryFingerprint, writePackage } from "./directory.js";
2
2
  import { fixSteps, removeCommand } from "../../platform.js";
3
3
  import { POSIX_MODE } from "../../shared/constants.js";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { mkdir, readdir, readFile, rename, rm, lstat } from "node:fs/promises";
5
+ import { mkdir, readdir, rename, rm, lstat } from "node:fs/promises";
6
6
  import { join } from "node:path";
7
7
  import { z } from "zod";
8
8
  import { defaultLimits, parsePackage, } from "@barndog-ai/api-contract/package";
@@ -13,8 +13,20 @@ import { assetFolders, packageKindList, } from "../../config/selection.js";
13
13
  import { GIT_OBJECT_ID, UUID_V4 } from "../../shared/patterns.js";
14
14
  import { CliError, PackageError } from "../../errors.js";
15
15
  import { barndogPaths, packageManifest } from "../../config/paths.js";
16
- import { ifExists, writeAtomic } from "../../shared/files.js";
16
+ import { ifExists, readIfExists, writeAtomic } from "../../shared/files.js";
17
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
+ }
18
30
  export function cacheKey(conn) {
19
31
  const server = createHash("sha256").update(conn.server).digest("hex");
20
32
  return join(server, conn.organizationId, conn.developerId);
@@ -59,9 +71,10 @@ export async function storePackage(kind, asset, { key, runtime }, load) {
59
71
  const parent = join(barndogPaths(home).packageCache(key), assetFolders[kind], asset.id);
60
72
  await mkdir(parent, { recursive: true, mode: POSIX_MODE.privateDirectory });
61
73
  const check = async (root) => {
74
+ // A missing or unreadable manifest means the same as a wrong fingerprint.
62
75
  const saved = z
63
76
  .object({ fingerprint: z.string() })
64
- .safeParse(JSON.parse(await readFile(packageManifest(root), "utf8")));
77
+ .safeParse(jsonOrUndefined(await readIfExists(packageManifest(root))));
65
78
  if (!saved.success ||
66
79
  (await directoryFingerprint(join(root, asset.name), runtime)) !==
67
80
  saved.data.fingerprint) {
@@ -46,7 +46,7 @@ export async function commitFiles(repo, parent, change, options) {
46
46
  ...(parent ? ["-p", parent] : []),
47
47
  "-m",
48
48
  change.message,
49
- ], runtime, { repo, allowPrompt: options.allowPrompt }).catch(explainIdentity);
49
+ ], runtime, { repo, allowPrompt: options.allowPrompt }).catch((error) => explainIdentity(error, runtime.platform));
50
50
  }
51
51
  finally {
52
52
  await rm(index, { force: true });
@@ -1,10 +1,11 @@
1
+ import { gitAccessCommand } from "../../platform.js";
1
2
  import { POSIX_MODE, HOURS_PER_DAY, MILLISECONDS_PER_MINUTE, MINUTES_PER_HOUR, } from "../../shared/constants.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import { mkdir } from "node:fs/promises";
4
5
  import { join } from "node:path";
5
6
  import { CliError } from "../../errors.js";
6
7
  import { storePackage } from "./packages.js";
7
- import { loadWorkspace, NAME_RULE, } from "./format.js";
8
+ import { loadWorkspace, } from "./format.js";
8
9
  import { git, GitError, gitReason, gitText } from "./git.js";
9
10
  import { folderSnapshot, gitSnapshot } from "./snapshot.js";
10
11
  import { defined } from "../../shared/lookup.js";
@@ -41,7 +42,7 @@ function repoSource(backend, runtime) {
41
42
  return [
42
43
  ...invalidKnowledge.map((problem) => `Knowledge file ${problem.path} was skipped: ${problem.reason}`),
43
44
  ...problems
44
- .filter((problem) => problem.reason === NAME_RULE)
45
+ .filter((problem) => problem.badName)
45
46
  .map((problem) => `${problem.path} was skipped: ${problem.reason}. Rename it to deliver it.`),
46
47
  ];
47
48
  },
@@ -157,7 +158,7 @@ export function gitRepoSource(workspace, runtime, options = {}) {
157
158
  throw error;
158
159
  }
159
160
  if (!state.accepted) {
160
- throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, `git clone ${workspace.url}`, { cause: error });
161
+ throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, gitAccessCommand(workspace.url, runtime.platform), { cause: error });
161
162
  }
162
163
  notices.push(`Can't reach ${workspace.url}, so this uses what was fetched ${age(state.fetchedAt)} ago.`);
163
164
  return state.accepted;
@@ -1,3 +1,4 @@
1
+ import { gitAccessCommand } from "../../platform.js";
1
2
  import { POSIX_MODE } from "../../shared/constants.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { mkdir, rename, rm, writeFile } from "node:fs/promises";
@@ -9,6 +10,7 @@ import { commitFiles, pushCommit } from "./publish.js";
9
10
  import { ensureBareClone, fetchBranch, recordFetch, trackingRef, } from "./repo-source.js";
10
11
  import { barndogPaths } from "../../config/paths.js";
11
12
  import { readIfExists } from "../../shared/files.js";
13
+ import { errorCode } from "../../shared/values.js";
12
14
  /**
13
15
  * Branch name used when creating the first commit of an empty Git workspace.
14
16
  */
@@ -100,7 +102,7 @@ export async function cloneGitWorkspace(url, runtime) {
100
102
  await gitInTerminal(["clone", "--bare", "--", url, staging], runtime);
101
103
  }
102
104
  catch (error) {
103
- throw new CliError(`Git couldn't clone ${url}. Check that you have access, and that this URL is right.`, `git clone ${url}`, { cause: error });
105
+ throw new CliError(`Git couldn't clone ${url}. Check that you have access, and that this URL is right.`, gitAccessCommand(url, runtime.platform), { cause: error });
104
106
  }
105
107
  let commit;
106
108
  let branch;
@@ -143,11 +145,18 @@ export async function localWorkspace(runtime, path = barndogPaths(runtime.home).
143
145
  if (config !== null) {
144
146
  return { path, workspaceId: parseConfig(config).workspaceId };
145
147
  }
148
+ // barndog.yaml goes last, so a run that stopped part way is finished by the
149
+ // next one; files that run already wrote are kept as they are.
146
150
  const workspaceId = randomUUID();
147
- for (const file of skeleton({ workspaceId, name: "My workspace" })) {
151
+ const files = skeleton({ workspaceId, name: "My workspace" }).sort((a, b) => Number(a.path === CONFIG_FILE) - Number(b.path === CONFIG_FILE));
152
+ for (const file of files) {
148
153
  const target = join(path, file.path);
149
154
  await mkdir(dirname(target), { recursive: true });
150
- await writeFile(target, file.data, { flag: "wx" });
155
+ await writeFile(target, file.data, { flag: "wx" }).catch((error) => {
156
+ if (errorCode(error) !== "EEXIST" || file.path === CONFIG_FILE) {
157
+ throw error;
158
+ }
159
+ });
151
160
  }
152
161
  return { path, workspaceId };
153
162
  }
@@ -130,7 +130,13 @@ export async function gitSnapshot(repo, commit, runtime) {
130
130
  let offset = 0;
131
131
  for (const hash of unique) {
132
132
  const end = output.indexOf(LF_BYTE, offset);
133
- const size = Number(output.toString("utf8", offset, end).split(" ")[2]);
133
+ const header = output.toString("utf8", offset, end);
134
+ // `<hash> <type> <size>`, or `<hash> missing` for an absent object.
135
+ const [, type, sizeText] = header.split(" ");
136
+ const size = Number(sizeText);
137
+ if (end < 0 || type === "missing" || !Number.isSafeInteger(size)) {
138
+ throw new Error(`Git object ${hash} is missing from ${repo}: git cat-file answered "${header}"`);
139
+ }
134
140
  blobs.set(hash, output.subarray(end + 1, end + 1 + size));
135
141
  offset = end + 1 + size + 1;
136
142
  }
@@ -65,10 +65,10 @@ export const claude = {
65
65
  file: ".claude.json",
66
66
  files: [".claude.json"],
67
67
  path: ["mcpServers"],
68
- server: (definition) => jsonMcpServer(definition, {
68
+ server: (definition, _launcher, kept) => jsonMcpServer(definition, {
69
69
  reference: (variable) => `\${${variable}}`,
70
70
  typed: true,
71
- }),
71
+ }, kept),
72
72
  login: { command: ["claude", "mcp", "login"] },
73
73
  },
74
74
  configHome: {
@@ -1,36 +1,46 @@
1
1
  import { hookSpecificContext, nestedHookEntry, secretRefs } from "./formats.js";
2
2
  /**
3
3
  * Codex forwards variables by name (`env_vars`, `env_http_headers`) instead of
4
- * interpolating references, so secrets stay out of `config.toml`. It can't give
5
- * a stdio server a variable under another name; BarnDog's launcher does that.
4
+ * interpolating references. It can't give a stdio server a variable under
5
+ * another name; BarnDog's launcher does that. A value BarnDog keeps goes in
6
+ * `env` or `http_headers` as written, the way Codex stores values it's given.
6
7
  */
7
- function mcpServer(definition, launcher) {
8
- const refs = secretRefs(definition);
9
- const variables = Object.values(refs).map((ref) => ref.secretRef);
8
+ function mcpServer(definition, launcher, kept) {
9
+ const refs = Object.entries(secretRefs(definition));
10
+ const literal = refs.filter(([, ref]) => kept[ref.secretRef] !== undefined);
11
+ const forwarded = refs.filter(([, ref]) => kept[ref.secretRef] === undefined);
12
+ const values = Object.fromEntries(literal.map(([name, ref]) => [name, kept[ref.secretRef] ?? ""]));
13
+ const variables = forwarded.map(([, ref]) => ref.secretRef);
10
14
  if (definition.transport === "http") {
11
15
  return {
12
16
  url: definition.url,
13
- ...(variables.length
17
+ ...(literal.length ? { http_headers: values } : {}),
18
+ ...(forwarded.length
14
19
  ? {
15
- env_http_headers: Object.fromEntries(Object.entries(refs).map(([name, ref]) => [name, ref.secretRef])),
20
+ env_http_headers: Object.fromEntries(forwarded.map(([name, ref]) => [name, ref.secretRef])),
16
21
  }
17
22
  : {}),
18
23
  };
19
24
  }
20
- const renamed = Object.entries(refs).some(([name, ref]) => name !== ref.secretRef);
25
+ const inline = literal.length ? { env: values } : {};
26
+ const renamed = forwarded.some(([name, ref]) => name !== ref.secretRef);
21
27
  if (renamed) {
28
+ // The launcher checks only the variables it forwards; kept ones arrive in `env`.
29
+ const environment = Object.fromEntries(forwarded);
22
30
  return {
23
31
  command: process.execPath,
24
32
  args: [
25
33
  launcher,
26
- Buffer.from(JSON.stringify(definition)).toString("base64url"),
34
+ Buffer.from(JSON.stringify({ ...definition, environment })).toString("base64url"),
27
35
  ],
36
+ ...inline,
28
37
  env_vars: variables,
29
38
  };
30
39
  }
31
40
  return {
32
41
  command: definition.command,
33
42
  args: definition.args,
43
+ ...inline,
34
44
  env_vars: variables,
35
45
  };
36
46
  }
@@ -56,10 +56,10 @@ export const cursor = {
56
56
  file: ".cursor/mcp.json",
57
57
  files: [".cursor/mcp.json"],
58
58
  path: ["mcpServers"],
59
- server: (definition) => jsonMcpServer(definition, {
59
+ server: (definition, _launcher, kept) => jsonMcpServer(definition, {
60
60
  reference: (variable) => `\${env:${variable}}`,
61
61
  typed: false,
62
- }),
62
+ }, kept),
63
63
  login: { settings: "Settings → MCP" },
64
64
  },
65
65
  };
@@ -2,16 +2,23 @@
2
2
  export const secretRefs = (definition) => definition.transport === "stdio"
3
3
  ? definition.environment
4
4
  : definition.headers;
5
+ /**
6
+ * Each environment variable or header of a definition: the kept value when
7
+ * BarnDog keeps one, else the tool's reference to the local variable.
8
+ */
9
+ export function valuesOrReferences(definition, kept, reference) {
10
+ return Object.fromEntries(Object.entries(secretRefs(definition)).map(([name, ref]) => [
11
+ name,
12
+ kept[ref.secretRef] ?? reference(ref.secretRef),
13
+ ]));
14
+ }
5
15
  /**
6
16
  * A server entry for a tool that keeps `mcpServers` in JSON, as Claude Code and
7
17
  * Cursor do. They differ in how a value refers to a local environment variable
8
18
  * and in whether an entry must name its transport in `type`.
9
19
  */
10
- export function jsonMcpServer(definition, format) {
11
- const references = Object.fromEntries(Object.entries(secretRefs(definition)).map(([name, ref]) => [
12
- name,
13
- format.reference(ref.secretRef),
14
- ]));
20
+ export function jsonMcpServer(definition, format, kept) {
21
+ const references = valuesOrReferences(definition, kept, format.reference);
15
22
  const type = format.typed ? { type: definition.transport } : {};
16
23
  const some = Object.keys(references).length > 0;
17
24
  if (definition.transport === "http") {
@@ -1,16 +1,13 @@
1
1
  import { VARIABLE_NAME } from "../shared/patterns.js";
2
2
  import { asRecord, asStrings } from "../shared/values.js";
3
- import { secretRefs } from "./formats.js";
3
+ import { valuesOrReferences } from "./formats.js";
4
4
  /**
5
5
  * OpenCode's server entry (`mcp.servers.<name>` in opencode.jsonc): a stdio
6
6
  * server is `local` with the program and its arguments in one `command` list,
7
7
  * an HTTP server is `remote`. Values refer to a local variable as `{env:NAME}`.
8
8
  */
9
- function mcpServer(definition) {
10
- const references = Object.fromEntries(Object.entries(secretRefs(definition)).map(([name, ref]) => [
11
- name,
12
- `{env:${ref.secretRef}}`,
13
- ]));
9
+ function mcpServer(definition, _launcher, kept) {
10
+ const references = valuesOrReferences(definition, kept, (variable) => `{env:${variable}}`);
14
11
  const some = Object.keys(references).length > 0;
15
12
  if (definition.transport === "http") {
16
13
  return {
package/dist/platform.js CHANGED
@@ -6,8 +6,8 @@ import crossSpawn from "cross-spawn";
6
6
  import { promisify } from "node:util";
7
7
  import { CliError } from "./errors.js";
8
8
  import { POSIX_MODE } from "./shared/constants.js";
9
- import { ifExists } from "./shared/files.js";
10
- import { posixQuote, powershellQuote } from "./shared/shell.js";
9
+ import { ifExists, isInside } from "./shared/files.js";
10
+ import { PLAIN_WORD, posixQuote, powershellQuote } from "./shared/shell.js";
11
11
  import { errorCode } from "./shared/values.js";
12
12
  const execute = promisify(execFile);
13
13
  /**
@@ -21,6 +21,8 @@ const OS_VARIABLES = {
21
21
  /** Windows: `C:\Program Files` and its 32-bit twin. */
22
22
  programFiles: "ProgramFiles",
23
23
  programFilesX86: "ProgramFiles(x86)",
24
+ /** Windows: `C:\Windows`, which holds WSL's `bash.exe` launcher. */
25
+ systemRoot: "SystemRoot",
24
26
  /** Windows: `C:\Users\<you>\AppData\Local`, where per-user apps install. */
25
27
  localAppData: "LOCALAPPDATA",
26
28
  /** Linux: XDG Base Directory specification. */
@@ -86,16 +88,29 @@ export async function findExecutable(command, runtime) {
86
88
  const shellQuote = (value, platform) => isWindows(platform) ? powershellQuote(value) : posixQuote(value);
87
89
  /**
88
90
  * Fix hints name commands for the shell people type into: Bash or zsh on
89
- * macOS and Linux, PowerShell on Windows (Windows PowerShell 5 has no `&&`).
91
+ * macOS and Linux, PowerShell on Windows. Each step runs only when the one
92
+ * before it succeeded; Windows PowerShell 5 has no `&&`, so there each later
93
+ * step goes inside `if ($?) { … }`.
90
94
  */
91
95
  export function fixSteps(steps, platform) {
92
- return steps.join(isWindows(platform) ? "; " : " && ");
96
+ if (!isWindows(platform)) {
97
+ return steps.join(" && ");
98
+ }
99
+ return steps.reduceRight((rest, step) => (rest ? `${step}; if ($?) { ${rest} }` : step), "");
93
100
  }
94
101
  export function removeCommand(path, platform) {
95
102
  return isWindows(platform)
96
103
  ? `Remove-Item -Recurse -Force ${shellQuote(path, platform)}`
97
104
  : `rm -rf ${shellQuote(path, platform)}`;
98
105
  }
106
+ /** One word for the platform's shell, quoted only when it needs to be. */
107
+ export function shellWord(value, platform) {
108
+ return PLAIN_WORD.test(value) ? value : shellQuote(value, platform);
109
+ }
110
+ /** Checks that the user's Git credentials can read `url`; clones nothing. */
111
+ export function gitAccessCommand(url, platform) {
112
+ return `git ls-remote ${shellQuote(url, platform)}`;
113
+ }
99
114
  export function unsetCommand(variable, platform) {
100
115
  return isWindows(platform)
101
116
  ? `Remove-Item Env:${variable}`
@@ -119,8 +134,12 @@ export function encodedPowerShell(script) {
119
134
  ],
120
135
  };
121
136
  }
122
- /** A program run from a PowerShell line, keeping its exit code. */
123
- export const powershellCall = (args) => `& ${args.map(powershellQuote).join(" ")}; exit $LASTEXITCODE`;
137
+ /**
138
+ * A program run from a PowerShell line, keeping its exit code. A program that
139
+ * can't be found sets no `$LASTEXITCODE`, and `exit $null` would report
140
+ * success, so that case exits 1.
141
+ */
142
+ export const powershellCall = (args) => `& ${args.map(powershellQuote).join(" ")}; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE`;
124
143
  /**
125
144
  * A program's stdout. Starts through cross-spawn, which also runs Windows
126
145
  * `.cmd` and `.bat` shims (such as npm-installed tools) with safely quoted
@@ -135,17 +154,22 @@ export function programOutput(command, args, runtime, limits) {
135
154
  stdio: ["ignore", "pipe", "ignore"],
136
155
  windowsHide: true,
137
156
  });
138
- let stdout = "";
157
+ // Decoded once at the end, so a character split across chunks survives.
158
+ const chunks = [];
159
+ let length = 0;
139
160
  const fail = (reason) => {
140
161
  child.kill();
141
162
  reject(new Error(`${command} ${reason}`));
142
163
  };
143
164
  const timer = setTimeout(() => fail("timed out"), limits.timeoutMs);
144
165
  child.stdout?.on("data", (chunk) => {
145
- stdout += chunk.toString("utf8");
146
- if (stdout.length > limits.maxBytes) {
166
+ length += chunk.length;
167
+ if (length > limits.maxBytes) {
147
168
  fail("printed too much");
148
169
  }
170
+ else {
171
+ chunks.push(chunk);
172
+ }
149
173
  });
150
174
  child.once("error", (error) => {
151
175
  clearTimeout(timer);
@@ -154,7 +178,7 @@ export function programOutput(command, args, runtime, limits) {
154
178
  child.once("close", (code) => {
155
179
  clearTimeout(timer);
156
180
  if (code === 0) {
157
- resolve(stdout);
181
+ resolve(Buffer.concat(chunks).toString("utf8"));
158
182
  }
159
183
  else {
160
184
  reject(new Error(`${command} exited with code ${code}`));
@@ -181,8 +205,12 @@ export async function bashShell(runtime) {
181
205
  return { command: candidate, args: ["-c"] };
182
206
  }
183
207
  }
208
+ // `C:\Windows\System32\bash.exe` starts WSL's Linux, not the Bash tools run
209
+ // hooks in, so a Bash found there doesn't count.
184
210
  const bash = await findExecutable("bash", runtime);
185
- if (bash) {
211
+ const system = environmentValue(runtime, OS_VARIABLES.systemRoot);
212
+ if (bash &&
213
+ !(system && isInside(system.toLowerCase(), bash.toLowerCase(), paths))) {
186
214
  return { command: bash, args: ["-c"] };
187
215
  }
188
216
  throw new CliError("This Hook runs in Bash, which isn't installed.", "Install Git for Windows from https://gitforwindows.org, then try again.");