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
@@ -1,6 +1,7 @@
1
1
  import { POSIX_MODE } from "../../shared/constants.js";
2
2
  import { readState } from "../../config/state.js";
3
- import { mkdir, readFile } from "node:fs/promises";
3
+ import { mkdir, readFile, readdir } from "node:fs/promises";
4
+ import { randomUUID } from "node:crypto";
4
5
  import { basename, join } from "node:path";
5
6
  import { mcpDefinitionSchema, } from "@barndog-ai/api-contract";
6
7
  import { parse as parseJsonc } from "jsonc-parser";
@@ -10,15 +11,18 @@ import { readSettings, SetupRequiredError } from "../../config/settings.js";
10
11
  import { CliError } from "../../errors.js";
11
12
  import { adapters, harnesses, nativeFile, } from "../../harnesses/registry.js";
12
13
  import { locked } from "../environment/transaction.js";
13
- import { fileText, writeAtomic } from "../../shared/files.js";
14
+ import { fileText, ifExists, writeAtomic } from "../../shared/files.js";
14
15
  import { synchronize } from "../environment/sync.js";
15
16
  import { patchNative } from "../native/configuration.js";
16
- import { NAME_RULE } from "../workspace/format.js";
17
- import { validAssetName, VARIABLE_NAME } from "../../shared/patterns.js";
17
+ import { validMcpName, VARIABLE_NAME } from "../../shared/patterns.js";
18
+ import { assetKinds } from "../asset-kinds/index.js";
18
19
  import { LOCAL_ORIGIN } from "../workspace/overlay.js";
19
20
  import { ensureLocalWorkspace } from "../imports/local.js";
21
+ import { updateSecrets } from "../secrets/index.js";
20
22
  import { asRecord, asStrings, isRecord } from "../../shared/values.js";
21
23
  import { barndogPaths } from "../../config/paths.js";
24
+ /** Random characters that keep two backups of one file taken in the same millisecond apart. */
25
+ const BACKUP_SUFFIX_LENGTH = 8;
22
26
  const isServer = (value) => isRecord(value) &&
23
27
  ("command" in value || "url" in value || "httpUrl" in value);
24
28
  /** Accepts the shapes people copy: a harness's whole file, a name map, or one server. */
@@ -85,8 +89,17 @@ const SECRET_WORD = /api[-_]?key|token|secret|password/i;
85
89
  * @internal Exported for its table test in `src/tests/patterns.test.ts`.
86
90
  */
87
91
  export const looksSecret = (arg) => SECRET_WORD.test(arg) || arg.startsWith("sk-");
88
- /** Secrets are named, never stored: every literal becomes a variable to set locally. */
89
- function reference(key, value, fallback, notes) {
92
+ /**
93
+ * What to tell the developer about each literal: where BarnDog keeps it, or
94
+ * which variable to set. `kept` holds the variables BarnDog keeps.
95
+ */
96
+ export function literalNotes(literals, kept) {
97
+ return literals.map((literal) => kept.includes(literal.variable)
98
+ ? `BarnDog keeps the value of ${literal.variable} in ~/.barndog/secrets.json on this machine, never uploaded, and writes it into your coding tools.`
99
+ : `${literal.key} held a literal value, which BarnDog doesn't keep. Set ${literal.variable} in your environment, or keep it with barndog mcp env set ${literal.variable}.`);
100
+ }
101
+ /** Secrets are named, never shared: every literal becomes a variable the definition refers to. */
102
+ function reference(key, value, fallback, found) {
90
103
  const text = String(value);
91
104
  const whole = variableName(text);
92
105
  if (whole) {
@@ -94,10 +107,10 @@ function reference(key, value, fallback, notes) {
94
107
  }
95
108
  const inside = embeddedVariable(text);
96
109
  if (inside) {
97
- notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
110
+ found.notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
98
111
  return { secretRef: inside };
99
112
  }
100
- notes.push(`${key} held a literal value, which BarnDog doesn't store. Set ${fallback} in your environment.`);
113
+ found.literals.push({ key, variable: fallback, value: text });
101
114
  return { secretRef: fallback };
102
115
  }
103
116
  /**
@@ -115,6 +128,8 @@ function serverUrl(name, server) {
115
128
  }
116
129
  export function convertServer({ name, server }, description, oauth) {
117
130
  const notes = [];
131
+ const literals = [];
132
+ const found = { notes, literals };
118
133
  const type = typeof server.type === "string" ? server.type : undefined;
119
134
  if (type === "sse" || type === "ws") {
120
135
  throw new CliError(`${name} uses ${type} transport. BarnDog supports stdio and HTTP servers.`);
@@ -130,7 +145,7 @@ export function convertServer({ name, server }, description, oauth) {
130
145
  if (url) {
131
146
  const headers = {};
132
147
  for (const [key, value] of Object.entries(asRecord(server.headers ?? server.http_headers))) {
133
- headers[key] = reference(key, value, envName(`${name}_${key}`), notes);
148
+ headers[key] = reference(key, value, envName(`${name}_${key}`), found);
134
149
  }
135
150
  for (const [key, value] of Object.entries(asRecord(server.env_http_headers))) {
136
151
  if (typeof value === "string") {
@@ -160,7 +175,7 @@ export function convertServer({ name, server }, description, oauth) {
160
175
  }
161
176
  const environment = {};
162
177
  for (const [key, value] of Object.entries(asRecord(server.env))) {
163
- environment[key] = reference(key, value, key, notes);
178
+ environment[key] = reference(key, value, key, found);
164
179
  }
165
180
  for (const key of asStrings(server.env_vars)) {
166
181
  environment[key] = { secretRef: key };
@@ -183,7 +198,7 @@ export function convertServer({ name, server }, description, oauth) {
183
198
  if (!parsed.success) {
184
199
  throw new CliError(`${name} can't be added: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "server"}: ${issue.message}`).join("; ")}`);
185
200
  }
186
- return { name, definition: parsed.data, notes };
201
+ return { name, definition: parsed.data, notes, literals };
187
202
  }
188
203
  /** How an imported HTTP server authenticates. */
189
204
  function httpAuthentication(signsIn, headers) {
@@ -230,7 +245,14 @@ export async function harnessServers(runtime) {
230
245
  const codexFile = nativeFile("codex", "mcp", home);
231
246
  const codex = await fileText(codexFile).catch(() => null);
232
247
  if (codex) {
233
- add("codex", { label: adapters.codex.name, file: codexFile }, parseToml(codex).mcp_servers);
248
+ let settings;
249
+ try {
250
+ settings = parseToml(codex);
251
+ }
252
+ catch (error) {
253
+ throw new CliError(`${codexFile} isn't valid TOML, so BarnDog can't read the MCP servers in it.`, `Fix ${codexFile}, then try again`, { cause: error });
254
+ }
255
+ add("codex", { label: adapters.codex.name, file: codexFile }, settings.mcp_servers);
234
256
  }
235
257
  const { mcp } = adapters.opencode;
236
258
  for (const relative of mcp.files) {
@@ -258,6 +280,21 @@ export async function conflictingEntries(name, runtime) {
258
280
  server: entry.native,
259
281
  }));
260
282
  }
283
+ /**
284
+ * The local MCP server named `name`, ignoring case: macOS and Windows disks
285
+ * usually treat `Docs.yaml` and `docs.yaml` as one file. Null when none is.
286
+ */
287
+ export async function localMcpNamed(name, runtime) {
288
+ const settings = await readSettings(runtime.home);
289
+ const folder = settings?.localWorkspace
290
+ ? join(settings.localWorkspace.path, "org", assetKinds.mcp.folder)
291
+ : null;
292
+ const files = folder ? ((await ifExists(readdir(folder))) ?? []) : [];
293
+ const names = files
294
+ .filter((file) => file.endsWith(".yaml"))
295
+ .map((file) => file.slice(0, -".yaml".length));
296
+ return (names.find((other) => other.toLowerCase() === name.toLowerCase()) ?? null);
297
+ }
261
298
  /**
262
299
  * Writes converted MCP servers and synchronizes them. Existing local workspace
263
300
  * names are always rejected; replace permits backing up and removing
@@ -265,29 +302,37 @@ export async function conflictingEntries(name, runtime) {
265
302
  */
266
303
  export async function addMcpServers(servers, options, runtime) {
267
304
  const { home } = runtime;
268
- const invalid = servers.filter(({ name }) => !validAssetName(name));
305
+ const invalid = servers.filter(({ name }) => !validMcpName(name));
269
306
  if (invalid.length) {
270
- throw new CliError(`${invalid.map(({ name }) => name).join(", ")} can't be used as ${invalid.length === 1 ? "an MCP name" : "MCP names"}. ${NAME_RULE}. To add one, save only that server to a JSON file under a new name.`, "barndog mcp add <new-name> --file <path>");
307
+ throw new CliError(`${invalid.map(({ name }) => name).join(", ")} can't be used as ${invalid.length === 1 ? "an MCP name" : "MCP names"}. ${assetKinds.mcp.nameRule}.`, "barndog mcp add <name> --as <new-name>");
271
308
  }
272
309
  return locked(runtime, async () => {
273
310
  const workspace = await ensureLocalWorkspace(runtime);
274
311
  for (const { name } of servers) {
275
- const target = join(workspace.path, "org/mcp", `${name}.yaml`);
276
- if (await fileText(target).catch(() => null)) {
277
- throw new CliError(`A local MCP server named ${name} already exists.`, `barndog mcp add ${name}-2 --file <path>`);
312
+ const existing = await localMcpNamed(name, runtime);
313
+ if (existing !== null) {
314
+ throw new CliError(existing === name
315
+ ? `A local MCP server named ${name} already exists.`
316
+ : `${name} differs from the local MCP server ${existing} only in case, and they'd share one file on this disk.`, `barndog mcp add ${name} --as <new-name>`);
278
317
  }
279
318
  const conflicts = await conflictingEntries(name, runtime);
280
319
  if (conflicts.length && !options.replace) {
281
320
  throw new CliError(`${name} is already configured in ${conflicts.map((c) => c.file).join(" and ")}. Replacing it is required for BarnDog to manage it.`, `barndog mcp add ${name} --replace`);
282
321
  }
283
322
  }
323
+ // One backup per settings file, taken before its first change, so a file
324
+ // that holds several of the servers is backed up as the user left it.
325
+ const backedUp = new Set();
284
326
  const backups = [];
285
327
  for (const { name, definition } of servers) {
286
328
  for (const conflict of await conflictingEntries(name, runtime)) {
287
329
  const text = await readFile(conflict.file, "utf8");
288
- const backup = join(barndogPaths(home).migrations, `${basename(conflict.file)}-${Date.now()}.bak`);
289
- await writeAtomic(backup, text);
290
- backups.push(backup);
330
+ if (!backedUp.has(conflict.file)) {
331
+ const backup = join(barndogPaths(home).migrations, `${basename(conflict.file)}-${Date.now()}-${randomUUID().slice(0, BACKUP_SUFFIX_LENGTH)}.bak`);
332
+ await writeAtomic(backup, text);
333
+ backedUp.add(conflict.file);
334
+ backups.push(backup);
335
+ }
291
336
  await writeAtomic(conflict.file, patchNative(text, [
292
337
  {
293
338
  id: "import",
@@ -303,12 +348,20 @@ export async function addMcpServers(servers, options, runtime) {
303
348
  await mkdir(join(workspace.path, "org/mcp"), { recursive: true });
304
349
  await writeAtomic(join(workspace.path, "org/mcp", `${name}.yaml`), stringify(definition), { mode: POSIX_MODE.regularFile });
305
350
  }
351
+ // Saved before the sync, which writes them into the tools' settings.
352
+ const kept = servers.flatMap((s) => s.literals.filter((literal) => options.keep.includes(literal.variable)));
353
+ if (kept.length) {
354
+ await updateSecrets(Object.fromEntries(kept.map((l) => [l.variable, l.value])), runtime);
355
+ }
306
356
  const events = await synchronize(undefined, runtime, undefined, {
307
357
  prompt: false,
308
358
  });
309
359
  return {
310
360
  added: servers.map((s) => s.name),
311
- notes: servers.flatMap((s) => s.notes),
361
+ notes: servers.flatMap((s) => [...s.notes, ...literalNotes(s.literals, options.keep)].map((text) => ({
362
+ server: s.name,
363
+ text,
364
+ }))),
312
365
  backups,
313
366
  events,
314
367
  };
@@ -1,7 +1,7 @@
1
1
  import { localPath } from "../../platform.js";
2
2
  import { POSIX_MODE } from "../../shared/constants.js";
3
3
  import { readState } from "../../config/state.js";
4
- import { readFile, mkdir } from "node:fs/promises";
4
+ import { mkdir } from "node:fs/promises";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import crossSpawn from "cross-spawn";
7
7
  import { z } from "zod";
@@ -15,13 +15,17 @@ import { repoForOrigin, selectRepoAsset, showRepoAsset, } from "../workspace/ass
15
15
  import { gitVersions } from "../collaboration/workspace-git.js";
16
16
  import { adapters } from "../../harnesses/registry.js";
17
17
  import { patchNative } from "../native/configuration.js";
18
- import { fileText } from "../../shared/files.js";
18
+ import { fileText, inputJson } from "../../shared/files.js";
19
19
  import { defined } from "../../shared/lookup.js";
20
- import { CliError } from "../../errors.js";
20
+ import { CliError, friendlyMessage } from "../../errors.js";
21
21
  import { barndogPaths } from "../../config/paths.js";
22
22
  import { apiClient } from "../auth/transport.js";
23
23
  async function readDefinition(file, runtime) {
24
- return mcpDefinitionSchema.parse(JSON.parse(await readFile(localPath(file, runtime), "utf8")));
24
+ const result = mcpDefinitionSchema.safeParse(await inputJson(localPath(file, runtime)));
25
+ if (!result.success) {
26
+ throw new CliError(`${file} isn't an MCP definition: ${friendlyMessage(result.error)}.`, "Check the fields against the MCP definition format at barndog.dev/docs", { cause: result.error });
27
+ }
28
+ return result.data;
25
29
  }
26
30
  /** Publishes a new MCP configuration in a scope. */
27
31
  export async function createMcp(input, runtime) {
@@ -122,7 +126,7 @@ export async function authenticateMcp(name, origin, harness, runtime) {
122
126
  const { name: tool, mcp } = adapters[harness];
123
127
  if ("settings" in mcp.login) {
124
128
  return {
125
- message: `Open ${tool} → ${mcp.login.settings} and authenticate ${asset.name}. ${tool} manages this login locally.`,
129
+ message: `Open ${tool} → ${mcp.login.settings} and authenticate ${installed.key}. ${tool} manages this login locally.`,
126
130
  };
127
131
  }
128
132
  const [command, ...loginArguments] = mcp.login.command;
@@ -133,7 +137,8 @@ export async function authenticateMcp(name, origin, harness, runtime) {
133
137
  const cwd = barndogPaths(home).nativeAuth;
134
138
  await mkdir(cwd, { recursive: true, mode: POSIX_MODE.privateDirectory });
135
139
  // cross-spawn also starts Windows .cmd shims, such as an npm-installed claude.
136
- const child = crossSpawn(command, [...loginArguments, asset.name], {
140
+ // The installed key differs from the asset's name after a clash rename.
141
+ const child = crossSpawn(command, [...loginArguments, installed.key], {
137
142
  cwd,
138
143
  stdio: "inherit",
139
144
  env: { ...runtime.env },
@@ -143,7 +148,7 @@ export async function authenticateMcp(name, origin, harness, runtime) {
143
148
  child.once("exit", (code) => resolve(code ?? 1));
144
149
  });
145
150
  if (code) {
146
- throw new CliError(`${login} exited with code ${code}, so sign-in didn't finish.`, `${login} ${asset.name}`);
151
+ throw new CliError(`${login} exited with code ${code}, so sign-in didn't finish.`, `${login} ${installed.key}`);
147
152
  }
148
153
  return {
149
154
  message: `${harness} authentication completed. Credentials remain in native storage.`,
@@ -0,0 +1,33 @@
1
+ import { readState } from "../../config/state.js";
2
+ import { CliError } from "../../errors.js";
3
+ import { synchronize } from "../environment/sync.js";
4
+ import { recordedVariables } from "../native/secret-values.js";
5
+ import { readSecrets, updateSecrets } from "../secrets/index.js";
6
+ /** Keeps `value` for `variable` and writes it into the coding tools. */
7
+ export async function keepMcpValue(variable, value, runtime) {
8
+ if (!value) {
9
+ throw new CliError(`The value for ${variable} is empty, so nothing was kept.`, `barndog mcp env set ${variable}`);
10
+ }
11
+ const file = await updateSecrets({ [variable]: value }, runtime);
12
+ return { file, events: await synchronize(undefined, runtime) };
13
+ }
14
+ /** Forgets a kept value; the tools refer to the environment variable again. */
15
+ export async function forgetMcpValue(variable, runtime) {
16
+ if ((await readSecrets(runtime))[variable] === undefined) {
17
+ throw new CliError(`BarnDog doesn't keep a value for ${variable}.`, "barndog mcp env list");
18
+ }
19
+ const file = await updateSecrets({ [variable]: null }, runtime);
20
+ return { file, events: await synchronize(undefined, runtime) };
21
+ }
22
+ /** The kept variables, with the settings files sync wrote each into. */
23
+ export async function listKeptValues(runtime) {
24
+ const names = Object.keys(await readSecrets(runtime)).sort();
25
+ const { native } = await readState(runtime.home);
26
+ return names.map((variable) => ({
27
+ variable,
28
+ writtenTo: native
29
+ .filter((entry) => entry.kind === "mcp" &&
30
+ recordedVariables(entry.value).includes(variable))
31
+ .map((entry) => ({ file: entry.file, server: entry.key })),
32
+ }));
33
+ }
@@ -1,5 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { basename } from "node:path";
2
+ import { basename, join } from "node:path";
3
+ import { rm } from "node:fs/promises";
3
4
  import { knowledgeIndexSchema, } from "@barndog-ai/api-contract";
4
5
  import { stringify } from "yaml";
5
6
  import { readSettings, SetupRequiredError, } from "../../config/settings.js";
@@ -19,7 +20,7 @@ import { connectGitWorkspace, createGitWorkspace, inspectRepository, } from "../
19
20
  import { LoginRequiredError, normalizeServer, apiClient, } from "../auth/transport.js";
20
21
  import { connectionContext } from "../auth/session.js";
21
22
  import { publishKnowledge, publishMcp, publishPackage } from "./migrate.js";
22
- import { readMoved, recordMoved } from "../workspace/overlay.js";
23
+ import { moveDestination, readMoved, recordMoved, } from "../workspace/overlay.js";
23
24
  import { commitFiles, openPullRequest, pushCommit, } from "../workspace/publish.js";
24
25
  import { acceptedCommit, gitRepoSource, localRepoSource, recordFetch, trackingRef, } from "../workspace/repo-source.js";
25
26
  import { defined } from "../../shared/lookup.js";
@@ -69,6 +70,8 @@ async function candidates(overlay, names, as, kind) {
69
70
  const pending = (path) => names?.length ? true : !moved.some((entry) => entry.path === path);
70
71
  const items = [];
71
72
  const invalid = [];
73
+ // Requested names, as the local workspace spells them, that matched an asset.
74
+ const found = new Set();
72
75
  for (const asset of model.assets) {
73
76
  if (!pending(asset.path) ||
74
77
  (names?.length && !names.includes(asset.name)) ||
@@ -84,6 +87,7 @@ async function candidates(overlay, names, as, kind) {
84
87
  });
85
88
  continue;
86
89
  }
90
+ found.add(asset.name);
87
91
  const name = as ?? asset.name;
88
92
  items.push({
89
93
  kind: asset.kind,
@@ -100,6 +104,7 @@ async function candidates(overlay, names, as, kind) {
100
104
  (names?.length && !names.includes(doc.content.name))) {
101
105
  continue;
102
106
  }
107
+ found.add(doc.content.name);
103
108
  const name = as ?? doc.content.name;
104
109
  items.push({
105
110
  kind: "knowledge",
@@ -112,8 +117,7 @@ async function candidates(overlay, names, as, kind) {
112
117
  });
113
118
  }
114
119
  for (const name of names ?? []) {
115
- if (!items.some((item) => item.path.includes(`/${name}`)) &&
116
- !invalid.some((row) => row.name === name)) {
120
+ if (!found.has(name) && !invalid.some((row) => row.name === name)) {
117
121
  throw new CliError(`No local asset named ${name}.`, "barndog local list");
118
122
  }
119
123
  }
@@ -177,6 +181,8 @@ async function moveToGit(workspace, items, to, runtime) {
177
181
  }
178
182
  const result = {
179
183
  target: workspace.url,
184
+ keepLocal: true,
185
+ removed: [],
180
186
  rows,
181
187
  originId: stableId(workspace.workspaceId, "scope", scope.type, ...(scope.type === "org" ? [] : [scope.slug])),
182
188
  };
@@ -293,9 +299,51 @@ async function moveToCloud(conn, items, to, runtime) {
293
299
  });
294
300
  }
295
301
  }
296
- return { target: originLabel(scope), rows, originId: scope.id };
302
+ return {
303
+ target: originLabel(scope),
304
+ keepLocal: true,
305
+ removed: [],
306
+ rows,
307
+ originId: scope.id,
308
+ direct: true,
309
+ };
310
+ }
311
+ /** A one-off destination (`--repo`, `--server`) leaves this machine as it is, so it only copies. */
312
+ const keepsLocal = (options) => options.keepLocal || Boolean(options.repo ?? options.server);
313
+ /**
314
+ * Records full moves so sync can replace each local copy with the shared one
315
+ * once it exists. Knowledge that is already published needs no selection, so
316
+ * its local file goes at once; the rest waits for the next sync.
317
+ */
318
+ async function finishMove(folder, result, moved, items) {
319
+ const removed = [];
320
+ const records = [];
321
+ for (const row of moved) {
322
+ const item = defined(items.find((i) => i.kind === row.kind && i.name === row.name), `${row.name} isn't among the moved items`);
323
+ if (row.kind === "knowledge" && result.direct) {
324
+ const path = join(folder, item.path);
325
+ await rm(path, { force: true });
326
+ removed.push(path);
327
+ continue;
328
+ }
329
+ records.push({
330
+ kind: row.kind,
331
+ name: row.name,
332
+ path: item.path,
333
+ version: item.version,
334
+ target: result.target,
335
+ ...(row.kind !== "knowledge" ? { originId: result.originId } : {}),
336
+ ...(result.url ? { url: result.url } : {}),
337
+ });
338
+ }
339
+ await recordMoved(folder, records);
340
+ return removed;
297
341
  }
298
- /** Copies local assets into the shared workspace; the local folder is never deleted. */
342
+ /**
343
+ * Copies local assets into the shared workspace. With `keepLocal` false the
344
+ * shared copy becomes the only one: sync removes each local copy once its
345
+ * shared copy exists.
346
+ */
299
347
  export function moveLocalAssets(options, runtime) {
300
348
  const { home } = runtime;
301
349
  return locked(runtime, async () => {
@@ -331,13 +379,11 @@ export function moveLocalAssets(options, runtime) {
331
379
  };
332
380
  const result = await moveItems();
333
381
  result.rows.unshift(...invalid);
382
+ result.keepLocal = keepsLocal(options);
334
383
  const moved = result.rows.filter((row) => row.status === "moved");
335
- await recordMoved(overlay.label, moved.map((row) => ({
336
- kind: row.kind,
337
- name: row.name,
338
- ...(row.kind !== "knowledge" ? { originId: result.originId } : {}),
339
- path: defined(items.find((i) => i.kind === row.kind && i.name === row.name), `${row.name} isn't among the moved items`).path,
340
- })));
384
+ if (!result.keepLocal) {
385
+ result.removed = await finishMove(overlay.label, result, moved, items);
386
+ }
341
387
  if (moved.length) {
342
388
  await synchronize(undefined, runtime, undefined, { prompt: false });
343
389
  }
@@ -352,12 +398,21 @@ export async function listLocalAssets(runtime) {
352
398
  }
353
399
  const source = localRepoSource(settings.localWorkspace, runtime);
354
400
  const model = await source.model();
355
- const moved = await readMoved(source.label);
401
+ // A move can only be under way while the workspace it goes to is in use.
402
+ const moving = settings.connection || settings.gitWorkspace
403
+ ? await readMoved(source.label)
404
+ : [];
356
405
  const state = (path, invalid) => {
357
406
  if (invalid) {
358
- return "invalid";
407
+ return { state: "invalid" };
359
408
  }
360
- return moved.some((m) => m.path === path) ? "moved" : "active";
409
+ const entry = moving.find((m) => m.path === path);
410
+ return entry
411
+ ? {
412
+ state: "moving",
413
+ movingTo: moveDestination(entry),
414
+ }
415
+ : { state: "active" };
361
416
  };
362
417
  return {
363
418
  folder: settings.localWorkspace.path,
@@ -366,13 +421,13 @@ export async function listLocalAssets(runtime) {
366
421
  kind: asset.kind,
367
422
  name: asset.name,
368
423
  path: asset.path,
369
- state: state(asset.path, asset.invalid),
424
+ ...state(asset.path, asset.invalid),
370
425
  })),
371
426
  ...model.knowledge.map((doc) => ({
372
427
  kind: "knowledge",
373
428
  name: doc.content.name,
374
429
  path: doc.path,
375
- state: state(doc.path),
430
+ ...state(doc.path),
376
431
  })),
377
432
  ],
378
433
  };
@@ -12,6 +12,8 @@ export async function promote(input, runtime) {
12
12
  move: await moveLocalAssets({
13
13
  names: [input.name],
14
14
  kind: input.kind,
15
+ // Promoting shares a copy; the original stays, as on the server.
16
+ keepLocal: true,
15
17
  to: input.target,
16
18
  as: input.newName === input.name ? undefined : input.newName,
17
19
  }, runtime),
@@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url";
2
2
  import { coerce, satisfies, validRange } from "semver";
3
3
  import { programOutput, findExecutable, runtimeExecutable, } from "../../platform.js";
4
4
  import { adapters, nativeFile } from "../../harnesses/registry.js";
5
+ import { secretRefs } from "../../harnesses/formats.js";
5
6
  import { hookCommand } from "./hook-shell.js";
6
7
  /** A `--version` answer is one short line; anything slower or longer is broken. */
7
8
  const VERSION_TIMEOUT_MS = 5000;
@@ -55,18 +56,31 @@ export async function hookIssue(harness, manifest, runtime) {
55
56
  return runtimeRequirements(harness, implementation.requirements, runtime);
56
57
  }
57
58
  /**
58
- * Builds a harness-specific MCP configuration entry with secret references;
59
- * does not write native settings.
59
+ * Builds a harness-specific MCP configuration entry; does not write native
60
+ * settings. Variables in `kept` are written as their values, the rest as
61
+ * references to local environment variables.
60
62
  */
61
- export function mcpEntry(harness, asset, definition, runtime) {
63
+ export function mcpEntry(harness, server, kept, runtime) {
62
64
  const { home } = runtime;
65
+ const used = Object.fromEntries(Object.values(secretRefs(server.definition)).flatMap((ref) => {
66
+ const value = kept[ref.secretRef];
67
+ return value === undefined ? [] : [[ref.secretRef, value]];
68
+ }));
63
69
  return {
64
- id: asset.id,
70
+ id: server.id,
65
71
  kind: "mcp",
66
72
  harness,
67
73
  file: nativeFile(harness, "mcp", home),
68
- key: asset.name,
69
- value: adapters[harness].mcp.server(definition, fileURLToPath(new URL("../../entry/mcp-launch.js", import.meta.url))),
74
+ key: server.name,
75
+ value: adapters[harness].mcp.server(server.definition, fileURLToPath(new URL("../../entry/mcp-launch.js", import.meta.url)), used),
76
+ ...(Object.keys(used).length
77
+ ? {
78
+ secrets: Object.entries(used).map(([variable, value]) => ({
79
+ variable,
80
+ value,
81
+ })),
82
+ }
83
+ : {}),
70
84
  };
71
85
  }
72
86
  /**
@@ -4,10 +4,10 @@ import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
4
4
  // source positions, and toml-eslint-parser (despite the name, a plain TOML parser
5
5
  // that doesn't need ESLint) gives each table's range in the text. See tomlEdit().
6
6
  import { parseForESLint } from "toml-eslint-parser";
7
- import { isDeepStrictEqual } from "node:util";
8
7
  import { adapters } from "../../harnesses/registry.js";
9
8
  import { isRecord } from "../../shared/values.js";
10
9
  import { CliError } from "../../errors.js";
10
+ import { sameValue } from "./secret-values.js";
11
11
  function object(value, file) {
12
12
  if (!isRecord(value)) {
13
13
  throw new CliError(`${file} doesn't hold the settings object BarnDog expects, so it was left unchanged. Fix it, then sync again.`, "barndog sync");
@@ -18,7 +18,7 @@ function same(left, right) {
18
18
  if (left === undefined || right === undefined) {
19
19
  return left === right;
20
20
  }
21
- return isDeepStrictEqual(JSON.parse(JSON.stringify(left)), JSON.parse(JSON.stringify(right)));
21
+ return sameValue(JSON.parse(JSON.stringify(left)), JSON.parse(JSON.stringify(right)));
22
22
  }
23
23
  function json(text, file) {
24
24
  const errors = [];
@@ -164,10 +164,10 @@ export function patchNative(text, before, after) {
164
164
  if (next.kind === "mcp") {
165
165
  if (Object.hasOwn(servers(), next.key) &&
166
166
  !before.some((old) => old.kind === "mcp" && old.key === next.key)) {
167
- throw new CliError(`${sample.file} already has an MCP server named ${next.key} that BarnDog didn't add. Remove it, or install BarnDog's under another name.`, `barndog mcp rename ${next.key}`);
167
+ throw new CliError(`${sample.file} already has an MCP server named ${next.key} that BarnDog didn't add. Remove it, or install BarnDog's under another name.`, `barndog mcp rename ${next.key} --as <new-name>`);
168
168
  }
169
169
  if (after.filter((e) => e.kind === "mcp" && e.key === next.key).length > 1) {
170
- throw new CliError(`Two MCP servers would both be installed as ${next.key}.`, `barndog mcp rename ${next.key}`);
170
+ throw new CliError(`Two MCP servers would both be installed as ${next.key}.`, `barndog mcp rename ${next.key} --origin <origin> --as <new-name>`);
171
171
  }
172
172
  }
173
173
  else {
@@ -235,6 +235,10 @@ export function patchNative(text, before, after) {
235
235
  }
236
236
  }
237
237
  }
238
+ // A file written by hand may leave the version out; the tool needs it.
239
+ if (version !== undefined && data.version === undefined && !toml) {
240
+ change(["version"], version);
241
+ }
238
242
  if (version !== undefined && data.version !== version) {
239
243
  throw new CliError(`${sample.file} has a version BarnDog doesn't support (it expects "version": ${version}), so it was left unchanged.`);
240
244
  }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * MCP values BarnDog keeps (`~/.barndog/secrets.json`) are written into the
3
+ * coding tools' settings, so `state.json` would copy them when it records
4
+ * BarnDog's entries. It records a marker instead: the variable's name and a
5
+ * SHA-256 of the value. Comparing a recorded entry with one in a settings file
6
+ * hashes the file's value at each marker, so hand edits are still noticed.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { isRecord } from "../../shared/values.js";
11
+ const PREFIX = "barndog-secret:";
12
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
13
+ const marker = (secret) => `${PREFIX}${secret.variable}:sha256:${digest(secret.value)}`;
14
+ /** The variable and hash in a marker; null for any other text. */
15
+ function parseMarker(text) {
16
+ if (!text.startsWith(PREFIX)) {
17
+ return null;
18
+ }
19
+ const [variable, , hash] = text.slice(PREFIX.length).split(":");
20
+ return variable && hash ? { variable, hash } : null;
21
+ }
22
+ /** `value` with every kept value in it replaced by its marker. */
23
+ export function redacted(value, secrets) {
24
+ const walk = (item) => {
25
+ if (typeof item === "string") {
26
+ const secret = secrets.find((s) => s.value === item);
27
+ return secret ? marker(secret) : item;
28
+ }
29
+ if (Array.isArray(item)) {
30
+ return item.map(walk);
31
+ }
32
+ if (isRecord(item)) {
33
+ return Object.fromEntries(Object.entries(item).map(([key, inner]) => [key, walk(inner)]));
34
+ }
35
+ return item;
36
+ };
37
+ const result = walk(value);
38
+ return isRecord(result) ? result : value;
39
+ }
40
+ /** Deep equality where a marker on either side equals the value it hashes. */
41
+ export function sameValue(left, right) {
42
+ if (typeof left === "string" && typeof right === "string") {
43
+ const l = parseMarker(left);
44
+ const r = parseMarker(right);
45
+ if (l && r) {
46
+ return l.hash === r.hash;
47
+ }
48
+ if (l || r) {
49
+ return l ? digest(right) === l.hash : digest(left) === r?.hash;
50
+ }
51
+ return left === right;
52
+ }
53
+ if (Array.isArray(left) && Array.isArray(right)) {
54
+ return (left.length === right.length &&
55
+ left.every((item, index) => sameValue(item, right[index])));
56
+ }
57
+ if (isRecord(left) && isRecord(right)) {
58
+ const keys = Object.keys(left);
59
+ return (keys.length === Object.keys(right).length &&
60
+ keys.every((key) => key in right && sameValue(left[key], right[key])));
61
+ }
62
+ return isDeepStrictEqual(left, right);
63
+ }
64
+ /** The variables whose kept values a recorded entry holds. */
65
+ export function recordedVariables(value) {
66
+ if (typeof value === "string") {
67
+ const parsed = parseMarker(value);
68
+ return parsed ? [parsed.variable] : [];
69
+ }
70
+ if (Array.isArray(value)) {
71
+ return value.flatMap(recordedVariables);
72
+ }
73
+ return isRecord(value) ? Object.values(value).flatMap(recordedVariables) : [];
74
+ }