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
@@ -1,148 +0,0 @@
1
- import { homedir } from "node:os";
2
- import { readFile } from "node:fs/promises";
3
- import { resolve } from "node:path";
4
- import { spawn } from "node:child_process";
5
- import { randomUUID } from "node:crypto";
6
- import { z } from "zod";
7
- import { gitCopyImportSchema, gitCopyImportResultSchema, gitCreateRepositorySchema, githubStatusSchema, gitRemoteHeadSchema, gitAuthorizationSchema, gitInstallationSchema, gitConnectionSchema, gitConnectSchema, gitImportSchema, gitMirrorResolutionSchema, gitPullSchema, gitPullDetailsSchema, gitProposalSchema, gitRevisionSchema, gitReviewSchema, gitCommentSchema, gitMergeSchema, okSchema, } from "@barndog-ai/api-contract";
8
- import { readDirectory } from "@barndog-ai/api-contract/collaboration";
9
- import { connection, selectOrigin } from "../collaboration/remote.js";
10
- import { request, selectAsset } from "../environment/remote.js";
11
- export async function gitOperation(action, options = {}, home = homedir()) {
12
- const conn = await connection(home), key = options.key ?? randomUUID();
13
- if (action === "status")
14
- return request(conn, "/v1/github/status", githubStatusSchema, home);
15
- if (action === "remote-head")
16
- return request(conn, `/v1/git-connections/${z.uuidv4().parse(options.id)}/remote-head`, gitRemoteHeadSchema, home);
17
- if (action === "auth" || action === "install") {
18
- const result = await request(conn, action === "auth" ? "/v1/github/authorize" : "/v1/github/install", gitAuthorizationSchema, home, "POST");
19
- if (options.browser !== false) {
20
- const command = process.platform === "darwin"
21
- ? "open"
22
- : process.platform === "win32"
23
- ? "rundll32"
24
- : "xdg-open";
25
- const child = spawn(command, process.platform === "win32"
26
- ? ["url.dll,FileProtocolHandler", result.url]
27
- : [result.url], { stdio: "ignore" });
28
- child.once("error", () => undefined);
29
- child.unref();
30
- }
31
- return {
32
- message: `Complete GitHub ${action === "auth" ? "authorization" : "App installation"} in your browser: ${result.url}`,
33
- };
34
- }
35
- if (action === "installations")
36
- return request(conn, "/v1/github/installations", z.array(gitInstallationSchema), home);
37
- if (action === "list")
38
- return request(conn, "/v1/git-connections", z.array(gitConnectionSchema), home);
39
- if (action === "connect" ||
40
- action === "import" ||
41
- action === "create-repository") {
42
- const parts = options.repository?.split("/");
43
- if (!parts || parts.length !== 2 || parts.some((p) => !p))
44
- throw new Error("Use --repository <owner/name>");
45
- const common = {
46
- kind: options.kind ?? "skill",
47
- installationId: options.installation,
48
- owner: parts[0],
49
- repository: parts[1],
50
- };
51
- if (action === "create-repository") {
52
- if (!options.key)
53
- throw new Error("Use --key <key> and retain it for exact retries");
54
- const selected = await selectAsset(common.kind, options.name, options.origin, home);
55
- return request(conn, "/v1/git-connections/create-repository", gitConnectionSchema, home, "POST", gitCreateRepositorySchema.parse({
56
- ...common,
57
- assetId: selected.reference.id,
58
- expectedVersionId: options.expectedVersion ?? selected.asset.version.id,
59
- mode: options.mode ?? "mirror",
60
- visibility: options.visibility ?? "private",
61
- idempotencyKey: options.key,
62
- }));
63
- }
64
- if (action === "import") {
65
- const origin = await selectOrigin(options.origin, conn, home);
66
- if (options.authority === "barndog") {
67
- if (!options.key)
68
- throw new Error("Use --key <key> and retain it for exact retries");
69
- return request(conn, "/v1/git-connections/import-copy", gitCopyImportResultSchema, home, "POST", gitCopyImportSchema.parse({
70
- ...common,
71
- name: options.name,
72
- origin: { type: origin.type, id: origin.id },
73
- idempotencyKey: options.key,
74
- }));
75
- }
76
- const body = gitImportSchema.parse({
77
- ...common,
78
- name: options.name,
79
- origin: { type: origin.type, id: origin.id },
80
- });
81
- return request(conn, "/v1/git-connections/import", gitConnectionSchema, home, "POST", body);
82
- }
83
- const selected = await selectAsset(common.kind, options.name, options.origin, home);
84
- const body = gitConnectSchema.parse({
85
- ...common,
86
- assetId: selected.reference.id,
87
- expectedVersionId: options.expectedVersion ?? selected.asset.version.id,
88
- mode: options.mode ?? "connect",
89
- });
90
- return request(conn, "/v1/git-connections", gitConnectionSchema, home, "POST", body);
91
- }
92
- const id = z.uuidv4().parse(options.id), path = `/v1/git-connections/${id}`;
93
- if (action === "show")
94
- return request(conn, path, gitConnectionSchema, home);
95
- if (action === "sync")
96
- return request(conn, `${path}/sync`, gitConnectionSchema, home, "POST");
97
- if (action === "mirror-resolve") {
98
- const body = gitMirrorResolutionSchema.parse({
99
- action: options.action,
100
- expectedVersionId: options.expectedVersion,
101
- expectedRemoteCommit: options.expectedRemote === "absent" ? null : options.expectedRemote,
102
- idempotencyKey: key,
103
- });
104
- return request(conn, `${path}/mirror-resolution`, okSchema, home, "POST", body);
105
- }
106
- if (action === "pulls-list")
107
- return request(conn, `${path}/pulls`, z.array(gitPullSchema), home);
108
- const bodyText = options.bodyFile
109
- ? await readFile(options.bodyFile, "utf8")
110
- : (options.body ?? "");
111
- if (action === "pulls-create" || action === "pulls-revise") {
112
- const files = (await readDirectory(resolve(options.directory ?? process.cwd()))).map((e) => ({
113
- path: e.path,
114
- content: e.data.toString("base64"),
115
- executable: e.executable,
116
- }));
117
- const body = (action === "pulls-create" ? gitProposalSchema : gitRevisionSchema).parse({
118
- expectedCommit: options.expectedCommit,
119
- files,
120
- title: options.title,
121
- body: bodyText,
122
- idempotencyKey: key,
123
- });
124
- return request(conn, action === "pulls-create"
125
- ? `${path}/pulls`
126
- : `${path}/pulls/${z.number().int().positive().parse(options.number)}/revisions`, gitPullSchema, home, action === "pulls-create" ? "POST" : "PUT", body);
127
- }
128
- const number = z.number().int().positive().parse(options.number), pull = `${path}/pulls/${number}`;
129
- if (action === "pulls-show")
130
- return request(conn, pull, gitPullDetailsSchema, home);
131
- if (action === "pulls-review")
132
- return request(conn, `${pull}/reviews`, gitPullDetailsSchema, home, "POST", gitReviewSchema.parse({
133
- expectedCommit: options.expectedCommit,
134
- event: options.event,
135
- body: bodyText,
136
- }));
137
- if (action === "pulls-comment")
138
- return request(conn, `${pull}/comments`, gitPullDetailsSchema, home, "POST", gitCommentSchema.parse({
139
- expectedCommit: options.expectedCommit,
140
- body: bodyText,
141
- path: options.path,
142
- line: options.line,
143
- side: options.side,
144
- }));
145
- if (action === "pulls-merge")
146
- return request(conn, `${pull}/merge`, gitConnectionSchema, home, "PUT", gitMergeSchema.parse({ expectedCommit: options.expectedCommit }));
147
- throw new Error(`Unknown GitHub action: ${action}`);
148
- }
@@ -1,71 +0,0 @@
1
- import { runtimeRequirements } from "../native/adapters.js";
2
- import { hookMetadata } from "@barndog-ai/api-contract/package";
3
- import { CliError } from "../../errors.js";
4
- import { matchesOrigin } from "../collaboration/remote.js";
5
- import { originLabel } from "../environment/names.js";
6
- import { folderSnapshot } from "./snapshot.js";
7
- import { loadWorkspace } from "./format.js";
8
- import { resolve } from "node:path";
9
- import { openRepoSource } from "../environment/workspace-source.js";
10
- import { LOCAL_ORIGIN, localOverlay } from "./overlay.js";
11
- /** The repo-backed source that answers for an origin, if any. */
12
- export function repoForOrigin(settings, home, origin) {
13
- const overlay = localOverlay(settings, home);
14
- return origin === LOCAL_ORIGIN && overlay
15
- ? overlay
16
- : openRepoSource(settings, home, { refresh: "auto" });
17
- }
18
- /** Finds one asset by name and origin, the way cloud commands address assets. */
19
- export function selectRepoAsset(model, kind, name, origin) {
20
- const matches = model.assets.filter((asset) => asset.kind === kind &&
21
- (asset.id === name || asset.name === name) &&
22
- (origin === LOCAL_ORIGIN || matchesOrigin(asset.origin, origin, model)));
23
- if (matches.length !== 1)
24
- throw new CliError(`No ${kind === "mcp" ? "MCP server" : kind} named ${name} in ${origin}.`, `barndog ${kind === "skill" ? "skills" : kind === "hook" ? "hooks" : "mcp"} search ${name}`);
25
- const asset = matches[0];
26
- if (asset.invalid)
27
- throw new CliError(`${asset.path} is invalid: ${asset.invalid}`);
28
- return asset;
29
- }
30
- export function showRepoAsset(asset) {
31
- return {
32
- id: asset.id,
33
- kind: asset.kind,
34
- name: asset.name,
35
- origin: originLabel(asset.origin),
36
- path: asset.path,
37
- version: asset.publishedVersion,
38
- description: asset.description,
39
- ...(asset.definition ? { definition: asset.definition } : {}),
40
- ...(asset.kind === "hook" ? { manifest: hookMetadata(asset.entries) } : {}),
41
- };
42
- }
43
- export async function repoHookCompatibility(asset) {
44
- const manifest = hookMetadata(asset.entries);
45
- return {
46
- version: asset.publishedVersion,
47
- compatibility: await Promise.all(["claude", "codex", "cursor"].map(async (harness) => {
48
- const implementation = manifest.implementations[harness] ?? null;
49
- return {
50
- harness,
51
- status: implementation?.compatibility ?? "unsupported",
52
- declared: true,
53
- implementation,
54
- runtimeIssue: implementation
55
- ? await runtimeRequirements(harness, implementation.requirements)
56
- : "No implementation for this harness",
57
- };
58
- })),
59
- };
60
- }
61
- /** Checks a workspace folder without installing anything, for use in repo CI. */
62
- export async function validateFolder(directory) {
63
- const model = await loadWorkspace(await folderSnapshot(resolve(directory)));
64
- if (model.problems.length)
65
- throw new CliError(`${model.problems.length} problem${model.problems.length === 1 ? "" : "s"} found:\n${model.problems.map((problem) => ` ${problem.path}: ${problem.reason}`).join("\n")}`);
66
- return {
67
- workspace: model.config.name,
68
- assets: model.assets.length,
69
- knowledge: model.knowledge.length,
70
- };
71
- }
@@ -1,135 +0,0 @@
1
- import { execFile, spawn } from "node:child_process";
2
- import { stat } from "node:fs/promises";
3
- import { CliError } from "../../errors.js";
4
- /** The line of Git's output that says what went wrong. */
5
- export function gitReason(stderr) {
6
- const lines = stderr
7
- .split("\n")
8
- .map((line) => line.trim())
9
- .filter(Boolean);
10
- const line = lines.find((text) => /^(fatal|error|remote):/.test(text)) ??
11
- lines.at(-1) ??
12
- "";
13
- return line.replace(/^(fatal|error|remote):\s*/, "");
14
- }
15
- /** Git can't read the repository with what this machine has set up. */
16
- export class RepositoryAccessError extends CliError {
17
- }
18
- export class GitError extends Error {
19
- stderr;
20
- exitCode;
21
- constructor(message, stderr, exitCode) {
22
- super(message);
23
- this.stderr = stderr;
24
- this.exitCode = exitCode;
25
- this.name = "GitError";
26
- }
27
- }
28
- // A caller running inside a Git hook passes these, and they would redirect every command.
29
- const inherited = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX"];
30
- /** Runs system Git with repository hooks and the arbitrary-command transport disabled. */
31
- export function git(args, options = {}) {
32
- const env = { ...process.env };
33
- for (const name of inherited)
34
- delete env[name];
35
- if (!options.allowPrompt)
36
- env.GIT_TERMINAL_PROMPT = "0";
37
- return new Promise((resolve, reject) => {
38
- const child = execFile("git", [
39
- ...(options.repo ? ["-C", options.repo] : []),
40
- "-c",
41
- "core.hooksPath=/dev/null",
42
- "-c",
43
- "protocol.ext.allow=never",
44
- ...args,
45
- ], {
46
- encoding: "buffer",
47
- env: { ...env, ...options.env },
48
- maxBuffer: 512 * 1024 * 1024,
49
- timeout: options.timeoutMs ?? 180_000,
50
- }, (error, stdout, stderr) => {
51
- if (!error)
52
- return resolve(stdout);
53
- const code = error.code ?? null;
54
- if (code === "ENOENT")
55
- return reject(new CliError("Git isn't installed or isn't on your PATH. Git repo workspaces need it."));
56
- const text = stderr.toString("utf8").trim();
57
- reject(new GitError(text || error.message, text, code));
58
- });
59
- child.stdin?.end(options.input);
60
- });
61
- }
62
- /** Runs Git attached to the terminal, so its own prompts and errors reach the developer. */
63
- export function gitInTerminal(args) {
64
- const env = { ...process.env };
65
- for (const name of inherited)
66
- delete env[name];
67
- return new Promise((resolve, reject) => {
68
- const child = spawn("git", [
69
- "-c",
70
- "core.hooksPath=/dev/null",
71
- "-c",
72
- "protocol.ext.allow=never",
73
- ...args,
74
- ], { env, stdio: "inherit" });
75
- child.once("error", reject);
76
- child.once("exit", (code) => code === 0
77
- ? resolve()
78
- : reject(new GitError(`git exited with ${code}`, "", code)));
79
- });
80
- }
81
- export const gitText = async (args, options) => (await git(args, options)).toString("utf8").trim();
82
- /** Lets `--repo` name a clone on disk: the workspace is the remote it came from. */
83
- export async function cloneOrigin(value) {
84
- try {
85
- if (!(await stat(value.trim())).isDirectory())
86
- return value;
87
- return await gitText(["config", "--get", "remote.origin.url"], {
88
- repo: value.trim(),
89
- });
90
- }
91
- catch {
92
- return value;
93
- }
94
- }
95
- /** Refuses URLs Git would read as options, helpers, or stored passwords. */
96
- export function checkRepositoryUrl(value) {
97
- const url = value.trim();
98
- if (!url || url.startsWith("-") || /^(ext|fd)::/i.test(url))
99
- throw new CliError(`That isn't a Git repository URL: ${url || "(empty)"}`);
100
- if (/^[a-z][a-z0-9+.-]*:\/\/[^/@]*:[^/@]*@/i.test(url))
101
- throw new CliError("Remove the password or token from the URL. BarnDog uses your own Git credentials and never stores them.");
102
- return url;
103
- }
104
- const FORTY_HEX = /^[0-9a-f]{40}$/;
105
- /** Reads a remote's default branch; null means the repository is empty. */
106
- export async function remoteHead(url, allowPrompt = false) {
107
- let output;
108
- try {
109
- output = await gitText(["ls-remote", "--symref", "--", url, "HEAD"], {
110
- allowPrompt,
111
- timeoutMs: 60_000,
112
- });
113
- }
114
- catch (error) {
115
- if (error instanceof GitError)
116
- throw new RepositoryAccessError(`Can't read ${url} with your Git credentials: ${gitReason(error.stderr)}`, `git clone ${url}`, { cause: error });
117
- throw error;
118
- }
119
- if (!output)
120
- return null;
121
- const branch = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(output)?.[1];
122
- const commit = /^([0-9a-f]+)\s+HEAD$/m.exec(output)?.[1];
123
- if (commit && !FORTY_HEX.test(commit))
124
- throw new CliError("This repository uses SHA-256 object names, which BarnDog doesn't support yet.");
125
- if (!branch || !commit)
126
- throw new CliError(`Can't find the default branch of ${url}.`);
127
- return { branch, commit };
128
- }
129
- const identityHint = 'git config --global user.email "you@example.com"';
130
- /** Git's "who are you" failure is common on new machines and has one clear fix. */
131
- export function explainIdentity(error) {
132
- if (error instanceof GitError && /tell me who you are/i.test(error.stderr))
133
- throw new CliError("Git doesn't know who you are, so BarnDog can't make a commit.", identityHint, { cause: error });
134
- throw error;
135
- }
@@ -1,188 +0,0 @@
1
- import { homedir } from "node:os";
2
- import { changeSchema, mcpSchema, knowledgeDocumentSchema, knowledgeIndexSchema, scopeSchema, } from "@barndog-ai/api-contract";
3
- import { z } from "zod";
4
- import { selectionState, withSelection } from "../../config/environment.js";
5
- import { readSettings, saveSettings, SetupRequiredError, upgradeSettings, } from "../../config/settings.js";
6
- import { CliError } from "../../errors.js";
7
- import { normalizeServer } from "../auth/transport.js";
8
- import { collaborationClient } from "../collaboration/domain.js";
9
- import { archive } from "../collaboration/workspace.js";
10
- import { encodeFiles } from "../collaboration/workspace-store.js";
11
- import { originLabel } from "../environment/names.js";
12
- import { environmentCatalog, request } from "../environment/remote.js";
13
- import { synchronize } from "../environment/sync.js";
14
- import { locked } from "../environment/transaction.js";
15
- import { openRepoSource } from "../environment/workspace-source.js";
16
- import { connectionContext } from "../skills/remote.js";
17
- import { localOverlay } from "./overlay.js";
18
- const sameScope = (cloud, local) => cloud.type === local.type &&
19
- (local.type === "org" || cloud.slug === local.slug);
20
- export async function publishPackage(asset, scope, conn, home) {
21
- const kind = asset.kind === "hook" ? "hook" : "skill";
22
- const client = collaborationClient(conn.server, home, kind);
23
- const files = encodeFiles(asset.entries);
24
- const metadata = {
25
- name: asset.name,
26
- origin: { type: scope.type, id: scope.id },
27
- baseVersionId: null,
28
- title: `Migrate ${asset.name} from Git`,
29
- // Stable per content, so re-running after a failure repeats rather than duplicates.
30
- idempotencyKey: `migrate-${asset.id}-${asset.publishedVersion}-${scope.id}-${asset.name}`,
31
- };
32
- const form = new FormData();
33
- form.set("metadata", JSON.stringify(metadata));
34
- form.set("package", await archive(files, home), "skill.tar.gz");
35
- const change = changeSchema.parse((await client.POST("/v1/skill-changes", { body: form })).data);
36
- await client.POST("/v1/skill-changes/{id}/merge", {
37
- params: { path: { id: change.id } },
38
- body: { expectedRevision: change.submittedRevision },
39
- });
40
- }
41
- export const publishMcp = (asset, scope, conn, home) => request(conn, "/v1/mcps", mcpSchema, home, "POST", {
42
- name: asset.name,
43
- origin: { type: scope.type, id: scope.id },
44
- definition: asset.definition,
45
- idempotencyKey: `migrate-${asset.id}-${asset.publishedVersion}-${scope.id}-${asset.name}`,
46
- });
47
- export const publishKnowledge = (doc, conn, home) => request(conn, "/v1/knowledge/publish", knowledgeDocumentSchema, home, "POST", {
48
- baseVersionId: null,
49
- content: doc.content,
50
- idempotencyKey: `migrate-${doc.id}-${doc.version}-${doc.content.name}`,
51
- });
52
- /** Carries each choice over by scope and name, because cloud assigns new IDs. */
53
- function translateSelection(state, scopes, assets, target) {
54
- const assetId = (id) => {
55
- const asset = assets.find((a) => a.id === id);
56
- const pair = asset && scopes.find((s) => s.local.id === asset.origin.id);
57
- return target.find((t) => t.kind === asset?.kind &&
58
- t.name === asset.name &&
59
- t.origin.type === pair?.cloud.type &&
60
- t.origin.id === pair.cloud.id)?.id;
61
- };
62
- const ids = (values) => values.flatMap((id) => assetId(id) ?? []);
63
- return {
64
- subscriptions: state.subscriptions.flatMap((subscription) => {
65
- const pair = scopes.find((s) => s.local.id === subscription.scope.id);
66
- return pair && pair.cloud.type !== "dev"
67
- ? [
68
- {
69
- ...subscription,
70
- scope: { type: pair.cloud.type, id: pair.cloud.id },
71
- },
72
- ]
73
- : [];
74
- }),
75
- individualAssetIds: ids(state.individualAssetIds),
76
- excludedAssetIds: ids(state.excludedAssetIds),
77
- disabledAssetIds: ids(state.disabledAssetIds),
78
- };
79
- }
80
- /** A kept local folder isn't part of the move, so its choices stay as they were. */
81
- function keepLocalChoices(next, before, kept) {
82
- if (!kept)
83
- return next;
84
- const local = (ids) => ids.filter((id) => kept.assets.some((asset) => asset.id === id));
85
- return {
86
- subscriptions: [
87
- ...next.subscriptions,
88
- ...before.subscriptions.filter((s) => s.scope.id === kept.organizationId),
89
- ],
90
- individualAssetIds: [
91
- ...next.individualAssetIds,
92
- ...local(before.individualAssetIds),
93
- ],
94
- excludedAssetIds: [
95
- ...next.excludedAssetIds,
96
- ...local(before.excludedAssetIds),
97
- ],
98
- disabledAssetIds: [
99
- ...next.disabledAssetIds,
100
- ...local(before.disabledAssetIds),
101
- ],
102
- };
103
- }
104
- /** Publishes current content to a cloud workspace; Git history stays in the repo. */
105
- export async function migrate(options, home = homedir()) {
106
- return locked(home, async () => {
107
- const settings = await readSettings(home);
108
- if (!settings)
109
- throw new SetupRequiredError();
110
- const source = openRepoSource(settings, home);
111
- if (settings.version === 2 &&
112
- !settings.gitWorkspace &&
113
- settings.localWorkspace &&
114
- !settings.connection)
115
- throw new CliError("`barndog migrate` moves a team's Git repo. To bring local assets to cloud, switch first: they stay active, and you can then move them with barndog local move.", "barndog init --server <url>");
116
- if (!source)
117
- throw new CliError("This machine isn't using a Git repo, so there's nothing to migrate.");
118
- const overlay = localOverlay(settings, home);
119
- const kept = overlay ? await overlay.model() : undefined;
120
- const model = await source.model();
121
- const server = normalizeServer(options.server);
122
- const conn = await connectionContext(server, home);
123
- const cloudScopes = await request(conn, "/v1/scopes", z.array(scopeSchema), home);
124
- const { catalog: existing } = await environmentCatalog(home, conn);
125
- const existingDocs = (await request(conn, "/v1/knowledge?limit=100", knowledgeIndexSchema, home)).documents;
126
- const pairs = model.scopes.flatMap((local) => {
127
- const cloud = cloudScopes.find((scope) => sameScope(scope, local));
128
- return cloud ? [{ local, cloud }] : [];
129
- });
130
- const rows = [];
131
- const pending = [];
132
- for (const asset of model.assets) {
133
- const base = {
134
- kind: asset.kind,
135
- name: asset.name,
136
- origin: originLabel(asset.origin),
137
- };
138
- const pair = pairs.find((p) => p.local.id === asset.origin.id);
139
- if (asset.invalid)
140
- rows.push({ ...base, action: "invalid", detail: asset.invalid });
141
- else if (!pair)
142
- rows.push({
143
- ...base,
144
- action: "missing-scope",
145
- detail: `Create ${originLabel(asset.origin)} in the workspace first`,
146
- });
147
- else if (existing.assets.some((a) => a.kind === asset.kind &&
148
- a.name === asset.name &&
149
- a.origin.type === pair.cloud.type &&
150
- a.origin.id === pair.cloud.id))
151
- rows.push({ ...base, action: "exists" });
152
- else {
153
- rows.push({ ...base, action: "publish" });
154
- pending.push(() => asset.kind === "mcp"
155
- ? publishMcp(asset, pair.cloud, conn, home)
156
- : publishPackage(asset, pair.cloud, conn, home));
157
- }
158
- }
159
- for (const doc of model.knowledge) {
160
- const base = { kind: "knowledge", name: doc.content.name, origin: "org" };
161
- if (existingDocs.some((d) => d.name === doc.content.name))
162
- rows.push({ ...base, action: "exists" });
163
- else {
164
- rows.push({ ...base, action: "publish" });
165
- pending.push(() => publishKnowledge(doc, conn, home));
166
- }
167
- }
168
- if (options.dryRun)
169
- return { server, dryRun: true, rows, migrated: false };
170
- const blocked = rows.filter((row) => row.action === "invalid" || row.action === "missing-scope");
171
- if (blocked.length)
172
- throw new CliError(`Nothing was published. Fix these first:\n${blocked.map((row) => ` ${row.origin}/${row.name}: ${row.detail}`).join("\n")}`, `barndog migrate --to ${server} --dry-run`);
173
- for (const publish of pending)
174
- await publish();
175
- const { catalog } = await environmentCatalog(home, conn);
176
- const upgraded = upgradeSettings(settings);
177
- const next = withSelection({
178
- ...upgraded,
179
- connection: conn,
180
- gitWorkspace: undefined,
181
- }, keepLocalChoices(translateSelection(selectionState(settings), pairs, model.assets, catalog.assets), selectionState(settings), kept));
182
- delete next.gitWorkspace;
183
- delete next.localNames;
184
- await saveSettings(next, home);
185
- await synchronize(undefined, home, next, { catalog });
186
- return { server, dryRun: false, rows, migrated: true };
187
- });
188
- }