barndog 0.1.1 → 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 (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,5 +1,17 @@
1
+ import { SHORT_COMMIT_LENGTH } from "../shared/constants.js";
1
2
  import { bad, dim, fields, hint, ok, table } from "./format.js";
2
3
  /** Whether each coding tool has a version of the Hook, and whether it can run here. */
4
+ /** Whether a harness can run the Hook here: "—" when it isn't supported at all. */
5
+ function runtimeLabel(status, runtimeIssue) {
6
+ if (status === "unsupported") {
7
+ return dim("—");
8
+ }
9
+ return runtimeIssue ? `${bad("✖")} ${runtimeIssue}` : ok("✔");
10
+ }
11
+ /**
12
+ * Returns Hook support and runtime-readiness table lines, abbreviating content
13
+ * hashes to seven characters.
14
+ */
3
15
  export function renderHookCompatibility(name, result) {
4
16
  const missing = result.compatibility
5
17
  .filter((row) => row.status === "unsupported")
@@ -11,17 +23,13 @@ export function renderHookCompatibility(name, result) {
11
23
  "Version",
12
24
  typeof result.version === "number"
13
25
  ? String(result.version)
14
- : result.version.slice(0, 7),
26
+ : result.version.slice(0, SHORT_COMMIT_LENGTH),
15
27
  ],
16
28
  ]),
17
29
  ...table(result.compatibility.map((row) => [
18
30
  row.harness,
19
31
  row.status === "supported" ? row.status : dim(row.status),
20
- row.status === "unsupported"
21
- ? dim("—")
22
- : row.runtimeIssue
23
- ? `${bad("✖")} ${row.runtimeIssue}`
24
- : ok("✔"),
32
+ runtimeLabel(row.status, row.runtimeIssue),
25
33
  ]), { header: ["Tool", "Support", "Ready on this machine"], indent: 0 }),
26
34
  ...(missing.length
27
35
  ? [
package/dist/ui/mcp.js CHANGED
@@ -1,4 +1,24 @@
1
+ import { SHORT_COMMIT_LENGTH } from "../shared/constants.js";
2
+ import { mcpDefinitionSchema } from "@barndog-ai/api-contract";
3
+ import { z } from "zod";
1
4
  import { clean, fields, originLabel, renderValue } from "./format.js";
5
+ const shownMcpSchema = z.looseObject({
6
+ name: z.string(),
7
+ origin: z.union([
8
+ z.string(),
9
+ z.looseObject({
10
+ type: z.string(),
11
+ slug: z.string().optional(),
12
+ id: z.string(),
13
+ }),
14
+ ]),
15
+ /** Cloud nests the definition in a numbered version; repos give a content hash. */
16
+ version: z.union([
17
+ z.string(),
18
+ z.looseObject({ number: z.number(), definition: mcpDefinitionSchema }),
19
+ ]),
20
+ definition: mcpDefinitionSchema.optional(),
21
+ });
2
22
  const signIn = {
3
23
  none: "none",
4
24
  environment: "environment variables",
@@ -6,11 +26,16 @@ const signIn = {
6
26
  };
7
27
  /** An MCP configuration as a person reads it; secret references print by name. */
8
28
  export function renderMcp(value) {
9
- const mcp = value;
29
+ const shown = shownMcpSchema.safeParse(value);
30
+ if (!shown.success) {
31
+ return renderValue(value);
32
+ }
33
+ const mcp = shown.data;
10
34
  const definition = mcp.definition ??
11
35
  (typeof mcp.version === "object" ? mcp.version.definition : undefined);
12
- if (!definition)
36
+ if (!definition) {
13
37
  return renderValue(value);
38
+ }
14
39
  const references = definition.transport === "stdio"
15
40
  ? definition.environment
16
41
  : definition.headers;
@@ -25,7 +50,7 @@ export function renderMcp(value) {
25
50
  "Version",
26
51
  typeof mcp.version === "object"
27
52
  ? `v${mcp.version.number}`
28
- : mcp.version.slice(0, 7),
53
+ : mcp.version.slice(0, SHORT_COMMIT_LENGTH),
29
54
  ],
30
55
  ["Description", clean(definition.description)],
31
56
  [
package/dist/ui/move.js CHANGED
@@ -1,7 +1,41 @@
1
+ import select from "@inquirer/select";
1
2
  import { bold, dim, hint, ok, table, warn } from "./format.js";
3
+ import { pickMany } from "./pick.js";
4
+ import { promptTheme } from "./theme.js";
5
+ /** The local assets `local move` can take: valid, and not already moving. */
6
+ export function pickLocalAssets(local) {
7
+ return pickMany("Which local assets should move?", local.assets
8
+ .filter((asset) => asset.state === "active")
9
+ .map((asset) => ({
10
+ value: asset.name,
11
+ name: asset.name,
12
+ hint: asset.kind,
13
+ })), { empty: "No local assets can be moved." });
14
+ }
15
+ /** True keeps separate local copies; false makes the shared copies the only ones. */
16
+ export function chooseKeepLocal(count) {
17
+ const them = count === 1 ? "it" : "them";
18
+ return select({
19
+ message: `Move ${them}, or share a copy and keep ${them} here too?`,
20
+ choices: [
21
+ {
22
+ name: "Move",
23
+ value: false,
24
+ description: `The shared copy becomes the only one. Once it exists, the next sync installs it and removes the local copy.`,
25
+ },
26
+ {
27
+ name: "Keep a separate local copy",
28
+ value: true,
29
+ description: `Shares a copy. The local ${count === 1 ? "asset stays" : "assets stay"} on this machine as ${count === 1 ? "its" : "their"} own.`,
30
+ },
31
+ ],
32
+ theme: promptTheme,
33
+ });
34
+ }
2
35
  export function renderMove(result) {
3
- if (!result.rows.length)
36
+ if (!result.rows.length) {
4
37
  return [dim("Nothing to move.")];
38
+ }
5
39
  const output = table(result.rows.map((row) => [
6
40
  row.status === "moved" ? ok(row.status) : warn(row.status),
7
41
  dim(row.kind),
@@ -9,14 +43,31 @@ export function renderMove(result) {
9
43
  dim(row.detail ?? ""),
10
44
  ]), { header: ["Status", "Kind", "Name", ""] });
11
45
  output.push("");
12
- if (result.direct)
46
+ const moved = result.rows.some((row) => row.status === "moved");
47
+ if (result.direct && result.branch) {
13
48
  output.push(`${ok("✔")} Added to ${result.branch}.`);
14
- else if (result.branch)
49
+ }
50
+ else if (result.branch) {
15
51
  output.push(result.url
16
52
  ? `Open the pull request: ${result.url}`
17
- : `Open a pull request from ${result.branch} on your Git host.`, dim("Your local copies stay active until it merges."));
18
- for (const row of result.rows)
19
- if (row.status === "clash")
53
+ : `Open a pull request from ${result.branch} on your Git host.`);
54
+ }
55
+ if (moved && result.keepLocal) {
56
+ output.push(dim("Your local copies stay as separate assets. Where one has the same name as its shared copy, sync asks which to rename."));
57
+ }
58
+ else if (moved && result.direct) {
59
+ output.push(dim("The shared copies are installed and the local ones removed."));
60
+ }
61
+ else if (moved) {
62
+ output.push(dim("The move finishes when that merges: your local copies stay in use until then, and the next sync replaces them with the shared ones."));
63
+ }
64
+ for (const path of result.removed) {
65
+ output.push(dim(`Removed ${path}`));
66
+ }
67
+ for (const row of result.rows) {
68
+ if (row.status === "clash") {
20
69
  output.push(hint(`barndog local move ${row.name} --as <new-name>`, "Fix"));
70
+ }
71
+ }
21
72
  return output;
22
73
  }
@@ -1,72 +1,109 @@
1
1
  import { environmentChooser } from "./environment-onboarding.js";
2
2
  import { authStatus, configuredServer } from "../features/auth/session.js";
3
3
  import { chooseConnection, chooseLocalAssets, chooseMoveTarget, } from "./connection.js";
4
- import { cloudMoveTargets, moveLocalAssets, } from "../features/git-workspace/move.js";
5
- import { localRepoSource } from "../features/git-workspace/source.js";
4
+ import { cloudMoveTargets, moveLocalAssets, } from "../features/migration/move.js";
5
+ import { localRepoSource } from "../features/workspace/repo-source.js";
6
6
  import { renderMove } from "./move.js";
7
- import { checkRepositoryUrl, cloneOrigin, RepositoryAccessError, } from "../features/git-workspace/git.js";
8
- import { cloneGitWorkspace, connectGitWorkspace, createGitWorkspace, defaultLocalPath, inspectRepository, localWorkspace, } from "../features/git-workspace/setup.js";
9
- import { CliError } from "../errors.js";
7
+ import { checkRepositoryUrl, cloneOrigin, RepositoryAccessError, } from "../features/workspace/git.js";
8
+ import { cloneGitWorkspace, connectGitWorkspace, createGitWorkspace, inspectRepository, localWorkspace, } from "../features/workspace/setup.js";
9
+ import { CliError, friendlyMessage } from "../errors.js";
10
10
  import { selectionState } from "../config/environment.js";
11
11
  import { LoginRequiredError } from "../features/auth/transport.js";
12
12
  import { runLogin } from "./auth.js";
13
+ import { interactiveTerminal } from "./pick.js";
13
14
  import { synchronize } from "../features/environment/sync.js";
14
15
  import { cleanUpIfInterrupted } from "../features/environment/transaction.js";
15
16
  import { renderSyncOutput } from "./output.js";
16
- import checkbox from "@inquirer/checkbox";
17
17
  import confirm from "@inquirer/confirm";
18
- import { existsSync, rmSync } from "node:fs";
19
- import { homedir } from "node:os";
20
- import { basename, join } from "node:path";
18
+ import { existsSync, readdirSync, rmSync } from "node:fs";
19
+ import { basename } from "node:path";
21
20
  import { styleText } from "node:util";
22
- import { readSettings, settingsPath, } from "../config/settings.js";
21
+ import { readSettings, } from "../config/settings.js";
23
22
  import { initialize, } from "../features/onboarding/setup.js";
24
- import { checkboxTheme, promptTheme, selected } from "./theme.js";
25
- import { bold, dim, fields, heading, originLabel, table } from "./format.js";
26
- const chooseHarnesses = (choices) => {
27
- const width = Math.max(...choices.map((choice) => choice.name.length));
28
- return checkbox({
29
- loop: false,
30
- message: "Which coding tools should BarnDog manage?",
31
- choices: choices.map((choice) => ({
32
- value: choice.value,
33
- checked: choice.checked,
34
- short: choice.name,
35
- name: `${choice.name.padEnd(width)} ${choice.evidence ? selected("detected") : dim("not found")}`,
36
- description: choice.evidence ?? undefined,
37
- })),
38
- theme: checkboxTheme,
39
- });
40
- };
23
+ import { promptTheme, selected } from "./theme.js";
24
+ import { chooseHarnesses } from "./harness-picker.js";
25
+ import { offerAdoptionAtSetup, } from "./adopt.js";
26
+ import { bold, dim, fields, heading, originLabel, table, warn, } from "./format.js";
27
+ import { barndogPaths } from "../config/paths.js";
28
+ /** The source setup was last run with, offered as the default. */
29
+ function savedChoice(previous, server) {
30
+ if (previous.gitWorkspace) {
31
+ return { kind: "git", url: previous.gitWorkspace.url };
32
+ }
33
+ if (previous.localWorkspace) {
34
+ return { kind: "local" };
35
+ }
36
+ return server ? { kind: "cloud", server } : undefined;
37
+ }
38
+ /** The source named by `--local`, `--repo` or `--server`, if any. */
39
+ function flagChoice(options) {
40
+ if (options.local) {
41
+ return { kind: "local" };
42
+ }
43
+ if (options.repo) {
44
+ return { kind: "git", url: options.repo };
45
+ }
46
+ return options.server ? { kind: "cloud", server: options.server } : undefined;
47
+ }
41
48
  /** Starting over always offers every source; a saved server is only the default. */
42
- async function chooseSource(previous, home, choose = chooseConnection) {
43
- const server = await configuredServer(home);
44
- if (!previous)
49
+ async function chooseSource(previous, runtime, choose = chooseConnection) {
50
+ const server = await configuredServer(runtime);
51
+ if (!previous) {
45
52
  return server ? { kind: "cloud", server } : choose();
46
- const saved = previous.version === 2 ? previous : undefined;
47
- return choose(saved?.gitWorkspace
48
- ? { kind: "git", url: saved.gitWorkspace.url }
49
- : saved?.localWorkspace
50
- ? { kind: "local" }
51
- : server
52
- ? { kind: "cloud", server }
53
- : undefined);
53
+ }
54
+ return choose(savedChoice(previous, server));
55
+ }
56
+ /**
57
+ * Runs setup prompts and connection preparation, saves settings and applies the
58
+ * chosen environment when confirmed.
59
+ */
60
+ /** The bare clones `~/.barndog/git` holds, so setup can tell which one it made. */
61
+ function gitClones(home) {
62
+ const folder = barndogPaths(home).git;
63
+ return new Set(existsSync(folder) ? readdirSync(folder) : []);
54
64
  }
55
- export async function runSetup(options = {}) {
56
- const home = options.home ?? homedir();
65
+ /**
66
+ * A clone made for this run shouldn't outlive a setup that didn't finish; one
67
+ * that was already there belongs to an earlier setup and stays.
68
+ */
69
+ function cloneCleanup(home, before, workspaceId) {
70
+ const paths = barndogPaths(home);
71
+ if (before.has(basename(paths.bareClone(workspaceId)))) {
72
+ return { keep: () => { } };
73
+ }
74
+ const discard = () => {
75
+ rmSync(paths.bareClone(workspaceId), { recursive: true, force: true });
76
+ rmSync(paths.fetchState(workspaceId), { force: true });
77
+ };
78
+ return { discard, keep: cleanUpIfInterrupted(discard) };
79
+ }
80
+ /** The setup choices that send local assets to the new workspace. */
81
+ const sharesLocalAssets = {
82
+ keep: false,
83
+ copy: true,
84
+ move: true,
85
+ leave: false,
86
+ };
87
+ export async function runSetup(options) {
88
+ const { runtime } = options;
89
+ const { home } = runtime;
57
90
  const write = options.write ?? console.log;
91
+ // Checked first, so a wrong command line fails before any question.
92
+ if ([options.local, options.server, options.repo].filter(Boolean).length > 1) {
93
+ throw new CliError("--local, --repo and --server can't be combined. Choose one.", "barndog init --help");
94
+ }
58
95
  const previous = await readSettings(home);
59
96
  if (previous) {
60
- write(`Configuration already exists at ${settingsPath(home)}.`);
97
+ write(`Configuration already exists at ${barndogPaths(home).settings}.`);
61
98
  write("");
62
99
  if (!options.restart) {
63
100
  write(`To start setup again, run ${styleText("bold", "barndog init")}.`);
64
101
  return;
65
102
  }
66
103
  }
67
- const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
104
+ const interactive = options.interactive ?? interactiveTerminal();
68
105
  if (!interactive) {
69
- throw new Error(`Onboarding requires an interactive terminal. Run ${styleText("bold", "barndog init", { stream: process.stderr })} in your terminal.`);
106
+ throw new CliError("Setup needs an interactive terminal. Run it in your terminal, not from a script or pipe.", "barndog init");
70
107
  }
71
108
  if (previous) {
72
109
  const confirmed = await (options.confirmRestart ??
@@ -81,22 +118,15 @@ export async function runSetup(options = {}) {
81
118
  }
82
119
  }
83
120
  write(`\n${heading("setup")}\n`);
84
- if ([options.local, options.server, options.repo].filter(Boolean).length > 1)
85
- throw new Error("--local, --repo and --server cannot be combined");
86
- const choice = options.local
87
- ? { kind: "local" }
88
- : options.repo
89
- ? { kind: "git", url: options.repo }
90
- : options.server
91
- ? { kind: "cloud", server: options.server }
92
- : await chooseSource(previous, home, options.chooseConnection);
121
+ const choice = flagChoice(options) ??
122
+ (await chooseSource(previous, options.runtime, options.chooseConnection));
93
123
  const server = choice.kind === "cloud" ? choice.server : undefined;
94
124
  let workspace;
95
125
  let discardWorkspace;
96
126
  let keepWorkspace = () => { };
97
127
  if (choice.kind === "local") {
98
- const fresh = !existsSync(defaultLocalPath(home));
99
- const local = await localWorkspace(home);
128
+ const fresh = !existsSync(barndogPaths(home).localWorkspace);
129
+ const local = await localWorkspace(options.runtime);
100
130
  workspace = { kind: "local", local };
101
131
  // A folder made for this run shouldn't outlive a setup that didn't finish.
102
132
  if (fresh) {
@@ -105,26 +135,29 @@ export async function runSetup(options = {}) {
105
135
  }
106
136
  }
107
137
  if (choice.kind === "git") {
108
- const url = checkRepositoryUrl(await cloneOrigin(choice.url));
138
+ const clonesBefore = gitClones(home);
139
+ const url = checkRepositoryUrl(await cloneOrigin(choice.url, options.runtime));
109
140
  let head = null;
110
141
  let cloned = null;
111
142
  try {
112
- head = await inspectRepository(url);
143
+ head = await inspectRepository(url, options.runtime);
113
144
  }
114
145
  catch (error) {
115
- if (!(error instanceof RepositoryAccessError))
146
+ if (!(error instanceof RepositoryAccessError)) {
116
147
  throw error;
148
+ }
117
149
  write(`${error.message}`);
118
150
  write(dim("Git has to be able to clone this repo on this machine. Once it can, BarnDog manages it for you."));
119
151
  const clone = await (options.confirmClone ??
120
152
  (() => confirm({
121
- message: `Clone it now into ${join(home, ".barndog", "git")}? Git will ask for anything it needs.`,
153
+ message: `Clone it now into ${barndogPaths(home).git}? Git will ask for anything it needs.`,
122
154
  default: true,
123
155
  theme: promptTheme,
124
156
  })))(url);
125
- if (!clone)
157
+ if (!clone) {
126
158
  throw error;
127
- cloned = await cloneGitWorkspace(url, home);
159
+ }
160
+ cloned = await cloneGitWorkspace(url, options.runtime);
128
161
  }
129
162
  if (!head && !cloned) {
130
163
  const create = await (options.confirmCreateRepo ??
@@ -133,43 +166,53 @@ export async function runSetup(options = {}) {
133
166
  default: true,
134
167
  theme: promptTheme,
135
168
  })))(url);
136
- if (!create)
169
+ if (!create) {
137
170
  throw new CliError("Setup stopped. The repository was not changed.");
171
+ }
138
172
  }
139
- workspace = {
140
- kind: "git",
141
- git: cloned ??
142
- (head
143
- ? await connectGitWorkspace(url, head.branch, home)
144
- : await createGitWorkspace(url, basename(url).replace(/\.git$/, "") || "Workspace", home)),
145
- };
173
+ const git = cloned ??
174
+ (head
175
+ ? await connectGitWorkspace(url, head.branch, options.runtime)
176
+ : await createGitWorkspace(url, basename(url).replace(/\.git$/, "") || "Workspace", options.runtime));
177
+ workspace = { kind: "git", git };
178
+ ({ discard: discardWorkspace, keep: keepWorkspace } = cloneCleanup(home, clonesBefore, git.workspaceId));
146
179
  write(`${dim("Git repo")} ${url}`);
147
180
  write(dim("Anything merged to its default branch installs on every machine that selected it, including code that runs. Keeping the repo safe is the job of its maintainers and members, so protect the default branch."));
148
- if (!head && !cloned)
181
+ if (!head && !cloned) {
149
182
  write(dim("Next, protect the default branch on your Git host and let members push other branches."));
183
+ }
150
184
  }
151
185
  if (server) {
152
186
  write(`${dim("Workspace")} ${server}`);
153
187
  let session;
154
188
  try {
155
- session = await authStatus(home, server);
189
+ session = await authStatus(options.runtime, server);
156
190
  }
157
191
  catch (error) {
158
- if (!(error instanceof LoginRequiredError))
192
+ if (!(error instanceof LoginRequiredError)) {
159
193
  throw error;
160
- await runLogin({ server, browser: options.browser !== false, home, force: true }, write);
161
- session = await authStatus(home, server);
194
+ }
195
+ await runLogin({
196
+ server,
197
+ browser: options.browser !== false,
198
+ runtime,
199
+ force: true,
200
+ interactive,
201
+ }, write);
202
+ session = await authStatus(options.runtime, server);
162
203
  }
163
204
  write(`${dim("Signed in")} ${session.context.developer.name} · ${session.context.organization.name}`);
164
205
  }
165
- const keptFolder = previous?.version === 2 && choice.kind !== "local"
166
- ? previous.localWorkspace
167
- : undefined;
206
+ const keptFolder = previous && choice.kind !== "local" ? previous.localWorkspace : undefined;
168
207
  const localCount = keptFolder
169
- ? await localRepoSource(keptFolder, home)
208
+ ? await localRepoSource(keptFolder, options.runtime)
170
209
  .model()
171
210
  .then((model) => model.assets.length + model.knowledge.length)
172
- .catch(() => 0)
211
+ .catch((error) => {
212
+ // Setup goes on and leaves the folder as it is, but says why it didn't ask.
213
+ write(`${warn("!")} Couldn't read the local workspace at ${keptFolder.path}, so it stays as it is: ${friendlyMessage(error)}`);
214
+ return 0;
215
+ })
173
216
  : 0;
174
217
  const localChoice = localCount
175
218
  ? await (options.chooseLocalAssets ?? chooseLocalAssets)(localCount)
@@ -178,11 +221,10 @@ export async function runSetup(options = {}) {
178
221
  write("");
179
222
  let environmentChoices;
180
223
  const initialized = initialize({
181
- home,
224
+ runtime,
182
225
  server,
183
226
  workspace,
184
227
  keepLocal: localChoice === "leave" ? undefined : keptFolder,
185
- cwd: options.cwd,
186
228
  chooseEnvironment: async (choices) => {
187
229
  environmentChoices = choices;
188
230
  return (options.chooseEnvironment ?? environmentChooser(write))(choices);
@@ -197,16 +239,14 @@ export async function runSetup(options = {}) {
197
239
  ["Coding tools", settings.harnesses.join(", ") || "none"],
198
240
  [
199
241
  "Workspace",
200
- settings.version === 2
201
- ? (settings.connection?.server ??
202
- settings.gitWorkspace?.url ??
203
- settings.localWorkspace?.path)
204
- : undefined,
242
+ settings.connection?.server ??
243
+ settings.gitWorkspace?.url ??
244
+ settings.localWorkspace?.path,
205
245
  ],
206
- ]))
246
+ ])) {
207
247
  write(line);
208
- if (settings.version === 2 &&
209
- (settings.connection || settings.gitWorkspace)) {
248
+ }
249
+ if (settings.connection || settings.gitWorkspace) {
210
250
  const selection = selectionState(settings);
211
251
  write("");
212
252
  write(`${bold("Scope sets")} ${dim(`(${selection.subscriptions.length})`)}`);
@@ -214,8 +254,9 @@ export async function runSetup(options = {}) {
214
254
  ? table(selection.subscriptions.map((subscription) => {
215
255
  const scope = environmentChoices?.scopes.find((scope) => scope.id === subscription.scope.id &&
216
256
  scope.type === subscription.scope.type);
217
- if (!scope && settings.localWorkspace)
257
+ if (!scope && settings.localWorkspace) {
218
258
  return ["local", "Your local assets", subscription.mode];
259
+ }
219
260
  return [
220
261
  scope
221
262
  ? originLabel(scope)
@@ -252,8 +293,9 @@ export async function runSetup(options = {}) {
252
293
  },
253
294
  apply: connected
254
295
  ? async (settings) => {
255
- for (const line of renderSyncOutput(await synchronize(undefined, home, settings)))
296
+ for (const line of renderSyncOutput(await synchronize(undefined, options.runtime, settings))) {
256
297
  write(line);
298
+ }
257
299
  }
258
300
  : undefined,
259
301
  });
@@ -268,13 +310,22 @@ export async function runSetup(options = {}) {
268
310
  write("Setup cancelled. Configuration and installed assets were not changed. Your sign-in is retained.");
269
311
  return;
270
312
  }
271
- if (localChoice === "move" && localCount) {
313
+ if (sharesLocalAssets[localChoice] && localCount) {
272
314
  const to = choice.kind === "cloud"
273
- ? await (options.chooseMoveTarget ?? chooseMoveTarget)(await cloudMoveTargets(home))
315
+ ? await (options.chooseMoveTarget ?? chooseMoveTarget)(await cloudMoveTargets(options.runtime))
274
316
  : undefined;
275
317
  write("");
276
- for (const line of renderMove(await moveLocalAssets({ to }, home)))
318
+ for (const line of renderMove(await moveLocalAssets({ to, keepLocal: localChoice === "copy" }, options.runtime))) {
277
319
  write(line);
320
+ }
321
+ }
322
+ // Only a first setup asks: later runs already had the chance, and `barndog adopt` stays available.
323
+ if (!previous) {
324
+ await offerAdoptionAtSetup(runtime, {
325
+ write,
326
+ choose: options.chooseAdoption,
327
+ confirm: options.confirmAdoption,
328
+ });
278
329
  }
279
330
  write("");
280
331
  write(`${selected("✔")} Saved to ${result.configPath}`);
@@ -285,9 +336,11 @@ export async function runSetup(options = {}) {
285
336
  ? ` ${bold("barndog skills install")} ${dim("add more (also mcp, hooks, sets)")}`
286
337
  : ` ${bold("barndog skills add <url>")} ${dim("add from a repo (also hooks add, mcp add)")}`);
287
338
  write(` ${bold("barndog sync")} ${dim("pick up published updates")}`);
288
- if (choice.kind === "local")
339
+ if (choice.kind === "local") {
289
340
  write(` ${dim(`add assets under ${workspace?.kind === "local" ? workspace.local.path : ""}`)}`);
341
+ }
290
342
  }
291
- else
343
+ else {
292
344
  write(`${dim("Next:")} ${bold("barndog sync")} ${dim("then connect a Git repo or Cloud Workspace later with barndog init")}`);
345
+ }
293
346
  }
@@ -0,0 +1,9 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { POSITIVE_INTEGER } from "../shared/patterns.js";
3
+ /** Commander option parser for counts, pages, line numbers and revisions. */
4
+ export function positiveInteger(value) {
5
+ if (!POSITIVE_INTEGER.test(value) || !Number.isSafeInteger(Number(value))) {
6
+ throw new InvalidArgumentError("Use a positive integer");
7
+ }
8
+ return Number(value);
9
+ }