barndog 0.2.0 → 0.2.2

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 (112) hide show
  1. package/README.md +45 -24
  2. package/dist/cli.js +27 -1
  3. package/dist/commands/add.js +1 -0
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/asset-install.js +1 -0
  6. package/dist/commands/asset-list.js +12 -3
  7. package/dist/commands/availability.js +25 -8
  8. package/dist/commands/capabilities.js +8 -2
  9. package/dist/commands/collaboration.js +22 -2
  10. package/dist/commands/harnesses.js +104 -0
  11. package/dist/commands/mcp-env.js +167 -0
  12. package/dist/commands/mcp.js +4 -2
  13. package/dist/commands/sets.js +13 -2
  14. package/dist/commands/status.js +2 -1
  15. package/dist/commands/sync.js +2 -1
  16. package/dist/commands/uninstall.js +62 -0
  17. package/dist/commands/workspace.js +43 -5
  18. package/dist/config/paths.js +21 -0
  19. package/dist/config/settings.js +5 -3
  20. package/dist/config/state.js +18 -6
  21. package/dist/entry/update-check.js +15 -0
  22. package/dist/features/adoption/adopt.js +235 -0
  23. package/dist/features/adoption/copies.js +29 -0
  24. package/dist/features/adoption/originals.js +116 -0
  25. package/dist/features/adoption/record.js +120 -0
  26. package/dist/features/adoption/restore.js +28 -0
  27. package/dist/features/adoption/scan.js +482 -0
  28. package/dist/features/adoption/undo.js +42 -0
  29. package/dist/features/asset-kinds/index.js +9 -0
  30. package/dist/features/auth/credentials.js +7 -14
  31. package/dist/features/auth/session.js +26 -5
  32. package/dist/features/auth/transport.js +3 -2
  33. package/dist/features/collaboration/workspace-git.js +13 -7
  34. package/dist/features/collaboration/workspace-github.js +2 -1
  35. package/dist/features/collaboration/workspace-store.js +25 -4
  36. package/dist/features/collaboration/workspace.js +22 -2
  37. package/dist/features/doctor/index.js +46 -7
  38. package/dist/features/environment/events.js +8 -1
  39. package/dist/features/environment/harnesses.js +36 -0
  40. package/dist/features/environment/kept-values.js +68 -0
  41. package/dist/features/environment/moves.js +187 -0
  42. package/dist/features/environment/names.js +10 -6
  43. package/dist/features/environment/operations.js +7 -7
  44. package/dist/features/environment/stage.js +25 -1
  45. package/dist/features/environment/sync.js +17 -6
  46. package/dist/features/environment/writes.js +55 -8
  47. package/dist/features/hooks/compatibility.js +11 -5
  48. package/dist/features/hooks/divergence.js +30 -9
  49. package/dist/features/hooks/test.js +25 -25
  50. package/dist/features/imports/discover.js +1 -1
  51. package/dist/features/imports/local.js +15 -2
  52. package/dist/features/imports/remote.js +2 -1
  53. package/dist/features/inventory/index.js +57 -3
  54. package/dist/features/inventory/show.js +74 -0
  55. package/dist/features/mcps/import.js +95 -21
  56. package/dist/features/mcps/index.js +24 -9
  57. package/dist/features/mcps/values.js +121 -0
  58. package/dist/features/migration/migrate.js +15 -0
  59. package/dist/features/migration/move.js +105 -25
  60. package/dist/features/migration/promote.js +2 -0
  61. package/dist/features/native/adapters.js +20 -7
  62. package/dist/features/native/configuration.js +8 -4
  63. package/dist/features/native/hook-shell.js +11 -0
  64. package/dist/features/native/secret-values.js +74 -0
  65. package/dist/features/secrets/index.js +142 -0
  66. package/dist/features/uninstall/index.js +126 -0
  67. package/dist/features/uninstall/leave.js +152 -0
  68. package/dist/features/uninstall/survey.js +103 -0
  69. package/dist/features/update-check/index.js +108 -0
  70. package/dist/features/workspace/format.js +19 -10
  71. package/dist/features/workspace/git.js +11 -4
  72. package/dist/features/workspace/overlay.js +23 -36
  73. package/dist/features/workspace/packages.js +16 -3
  74. package/dist/features/workspace/publish.js +1 -1
  75. package/dist/features/workspace/repo-source.js +4 -3
  76. package/dist/features/workspace/setup.js +12 -3
  77. package/dist/features/workspace/snapshot.js +7 -1
  78. package/dist/harnesses/claude.js +2 -2
  79. package/dist/harnesses/codex.js +54 -20
  80. package/dist/harnesses/cursor.js +2 -2
  81. package/dist/harnesses/formats.js +12 -5
  82. package/dist/harnesses/opencode.js +3 -6
  83. package/dist/harnesses/read-renamed-variables.js +141 -0
  84. package/dist/harnesses/renamed-variables.js +99 -0
  85. package/dist/platform.js +51 -12
  86. package/dist/program.js +68 -8
  87. package/dist/shared/files.js +35 -0
  88. package/dist/shared/lock.js +87 -23
  89. package/dist/shared/patterns.js +8 -0
  90. package/dist/shared/shell.js +0 -2
  91. package/dist/ui/add-hook.js +8 -2
  92. package/dist/ui/add-mcp.js +82 -13
  93. package/dist/ui/add-skills.js +7 -5
  94. package/dist/ui/adopt.js +202 -0
  95. package/dist/ui/assets.js +5 -3
  96. package/dist/ui/auth.js +2 -1
  97. package/dist/ui/clash.js +2 -3
  98. package/dist/ui/connection.js +9 -2
  99. package/dist/ui/harness-picker.js +23 -0
  100. package/dist/ui/mcp.js +89 -23
  101. package/dist/ui/move.js +49 -2
  102. package/dist/ui/onboarding.js +40 -27
  103. package/dist/ui/output.js +35 -8
  104. package/dist/ui/package-details.js +34 -0
  105. package/dist/ui/scope-install.js +4 -1
  106. package/dist/ui/secret-input.js +28 -0
  107. package/dist/ui/selection.js +3 -1
  108. package/dist/ui/uninstall.js +174 -0
  109. package/dist/ui/update.js +10 -0
  110. package/dist/version.js +2 -2
  111. package/package.json +1 -1
  112. package/dist/entry/mcp-launch.js +0 -71
@@ -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";
@@ -13,13 +14,14 @@ import { environmentCatalog } from "../server/catalog.js";
13
14
  import { parsed } from "../server/client.js";
14
15
  import { synchronize } from "../environment/sync.js";
15
16
  import { locked } from "../environment/transaction.js";
16
- import { assetPath, stableId } from "../workspace/format.js";
17
+ import { assetPath, repoAssetId, stableId, } from "../workspace/format.js";
18
+ import { updateKeptValues, withMovedServers, } from "../environment/kept-values.js";
17
19
  import { checkRepositoryUrl, cloneOrigin, git } from "../workspace/git.js";
18
20
  import { connectGitWorkspace, createGitWorkspace, inspectRepository, } from "../workspace/setup.js";
19
21
  import { LoginRequiredError, normalizeServer, apiClient, } from "../auth/transport.js";
20
22
  import { connectionContext } from "../auth/session.js";
21
23
  import { publishKnowledge, publishMcp, publishPackage } from "./migrate.js";
22
- import { readMoved, recordMoved } from "../workspace/overlay.js";
24
+ import { moveDestination, readMoved, recordMoved, } from "../workspace/overlay.js";
23
25
  import { commitFiles, openPullRequest, pushCommit, } from "../workspace/publish.js";
24
26
  import { acceptedCommit, gitRepoSource, localRepoSource, recordFetch, trackingRef, } from "../workspace/repo-source.js";
25
27
  import { defined } from "../../shared/lookup.js";
@@ -69,6 +71,8 @@ async function candidates(overlay, names, as, kind) {
69
71
  const pending = (path) => names?.length ? true : !moved.some((entry) => entry.path === path);
70
72
  const items = [];
71
73
  const invalid = [];
74
+ // Requested names, as the local workspace spells them, that matched an asset.
75
+ const found = new Set();
72
76
  for (const asset of model.assets) {
73
77
  if (!pending(asset.path) ||
74
78
  (names?.length && !names.includes(asset.name)) ||
@@ -84,6 +88,7 @@ async function candidates(overlay, names, as, kind) {
84
88
  });
85
89
  continue;
86
90
  }
91
+ found.add(asset.name);
87
92
  const name = as ?? asset.name;
88
93
  items.push({
89
94
  kind: asset.kind,
@@ -100,6 +105,7 @@ async function candidates(overlay, names, as, kind) {
100
105
  (names?.length && !names.includes(doc.content.name))) {
101
106
  continue;
102
107
  }
108
+ found.add(doc.content.name);
103
109
  const name = as ?? doc.content.name;
104
110
  items.push({
105
111
  kind: "knowledge",
@@ -112,8 +118,7 @@ async function candidates(overlay, names, as, kind) {
112
118
  });
113
119
  }
114
120
  for (const name of names ?? []) {
115
- if (!items.some((item) => item.path.includes(`/${name}`)) &&
116
- !invalid.some((row) => row.name === name)) {
121
+ if (!found.has(name) && !invalid.some((row) => row.name === name)) {
117
122
  throw new CliError(`No local asset named ${name}.`, "barndog local list");
118
123
  }
119
124
  }
@@ -148,7 +153,8 @@ function candidateFiles(item, path) {
148
153
  path: `${path}/${entry.path}`,
149
154
  }));
150
155
  }
151
- async function moveToGit(workspace, items, to, runtime) {
156
+ async function moveToGit(workspace, move, runtime) {
157
+ const { items, to, sharedIds = new Map() } = move;
152
158
  const { home } = runtime;
153
159
  const shared = await gitRepoSource(workspace, runtime).model();
154
160
  const tip = defined(await acceptedCommit(workspace.workspaceId, runtime), "This Git workspace hasn't been fetched yet");
@@ -177,6 +183,8 @@ async function moveToGit(workspace, items, to, runtime) {
177
183
  }
178
184
  const result = {
179
185
  target: workspace.url,
186
+ keepLocal: true,
187
+ removed: [],
180
188
  rows,
181
189
  originId: stableId(workspace.workspaceId, "scope", scope.type, ...(scope.type === "org" ? [] : [scope.slug])),
182
190
  };
@@ -221,9 +229,15 @@ async function moveToGit(workspace, items, to, runtime) {
221
229
  name: item.name,
222
230
  status: "moved",
223
231
  })));
232
+ for (const { item } of moving) {
233
+ if (item.kind === "mcp") {
234
+ sharedIds.set(item.id, repoAssetId(workspace.workspaceId, "mcp", scope, item.name));
235
+ }
236
+ }
224
237
  return result;
225
238
  }
226
- async function moveToCloud(conn, items, to, runtime) {
239
+ async function moveToCloud(conn, move, runtime) {
240
+ const { items, to, sharedIds = new Map() } = move;
227
241
  const scope = await selectOrigin(to ?? "me", conn, runtime);
228
242
  if (!scope.canPublish) {
229
243
  throw new CliError(`You can't publish to ${originLabel(scope)}.`, "barndog local move --to me");
@@ -278,7 +292,7 @@ async function moveToCloud(conn, items, to, runtime) {
278
292
  definition: item.definition,
279
293
  };
280
294
  if (asset.kind === "mcp") {
281
- await publishMcp(asset, scope, conn, runtime);
295
+ sharedIds.set(item.id, (await publishMcp(asset, scope, conn, runtime)).id);
282
296
  }
283
297
  else {
284
298
  await publishPackage({ ...asset, kind: asset.kind }, scope, conn, runtime);
@@ -293,9 +307,63 @@ async function moveToCloud(conn, items, to, runtime) {
293
307
  });
294
308
  }
295
309
  }
296
- return { target: originLabel(scope), rows, originId: scope.id };
310
+ return {
311
+ target: originLabel(scope),
312
+ keepLocal: true,
313
+ removed: [],
314
+ rows,
315
+ originId: scope.id,
316
+ direct: true,
317
+ };
297
318
  }
298
- /** Copies local assets into the shared workspace; the local folder is never deleted. */
319
+ /**
320
+ * A shared copy that sits beside its local server starts with the local one's
321
+ * kept values; after that each keeps its own. A full move carries them over
322
+ * when sync finishes it (`environment/moves.ts`).
323
+ */
324
+ async function copyKeptValues(sharedIds, runtime) {
325
+ const copies = [...sharedIds].map(([from, to]) => ({ from, to, copy: true }));
326
+ if (!copies.length) {
327
+ return;
328
+ }
329
+ await updateKeptValues((secrets) => withMovedServers(secrets, copies), runtime);
330
+ }
331
+ /** A one-off destination (`--repo`, `--server`) leaves this machine as it is, so it only copies. */
332
+ const keepsLocal = (options) => options.keepLocal || Boolean(options.repo ?? options.server);
333
+ /**
334
+ * Records full moves so sync can replace each local copy with the shared one
335
+ * once it exists. Knowledge that is already published needs no selection, so
336
+ * its local file goes at once; the rest waits for the next sync.
337
+ */
338
+ async function finishMove(folder, result, moved, items) {
339
+ const removed = [];
340
+ const records = [];
341
+ for (const row of moved) {
342
+ const item = defined(items.find((i) => i.kind === row.kind && i.name === row.name), `${row.name} isn't among the moved items`);
343
+ if (row.kind === "knowledge" && result.direct) {
344
+ const path = join(folder, item.path);
345
+ await rm(path, { force: true });
346
+ removed.push(path);
347
+ continue;
348
+ }
349
+ records.push({
350
+ kind: row.kind,
351
+ name: row.name,
352
+ path: item.path,
353
+ version: item.version,
354
+ target: result.target,
355
+ ...(row.kind !== "knowledge" ? { originId: result.originId } : {}),
356
+ ...(result.url ? { url: result.url } : {}),
357
+ });
358
+ }
359
+ await recordMoved(folder, records);
360
+ return removed;
361
+ }
362
+ /**
363
+ * Copies local assets into the shared workspace. With `keepLocal` false the
364
+ * shared copy becomes the only one: sync removes each local copy once its
365
+ * shared copy exists.
366
+ */
299
367
  export function moveLocalAssets(options, runtime) {
300
368
  const { home } = runtime;
301
369
  return locked(runtime, async () => {
@@ -317,27 +385,30 @@ export function moveLocalAssets(options, runtime) {
317
385
  throw new CliError("--as renames one asset, so name exactly one.", "barndog local move <name> --as <new-name>");
318
386
  }
319
387
  const { items, invalid } = await candidates(overlay, options.names, options.as, options.kind);
388
+ // Only this machine's own workspace: a one-off destination isn't installed here.
389
+ const sharedIds = new Map();
320
390
  const moveItems = async () => {
321
391
  if (options.repo) {
322
- return moveToGit(await repoDestination(options.repo, runtime), items, options.to, runtime);
392
+ return moveToGit(await repoDestination(options.repo, runtime), { items, to: options.to }, runtime);
323
393
  }
324
394
  if (options.server) {
325
- return moveToCloud(await serverDestination(options.server, runtime), items, options.to, runtime);
395
+ return moveToCloud(await serverDestination(options.server, runtime), { items, to: options.to }, runtime);
326
396
  }
327
397
  if (settings.gitWorkspace) {
328
- return moveToGit(settings.gitWorkspace, items, options.to, runtime);
398
+ return moveToGit(settings.gitWorkspace, { items, to: options.to, sharedIds }, runtime);
329
399
  }
330
- return moveToCloud(await connection(runtime), items, options.to, runtime);
400
+ return moveToCloud(await connection(runtime), { items, to: options.to, sharedIds }, runtime);
331
401
  };
332
402
  const result = await moveItems();
333
403
  result.rows.unshift(...invalid);
404
+ result.keepLocal = keepsLocal(options);
334
405
  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
- })));
406
+ if (!result.keepLocal) {
407
+ result.removed = await finishMove(overlay.label, result, moved, items);
408
+ }
409
+ else {
410
+ await copyKeptValues(sharedIds, runtime);
411
+ }
341
412
  if (moved.length) {
342
413
  await synchronize(undefined, runtime, undefined, { prompt: false });
343
414
  }
@@ -352,12 +423,21 @@ export async function listLocalAssets(runtime) {
352
423
  }
353
424
  const source = localRepoSource(settings.localWorkspace, runtime);
354
425
  const model = await source.model();
355
- const moved = await readMoved(source.label);
426
+ // A move can only be under way while the workspace it goes to is in use.
427
+ const moving = settings.connection || settings.gitWorkspace
428
+ ? await readMoved(source.label)
429
+ : [];
356
430
  const state = (path, invalid) => {
357
431
  if (invalid) {
358
- return "invalid";
432
+ return { state: "invalid" };
359
433
  }
360
- return moved.some((m) => m.path === path) ? "moved" : "active";
434
+ const entry = moving.find((m) => m.path === path);
435
+ return entry
436
+ ? {
437
+ state: "moving",
438
+ movingTo: moveDestination(entry),
439
+ }
440
+ : { state: "available" };
361
441
  };
362
442
  return {
363
443
  folder: settings.localWorkspace.path,
@@ -366,13 +446,13 @@ export async function listLocalAssets(runtime) {
366
446
  kind: asset.kind,
367
447
  name: asset.name,
368
448
  path: asset.path,
369
- state: state(asset.path, asset.invalid),
449
+ ...state(asset.path, asset.invalid),
370
450
  })),
371
451
  ...model.knowledge.map((doc) => ({
372
452
  kind: "knowledge",
373
453
  name: doc.content.name,
374
454
  path: doc.path,
375
- state: state(doc.path),
455
+ ...state(doc.path),
376
456
  })),
377
457
  ],
378
458
  };
@@ -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),
@@ -1,7 +1,7 @@
1
- import { fileURLToPath } from "node:url";
2
1
  import { coerce, satisfies, validRange } from "semver";
3
2
  import { programOutput, findExecutable, runtimeExecutable, } from "../../platform.js";
4
3
  import { adapters, nativeFile } from "../../harnesses/registry.js";
4
+ import { secretRefs } from "../../harnesses/formats.js";
5
5
  import { hookCommand } from "./hook-shell.js";
6
6
  /** A `--version` answer is one short line; anything slower or longer is broken. */
7
7
  const VERSION_TIMEOUT_MS = 5000;
@@ -55,18 +55,31 @@ export async function hookIssue(harness, manifest, runtime) {
55
55
  return runtimeRequirements(harness, implementation.requirements, runtime);
56
56
  }
57
57
  /**
58
- * Builds a harness-specific MCP configuration entry with secret references;
59
- * does not write native settings.
58
+ * Builds a harness-specific MCP configuration entry; does not write native
59
+ * settings. Variables in `kept` are written as their values, the rest as
60
+ * references to local environment variables.
60
61
  */
61
- export function mcpEntry(harness, asset, definition, runtime) {
62
+ export function mcpEntry(harness, server, kept, runtime) {
62
63
  const { home } = runtime;
64
+ const used = Object.fromEntries(Object.values(secretRefs(server.definition)).flatMap((ref) => {
65
+ const value = kept[ref.secretRef];
66
+ return value === undefined ? [] : [[ref.secretRef, value]];
67
+ }));
63
68
  return {
64
- id: asset.id,
69
+ id: server.id,
65
70
  kind: "mcp",
66
71
  harness,
67
72
  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))),
73
+ key: server.name,
74
+ value: adapters[harness].mcp.server(server.definition, used, runtime.platform),
75
+ ...(Object.keys(used).length
76
+ ? {
77
+ secrets: Object.entries(used).map(([variable, value]) => ({
78
+ variable,
79
+ value,
80
+ })),
81
+ }
82
+ : {}),
70
83
  };
71
84
  }
72
85
  /**
@@ -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
  }
@@ -43,6 +43,17 @@ function hookLine(root, command, harness, platform) {
43
43
  };
44
44
  }
45
45
  export const hookCommand = (root, command, harness, platform) => lineFor(harness, hookLine(root, command, harness, platform), platform);
46
+ /**
47
+ * A command `hookCommand()` wrote for the folder `from`, rewritten to set the
48
+ * root variables to `to` instead; the Hook author's own command is kept as
49
+ * is. Undefined when the command doesn't start the way BarnDog writes it.
50
+ */
51
+ export function movedHookCommand(command, folders, harness, platform) {
52
+ const prefix = hookCommand(folders.from, "", harness, platform);
53
+ return command.startsWith(prefix)
54
+ ? hookCommand(folders.to, command.slice(prefix.length), harness, platform)
55
+ : undefined;
56
+ }
46
57
  /** How `hooks test` runs a Hook: in the shell its tool would use. */
47
58
  export async function hookInvocation(root, command, harness, runtime) {
48
59
  const line = hookLine(root, command, harness, runtime.platform);
@@ -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
+ }
@@ -0,0 +1,142 @@
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 { secretRefs } from "../../harnesses/formats.js";
6
+ import { privatePermissions, protectPrivate, removeCommand, } from "../../platform.js";
7
+ import { POSIX_MODE } from "../../shared/constants.js";
8
+ import { ifExists, writeAtomic } from "../../shared/files.js";
9
+ import { withPidLock } from "../../shared/lock.js";
10
+ import { VARIABLE_NAME } from "../../shared/patterns.js";
11
+ import { posixQuote } from "../../shared/shell.js";
12
+ const variable = z.string().regex(new RegExp(`^${VARIABLE_NAME.source}$`));
13
+ /** A kept value, or another environment variable the server reads in its place. */
14
+ const keptValueSchema = z.union([
15
+ z.strictObject({ value: z.string() }),
16
+ z.strictObject({ from: variable }),
17
+ ]);
18
+ const secretsSchema = z.discriminatedUnion("version", [
19
+ z.strictObject({
20
+ version: z.literal(1),
21
+ values: z.record(variable, z.string()),
22
+ }),
23
+ z.strictObject({
24
+ version: z.literal(2),
25
+ /** MCP asset ID → variable → its value. */
26
+ servers: z.record(z.string(), z.record(variable, keptValueSchema)),
27
+ /** Values from a version 1 file that no installed server was using. */
28
+ unassigned: z.record(variable, z.string()),
29
+ }),
30
+ ]);
31
+ /** The variable a kept value says to read instead; undefined for a value kept as written. */
32
+ export const readsFrom = (kept) => kept && "from" in kept ? kept.from : undefined;
33
+ /** The value kept as written; undefined for one that reads another variable. */
34
+ export const literalOf = (kept) => kept && "value" in kept ? kept.value : undefined;
35
+ const empty = { version: 2, servers: {}, unassigned: {} };
36
+ /** The file as stored; an empty current one when there's no file yet. */
37
+ export async function readStoredSecrets(runtime) {
38
+ const path = barndogPaths(runtime.home).secrets;
39
+ const info = await ifExists(lstat(path));
40
+ if (!info) {
41
+ return empty;
42
+ }
43
+ if (!info.isFile()) {
44
+ 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) });
45
+ }
46
+ // Always passes on Windows, where the ACL set on every write keeps it private.
47
+ if (!privatePermissions(info.mode, runtime.platform)) {
48
+ 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)}` });
49
+ }
50
+ const parsed = secretsSchema.safeParse(parseJson(await readFile(path, "utf8")));
51
+ if (!parsed.success) {
52
+ 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) });
53
+ }
54
+ return parsed.data;
55
+ }
56
+ function parseJson(text) {
57
+ try {
58
+ return JSON.parse(text);
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ }
64
+ /**
65
+ * Replaces the file with what `change` makes of it, under a lock, and returns
66
+ * the file's path and what it now holds. `change` receives the file as stored,
67
+ * so a version 1 file has to be converted there.
68
+ */
69
+ export async function changeSecrets(change, runtime) {
70
+ const paths = barndogPaths(runtime.home);
71
+ await mkdir(paths.root, {
72
+ recursive: true,
73
+ mode: POSIX_MODE.privateDirectory,
74
+ });
75
+ await chmod(paths.root, POSIX_MODE.privateDirectory);
76
+ await protectPrivate(paths.root, runtime);
77
+ const secrets = await withPidLock(paths.secretsLock, {
78
+ starting: "Another change to the kept MCP values is starting. Wait for it to finish, then try again.",
79
+ running: "Another change to the kept MCP values is running. Wait for it to finish, then try again.",
80
+ }, async () => {
81
+ const next = withoutEmptyServers(change(await readStoredSecrets(runtime)));
82
+ await writeAtomic(paths.secrets, JSON.stringify({ version: 2, ...next }, null, 2) + "\n");
83
+ await protectPrivate(paths.secrets, runtime);
84
+ return next;
85
+ });
86
+ return { file: paths.secrets, secrets };
87
+ }
88
+ function withoutEmptyServers(secrets) {
89
+ return {
90
+ servers: Object.fromEntries(Object.entries(secrets.servers).filter(([, values]) => Object.keys(values).length > 0)),
91
+ unassigned: secrets.unassigned,
92
+ };
93
+ }
94
+ /** Throws unless `name` can be an environment variable's name. */
95
+ export function assertVariableName(name) {
96
+ if (!variable.safeParse(name).success) {
97
+ throw new CliError(`${name} isn't an environment variable name.`, "Use letters, digits and underscores, not starting with a digit.");
98
+ }
99
+ }
100
+ /**
101
+ * A server's definition with each variable kept as `from` read from that other
102
+ * variable instead, and the values written into its entries as they are.
103
+ */
104
+ export function applyKeptValues(definition, values = {}) {
105
+ const rewrite = (refs) => Object.fromEntries(Object.entries(refs).map(([key, ref]) => {
106
+ const from = readsFrom(values[ref.secretRef]);
107
+ return [key, from ? { ...ref, secretRef: from } : ref];
108
+ }));
109
+ const kept = Object.fromEntries(Object.entries(values).flatMap(([name, value]) => {
110
+ const literal = literalOf(value);
111
+ return literal === undefined ? [] : [[name, literal]];
112
+ }));
113
+ return {
114
+ definition: definition.transport === "stdio"
115
+ ? { ...definition, environment: rewrite(definition.environment) }
116
+ : { ...definition, headers: rewrite(definition.headers) },
117
+ kept,
118
+ };
119
+ }
120
+ /**
121
+ * The variables a definition names that have no value on this machine:
122
+ * BarnDog keeps none for this server and `env` doesn't set the variable read.
123
+ * Each once, in the order the definition names them.
124
+ */
125
+ export function missingValues(definition, values, env) {
126
+ const missing = new Map();
127
+ for (const { secretRef } of Object.values(secretRefs(definition))) {
128
+ const kept = values[secretRef];
129
+ const from = readsFrom(kept);
130
+ const read = from ?? secretRef;
131
+ const found = literalOf(kept) ??
132
+ literalOf(from ? values[from] : undefined) ??
133
+ env[read];
134
+ if (!found) {
135
+ missing.set(secretRef, {
136
+ variable: secretRef,
137
+ ...(from ? { from } : {}),
138
+ });
139
+ }
140
+ }
141
+ return [...missing.values()];
142
+ }