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
package/dist/platform.js CHANGED
@@ -6,8 +6,8 @@ import crossSpawn from "cross-spawn";
6
6
  import { promisify } from "node:util";
7
7
  import { CliError } from "./errors.js";
8
8
  import { POSIX_MODE } from "./shared/constants.js";
9
- import { ifExists } from "./shared/files.js";
10
- import { posixQuote, powershellQuote } from "./shared/shell.js";
9
+ import { ifExists, isInside } from "./shared/files.js";
10
+ import { PLAIN_WORD, posixQuote, powershellQuote } from "./shared/shell.js";
11
11
  import { errorCode } from "./shared/values.js";
12
12
  const execute = promisify(execFile);
13
13
  /**
@@ -21,6 +21,8 @@ const OS_VARIABLES = {
21
21
  /** Windows: `C:\Program Files` and its 32-bit twin. */
22
22
  programFiles: "ProgramFiles",
23
23
  programFilesX86: "ProgramFiles(x86)",
24
+ /** Windows: `C:\Windows`, which holds WSL's `bash.exe` launcher. */
25
+ systemRoot: "SystemRoot",
24
26
  /** Windows: `C:\Users\<you>\AppData\Local`, where per-user apps install. */
25
27
  localAppData: "LOCALAPPDATA",
26
28
  /** Linux: XDG Base Directory specification. */
@@ -86,16 +88,29 @@ export async function findExecutable(command, runtime) {
86
88
  const shellQuote = (value, platform) => isWindows(platform) ? powershellQuote(value) : posixQuote(value);
87
89
  /**
88
90
  * Fix hints name commands for the shell people type into: Bash or zsh on
89
- * macOS and Linux, PowerShell on Windows (Windows PowerShell 5 has no `&&`).
91
+ * macOS and Linux, PowerShell on Windows. Each step runs only when the one
92
+ * before it succeeded; Windows PowerShell 5 has no `&&`, so there each later
93
+ * step goes inside `if ($?) { … }`.
90
94
  */
91
95
  export function fixSteps(steps, platform) {
92
- return steps.join(isWindows(platform) ? "; " : " && ");
96
+ if (!isWindows(platform)) {
97
+ return steps.join(" && ");
98
+ }
99
+ return steps.reduceRight((rest, step) => (rest ? `${step}; if ($?) { ${rest} }` : step), "");
93
100
  }
94
101
  export function removeCommand(path, platform) {
95
102
  return isWindows(platform)
96
103
  ? `Remove-Item -Recurse -Force ${shellQuote(path, platform)}`
97
104
  : `rm -rf ${shellQuote(path, platform)}`;
98
105
  }
106
+ /** One word for the platform's shell, quoted only when it needs to be. */
107
+ export function shellWord(value, platform) {
108
+ return PLAIN_WORD.test(value) ? value : shellQuote(value, platform);
109
+ }
110
+ /** Checks that the user's Git credentials can read `url`; clones nothing. */
111
+ export function gitAccessCommand(url, platform) {
112
+ return `git ls-remote ${shellQuote(url, platform)}`;
113
+ }
99
114
  export function unsetCommand(variable, platform) {
100
115
  return isWindows(platform)
101
116
  ? `Remove-Item Env:${variable}`
@@ -119,8 +134,12 @@ export function encodedPowerShell(script) {
119
134
  ],
120
135
  };
121
136
  }
122
- /** A program run from a PowerShell line, keeping its exit code. */
123
- export const powershellCall = (args) => `& ${args.map(powershellQuote).join(" ")}; exit $LASTEXITCODE`;
137
+ /**
138
+ * A program run from a PowerShell line, keeping its exit code. A program that
139
+ * can't be found sets no `$LASTEXITCODE`, and `exit $null` would report
140
+ * success, so that case exits 1.
141
+ */
142
+ export const powershellCall = (args) => `& ${args.map(powershellQuote).join(" ")}; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE`;
124
143
  /**
125
144
  * A program's stdout. Starts through cross-spawn, which also runs Windows
126
145
  * `.cmd` and `.bat` shims (such as npm-installed tools) with safely quoted
@@ -135,17 +154,22 @@ export function programOutput(command, args, runtime, limits) {
135
154
  stdio: ["ignore", "pipe", "ignore"],
136
155
  windowsHide: true,
137
156
  });
138
- let stdout = "";
157
+ // Decoded once at the end, so a character split across chunks survives.
158
+ const chunks = [];
159
+ let length = 0;
139
160
  const fail = (reason) => {
140
161
  child.kill();
141
162
  reject(new Error(`${command} ${reason}`));
142
163
  };
143
164
  const timer = setTimeout(() => fail("timed out"), limits.timeoutMs);
144
165
  child.stdout?.on("data", (chunk) => {
145
- stdout += chunk.toString("utf8");
146
- if (stdout.length > limits.maxBytes) {
166
+ length += chunk.length;
167
+ if (length > limits.maxBytes) {
147
168
  fail("printed too much");
148
169
  }
170
+ else {
171
+ chunks.push(chunk);
172
+ }
149
173
  });
150
174
  child.once("error", (error) => {
151
175
  clearTimeout(timer);
@@ -154,7 +178,7 @@ export function programOutput(command, args, runtime, limits) {
154
178
  child.once("close", (code) => {
155
179
  clearTimeout(timer);
156
180
  if (code === 0) {
157
- resolve(stdout);
181
+ resolve(Buffer.concat(chunks).toString("utf8"));
158
182
  }
159
183
  else {
160
184
  reject(new Error(`${command} exited with code ${code}`));
@@ -181,8 +205,12 @@ export async function bashShell(runtime) {
181
205
  return { command: candidate, args: ["-c"] };
182
206
  }
183
207
  }
208
+ // `C:\Windows\System32\bash.exe` starts WSL's Linux, not the Bash tools run
209
+ // hooks in, so a Bash found there doesn't count.
184
210
  const bash = await findExecutable("bash", runtime);
185
- if (bash) {
211
+ const system = environmentValue(runtime, OS_VARIABLES.systemRoot);
212
+ if (bash &&
213
+ !(system && isInside(system.toLowerCase(), bash.toLowerCase(), paths))) {
186
214
  return { command: bash, args: ["-c"] };
187
215
  }
188
216
  throw new CliError("This Hook runs in Bash, which isn't installed.", "Install Git for Windows from https://gitforwindows.org, then try again.");
@@ -230,6 +258,17 @@ export function stopProcessTree(child, runtime, signal = "SIGKILL") {
230
258
  /* The child has already exited. */
231
259
  }
232
260
  }
261
+ /**
262
+ * The environment for a Windows PowerShell (5.1) that BarnDog runs itself.
263
+ * PowerShell 7 puts its own module folders first in `PSModulePath`, and a
264
+ * Windows PowerShell started from it inherits them, then fails to load
265
+ * PowerShell 7's `Microsoft.PowerShell.Security` (`Get-Acl`). Without the
266
+ * variable, Windows PowerShell builds its default module path. Windows
267
+ * environment names ignore case.
268
+ */
269
+ function windowsPowerShellEnvironment(env) {
270
+ return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "PSMODULEPATH"));
271
+ }
233
272
  /** Windows DACLs replace POSIX modes: only the current user receives access. */
234
273
  export async function protectPrivate(path, runtime) {
235
274
  if (!isWindows(runtime.platform)) {
@@ -238,7 +277,7 @@ export async function protectPrivate(path, runtime) {
238
277
  const script = `$ErrorActionPreference='Stop'; $path=${shellQuote(path, runtime.platform)}; $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $acl=Get-Acl -LiteralPath $path; $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true,$false); foreach($rule in @($acl.Access)){$acl.RemoveAccessRuleSpecific($rule)}; $inherit=if((Get-Item -LiteralPath $path).PSIsContainer){[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'}else{[Security.AccessControl.InheritanceFlags]::None}; $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl',$inherit,'None','Allow'); $acl.AddAccessRule($rule); Set-Acl -LiteralPath $path -AclObject $acl`;
239
278
  const invocation = encodedPowerShell(script);
240
279
  await execute(invocation.command, invocation.args, {
241
- env: { ...runtime.env },
280
+ env: windowsPowerShellEnvironment(runtime.env),
242
281
  cwd: runtime.cwd,
243
282
  windowsHide: true,
244
283
  });
package/dist/program.js CHANGED
@@ -1,6 +1,6 @@
1
- import { resolve } from "node:path";
2
1
  import { Command, Help, Option } from "commander";
3
2
  import { homedir } from "node:os";
3
+ import { pathsFor } from "./platform.js";
4
4
  import { styleText } from "node:util";
5
5
  import { registerCollaboration, registerWorkingCopy, } from "./commands/collaboration.js";
6
6
  import { applySuggestion, changeDiff, commentOnChange, createPackage, diffVersions, listChanges, mergeChange, packageVersions, pullPackage, pushWorkingCopy, rejectChange, resolveFile, reviewChange, setDiscussionResolved, showChange, updateWorkingCopy, versionFiles, workingDiff, workingStatus, } from "./features/collaboration/index.js";
@@ -8,14 +8,20 @@ import { registerAuth } from "./commands/auth.js";
8
8
  import { runLogin, runLogout, showAuthStatus } from "./ui/auth.js";
9
9
  import { registerInit } from "./commands/init.js";
10
10
  import { registerSync } from "./commands/sync.js";
11
+ import { registerHarnesses } from "./commands/harnesses.js";
11
12
  import { registerStatus } from "./commands/status.js";
12
13
  import { clashPrompt, synchronize } from "./features/environment/sync.js";
13
14
  import { changeAsset, changeAssets, changeSet, installSet, installSetAssets, listSets, previewSet, renameAsset, setKnowledge, switchSet, } from "./features/environment/operations.js";
15
+ import { changeHarnesses, listHarnesses, selectHarnesses, } from "./features/environment/harnesses.js";
14
16
  import { doctor } from "./features/doctor/index.js";
15
17
  import { repoStatus, workspaceUrl } from "./features/inspection/index.js";
16
18
  import { validateFolder } from "./features/workspace/assets.js";
17
19
  import { migrate } from "./features/migration/migrate.js";
18
20
  import { listLocalAssets, moveLocalAssets } from "./features/migration/move.js";
21
+ import { adoptNative } from "./features/adoption/adopt.js";
22
+ import { undoAdoption } from "./features/adoption/undo.js";
23
+ import { listAdoptions } from "./features/adoption/record.js";
24
+ import { scanNative } from "./features/adoption/scan.js";
19
25
  import { updateImported } from "./features/imports/local.js";
20
26
  import { authenticateMcp, createMcp, mcpVersions, showMcp, updateMcp, } from "./features/mcps/index.js";
21
27
  import { adaptHook, toolNames } from "./features/hooks/adapt.js";
@@ -33,6 +39,10 @@ import { searchCatalog } from "./features/catalog/index.js";
33
39
  import { registerEnvironment } from "./commands/environment.js";
34
40
  import { registerCapabilities } from "./commands/capabilities.js";
35
41
  import { registerWorkspace } from "./commands/workspace.js";
42
+ import { registerAdopt } from "./commands/adopt.js";
43
+ import { registerUninstall } from "./commands/uninstall.js";
44
+ import { uninstall } from "./features/uninstall/index.js";
45
+ import { uninstallSurvey } from "./features/uninstall/survey.js";
36
46
  import { registerAdd } from "./commands/add.js";
37
47
  import { commandNeeds, modeName, needText, unavailableNote, } from "./commands/availability.js";
38
48
  import { runSetup } from "./ui/onboarding.js";
@@ -42,13 +52,28 @@ import { primary } from "./ui/theme.js";
42
52
  import { versionReport } from "./version.js";
43
53
  import { defined } from "./shared/lookup.js";
44
54
  import { barndogPaths } from "./config/paths.js";
55
+ import { showPackage } from "./features/inventory/show.js";
56
+ import { assignKeptValue, forgetMcpValue, forgetUnassignedValue, keepMcpValue, listKeptValues, } from "./features/mcps/values.js";
57
+ import { readSettings } from "./config/settings.js";
45
58
  /** Keep command help readable at the conventional eighty-column terminal width. */
46
59
  const HELP_WIDTH = 80;
47
60
  /** Help sections, in order; every top-level command belongs to one. */
48
61
  const groups = [
49
62
  [
50
63
  "Get started:",
51
- ["init", "login", "logout", "auth", "whoami", "sync", "status", "doctor"],
64
+ [
65
+ "init",
66
+ "login",
67
+ "logout",
68
+ "auth",
69
+ "whoami",
70
+ "sync",
71
+ "status",
72
+ "doctor",
73
+ "harnesses",
74
+ "adopt",
75
+ "uninstall",
76
+ ],
52
77
  ],
53
78
  ["Assets:", ["skills", "mcp", "hooks", "sets", "knowledge"]],
54
79
  [
@@ -209,12 +234,15 @@ function guardRequiredOptions(parent, guard) {
209
234
  }
210
235
  /** Process entry points capture ambient inputs here; downstream code receives this object. */
211
236
  export function captureRuntime(options = {}) {
212
- const cwd = resolve(options.cwd ?? process.cwd());
237
+ // Resolved by the platform's own rules, so a test can run as another OS.
238
+ const platform = options.platform ?? process.platform;
239
+ const paths = pathsFor(platform);
240
+ const cwd = paths.resolve(options.cwd ?? process.cwd());
213
241
  return {
214
- home: resolve(cwd, options.home ?? homedir()),
242
+ home: paths.resolve(cwd, options.home ?? homedir()),
215
243
  cwd,
216
244
  env: { ...(options.env ?? process.env) },
217
- platform: options.platform ?? process.platform,
245
+ platform,
218
246
  };
219
247
  }
220
248
  /** Construct a fresh parser for every invocation or test; command behavior is independently injectable. */
@@ -251,15 +279,20 @@ export function createProgram(options = {}) {
251
279
  versionFiles: options.versionFiles ?? ((target) => versionFiles(target, runtime)),
252
280
  workingDiff: options.workingDiff ?? (() => workingDiff(runtime)),
253
281
  workingStatus: options.workingStatus ?? (() => workingStatus(runtime)),
254
- login: options.login ?? ((login) => runLogin({ ...login, runtime }, write)),
282
+ login: options.login ??
283
+ ((login) => runLogin({ ...login, runtime, interactive: mode.interactive }, write)),
255
284
  logout: options.logout ?? (() => runLogout(write, runtime)),
256
285
  authStatus: options.authStatus ??
257
286
  (() => showAuthStatus({ write, json: mode.json }, runtime)),
287
+ isSetUp: options.isSetUp ??
288
+ // A damaged file counts as set up: the command that reads it explains what's wrong.
289
+ (async () => (await readSettings(home).catch(() => true)) !== null),
258
290
  setup: options.setup ??
259
291
  ((restart, server, setupOptions) => runSetup({
260
292
  restart,
261
293
  server,
262
294
  ...setupOptions,
295
+ interactive: mode.interactive,
263
296
  write: options.write,
264
297
  runtime,
265
298
  })),
@@ -277,9 +310,20 @@ export function createProgram(options = {}) {
277
310
  ((change, options) => changeSet(change, options, runtime)),
278
311
  switchSet: options.switchSet ?? ((options) => switchSet(options, runtime)),
279
312
  setKnowledge: options.setKnowledge ?? ((enabled) => setKnowledge(enabled, runtime)),
313
+ listHarnesses: options.listHarnesses ?? (() => listHarnesses(runtime)),
314
+ changeHarnesses: options.changeHarnesses ??
315
+ ((change, targets) => changeHarnesses(change, targets, runtime)),
316
+ selectHarnesses: options.selectHarnesses ??
317
+ ((selected) => selectHarnesses(selected, runtime)),
280
318
  doctor: options.doctor ?? (() => doctor(runtime)),
281
319
  workspaceUrl: options.workspaceUrl ?? (() => workspaceUrl(runtime)),
282
320
  repoStatus: options.repoStatus ?? (() => repoStatus(runtime)),
321
+ scanNative: options.scanNative ?? (() => scanNative(runtime)),
322
+ uninstallSurvey: options.uninstallSurvey ?? (() => uninstallSurvey(runtime)),
323
+ uninstall: options.uninstall ?? ((choices) => uninstall(choices, runtime)),
324
+ adoptNative: options.adoptNative ?? ((keys, keep) => adoptNative(keys, keep, runtime)),
325
+ listAdoptions: options.listAdoptions ?? (() => listAdoptions(home)),
326
+ undoAdoption: options.undoAdoption ?? ((target) => undoAdoption(target, runtime)),
283
327
  listLocalAssets: options.listLocalAssets ?? (() => listLocalAssets(runtime)),
284
328
  knowledgeProblems: options.knowledgeProblems ?? (() => knowledgeProblems(runtime)),
285
329
  githubStatus: options.githubStatus ?? (() => githubStatus(runtime)),
@@ -292,6 +336,15 @@ export function createProgram(options = {}) {
292
336
  ((options) => moveLocalAssets(options, runtime)),
293
337
  updateImported: options.updateImported ??
294
338
  ((kind, name, options) => updateImported(kind, name, options, runtime)),
339
+ keepMcpValue: options.keepMcpValue ??
340
+ ((target, kept) => keepMcpValue(target, kept, runtime)),
341
+ assignKeptValue: options.assignKeptValue ?? ((target) => assignKeptValue(target, runtime)),
342
+ forgetMcpValue: options.forgetMcpValue ?? ((target) => forgetMcpValue(target, runtime)),
343
+ forgetUnassignedValue: options.forgetUnassignedValue ??
344
+ ((variable) => forgetUnassignedValue(variable, runtime)),
345
+ listKeptValues: options.listKeptValues ?? (() => listKeptValues(runtime)),
346
+ showPackage: options.showPackage ??
347
+ ((kind, name, origin) => showPackage(kind, name, origin, runtime)),
295
348
  showMcp: options.showMcp ?? ((name, origin) => showMcp(name, origin, runtime)),
296
349
  createMcp: options.createMcp ?? ((input) => createMcp(input, runtime)),
297
350
  updateMcp: options.updateMcp ?? ((input) => updateMcp(input, runtime)),
@@ -344,7 +397,7 @@ export function createProgram(options = {}) {
344
397
  knowledgeList: options.knowledgeList ?? ((always) => knowledgeList(always, runtime)),
345
398
  synchronize: options.synchronize ??
346
399
  ((path, syncOptions) => synchronize(path, runtime, undefined, syncOptions)),
347
- inventory: options.inventory ?? (() => inventory(runtime)),
400
+ inventory: options.inventory ?? ((choice) => inventory(runtime, choice)),
348
401
  searchCatalog: options.searchCatalog ?? ((kind) => searchCatalog(kind, runtime)),
349
402
  write,
350
403
  mode,
@@ -376,10 +429,14 @@ export function createProgram(options = {}) {
376
429
  .showHelpAfterError(styleText("dim", "Add --help to any command to see its usage."))
377
430
  .addHelpText("after", `\nRun ${styleText("bold", "barndog <command> --help")} for details. Configuration: ${barndogPaths(home).settings}`)
378
431
  .addHelpText("afterAll", ({ command }) => options.setupMode ? unavailableHint(command, options.setupMode) : "")
379
- .action((_, command) => {
432
+ .action(async (_, command) => {
380
433
  if (command.args.length) {
381
434
  program.error(`error: unknown command '${command.args[0]}'`);
382
435
  }
436
+ // Setup needs a terminal; without one, help says to run `barndog init`.
437
+ if (mode.interactive && !(await context.isSetUp())) {
438
+ return context.setup(true);
439
+ }
383
440
  program.help();
384
441
  });
385
442
  program.hook("preAction", async (_, action) => {
@@ -405,6 +462,9 @@ export function createProgram(options = {}) {
405
462
  registerAuth(program, context);
406
463
  registerInit(program, context);
407
464
  registerSync(program, context);
465
+ registerHarnesses(program, context);
466
+ registerAdopt(program, context);
467
+ registerUninstall(program, context);
408
468
  registerStatus(program, context);
409
469
  registerEnvironment(program, context);
410
470
  registerCapabilities(program, context);
@@ -35,6 +35,41 @@ export async function ifExists(operation) {
35
35
  throw error;
36
36
  }
37
37
  }
38
+ /** Why a file named on the command line can't be read, by Node error code. */
39
+ const inputProblems = {
40
+ ENOENT: "doesn't exist",
41
+ EISDIR: "is a folder, not a file",
42
+ EACCES: "can't be read: permission denied",
43
+ EPERM: "can't be read: permission denied",
44
+ };
45
+ /**
46
+ * A file the person running the CLI named, such as `--file` or `--input`. A
47
+ * missing or unreadable one is a mistake they can fix, so it says which file.
48
+ */
49
+ export async function inputFile(path) {
50
+ try {
51
+ return await readFile(path);
52
+ }
53
+ catch (error) {
54
+ const problem = inputProblems[errorCode(error) ?? ""];
55
+ if (problem) {
56
+ throw new CliError(`${path} ${problem}.`, undefined, { cause: error });
57
+ }
58
+ throw error;
59
+ }
60
+ }
61
+ /** `inputFile()` parsed as JSON; invalid JSON says which file. */
62
+ export async function inputJson(path) {
63
+ const text = (await inputFile(path)).toString("utf8");
64
+ try {
65
+ return JSON.parse(text);
66
+ }
67
+ catch (error) {
68
+ throw new CliError(`${path} isn't valid JSON.`, undefined, {
69
+ cause: error,
70
+ });
71
+ }
72
+ }
38
73
  /** A file's text, or null when it doesn't exist. */
39
74
  export function readIfExists(path) {
40
75
  return ifExists(readFile(path, "utf8"));
@@ -1,44 +1,108 @@
1
1
  import { POSIX_MODE } from "./constants.js";
2
- import { mkdir, readFile, rm } from "node:fs/promises";
2
+ import { mkdir, readFile, rm, stat } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
4
5
  import { errorCode } from "./values.js";
5
6
  import { CliError } from "./cli-error.js";
6
- import { writeAtomic } from "./files.js";
7
+ import { ifExists, writeAtomic } from "./files.js";
7
8
  /**
8
- * Runs `run` while holding a lock across processes: a folder at `path` holding
9
- * the owner's PID. A lock whose process has died is taken over; liveness comes
10
- * from the PID, not from the lock's age, so a long operation never loses it.
9
+ * How long a lock may exist without a PID before it counts as left by a
10
+ * process that crashed between creating it and writing its PID. Writing the
11
+ * PID takes milliseconds.
11
12
  */
12
- export async function withPidLock(path, messages, run) {
13
- await mkdir(dirname(path), {
14
- recursive: true,
15
- mode: POSIX_MODE.privateDirectory,
16
- });
13
+ const STARTING_GRACE_MS = 10_000;
14
+ /** How long to wait while another process clears the same stale lock. */
15
+ const TAKEOVER_RETRY_MS = 50;
16
+ /** Attempts before giving up on a lock that keeps changing hands. */
17
+ const MAX_ATTEMPTS = 100;
18
+ async function ownerOf(path) {
19
+ const info = await ifExists(stat(path));
20
+ if (!info) {
21
+ return "free";
22
+ }
23
+ const text = await ifExists(readFile(join(path, "pid"), "utf8"));
24
+ const pid = Number(text ?? 0);
25
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
26
+ return Date.now() - info.mtimeMs > STARTING_GRACE_MS ? "stale" : "starting";
27
+ }
28
+ try {
29
+ process.kill(pid, 0);
30
+ return "running";
31
+ }
32
+ catch (failure) {
33
+ // EPERM: the owner is alive but belongs to another user, so it still holds the lock.
34
+ return errorCode(failure) === "ESRCH" ? "stale" : "running";
35
+ }
36
+ }
37
+ /**
38
+ * Removes the lock at `path` if it is still stale. A short-lived guard folder
39
+ * makes the check and the removal one step, so a process that saw the same
40
+ * stale lock can't remove a fresh lock another process just took.
41
+ */
42
+ async function removeStale(path) {
43
+ const guard = `${path}.takeover`;
17
44
  try {
18
- await mkdir(path);
45
+ await mkdir(guard);
19
46
  }
20
47
  catch (error) {
21
48
  if (errorCode(error) !== "EEXIST") {
22
49
  throw error;
23
50
  }
24
- const pid = Number(await readFile(join(path, "pid"), "utf8").catch(() => "0"));
25
- if (!pid) {
26
- throw new CliError(messages.starting, undefined, { cause: error });
51
+ const info = await ifExists(stat(guard));
52
+ if (info && Date.now() - info.mtimeMs > STARTING_GRACE_MS) {
53
+ await rm(guard, { recursive: true, force: true });
54
+ }
55
+ else {
56
+ await sleep(TAKEOVER_RETRY_MS);
57
+ }
58
+ return;
59
+ }
60
+ try {
61
+ if ((await ownerOf(path)) === "stale") {
62
+ await rm(path, { recursive: true, force: true });
27
63
  }
64
+ }
65
+ finally {
66
+ await rm(guard, { recursive: true, force: true });
67
+ }
68
+ }
69
+ /** Creates the lock folder, taking over a stale one; throws when it is held. */
70
+ async function acquire(path, messages) {
71
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
28
72
  try {
29
- process.kill(pid, 0);
73
+ await mkdir(path, { mode: POSIX_MODE.privateDirectory });
74
+ return;
30
75
  }
31
- catch (failure) {
32
- // EPERM: the owner is alive but belongs to another user, so it still holds the lock.
33
- if (errorCode(failure) !== "ESRCH") {
34
- throw new CliError(messages.running, undefined, { cause: failure });
76
+ catch (error) {
77
+ if (errorCode(error) !== "EEXIST") {
78
+ throw error;
79
+ }
80
+ const owner = await ownerOf(path);
81
+ if (owner === "starting") {
82
+ throw new CliError(messages.starting, undefined, { cause: error });
83
+ }
84
+ if (owner === "running") {
85
+ throw new CliError(messages.running, undefined, { cause: error });
86
+ }
87
+ if (owner === "stale") {
88
+ await removeStale(path);
35
89
  }
36
- // Another process may have cleared the same stale lock first.
37
- await rm(path, { recursive: true, force: true });
38
- return withPidLock(path, messages, run);
39
90
  }
40
- throw new CliError(messages.running, undefined, { cause: error });
41
91
  }
92
+ throw new CliError(messages.running);
93
+ }
94
+ /**
95
+ * Runs `run` while holding a lock across processes: a folder at `path` holding
96
+ * the owner's PID. A lock whose process has died, or that never got a PID, is
97
+ * taken over; liveness comes from the PID, not from the lock's age, so a long
98
+ * operation never loses it.
99
+ */
100
+ export async function withPidLock(path, messages, run) {
101
+ await mkdir(dirname(path), {
102
+ recursive: true,
103
+ mode: POSIX_MODE.privateDirectory,
104
+ });
105
+ await acquire(path, messages);
42
106
  try {
43
107
  await writeAtomic(join(path, "pid"), String(process.pid));
44
108
  return await run();
@@ -22,6 +22,14 @@ export const NAME = /^[a-z\d]+(?:-[a-z\d]+)*$/;
22
22
  * most 64 characters.
23
23
  */
24
24
  export const validAssetName = (name) => NAME.test(name) && name.length <= MAX_ASSET_NAME_LENGTH;
25
+ /**
26
+ * An MCP server name as coding tools accept it: letters, digits, `_` and `-`,
27
+ * such as `my_server` or `GitHub`. Tools name its tools after it
28
+ * (`mcp__my_server__search`), so BarnDog keeps it as written.
29
+ */
30
+ export const MCP_NAME = /^[\w-]+$/;
31
+ /** Whether `name` can be an MCP server's name: {@link MCP_NAME}, at most 64 characters. */
32
+ export const validMcpName = (name) => MCP_NAME.test(name) && name.length <= MAX_ASSET_NAME_LENGTH;
25
33
  /** Turns any text into a {@link NAME}-shaped slug: `Team A/Review!` → `team-a-review`. */
26
34
  export function slugify(text) {
27
35
  return text
@@ -3,8 +3,6 @@ export const posixQuote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
3
3
  /**
4
4
  * Text the shell reads as one word without quotes: `claude`, `v1.2-rc`, but
5
5
  * not `a b`, `$HOME` or `/usr/bin`.
6
- *
7
- * @internal
8
6
  */
9
7
  export const PLAIN_WORD = /^[\w.-]+$/;
10
8
  /** One POSIX shell word, quoted only when it needs to be. */
@@ -2,6 +2,7 @@
2
2
  import { GIT_MODE } from "../features/workspace/snapshot.js";
3
3
  import { basename } from "node:path";
4
4
  import { CliError } from "../errors.js";
5
+ import { readSettings } from "../config/settings.js";
5
6
  import { adapters, hookHarnesses, isHookHarness, } from "../harnesses/registry.js";
6
7
  import { buildHookPackage, discoverHooks, plainCommand, } from "../features/imports/discover.js";
7
8
  import { adaptHook, toolNames } from "../features/hooks/adapt.js";
@@ -19,7 +20,12 @@ async function pickHookPlan(draft, executable, context) {
19
20
  const { prompts } = context;
20
21
  // Choices made for one coding tool start out selected for the next.
21
22
  const carried = new Map();
22
- const chosen = (await prompts.chooseMany("Which coding tools should this Hook support?", hookHarnesses.map((h) => ({ name: adapters[h].name, value: h })))).filter(isHookHarness);
23
+ const managed = (await readSettings(context.runtime.home))?.harnesses ?? [];
24
+ const chosen = (await prompts.chooseMany("Which coding tools should this Hook support?", hookHarnesses.map((h) => ({
25
+ name: adapters[h].name,
26
+ value: h,
27
+ checked: managed.includes(h),
28
+ })))).filter(isHookHarness);
23
29
  const plan = {};
24
30
  for (const harness of chosen) {
25
31
  const known = adapters[harness].hooks.events;
@@ -107,7 +113,7 @@ export async function addHook(url, options, context) {
107
113
  }
108
114
  const location = parseLocation(url);
109
115
  const fallback = slugify(basename(url.replace(/\/$/, "").replace(/\.git$/, ""))) || "hook";
110
- await fetchRemote(location, { allowPrompt: true }, async (remote) => {
116
+ await fetchRemote(location, { allowPrompt: context.interactive }, async (remote) => {
111
117
  const { candidates, skipped } = discoverHooks(remote, fallback);
112
118
  for (const skip of skipped) {
113
119
  context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);