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,127 +1,118 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { dirname, isAbsolute, join } from "node:path";
4
- import { randomUUID } from "node:crypto";
1
+ import { MAX_ASSET_NAME_LENGTH } from "../shared/constants.js";
2
+ import { isAbsolute } from "node:path";
5
3
  import { parse, stringify } from "yaml";
6
- import { selectionStateSchema } from "./environment.js";
4
+ import { z } from "zod";
5
+ import { selectionStateSchema } from "./selection.js";
7
6
  import { isHarness } from "../harnesses/registry.js";
7
+ import { MCP_NAME, UUID_V4 } from "../shared/patterns.js";
8
+ import { readIfExists, writeAtomic } from "../shared/files.js";
9
+ import { CliError } from "../errors.js";
10
+ import { barndogPaths } from "./paths.js";
8
11
  export class SetupRequiredError extends Error {
9
12
  constructor() {
10
13
  super("Harness selection is not configured.");
11
14
  this.name = "SetupRequiredError";
12
15
  }
13
16
  }
14
- export function upgradeSettings(settings) {
15
- return settings.version === 2
16
- ? settings
17
- : {
18
- ...settings,
19
- version: 2,
20
- skills: settings.skills.map((skill) => ({ ...skill, kind: "local" })),
21
- };
22
- }
23
- export function settingsPath(home = homedir()) {
24
- return join(home, ".barndog", "config.yaml");
25
- }
26
- const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
+ const uuid = z.string().regex(UUID_V4);
18
+ const connectionSchema = z.looseObject({
19
+ server: z.string().regex(/^https?:\/\//),
20
+ organizationId: z.string(),
21
+ developerId: z.string(),
22
+ });
23
+ const gitWorkspaceSchema = z.looseObject({
24
+ url: z
25
+ .string()
26
+ .min(1)
27
+ .refine((url) => !url.startsWith("-")),
28
+ branch: z.string().min(1),
29
+ workspaceId: uuid,
30
+ });
31
+ const localWorkspaceSchema = z.looseObject({
32
+ path: z.string().refine(isAbsolute),
33
+ workspaceId: uuid,
34
+ });
35
+ // An MCP server's name may hold `_` and capitals; every other kind is checked
36
+ // against its own rule when renamed.
37
+ const localNamesSchema = z.record(uuid, z.string().regex(MCP_NAME).max(MAX_ASSET_NAME_LENGTH));
38
+ /** Every part of the file; each optional key is named only here. */
39
+ // Loose objects keep keys this version doesn't know, as the file had them.
40
+ const settingsSchema = z.looseObject({
41
+ harnesses: z
42
+ .array(z.custom(isHarness))
43
+ .refine((list) => new Set(list).size === list.length),
44
+ connection: connectionSchema.optional(),
45
+ gitWorkspace: gitWorkspaceSchema.optional(),
46
+ localWorkspace: localWorkspaceSchema.optional(),
47
+ // Lazy: config/environment.ts imports this module, so its schema isn't ready yet.
48
+ environment: z.lazy(() => selectionStateSchema).optional(),
49
+ knowledge: z.boolean().optional(),
50
+ localNames: localNamesSchema.optional(),
51
+ });
52
+ const invalidSettings = "harnesses must list each of claude, codex, cursor and opencode at most once";
53
+ /** What to say about an invalid part, keyed by the field Zod reports it under. */
54
+ const invalidPart = {
55
+ harnesses: invalidSettings,
56
+ connection: "the server connection is invalid",
57
+ gitWorkspace: "gitWorkspace is invalid",
58
+ localWorkspace: "localWorkspace is invalid",
59
+ environment: "the asset selection is invalid",
60
+ knowledge: "knowledge must be true or false",
61
+ localNames: "localNames must map asset IDs to lowercase hyphenated names",
62
+ };
63
+ const isInvalidPart = (key) => typeof key === "string" && Object.hasOwn(invalidPart, key);
27
64
  function validate(value) {
28
- if (typeof value !== "object" ||
29
- value === null ||
30
- !("version" in value) ||
31
- (value.version !== 1 && value.version !== 2) ||
32
- !("harnesses" in value) ||
33
- !Array.isArray(value.harnesses) ||
34
- !value.harnesses.every(isHarness) ||
35
- new Set(value.harnesses).size !== value.harnesses.length ||
36
- !("skills" in value) ||
37
- !Array.isArray(value.skills)) {
38
- throw new Error("Invalid user settings: expected version: 1 or 2, a unique harnesses list (claude, codex, cursor), and a skills array");
65
+ const result = settingsSchema.safeParse(value);
66
+ if (!result.success) {
67
+ const field = result.error.issues[0]?.path[0];
68
+ throw new Error((isInvalidPart(field) && invalidPart[field]) || invalidSettings);
69
+ }
70
+ // Keys older files had (a format `version` and a `skills` list) are left
71
+ // out here, so the next save removes them.
72
+ const { version, skills, ...settings } = result.data;
73
+ void version;
74
+ void skills;
75
+ const { connection, gitWorkspace, localWorkspace, environment } = settings;
76
+ if (connection && gitWorkspace) {
77
+ throw new Error("use only one of connection and gitWorkspace");
39
78
  }
40
- if (value.version === 2) {
41
- if ("environment" in value)
42
- selectionStateSchema.parse(value.environment);
43
- if ("knowledge" in value && typeof value.knowledge !== "boolean")
44
- throw new Error("Invalid knowledge integration setting");
45
- if ("localNames" in value &&
46
- (typeof value.localNames !== "object" ||
47
- value.localNames === null ||
48
- Array.isArray(value.localNames) ||
49
- Object.entries(value.localNames).some(([id, name]) => !uuidPattern.test(id) ||
50
- typeof name !== "string" ||
51
- !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) ||
52
- name.length > 64)))
53
- throw new Error("Invalid user settings: localNames maps asset IDs to lowercase hyphenated names");
54
- for (const skill of value.skills) {
55
- if (!skill ||
56
- typeof skill !== "object" ||
57
- !["local", "api"].includes(skill.kind) ||
58
- typeof skill.id !== "string" ||
59
- !uuidPattern.test(skill.id) ||
60
- typeof skill.enabled !== "boolean" ||
61
- (skill.kind === "local" &&
62
- (typeof skill.source !== "string" || !skill.source.trim())))
63
- throw new Error("Invalid user settings: invalid skill selection");
64
- }
65
- if (new Set(value.skills.map((skill) => skill.id.toLowerCase())).size !==
66
- value.skills.length)
67
- throw new Error("Invalid user settings: duplicate Skill ID");
68
- const connection = "connection" in value ? value.connection : undefined;
69
- if (connection &&
70
- (typeof connection.server !== "string" ||
71
- !/^https?:\/\//.test(connection.server) ||
72
- typeof connection.organizationId !== "string" ||
73
- typeof connection.developerId !== "string"))
74
- throw new Error("Invalid user settings: invalid server connection");
75
- const git = "gitWorkspace" in value
76
- ? value.gitWorkspace
77
- : undefined;
78
- const local = "localWorkspace" in value
79
- ? value.localWorkspace
80
- : undefined;
81
- if (git &&
82
- (typeof git.url !== "string" ||
83
- !git.url ||
84
- git.url.startsWith("-") ||
85
- typeof git.branch !== "string" ||
86
- !git.branch ||
87
- !uuidPattern.test(git.workspaceId)))
88
- throw new Error("Invalid user settings: invalid Git workspace");
89
- if (local &&
90
- (typeof local.path !== "string" ||
91
- !isAbsolute(local.path) ||
92
- !uuidPattern.test(local.workspaceId)))
93
- throw new Error("Invalid user settings: invalid local workspace");
94
- if (connection && git)
95
- throw new Error("Invalid user settings: use only one of connection and gitWorkspace");
96
- if (value.skills.some((skill) => skill.kind === "api") && !connection)
97
- throw new Error("Invalid user settings: API selections require a connection");
98
- if ("environment" in value &&
99
- (() => {
100
- const state = selectionStateSchema.parse(value.environment);
101
- return state.subscriptions.length || state.individualAssetIds.length;
102
- })() &&
103
- !connection &&
104
- !git &&
105
- !local)
106
- throw new Error("Invalid user settings: API selections require a connection");
79
+ const selectsRemoteAssets = environment &&
80
+ (environment.subscriptions.length ||
81
+ environment.individualAssetIds.length) &&
82
+ !gitWorkspace &&
83
+ !localWorkspace;
84
+ if (selectsRemoteAssets && !connection) {
85
+ throw new Error("assets selected from a server need a connection");
107
86
  }
108
- return value;
87
+ return settings;
109
88
  }
110
- export async function readSettings(home = homedir(), path = settingsPath(home)) {
89
+ /**
90
+ * Reads and validates YAML settings at the given path; a missing file returns
91
+ * null, malformed settings throw.
92
+ */
93
+ export async function readSettings(home, path = barndogPaths(home).settings) {
94
+ const text = await readIfExists(path);
95
+ if (text === null) {
96
+ return null;
97
+ }
111
98
  try {
112
- return validate(parse(await readFile(path, "utf8")));
99
+ return validate(parse(text));
113
100
  }
114
101
  catch (error) {
115
- if (error.code === "ENOENT")
116
- return null;
117
- throw error;
102
+ // Someone edited the file by hand; saving runs the same checks as a guard.
103
+ throw new CliError(`${path} isn't valid: ${error instanceof Error ? error.message : String(error)}. Fix it, or move it aside and set up again.`, `Fix the file, or move it aside (keep a copy) and run barndog init`, { cause: error });
118
104
  }
119
105
  }
120
- export async function saveSettings(settings, home = homedir()) {
106
+ /** The file's text, after checking the settings are valid. */
107
+ export function settingsText(settings) {
121
108
  validate(settings);
122
- const path = settingsPath(home);
123
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
124
- const temporary = `${path}.${randomUUID()}.tmp`;
125
- await writeFile(temporary, stringify(settings), { mode: 0o600 });
126
- await rename(temporary, path);
109
+ return stringify(settings);
110
+ }
111
+ /**
112
+ * Validates and atomically writes settings under the supplied home directory.
113
+ */
114
+ export async function saveSettings(settings, home) {
115
+ const text = settingsText(settings);
116
+ const path = barndogPaths(home).settings;
117
+ await writeAtomic(path, text);
127
118
  }
@@ -1,70 +1,82 @@
1
- import { readFile, readlink, rename, writeFile } from "node:fs/promises";
2
1
  import { basename, dirname, isAbsolute } from "node:path";
3
- import { isHarness, skillDirectory, } from "../harnesses/registry.js";
4
- import { treeFingerprint } from "../features/environment/installed.js";
5
- import { isRecord, uuid, skillName } from "../features/skills/validation.js";
2
+ import { harnesses, skillDirectory, nativeFile, nativeKinds, } from "../harnesses/registry.js";
3
+ import { z } from "zod";
4
+ import { packageKindList } from "./selection.js";
5
+ import { NAME, UUID_V4 } from "../shared/patterns.js";
6
+ import { barndogPaths } from "./paths.js";
7
+ import { readIfExists } from "../shared/files.js";
8
+ import { CliError } from "../shared/cli-error.js";
9
+ const linkSchema = z.object({
10
+ id: z.string().regex(UUID_V4),
11
+ harness: z.enum(harnesses),
12
+ source: z.string().refine(isAbsolute),
13
+ target: z.string(),
14
+ });
15
+ /** The complete persisted installation ownership journal. */
16
+ const stateSchema = z.looseObject({
17
+ version: z.literal(1),
18
+ links: z.array(linkSchema),
19
+ native: z.array(z.strictObject({
20
+ id: z.string(),
21
+ kind: z.enum(nativeKinds),
22
+ harness: z.enum(harnesses),
23
+ file: z.string(),
24
+ key: z.string(),
25
+ value: z.record(z.string(), z.unknown()),
26
+ })),
27
+ installed: z.array(z.strictObject({
28
+ id: z.string(),
29
+ kind: z.enum(packageKindList),
30
+ path: z.string(),
31
+ fingerprint: z.string(),
32
+ versionId: z.string(),
33
+ })),
34
+ });
6
35
  /**
7
- * Older versions could record two assets at one target. Only one can be real, so
8
- * keep the link the target actually points to, then the one whose copy is on disk.
36
+ * Reads installation ownership and checks targets against the supplied home;
37
+ * missing state yields no links.
9
38
  */
10
- async function withoutRepeatedLinks(links, installed) {
11
- const records = Array.isArray(installed) ? installed.filter(isRecord) : [];
12
- const score = async (link) => {
13
- if (typeof link.target !== "string" || typeof link.source !== "string")
14
- return 0;
15
- const actual = await readlink(link.target).catch(() => null);
16
- const entry = records.find((item) => item.id === link.id && item.path === link.source);
17
- return ((actual === link.source ? 2 : 0) +
18
- (entry?.fingerprint === (await treeFingerprint(link.source)) ? 1 : 0));
19
- };
20
- const kept = [];
21
- for (const link of links) {
22
- const index = isRecord(link) && typeof link.target === "string"
23
- ? kept.findIndex((other) => isRecord(other) && other.target === link.target)
24
- : -1;
25
- if (index < 0) {
26
- kept.push(link);
27
- continue;
28
- }
29
- const held = kept[index];
30
- if ((await score(link)) > (await score(held)))
31
- kept[index] = link;
39
+ export async function readState(home) {
40
+ const path = barndogPaths(home).state;
41
+ const text = await readIfExists(path);
42
+ if (text === null) {
43
+ return { version: 1, links: [], native: [], installed: [] };
32
44
  }
33
- return kept;
34
- }
35
- export async function readState(path, home) {
45
+ // Without this record BarnDog can't tell its own entries from yours, so
46
+ // nothing is changed until it is repaired.
47
+ const damaged = (cause) => new CliError(`${path} is damaged, so BarnDog won't change your tools' files.`, "Undo any edit to that file. If it can't be repaired, move it aside, remove what BarnDog installed in your tools, then run barndog sync", { cause });
36
48
  let value;
37
49
  try {
38
- value = JSON.parse(await readFile(path, "utf8"));
50
+ value = JSON.parse(text);
39
51
  }
40
52
  catch (error) {
41
- if (isRecord(error) && error.code === "ENOENT")
42
- return { version: 1, links: [] };
43
- throw error;
53
+ throw damaged(error);
54
+ }
55
+ const parsed = stateSchema.safeParse(value);
56
+ if (!parsed.success) {
57
+ throw damaged(parsed.error);
58
+ }
59
+ const state = parsed.data;
60
+ for (const entry of state.native) {
61
+ if (entry.file !== nativeFile(entry.harness, entry.kind, home)) {
62
+ throw damaged();
63
+ }
64
+ }
65
+ for (const entry of state.installed) {
66
+ if (dirname(entry.path) !== barndogPaths(home).installed(entry.kind)) {
67
+ throw damaged();
68
+ }
44
69
  }
45
- if (!isRecord(value) || value.version !== 1 || !Array.isArray(value.links))
46
- throw new Error("Invalid installation state");
47
- const links = await withoutRepeatedLinks(value.links, value.installed);
48
70
  const targets = new Set();
49
- for (const link of links) {
50
- if (!isRecord(link) ||
51
- typeof link.id !== "string" ||
52
- !uuid.test(link.id) ||
53
- !isHarness(link.harness) ||
54
- typeof link.source !== "string" ||
55
- !isAbsolute(link.source) ||
56
- typeof link.target !== "string" ||
57
- dirname(link.target) !== skillDirectory(link.harness, home) ||
58
- !skillName.test(basename(link.target)) ||
71
+ const checked = [];
72
+ for (const link of state.links) {
73
+ if (dirname(link.target) !== skillDirectory(link.harness, home) ||
74
+ !NAME.test(basename(link.target)) ||
59
75
  targets.has(link.target)) {
60
- throw new Error("Invalid installation state; refusing to modify harness files");
76
+ throw damaged();
61
77
  }
62
78
  targets.add(link.target);
79
+ checked.push(link);
63
80
  }
64
- return { ...value, links };
65
- }
66
- export async function saveState(path, state) {
67
- const temp = `${path}.${process.pid}.tmp`;
68
- await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
69
- await rename(temp, path);
81
+ return { ...state, links: checked };
70
82
  }
@@ -0,0 +1,32 @@
1
+ import { homedir } from "node:os";
2
+ import { adapters, isHarness } from "../harnesses/registry.js";
3
+ import { knowledgeList, knowledgeIndexText, } from "../features/knowledge/index.js";
4
+ /** Keep knowledge delivery from blocking harness startup beyond five seconds. */
5
+ const STARTUP_KNOWLEDGE_TIMEOUT_MS = 5000;
6
+ // BarnDog-owned integration, independent from developer-authored Hook packages.
7
+ // Failure to retrieve an index must never block starting a coding session.
8
+ const timer = setTimeout(() => {
9
+ console.error("BarnDog knowledge index timed out; use barndog knowledge list.");
10
+ process.exit(0);
11
+ }, STARTUP_KNOWLEDGE_TIMEOUT_MS);
12
+ const runtime = {
13
+ home: process.argv[3] ?? homedir(),
14
+ cwd: process.cwd(),
15
+ env: { ...process.env },
16
+ platform: process.platform,
17
+ };
18
+ try {
19
+ const text = knowledgeIndexText(await knowledgeList(true, runtime));
20
+ const harness = process.argv[2];
21
+ if (text && isHarness(harness)) {
22
+ // A plugin (OpenCode's) adds the plain text itself; a hook prints the tool's JSON.
23
+ const { hooks } = adapters[harness];
24
+ console.log(hooks ? JSON.stringify(hooks.sessionContext(text)) : text);
25
+ }
26
+ }
27
+ catch {
28
+ console.error("BarnDog knowledge index is unavailable; use barndog knowledge list after reconnecting.");
29
+ }
30
+ finally {
31
+ clearTimeout(timer);
32
+ }
@@ -0,0 +1,71 @@
1
+ import { homedir } from "node:os";
2
+ import crossSpawn from "cross-spawn";
3
+ import { isWindows, stopProcessTree } from "../platform.js";
4
+ import { mcpDefinitionSchema } from "@barndog-ai/api-contract";
5
+ import { CliError } from "../errors.js";
6
+ /** Allow two seconds for the MCP child to exit before forcing shutdown. */
7
+ const MCP_SHUTDOWN_GRACE_MS = 2000;
8
+ // This process runs only when the native harness starts a selected stdio MCP.
9
+ // Definitions contain references, never credential values. No shell is involved.
10
+ try {
11
+ const definition = mcpDefinitionSchema.parse(JSON.parse(Buffer.from(process.argv[2] ?? "", "base64url").toString("utf8")));
12
+ if (definition.transport !== "stdio") {
13
+ throw new Error("A stdio configuration is required");
14
+ }
15
+ const runtime = {
16
+ home: homedir(),
17
+ cwd: process.cwd(),
18
+ env: { ...process.env },
19
+ platform: process.platform,
20
+ };
21
+ const env = { ...runtime.env };
22
+ for (const [name, reference] of Object.entries(definition.environment)) {
23
+ if (!runtime.env[reference.secretRef]) {
24
+ throw new CliError(`${reference.secretRef} isn't set in your environment. Set it, then restart your coding tool.`);
25
+ }
26
+ env[name] = runtime.env[reference.secretRef];
27
+ }
28
+ // cross-spawn finds the command on PATH and also starts Windows .cmd shims
29
+ // (such as npx) with safely quoted arguments.
30
+ const child = crossSpawn(definition.command, definition.args, {
31
+ env,
32
+ stdio: "inherit",
33
+ detached: !isWindows(runtime.platform),
34
+ cwd: runtime.cwd,
35
+ windowsHide: true,
36
+ });
37
+ for (const signal of ["SIGINT", "SIGTERM"]) {
38
+ process.on(signal, () => {
39
+ const { pid } = child;
40
+ if (!pid) {
41
+ return;
42
+ }
43
+ try {
44
+ stopProcessTree(child, runtime, signal);
45
+ const timer = setTimeout(() => {
46
+ try {
47
+ stopProcessTree(child, runtime);
48
+ }
49
+ catch {
50
+ /* exited */
51
+ }
52
+ }, MCP_SHUTDOWN_GRACE_MS);
53
+ timer.unref();
54
+ }
55
+ catch {
56
+ /* already exited */
57
+ }
58
+ });
59
+ }
60
+ child.once("error", () => {
61
+ console.error("Unable to start the configured MCP command");
62
+ process.exitCode = 1;
63
+ });
64
+ child.once("exit", (code) => {
65
+ process.exitCode = code ?? 1;
66
+ });
67
+ }
68
+ catch (error) {
69
+ console.error(error instanceof Error ? error.message : "Invalid MCP configuration.");
70
+ process.exitCode = 1;
71
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * BarnDog's OpenCode plugin. OpenCode has no command hooks, so the module sync
3
+ * writes to `~/.config/opencode/plugins/barndog.js` imports `barndog` from
4
+ * here and hands it the command lines a session-start hook would run in other
5
+ * tools. OpenCode runs plugins in its own process, so this file only starts
6
+ * BarnDog's other entry scripts and never imports the CLI.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ /** OpenCode's event for a new session, the counterpart of other tools' SessionStart. */
10
+ const SESSION_CREATED = "session.created";
11
+ /** knowledge-startup gives up after five seconds; this covers starting Node too. */
12
+ const COMMAND_TIMEOUT_MS = 10_000;
13
+ /** The index lists names and descriptions only; anything longer is broken. */
14
+ const OUTPUT_LIMIT_BYTES = 1_048_576;
15
+ /** A command's trimmed stdout; empty when it fails, so a session never does. */
16
+ function output([program, ...args]) {
17
+ return new Promise((resolve) => {
18
+ if (!program) {
19
+ resolve("");
20
+ return;
21
+ }
22
+ execFile(program, args, {
23
+ timeout: COMMAND_TIMEOUT_MS,
24
+ maxBuffer: OUTPUT_LIMIT_BYTES,
25
+ windowsHide: true,
26
+ }, (error, stdout) => {
27
+ resolve(error ? "" : stdout.trim());
28
+ });
29
+ });
30
+ }
31
+ /**
32
+ * At each new session, starts the background workspace sync and reads the
33
+ * knowledge index afresh; every request of that session gets the index added
34
+ * to its system prompt.
35
+ */
36
+ export function barndog(options) {
37
+ // OpenCode awaits what a plugin returns, so a plain object will do.
38
+ return () => {
39
+ let index;
40
+ return {
41
+ event: async ({ event }) => {
42
+ if (event.type !== SESSION_CREATED) {
43
+ return;
44
+ }
45
+ index = undefined;
46
+ if (options.sync) {
47
+ await output(options.sync);
48
+ }
49
+ },
50
+ "experimental.chat.system.transform": async (_input, result) => {
51
+ if (!options.knowledge) {
52
+ return;
53
+ }
54
+ index ??= output(options.knowledge);
55
+ const text = await index;
56
+ if (text) {
57
+ result.system.push(text);
58
+ }
59
+ },
60
+ };
61
+ };
62
+ }
@@ -3,10 +3,15 @@ import { fileURLToPath } from "node:url";
3
3
  // Runs at session start. It must return at once and can never fail the session,
4
4
  // so the real sync happens in a detached process that outlives this one.
5
5
  try {
6
- const child = spawn(process.execPath, [fileURLToPath(new URL("../../cli.js", import.meta.url)), "sync", "--auto"], {
6
+ const child = spawn(process.execPath, [fileURLToPath(new URL("../cli.js", import.meta.url)), "sync", "--auto"], {
7
7
  detached: true,
8
+ windowsHide: true,
8
9
  stdio: "ignore",
9
- env: { ...process.env, HOME: process.argv[2] },
10
+ env: {
11
+ ...process.env,
12
+ HOME: process.argv[2],
13
+ USERPROFILE: process.argv[2],
14
+ },
10
15
  });
11
16
  child.on("error", () => { });
12
17
  child.unref();