barndog 0.1.0 → 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 +11 -10
  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 +24 -11
  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
@@ -13,18 +13,25 @@ export function registerSync(program, context) {
13
13
  .action(async (options) => {
14
14
  // Runs detached at session start: nobody is watching, so it never reports.
15
15
  if (options.auto) {
16
- await autoSync(() => context.synchronize(undefined, { refresh: "auto", prompt: false })).catch(() => undefined);
16
+ await autoSync(() => context.synchronize(undefined, {
17
+ refresh: "auto",
18
+ prompt: false,
19
+ }), context.runtime).catch(() => undefined);
17
20
  return;
18
21
  }
19
- const configPath = options.config === undefined ? undefined : resolve(options.config);
22
+ const configPath = options.config === undefined
23
+ ? undefined
24
+ : resolve(context.runtime.cwd, options.config);
20
25
  const events = await context.synchronize(configPath, options.dryRun ? { dryRun: true } : undefined);
21
- if (context.mode.json)
26
+ if (context.mode.json) {
22
27
  return context.write(json(events));
28
+ }
23
29
  for (const line of renderSyncOutput(events, {
24
30
  title: options.dryRun ? "sync --dry-run" : "sync",
25
31
  preview: options.dryRun,
26
32
  verbose: options.verbose,
27
- }))
33
+ })) {
28
34
  context.write(line);
35
+ }
29
36
  });
30
37
  }
@@ -1,13 +1,24 @@
1
1
  import { bold, dim, heading, json, ok, plural, table, warn, } from "../ui/format.js";
2
2
  import { renderMove } from "../ui/move.js";
3
+ const migrationActionStyles = {
4
+ publish: ok,
5
+ exists: dim,
6
+ invalid: warn,
7
+ "missing-scope": warn,
8
+ };
9
+ /**
10
+ * Registers workspace validation, local asset movement and migration commands
11
+ * using the supplied services.
12
+ */
3
13
  export function registerWorkspace(program, context) {
4
14
  program
5
15
  .command("validate [directory]")
6
16
  .description("Check a BarnDog workspace folder, for example in a repo's CI")
7
17
  .action(async (directory) => {
8
- const result = (await context.capability("validate", { directory }));
9
- if (context.mode.json)
18
+ const result = await context.validateFolder(directory ?? ".");
19
+ if (context.mode.json) {
10
20
  return context.write(json(result));
21
+ }
11
22
  context.write(`${ok("✔")} ${bold(result.workspace)} is valid · ${plural(result.assets, "asset")}, ${plural(result.knowledge, "knowledge document")}`);
12
23
  });
13
24
  const local = program
@@ -17,19 +28,22 @@ export function registerWorkspace(program, context) {
17
28
  .command("list")
18
29
  .description("List local assets and whether they've been moved")
19
30
  .action(async () => {
20
- const result = (await context.capability("local-list", {}));
21
- if (context.mode.json)
31
+ const result = await context.listLocalAssets();
32
+ if (context.mode.json) {
22
33
  return context.write(json(result));
34
+ }
23
35
  context.write(dim(result.folder));
24
- if (!result.assets.length)
36
+ if (!result.assets.length) {
25
37
  return context.write(dim("No local assets."));
38
+ }
26
39
  for (const line of table(result.assets.map((asset) => [
27
40
  bold(asset.name),
28
41
  dim(asset.kind),
29
42
  asset.state === "invalid" ? warn(asset.state) : asset.state,
30
43
  dim(asset.path),
31
- ]), { header: ["Name", "Kind", "State", "Path"] }))
44
+ ]), { header: ["Name", "Kind", "State", "Path"] })) {
32
45
  context.write(line);
46
+ }
33
47
  });
34
48
  local
35
49
  .command("move [names...]")
@@ -39,17 +53,19 @@ export function registerWorkspace(program, context) {
39
53
  .option("--repo <url>", "Send to this Git repo; this machine stays as it is")
40
54
  .option("--server <url>", "Send to this Cloud Workspace; this machine stays as it is")
41
55
  .action(async (names, options) => {
42
- const result = (await context.capability("local-move", {
56
+ const result = await context.moveLocalAssets({
43
57
  names,
44
58
  to: options.to,
45
59
  as: options.as,
46
60
  repo: options.repo,
47
61
  server: options.server,
48
- }));
49
- if (context.mode.json)
62
+ });
63
+ if (context.mode.json) {
50
64
  return context.write(json(result));
51
- for (const line of renderMove(result))
65
+ }
66
+ for (const line of renderMove(result)) {
52
67
  context.write(line);
68
+ }
53
69
  });
54
70
  program
55
71
  .command("migrate")
@@ -57,25 +73,23 @@ export function registerWorkspace(program, context) {
57
73
  .requiredOption("--to <server>", "Cloud or self-hosted server URL")
58
74
  .option("--dry-run", "Show what would move without changing anything")
59
75
  .action(async (options) => {
60
- const result = (await context.capability("migrate", {
76
+ const result = await context.migrate({
61
77
  server: options.to,
62
78
  dryRun: options.dryRun,
63
- }));
64
- if (context.mode.json)
79
+ });
80
+ if (context.mode.json) {
65
81
  return context.write(json(result));
82
+ }
66
83
  context.write(`\n${heading(options.dryRun ? "migrate --dry-run" : "migrate")}\n`);
67
84
  for (const line of table(result.rows.map((row) => [
68
- row.action === "publish"
69
- ? ok(row.action)
70
- : row.action === "exists"
71
- ? dim(row.action)
72
- : warn(row.action),
85
+ migrationActionStyles[row.action](row.action),
73
86
  dim(row.kind),
74
87
  bold(row.name),
75
88
  row.origin,
76
89
  dim(row.detail ?? ""),
77
- ]), { header: ["Action", "Kind", "Name", "Origin", ""] }))
90
+ ]), { header: ["Action", "Kind", "Name", "Origin", ""] })) {
78
91
  context.write(line);
92
+ }
79
93
  context.write("");
80
94
  context.write(result.migrated
81
95
  ? `${ok("✔")} This machine now uses ${result.server}. Only current content moved; older versions stay in your repo.`
@@ -1,40 +1,26 @@
1
- import { z } from "zod";
2
- import { upgradeSettings } from "./settings.js";
3
- const id = z.uuidv4().transform((value) => value.toLowerCase());
4
- export const selectionStateSchema = z
5
- .object({
6
- subscriptions: z.array(z
7
- .object({
8
- scope: z.object({ type: z.enum(["org", "team", "repo"]), id }),
9
- mode: z.enum(["recommended", "optional", "all"]),
10
- enabled: z.boolean(),
11
- })
12
- .strict()),
13
- individualAssetIds: z.array(id),
14
- excludedAssetIds: z.array(id),
15
- disabledAssetIds: z.array(id),
16
- })
17
- .strict();
1
+ import { selectionStateSchema } from "./selection.js";
2
+ /**
3
+ * Reads selections from settings, returning empty lists when no environment has
4
+ * been saved.
5
+ */
18
6
  export function selectionState(settings) {
19
- const next = upgradeSettings(settings);
20
- return (next.environment ?? {
7
+ return (settings.environment ?? {
21
8
  subscriptions: [],
22
- individualAssetIds: next.skills
23
- .filter((s) => s.kind === "api")
24
- .map((s) => s.id),
9
+ individualAssetIds: [],
25
10
  excludedAssetIds: [],
26
- disabledAssetIds: next.skills
27
- .filter((s) => s.kind === "api" && !s.enabled)
28
- .map((s) => s.id),
11
+ disabledAssetIds: [],
29
12
  });
30
13
  }
31
14
  export function withSelection(settings, environment) {
32
15
  return {
33
- ...upgradeSettings(settings),
34
- skills: upgradeSettings(settings).skills.filter((s) => s.kind === "local"),
16
+ ...settings,
35
17
  environment: selectionStateSchema.parse(environment),
36
18
  };
37
19
  }
20
+ /**
21
+ * Checks whether settings contain subscriptions or individually selected
22
+ * assets, including disabled selections.
23
+ */
38
24
  export function hasRemoteSelections(settings) {
39
25
  const state = selectionState(settings);
40
26
  return !!(state.subscriptions.length || state.individualAssetIds.length);
@@ -0,0 +1,62 @@
1
+ import { join } from "node:path";
2
+ import { assetFolders } from "./selection.js";
3
+ /**
4
+ * Every path BarnDog keeps under `~/.barndog/`. These files are part of the
5
+ * public surface: older and newer CLI versions, and the end-to-end tests, read
6
+ * them. A new one gets a path here, a Zod schema, one reader, and writes
7
+ * through `writeAtomic()`.
8
+ */
9
+ export function barndogPaths(home) {
10
+ const root = join(home, ".barndog");
11
+ const git = join(root, "git");
12
+ const workingCopies = join(root, "workspaces");
13
+ return {
14
+ root,
15
+ /** Settings: harnesses, the workspace source and the asset selection. */
16
+ settings: join(root, "config.yaml"),
17
+ /** What BarnDog installed: harness links, native entries, package folders. */
18
+ state: join(root, "state.json"),
19
+ /** The writes of a sync in progress, rolled forward after a crash. */
20
+ pendingSync: join(root, "pending-sync.json"),
21
+ syncLock: join(root, "sync.lock"),
22
+ /** Backups of config.yaml and native files taken before BarnDog changes them. */
23
+ migrations: join(root, "migrations"),
24
+ /** The last Cloud catalog revision a background sync delivered. */
25
+ cloudCheck: join(root, "cloud-check.json"),
26
+ /** Saved sessions, per server. */
27
+ credentials: join(root, "credentials.json"),
28
+ credentialsLock: join(root, "credentials.lock"),
29
+ /** Where `claude mcp login` and `codex mcp login` run. */
30
+ nativeAuth: join(root, "native-auth"),
31
+ /** The default local workspace folder. */
32
+ localWorkspace: join(root, "workspace"),
33
+ /** Bare clones of Git workspaces. */
34
+ git,
35
+ /** The bare clone a Git workspace is read from; nothing is checked out. */
36
+ bareClone: (workspaceId) => join(git, `${workspaceId}.git`),
37
+ /** The commit last accepted from a Git workspace's host, and when. */
38
+ fetchState: (workspaceId) => join(git, `${workspaceId}.json`),
39
+ /** A clone that `barndog init --repo` checks before keeping it. */
40
+ setupClone: (id) => join(git, `.setup-${id}.git`),
41
+ /** Working-copy records, keyed by folder, with their lock and snapshots. */
42
+ workingCopies,
43
+ workingCopiesLock: join(workingCopies, "lock"),
44
+ /** What a working copy held before an update, for recovery. */
45
+ workingCopySnapshots: join(workingCopies, "snapshots"),
46
+ /** The commit-pinned package cache of one source: `<skills|hooks>/<asset ID>/<commit>/`. */
47
+ packageCache: (key) => join(root, "packages", key),
48
+ /** Readable folders that harness links point at. */
49
+ installed: (kind) => join(root, "installed", assetFolders[kind]),
50
+ };
51
+ }
52
+ /** Files BarnDog keeps inside a local workspace folder. */
53
+ export function localWorkspaceFiles(folder) {
54
+ return {
55
+ /** Assets imported from repositories, and how each one updates. */
56
+ sources: join(folder, ".barndog-sources.json"),
57
+ /** Assets moved to a shared workspace, so sync stops installing the local copy. */
58
+ moved: join(folder, ".barndog-moved.json"),
59
+ };
60
+ }
61
+ /** Beside each cached package: the fingerprint it was stored with. */
62
+ export const packageManifest = (revisionFolder) => join(revisionFolder, "manifest.json");
@@ -0,0 +1,30 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Asset kinds delivered as file packages; MCP definitions use separate
4
+ * configuration handling.
5
+ */
6
+ export const packageKindList = [
7
+ "skill",
8
+ "hook",
9
+ ];
10
+ /** The folder each kind lives in, in a workspace and under ~/.barndog/installed/. */
11
+ export const assetFolders = {
12
+ skill: "skills",
13
+ mcp: "mcp",
14
+ hook: "hooks",
15
+ };
16
+ const id = z.uuidv4().transform((value) => value.toLowerCase());
17
+ export const selectionStateSchema = z
18
+ .object({
19
+ subscriptions: z.array(z
20
+ .object({
21
+ scope: z.object({ type: z.enum(["org", "team", "repo"]), id }),
22
+ mode: z.enum(["recommended", "optional", "all"]),
23
+ enabled: z.boolean(),
24
+ })
25
+ .strict()),
26
+ individualAssetIds: z.array(id),
27
+ excludedAssetIds: z.array(id),
28
+ disabledAssetIds: z.array(id),
29
+ })
30
+ .strict();
@@ -1,127 +1,116 @@
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 { 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
+ const localNamesSchema = z.record(uuid, z.string().regex(NAME).max(MAX_ASSET_NAME_LENGTH));
36
+ /** Every part of the file; each optional key is named only here. */
37
+ // Loose objects keep keys this version doesn't know, as the file had them.
38
+ const settingsSchema = z.looseObject({
39
+ harnesses: z
40
+ .array(z.custom(isHarness))
41
+ .refine((list) => new Set(list).size === list.length),
42
+ connection: connectionSchema.optional(),
43
+ gitWorkspace: gitWorkspaceSchema.optional(),
44
+ localWorkspace: localWorkspaceSchema.optional(),
45
+ // Lazy: config/environment.ts imports this module, so its schema isn't ready yet.
46
+ environment: z.lazy(() => selectionStateSchema).optional(),
47
+ knowledge: z.boolean().optional(),
48
+ localNames: localNamesSchema.optional(),
49
+ });
50
+ const invalidSettings = "harnesses must list each of claude, codex, cursor and opencode at most once";
51
+ /** What to say about an invalid part, keyed by the field Zod reports it under. */
52
+ const invalidPart = {
53
+ harnesses: invalidSettings,
54
+ connection: "the server connection is invalid",
55
+ gitWorkspace: "gitWorkspace is invalid",
56
+ localWorkspace: "localWorkspace is invalid",
57
+ environment: "the asset selection is invalid",
58
+ knowledge: "knowledge must be true or false",
59
+ localNames: "localNames must map asset IDs to lowercase hyphenated names",
60
+ };
61
+ const isInvalidPart = (key) => typeof key === "string" && Object.hasOwn(invalidPart, key);
27
62
  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");
63
+ const result = settingsSchema.safeParse(value);
64
+ if (!result.success) {
65
+ const field = result.error.issues[0]?.path[0];
66
+ throw new Error((isInvalidPart(field) && invalidPart[field]) || invalidSettings);
67
+ }
68
+ // Keys older files had (a format `version` and a `skills` list) are left
69
+ // out here, so the next save removes them.
70
+ const { version, skills, ...settings } = result.data;
71
+ void version;
72
+ void skills;
73
+ const { connection, gitWorkspace, localWorkspace, environment } = settings;
74
+ if (connection && gitWorkspace) {
75
+ throw new Error("use only one of connection and gitWorkspace");
39
76
  }
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");
77
+ const selectsRemoteAssets = environment &&
78
+ (environment.subscriptions.length ||
79
+ environment.individualAssetIds.length) &&
80
+ !gitWorkspace &&
81
+ !localWorkspace;
82
+ if (selectsRemoteAssets && !connection) {
83
+ throw new Error("assets selected from a server need a connection");
107
84
  }
108
- return value;
85
+ return settings;
109
86
  }
110
- export async function readSettings(home = homedir(), path = settingsPath(home)) {
87
+ /**
88
+ * Reads and validates YAML settings at the given path; a missing file returns
89
+ * null, malformed settings throw.
90
+ */
91
+ export async function readSettings(home, path = barndogPaths(home).settings) {
92
+ const text = await readIfExists(path);
93
+ if (text === null) {
94
+ return null;
95
+ }
111
96
  try {
112
- return validate(parse(await readFile(path, "utf8")));
97
+ return validate(parse(text));
113
98
  }
114
99
  catch (error) {
115
- if (error.code === "ENOENT")
116
- return null;
117
- throw error;
100
+ // Someone edited the file by hand; saving runs the same checks as a guard.
101
+ throw new CliError(`${path} isn't valid: ${error instanceof Error ? error.message : String(error)}. Fix it, or move it aside and set up again.`, `mv ${path} ${path}.bak && barndog init`, { cause: error });
118
102
  }
119
103
  }
120
- export async function saveSettings(settings, home = homedir()) {
104
+ /** The file's text, after checking the settings are valid. */
105
+ export function settingsText(settings) {
121
106
  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);
107
+ return stringify(settings);
108
+ }
109
+ /**
110
+ * Validates and atomically writes settings under the supplied home directory.
111
+ */
112
+ export async function saveSettings(settings, home) {
113
+ const text = settingsText(settings);
114
+ const path = barndogPaths(home).settings;
115
+ await writeAtomic(path, text);
127
116
  }
@@ -1,70 +1,70 @@
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
+ const linkSchema = z.object({
9
+ id: z.string().regex(UUID_V4),
10
+ harness: z.enum(harnesses),
11
+ source: z.string().refine(isAbsolute),
12
+ target: z.string(),
13
+ });
14
+ /** The complete persisted installation ownership journal. */
15
+ const stateSchema = z.looseObject({
16
+ version: z.literal(1),
17
+ links: z.array(linkSchema),
18
+ native: z.array(z.strictObject({
19
+ id: z.string(),
20
+ kind: z.enum(nativeKinds),
21
+ harness: z.enum(harnesses),
22
+ file: z.string(),
23
+ key: z.string(),
24
+ value: z.record(z.string(), z.unknown()),
25
+ })),
26
+ installed: z.array(z.strictObject({
27
+ id: z.string(),
28
+ kind: z.enum(packageKindList),
29
+ path: z.string(),
30
+ fingerprint: z.string(),
31
+ versionId: z.string(),
32
+ })),
33
+ });
6
34
  /**
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.
35
+ * Reads installation ownership and checks targets against the supplied home;
36
+ * missing state yields no links.
9
37
  */
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;
38
+ export async function readState(home) {
39
+ const text = await readIfExists(barndogPaths(home).state);
40
+ if (text === null) {
41
+ return { version: 1, links: [], native: [], installed: [] };
32
42
  }
33
- return kept;
34
- }
35
- export async function readState(path, home) {
36
- let value;
37
- try {
38
- value = JSON.parse(await readFile(path, "utf8"));
43
+ const parsed = stateSchema.safeParse(JSON.parse(text));
44
+ if (!parsed.success) {
45
+ throw new Error("Invalid installation state; refusing to modify harness files", { cause: parsed.error });
46
+ }
47
+ const state = parsed.data;
48
+ for (const entry of state.native) {
49
+ if (entry.file !== nativeFile(entry.harness, entry.kind, home)) {
50
+ throw new Error("Invalid native installation state");
51
+ }
39
52
  }
40
- catch (error) {
41
- if (isRecord(error) && error.code === "ENOENT")
42
- return { version: 1, links: [] };
43
- throw error;
53
+ for (const entry of state.installed) {
54
+ if (dirname(entry.path) !== barndogPaths(home).installed(entry.kind)) {
55
+ throw new Error("Invalid installed package state");
56
+ }
44
57
  }
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
58
  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)) ||
59
+ const checked = [];
60
+ for (const link of state.links) {
61
+ if (dirname(link.target) !== skillDirectory(link.harness, home) ||
62
+ !NAME.test(basename(link.target)) ||
59
63
  targets.has(link.target)) {
60
64
  throw new Error("Invalid installation state; refusing to modify harness files");
61
65
  }
62
66
  targets.add(link.target);
67
+ checked.push(link);
63
68
  }
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);
69
+ return { ...state, links: checked };
70
70
  }