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
@@ -0,0 +1,126 @@
1
+ /**
2
+ * `barndog uninstall`: takes BarnDog off this machine. BarnDog's own
3
+ * registrations (the session-start sync, the knowledge index, OpenCode's
4
+ * plugin module) always go. The developer's Skills, MCP servers and Hooks
5
+ * either stay in each coding tool as plain files of its own, or go too, with
6
+ * adopted assets put back where they came from. Then every session is signed
7
+ * out and `~/.barndog/` is deleted, except the local workspace when kept.
8
+ */
9
+ import { readdir, rm } from "node:fs/promises";
10
+ import { basename, join, relative, sep } from "node:path";
11
+ import { barndogPaths } from "../../config/paths.js";
12
+ import { readSettings } from "../../config/settings.js";
13
+ import { readState } from "../../config/state.js";
14
+ import { fileText, ifExists, isInside } from "../../shared/files.js";
15
+ import { readAdoptions } from "../adoption/record.js";
16
+ import { undoAdoption } from "../adoption/undo.js";
17
+ import { signOutEverywhere } from "../auth/session.js";
18
+ import { locked, transact } from "../environment/transaction.js";
19
+ import { entryNames, linkWrites, nativeWrites, stateText, } from "../environment/writes.js";
20
+ import { leaveInPlace } from "./leave.js";
21
+ import { mcpVariables } from "./survey.js";
22
+ /** Undoes each adoption holding a chosen asset: whole when unfinished or fully chosen. */
23
+ async function restoreAdopted(options, runtime) {
24
+ if (options.keepSetup || !options.restore.length) {
25
+ return [];
26
+ }
27
+ const restored = [];
28
+ for (const record of await readAdoptions(runtime.home)) {
29
+ const open = record.items.filter((item) => !item.undone);
30
+ const chosen = open.filter((item) => options.restore.includes(item.key));
31
+ if (record.status === "undone" || !chosen.length) {
32
+ continue;
33
+ }
34
+ const whole = record.status === "pending" || chosen.length === open.length;
35
+ const result = await undoAdoption({
36
+ id: record.id,
37
+ only: whole ? undefined : chosen.map((item) => item.key),
38
+ force: options.force,
39
+ }, runtime);
40
+ restored.push(...result.restored);
41
+ }
42
+ return restored;
43
+ }
44
+ /**
45
+ * Takes BarnDog's entries out of the coding tools' settings (all of them, or
46
+ * only its own registrations when the setup stays, with Hooks pointed at
47
+ * their new folders), removes Skill links, and empties `state.json`, as one
48
+ * journaled change.
49
+ */
50
+ async function removeEntries(keepSetup, runtime) {
51
+ const { home } = runtime;
52
+ const stateFile = barndogPaths(home).state;
53
+ const state = await readState(home);
54
+ const kept = keepSetup
55
+ ? await leaveInPlace(state, runtime)
56
+ : { left: [], hooks: [] };
57
+ // MCP entries that stay aren't BarnDog's to edit any more, so they are left out.
58
+ const previous = keepSetup
59
+ ? state.native.filter((entry) => entry.kind !== "mcp")
60
+ : state.native;
61
+ const nameOf = entryNames(state.installed.map((entry) => [entry.id, basename(entry.path)]));
62
+ const settings = await nativeWrites(previous, kept.hooks, {
63
+ trees: [],
64
+ updated: new Set(),
65
+ nameOf,
66
+ platform: runtime.platform,
67
+ });
68
+ // A Skill left in place is a folder now, so only links still to remove are written.
69
+ const links = keepSetup
70
+ ? { writes: [], events: [] }
71
+ : await linkWrites(state.links, [], new Set());
72
+ const writes = [
73
+ ...links.writes,
74
+ ...settings.writes,
75
+ {
76
+ kind: "file",
77
+ path: stateFile,
78
+ before: await fileText(stateFile),
79
+ after: stateText({ links: [], native: [], trees: [] }),
80
+ },
81
+ ];
82
+ await transact(runtime, writes);
83
+ const removed = [...links.events, ...settings.events].filter((event) => event.type === "removed" ||
84
+ (event.type === "native" && event.action === "removed"));
85
+ return {
86
+ left: kept.left,
87
+ removed,
88
+ variables: keepSetup ? mcpVariables(state) : [],
89
+ };
90
+ }
91
+ /** Deletes `root`, or everything in it except the top folder holding `keep`. */
92
+ async function deleteRoot(root, keep) {
93
+ if (!keep) {
94
+ await rm(root, { recursive: true, force: true });
95
+ return;
96
+ }
97
+ const [top] = relative(root, keep).split(sep);
98
+ for (const name of (await ifExists(readdir(root))) ?? []) {
99
+ if (name !== top) {
100
+ await rm(join(root, name), { recursive: true, force: true });
101
+ }
102
+ }
103
+ }
104
+ export async function uninstall(options, runtime) {
105
+ const root = barndogPaths(runtime.home).root;
106
+ // Read before anything changes; a damaged config.yaml only means no workspace to keep.
107
+ const settings = await readSettings(runtime.home).catch(() => null);
108
+ const workspace = settings?.localWorkspace?.path;
109
+ const restored = await restoreAdopted(options, runtime);
110
+ const { left, removed, variables } = await locked(runtime, () => removeEntries(options.keepSetup, runtime));
111
+ const signedOut = await signOutEverywhere(runtime);
112
+ const keptWorkspace = options.keepWorkspace && workspace && isInside(root, workspace)
113
+ ? workspace
114
+ : undefined;
115
+ await deleteRoot(root, keptWorkspace);
116
+ return {
117
+ keptSetup: options.keepSetup,
118
+ left,
119
+ removed,
120
+ variables,
121
+ restored,
122
+ signedOut,
123
+ root,
124
+ keptWorkspace,
125
+ };
126
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Leaves BarnDog's Skills and Hooks in each coding tool as plain files of the
3
+ * tool's own, so they keep working once `~/.barndog/` is gone: each Skill link
4
+ * becomes a copy of the folder it pointed at, and each Hook folder is copied
5
+ * beside the tool's hook settings, where its registrations are pointed next.
6
+ * MCP entries need nothing: they never point into BarnDog's files.
7
+ *
8
+ * Every step checks what is already done, so an interrupted uninstall can run
9
+ * again.
10
+ */
11
+ import { cp, lstat, rename, rm, unlink } from "node:fs/promises";
12
+ import { basename, dirname, join } from "node:path";
13
+ import { CliError } from "../../errors.js";
14
+ import { isHookHarness, nativeFile } from "../../harnesses/registry.js";
15
+ import { ifExists } from "../../shared/files.js";
16
+ import { isRecord } from "../../shared/values.js";
17
+ import { movedHookCommand } from "../native/hook-shell.js";
18
+ import { linkTarget } from "../environment/transaction.js";
19
+ import { treeFingerprint } from "../workspace/tree.js";
20
+ /** Where a Hook's folder goes: `hooks/<name>` beside the tool's hook settings. */
21
+ const hookFolder = (harness, name, home) => join(dirname(nativeFile(harness, "hook", home)), "hooks", name);
22
+ function placements(state, home) {
23
+ const skills = state.links.map((link) => ({
24
+ kind: "skill",
25
+ name: basename(link.target),
26
+ harness: link.harness,
27
+ path: link.target,
28
+ source: link.source,
29
+ }));
30
+ const hooks = [];
31
+ for (const entry of state.native) {
32
+ const folder = state.installed.find((installed) => installed.kind === "hook" && installed.id === entry.id);
33
+ if (entry.kind !== "hook" ||
34
+ !folder ||
35
+ hooks.some((hook) => hook.source === folder.path && hook.harness === entry.harness)) {
36
+ continue;
37
+ }
38
+ const name = basename(folder.path);
39
+ hooks.push({
40
+ kind: "hook",
41
+ name,
42
+ harness: entry.harness,
43
+ path: hookFolder(entry.harness, name, home),
44
+ source: folder.path,
45
+ });
46
+ }
47
+ return [...skills, ...hooks];
48
+ }
49
+ /**
50
+ * Whether the folder is already in place: true when `path` holds the same
51
+ * files as `source`. Throws when something else is there.
52
+ */
53
+ async function placed(placement, runtime) {
54
+ const { path, source } = placement;
55
+ const info = await ifExists(lstat(path));
56
+ if (!info) {
57
+ return false;
58
+ }
59
+ if (info.isSymbolicLink() && placement.kind === "skill") {
60
+ if ((await linkTarget(path)) !== source) {
61
+ throw new CliError(`${path} was changed outside BarnDog, so uninstall stopped before changing anything.`, "Restore or remove that link, then run barndog uninstall again");
62
+ }
63
+ return false;
64
+ }
65
+ const [here, there] = await Promise.all([
66
+ treeFingerprint(path, runtime),
67
+ treeFingerprint(source, runtime),
68
+ ]);
69
+ if (here === null || here !== there) {
70
+ throw new CliError(`${path} already exists, so BarnDog can't leave its ${placement.name} ${placement.kind === "skill" ? "Skill" : "Hook"} there.`, "Move it aside, then run barndog uninstall again");
71
+ }
72
+ return true;
73
+ }
74
+ /** Copies beside the destination first, so a Skill is never missing for long. */
75
+ async function place(placement) {
76
+ const { path, source } = placement;
77
+ const staging = `${path}.barndog-uninstall`;
78
+ await rm(staging, { recursive: true, force: true });
79
+ await cp(source, staging, { recursive: true });
80
+ if (await ifExists(lstat(path))) {
81
+ await unlink(path);
82
+ }
83
+ await rename(staging, path);
84
+ }
85
+ /** The Hook registration with its root variables pointing at `to`. */
86
+ function movedHook(entry, folders, platform) {
87
+ const { harness } = entry;
88
+ if (!isHookHarness(harness)) {
89
+ throw new Error(`${harness} has no hook settings to move a Hook in`);
90
+ }
91
+ return {
92
+ ...entry,
93
+ value: mapCommands(entry.value, (command) => {
94
+ const moved = movedHookCommand(command, folders, harness, platform);
95
+ if (moved === undefined) {
96
+ throw new Error(`A ${entry.key} Hook registration doesn't start the way BarnDog writes it`);
97
+ }
98
+ return moved;
99
+ }),
100
+ };
101
+ }
102
+ /** Rewrites the handler's `command`, or each of its nested `hooks[].command`. */
103
+ function mapCommands(value, change) {
104
+ const next = { ...value };
105
+ if (typeof next.command === "string") {
106
+ next.command = change(next.command);
107
+ }
108
+ if (Array.isArray(next.hooks)) {
109
+ next.hooks = next.hooks.map((hook) => isRecord(hook) && typeof hook.command === "string"
110
+ ? { ...hook, command: change(hook.command) }
111
+ : hook);
112
+ }
113
+ return next;
114
+ }
115
+ /**
116
+ * Puts every Skill and Hook folder in place and returns the Hook registrations
117
+ * pointed at their new folders, for the caller to write with the rest.
118
+ */
119
+ export async function leaveInPlace(state, runtime) {
120
+ const planned = placements(state, runtime.home);
121
+ // Check every destination before changing any.
122
+ const done = new Set();
123
+ for (const placement of planned) {
124
+ if (await placed(placement, runtime)) {
125
+ done.add(placement);
126
+ }
127
+ }
128
+ for (const placement of planned) {
129
+ if (!done.has(placement)) {
130
+ await place(placement);
131
+ }
132
+ }
133
+ const hooks = state.native.flatMap((entry) => {
134
+ const folder = planned.find((placement) => placement.kind === "hook" &&
135
+ placement.harness === entry.harness &&
136
+ state.installed.some((installed) => installed.id === entry.id && installed.path === placement.source));
137
+ return entry.kind === "hook" && folder
138
+ ? [
139
+ movedHook(entry, { from: folder.source, to: folder.path }, runtime.platform),
140
+ ]
141
+ : [];
142
+ });
143
+ return {
144
+ left: planned.map(({ kind, name, harness, path }) => ({
145
+ kind,
146
+ name,
147
+ harness,
148
+ path,
149
+ })),
150
+ hooks,
151
+ };
152
+ }
@@ -0,0 +1,103 @@
1
+ /** What `barndog uninstall` would find to remove or leave on this machine. */
2
+ import { lstat } from "node:fs/promises";
3
+ import { basename } from "node:path";
4
+ import { barndogPaths } from "../../config/paths.js";
5
+ import { readSettings } from "../../config/settings.js";
6
+ import { readState } from "../../config/state.js";
7
+ import { CliError } from "../../errors.js";
8
+ import { secretRefs } from "../../harnesses/formats.js";
9
+ import { adapters } from "../../harnesses/registry.js";
10
+ import { ifExists, isInside } from "../../shared/files.js";
11
+ import { readCredentials } from "../auth/credentials.js";
12
+ import { readAdoptions, summary, } from "../adoption/record.js";
13
+ import { convertServer } from "../mcps/import.js";
14
+ /** The installed folder name a Hook registration's asset ID refers to. */
15
+ const hookName = (id, state) => {
16
+ const folder = state.installed.find((entry) => entry.kind === "hook" && entry.id === id);
17
+ return folder ? basename(folder.path) : id;
18
+ };
19
+ /** Each asset once per tool; a Hook has one entry per event it handles. */
20
+ function installedAssets(state) {
21
+ const assets = state.links.map((link) => ({
22
+ kind: "skill",
23
+ name: basename(link.target),
24
+ harness: link.harness,
25
+ }));
26
+ for (const entry of state.native) {
27
+ if (entry.kind !== "mcp" && entry.kind !== "hook") {
28
+ continue;
29
+ }
30
+ const name = entry.kind === "mcp" ? entry.key : hookName(entry.id, state);
31
+ if (!assets.some((asset) => asset.kind === entry.kind &&
32
+ asset.name === name &&
33
+ asset.harness === entry.harness)) {
34
+ assets.push({ kind: entry.kind, name, harness: entry.harness });
35
+ }
36
+ }
37
+ return assets;
38
+ }
39
+ /** An MCP entry BarnDog wrote, read back the way `mcp add --from` reads one. */
40
+ function definitionOf(entry) {
41
+ const { imported } = adapters[entry.harness].mcp;
42
+ try {
43
+ return convertServer({
44
+ name: entry.key,
45
+ server: imported ? imported(entry.value) : entry.value,
46
+ });
47
+ }
48
+ catch (error) {
49
+ if (error instanceof CliError) {
50
+ return undefined;
51
+ }
52
+ throw error;
53
+ }
54
+ }
55
+ /**
56
+ * The variables BarnDog's MCP entries read from the environment, each once.
57
+ * A value BarnDog kept is written into the entry, so it isn't one of them.
58
+ */
59
+ export function mcpVariables(state) {
60
+ const variables = new Map();
61
+ for (const entry of state.native) {
62
+ const converted = entry.kind === "mcp" ? definitionOf(entry) : undefined;
63
+ if (!converted) {
64
+ continue;
65
+ }
66
+ const written = new Set(converted.literals.map(({ variable }) => variable));
67
+ for (const { secretRef } of Object.values(secretRefs(converted.definition))) {
68
+ if (!written.has(secretRef)) {
69
+ variables.set(secretRef, (variables.get(secretRef) ?? new Set()).add(entry.key));
70
+ }
71
+ }
72
+ }
73
+ return [...variables].map(([name, servers]) => ({
74
+ name,
75
+ servers: [...servers],
76
+ }));
77
+ }
78
+ export async function uninstallSurvey(runtime) {
79
+ const { home } = runtime;
80
+ const root = barndogPaths(home).root;
81
+ // A damaged config.yaml shouldn't stop an uninstall; only the workspace path comes from it.
82
+ const settings = await readSettings(home).catch(() => null);
83
+ const state = await readState(home);
84
+ const adoptions = await readAdoptions(home);
85
+ const { servers } = await readCredentials(runtime);
86
+ const local = settings?.localWorkspace?.path;
87
+ // Setup always puts it in ~/.barndog/workspace; a path edited to point
88
+ // elsewhere is outside what uninstall deletes, so there is nothing to ask.
89
+ const workspace = local && isInside(root, local) && (await ifExists(lstat(local)))
90
+ ? local
91
+ : undefined;
92
+ return {
93
+ root,
94
+ installed: installedAssets(state),
95
+ adopted: adoptions
96
+ .filter((record) => record.status !== "undone")
97
+ .flatMap((record) => summary(record).items)
98
+ .filter((item) => !item.undone),
99
+ workspace,
100
+ servers: Object.keys(servers),
101
+ variables: mcpVariables(state),
102
+ };
103
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Whether a newer BarnDog CLI is published. The answer comes from the public
3
+ * npm registry, whichever workspace or server the developer uses, and is
4
+ * cached in `~/.barndog/update-check.json`, so a command only reads a file;
5
+ * a detached process (`entry/update-check.ts`) refreshes it at most once a day.
6
+ */
7
+ import { stat } from "node:fs/promises";
8
+ import semver from "semver";
9
+ import { z } from "zod";
10
+ import { barndogPaths } from "../../config/paths.js";
11
+ import { HOURS_PER_DAY, MILLISECONDS_PER_MINUTE, MINUTES_PER_HOUR, } from "../../shared/constants.js";
12
+ import { ifExists, readJsonIfExists, writeAtomic } from "../../shared/files.js";
13
+ /** The package's dist-tags, from the npm registry API. */
14
+ const DIST_TAGS_URL = "https://registry.npmjs.org/-/package/barndog/dist-tags";
15
+ /** Once a day is often enough to hear about a release. */
16
+ const CHECK_INTERVAL_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * MILLISECONDS_PER_MINUTE;
17
+ /** The background check gives up rather than linger. */
18
+ const REQUEST_TIMEOUT_MS = 5000;
19
+ /**
20
+ * Variables that turn the check off. `NO_UPDATE_NOTIFIER` is the one the
21
+ * `update-notifier` package made common across npm CLIs.
22
+ */
23
+ const OPT_OUT_VARIABLES = ["BARNDOG_NO_UPDATE_CHECK", "NO_UPDATE_NOTIFIER"];
24
+ const distTagsSchema = z.object({
25
+ latest: z.string(),
26
+ next: z.string().optional(),
27
+ });
28
+ const cacheSchema = z.object({
29
+ checkedAt: z.string(),
30
+ /** Absent until the registry has answered once. */
31
+ latest: z.string().optional(),
32
+ next: z.string().optional(),
33
+ });
34
+ /** A missing or unreadable cache counts as never checked. */
35
+ async function readCache(home) {
36
+ try {
37
+ return ((await readJsonIfExists(barndogPaths(home).updateCheck, cacheSchema)) ??
38
+ undefined);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /**
45
+ * Asks the registry for the published versions and caches them. A failure is
46
+ * cached as a check that keeps the earlier answer, so an offline machine
47
+ * still waits a day before trying again.
48
+ */
49
+ export async function refreshUpdateCheck(runtime, fetchTags = fetch) {
50
+ const previous = await readCache(runtime.home);
51
+ let tags;
52
+ try {
53
+ const response = await fetchTags(DIST_TAGS_URL, {
54
+ headers: { accept: "application/json" },
55
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
56
+ });
57
+ tags = response.ok
58
+ ? distTagsSchema.parse(await response.json())
59
+ : undefined;
60
+ }
61
+ catch {
62
+ tags = undefined;
63
+ }
64
+ const cache = {
65
+ checkedAt: new Date().toISOString(),
66
+ latest: tags ? tags.latest : previous?.latest,
67
+ next: tags ? tags.next : previous?.next,
68
+ };
69
+ await writeAtomic(barndogPaths(runtime.home).updateCheck, `${JSON.stringify(cache)}\n`);
70
+ }
71
+ /**
72
+ * The newest cached version above `current`. Someone on a prerelease also
73
+ * hears about newer prereleases; everyone else only about `latest`.
74
+ */
75
+ function newestAbove(current, cache) {
76
+ if (!semver.valid(current)) {
77
+ return undefined;
78
+ }
79
+ const candidates = [];
80
+ if (cache.latest && semver.valid(cache.latest)) {
81
+ candidates.push({ current, version: cache.latest, tag: "latest" });
82
+ }
83
+ if (cache.next && semver.valid(cache.next) && semver.prerelease(current)) {
84
+ candidates.push({ current, version: cache.next, tag: "next" });
85
+ }
86
+ return candidates
87
+ .filter((candidate) => semver.gt(candidate.version, current))
88
+ .sort((a, b) => semver.rcompare(a.version, b.version))[0];
89
+ }
90
+ /**
91
+ * What to do about updates after a command, from the cache alone. Undefined
92
+ * when the check is off: by an opt-out variable, in CI, or while BarnDog isn't
93
+ * set up (before `init`, after `uninstall`), so it never creates `~/.barndog/`.
94
+ */
95
+ export async function updateCheck(current, runtime) {
96
+ const { env, home } = runtime;
97
+ if (env.CI || OPT_OUT_VARIABLES.some((name) => env[name]?.trim())) {
98
+ return undefined;
99
+ }
100
+ if (!(await ifExists(stat(barndogPaths(home).settings)))) {
101
+ return undefined;
102
+ }
103
+ const cache = await readCache(home);
104
+ return {
105
+ update: cache && newestAbove(current, cache),
106
+ due: !cache || !(Date.now() - Date.parse(cache.checkedAt) < CHECK_INTERVAL_MS),
107
+ };
108
+ }
@@ -73,17 +73,26 @@ function renderConfig(config) {
73
73
  optional: [],
74
74
  });
75
75
  }
76
- /**
77
- * Parses barndog.yaml and reports schema-invalid fields in a CliError.
78
- * Malformed YAML can throw a parser error before schema validation.
79
- */
76
+ /** Parses barndog.yaml; malformed YAML and invalid fields are a CliError. */
80
77
  export function parseConfig(text) {
81
- const parsed = configSchema.safeParse(parse(text));
78
+ let value;
79
+ try {
80
+ value = parse(text);
81
+ }
82
+ catch (error) {
83
+ throw new CliError(`${CONFIG_FILE} isn't valid YAML: ${friendlyMessage(error)}`, `Fix the YAML in ${CONFIG_FILE}, then try again`, { cause: error });
84
+ }
85
+ const parsed = configSchema.safeParse(value);
82
86
  if (!parsed.success) {
83
87
  throw new CliError(`${CONFIG_FILE} is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "file"}: ${issue.message}`).join("; ")}`);
84
88
  }
85
89
  return parsed.data;
86
90
  }
91
+ /**
92
+ * The ID a Git or local workspace gives an asset, from where it lives: the
93
+ * same before it's committed as after, so a copy's ID is known as it's made.
94
+ */
95
+ export const repoAssetId = (workspaceId, kind, scope, name) => stableId(workspaceId, "asset", kind, scope.type, scope.slug, name);
87
96
  /** A hash formatted as UUIDv4, so IDs need no stored record and cannot merge-conflict. */
88
97
  export function stableId(...parts) {
89
98
  const bytes = createHash("sha256")
@@ -186,11 +195,11 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
186
195
  const assets = [];
187
196
  const knowledge = [];
188
197
  const invalidKnowledge = [];
189
- const named = (path, name) => {
190
- if (validAssetName(name)) {
198
+ const named = (path, name, rule = { validName: validAssetName, nameRule: NAME_RULE }) => {
199
+ if (rule.validName(name)) {
191
200
  return true;
192
201
  }
193
- problems.push({ path, reason: NAME_RULE });
202
+ problems.push({ path, reason: rule.nameRule, badName: true });
194
203
  return false;
195
204
  };
196
205
  function packageEntries(root) {
@@ -214,7 +223,7 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
214
223
  const add = (kind, name, entry, read) => {
215
224
  const base = {
216
225
  kind,
217
- id: id("asset", kind, scope.type, scope.slug, name),
226
+ id: repoAssetId(config.workspaceId, kind, scope, name),
218
227
  name,
219
228
  origin: scope,
220
229
  publishedVersion: entry.hash,
@@ -260,7 +269,7 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
260
269
  continue;
261
270
  }
262
271
  const name = file.replace(/\.ya?ml$/, "");
263
- if (!named(entry.path, name)) {
272
+ if (!named(entry.path, name, assetKinds.mcp)) {
264
273
  continue;
265
274
  }
266
275
  add("mcp", name, entry, () => {
@@ -1,3 +1,4 @@
1
+ import { fixSteps, gitAccessCommand } from "../../platform.js";
1
2
  import { execFile, spawn } from "node:child_process";
2
3
  import { stat } from "node:fs/promises";
3
4
  import { CliError } from "../../errors.js";
@@ -191,13 +192,12 @@ export async function remoteHead(url, runtime, allowPrompt = false) {
191
192
  }
192
193
  catch (error) {
193
194
  if (error instanceof GitError) {
194
- throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, `git clone ${url}`, { cause: error });
195
+ throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, gitAccessCommand(url, runtime.platform), { cause: error });
195
196
  }
196
197
  throw error;
197
198
  }
198
199
  return parseRemoteHead(output, url);
199
200
  }
200
- const identityHint = 'git config --global user.email "you@example.com"';
201
201
  /**
202
202
  * Git's stderr when a commit has no author: `*** Please tell me who you are.`
203
203
  * followed by the `git config` commands to run.
@@ -206,9 +206,16 @@ const identityHint = 'git config --global user.email "you@example.com"';
206
206
  */
207
207
  export const UNKNOWN_IDENTITY = /tell me who you are/i;
208
208
  /** Git's "who are you" failure is common on new machines and has one clear fix. */
209
- export function explainIdentity(error) {
209
+ export function explainIdentity(error, platform) {
210
210
  if (error instanceof GitError && UNKNOWN_IDENTITY.test(error.stderr)) {
211
- throw new CliError("Git doesn't know who you are, so BarnDog can't make a commit.", identityHint, { cause: error });
211
+ // Git needs both; double quotes read the same in Bash, zsh and PowerShell.
212
+ throw new CliError("Git doesn't know who you are, so BarnDog can't make a commit.", "Tell Git your name and email for every repository, then try again", {
213
+ cause: error,
214
+ command: fixSteps([
215
+ 'git config --global user.name "Your Name"',
216
+ 'git config --global user.email "you@example.com"',
217
+ ], platform),
218
+ });
212
219
  }
213
220
  throw error;
214
221
  }