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,5 +1,6 @@
1
1
  import { bold, dim, heading, json, ok, plural, table, warn, } from "../ui/format.js";
2
- import { renderMove } from "../ui/move.js";
2
+ import { chooseKeepLocal, pickLocalAssets, renderMove } from "../ui/move.js";
3
+ import { CliError } from "../errors.js";
3
4
  const migrationActionStyles = {
4
5
  publish: ok,
5
6
  exists: dim,
@@ -26,7 +27,7 @@ export function registerWorkspace(program, context) {
26
27
  .description("See and share the assets kept in this machine's folder");
27
28
  local
28
29
  .command("list")
29
- .description("List local assets and whether they've been moved")
30
+ .description("List the assets kept in this machine's folder")
30
31
  .action(async () => {
31
32
  const result = await context.listLocalAssets();
32
33
  if (context.mode.json) {
@@ -41,20 +42,38 @@ export function registerWorkspace(program, context) {
41
42
  dim(asset.kind),
42
43
  asset.state === "invalid" ? warn(asset.state) : asset.state,
43
44
  dim(asset.path),
44
- ]), { header: ["Name", "Kind", "State", "Path"] })) {
45
+ asset.movingTo ? dim(`to ${asset.movingTo}`) : "",
46
+ ]), { header: ["Name", "Kind", "State", "Path", ""] })) {
45
47
  context.write(line);
46
48
  }
47
49
  });
48
50
  local
49
51
  .command("move [names...]")
50
- .description("Copy local assets into your Git or Cloud workspace")
52
+ .description("Move local assets into your Git or Cloud workspace")
53
+ .option("--all", "Move every local asset that isn't already moving")
54
+ .option("--keep-local", "Share a copy and keep the local assets as separate ones")
55
+ .option("--no-keep-local", "Make the shared copy the only one; the local copy is removed once it exists")
51
56
  .option("--to <origin>", "Destination, such as me, org or team/web. Defaults to me in cloud, org in Git")
52
57
  .option("--as <name>", "New name, for moving one asset whose name is taken")
53
58
  .option("--repo <url>", "Send to this Git repo; this machine stays as it is")
54
59
  .option("--server <url>", "Send to this Cloud Workspace; this machine stays as it is")
60
+ .addHelpText("after", `
61
+ Without names, a terminal lists your local assets to pick from; elsewhere, name them or pass --all.
62
+
63
+ It then asks whether to move them or keep separate local copies; --keep-local or --no-keep-local answers without asking.
64
+ Move: the shared copy becomes the only one. Once it exists, the next sync installs it and removes the local copy.
65
+ A move into a Git repo with assets in it waits for its pull request: until it merges, local list shows
66
+ the asset as moving and the local copy stays in use. A local copy edited before then stays as a separate asset.
67
+ Keep: a copy is shared and the local asset stays. When both have the same name, sync asks which to rename.
68
+ With --repo or --server this machine stays as it is, so the assets are always copied.`)
55
69
  .action(async (names, options) => {
70
+ const chosen = await chooseNames(names, options.all);
71
+ // --repo and --server send a copy and leave this machine as it is.
72
+ const oneOff = Boolean(options.repo || options.server);
73
+ const keepLocal = options.keepLocal ?? (oneOff || (await askKeepLocal(chosen?.length)));
56
74
  const result = await context.moveLocalAssets({
57
- names,
75
+ names: chosen,
76
+ keepLocal,
58
77
  to: options.to,
59
78
  as: options.as,
60
79
  repo: options.repo,
@@ -67,6 +86,25 @@ export function registerWorkspace(program, context) {
67
86
  context.write(line);
68
87
  }
69
88
  });
89
+ /** The names to move; undefined means every local asset not already moving. */
90
+ async function chooseNames(names, all) {
91
+ if (all && names.length) {
92
+ throw new CliError("Name the assets to move or pass --all, not both.", "barndog local move --help");
93
+ }
94
+ if (all || names.length) {
95
+ return all ? undefined : names;
96
+ }
97
+ if (!context.mode.interactive) {
98
+ throw new CliError("Name the local assets to move, or pass --all.", "barndog local move <names...> --keep-local, or barndog local move --all --no-keep-local");
99
+ }
100
+ return pickLocalAssets(await context.listLocalAssets());
101
+ }
102
+ async function askKeepLocal(count) {
103
+ if (!context.mode.interactive) {
104
+ throw new CliError("Say whether to keep separate local copies: --keep-local keeps them, --no-keep-local makes the shared copy the only one.", "barndog local move --help");
105
+ }
106
+ return chooseKeepLocal(count ?? 2);
107
+ }
70
108
  program
71
109
  .command("migrate")
72
110
  .description("Move a Git repo or local workspace to a BarnDog Cloud Workspace")
@@ -21,11 +21,30 @@ export function barndogPaths(home) {
21
21
  syncLock: join(root, "sync.lock"),
22
22
  /** Backups of config.yaml and native files taken before BarnDog changes them. */
23
23
  migrations: join(root, "migrations"),
24
+ /** One folder per `barndog adopt`: its record and the originals it moved aside. */
25
+ adoptions: join(root, "adoptions"),
26
+ adoption: (id) => {
27
+ const folder = join(root, "adoptions", id);
28
+ return {
29
+ folder,
30
+ record: join(folder, "record.json"),
31
+ /** Each tool settings file as it was before the adoption changed it. */
32
+ settings: join(folder, "settings"),
33
+ /** Skill folders taken out of the tools: `<harness>/<name>`. */
34
+ skills: join(folder, "skills"),
35
+ };
36
+ },
24
37
  /** The last Cloud catalog revision a background sync delivered. */
25
38
  cloudCheck: join(root, "cloud-check.json"),
26
39
  /** Saved sessions, per server. */
27
40
  credentials: join(root, "credentials.json"),
28
41
  credentialsLock: join(root, "credentials.lock"),
42
+ /**
43
+ * MCP variable values kept on this machine only, by variable name. Never
44
+ * uploaded; sync writes them into the coding tools' settings.
45
+ */
46
+ secrets: join(root, "secrets.json"),
47
+ secretsLock: join(root, "secrets.lock"),
29
48
  /** Where `claude mcp login` and `codex mcp login` run. */
30
49
  nativeAuth: join(root, "native-auth"),
31
50
  /** The default local workspace folder. */
@@ -4,7 +4,7 @@ import { parse, stringify } from "yaml";
4
4
  import { z } from "zod";
5
5
  import { selectionStateSchema } from "./selection.js";
6
6
  import { isHarness } from "../harnesses/registry.js";
7
- import { NAME, UUID_V4 } from "../shared/patterns.js";
7
+ import { MCP_NAME, UUID_V4 } from "../shared/patterns.js";
8
8
  import { readIfExists, writeAtomic } from "../shared/files.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { barndogPaths } from "./paths.js";
@@ -32,7 +32,9 @@ const localWorkspaceSchema = z.looseObject({
32
32
  path: z.string().refine(isAbsolute),
33
33
  workspaceId: uuid,
34
34
  });
35
- const localNamesSchema = z.record(uuid, z.string().regex(NAME).max(MAX_ASSET_NAME_LENGTH));
35
+ // An MCP server's name may hold `_` and capitals; every other kind is checked
36
+ // against its own rule when renamed.
37
+ const localNamesSchema = z.record(uuid, z.string().regex(MCP_NAME).max(MAX_ASSET_NAME_LENGTH));
36
38
  /** Every part of the file; each optional key is named only here. */
37
39
  // Loose objects keep keys this version doesn't know, as the file had them.
38
40
  const settingsSchema = z.looseObject({
@@ -98,7 +100,7 @@ export async function readSettings(home, path = barndogPaths(home).settings) {
98
100
  }
99
101
  catch (error) {
100
102
  // Someone edited the file by hand; saving runs the same checks as a guard.
101
- throw new CliError(`${path} isn't valid: ${error instanceof Error ? error.message : String(error)}. Fix it, or move it aside and set up again.`, `mv ${path} ${path}.bak && barndog init`, { cause: error });
103
+ throw new CliError(`${path} isn't valid: ${error instanceof Error ? error.message : String(error)}. Fix it, or move it aside and set up again.`, `Fix the file, or move it aside (keep a copy) and run barndog init`, { cause: error });
102
104
  }
103
105
  }
104
106
  /** The file's text, after checking the settings are valid. */
@@ -5,6 +5,7 @@ import { packageKindList } from "./selection.js";
5
5
  import { NAME, UUID_V4 } from "../shared/patterns.js";
6
6
  import { barndogPaths } from "./paths.js";
7
7
  import { readIfExists } from "../shared/files.js";
8
+ import { CliError } from "../shared/cli-error.js";
8
9
  const linkSchema = z.object({
9
10
  id: z.string().regex(UUID_V4),
10
11
  harness: z.enum(harnesses),
@@ -36,23 +37,34 @@ const stateSchema = z.looseObject({
36
37
  * missing state yields no links.
37
38
  */
38
39
  export async function readState(home) {
39
- const text = await readIfExists(barndogPaths(home).state);
40
+ const path = barndogPaths(home).state;
41
+ const text = await readIfExists(path);
40
42
  if (text === null) {
41
43
  return { version: 1, links: [], native: [], installed: [] };
42
44
  }
43
- const parsed = stateSchema.safeParse(JSON.parse(text));
45
+ // Without this record BarnDog can't tell its own entries from yours, so
46
+ // nothing is changed until it is repaired.
47
+ const damaged = (cause) => new CliError(`${path} is damaged, so BarnDog won't change your tools' files.`, "Undo any edit to that file. If it can't be repaired, move it aside, remove what BarnDog installed in your tools, then run barndog sync", { cause });
48
+ let value;
49
+ try {
50
+ value = JSON.parse(text);
51
+ }
52
+ catch (error) {
53
+ throw damaged(error);
54
+ }
55
+ const parsed = stateSchema.safeParse(value);
44
56
  if (!parsed.success) {
45
- throw new Error("Invalid installation state; refusing to modify harness files", { cause: parsed.error });
57
+ throw damaged(parsed.error);
46
58
  }
47
59
  const state = parsed.data;
48
60
  for (const entry of state.native) {
49
61
  if (entry.file !== nativeFile(entry.harness, entry.kind, home)) {
50
- throw new Error("Invalid native installation state");
62
+ throw damaged();
51
63
  }
52
64
  }
53
65
  for (const entry of state.installed) {
54
66
  if (dirname(entry.path) !== barndogPaths(home).installed(entry.kind)) {
55
- throw new Error("Invalid installed package state");
67
+ throw damaged();
56
68
  }
57
69
  }
58
70
  const targets = new Set();
@@ -61,7 +73,7 @@ export async function readState(home) {
61
73
  if (dirname(link.target) !== skillDirectory(link.harness, home) ||
62
74
  !NAME.test(basename(link.target)) ||
63
75
  targets.has(link.target)) {
64
- throw new Error("Invalid installation state; refusing to modify harness files");
76
+ throw damaged();
65
77
  }
66
78
  targets.add(link.target);
67
79
  checked.push(link);
@@ -0,0 +1,234 @@
1
+ /**
2
+ * `barndog adopt`: copy assets the user set up in their coding tools into
3
+ * BarnDog's local folder, take the originals out of the tools, and sync so
4
+ * BarnDog's copies install in their place. `undo.ts` puts them back.
5
+ */
6
+ import { randomUUID } from "node:crypto";
7
+ import { copyFile, lstat, mkdir } from "node:fs/promises";
8
+ import { basename, dirname, join } from "node:path";
9
+ import { stringify } from "yaml";
10
+ import { barndogPaths } from "../../config/paths.js";
11
+ import { readSettings } from "../../config/settings.js";
12
+ import { readState } from "../../config/state.js";
13
+ import { CliError, friendlyMessage } from "../../errors.js";
14
+ import { POSIX_MODE } from "../../shared/constants.js";
15
+ import { ifExists, writeAtomic } from "../../shared/files.js";
16
+ import { defined } from "../../shared/lookup.js";
17
+ import { assetKinds } from "../asset-kinds/index.js";
18
+ import { synchronize } from "../environment/sync.js";
19
+ import { locked } from "../environment/transaction.js";
20
+ import { ensureLocalWorkspace } from "../imports/local.js";
21
+ import { literalNotes } from "../mcps/import.js";
22
+ import { readSecrets, updateSecrets } from "../secrets/index.js";
23
+ import { writePackage } from "../workspace/directory.js";
24
+ import { localRepoSource } from "../workspace/repo-source.js";
25
+ import { copyFingerprint, installed } from "./copies.js";
26
+ import { takeOut } from "./originals.js";
27
+ import { restore } from "./restore.js";
28
+ import { readAdoptions, writeAdoption, } from "./record.js";
29
+ import { findNativeAssets, } from "./scan.js";
30
+ /**
31
+ * What adopting `keys` takes over: each chosen asset, plus other tools'
32
+ * Skills and MCP servers of the same name, which BarnDog's one copy replaces.
33
+ */
34
+ export function adoptionPlan(scan, keys) {
35
+ const byKey = new Map(scan.assets.map((asset) => [asset.key, asset]));
36
+ const unknown = keys.filter((key) => !byKey.has(key));
37
+ if (unknown.length) {
38
+ throw new CliError(`${unknown.join(", ")} ${unknown.length === 1 ? "isn't an asset" : "aren't assets"} BarnDog can adopt.`, "barndog adopt --dry-run");
39
+ }
40
+ const planned = new Map();
41
+ for (const key of keys) {
42
+ const asset = byKey.get(key);
43
+ if (!asset || planned.has(key)) {
44
+ continue;
45
+ }
46
+ const group = [key, ...asset.sameName.map((other) => other.key)];
47
+ const chosen = group.filter((other) => keys.includes(other));
48
+ const differing = chosen.find((other) => other !== key && !byKey.get(other)?.identical);
49
+ if (differing) {
50
+ throw new CliError(`${key} and ${differing} are different ${assetKinds[asset.kind].many} with the same name, and BarnDog installs one copy in every tool.`, `barndog adopt --only ${key}`);
51
+ }
52
+ for (const member of group) {
53
+ const found = byKey.get(member);
54
+ if (found) {
55
+ planned.set(member, {
56
+ ...found,
57
+ source: { key, harness: asset.harness },
58
+ });
59
+ }
60
+ }
61
+ }
62
+ return [...planned.values()];
63
+ }
64
+ async function hasSharedWorkspace(home) {
65
+ const settings = await readSettings(home);
66
+ return Boolean(settings?.connection ?? settings?.gitWorkspace);
67
+ }
68
+ /** Same-named copies share one source, so each source's notes appear once. */
69
+ function adoptionNotes(plan, sourceOf, keep) {
70
+ const sources = new Map(plan.map((asset) => [asset.source.key, asset]));
71
+ return [...sources.values()].flatMap((asset) => {
72
+ const source = sourceOf(asset);
73
+ return [...source.notes, ...literalNotes(source.literals, keep)].map((text) => ({ kind: asset.kind, name: asset.name, text }));
74
+ });
75
+ }
76
+ /**
77
+ * Keeps the chosen values before the sync that writes them into the tools,
78
+ * and returns how to put the file back as it was if adopting fails.
79
+ */
80
+ async function keepValues(literals, keep, runtime) {
81
+ const chosen = literals.filter((l) => keep.includes(l.variable));
82
+ if (!chosen.length) {
83
+ return async () => { };
84
+ }
85
+ const before = await readSecrets(runtime);
86
+ await updateSecrets(Object.fromEntries(chosen.map((l) => [l.variable, l.value])), runtime);
87
+ return async () => {
88
+ await updateSecrets(Object.fromEntries(chosen.map((l) => [l.variable, before[l.variable] ?? null])), runtime);
89
+ };
90
+ }
91
+ /** Takes over the chosen assets; on any failure, puts back what it changed. */
92
+ export async function adoptNative(keys,
93
+ /** Variables whose values BarnDog keeps on this machine (see `mcp env`). */
94
+ keep, runtime) {
95
+ const { home } = runtime;
96
+ return locked(runtime, async () => {
97
+ const unfinished = (await readAdoptions(home)).find((record) => record.status === "pending");
98
+ if (unfinished) {
99
+ throw new CliError("An earlier adoption didn't finish. Undo it before adopting more.", `barndog adopt undo ${unfinished.id}`);
100
+ }
101
+ const { found, skipped } = await findNativeAssets(runtime);
102
+ const plan = adoptionPlan({ assets: found, skipped }, keys);
103
+ if (!plan.length) {
104
+ throw new CliError("Choose at least one asset to adopt.", "barndog adopt");
105
+ }
106
+ const workspace = await ensureLocalWorkspace(runtime);
107
+ const id = randomUUID();
108
+ const paths = barndogPaths(home).adoption(id);
109
+ const byKey = new Map(found.map((asset) => [asset.key, asset]));
110
+ const scanned = (key) => defined(byKey.get(key), `The scan found no ${key}`);
111
+ const sourceOf = (asset) => scanned(asset.source.key);
112
+ const record = {
113
+ id,
114
+ createdAt: new Date().toISOString(),
115
+ status: "pending",
116
+ files: [],
117
+ items: plan.map((asset) => {
118
+ const { copy, original } = scanned(asset.key);
119
+ return {
120
+ key: asset.key,
121
+ harness: asset.harness,
122
+ kind: asset.kind,
123
+ name: asset.name,
124
+ description: asset.description,
125
+ copy: join(workspace.path, copy),
126
+ assetId: "",
127
+ fingerprint: "",
128
+ original,
129
+ backup: original.type === "folder"
130
+ ? join(paths.skills, asset.harness, asset.name)
131
+ : undefined,
132
+ undone: false,
133
+ };
134
+ }),
135
+ };
136
+ // Undo removes every copy, so none may be there already.
137
+ for (const item of record.items) {
138
+ if ((await ifExists(lstat(item.copy))) !== null) {
139
+ throw new CliError(`${item.copy} already exists, so ${item.name} can't be adopted.`, "barndog adopt --dry-run");
140
+ }
141
+ }
142
+ // Written before anything changes, so undo can always find what moved.
143
+ await writeAdoption(record, home);
144
+ const sources = [
145
+ ...new Map(plan.map((asset) => [asset.source.key, asset])).values(),
146
+ ].map(sourceOf);
147
+ let forgetValues = async () => { };
148
+ try {
149
+ forgetValues = await keepValues(sources.flatMap((source) => source.literals), keep, runtime);
150
+ const events = await apply({ record, plan, sourceOf, workspace }, runtime);
151
+ return {
152
+ id,
153
+ adopted: plan,
154
+ backup: paths.folder,
155
+ notes: adoptionNotes(plan, sourceOf, keep),
156
+ events,
157
+ canShare: await hasSharedWorkspace(home),
158
+ };
159
+ }
160
+ catch (error) {
161
+ await restore(record, record.items, runtime).catch((undoError) => {
162
+ throw new CliError(`Adopting failed (${friendlyMessage(error)}), and putting things back failed too: ${friendlyMessage(undoError)}`, `barndog adopt undo ${id}`, { cause: error });
163
+ });
164
+ await forgetValues();
165
+ throw error;
166
+ }
167
+ });
168
+ }
169
+ async function apply(input, runtime) {
170
+ const { home } = runtime;
171
+ const { record, plan, sourceOf, workspace } = input;
172
+ // One copy per name: tools that had the same asset share it.
173
+ const written = new Map();
174
+ for (const [index, asset] of plan.entries()) {
175
+ const item = defined(record.items[index], "Each planned asset has an item");
176
+ if (!written.has(item.copy)) {
177
+ await writeCopy(item.copy, sourceOf(asset), runtime);
178
+ written.set(item.copy, defined(await copyFingerprint(item, runtime), "The copy was written"));
179
+ }
180
+ item.fingerprint = defined(written.get(item.copy), "The copy was written");
181
+ }
182
+ const model = await localRepoSource(workspace, runtime).model();
183
+ for (const item of record.items) {
184
+ const asset = model.assets.find((candidate) => join(workspace.path, candidate.path) === item.copy);
185
+ if (!asset || asset.invalid) {
186
+ throw new CliError(`BarnDog couldn't read its copy of ${item.name}: ${asset?.invalid ?? "it's missing"}.`);
187
+ }
188
+ item.assetId = asset.id;
189
+ }
190
+ // A settings file is saved as the user left it, before BarnDog's first change.
191
+ for (const item of record.items) {
192
+ const { original } = item;
193
+ if (original.type === "entry" &&
194
+ !record.files.some((saved) => saved.file === original.file)) {
195
+ const backup = join(barndogPaths(home).adoption(record.id).settings, `${record.files.length + 1}-${basename(original.file)}`);
196
+ await mkdir(dirname(backup), { recursive: true });
197
+ await copyFile(original.file, backup);
198
+ record.files.push({ file: original.file, backup });
199
+ }
200
+ }
201
+ await writeAdoption(record, home);
202
+ for (const item of record.items) {
203
+ await takeOut(item.harness, item.original, item.backup);
204
+ }
205
+ const events = await synchronize(undefined, runtime, undefined, {
206
+ prompt: false,
207
+ });
208
+ const state = await readState(home);
209
+ const missing = record.items.filter((item) => !installed(item, state));
210
+ if (missing.length) {
211
+ const clashes = events.flatMap((event) => event.type === "clash" &&
212
+ missing.some((item) => item.name === event.skipped.name)
213
+ ? [
214
+ `BarnDog already installs ${event.kind === "skill" ? "a Skill" : "an MCP server"} named ${event.installed.name} from ${event.installed.origin}.`,
215
+ ]
216
+ : []);
217
+ throw new CliError(`BarnDog couldn't install ${missing.map((item) => item.key).join(", ")}, so nothing was adopted. ${clashes.join(" ")}`.trim(), "Rename yours in its coding tool, then run barndog adopt again");
218
+ }
219
+ record.status = "applied";
220
+ await writeAdoption(record, home);
221
+ return events;
222
+ }
223
+ async function writeCopy(path, asset, runtime) {
224
+ const { content } = asset;
225
+ // The workspace's own folders keep default permissions; writeAtomic would make them private.
226
+ await mkdir(dirname(path), { recursive: true });
227
+ if (content.kind === "mcp") {
228
+ await writeAtomic(path, stringify(content.definition), {
229
+ mode: POSIX_MODE.regularFile,
230
+ });
231
+ return;
232
+ }
233
+ await writePackage(path, content.entries, runtime);
234
+ }
@@ -0,0 +1,29 @@
1
+ /** BarnDog's copy of an adopted asset: what it holds, and whether sync installed it. */
2
+ import { lstat, readFile } from "node:fs/promises";
3
+ import { basename } from "node:path";
4
+ import { packageFingerprint } from "@barndog-ai/api-contract/package";
5
+ import { ifExists } from "../../shared/files.js";
6
+ import { readDirectory } from "../workspace/directory.js";
7
+ /** What BarnDog's copy holds now, to tell later whether someone edited it. */
8
+ export async function copyFingerprint(item, runtime) {
9
+ if (item.kind === "mcp") {
10
+ const data = await ifExists(readFile(item.copy));
11
+ return data === null
12
+ ? null
13
+ : packageFingerprint([
14
+ { path: basename(item.copy), data, executable: false },
15
+ ]);
16
+ }
17
+ return (await ifExists(lstat(item.copy))) === null
18
+ ? null
19
+ : packageFingerprint(await readDirectory(item.copy, runtime));
20
+ }
21
+ /** Whether the last sync installed an adopted asset in the tool it came from. */
22
+ export function installed(item, state) {
23
+ if (item.kind === "skill") {
24
+ return state.links.some((link) => link.id === item.assetId && link.harness === item.harness);
25
+ }
26
+ return state.native.some((entry) => entry.id === item.assetId &&
27
+ entry.harness === item.harness &&
28
+ entry.kind === item.kind);
29
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Taking an asset out of its coding tool and putting it back. Each step checks
3
+ * the disk first, so running it again after a crash does only what is left.
4
+ */
5
+ import { cp, lstat, mkdir, readlink, rename, rm, symlink, unlink, } from "node:fs/promises";
6
+ import { dirname } from "node:path";
7
+ import { isDeepStrictEqual } from "node:util";
8
+ import { parse as parseJsonc } from "jsonc-parser";
9
+ import { parse as parseToml } from "smol-toml";
10
+ import { CliError } from "../../errors.js";
11
+ import { adapters } from "../../harnesses/registry.js";
12
+ import { directoryLinkType } from "../../platform.js";
13
+ import { ifExists, readIfExists, writeAtomic } from "../../shared/files.js";
14
+ import { asRecord } from "../../shared/values.js";
15
+ import { errorCode } from "../../shared/values.js";
16
+ import { patchNative } from "../native/configuration.js";
17
+ /** A rename can't cross disks, so a folder on another one is copied, then removed. */
18
+ async function moveFolder(from, to) {
19
+ await mkdir(dirname(to), { recursive: true });
20
+ try {
21
+ await rename(from, to);
22
+ }
23
+ catch (error) {
24
+ if (errorCode(error) !== "EXDEV") {
25
+ throw error;
26
+ }
27
+ await cp(from, to, { recursive: true, verbatimSymlinks: true });
28
+ await rm(from, { recursive: true, force: true });
29
+ }
30
+ }
31
+ const nativeEntry = (harness, original) => ({
32
+ id: "adoption",
33
+ kind: original.kind,
34
+ harness,
35
+ file: original.file,
36
+ key: original.key,
37
+ value: original.value,
38
+ });
39
+ /** Whether the tool's settings file holds this entry exactly as it was adopted. */
40
+ function holds(text, harness, original) {
41
+ if (text === null) {
42
+ return false;
43
+ }
44
+ const data = asRecord(original.file.endsWith(".toml") ? parseToml(text) : parseJsonc(text));
45
+ if (original.kind === "mcp") {
46
+ const servers = adapters[harness].mcp.path.reduce((value, key) => asRecord(value)[key], data);
47
+ return isDeepStrictEqual(asRecord(servers)[original.key], original.value);
48
+ }
49
+ const list = asRecord(data.hooks)[original.key];
50
+ return (Array.isArray(list) &&
51
+ list.some((entry) => isDeepStrictEqual(entry, original.value)));
52
+ }
53
+ /** Takes an asset out of its tool; a Skill folder moves to `backup`. */
54
+ export async function takeOut(harness, original, backup) {
55
+ switch (original.type) {
56
+ case "folder": {
57
+ if (!backup) {
58
+ throw new Error("A Skill folder is adopted without a backup path");
59
+ }
60
+ if ((await ifExists(lstat(original.path))) !== null) {
61
+ await moveFolder(original.path, backup);
62
+ }
63
+ return;
64
+ }
65
+ case "link": {
66
+ if ((await ifExists(lstat(original.path))) !== null) {
67
+ await unlink(original.path);
68
+ }
69
+ return;
70
+ }
71
+ case "entry": {
72
+ const text = await readIfExists(original.file);
73
+ if (holds(text, harness, original)) {
74
+ await writeAtomic(original.file, patchNative(text, [nativeEntry(harness, original)], []));
75
+ }
76
+ return;
77
+ }
78
+ }
79
+ }
80
+ /** Puts an asset back where it was, refusing to replace anything that took its place. */
81
+ export async function putBack(harness, original, backup, runtime) {
82
+ const occupied = (path) => new CliError(`${path} exists again, so BarnDog can't put the adopted copy back there.`, "Move it aside, then run barndog adopt undo again");
83
+ switch (original.type) {
84
+ case "folder": {
85
+ const saved = backup && (await ifExists(lstat(backup)));
86
+ if (!backup || !saved) {
87
+ return;
88
+ }
89
+ if ((await ifExists(lstat(original.path))) !== null) {
90
+ throw occupied(original.path);
91
+ }
92
+ await moveFolder(backup, original.path);
93
+ return;
94
+ }
95
+ case "link": {
96
+ const existing = await ifExists(lstat(original.path));
97
+ if (existing) {
98
+ if (existing.isSymbolicLink() &&
99
+ (await readlink(original.path)) === original.target) {
100
+ return;
101
+ }
102
+ throw occupied(original.path);
103
+ }
104
+ await mkdir(dirname(original.path), { recursive: true });
105
+ await symlink(original.target, original.path, directoryLinkType(runtime.platform));
106
+ return;
107
+ }
108
+ case "entry": {
109
+ const text = await readIfExists(original.file);
110
+ if (!holds(text, harness, original)) {
111
+ await writeAtomic(original.file, patchNative(text, [], [nativeEntry(harness, original)]));
112
+ }
113
+ return;
114
+ }
115
+ }
116
+ }