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
@@ -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,23 @@
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";
12
13
  const failure = (error) => ({
13
14
  detail: error instanceof Error ? error.message : String(error),
14
15
  fix: error instanceof CliError ? error.hint : undefined,
15
16
  });
16
- async function gitChecks(workspace, home) {
17
+ async function gitChecks(workspace, runtime) {
17
18
  const checks = [];
18
19
  try {
19
- await remoteHead(workspace.url);
20
+ await remoteHead(workspace.url, runtime);
20
21
  checks.push({
21
22
  name: "Git access",
22
23
  status: "ok",
@@ -27,7 +28,7 @@ async function gitChecks(workspace, home) {
27
28
  checks.push({ name: "Git access", status: "fail", ...failure(error) });
28
29
  return checks;
29
30
  }
30
- const state = await readFetchState(workspace.workspaceId, home);
31
+ const state = await readFetchState(workspace.workspaceId, runtime);
31
32
  checks.push({
32
33
  name: "Last fetch",
33
34
  status: state.fetchedAt ? "ok" : "warn",
@@ -36,8 +37,8 @@ async function gitChecks(workspace, home) {
36
37
  : "Never fetched.",
37
38
  fix: state.fetchedAt ? undefined : "barndog sync",
38
39
  });
39
- const protectedBranch = await branchProtected(workspace.url, workspace.branch);
40
- if (protectedBranch !== true)
40
+ const protectedBranch = await branchProtected(workspace.url, workspace.branch, runtime);
41
+ if (protectedBranch !== true) {
41
42
  checks.push({
42
43
  name: "Branch protection",
43
44
  status: "warn",
@@ -45,10 +46,12 @@ async function gitChecks(workspace, home) {
45
46
  ? `${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
47
  : `BarnDog can't tell whether ${workspace.branch} is protected on this host. Make sure it is.`,
47
48
  });
49
+ }
48
50
  return checks;
49
51
  }
50
52
  /** Every check runs; one failure never hides the others. */
51
- export async function doctor(home = homedir()) {
53
+ export async function doctor(runtime) {
54
+ const { home } = runtime;
52
55
  const checks = [];
53
56
  let settings;
54
57
  try {
@@ -70,9 +73,9 @@ export async function doctor(home = homedir()) {
70
73
  checks.push({
71
74
  name: "Configuration",
72
75
  status: "ok",
73
- detail: settingsPath(home),
76
+ detail: barndogPaths(home).settings,
74
77
  });
75
- const detected = await detectHarnesses({ home });
78
+ const detected = await detectHarnesses(runtime);
76
79
  for (const harness of settings.harnesses) {
77
80
  const found = detected.find((d) => d.id === harness)?.evidence;
78
81
  checks.push({
@@ -83,10 +86,10 @@ export async function doctor(home = homedir()) {
83
86
  fix: found ? undefined : "barndog init",
84
87
  });
85
88
  }
86
- const connected = settings.version === 2 ? settings.connection : undefined;
89
+ const connected = settings.connection;
87
90
  if (connected) {
88
91
  try {
89
- const session = await authStatus(home, connected.server);
92
+ const session = await authStatus(runtime, connected.server);
90
93
  checks.push({
91
94
  name: "Session",
92
95
  status: "ok",
@@ -104,10 +107,11 @@ export async function doctor(home = homedir()) {
104
107
  return checks;
105
108
  }
106
109
  }
107
- if (settings.version === 2 && settings.gitWorkspace)
108
- checks.push(...(await gitChecks(settings.gitWorkspace, home)));
110
+ if (settings.gitWorkspace) {
111
+ checks.push(...(await gitChecks(settings.gitWorkspace, runtime)));
112
+ }
109
113
  try {
110
- const events = await synchronize(undefined, home, undefined, {
114
+ const events = await synchronize(undefined, runtime, undefined, {
111
115
  dryRun: true,
112
116
  prompt: false,
113
117
  });
@@ -124,27 +128,31 @@ export async function doctor(home = homedir()) {
124
128
  fix: pending ? "barndog sync" : undefined,
125
129
  });
126
130
  for (const event of events) {
127
- if (event.type === "notice")
131
+ if (event.type === "notice") {
128
132
  checks.push({ name: "Notice", status: "warn", detail: event.message });
129
- if (event.type === "clash")
133
+ }
134
+ if (event.type === "clash") {
130
135
  checks.push({
131
136
  name: "Name clash",
132
137
  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}`,
138
+ detail: `${event.skipped.origin} ${event.skipped.name} is skipped: ${event.installed.origin} already installs ${assetKinds[event.kind].a} with that name.`,
139
+ fix: `barndog ${assetKinds[event.kind].command} rename ${event.skipped.name} --origin ${event.skipped.origin} --as ${event.skipped.rename}`,
135
140
  });
136
- if (event.type === "invalid")
141
+ }
142
+ if (event.type === "invalid") {
137
143
  checks.push({
138
144
  name: "Invalid asset",
139
145
  status: "warn",
140
146
  detail: `${event.kind} ${event.name}: ${event.reason}. The installed version stays in place.`,
141
147
  });
142
- if (event.type === "unsupported")
148
+ }
149
+ if (event.type === "unsupported") {
143
150
  checks.push({
144
151
  name: "Unsupported",
145
152
  status: "warn",
146
153
  detail: `${event.kind} ${event.name} on ${adapters[event.harness].name}: ${event.reason}`,
147
154
  });
155
+ }
148
156
  }
149
157
  }
150
158
  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;
@@ -1,12 +1,10 @@
1
- import { skillName } from "../skills/validation.js";
2
- /** Human scope label such as local, org, team/engineering, repo/web or dev/john. */
3
- export function originLabel(origin) {
4
- if (origin.localOnly || origin.type === "local")
5
- return "local";
6
- return origin.type === "org"
7
- ? "org"
8
- : `${origin.type}/${origin.slug ?? origin.id ?? "unknown"}`;
9
- }
1
+ import { slugify, validAssetName } from "../../shared/patterns.js";
2
+ /** Eight ID characters distinguish hooks with the same display name. */
3
+ const HOOK_ID_SUFFIX_LENGTH = 8;
4
+ /** Unknown origins sort after all explicitly ranked origins. */
5
+ const UNKNOWN_ORIGIN_RANK = 9;
6
+ /** Allow repeated scope and ID disambiguation before declaring a collision. */
7
+ const NAME_RESOLUTION_PASSES_PER_ASSET = 4;
10
8
  const rank = {
11
9
  local: 0,
12
10
  dev: 1,
@@ -16,20 +14,25 @@ const rank = {
16
14
  };
17
15
  /** `<origin-type>-<origin-slug>-<name>` with single hyphens, e.g. team-super-team-review. */
18
16
  export function prefixedName(asset) {
19
- return [
17
+ return slugify([
20
18
  asset.origin.type,
21
19
  asset.origin.slug ?? asset.origin.id ?? "",
22
20
  asset.name,
23
- ]
24
- .join("-")
25
- .toLowerCase()
26
- .replace(/[^a-z0-9]+/g, "-")
27
- .replace(/^-+|-+$/g, "");
28
- }
29
- export function validInstalledName(name) {
30
- return skillName.test(name) && name.length <= 64;
21
+ ].join("-"));
31
22
  }
23
+ /**
24
+ * The name an asset installs under: its saved rename from `localNames`, else
25
+ * its published name.
26
+ */
32
27
  export const installedName = (asset, localNames) => localNames[asset.id] ?? asset.name;
28
+ /** A folder name with a trailing copy number, `review-1a2b-2`; group 1 is the rest. */
29
+ const COPY_NUMBER = /^(.*)-\d+$/;
30
+ /**
31
+ * `review-1a2b-2` → `review-1a2b`; undefined when there is no copy number.
32
+ *
33
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
34
+ */
35
+ export const withoutCopyNumber = (folder) => COPY_NUMBER.exec(folder)?.[1];
33
36
  /**
34
37
  * Origin prefixes are ambiguous: team a's b-c and team a-b's c read the same. Each
35
38
  * Hook gets its own folder: kept and already-installed folders stay put, a name only
@@ -44,64 +47,75 @@ export function hookFolders(hooks, localNames) {
44
47
  };
45
48
  const plain = (hook) => localNames[hook.id] ?? prefixedName(hook);
46
49
  const idText = (hook) => hook.id.replace(/[^a-z0-9]/gi, "").toLowerCase();
47
- const suffixed = (hook) => `${plain(hook)}-${idText(hook).slice(0, 8)}`;
50
+ const suffixed = (hook) => `${plain(hook)}-${idText(hook).slice(0, HOOK_ID_SUFFIX_LENGTH)}`;
48
51
  const whole = (hook) => `${plain(hook)}-${idText(hook)}`;
49
52
  const ordered = [...hooks].sort((a, b) => a.id.localeCompare(b.id));
50
53
  const open = () => ordered.filter((hook) => !folders.has(hook.id));
51
- for (const hook of ordered)
52
- if (hook.kept)
54
+ for (const hook of ordered) {
55
+ if (hook.kept) {
53
56
  claim(hook, hook.kept);
54
- for (const hook of open())
57
+ }
58
+ }
59
+ for (const hook of open()) {
55
60
  if (hook.current &&
56
61
  !used.has(hook.current) &&
57
62
  (hook.current === plain(hook) ||
58
63
  hook.current === suffixed(hook) ||
59
64
  hook.current === whole(hook) ||
60
- hook.current.match(/^(.*)-\d+$/)?.[1] === whole(hook)))
65
+ withoutCopyNumber(hook.current) === whole(hook))) {
61
66
  claim(hook, hook.current);
67
+ }
68
+ }
62
69
  const wanting = open().map(plain);
63
- for (const hook of open())
70
+ for (const hook of open()) {
64
71
  if (!used.has(plain(hook)) &&
65
- wanting.filter((folder) => folder === plain(hook)).length === 1)
72
+ wanting.filter((folder) => folder === plain(hook)).length === 1) {
66
73
  claim(hook, plain(hook));
74
+ }
75
+ }
67
76
  for (const hook of open()) {
68
77
  let folder = used.has(suffixed(hook)) ? whole(hook) : suffixed(hook);
69
- for (let n = 2; used.has(folder); n++)
78
+ for (let n = 2; used.has(folder); n++) {
70
79
  folder = `${whole(hook)}-${n}`;
80
+ }
71
81
  claim(hook, folder);
72
82
  }
73
83
  return folders;
74
84
  }
75
85
  /** Drops automatic renames whose plain name is free again; explicit names stay. */
76
- export function restoreNames(assets, localNames) {
86
+ function restoreNames(assets, localNames) {
77
87
  const next = { ...localNames };
78
88
  for (const asset of assets) {
79
- if (asset.renamable === false || next[asset.id] !== prefixedName(asset))
89
+ if (asset.renamable === false || next[asset.id] !== prefixedName(asset)) {
80
90
  continue;
91
+ }
81
92
  const taken = assets.some((other) => other.id !== asset.id &&
82
93
  other.kind === asset.kind &&
83
94
  installedName(other, next) === asset.name);
84
- if (!taken)
95
+ if (!taken) {
85
96
  delete next[asset.id];
97
+ }
86
98
  }
87
99
  return next;
88
100
  }
89
101
  /** The first clash in a stable order; the asset already installed (or most specific scope) keeps the name. */
90
- export function findClash(assets, localNames) {
102
+ function findClash(assets, localNames) {
91
103
  const groups = new Map();
92
104
  for (const asset of assets) {
93
105
  const key = `${asset.kind}\0${installedName(asset, localNames)}`;
94
106
  groups.set(key, [...(groups.get(key) ?? []), asset]);
95
107
  }
96
- for (const [key, group] of [...groups].sort(([a], [b]) => a.localeCompare(b))) {
97
- if (group.length < 2)
98
- continue;
108
+ for (const [, group] of [...groups].sort(([a], [b]) => a.localeCompare(b))) {
99
109
  const [installed, incoming] = [...group].sort((a, b) => Number(b.installed) - Number(a.installed) ||
100
- (rank[a.origin.type] ?? 9) - (rank[b.origin.type] ?? 9) ||
110
+ (rank[a.origin.type] ?? UNKNOWN_ORIGIN_RANK) -
111
+ (rank[b.origin.type] ?? UNKNOWN_ORIGIN_RANK) ||
101
112
  a.id.localeCompare(b.id));
113
+ if (!installed || !incoming) {
114
+ continue;
115
+ }
102
116
  return {
103
117
  kind: installed.kind,
104
- name: key.split("\0")[1],
118
+ name: installedName(installed, localNames),
105
119
  installed,
106
120
  incoming,
107
121
  installedRename: prefixedName(installed),
@@ -119,24 +133,28 @@ export async function resolveClashes(assets, localNames, resolver) {
119
133
  let active = [...assets];
120
134
  const disabled = [];
121
135
  const skipped = [];
122
- for (let guard = 0; guard < assets.length * 4 + 4; guard++) {
136
+ for (let guard = 0; guard <
137
+ assets.length * NAME_RESOLUTION_PASSES_PER_ASSET +
138
+ NAME_RESOLUTION_PASSES_PER_ASSET; guard++) {
123
139
  const clash = findClash(active, names);
124
- if (!clash)
140
+ if (!clash) {
125
141
  return { localNames: names, disabledAssetIds: disabled, skipped };
142
+ }
126
143
  let choice = resolver ? await resolver(clash) : "skip-incoming";
127
- const rename = choice === "rename-incoming"
128
- ? clash.incoming
129
- : choice === "rename-installed"
130
- ? clash.installed
131
- : undefined;
144
+ const renames = {
145
+ "rename-incoming": clash.incoming,
146
+ "rename-installed": clash.installed,
147
+ };
148
+ const rename = renames[choice];
132
149
  if (rename) {
133
150
  const name = prefixedName(rename);
134
151
  if (rename.renamable === false ||
135
- !validInstalledName(name) ||
152
+ !validAssetName(name) ||
136
153
  active.some((other) => other.id !== rename.id &&
137
154
  other.kind === rename.kind &&
138
- installedName(other, names) === name))
155
+ installedName(other, names) === name)) {
139
156
  choice = "skip-incoming";
157
+ }
140
158
  else {
141
159
  names = { ...names, [rename.id]: name };
142
160
  continue;
@@ -144,10 +162,12 @@ export async function resolveClashes(assets, localNames, resolver) {
144
162
  }
145
163
  const removed = choice === "replace-installed" ? clash.installed : clash.incoming;
146
164
  active = active.filter((asset) => asset.id !== removed.id);
147
- if (resolver)
165
+ if (resolver) {
148
166
  disabled.push(removed.id);
149
- else
167
+ }
168
+ else {
150
169
  skipped.push(clash);
170
+ }
151
171
  }
152
- throw new Error("Unable to resolve installed name clashes");
172
+ throw new Error("Installed names still clash after renaming");
153
173
  }