barndog 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +8 -7
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +13 -3
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,31 +1,43 @@
1
- import { readFile, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
1
  import { resolveAssets } from "../asset-selection/index.js";
4
- import { localRepoSource } from "./source.js";
2
+ import { localRepoSource } from "./repo-source.js";
3
+ import { z } from "zod";
4
+ import { localWorkspaceFiles } from "../../config/paths.js";
5
+ import { readJsonIfExists, writeAtomic } from "../../shared/files.js";
6
+ import { POSIX_MODE } from "../../shared/constants.js";
5
7
  /** How assets in the kept local folder are addressed next to a shared workspace. */
6
8
  export const LOCAL_ORIGIN = "local";
7
- const MOVED_FILE = ".barndog-moved.json";
9
+ const movedSchema = z.array(z.looseObject({
10
+ kind: z.string(),
11
+ path: z.string(),
12
+ name: z.string(),
13
+ /** Scope it was moved to; knowledge has none. */
14
+ originId: z.string().optional(),
15
+ /** Set once the shared copy was selected, so removing it later sticks. */
16
+ adopted: z.boolean().optional(),
17
+ }));
18
+ /**
19
+ * Reads and validates movement records in a workspace folder; an absent file
20
+ * means nothing has moved.
21
+ */
8
22
  export async function readMoved(folder) {
9
- try {
10
- return JSON.parse(await readFile(join(folder, MOVED_FILE), "utf8"));
11
- }
12
- catch (error) {
13
- if (error.code === "ENOENT")
14
- return [];
15
- throw error;
16
- }
23
+ return ((await readJsonIfExists(localWorkspaceFiles(folder).moved, movedSchema)) ??
24
+ []);
17
25
  }
26
+ /**
27
+ * Writes movement records in the folder, replacing prior entries with the same
28
+ * local path.
29
+ */
18
30
  export async function recordMoved(folder, added) {
19
31
  const kept = (await readMoved(folder)).filter((entry) => !added.some((asset) => asset.path === entry.path));
20
- await writeFile(join(folder, MOVED_FILE), JSON.stringify([...kept, ...added], null, 2) + "\n");
32
+ await writeAtomic(localWorkspaceFiles(folder).moved, JSON.stringify([...kept, ...added], null, 2) + "\n", { mode: POSIX_MODE.regularFile });
21
33
  }
22
34
  /** The local folder, when it runs alongside a Git or Cloud workspace. */
23
- export function localOverlay(settings, home) {
24
- if (settings.version !== 2 ||
25
- !settings.localWorkspace ||
26
- (!settings.connection && !settings.gitWorkspace))
35
+ export function localOverlay(settings, runtime) {
36
+ if (!settings.localWorkspace ||
37
+ (!settings.connection && !settings.gitWorkspace)) {
27
38
  return undefined;
28
- return localRepoSource(settings.localWorkspace, home);
39
+ }
40
+ return localRepoSource(settings.localWorkspace, runtime);
29
41
  }
30
42
  /** Local copies step aside once what was moved exists in the shared workspace. */
31
43
  export async function activeLocal(overlay, shared) {
@@ -42,6 +54,10 @@ export async function activeLocal(overlay, shared) {
42
54
  knowledge: model.knowledge.filter((doc) => !retired("knowledge", doc.path)),
43
55
  };
44
56
  }
57
+ /**
58
+ * Adds active local assets and their recommended distribution to a shared
59
+ * catalog without mutating the input.
60
+ */
45
61
  export async function mergeLocalCatalog(catalog, overlay) {
46
62
  const { model, assets } = await activeLocal(overlay, [...catalog.assets]);
47
63
  const local = assets.map((asset) => ({
@@ -77,19 +93,23 @@ export async function adoptMoved(overlay, catalog, state, persist) {
77
93
  const ids = [...state.individualAssetIds];
78
94
  const adopted = [];
79
95
  for (const entry of moved) {
80
- if (entry.adopted || !entry.originId)
96
+ if (entry.adopted || !entry.originId) {
81
97
  continue;
98
+ }
82
99
  const asset = catalog.assets.find((a) => a.kind === entry.kind &&
83
100
  a.name === entry.name &&
84
101
  a.origin.id === entry.originId);
85
- if (!asset)
102
+ if (!asset) {
86
103
  continue;
87
- if (!selected.has(asset.id))
104
+ }
105
+ if (!selected.has(asset.id)) {
88
106
  ids.push(asset.id);
107
+ }
89
108
  adopted.push({ ...entry, adopted: true });
90
109
  }
91
- if (persist && adopted.length)
110
+ if (persist && adopted.length) {
92
111
  await recordMoved(overlay.label, adopted);
112
+ }
93
113
  return ids.length === state.individualAssetIds.length
94
114
  ? state
95
115
  : { ...state, individualAssetIds: ids };
@@ -120,7 +140,7 @@ export function withOverlay(primary, overlay) {
120
140
  extraCacheKeys: [overlay.cacheKey],
121
141
  journal: primary.journal,
122
142
  catalog: async () => mergeLocalCatalog(await primary.catalog(), overlay),
123
- skillOrHookPackage: async (kind, reference) => (await owner(reference)).skillOrHookPackage(kind, reference),
143
+ packageFolder: async (kind, reference) => (await owner(reference)).packageFolder(kind, reference),
124
144
  mcpDefinition: async (reference) => (await owner(reference)).mcpDefinition(reference),
125
145
  invalidAssets: async () => new Map([
126
146
  ...(await primary.invalidAssets()),
@@ -0,0 +1,160 @@
1
+ import { directoryFingerprint, writePackage } from "./directory.js";
2
+ import { fixSteps, removeCommand } from "../../platform.js";
3
+ import { POSIX_MODE } from "../../shared/constants.js";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { mkdir, readdir, readFile, rename, rm, lstat } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { z } from "zod";
8
+ import { defaultLimits, parsePackage, } from "@barndog-ai/api-contract/package";
9
+ import { ApiError } from "@barndog-ai/api-contract";
10
+ import { apiClient } from "../auth/transport.js";
11
+ import { assetKinds, metadata } from "../asset-kinds/index.js";
12
+ import { assetFolders, packageKindList, } from "../../config/selection.js";
13
+ import { GIT_OBJECT_ID, UUID_V4 } from "../../shared/patterns.js";
14
+ import { CliError, PackageError } from "../../errors.js";
15
+ import { barndogPaths, packageManifest } from "../../config/paths.js";
16
+ import { ifExists, writeAtomic } from "../../shared/files.js";
17
+ /** One identity's cache partition: server, organization and developer never mix. */
18
+ export function cacheKey(conn) {
19
+ const server = createHash("sha256").update(conn.server).digest("hex");
20
+ return join(server, conn.organizationId, conn.developerId);
21
+ }
22
+ /**
23
+ * Deletes cached versions nothing installs any more. Every cached version was
24
+ * downloaded from the workspace, so an older one can always be fetched again.
25
+ * Other identities' caches are left alone.
26
+ */
27
+ export async function pruneCache(key, runtime, keep) {
28
+ const { home } = runtime;
29
+ const root = barndogPaths(home).packageCache(key);
30
+ let removed = 0;
31
+ const children = async (path) => (await ifExists(readdir(path))) ?? [];
32
+ for (const parent of packageKindList.map((kind) => join(root, assetFolders[kind]))) {
33
+ for (const asset of await children(parent)) {
34
+ if (!UUID_V4.test(asset)) {
35
+ continue;
36
+ }
37
+ const directory = join(parent, asset);
38
+ for (const revision of await children(directory)) {
39
+ const path = join(directory, revision);
40
+ if (keep.has(path)) {
41
+ continue;
42
+ }
43
+ if (!GIT_OBJECT_ID.test(revision) && !revision.startsWith(".stage-")) {
44
+ continue;
45
+ }
46
+ await rm(path, { recursive: true, force: true });
47
+ removed++;
48
+ }
49
+ if (!(await children(directory)).length) {
50
+ await rm(directory, { recursive: true, force: true });
51
+ }
52
+ }
53
+ }
54
+ return removed;
55
+ }
56
+ /** Returns the immutable cached folder for a revision, loading it only when absent. */
57
+ export async function storePackage(kind, asset, { key, runtime }, load) {
58
+ const { home } = runtime;
59
+ const parent = join(barndogPaths(home).packageCache(key), assetFolders[kind], asset.id);
60
+ await mkdir(parent, { recursive: true, mode: POSIX_MODE.privateDirectory });
61
+ const check = async (root) => {
62
+ const saved = z
63
+ .object({ fingerprint: z.string() })
64
+ .safeParse(JSON.parse(await readFile(packageManifest(root), "utf8")));
65
+ if (!saved.success ||
66
+ (await directoryFingerprint(join(root, asset.name), runtime)) !==
67
+ saved.data.fingerprint) {
68
+ throw new CliError(`The downloaded copy of ${asset.name} in ${root} was changed on this machine, so BarnDog won't use it.`, "Delete that folder; the next sync downloads it again.", {
69
+ command: fixSteps([removeCommand(root, runtime.platform), "barndog sync"], runtime.platform),
70
+ });
71
+ }
72
+ };
73
+ for (const revision of await readdir(parent)) {
74
+ if (GIT_OBJECT_ID.test(revision)) {
75
+ await check(join(parent, revision));
76
+ }
77
+ }
78
+ const target = join(parent, asset.revision);
79
+ if (await ifExists(lstat(target))) {
80
+ await check(target);
81
+ return join(target, asset.name);
82
+ }
83
+ const entries = await load();
84
+ const stage = join(parent, `.stage-${randomUUID()}`);
85
+ try {
86
+ await writePackage(join(stage, asset.name), entries, runtime);
87
+ // Read back, so Windows (no executable bits) records what `check` will see.
88
+ await writeAtomic(packageManifest(stage), JSON.stringify({
89
+ fingerprint: await directoryFingerprint(join(stage, asset.name), runtime),
90
+ }));
91
+ await rename(stage, target);
92
+ }
93
+ finally {
94
+ await rm(stage, { recursive: true, force: true });
95
+ }
96
+ return join(target, asset.name);
97
+ }
98
+ /**
99
+ * Reads and unpacks a package download within the package size limits. With
100
+ * `commit`, refuses a package whose ETag names another revision. `subject`
101
+ * names the package in errors.
102
+ */
103
+ export async function unpackDownload(download, options) {
104
+ const { kind, commit, subject, fix } = options;
105
+ let response;
106
+ try {
107
+ ({ response } = await download);
108
+ }
109
+ catch (error) {
110
+ if (error instanceof ApiError) {
111
+ throw new CliError(`Downloading ${subject} failed (${error.status}). Try again.`, fix, { cause: error });
112
+ }
113
+ throw error;
114
+ }
115
+ if (commit && response.headers.get("etag") !== `"${commit}"`) {
116
+ throw new CliError(`The server changed ${subject} while it was downloading. Try again.`, fix);
117
+ }
118
+ if (!response.body) {
119
+ throw new Error("The server sent a package download with no body");
120
+ }
121
+ let size = 0;
122
+ const chunks = [];
123
+ for await (const chunk of response.body) {
124
+ size += chunk.length;
125
+ if (size > defaultLimits.compressed) {
126
+ throw new PackageError("PACKAGE_TOO_LARGE");
127
+ }
128
+ chunks.push(chunk);
129
+ }
130
+ return parsePackage(Buffer.concat(chunks), defaultLimits, assetKinds[kind].manifest);
131
+ }
132
+ /** The published-package route of each kind. */
133
+ const packageDownloads = {
134
+ skill: (client, asset) => client.GET("/v1/skills/{id}/versions/{version}/package", {
135
+ params: { path: { id: asset.id, version: asset.version.number } },
136
+ parseAs: "stream",
137
+ }),
138
+ hook: (client, asset) => client.GET("/v1/hooks/{id}/versions/{version}/package", {
139
+ params: { path: { id: asset.id, version: asset.version.number } },
140
+ parseAs: "stream",
141
+ }),
142
+ };
143
+ /**
144
+ * Returns a cached package or downloads and validates its revision, size and
145
+ * metadata before storing it.
146
+ */
147
+ export async function cachedPackage(kind, asset, conn, runtime) {
148
+ return storePackage(kind, { id: asset.id, name: asset.name, revision: asset.version.commit }, { key: cacheKey(conn), runtime }, async () => {
149
+ const entries = await unpackDownload(packageDownloads[kind](apiClient(conn.server, runtime), asset), {
150
+ kind,
151
+ commit: asset.version.commit,
152
+ subject: asset.name,
153
+ fix: "barndog sync",
154
+ });
155
+ if (metadata(entries, kind).name !== asset.name) {
156
+ throw new Error(`The server sent a package whose name isn't ${asset.name}`);
157
+ }
158
+ return entries;
159
+ });
160
+ }
@@ -1,3 +1,4 @@
1
+ import { GIT_MODE } from "./snapshot.js";
1
2
  import { execFile } from "node:child_process";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { rm } from "node:fs/promises";
@@ -5,86 +6,115 @@ import { join } from "node:path";
5
6
  import { promisify } from "node:util";
6
7
  import { normalizeRepositoryRemote } from "@barndog-ai/api-contract";
7
8
  import { CliError } from "../../errors.js";
8
- import { explainIdentity, git, GitError, gitReason, gitText } from "./git.js";
9
+ import { explainIdentity, git, GitError, gitReason, gitText, parseLsRemote, } from "./git.js";
10
+ /** Git SHA-1 object IDs contain forty hexadecimal digits. */
11
+ const SHA1_HEX_LENGTH = 40;
9
12
  const execute = promisify(execFile);
10
- const NULL_HASH = "0".repeat(40);
13
+ const NULL_HASH = "0".repeat(SHA1_HEX_LENGTH);
11
14
  /** Builds a commit in a bare repository using a throwaway index, never a checkout. */
12
- export async function commitFiles(repo, parent, change, message, options = {}) {
15
+ export async function commitFiles(repo, parent, change, options) {
16
+ const { runtime } = options;
13
17
  const index = join(repo, `barndog-index-${randomUUID()}`);
14
18
  const env = { GIT_INDEX_FILE: index };
15
19
  try {
16
- if (parent)
17
- await git(["read-tree", parent], { repo, env });
20
+ if (parent) {
21
+ await git(["read-tree", parent], runtime, { repo, env });
22
+ }
18
23
  const updates = [];
19
24
  if (parent && change.replace) {
20
- const listing = await git(["ls-tree", "-r", "-z", "--name-only", parent, "--", change.replace], { repo });
21
- for (const path of listing.toString("utf8").split("\0").filter(Boolean))
25
+ const listing = await git(["ls-tree", "-r", "-z", "--name-only", parent, "--", change.replace], runtime, { repo });
26
+ for (const path of listing.toString("utf8").split("\0").filter(Boolean)) {
22
27
  updates.push(`0 ${NULL_HASH}\t${path}`);
28
+ }
23
29
  }
24
30
  for (const file of change.files) {
25
- const hash = await gitText(["hash-object", "-w", "--stdin"], {
31
+ const hash = await gitText(["hash-object", "-w", "--stdin"], runtime, {
26
32
  repo,
27
33
  input: file.data,
28
34
  });
29
- updates.push(`${file.executable ? "100755" : "100644"} ${hash}\t${file.path}`);
35
+ updates.push(`${file.executable ? GIT_MODE.executable : GIT_MODE.file} ${hash}\t${file.path}`);
30
36
  }
31
- await git(["update-index", "-z", "--index-info"], {
37
+ await git(["update-index", "-z", "--index-info"], runtime, {
32
38
  repo,
33
39
  env,
34
40
  input: updates.join("\0") + "\0",
35
41
  });
36
- const tree = await gitText(["write-tree"], { repo, env });
37
- return await gitText(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", message], { repo, allowPrompt: options.allowPrompt }).catch(explainIdentity);
42
+ const tree = await gitText(["write-tree"], runtime, { repo, env });
43
+ return await gitText([
44
+ "commit-tree",
45
+ tree,
46
+ ...(parent ? ["-p", parent] : []),
47
+ "-m",
48
+ change.message,
49
+ ], runtime, { repo, allowPrompt: options.allowPrompt }).catch(explainIdentity);
38
50
  }
39
51
  finally {
40
52
  await rm(index, { force: true });
41
53
  await rm(`${index}.lock`, { force: true });
42
54
  }
43
55
  }
44
- export async function pushCommit(repo, commit, branch, allowPrompt = false) {
56
+ /**
57
+ * Pushes a commit to an origin branch; prompts are opt-in and Git rejections
58
+ * become CLI errors.
59
+ */
60
+ export async function pushCommit(repo, commit, branch, options) {
61
+ const { runtime, allowPrompt = false } = options;
45
62
  try {
46
- await git(["push", "--quiet", "origin", `${commit}:refs/heads/${branch}`], {
63
+ await git(["push", "--quiet", "origin", `${commit}:refs/heads/${branch}`], runtime, {
47
64
  repo,
48
65
  allowPrompt,
49
66
  });
50
67
  }
51
68
  catch (error) {
52
- if (error instanceof GitError)
69
+ if (error instanceof GitError) {
53
70
  throw new CliError(`The Git host rejected the push to ${branch}: ${gitReason(error.stderr)}`, undefined, { cause: error });
71
+ }
54
72
  throw error;
55
73
  }
56
74
  }
57
75
  /** The tip of a branch on the host, or null when it no longer exists. */
58
- export async function remoteBranch(repo, branch) {
59
- const output = await gitText(["ls-remote", "origin", `refs/heads/${branch}`], {
76
+ export async function remoteBranch(repo, branch, runtime) {
77
+ const output = await gitText(["ls-remote", "origin", `refs/heads/${branch}`], runtime, {
60
78
  repo,
61
79
  });
62
- return output ? output.split(/\s/)[0] : null;
80
+ return parseLsRemote(output)[0]?.commit ?? null;
63
81
  }
64
- export function hostOf(url) {
82
+ /**
83
+ * Extracts a normalized credential-free host and repository path from a remote
84
+ * URL; invalid remotes return null.
85
+ */
86
+ function hostOf(url) {
65
87
  const remote = normalizeRepositoryRemote(url);
66
- if (!remote)
88
+ if (!remote) {
67
89
  return null;
90
+ }
68
91
  const [host, ...path] = remote.split("/");
69
- if (!host || path.length < 2)
92
+ if (!host || path.length < 2) {
70
93
  return null;
94
+ }
71
95
  return { host, path: path.join("/") };
72
96
  }
73
97
  /** A browser link that starts a pull request, for hosts with a known URL shape. */
74
- export function compareUrl(url, base, branch) {
98
+ function compareUrl(url, base, branch) {
75
99
  const remote = hostOf(url);
76
- if (!remote)
100
+ if (!remote) {
77
101
  return null;
102
+ }
78
103
  const encoded = branch.split("/").map(encodeURIComponent).join("/");
79
- if (remote.host.includes("github"))
104
+ if (remote.host.includes("github")) {
80
105
  return `https://${remote.host}/${remote.path}/compare/${encodeURIComponent(base)}...${encoded}?expand=1`;
81
- if (remote.host.includes("gitlab"))
106
+ }
107
+ if (remote.host.includes("gitlab")) {
82
108
  return `https://${remote.host}/${remote.path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=${encodeURIComponent(branch)}&merge_request%5Btarget_branch%5D=${encodeURIComponent(base)}`;
109
+ }
83
110
  return null;
84
111
  }
85
- const signedIn = async (tool, host) => {
112
+ const signedIn = async (tool, host, runtime) => {
86
113
  try {
87
114
  await execute(tool, ["auth", "status", "--hostname", host], {
115
+ env: { ...runtime.env },
116
+ cwd: runtime.cwd,
117
+ windowsHide: true,
88
118
  timeout: 15_000,
89
119
  });
90
120
  return true;
@@ -93,24 +123,23 @@ const signedIn = async (tool, host) => {
93
123
  return false;
94
124
  }
95
125
  };
96
- const firstUrl = (text) => /https?:\/\/\S+/.exec(text)?.[0];
97
- /** Opens the review with gh or glab when signed in, else hands back a link. */
98
- export async function openPullRequest(request) {
99
- const { url, base, branch, title } = request;
100
- const remote = hostOf(url);
101
- const fallback = {
102
- url: compareUrl(url, base, branch) ?? undefined,
103
- opened: false,
104
- };
105
- if (!remote)
106
- return fallback;
107
- const command = remote.host.includes("github")
108
- ? [
126
+ /**
127
+ * The first web link in a tool's output: `Created https://github.com/o/r/pull/1` → the link.
128
+ *
129
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
130
+ */
131
+ export const firstUrl = (text) => /https?:\/\/\S+/.exec(text)?.[0];
132
+ /** The gh or glab command that opens a review of `branch` against `base`, if the host has one. */
133
+ function pullRequestCommand(remote, change) {
134
+ const repository = `${remote.host}/${remote.path}`;
135
+ const { base, branch, title } = change;
136
+ if (remote.host.includes("github")) {
137
+ return [
109
138
  "gh",
110
139
  "pr",
111
140
  "create",
112
141
  "--repo",
113
- `${remote.host}/${remote.path}`,
142
+ repository,
114
143
  "--head",
115
144
  branch,
116
145
  "--base",
@@ -119,29 +148,49 @@ export async function openPullRequest(request) {
119
148
  title,
120
149
  "--body",
121
150
  "",
122
- ]
123
- : remote.host.includes("gitlab")
124
- ? [
125
- "glab",
126
- "mr",
127
- "create",
128
- "-R",
129
- `${remote.host}/${remote.path}`,
130
- "-s",
131
- branch,
132
- "-b",
133
- base,
134
- "-t",
135
- title,
136
- "-d",
137
- "",
138
- "-y",
139
- ]
140
- : null;
141
- if (!command || !(await signedIn(command[0], remote.host)))
151
+ ];
152
+ }
153
+ if (remote.host.includes("gitlab")) {
154
+ return [
155
+ "glab",
156
+ "mr",
157
+ "create",
158
+ "-R",
159
+ repository,
160
+ "-s",
161
+ branch,
162
+ "-b",
163
+ base,
164
+ "-t",
165
+ title,
166
+ "-d",
167
+ "",
168
+ "-y",
169
+ ];
170
+ }
171
+ return null;
172
+ }
173
+ /** Opens the review with gh or glab when signed in, else hands back a link. */
174
+ export async function openPullRequest(request, runtime) {
175
+ const { url, base, branch, title } = request;
176
+ const remote = hostOf(url);
177
+ const fallback = {
178
+ url: compareUrl(url, base, branch) ?? undefined,
179
+ opened: false,
180
+ };
181
+ if (!remote) {
182
+ return fallback;
183
+ }
184
+ const command = pullRequestCommand(remote, { base, branch, title });
185
+ const [program, ...args] = command ?? [];
186
+ if (!program || !(await signedIn(program, remote.host, runtime))) {
142
187
  return fallback;
188
+ }
143
189
  try {
144
- const { stdout } = await execute(command[0], command.slice(1), {
190
+ const { stdout } = await execute(program, args, {
191
+ env: { ...runtime.env },
192
+ cwd: runtime.cwd,
193
+ windowsHide: true,
145
194
  timeout: 60_000,
146
195
  });
147
196
  return { url: firstUrl(stdout) ?? fallback.url, opened: true };
@@ -151,10 +200,12 @@ export async function openPullRequest(request) {
151
200
  }
152
201
  }
153
202
  /** Reports branch protection where the host will say; null means it can't tell. */
154
- export async function branchProtected(url, branch) {
203
+ export async function branchProtected(url, branch, runtime) {
155
204
  const remote = hostOf(url);
156
- if (!remote?.host.includes("github") || !(await signedIn("gh", remote.host)))
205
+ if (!remote?.host.includes("github") ||
206
+ !(await signedIn("gh", remote.host, runtime))) {
157
207
  return null;
208
+ }
158
209
  try {
159
210
  const { stdout } = await execute("gh", [
160
211
  "api",
@@ -163,7 +214,12 @@ export async function branchProtected(url, branch) {
163
214
  `repos/${remote.path}/branches/${encodeURIComponent(branch)}`,
164
215
  "--jq",
165
216
  ".protected",
166
- ], { timeout: 15_000 });
217
+ ], {
218
+ timeout: 15_000,
219
+ env: { ...runtime.env },
220
+ cwd: runtime.cwd,
221
+ windowsHide: true,
222
+ });
167
223
  return stdout.trim() === "true";
168
224
  }
169
225
  catch {