barndog 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,66 +1,77 @@
1
1
  import { CliError } from "../../errors.js";
2
- import { homedir } from "node:os";
3
2
  import { z } from "zod";
4
3
  import { developerListSchema, developerAssetsSchema, promotionInputSchema, forkInputSchema, } from "@barndog-ai/api-contract";
5
- import { connection, selectOrigin } from "../collaboration/remote.js";
6
- import { request, selectAsset } from "../environment/remote.js";
4
+ import { selectOrigin } from "../server/origin.js";
5
+ import { connection } from "../server/connection.js";
6
+ import { selectAsset } from "../server/catalog.js";
7
+ import { parsed } from "../server/client.js";
7
8
  import { randomUUID } from "node:crypto";
8
- export async function developers(search, home = homedir()) {
9
- const conn = await connection(home);
10
- const people = [];
11
- const seen = new Set();
12
- let cursor = null;
13
- do {
14
- const query = new URLSearchParams({
15
- limit: "100",
16
- ...(search ? { search } : {}),
17
- ...(cursor ? { cursor } : {}),
18
- });
19
- const page = await request(conn, `/v1/developers?${query}`, developerListSchema, home);
20
- people.push(...page.developers);
21
- if (page.nextCursor && seen.has(page.nextCursor))
22
- throw new Error("Invalid developer pagination");
23
- if (page.nextCursor)
24
- seen.add(page.nextCursor);
25
- cursor = page.nextCursor;
26
- } while (cursor);
27
- return people;
9
+ import { assetKindList } from "../asset-kinds/index.js";
10
+ import { only } from "../../shared/lookup.js";
11
+ import { allPages, PAGE_SIZE } from "../server/pages.js";
12
+ import { apiClient } from "../auth/transport.js";
13
+ /**
14
+ * Fetches every page of visible developers, optionally filtered by search;
15
+ * repeated cursors are rejected.
16
+ */
17
+ export async function developers(search, runtime) {
18
+ const conn = await connection(runtime);
19
+ return allPages(async (cursor) => {
20
+ const page = await parsed(developerListSchema, apiClient(conn.server, runtime).GET("/v1/developers", {
21
+ params: { query: { limit: PAGE_SIZE, search, cursor } },
22
+ }));
23
+ return { items: page.developers, nextCursor: page.nextCursor };
24
+ });
28
25
  }
29
- export async function developerAssets(selector, search, home = homedir()) {
30
- const people = await developers(undefined, home), matches = people.filter((p) => p.id === selector || p.slug === selector);
31
- if (matches.length !== 1)
26
+ /**
27
+ * Resolves a developer by ID or slug and fetches all pages of their visible
28
+ * assets, optionally filtered by search.
29
+ */
30
+ export async function developerAssets(selector, search, runtime) {
31
+ const people = await developers(undefined, runtime);
32
+ const matches = people.filter((p) => p.id === selector || p.slug === selector);
33
+ const developer = only(matches);
34
+ if (!developer) {
32
35
  throw new CliError(`No developer found with that handle.`, "barndog people list");
33
- const conn = await connection(home);
34
- const assets = [];
35
- const seen = new Set();
36
- let cursor = null;
37
- do {
38
- const query = new URLSearchParams({
39
- limit: "100",
40
- ...(search ? { search } : {}),
41
- ...(cursor ? { cursor } : {}),
42
- });
43
- const page = await request(conn, `/v1/developers/${matches[0].id}/assets?${query}`, developerAssetsSchema, home);
44
- assets.push(...page.assets);
45
- if (page.nextCursor && seen.has(page.nextCursor))
46
- throw new Error("Invalid discovery pagination");
47
- if (page.nextCursor)
48
- seen.add(page.nextCursor);
49
- cursor = page.nextCursor;
50
- } while (cursor);
51
- return { developer: matches[0], assets };
36
+ }
37
+ const conn = await connection(runtime);
38
+ const assets = await allPages(async (cursor) => {
39
+ const page = await parsed(developerAssetsSchema, apiClient(conn.server, runtime).GET("/v1/developers/{id}/assets", {
40
+ params: {
41
+ path: { id: developer.id },
42
+ query: { limit: PAGE_SIZE, search, cursor },
43
+ },
44
+ }));
45
+ return { items: page.assets, nextCursor: page.nextCursor };
46
+ });
47
+ return { developer, assets };
52
48
  }
53
- export async function promote(kind, name, origin, target, newName, home = homedir(), fork = false, key = randomUUID()) {
54
- const selected = await selectAsset(kind, name, origin, home), scope = await selectOrigin(target, selected.connection, home);
55
- const schema = fork ? forkInputSchema : promotionInputSchema;
56
- const body = schema.parse({
57
- name: newName,
49
+ const promotionSchema = z.object({
50
+ kind: z.enum(assetKindList),
51
+ id: z.uuid(),
52
+ changeId: z.uuid().optional(),
53
+ });
54
+ export async function copyToScope(action, input, runtime) {
55
+ const selected = await selectAsset(input.kind, input.name, input.origin, runtime);
56
+ const scope = await selectOrigin(input.target, selected.connection, runtime);
57
+ const client = apiClient(selected.connection.server, runtime);
58
+ const params = { path: { kind: input.kind, id: selected.reference.id } };
59
+ const body = {
60
+ name: input.newName,
58
61
  origin: { type: scope.type, id: scope.id },
59
- idempotencyKey: key,
60
- });
61
- return request(selected.connection, `/v1/environment/${kind}/${selected.reference.id}/${fork ? "fork" : "promote"}`, z.object({
62
- kind: z.enum(["skill", "hook", "mcp"]),
63
- id: z.uuid(),
64
- changeId: z.uuid().optional(),
65
- }), home, "POST", body);
62
+ idempotencyKey: input.key ?? randomUUID(),
63
+ };
64
+ return parsed(promotionSchema, action === "fork"
65
+ ? client.POST("/v1/environment/{kind}/{id}/fork", {
66
+ params,
67
+ body: forkInputSchema.parse(body),
68
+ })
69
+ : client.POST("/v1/environment/{kind}/{id}/promote", {
70
+ params,
71
+ body: promotionInputSchema.parse(body),
72
+ }));
73
+ }
74
+ /** Copies an asset into a scope the developer owns; a change ID means it needs review. */
75
+ export async function fork(input, runtime) {
76
+ return copyToScope("fork", input, runtime);
66
77
  }
@@ -1,22 +1,38 @@
1
- import { homedir } from "node:os";
2
- import { readSettings, settingsPath, } from "../../config/settings.js";
3
- import { remoteHead } from "../git-workspace/git.js";
4
- import { branchProtected } from "../git-workspace/publish.js";
5
- import { readFetchState } from "../git-workspace/source.js";
1
+ import { readSettings } from "../../config/settings.js";
2
+ import { remoteHead } from "../workspace/git.js";
3
+ import { branchProtected } from "../workspace/publish.js";
4
+ import { readFetchState } from "../workspace/repo-source.js";
6
5
  import { CliError } from "../../errors.js";
7
6
  import { detectHarnesses } from "../../harnesses/detect.js";
8
7
  import { adapters } from "../../harnesses/registry.js";
9
8
  import { authStatus } from "../auth/session.js";
10
9
  import { LoginRequiredError } from "../auth/transport.js";
11
10
  import { synchronize } from "../environment/sync.js";
11
+ import { assetKinds } from "../asset-kinds/index.js";
12
+ import { barndogPaths } from "../../config/paths.js";
13
+ /** An MCP variable installed servers refer to that has no value on this machine. */
14
+ function variableCheck(event) {
15
+ if (event.type !== "unset-variable") {
16
+ return [];
17
+ }
18
+ return [
19
+ {
20
+ name: "MCP variable",
21
+ status: "warn",
22
+ detail: `${event.variable} has no value here, so ${event.servers.join(", ")} can't use it: BarnDog doesn't keep it and it isn't set in this shell. Coding tools opened outside a terminal may not see your shell's variables either.`,
23
+ fix: `barndog mcp env set ${event.variable}`,
24
+ },
25
+ ];
26
+ }
12
27
  const failure = (error) => ({
13
28
  detail: error instanceof Error ? error.message : String(error),
14
29
  fix: error instanceof CliError ? error.hint : undefined,
30
+ command: error instanceof CliError ? error.command : undefined,
15
31
  });
16
- async function gitChecks(workspace, home) {
32
+ async function gitChecks(workspace, runtime) {
17
33
  const checks = [];
18
34
  try {
19
- await remoteHead(workspace.url);
35
+ await remoteHead(workspace.url, runtime);
20
36
  checks.push({
21
37
  name: "Git access",
22
38
  status: "ok",
@@ -25,9 +41,9 @@ async function gitChecks(workspace, home) {
25
41
  }
26
42
  catch (error) {
27
43
  checks.push({ name: "Git access", status: "fail", ...failure(error) });
28
- return checks;
29
44
  }
30
- const state = await readFetchState(workspace.workspaceId, home);
45
+ // Read locally, so it still helps when the remote can't be reached.
46
+ const state = await readFetchState(workspace.workspaceId, runtime);
31
47
  checks.push({
32
48
  name: "Last fetch",
33
49
  status: state.fetchedAt ? "ok" : "warn",
@@ -36,8 +52,11 @@ async function gitChecks(workspace, home) {
36
52
  : "Never fetched.",
37
53
  fix: state.fetchedAt ? undefined : "barndog sync",
38
54
  });
39
- const protectedBranch = await branchProtected(workspace.url, workspace.branch);
40
- if (protectedBranch !== true)
55
+ if (checks.some((check) => check.status === "fail")) {
56
+ return checks;
57
+ }
58
+ const protectedBranch = await branchProtected(workspace.url, workspace.branch, runtime);
59
+ if (protectedBranch !== true) {
41
60
  checks.push({
42
61
  name: "Branch protection",
43
62
  status: "warn",
@@ -45,10 +64,15 @@ async function gitChecks(workspace, home) {
45
64
  ? `${workspace.branch} isn't protected, so anyone who can push can install code on every teammate's machine. Protect it on the Git host.`
46
65
  : `BarnDog can't tell whether ${workspace.branch} is protected on this host. Make sure it is.`,
47
66
  });
67
+ }
48
68
  return checks;
49
69
  }
50
- /** Every check runs; one failure never hides the others. */
51
- export async function doctor(home = homedir()) {
70
+ /**
71
+ * Runs every check that can run: a failure hides only the checks that need
72
+ * what failed (a readable configuration, a session).
73
+ */
74
+ export async function doctor(runtime) {
75
+ const { home } = runtime;
52
76
  const checks = [];
53
77
  let settings;
54
78
  try {
@@ -70,9 +94,9 @@ export async function doctor(home = homedir()) {
70
94
  checks.push({
71
95
  name: "Configuration",
72
96
  status: "ok",
73
- detail: settingsPath(home),
97
+ detail: barndogPaths(home).settings,
74
98
  });
75
- const detected = await detectHarnesses({ home });
99
+ const detected = await detectHarnesses(runtime);
76
100
  for (const harness of settings.harnesses) {
77
101
  const found = detected.find((d) => d.id === harness)?.evidence;
78
102
  checks.push({
@@ -83,10 +107,10 @@ export async function doctor(home = homedir()) {
83
107
  fix: found ? undefined : "barndog init",
84
108
  });
85
109
  }
86
- const connected = settings.version === 2 ? settings.connection : undefined;
110
+ const connected = settings.connection;
87
111
  if (connected) {
88
112
  try {
89
- const session = await authStatus(home, connected.server);
113
+ const session = await authStatus(runtime, connected.server);
90
114
  checks.push({
91
115
  name: "Session",
92
116
  status: "ok",
@@ -104,10 +128,11 @@ export async function doctor(home = homedir()) {
104
128
  return checks;
105
129
  }
106
130
  }
107
- if (settings.version === 2 && settings.gitWorkspace)
108
- checks.push(...(await gitChecks(settings.gitWorkspace, home)));
131
+ if (settings.gitWorkspace) {
132
+ checks.push(...(await gitChecks(settings.gitWorkspace, runtime)));
133
+ }
109
134
  try {
110
- const events = await synchronize(undefined, home, undefined, {
135
+ const events = await synchronize(undefined, runtime, undefined, {
111
136
  dryRun: true,
112
137
  prompt: false,
113
138
  });
@@ -123,28 +148,33 @@ export async function doctor(home = homedir()) {
123
148
  : "Everything selected is installed and up to date.",
124
149
  fix: pending ? "barndog sync" : undefined,
125
150
  });
151
+ checks.push(...events.flatMap(variableCheck));
126
152
  for (const event of events) {
127
- if (event.type === "notice")
153
+ if (event.type === "notice") {
128
154
  checks.push({ name: "Notice", status: "warn", detail: event.message });
129
- if (event.type === "clash")
155
+ }
156
+ if (event.type === "clash") {
130
157
  checks.push({
131
158
  name: "Name clash",
132
159
  status: "warn",
133
- detail: `${event.skipped.origin} ${event.skipped.name} is skipped: ${event.installed.origin} already installs a ${event.kind === "skill" ? "Skill" : "MCP server"} with that name.`,
134
- fix: `barndog ${event.kind === "skill" ? "skills" : "mcp"} rename ${event.skipped.name} --origin ${event.skipped.origin} --as ${event.skipped.rename}`,
160
+ detail: `${event.skipped.origin} ${event.skipped.name} is skipped: ${event.installed.origin} already installs ${assetKinds[event.kind].a} with that name.`,
161
+ fix: `barndog ${assetKinds[event.kind].command} rename ${event.skipped.name} --origin ${event.skipped.origin} --as ${event.skipped.rename}`,
135
162
  });
136
- if (event.type === "invalid")
163
+ }
164
+ if (event.type === "invalid") {
137
165
  checks.push({
138
166
  name: "Invalid asset",
139
167
  status: "warn",
140
168
  detail: `${event.kind} ${event.name}: ${event.reason}. The installed version stays in place.`,
141
169
  });
142
- if (event.type === "unsupported")
170
+ }
171
+ if (event.type === "unsupported") {
143
172
  checks.push({
144
173
  name: "Unsupported",
145
174
  status: "warn",
146
175
  detail: `${event.kind} ${event.name} on ${adapters[event.harness].name}: ${event.reason}`,
147
176
  });
177
+ }
148
178
  }
149
179
  }
150
180
  catch (error) {
@@ -1,12 +1,14 @@
1
- import { randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
- import { homedir } from "node:os";
4
- import { dirname, join } from "node:path";
1
+ import { HTTP_STATUS } from "../../shared/constants.js";
2
+ import { readFile } from "node:fs/promises";
5
3
  import { ApiError, environmentCatalogRevisionSchema, } from "@barndog-ai/api-contract";
6
4
  import { z } from "zod";
7
5
  import { readSettings } from "../../config/settings.js";
8
- import { request } from "./remote.js";
9
- const CHECK_INTERVAL_MS = 5 * 60 * 1000;
6
+ import { parsed } from "../server/client.js";
7
+ import { writeAtomic } from "../../shared/files.js";
8
+ import { barndogPaths } from "../../config/paths.js";
9
+ import { apiClient } from "../auth/transport.js";
10
+ /** Background refresh policy: check at most every five minutes (milliseconds). */
11
+ const CHECK_INTERVAL_MS = 300000;
10
12
  const checkSchema = z.object({
11
13
  server: z.string(),
12
14
  organizationId: z.string(),
@@ -15,11 +17,12 @@ const checkSchema = z.object({
15
17
  /** The catalog revision the last successful sync delivered. */
16
18
  revision: z.string().optional(),
17
19
  });
18
- const checkPath = (home) => join(home, ".barndog/cloud-check.json");
19
- async function readCheck(home, conn) {
20
- const text = await readFile(checkPath(home), "utf8").catch(() => null);
21
- if (!text)
20
+ async function readCheck(runtime, conn) {
21
+ const { home } = runtime;
22
+ const text = await readFile(barndogPaths(home).cloudCheck, "utf8").catch(() => null);
23
+ if (!text) {
22
24
  return undefined;
25
+ }
23
26
  let value;
24
27
  try {
25
28
  value = JSON.parse(text);
@@ -35,22 +38,20 @@ async function readCheck(home, conn) {
35
38
  ? check.data
36
39
  : undefined;
37
40
  }
38
- async function writeCheck(home, check) {
39
- const path = checkPath(home);
40
- const temporary = `${path}.${randomUUID()}.tmp`;
41
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
42
- await writeFile(temporary, `${JSON.stringify(check)}\n`, { mode: 0o600 });
43
- await rename(temporary, path);
41
+ async function writeCheck(runtime, check) {
42
+ const { home } = runtime;
43
+ await writeAtomic(barndogPaths(home).cloudCheck, `${JSON.stringify(check)}\n`);
44
44
  }
45
45
  /** A server from before the check existed answers 404; sync as if it changed. */
46
- async function currentRevision(conn, home) {
46
+ async function currentRevision(conn, runtime) {
47
47
  try {
48
- const { revision } = await request(conn, "/v1/environment/catalog/revision", environmentCatalogRevisionSchema, home);
48
+ const { revision } = await parsed(environmentCatalogRevisionSchema, apiClient(conn.server, runtime).GET("/v1/environment/catalog/revision"));
49
49
  return revision;
50
50
  }
51
51
  catch (error) {
52
- if (error instanceof ApiError && error.status === 404)
52
+ if (error instanceof ApiError && error.status === HTTP_STATUS.notFound) {
53
53
  return undefined;
54
+ }
54
55
  throw error;
55
56
  }
56
57
  }
@@ -59,20 +60,20 @@ async function currentRevision(conn, home) {
59
60
  * changed before doing the work. Git and local workspaces have their own fetch
60
61
  * limit. A local folder beside cloud can change at any time, so it always syncs.
61
62
  */
62
- export async function autoSync(sync, home = homedir()) {
63
+ export async function autoSync(sync, runtime) {
64
+ const { home } = runtime;
63
65
  const settings = await readSettings(home);
64
- if (settings?.version !== 2 ||
65
- !settings.connection ||
66
- settings.localWorkspace) {
66
+ if (!settings || !settings.connection || settings.localWorkspace) {
67
67
  await sync();
68
68
  return;
69
69
  }
70
70
  const conn = settings.connection;
71
- const previous = await readCheck(home, conn);
71
+ const previous = await readCheck(runtime, conn);
72
72
  if (previous &&
73
- Date.now() - Date.parse(previous.checkedAt) < CHECK_INTERVAL_MS)
73
+ Date.now() - Date.parse(previous.checkedAt) < CHECK_INTERVAL_MS) {
74
74
  return;
75
- const record = (revision) => writeCheck(home, {
75
+ }
76
+ const record = (revision) => writeCheck(runtime, {
76
77
  server: conn.server,
77
78
  organizationId: conn.organizationId,
78
79
  developerId: conn.developerId,
@@ -80,7 +81,7 @@ export async function autoSync(sync, home = homedir()) {
80
81
  revision,
81
82
  });
82
83
  try {
83
- const revision = await currentRevision(conn, home);
84
+ const revision = await currentRevision(conn, runtime);
84
85
  if (revision !== undefined && revision === previous?.revision) {
85
86
  await record(revision);
86
87
  return;
@@ -0,0 +1,36 @@
1
+ import { detectHarnesses } from "../../harnesses/detect.js";
2
+ import { harnesses } from "../../harnesses/registry.js";
3
+ import { locked } from "./transaction.js";
4
+ import { synchronize } from "./sync.js";
5
+ import { readRequiredSettings } from "./operations.js";
6
+ /** Every coding tool BarnDog supports, in registry order. */
7
+ export async function listHarnesses(runtime) {
8
+ const settings = await readRequiredSettings(runtime);
9
+ const detected = await detectHarnesses(runtime);
10
+ return detected.map((harness) => ({
11
+ ...harness,
12
+ enabled: settings.harnesses.includes(harness.id),
13
+ }));
14
+ }
15
+ /** Leaves the tools not named as they are. */
16
+ export function changeHarnesses(change, targets, runtime) {
17
+ return applyHarnesses(runtime, (current) => change === "enable"
18
+ ? [...current, ...targets]
19
+ : current.filter((harness) => !targets.includes(harness)));
20
+ }
21
+ export function selectHarnesses(selected, runtime) {
22
+ return applyHarnesses(runtime, () => selected);
23
+ }
24
+ function applyHarnesses(runtime, next) {
25
+ return locked(runtime, async () => {
26
+ const settings = await readRequiredSettings(runtime);
27
+ const chosen = new Set(next(settings.harnesses));
28
+ // Registry order, so the saved list doesn't depend on the order typed.
29
+ const managed = harnesses.filter((harness) => chosen.has(harness));
30
+ const events = await synchronize(undefined, runtime, {
31
+ ...settings,
32
+ harnesses: managed,
33
+ });
34
+ return { status: "applied", events, harnesses: managed };
35
+ });
36
+ }
@@ -0,0 +1,171 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { resolveAssets } from "../asset-selection/index.js";
5
+ import { forgetImport } from "../imports/local.js";
6
+ import { saveSettings } from "../../config/settings.js";
7
+ import { withSelection } from "../../config/environment.js";
8
+ import { localOverlay, moveDestination, readMoved, recordMoved, } from "../workspace/overlay.js";
9
+ import { openRepoSource, openWorkspaceSource, } from "../workspace/workspace-source.js";
10
+ import { treeFingerprint } from "../workspace/tree.js";
11
+ const targetOf = (entry) => entry.target ?? "the shared workspace";
12
+ const waiting = (entry) => `${entry.name} is still moving to ${moveDestination(entry)}. Your local copy stays in use until that merges.`;
13
+ /** Whether the local copy still holds exactly what was moved. */
14
+ async function unchanged(entry, local, shared, input) {
15
+ if (entry.version) {
16
+ return local.publishedVersion === entry.version;
17
+ }
18
+ // Moves recorded before versions were kept: compare with the shared copy.
19
+ if (local.kind === "mcp") {
20
+ return isDeepStrictEqual(await input.source.mcpDefinition(shared), local.definition);
21
+ }
22
+ const folder = await input.source.packageFolder(local.kind, shared);
23
+ return ((await treeFingerprint(folder, input.runtime)) ===
24
+ (await treeFingerprint(join(input.overlay.label, local.path), input.runtime)));
25
+ }
26
+ /** Where a knowledge move stands; Cloud knowledge is published at once, so only Git waits. */
27
+ async function knowledgeOutcome(entry, model, input) {
28
+ const doc = model.knowledge.find((d) => d.path === entry.path);
29
+ if (!doc) {
30
+ return "gone";
31
+ }
32
+ // Recorded before versions were kept, and Cloud knowledge can't be compared here.
33
+ if (!entry.version) {
34
+ return "changed";
35
+ }
36
+ if (!(await input.sharedKnowledge())?.includes(entry.name)) {
37
+ return "waiting";
38
+ }
39
+ return doc.version === entry.version ? "unchanged" : "changed";
40
+ }
41
+ /** Only paths the local workspace's own model lists get here, so they stay inside it. */
42
+ async function removeLocal(entry, input) {
43
+ await rm(join(input.overlay.label, entry.path), {
44
+ recursive: true,
45
+ force: true,
46
+ });
47
+ await forgetImport(input.overlay.label, entry.kind, entry.name);
48
+ }
49
+ async function settleMoves(input) {
50
+ const records = await readMoved(input.overlay.label);
51
+ if (!records.length) {
52
+ return { selection: input.selection, notices: [], removedLocal: false };
53
+ }
54
+ const model = await input.overlay.model();
55
+ const selected = new Set(resolveAssets(input.catalog, input.selection).assets.map((entry) => entry.asset.id));
56
+ const ids = [...input.selection.individualAssetIds];
57
+ const notices = [];
58
+ const finished = [];
59
+ const removals = [];
60
+ const finish = (entry, keep) => {
61
+ finished.push(entry.path);
62
+ if (keep) {
63
+ notices.push(`${entry.name} changed after it was moved to ${targetOf(entry)}, so your local copy stays as a separate asset.`);
64
+ return;
65
+ }
66
+ removals.push(entry);
67
+ notices.push(`${entry.name} moved to ${targetOf(entry)}. Removed the local copy at ${join(input.overlay.label, entry.path)}.`);
68
+ };
69
+ for (const entry of records) {
70
+ if (entry.kind === "knowledge") {
71
+ const outcome = await knowledgeOutcome(entry, model, input);
72
+ if (outcome === "waiting") {
73
+ notices.push(waiting(entry));
74
+ }
75
+ else if (outcome === "gone") {
76
+ finished.push(entry.path);
77
+ }
78
+ else {
79
+ finish(entry, outcome === "changed");
80
+ }
81
+ continue;
82
+ }
83
+ const shared = input.catalog.assets.find((asset) => !asset.origin.localOnly &&
84
+ asset.kind === entry.kind &&
85
+ asset.name === entry.name &&
86
+ asset.origin.id === entry.originId);
87
+ if (!shared) {
88
+ notices.push(waiting(entry));
89
+ continue;
90
+ }
91
+ if (!selected.has(shared.id) && !ids.includes(shared.id)) {
92
+ ids.push(shared.id);
93
+ }
94
+ const local = model.assets.find((asset) => asset.path === entry.path);
95
+ if (!local) {
96
+ finished.push(entry.path);
97
+ continue;
98
+ }
99
+ finish(entry, !(await unchanged(entry, local, shared, input)));
100
+ }
101
+ const selection = ids.length === input.selection.individualAssetIds.length
102
+ ? input.selection
103
+ : { ...input.selection, individualAssetIds: ids };
104
+ if (input.persist && finished.length) {
105
+ // Saved first, so an interrupted sync can't leave an asset with neither copy.
106
+ await input.saveSelection(selection);
107
+ for (const entry of removals) {
108
+ await removeLocal(entry, input);
109
+ }
110
+ await recordMoved(input.overlay.label, [], finished);
111
+ }
112
+ return {
113
+ selection,
114
+ notices,
115
+ removedLocal: input.persist && removals.length > 0,
116
+ };
117
+ }
118
+ /**
119
+ * A machine that stopped using a Git or Cloud workspace can't finish moves
120
+ * into it, so they end here and the local copies stay as they are.
121
+ */
122
+ async function dropUnreachable(settings, persist) {
123
+ const folder = settings.localWorkspace?.path;
124
+ const records = folder ? await readMoved(folder) : [];
125
+ if (!folder || !records.length || !persist) {
126
+ return [];
127
+ }
128
+ await recordMoved(folder, [], records.map((entry) => entry.path));
129
+ return [
130
+ `This machine no longer uses the workspace ${records.map((entry) => entry.name).join(", ")} ${records.length === 1 ? "was" : "were"} moving to, so ${records.length === 1 ? "its local copy stays" : "their local copies stay"} as ${records.length === 1 ? "it is" : "they are"}.`,
131
+ ];
132
+ }
133
+ /**
134
+ * Finishes the moves whose shared copy exists. When a local copy was deleted,
135
+ * the catalog read before it still lists that copy, so it is read again
136
+ * unless the caller supplied it (`reread` false).
137
+ */
138
+ export async function finishMoves(input) {
139
+ const { settings, source, options, runtime } = input;
140
+ // A one-off --config delivery never changes what this machine keeps.
141
+ const persist = !options.dryRun && !input.configPath;
142
+ const reread = !options.source && !options.catalog;
143
+ const overlay = localOverlay(settings, runtime);
144
+ if (!overlay || !source) {
145
+ return {
146
+ source,
147
+ catalog: input.catalog,
148
+ selection: input.selection,
149
+ notices: await dropUnreachable(settings, persist),
150
+ };
151
+ }
152
+ const moves = await settleMoves({
153
+ overlay,
154
+ source,
155
+ catalog: input.catalog,
156
+ selection: input.selection,
157
+ sharedKnowledge: async () => settings.gitWorkspace
158
+ ? ((await openRepoSource(settings, runtime, {
159
+ refresh: "none",
160
+ })?.model())?.knowledge.map((doc) => doc.content.name) ?? null)
161
+ : null,
162
+ persist,
163
+ saveSelection: (next) => saveSettings(withSelection(settings, next), runtime.home),
164
+ runtime,
165
+ });
166
+ if (!moves.removedLocal || !reread) {
167
+ return { source, catalog: input.catalog, ...moves };
168
+ }
169
+ const fresh = openWorkspaceSource(settings, runtime, { refresh: "none" }) ?? source;
170
+ return { source: fresh, catalog: await fresh.catalog(), ...moves };
171
+ }