barndog 0.0.0-stage → 0.1.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -2
  3. package/dist/cli.js +40 -0
  4. package/dist/commands/add.js +99 -0
  5. package/dist/commands/auth.js +25 -0
  6. package/dist/commands/availability.js +87 -0
  7. package/dist/commands/capabilities.js +488 -0
  8. package/dist/commands/collaboration.js +203 -0
  9. package/dist/commands/context.js +1 -0
  10. package/dist/commands/environment.js +416 -0
  11. package/dist/commands/init.js +20 -0
  12. package/dist/commands/origin.js +48 -0
  13. package/dist/commands/status.js +66 -0
  14. package/dist/commands/sync.js +30 -0
  15. package/dist/commands/workspace.js +84 -0
  16. package/dist/config/build.js +2 -0
  17. package/dist/config/environment.js +41 -0
  18. package/dist/config/settings.js +127 -0
  19. package/dist/config/state.js +70 -0
  20. package/dist/errors.js +154 -0
  21. package/dist/features/asset-selection/index.js +212 -0
  22. package/dist/features/asset-selection/types.js +1 -0
  23. package/dist/features/auth/credentials.js +62 -0
  24. package/dist/features/auth/session.js +120 -0
  25. package/dist/features/auth/transport.js +44 -0
  26. package/dist/features/capabilities/index.js +106 -0
  27. package/dist/features/catalog/index.js +102 -0
  28. package/dist/features/collaboration/domain.js +90 -0
  29. package/dist/features/collaboration/index.js +254 -0
  30. package/dist/features/collaboration/remote.js +121 -0
  31. package/dist/features/collaboration/workspace-git.js +362 -0
  32. package/dist/features/collaboration/workspace-github.js +130 -0
  33. package/dist/features/collaboration/workspace-store.js +256 -0
  34. package/dist/features/collaboration/workspace.js +391 -0
  35. package/dist/features/discovery/index.js +66 -0
  36. package/dist/features/doctor/index.js +154 -0
  37. package/dist/features/environment/auto-sync.js +96 -0
  38. package/dist/features/environment/cloud-source.js +27 -0
  39. package/dist/features/environment/installed.js +124 -0
  40. package/dist/features/environment/names.js +153 -0
  41. package/dist/features/environment/operations.js +277 -0
  42. package/dist/features/environment/packages.js +120 -0
  43. package/dist/features/environment/remote.js +71 -0
  44. package/dist/features/environment/source.js +1 -0
  45. package/dist/features/environment/sync.js +547 -0
  46. package/dist/features/environment/transaction.js +284 -0
  47. package/dist/features/environment/workspace-source.js +19 -0
  48. package/dist/features/git-hosts/index.js +148 -0
  49. package/dist/features/git-workspace/assets.js +71 -0
  50. package/dist/features/git-workspace/format.js +310 -0
  51. package/dist/features/git-workspace/git.js +135 -0
  52. package/dist/features/git-workspace/migrate.js +188 -0
  53. package/dist/features/git-workspace/move.js +337 -0
  54. package/dist/features/git-workspace/overlay.js +131 -0
  55. package/dist/features/git-workspace/publish.js +172 -0
  56. package/dist/features/git-workspace/setup.js +135 -0
  57. package/dist/features/git-workspace/snapshot.js +105 -0
  58. package/dist/features/git-workspace/source.js +159 -0
  59. package/dist/features/git-workspace/startup.js +16 -0
  60. package/dist/features/hooks/adapt.js +103 -0
  61. package/dist/features/hooks/divergence.js +38 -0
  62. package/dist/features/hooks/test.js +114 -0
  63. package/dist/features/imports/discover.js +249 -0
  64. package/dist/features/imports/folder.js +52 -0
  65. package/dist/features/imports/local.js +242 -0
  66. package/dist/features/imports/mcp.js +219 -0
  67. package/dist/features/imports/remote.js +85 -0
  68. package/dist/features/inspection/index.js +42 -0
  69. package/dist/features/inventory/index.js +224 -0
  70. package/dist/features/knowledge/index.js +118 -0
  71. package/dist/features/knowledge/startup.js +25 -0
  72. package/dist/features/mcps/index.js +102 -0
  73. package/dist/features/native/adapters.js +143 -0
  74. package/dist/features/native/configuration.js +196 -0
  75. package/dist/features/native/mcp-launch.js +57 -0
  76. package/dist/features/onboarding/environment.js +160 -0
  77. package/dist/features/onboarding/setup.js +123 -0
  78. package/dist/features/repositories/context.js +55 -0
  79. package/dist/features/skills/install.js +25 -0
  80. package/dist/features/skills/remote.js +177 -0
  81. package/dist/features/skills/sync.js +121 -0
  82. package/dist/features/skills/validation.js +34 -0
  83. package/dist/harnesses/claude.js +57 -0
  84. package/dist/harnesses/codex.js +46 -0
  85. package/dist/harnesses/cursor.js +44 -0
  86. package/dist/harnesses/detect.js +61 -0
  87. package/dist/harnesses/registry.js +16 -0
  88. package/dist/harnesses/types.js +1 -0
  89. package/dist/program.js +272 -0
  90. package/dist/ui/add-asset.js +440 -0
  91. package/dist/ui/asset-list.js +50 -0
  92. package/dist/ui/assets.js +142 -0
  93. package/dist/ui/auth.js +138 -0
  94. package/dist/ui/clash.js +43 -0
  95. package/dist/ui/collaboration.js +142 -0
  96. package/dist/ui/connection.js +102 -0
  97. package/dist/ui/environment-onboarding.js +125 -0
  98. package/dist/ui/format.js +154 -0
  99. package/dist/ui/hook-compatibility.js +33 -0
  100. package/dist/ui/mcp.js +40 -0
  101. package/dist/ui/move.js +22 -0
  102. package/dist/ui/onboarding.js +293 -0
  103. package/dist/ui/output.js +155 -0
  104. package/dist/ui/pick.js +153 -0
  105. package/dist/ui/scope-install.js +47 -0
  106. package/dist/ui/selection.js +51 -0
  107. package/dist/ui/theme.js +37 -0
  108. package/dist/version.js +12 -0
  109. package/package.json +73 -4
@@ -0,0 +1,203 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { styleText } from "node:util";
3
+ import { renderCollaboration } from "../ui/collaboration.js";
4
+ import { folderDivergence, nearestHookFolder, } from "../features/hooks/divergence.js";
5
+ import { resolve } from "node:path";
6
+ import { CliError, friendlyHint, friendlyMessage } from "../errors.js";
7
+ import { ApiError } from "@barndog-ai/api-contract";
8
+ import { pickOne } from "../ui/pick.js";
9
+ import { resolveOrigin } from "./origin.js";
10
+ import { clean, json, ORIGIN_HELP, originLabel, warn } from "../ui/format.js";
11
+ function positive(value) {
12
+ if (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(Number(value)))
13
+ throw new InvalidArgumentError("Expected a positive integer");
14
+ return Number(value);
15
+ }
16
+ /** Skill and Hook changes are separate lists; point at the other when an ID isn't here. */
17
+ function reviewError(error, kind, options) {
18
+ if (!(error instanceof ApiError))
19
+ return error;
20
+ if (error.status === 404 && options.id && !options.thread)
21
+ return new CliError(`No ${kind === "skill" ? "Skill" : "Hook"} Suggested Change has that ID.`, `barndog ${kind === "skill" ? "hooks changes" : "changes"} show ${options.id}`, { cause: error });
22
+ const hint = friendlyHint(error);
23
+ return kind === "hook" && hint
24
+ ? new CliError(friendlyMessage(error), hint.replace(/^barndog changes/, "barndog hooks changes"), { cause: error })
25
+ : error;
26
+ }
27
+ export function registerCollaboration(program, context, kind = "skill") {
28
+ const run = async (action, options = {}) => {
29
+ const result = await context
30
+ .collaborate(action, kind === "hook" ? { ...options, kind } : options)
31
+ .catch((error) => {
32
+ throw reviewError(error, kind, options);
33
+ });
34
+ if (context.mode.json) {
35
+ context.write(json(result));
36
+ return;
37
+ }
38
+ for (const line of renderCollaboration(action, result))
39
+ context.write(line);
40
+ if (kind !== "hook" || (action !== "pull-skill" && action !== "push"))
41
+ return;
42
+ // Editing is when tools drifting apart matters, so say it at both ends.
43
+ const pulled = action === "pull-skill"
44
+ ? (result?.root ??
45
+ resolve(options.directory ?? options.name ?? "."))
46
+ : nearestHookFolder(process.cwd());
47
+ const warning = pulled && (await folderDivergence(pulled));
48
+ if (warning)
49
+ context.write(`${warn("!")} ${warning}`);
50
+ };
51
+ const skills = program.commands.find((c) => c.name() === (kind === "hook" ? "hooks" : "skills"));
52
+ const noun = kind === "skill" ? "Skill" : "Hook";
53
+ const group = kind === "skill" ? "skills" : "hooks";
54
+ /** Fills a missing name and origin from a searchable catalog list. */
55
+ const choose = async (name, origin, usage) => {
56
+ if (name)
57
+ return {
58
+ name,
59
+ origin: await resolveOrigin(context, kind, name, origin, usage.replace("<name>", name)),
60
+ };
61
+ if (!context.mode.interactive)
62
+ throw new CliError(`Name the ${noun} to use.`, usage);
63
+ const rows = await context.searchCatalog(kind);
64
+ const row = await pickOne(`Choose a ${noun}`, rows.map((row) => ({
65
+ value: row,
66
+ name: row.name,
67
+ hint: `${originLabel(row.origin)} · ${clean(row.version.description)}`,
68
+ })), { empty: `No ${noun}s are published yet.` });
69
+ return { name: row.name, origin: originLabel(row.origin) };
70
+ };
71
+ skills
72
+ .command("pull [name]")
73
+ .option("--origin <origin>", ORIGIN_HELP)
74
+ .option("--directory <path>", "Folder for the editable copy")
75
+ .description(`Download a ${noun} into an editable folder to change and propose edits`)
76
+ .action(async (name, options) => run("pull-skill", {
77
+ ...options,
78
+ ...(await choose(name, options.origin, `barndog ${group} pull <name>`)),
79
+ }));
80
+ if (kind === "skill") {
81
+ for (const [command, description] of [
82
+ [
83
+ "pull",
84
+ "Bring the latest published version into this working copy, keeping your edits",
85
+ ],
86
+ [
87
+ "diff",
88
+ "Show your edits in this working copy (elsewhere: preview what sync would change)",
89
+ ],
90
+ ])
91
+ program
92
+ .command(command)
93
+ .description(description)
94
+ .action(() => run(command));
95
+ program
96
+ .command("push")
97
+ .description("Propose this working copy's edits as a Suggested Change")
98
+ .option("--origin <origin>", "Origin for a new local Skill")
99
+ .option("--publish", "Publish directly with admin or personal-owner authority")
100
+ .option("--new", "Start a new proposal instead of updating the linked proposal")
101
+ .option("--title <title>", "Suggested Change title")
102
+ .action((options) => run("push", options));
103
+ program
104
+ .command("resolve <path>")
105
+ .description("Mark a conflicted file in this working copy as resolved")
106
+ .action((path) => run("resolve", { path }));
107
+ }
108
+ for (const [name, action, description] of [
109
+ [
110
+ "versions",
111
+ "versions",
112
+ `List ${noun === "Skill" ? "a Skill's" : "a Hook's"} published versions`,
113
+ ],
114
+ ["show", "version-show", "Print the files of a published version"],
115
+ ["diff", "version-diff", "Compare two published versions"],
116
+ ]) {
117
+ const command = skills
118
+ .command(`${name} [name]`)
119
+ .description(description)
120
+ .option("--origin <origin>", ORIGIN_HELP);
121
+ if (name === "show")
122
+ command.option("--version <number>", "Published version", positive);
123
+ if (name === "diff")
124
+ command
125
+ .requiredOption("--from <number>", "Old version", positive)
126
+ .requiredOption("--to <number>", "New version", positive);
127
+ command.action(async (asset, options) => run(action, {
128
+ ...options,
129
+ ...(await choose(asset, options.origin, `barndog ${group} ${name} <name>`)),
130
+ }));
131
+ }
132
+ skills
133
+ .command("push [name]")
134
+ .description("Propose this working copy's edits as a Suggested Change")
135
+ .option("--origin <origin>", "Scope for a new package, such as team/engineering")
136
+ .option("--publish", "Publish with direct authority")
137
+ .option("--new", "Start a new proposal")
138
+ .option("--title <title>", "Proposal title")
139
+ .action((name, options) => run("push", { ...options, name }));
140
+ skills
141
+ .command("create <name>")
142
+ .requiredOption("--origin <origin>", ORIGIN_HELP)
143
+ .option("--directory <path>", "New editable folder")
144
+ .description(`Start a new ${noun} in an editable folder (not installed until published)`)
145
+ .action((name, options) => run("create", { ...options, name }));
146
+ for (const parent of kind === "hook" ? [skills] : [program, skills])
147
+ registerChanges(parent, run);
148
+ }
149
+ function registerChanges(parent, run) {
150
+ const changes = parent
151
+ .command("changes")
152
+ .description("Review, discuss and merge Suggested Changes");
153
+ changes
154
+ .command("list")
155
+ .description("List accessible Suggested Changes")
156
+ .action(() => run("list"));
157
+ changes
158
+ .command("show <id>")
159
+ .description("Read proposal content, reviews, and discussion history")
160
+ .action((id) => run("show", { id }));
161
+ changes
162
+ .command("diff <id>")
163
+ .description("Inspect a proposal diff")
164
+ .option("--revision <number>", "Proposal revision", positive)
165
+ .option("--from-revision <number>", "Compare to another proposal revision", positive)
166
+ .action((id, options) => run("change-diff", { ...options, id }));
167
+ for (const [name, description] of [
168
+ ["approve", "Approve a reviewed revision"],
169
+ ["request-changes", "Request further changes"],
170
+ ["reject", "Close a proposal as its author or admin"],
171
+ ["merge", "Publish a proposal under its scope's merge rules"],
172
+ ])
173
+ changes
174
+ .command(`${name} <id>`)
175
+ .description(description)
176
+ .requiredOption("--revision <number>", "Revision you reviewed", positive)
177
+ .action((id, options) => run(name, { ...options, id }));
178
+ changes
179
+ .command("comment <id>")
180
+ .description("Comment, reply, or suggest an inline replacement")
181
+ .requiredOption("--revision <number>", "Proposal revision", positive)
182
+ .option("--body <text>", "Comment text")
183
+ .option("--body-file <path>", "Read comment text from a file")
184
+ .option("--thread <id>", "Reply to a discussion")
185
+ .option("--path <path>", "Package file for an inline discussion")
186
+ .option("--side <side>", "old or new")
187
+ .option("--start-line <number>", "First line", positive)
188
+ .option("--end-line <number>", "Last line", positive)
189
+ .option("--replacement-file <path>", "Replacement text file")
190
+ .option("--expected-file <path>", "Exact original text file")
191
+ .action((id, options) => run("comment", { ...options, id }));
192
+ for (const [name, description] of [
193
+ ["apply", "Apply a current reviewer suggestion"],
194
+ ["resolve-discussion", "Resolve a discussion"],
195
+ ["reopen-discussion", "Reopen a discussion"],
196
+ ])
197
+ changes
198
+ .command(`${name} <id> <thread>`)
199
+ .description(description)
200
+ .requiredOption("--revision <number>", "Current proposal revision", positive)
201
+ .action((id, thread, options) => run(name, { ...options, id, thread }));
202
+ changes.addHelpText("after", `\nReview ${styleText("bold", "barndog changes diff <id>")} before approving a revision. Approval does not publish; use ${styleText("bold", "barndog changes merge <id> --revision <number>")}.`);
203
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,416 @@
1
+ import { LOCAL_ORIGIN } from "../features/git-workspace/overlay.js";
2
+ import { renderMove } from "../ui/move.js";
3
+ import input from "@inquirer/input";
4
+ import { Option } from "commander";
5
+ import { z } from "zod";
6
+ import { prefixedName } from "../features/environment/names.js";
7
+ import { CliError, friendlyMessage } from "../errors.js";
8
+ import { assetListOptions, pageOptions, filterAssets, } from "../ui/asset-list.js";
9
+ import { assetListing, inventoryHints, kindLabels, renderCatalog, renderInventory, } from "../ui/assets.js";
10
+ import { runSetInstall } from "../ui/scope-install.js";
11
+ import { runSelection } from "../ui/selection.js";
12
+ import { pickMany, pickOne } from "../ui/pick.js";
13
+ import { promptTheme } from "../ui/theme.js";
14
+ import { bold, clean, dim, hint, json, ok, ORIGIN_HELP, originLabel, section, table, } from "../ui/format.js";
15
+ export { runSelection } from "../ui/selection.js";
16
+ /** Asks for a value in a terminal, or explains the flag to pass. */
17
+ export async function ask(context, value, message, flag, fallback) {
18
+ if (value)
19
+ return value;
20
+ if (!context.mode.interactive)
21
+ throw new CliError(`Add ${flag} <value> to this command, or run it in a terminal to be asked.`);
22
+ return (await input({ message, default: fallback, theme: promptTheme })).trim();
23
+ }
24
+ function requireArguments(context, usage) {
25
+ if (!context.mode.interactive)
26
+ throw new CliError("Name the asset to act on, or run this in a terminal to choose from a list.", usage);
27
+ }
28
+ /** Installed assets eligible for an action on this machine. */
29
+ function localCandidates(items, kind, action) {
30
+ return items.filter((item) => item.kind === kind &&
31
+ !item.via.includes("config") &&
32
+ item.origin !== "—" &&
33
+ (action === "enable"
34
+ ? item.state === "disabled"
35
+ : action === "disable"
36
+ ? item.state !== "disabled"
37
+ : true));
38
+ }
39
+ const localChoice = (item) => ({
40
+ value: item,
41
+ name: item.installedName,
42
+ hint: `${item.origin} · ${item.state}`,
43
+ });
44
+ export function registerEnvironment(program, context) {
45
+ for (const kind of ["skill", "mcp", "hook"]) {
46
+ const labels = kindLabels[kind];
47
+ const group = labels.group;
48
+ const addCommand = `barndog ${group} add${kind === "mcp" ? "" : kind === "skill" ? " <source>" : " <url>"}`;
49
+ const command = program
50
+ .command(group)
51
+ .description(kind === "skill"
52
+ ? "Install, browse and manage Skills"
53
+ : kind === "mcp"
54
+ ? "Install, browse and manage MCP servers"
55
+ : "Install, browse and manage Hooks");
56
+ const listCommand = command
57
+ .command("list")
58
+ .description(`List installed, disabled and available ${labels.many}`);
59
+ pageOptions(listCommand)
60
+ .option("--installed", `Only ${labels.many} installed on this machine`)
61
+ .option("--disabled", `Only ${labels.many} you've disabled`)
62
+ .option("--available", `Only ${labels.many} you can install`)
63
+ .option("--paths", "Show installed folders and configuration files")
64
+ .action(async (options) => {
65
+ const narrowed = options.installed || options.disabled;
66
+ const onlyAvailable = options.available && !narrowed;
67
+ let catalogProblem;
68
+ const [inventory, rows] = await Promise.all([
69
+ context.inventory(),
70
+ options.available || !narrowed
71
+ ? context.searchCatalog(kind).catch((error) => {
72
+ if (onlyAvailable)
73
+ throw error;
74
+ catalogProblem = friendlyMessage(error);
75
+ return [];
76
+ })
77
+ : [],
78
+ ]);
79
+ const items = inventory.items.filter((item) => item.kind === kind);
80
+ const listing = assetListing(items, rows, options);
81
+ if (context.mode.json)
82
+ return context.write(json(listing));
83
+ if (inventory.offline)
84
+ context.write(dim(`Showing local state only: ${inventory.offline}`));
85
+ else if (catalogProblem)
86
+ context.write(dim(`Couldn't load available ${labels.many}: ${catalogProblem}`));
87
+ if (!listing.length) {
88
+ if (narrowed) {
89
+ context.write(`No ${labels.many} match that filter.`);
90
+ return;
91
+ }
92
+ if (catalogProblem || inventory.offline) {
93
+ context.write(`No ${labels.many} on this machine yet.`);
94
+ return;
95
+ }
96
+ context.write(`No ${labels.many} yet.`);
97
+ context.write(hint(addCommand, "Next"));
98
+ return;
99
+ }
100
+ const start = (options.page - 1) * options.limit;
101
+ const page = listing.slice(start, start + options.limit);
102
+ if (!page.length) {
103
+ context.write(`Page ${options.page} is empty. Choose a page from 1 to ${Math.ceil(listing.length / options.limit)}.`);
104
+ return;
105
+ }
106
+ for (const line of renderInventory(page, options))
107
+ context.write(line);
108
+ if (listing.length > options.limit) {
109
+ const flags = ["installed", "disabled", "available"]
110
+ .filter((flag) => options[flag])
111
+ .map((flag) => ` --${flag}`)
112
+ .join("");
113
+ context.write("\n" +
114
+ dim(`Showing ${start + 1}–${start + page.length} of ${listing.length}`));
115
+ if (start + page.length < listing.length)
116
+ context.write(hint(`barndog ${group} list${flags} --page ${options.page + 1}`, "Next"));
117
+ }
118
+ const onThisMachine = page.filter((item) => item.state !== "available");
119
+ const hints = inventoryHints(onThisMachine);
120
+ if (hints.length)
121
+ context.write(["", ...hints].join("\n"));
122
+ else if (!options.paths && onThisMachine.length)
123
+ context.write("\n" +
124
+ hint(`barndog ${group} list --paths`, "Tip") +
125
+ dim(" to see where each one lives"));
126
+ });
127
+ const search = async (assetKind, query, options) => {
128
+ const [rows, inventory] = await Promise.all([
129
+ context.searchCatalog(assetKind),
130
+ context.inventory().catch(() => undefined),
131
+ ]);
132
+ const selected = new Set(inventory?.items
133
+ .filter((item) => item.state !== "removing")
134
+ .map((item) => item.id) ?? []);
135
+ // JSON gets the same matches the table shows, all pages at once.
136
+ if (context.mode.json)
137
+ return context.write(json(filterAssets(rows, { ...options, search: query }).map((row) => ({
138
+ ...row,
139
+ selected: selected.has(row.id),
140
+ }))));
141
+ for (const line of renderCatalog(rows, { ...options, search: query }, `barndog ${group} search`, selected))
142
+ context.write(line);
143
+ };
144
+ assetListOptions(command
145
+ .command("search [query]")
146
+ .description(`Browse ${labels.many} published in your workspace`), false).action((query, options) => search(kind, query ?? options.search, options));
147
+ command
148
+ .command("install [name]")
149
+ .description(`Install ${labels.many} on this machine; choose from a list when no name is given`)
150
+ .option("--origin <origin>", ORIGIN_HELP)
151
+ .addOption(new Option("--overrides <choice>", "Keep or clear your existing exclusions").choices(["preserve", "clear"]))
152
+ .option("--decisions <file>", "JSON per-asset override choices")
153
+ .action(async (name, options) => {
154
+ if (name)
155
+ return runSelection(context, "install", { ...options, name, kind });
156
+ requireArguments(context, `barndog ${group} install <name> --origin <origin>`);
157
+ const [rows, inventory] = await Promise.all([
158
+ context.searchCatalog(kind),
159
+ context.inventory(),
160
+ ]);
161
+ const selected = new Set(inventory.items
162
+ .filter((item) => item.state !== "removing")
163
+ .map((item) => item.id));
164
+ const inOrigin = rows.filter((row) => !options.origin ||
165
+ originLabel(row.origin) === options.origin.replace(":", "/"));
166
+ const ids = await pickMany(`Choose ${labels.many} to install`, inOrigin
167
+ .filter((row) => !selected.has(row.id))
168
+ .sort((a, b) => a.name.localeCompare(b.name))
169
+ .map((row) => ({
170
+ value: row.id,
171
+ name: row.name,
172
+ hint: `${originLabel(row.origin)} · ${clean(row.version.description)}`,
173
+ })), {
174
+ empty: inOrigin.length
175
+ ? `Every available ${labels.one} is already on this machine.`
176
+ : `No ${labels.many} available to install. Add one with ${addCommand}.`,
177
+ });
178
+ await runSelection(context, "install", {
179
+ kind,
180
+ ids,
181
+ overrides: options.overrides,
182
+ decisions: options.decisions,
183
+ });
184
+ });
185
+ for (const action of ["remove", "enable", "disable"])
186
+ command
187
+ .command(`${action} [name]`)
188
+ .description(action === "remove"
189
+ ? `Remove ${labels.many} from this machine, even when a set includes them`
190
+ : action === "enable"
191
+ ? `Turn disabled ${labels.many} back on`
192
+ : `Turn ${labels.many} off without removing them from your selection`)
193
+ .option("--origin <origin>", ORIGIN_HELP)
194
+ .action(async (name, options) => {
195
+ if (name)
196
+ return runSelection(context, action, { ...options, name, kind });
197
+ requireArguments(context, `barndog ${group} ${action} <name>`);
198
+ const items = localCandidates((await context.inventory()).items, kind, action);
199
+ const chosen = await pickMany(`Choose ${labels.many} to ${action}`, items.map(localChoice), {
200
+ empty: action === "enable"
201
+ ? `No ${labels.many} are disabled.`
202
+ : `No ${labels.many} to ${action} on this machine.`,
203
+ });
204
+ await runSelection(context, action, {
205
+ kind,
206
+ ids: chosen.map((item) => item.id),
207
+ });
208
+ });
209
+ command
210
+ .command("rename [name]")
211
+ .description(`Install ${labels.a} under a different local name`)
212
+ .option("--origin <origin>", ORIGIN_HELP)
213
+ .option("--as <name>", "New local name: lowercase letters, numbers and hyphens")
214
+ .option("--reset", "Go back to the published name")
215
+ .action(async (name, options) => {
216
+ let target = name;
217
+ let suggestion;
218
+ if (!target) {
219
+ requireArguments(context, `barndog ${group} rename <name> --as <new-name>`);
220
+ const item = await pickOne(`Choose ${labels.a} to rename`, localCandidates((await context.inventory()).items, kind, "rename").map(localChoice), { empty: `No ${labels.many} to rename on this machine.` });
221
+ target = item.id;
222
+ const [type, slug] = item.origin.split("/");
223
+ suggestion = prefixedName({
224
+ name: item.name,
225
+ origin: { type: type, slug: slug ?? "" },
226
+ });
227
+ }
228
+ const as = options.reset
229
+ ? undefined
230
+ : await ask(context, options.as, "New local name", "--as", suggestion);
231
+ await runSelection(context, "rename", {
232
+ kind,
233
+ name: target,
234
+ origin: options.origin,
235
+ as,
236
+ reset: options.reset,
237
+ });
238
+ // A clash prompt during the sync may have chosen a different name.
239
+ const item = (await context.inventory()).items.find((entry) => entry.kind === kind &&
240
+ [entry.id, entry.name, entry.installedName].includes(target) &&
241
+ (!options.origin || entry.origin === options.origin));
242
+ if (item && !context.mode.json)
243
+ context.write(item.installedName === item.name
244
+ ? `${ok("✔")} ${bold(item.name)} uses its published name.`
245
+ : `${ok("✔")} ${bold(item.name)} from ${item.origin} is installed as ${bold(item.installedName)}.`);
246
+ });
247
+ for (const action of ["fork", "promote"])
248
+ command
249
+ .command(`${action} [name]`)
250
+ .description(action === "fork"
251
+ ? `Copy ${labels.a} into a scope you own, such as your personal space`
252
+ : `Propose ${labels.a} for a team, repository or the organization`)
253
+ .option("--origin <origin>", ORIGIN_HELP)
254
+ .option("--target <origin>", "Destination scope, such as me, team/engineering or org")
255
+ .option("--name <newName>", "Name of the new asset")
256
+ .option("--key <key>", "Stable key for exact retries")
257
+ .action(async (name, options) => {
258
+ let origin = options.origin;
259
+ if (!name) {
260
+ requireArguments(context, `barndog ${group} ${action} <name> --origin <origin> --target <origin> --name <new-name>`);
261
+ const row = await pickOne(`Choose ${labels.a} to ${action}`, (await context.searchCatalog(kind)).map((row) => ({
262
+ value: row,
263
+ name: row.name,
264
+ hint: `${originLabel(row.origin)} · ${clean(row.version.description)}`,
265
+ })));
266
+ name = row.name;
267
+ origin = originLabel(row.origin);
268
+ }
269
+ origin = await ask(context, origin, "Current scope", "--origin");
270
+ const target = await ask(context, options.target, "Destination scope (me, team/<slug>, repo/<slug> or org)", "--target", action === "fork" ? "me" : undefined);
271
+ const newName = await ask(context, options.name, "New name", "--name", name);
272
+ const outcome = await context.capability(action, {
273
+ kind,
274
+ name,
275
+ origin,
276
+ target,
277
+ newName,
278
+ key: options.key,
279
+ });
280
+ if (origin === LOCAL_ORIGIN) {
281
+ if (context.mode.json)
282
+ return context.write(json(outcome));
283
+ for (const line of renderMove(outcome))
284
+ context.write(line);
285
+ return;
286
+ }
287
+ const result = z
288
+ .object({
289
+ kind: z.string(),
290
+ id: z.string(),
291
+ changeId: z.string().optional(),
292
+ })
293
+ .parse(outcome);
294
+ if (context.mode.json)
295
+ return context.write(json(result));
296
+ context.write(result.changeId
297
+ ? `${ok("✔")} Proposed ${bold(newName)} for ${target}. A reviewer must merge the Suggested Change.`
298
+ : `${ok("✔")} Created ${bold(newName)} in ${target}.`);
299
+ context.write(result.changeId
300
+ ? hint(`barndog changes show ${result.changeId}`)
301
+ : hint(`barndog ${group} install ${newName} --origin ${target === "me" ? "me" : target}`));
302
+ });
303
+ }
304
+ registerSets(program, context);
305
+ }
306
+ function registerSets(program, context) {
307
+ const sets = program
308
+ .command("sets")
309
+ .description("Subscribe to everything a team, repository or the organization shares");
310
+ const load = async () => (await context.environment("sets-list", {}));
311
+ const label = (scope) => originLabel(scope);
312
+ assetListOptions(sets
313
+ .command("list")
314
+ .description("Show your subscriptions and the scopes you can subscribe to")).action(async (options) => {
315
+ const result = await load();
316
+ if (context.mode.json)
317
+ return context.write(json(result));
318
+ const subscribed = result.subscriptions.map((subscription) => ({
319
+ subscription,
320
+ scope: result.available.find((s) => s.id === subscription.scope.id && s.type === subscription.scope.type),
321
+ }));
322
+ context.write(`${section("Subscribed")} ${dim(`(${subscribed.length})`)}`);
323
+ context.write(subscribed.length
324
+ ? table(subscribed.map(({ subscription, scope }) => [
325
+ bold(scope
326
+ ? label(scope)
327
+ : `${subscription.scope.type}/${subscription.scope.id}`),
328
+ scope?.name ?? dim("unavailable"),
329
+ subscription.mode,
330
+ subscription.enabled ? ok("enabled") : dim("disabled"),
331
+ ]), { header: ["Scope", "Name", "Mode", "State"] }).join("\n")
332
+ : dim(" None yet."));
333
+ const terms = options.search?.toLowerCase().split(/\s+/).filter(Boolean) ?? [];
334
+ const available = result.available
335
+ .filter((scope) => !result.subscriptions.some((s) => s.scope.id === scope.id && s.scope.type === scope.type))
336
+ .filter((scope) => (!options.origin ||
337
+ scope.type === options.origin ||
338
+ label(scope) === options.origin.replace(":", "/")) &&
339
+ terms.every((term) => `${label(scope)} ${scope.name ?? ""}`.toLowerCase().includes(term)))
340
+ .sort((a, b) => label(a).localeCompare(label(b)));
341
+ const start = (options.page - 1) * options.limit;
342
+ const page = available.slice(start, start + options.limit);
343
+ context.write("");
344
+ context.write(`${section("Available")} ${dim(`(${available.length})`)}`);
345
+ context.write(page.length
346
+ ? table(page.map((scope) => [bold(label(scope)), scope.name ?? ""]), { header: ["Scope", "Name"] }).join("\n")
347
+ : dim(" Nothing else to subscribe to."));
348
+ if (start + options.limit < available.length)
349
+ context.write(hint(`barndog sets list --page ${options.page + 1}`));
350
+ context.write("");
351
+ context.write(hint("barndog sets install", "Tip") + dim(" to subscribe"));
352
+ });
353
+ const chooseScope = async (message, filter, empty) => {
354
+ const result = await load();
355
+ return pickOne(message, result.available
356
+ .filter((scope) => filter(scope, result.subscriptions.some((s) => s.scope.id === scope.id && s.scope.type === scope.type)))
357
+ .sort((a, b) => label(a).localeCompare(label(b)))
358
+ .map((scope) => ({
359
+ value: label(scope),
360
+ name: label(scope),
361
+ hint: scope.name,
362
+ })), { empty });
363
+ };
364
+ for (const action of ["install", "remove", "enable", "disable"]) {
365
+ const command = sets
366
+ .command(`${action} [scope]`)
367
+ .description(action === "install"
368
+ ? "Subscribe to a scope's shared assets"
369
+ : action === "remove"
370
+ ? "Unsubscribe from a scope"
371
+ : action === "enable"
372
+ ? "Turn a paused subscription back on"
373
+ : "Pause a subscription without removing it")
374
+ .option("--origin <origin>", "Scope, such as org, team/engineering or repo/web-app");
375
+ if (action === "install")
376
+ command
377
+ .addOption(new Option("--mode <mode>", "Which assets to include; asks when omitted").choices(["recommended", "optional", "all"]))
378
+ .addOption(new Option("--overrides <choice>", "Keep or clear your existing exclusions").choices(["preserve", "clear"]))
379
+ .option("--decisions <file>", "JSON per-asset override choices");
380
+ command.action(async (scope, options) => {
381
+ let origin = scope ?? options.origin;
382
+ if (!origin) {
383
+ requireArguments(context, `barndog sets ${action} <scope>`);
384
+ origin = await chooseScope(action === "install"
385
+ ? "Choose a scope to subscribe to"
386
+ : `Choose a subscription to ${action}`, (_, subscribed) => (action === "install" ? !subscribed : subscribed), action === "install"
387
+ ? "You're already subscribed to every scope."
388
+ : "You have no subscriptions yet.");
389
+ }
390
+ return action === "install"
391
+ ? runSetInstall(context, { ...options, origin })
392
+ : runSelection(context, `sets-${action}`, { ...options, origin });
393
+ });
394
+ }
395
+ const switchCommand = (name, hidden) => sets
396
+ .command(`${name} [scope]`, { hidden })
397
+ .description("Switch to another team or repository, replacing your current one of that type")
398
+ .addOption(new Option("--mode <mode>", "Which assets to include")
399
+ .choices(["recommended", "optional", "all"])
400
+ .default("recommended"))
401
+ .addOption(new Option("--overrides <choice>", "Keep or clear your existing exclusions").choices(["preserve", "clear"]))
402
+ .option("--decisions <file>", "JSON per-asset override choices")
403
+ .action(async (scope, options) => {
404
+ let origin = scope && name === "switch-team" && !scope.includes("/")
405
+ ? `team/${scope}`
406
+ : scope;
407
+ if (!origin) {
408
+ requireArguments(context, "barndog sets switch <team/slug|repo/slug>");
409
+ origin = await chooseScope("Switch to", (candidate, subscribed) => !subscribed &&
410
+ (candidate.type === "team" || candidate.type === "repo"), "There is no other team or repository to switch to.");
411
+ }
412
+ await runSelection(context, "switch", { ...options, origin });
413
+ });
414
+ switchCommand("switch", false);
415
+ switchCommand("switch-team", true);
416
+ }
@@ -0,0 +1,20 @@
1
+ export function registerInit(program, context) {
2
+ program
3
+ .command("init")
4
+ .description("Set up this machine: connect, choose coding tools and shared assets")
5
+ .option("--server <url>", "Connect to a BarnDog server")
6
+ .option("--local", "Keep assets in a folder on this machine")
7
+ .option("--repo <url>", "Share assets through one Git repository")
8
+ .option("--no-browser", "Display the sign-in URL without opening it")
9
+ .action(async (options) => {
10
+ if (options.local && options.server)
11
+ program.error("--local cannot be combined with --server");
12
+ if (options.repo && (options.local || options.server))
13
+ program.error("--repo cannot be combined with --local or --server");
14
+ await context.setup(true, options.server, {
15
+ local: options.local,
16
+ browser: options.browser,
17
+ ...(options.repo ? { repo: options.repo } : {}),
18
+ });
19
+ });
20
+ }