barndog 0.1.1 → 0.2.0

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 (173) hide show
  1. package/README.md +8 -7
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +13 -3
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
package/dist/ui/format.js CHANGED
@@ -1,7 +1,27 @@
1
1
  import { stripVTControlCharacters, styleText } from "node:util";
2
- import { safe } from "./collaboration.js";
3
2
  import { danger, primary, selected } from "./theme.js";
3
+ import { CONSTANT_CASE } from "../shared/patterns.js";
4
+ import { isRecord } from "../shared/values.js";
5
+ import { HEX_RADIX } from "../shared/constants.js";
6
+ /** Keep the flexible table column readable when shrinking to terminal width. */
7
+ const MIN_FLEX_COLUMN_WIDTH = 8;
8
+ /** JavaScript Unicode escapes encode a UTF-16 code unit with four hex digits. */
9
+ const UNICODE_ESCAPE_DIGITS = 4;
10
+ /** C0 and C1 control characters other than tab and line feed, such as ESC (`\x1b`). */
11
+ // eslint-disable-next-line no-control-regex -- finding control characters is the point
12
+ const CONTROL_CHARACTERS = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
13
+ /**
14
+ * Remote package text must not be able to emit terminal control sequences:
15
+ * `"\x1b[31mred"` → `"\\u001b[31mred"`.
16
+ */
17
+ export function safe(value) {
18
+ return String(value).replace(CONTROL_CHARACTERS, (c) => `\\u${c.charCodeAt(0).toString(HEX_RADIX).padStart(UNICODE_ESCAPE_DIGITS, "0")}`);
19
+ }
4
20
  const paint = (style, text) => styleText(style, text, { stream: process.stdout });
21
+ /**
22
+ * Emphasis for commands, names and values, using Node's stream-aware color
23
+ * policy for stdout.
24
+ */
5
25
  export const bold = (text) => paint("bold", text);
6
26
  export const dim = (text) => paint("dim", text);
7
27
  export const warn = (text) => paint("yellow", text);
@@ -11,20 +31,28 @@ export const bad = (text) => danger(text);
11
31
  export function clean(value) {
12
32
  return safe(value).replace(/\s+/g, " ").trim();
13
33
  }
34
+ /**
35
+ * Counts Unicode code points after stripping terminal control sequences. This
36
+ * is a layout approximation, not the display-cell width of wide characters or
37
+ * emoji.
38
+ */
14
39
  export function visibleWidth(text) {
15
40
  return [...stripVTControlCharacters(text)].length;
16
41
  }
17
42
  function pad(text, width) {
18
43
  return text + " ".repeat(Math.max(0, width - visibleWidth(text)));
19
44
  }
45
+ /** One SGR style code, such as `\u001b[1m` (bold) or `\u001b[38;2;197;72;54m`; captured so `split` keeps it. */
20
46
  // eslint-disable-next-line no-control-regex -- matches terminal style codes
21
- const STYLE_CODE = new RegExp("(\\u001b\\[[0-9;]*m)");
47
+ const STYLE_CODE = /(\u001b\[[\d;]*m)/;
22
48
  function truncate(text, width) {
23
49
  const plain = stripVTControlCharacters(text);
24
- if ([...plain].length <= width)
50
+ if ([...plain].length <= width) {
25
51
  return text;
26
- if (width <= 1)
52
+ }
53
+ if (width <= 1) {
27
54
  return "…";
55
+ }
28
56
  // Every style code is kept, so a cut cell looks like the uncut ones.
29
57
  let room = width - 1;
30
58
  let cut = false;
@@ -34,8 +62,9 @@ function truncate(text, width) {
34
62
  output += part;
35
63
  continue;
36
64
  }
37
- if (cut)
65
+ if (cut) {
38
66
  continue;
67
+ }
39
68
  const characters = [...part];
40
69
  if (characters.length <= room) {
41
70
  output += part;
@@ -47,12 +76,17 @@ function truncate(text, width) {
47
76
  }
48
77
  return output;
49
78
  }
79
+ /**
80
+ * A command's title line: the brand name in the primary color, then `title` in
81
+ * bold.
82
+ */
50
83
  export function heading(title) {
51
84
  return `${primary(bold("BarnDog"))} ${bold(title)}`;
52
85
  }
53
86
  export function section(title) {
54
87
  return bold(title);
55
88
  }
89
+ /** A `Next:`, `Fix:` or `Tip:` line suggesting a command to run. */
56
90
  export function hint(command, label = "Next") {
57
91
  return `${dim(`${label}:`)} ${bold(command)}`;
58
92
  }
@@ -68,8 +102,9 @@ export function table(rows, options = {}) {
68
102
  const all = options.header
69
103
  ? [options.header.map((cell) => dim(cell)), ...rows]
70
104
  : [...rows];
71
- if (!all.length)
105
+ if (!all.length) {
72
106
  return [];
107
+ }
73
108
  const count = Math.max(...all.map((row) => row.length));
74
109
  const widths = Array.from({ length: count }, (_, column) => Math.max(0, ...all.map((row) => visibleWidth(row[column] ?? ""))));
75
110
  const flex = options.flex ?? count - 1;
@@ -77,8 +112,9 @@ export function table(rows, options = {}) {
77
112
  indent.length -
78
113
  (count - 1) * 2;
79
114
  const total = widths.reduce((sum, width) => sum + width, 0);
80
- if (total > available && widths[flex] !== undefined)
81
- widths[flex] = Math.max(8, widths[flex] - (total - available));
115
+ if (total > available && widths[flex] !== undefined) {
116
+ widths[flex] = Math.max(MIN_FLEX_COLUMN_WIDTH, widths[flex] - (total - available));
117
+ }
82
118
  return all.map((row) => (indent +
83
119
  widths
84
120
  .map((width, column) => {
@@ -88,6 +124,7 @@ export function table(rows, options = {}) {
88
124
  })
89
125
  .join(" ")).trimEnd());
90
126
  }
127
+ /** Known states get a color; any other text shows as it is. */
91
128
  export function badge(state, label = state) {
92
129
  switch (state) {
93
130
  case "installed":
@@ -105,14 +142,20 @@ export function badge(state, label = state) {
105
142
  return dim(label);
106
143
  }
107
144
  }
108
- export { originLabel } from "../features/environment/names.js";
145
+ export { originLabel } from "../features/server/origin.js";
146
+ /** `1 skill`, `2 skills`; pass `many` for irregular plurals. */
109
147
  export function plural(count, noun, many = `${noun}s`) {
110
148
  return `${count} ${count === 1 ? noun : many}`;
111
149
  }
150
+ /** `up_to_date` → `Up to date`: a server or state code as a label. */
112
151
  export function humanize(value) {
113
152
  const text = value.replaceAll("_", " ");
114
- return text[0].toUpperCase() + text.slice(1);
153
+ return text.charAt(0).toUpperCase() + text.slice(1);
115
154
  }
155
+ /**
156
+ * The `--json` rendering of a result: two-space indented JSON, without a
157
+ * trailing newline.
158
+ */
116
159
  export function json(value) {
117
160
  return JSON.stringify(value, null, 2);
118
161
  }
@@ -121,27 +164,32 @@ const isPlain = (value) => value === null || ["string", "number", "boolean"].inc
121
164
  const show = (value) => value === null || value === undefined ? dim("—") : clean(value);
122
165
  const label = (key) =>
123
166
  // Environment variable names are data, not field labels.
124
- /^[A-Z][A-Z0-9_]*$/.test(key)
167
+ CONSTANT_CASE.test(key)
125
168
  ? key
126
169
  : humanize(key.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase());
127
170
  /** Readable fallback for structured results: key/value blocks and tables. */
128
171
  export function renderValue(value, indent = 0) {
129
- if (isPlain(value))
172
+ if (isPlain(value)) {
130
173
  return [`${" ".repeat(indent)}${show(value)}`];
174
+ }
131
175
  if (Array.isArray(value)) {
132
- if (!value.length)
176
+ if (!value.length) {
133
177
  return [`${" ".repeat(indent)}${dim("None.")}`];
134
- if (value.every((row) => row && typeof row === "object" && !Array.isArray(row))) {
135
- const keys = Object.keys(value[0]).filter((key) => value.every((row) => isPlain(row[key])));
136
- if (keys.length)
137
- return table(value.map((row) => keys.map((key) => show(row[key]))), { header: keys.map(label), indent: indent + 2 });
178
+ }
179
+ const rows = value.filter(isRecord);
180
+ const [first] = rows;
181
+ if (first && rows.length === value.length) {
182
+ const keys = Object.keys(first).filter((key) => rows.every((row) => isPlain(row[key])));
183
+ if (keys.length) {
184
+ return table(rows.map((row) => keys.map((key) => show(row[key]))), { header: keys.map(label), indent: indent + 2 });
185
+ }
138
186
  }
139
187
  return value.flatMap((row, index) => [
140
188
  ...(index ? [""] : []),
141
189
  ...renderValue(row, indent),
142
190
  ]);
143
191
  }
144
- const entries = Object.entries(value);
192
+ const entries = Object.entries(isRecord(value) ? value : {});
145
193
  const simple = entries.filter(([, v]) => isPlain(v));
146
194
  const nested = entries.filter(([, v]) => !isPlain(v) && v !== undefined);
147
195
  return [
@@ -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,8 @@
1
1
  import { bold, dim, hint, ok, table, warn } from "./format.js";
2
2
  export function renderMove(result) {
3
- if (!result.rows.length)
3
+ if (!result.rows.length) {
4
4
  return [dim("Nothing to move.")];
5
+ }
5
6
  const output = table(result.rows.map((row) => [
6
7
  row.status === "moved" ? ok(row.status) : warn(row.status),
7
8
  dim(row.kind),
@@ -9,14 +10,18 @@ export function renderMove(result) {
9
10
  dim(row.detail ?? ""),
10
11
  ]), { header: ["Status", "Kind", "Name", ""] });
11
12
  output.push("");
12
- if (result.direct)
13
+ if (result.direct) {
13
14
  output.push(`${ok("✔")} Added to ${result.branch}.`);
14
- else if (result.branch)
15
+ }
16
+ else if (result.branch) {
15
17
  output.push(result.url
16
18
  ? `Open the pull request: ${result.url}`
17
19
  : `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")
20
+ }
21
+ for (const row of result.rows) {
22
+ if (row.status === "clash") {
20
23
  output.push(hint(`barndog local move ${row.name} --as <new-name>`, "Fix"));
24
+ }
25
+ }
21
26
  return output;
22
27
  }
@@ -1,11 +1,11 @@
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";
7
+ import { checkRepositoryUrl, cloneOrigin, RepositoryAccessError, } from "../features/workspace/git.js";
8
+ import { cloneGitWorkspace, connectGitWorkspace, createGitWorkspace, inspectRepository, localWorkspace, } from "../features/workspace/setup.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { selectionState } from "../config/environment.js";
11
11
  import { LoginRequiredError } from "../features/auth/transport.js";
@@ -15,14 +15,14 @@ import { cleanUpIfInterrupted } from "../features/environment/transaction.js";
15
15
  import { renderSyncOutput } from "./output.js";
16
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
23
  import { checkboxTheme, promptTheme, selected } from "./theme.js";
25
24
  import { bold, dim, fields, heading, originLabel, table } from "./format.js";
25
+ import { barndogPaths } from "../config/paths.js";
26
26
  const chooseHarnesses = (choices) => {
27
27
  const width = Math.max(...choices.map((choice) => choice.name.length));
28
28
  return checkbox({
@@ -38,26 +38,65 @@ const chooseHarnesses = (choices) => {
38
38
  theme: checkboxTheme,
39
39
  });
40
40
  };
41
+ /** The source setup was last run with, offered as the default. */
42
+ function savedChoice(previous, server) {
43
+ if (previous.gitWorkspace) {
44
+ return { kind: "git", url: previous.gitWorkspace.url };
45
+ }
46
+ if (previous.localWorkspace) {
47
+ return { kind: "local" };
48
+ }
49
+ return server ? { kind: "cloud", server } : undefined;
50
+ }
51
+ /** The source named by `--local`, `--repo` or `--server`, if any. */
52
+ function flagChoice(options) {
53
+ if (options.local) {
54
+ return { kind: "local" };
55
+ }
56
+ if (options.repo) {
57
+ return { kind: "git", url: options.repo };
58
+ }
59
+ return options.server ? { kind: "cloud", server: options.server } : undefined;
60
+ }
41
61
  /** 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)
62
+ async function chooseSource(previous, runtime, choose = chooseConnection) {
63
+ const server = await configuredServer(runtime);
64
+ if (!previous) {
45
65
  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);
66
+ }
67
+ return choose(savedChoice(previous, server));
68
+ }
69
+ /**
70
+ * Runs setup prompts and connection preparation, saves settings and applies the
71
+ * chosen environment when confirmed.
72
+ */
73
+ /** The bare clones `~/.barndog/git` holds, so setup can tell which one it made. */
74
+ function gitClones(home) {
75
+ const folder = barndogPaths(home).git;
76
+ return new Set(existsSync(folder) ? readdirSync(folder) : []);
54
77
  }
55
- export async function runSetup(options = {}) {
56
- const home = options.home ?? homedir();
78
+ /**
79
+ * A clone made for this run shouldn't outlive a setup that didn't finish; one
80
+ * that was already there belongs to an earlier setup and stays.
81
+ */
82
+ function cloneCleanup(home, before, workspaceId) {
83
+ const paths = barndogPaths(home);
84
+ if (before.has(basename(paths.bareClone(workspaceId)))) {
85
+ return { keep: () => { } };
86
+ }
87
+ const discard = () => {
88
+ rmSync(paths.bareClone(workspaceId), { recursive: true, force: true });
89
+ rmSync(paths.fetchState(workspaceId), { force: true });
90
+ };
91
+ return { discard, keep: cleanUpIfInterrupted(discard) };
92
+ }
93
+ export async function runSetup(options) {
94
+ const { runtime } = options;
95
+ const { home } = runtime;
57
96
  const write = options.write ?? console.log;
58
97
  const previous = await readSettings(home);
59
98
  if (previous) {
60
- write(`Configuration already exists at ${settingsPath(home)}.`);
99
+ write(`Configuration already exists at ${barndogPaths(home).settings}.`);
61
100
  write("");
62
101
  if (!options.restart) {
63
102
  write(`To start setup again, run ${styleText("bold", "barndog init")}.`);
@@ -66,7 +105,7 @@ export async function runSetup(options = {}) {
66
105
  }
67
106
  const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
68
107
  if (!interactive) {
69
- throw new Error(`Onboarding requires an interactive terminal. Run ${styleText("bold", "barndog init", { stream: process.stderr })} in your terminal.`);
108
+ throw new CliError("Setup needs an interactive terminal. Run it in your terminal, not from a script or pipe.", "barndog init");
70
109
  }
71
110
  if (previous) {
72
111
  const confirmed = await (options.confirmRestart ??
@@ -81,22 +120,18 @@ export async function runSetup(options = {}) {
81
120
  }
82
121
  }
83
122
  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);
123
+ if ([options.local, options.server, options.repo].filter(Boolean).length > 1) {
124
+ throw new CliError("--local, --repo and --server can't be combined. Choose one.", "barndog init --help");
125
+ }
126
+ const choice = flagChoice(options) ??
127
+ (await chooseSource(previous, options.runtime, options.chooseConnection));
93
128
  const server = choice.kind === "cloud" ? choice.server : undefined;
94
129
  let workspace;
95
130
  let discardWorkspace;
96
131
  let keepWorkspace = () => { };
97
132
  if (choice.kind === "local") {
98
- const fresh = !existsSync(defaultLocalPath(home));
99
- const local = await localWorkspace(home);
133
+ const fresh = !existsSync(barndogPaths(home).localWorkspace);
134
+ const local = await localWorkspace(options.runtime);
100
135
  workspace = { kind: "local", local };
101
136
  // A folder made for this run shouldn't outlive a setup that didn't finish.
102
137
  if (fresh) {
@@ -105,26 +140,29 @@ export async function runSetup(options = {}) {
105
140
  }
106
141
  }
107
142
  if (choice.kind === "git") {
108
- const url = checkRepositoryUrl(await cloneOrigin(choice.url));
143
+ const clonesBefore = gitClones(home);
144
+ const url = checkRepositoryUrl(await cloneOrigin(choice.url, options.runtime));
109
145
  let head = null;
110
146
  let cloned = null;
111
147
  try {
112
- head = await inspectRepository(url);
148
+ head = await inspectRepository(url, options.runtime);
113
149
  }
114
150
  catch (error) {
115
- if (!(error instanceof RepositoryAccessError))
151
+ if (!(error instanceof RepositoryAccessError)) {
116
152
  throw error;
153
+ }
117
154
  write(`${error.message}`);
118
155
  write(dim("Git has to be able to clone this repo on this machine. Once it can, BarnDog manages it for you."));
119
156
  const clone = await (options.confirmClone ??
120
157
  (() => confirm({
121
- message: `Clone it now into ${join(home, ".barndog", "git")}? Git will ask for anything it needs.`,
158
+ message: `Clone it now into ${barndogPaths(home).git}? Git will ask for anything it needs.`,
122
159
  default: true,
123
160
  theme: promptTheme,
124
161
  })))(url);
125
- if (!clone)
162
+ if (!clone) {
126
163
  throw error;
127
- cloned = await cloneGitWorkspace(url, home);
164
+ }
165
+ cloned = await cloneGitWorkspace(url, options.runtime);
128
166
  }
129
167
  if (!head && !cloned) {
130
168
  const create = await (options.confirmCreateRepo ??
@@ -133,40 +171,40 @@ export async function runSetup(options = {}) {
133
171
  default: true,
134
172
  theme: promptTheme,
135
173
  })))(url);
136
- if (!create)
174
+ if (!create) {
137
175
  throw new CliError("Setup stopped. The repository was not changed.");
176
+ }
138
177
  }
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
- };
178
+ const git = cloned ??
179
+ (head
180
+ ? await connectGitWorkspace(url, head.branch, options.runtime)
181
+ : await createGitWorkspace(url, basename(url).replace(/\.git$/, "") || "Workspace", options.runtime));
182
+ workspace = { kind: "git", git };
183
+ ({ discard: discardWorkspace, keep: keepWorkspace } = cloneCleanup(home, clonesBefore, git.workspaceId));
146
184
  write(`${dim("Git repo")} ${url}`);
147
185
  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)
186
+ if (!head && !cloned) {
149
187
  write(dim("Next, protect the default branch on your Git host and let members push other branches."));
188
+ }
150
189
  }
151
190
  if (server) {
152
191
  write(`${dim("Workspace")} ${server}`);
153
192
  let session;
154
193
  try {
155
- session = await authStatus(home, server);
194
+ session = await authStatus(options.runtime, server);
156
195
  }
157
196
  catch (error) {
158
- if (!(error instanceof LoginRequiredError))
197
+ if (!(error instanceof LoginRequiredError)) {
159
198
  throw error;
160
- await runLogin({ server, browser: options.browser !== false, home, force: true }, write);
161
- session = await authStatus(home, server);
199
+ }
200
+ await runLogin({ server, browser: options.browser !== false, runtime, force: true }, write);
201
+ session = await authStatus(options.runtime, server);
162
202
  }
163
203
  write(`${dim("Signed in")} ${session.context.developer.name} · ${session.context.organization.name}`);
164
204
  }
165
- const keptFolder = previous?.version === 2 && choice.kind !== "local"
166
- ? previous.localWorkspace
167
- : undefined;
205
+ const keptFolder = previous && choice.kind !== "local" ? previous.localWorkspace : undefined;
168
206
  const localCount = keptFolder
169
- ? await localRepoSource(keptFolder, home)
207
+ ? await localRepoSource(keptFolder, options.runtime)
170
208
  .model()
171
209
  .then((model) => model.assets.length + model.knowledge.length)
172
210
  .catch(() => 0)
@@ -178,11 +216,10 @@ export async function runSetup(options = {}) {
178
216
  write("");
179
217
  let environmentChoices;
180
218
  const initialized = initialize({
181
- home,
219
+ runtime,
182
220
  server,
183
221
  workspace,
184
222
  keepLocal: localChoice === "leave" ? undefined : keptFolder,
185
- cwd: options.cwd,
186
223
  chooseEnvironment: async (choices) => {
187
224
  environmentChoices = choices;
188
225
  return (options.chooseEnvironment ?? environmentChooser(write))(choices);
@@ -197,16 +234,14 @@ export async function runSetup(options = {}) {
197
234
  ["Coding tools", settings.harnesses.join(", ") || "none"],
198
235
  [
199
236
  "Workspace",
200
- settings.version === 2
201
- ? (settings.connection?.server ??
202
- settings.gitWorkspace?.url ??
203
- settings.localWorkspace?.path)
204
- : undefined,
237
+ settings.connection?.server ??
238
+ settings.gitWorkspace?.url ??
239
+ settings.localWorkspace?.path,
205
240
  ],
206
- ]))
241
+ ])) {
207
242
  write(line);
208
- if (settings.version === 2 &&
209
- (settings.connection || settings.gitWorkspace)) {
243
+ }
244
+ if (settings.connection || settings.gitWorkspace) {
210
245
  const selection = selectionState(settings);
211
246
  write("");
212
247
  write(`${bold("Scope sets")} ${dim(`(${selection.subscriptions.length})`)}`);
@@ -214,8 +249,9 @@ export async function runSetup(options = {}) {
214
249
  ? table(selection.subscriptions.map((subscription) => {
215
250
  const scope = environmentChoices?.scopes.find((scope) => scope.id === subscription.scope.id &&
216
251
  scope.type === subscription.scope.type);
217
- if (!scope && settings.localWorkspace)
252
+ if (!scope && settings.localWorkspace) {
218
253
  return ["local", "Your local assets", subscription.mode];
254
+ }
219
255
  return [
220
256
  scope
221
257
  ? originLabel(scope)
@@ -252,8 +288,9 @@ export async function runSetup(options = {}) {
252
288
  },
253
289
  apply: connected
254
290
  ? async (settings) => {
255
- for (const line of renderSyncOutput(await synchronize(undefined, home, settings)))
291
+ for (const line of renderSyncOutput(await synchronize(undefined, options.runtime, settings))) {
256
292
  write(line);
293
+ }
257
294
  }
258
295
  : undefined,
259
296
  });
@@ -270,11 +307,12 @@ export async function runSetup(options = {}) {
270
307
  }
271
308
  if (localChoice === "move" && localCount) {
272
309
  const to = choice.kind === "cloud"
273
- ? await (options.chooseMoveTarget ?? chooseMoveTarget)(await cloudMoveTargets(home))
310
+ ? await (options.chooseMoveTarget ?? chooseMoveTarget)(await cloudMoveTargets(options.runtime))
274
311
  : undefined;
275
312
  write("");
276
- for (const line of renderMove(await moveLocalAssets({ to }, home)))
313
+ for (const line of renderMove(await moveLocalAssets({ to }, options.runtime))) {
277
314
  write(line);
315
+ }
278
316
  }
279
317
  write("");
280
318
  write(`${selected("✔")} Saved to ${result.configPath}`);
@@ -285,9 +323,11 @@ export async function runSetup(options = {}) {
285
323
  ? ` ${bold("barndog skills install")} ${dim("add more (also mcp, hooks, sets)")}`
286
324
  : ` ${bold("barndog skills add <url>")} ${dim("add from a repo (also hooks add, mcp add)")}`);
287
325
  write(` ${bold("barndog sync")} ${dim("pick up published updates")}`);
288
- if (choice.kind === "local")
326
+ if (choice.kind === "local") {
289
327
  write(` ${dim(`add assets under ${workspace?.kind === "local" ? workspace.local.path : ""}`)}`);
328
+ }
290
329
  }
291
- else
330
+ else {
292
331
  write(`${dim("Next:")} ${bold("barndog sync")} ${dim("then connect a Git repo or Cloud Workspace later with barndog init")}`);
332
+ }
293
333
  }
@@ -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
+ }