@uniqbit/mate-core 0.18.1-canary.0 → 0.18.1-canary.2

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 (61) hide show
  1. package/claude-plugin/hooks/session-banner.mjs +1 -1
  2. package/opencode-plugin/server.ts +5 -0
  3. package/opencode-plugin/src/add-dir.ts +118 -0
  4. package/opencode-plugin/src/companion.ts +180 -0
  5. package/opencode-plugin/src/server.ts +26 -0
  6. package/opencode-plugin/src/tui.tsx +1 -0
  7. package/opencode-plugin/tui.tsx +2 -0
  8. package/package.json +13 -6
  9. package/src/cli/commands/artifact/finish/engine.ts +1 -1
  10. package/src/cli/commands/artifact/finish/git.ts +75 -51
  11. package/src/cli/commands/companion/hub.ts +1 -1
  12. package/src/cli/commands/companion/link.ts +13 -59
  13. package/src/cli/commands/doctor.ts +30 -4
  14. package/src/cli/commands/install.ts +17 -1
  15. package/src/cli/commands/plugin/plugin.ts +0 -4
  16. package/src/cli/commands/report/formatter.ts +0 -4
  17. package/src/cli/commands/studio/selection.ts +3 -0
  18. package/src/cli/commands/studio/terminal-launch.ts +1 -51
  19. package/src/cli/commands/studio/terminal.ts +2 -13
  20. package/src/cli/commands/studio/vault.ts +5 -3
  21. package/src/cli/commands/studio/views/workflow/steps.ts +5 -4
  22. package/src/cli/commands/update.ts +4 -20
  23. package/src/cli/commands/working/cleanup.ts +4 -1
  24. package/src/cli/launch-selector.tsx +0 -318
  25. package/src/cli/main.ts +0 -29
  26. package/src/cli/setup-selector.tsx +1 -1
  27. package/src/cli/usage.ts +0 -1
  28. package/src/hooks/session-banner.ts +7 -5
  29. package/src/hooks/validate-artifact-path.ts +17 -6
  30. package/src/lib/opencode-plugin-package.ts +7 -28
  31. package/src/lib/orchestrator/adapters/opencode.ts +28 -67
  32. package/src/lib/orchestrator/companion-git-sync.ts +29 -93
  33. package/src/lib/orchestrator/companion-hub.ts +71 -110
  34. package/src/lib/orchestrator/repo-local-registry.ts +0 -21
  35. package/src/lib/orchestrator/types.ts +0 -6
  36. package/src/lib/orchestrator/working-repo-projection.ts +13 -9
  37. package/src/lib/package-paths.ts +32 -0
  38. package/src/lib/prebuilt-workspace.ts +0 -3
  39. package/src/opencode/companion-hooks.ts +15 -10
  40. package/src/runtime/companion-git.ts +327 -84
  41. package/src/runtime/companion-sync.ts +34 -43
  42. package/src/runtime/index.ts +7 -5
  43. package/src/templates/mate-skills/agents/mate-domain-modeling/SKILL.md +2 -2
  44. package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +25 -0
  45. package/src/templates/mate-skills/agents/mate-grilling/SKILL.md +9 -7
  46. package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +34 -4
  47. package/src/templates/mate-skills/claude/mate-domain-modeling/SKILL.md +2 -2
  48. package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +25 -0
  49. package/src/templates/mate-skills/claude/mate-grilling/SKILL.md +9 -7
  50. package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +34 -4
  51. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +68 -77
  52. package/src/tools/setup/capabilities/graphify.ts +0 -4
  53. package/src/tools/setup/dynamic-plugins/frozen.ts +24 -3
  54. package/src/tools/setup/dynamic-plugins/loader.ts +16 -0
  55. package/src/tools/setup/dynamic-plugins/policy.ts +55 -0
  56. package/src/tools/setup/dynamic-plugins/staging.ts +55 -0
  57. package/src/tools/setup/dynamic-plugins/verify.ts +22 -18
  58. package/src/tools/setup/providers/opencode-format.ts +4 -0
  59. package/src/tools/setup/providers/opencode.ts +9 -65
  60. package/src/tools/setup/runtime-documents.ts +8 -9
  61. package/src/cli/commands/plugin/verify.ts +0 -29
@@ -149,7 +149,7 @@ export async function repairCompanionGitOnce(
149
149
  * unattended. The V2 server API has no toast; the notes reach the operator
150
150
  * through the persisted record and the TUI's staleness lines.
151
151
  */
152
- return unattendedSyncStalenessLines(syncCompanionUnattended(context.companionPath));
152
+ return unattendedSyncStalenessLines(await syncCompanionUnattended(context.companionPath));
153
153
  }
154
154
 
155
155
  /** Test seam: the once-per-session guard is process-wide by design. */
@@ -164,21 +164,25 @@ export function resetCompanionGitRepairGuard(): void {
164
164
  * reason — including the launch-environment gate that keeps a Managed
165
165
  * Launch's Git decision authoritative for the session it started.
166
166
  */
167
- export function refuseForkedCompanionWrite(
167
+ export async function refuseForkedCompanionWrite(
168
168
  context: CompanionContext,
169
169
  filePath: string,
170
170
  env: Record<string, string | undefined> = process.env,
171
- ): void {
171
+ ): Promise<void> {
172
172
  if (!filePath || !isArtifactPath(filePath)) return;
173
173
  if (!normalizeTargetPath(context, filePath).startsWith(path.normalize(context.companionPath))) {
174
174
  return;
175
175
  }
176
- const refusal = companionForkRefusal(env, context.companionPath);
176
+ const refusal = await companionForkRefusal(env, context.companionPath);
177
177
  if (refusal) throw new Error(refusal);
178
178
  }
179
179
 
180
- /** Throws when the tool call would write an artifact outside the companion. */
181
- export function guardToolInput(context: CompanionContext, tool: string, input: unknown): void {
180
+ /** Rejects when the tool call would write an artifact outside the companion. */
181
+ export async function guardToolInput(
182
+ context: CompanionContext,
183
+ tool: string,
184
+ input: unknown,
185
+ ): Promise<void> {
182
186
  const args = (input ?? {}) as Record<string, unknown>;
183
187
  const filePaths =
184
188
  tool === "write" || tool === "edit"
@@ -191,7 +195,8 @@ export function guardToolInput(context: CompanionContext, tool: string, input: u
191
195
  if (context.repositoryPath && filePath && shouldBlockArtifactWrite(context, filePath)) {
192
196
  throw new Error(buildArtifactError(context, filePath));
193
197
  }
194
- refuseForkedCompanionWrite(context, filePath);
198
+ // oxlint-disable-next-line no-await-in-loop -- the first refusal wins
199
+ await refuseForkedCompanionWrite(context, filePath);
195
200
  }
196
201
  }
197
202
 
@@ -215,9 +220,9 @@ export async function registerCompanionHooks(
215
220
  */
216
221
  await repairCompanionGitOnce(context).catch(() => []);
217
222
 
218
- await api.tool.hook("execute.before", (event) => {
219
- guardToolInput(context, event.tool, event.input);
220
- });
223
+ await api.tool.hook("execute.before", (event) =>
224
+ guardToolInput(context, event.tool, event.input),
225
+ );
221
226
 
222
227
  if (!context.repositoryPath || !context.reactDoctorEnabled) return;
223
228
 
@@ -1,16 +1,20 @@
1
1
  /**
2
- * Git primitives shared by the launch preflight and the session-runtime
3
- * surfaces. Upstream-ref resolution lives here because two callers depend on
4
- * meaning the same ref: `CompanionGitSync` (async, injectable runner) and the
5
- * hooks (synchronous `spawnSync`). The resolution is expressed once as a step
6
- * generator that both drivers run, so the two can never disagree.
2
+ * Companion Git: the one place remote-facing Git on a Companion Repository is
3
+ * run. It owns the policy every caller shares (inherited `GIT_*` overrides
4
+ * cleared, SSH first for HTTP(S) remotes, one prompt decision for Git and SSH,
5
+ * one time budget per operation) and the decision steps every synchronization
6
+ * shares (upstream target, fork state). Callers keep only their tails.
7
7
  */
8
- import { spawnSync } from "node:child_process";
8
+ import { spawn, type ChildProcess } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import path from "node:path";
9
11
 
10
12
  export interface GitResult {
11
13
  status: number;
12
14
  stdout: string;
13
15
  stderr: string;
16
+ /** The operation's time bound ended the command, or kept it from starting. */
17
+ timedOut?: boolean;
14
18
  }
15
19
 
16
20
  export interface UpstreamTarget {
@@ -19,9 +23,6 @@ export interface UpstreamTarget {
19
23
  ref: string;
20
24
  }
21
25
 
22
- /** Bounded but far above any diagnostic output; 1 MiB truncates large fetches. */
23
- const GIT_MAX_BUFFER = 64 * 1024 * 1024;
24
-
25
26
  /** Refs already local: no network, so a small bound is generous. */
26
27
  export const GIT_QUERY_TIMEOUT_MS = 5_000;
27
28
 
@@ -61,9 +62,58 @@ export function isAuthenticationFailure(result: GitResult): boolean {
61
62
  ].some((marker) => output.includes(marker));
62
63
  }
63
64
 
65
+ /** `git@host:path` (`ssh://` when a port is given) for an HTTP(S) Git URL; `null` otherwise. */
66
+ export function toSshUrl(url: string): string | null {
67
+ try {
68
+ const parsed = new URL(url.trim());
69
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
70
+ if (!parsed.hostname || parsed.pathname === "/") return null;
71
+
72
+ const repositoryPath = parsed.pathname.replace(/^\/+/, "");
73
+ if (!repositoryPath) return null;
74
+
75
+ if (!parsed.port) return `git@${parsed.hostname}:${repositoryPath}`;
76
+ return `ssh://git@${parsed.hostname}:${parsed.port}/${repositoryPath}`;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /** Lists every configured remote URL, one `remote.<name>.<key> <url>` per line. */
83
+ export const REMOTE_URLS_QUERY: readonly string[] = [
84
+ "config",
85
+ "--get-regexp",
86
+ String.raw`^remote\..+\.(url|pushurl)$`,
87
+ ];
88
+
89
+ /**
90
+ * `-c url.<ssh>.insteadOf=<https>` per HTTP(S) remote in `REMOTE_URLS_QUERY`
91
+ * output, so one invocation reaches every remote over SSH without rewriting
92
+ * the stored configuration. Empty when no remote is HTTP(S).
93
+ */
94
+ export function sshRewriteArgs(remoteUrlsOutput: string): string[] {
95
+ const urls = new Set(
96
+ outputLines(remoteUrlsOutput).flatMap((line) => {
97
+ const url = line.slice(line.indexOf(" ") + 1).trim();
98
+ return url ? [url] : [];
99
+ }),
100
+ );
101
+ return [...urls].flatMap((url) => {
102
+ const ssh = toSshUrl(url);
103
+ return ssh ? ["-c", `url.${ssh}.insteadOf=${url}`] : [];
104
+ });
105
+ }
106
+
107
+ /** A remote rejection is a verdict the configured URL would repeat; anything else may be SSH-only. */
108
+ export function shouldRetryWithoutSsh(result: GitResult): boolean {
109
+ if (result.status === 0) return false;
110
+ return !/\[(?:remote )?rejected\]/.test(`${result.stderr}\n${result.stdout}`);
111
+ }
112
+
64
113
  /**
65
114
  * Inherited `GIT_*` overrides would point Git at the session's own repository
66
- * rather than the companion, so they are stripped from every invocation.
115
+ * rather than the one named, so they are stripped from every invocation.
116
+ * Prompting is not decided here.
67
117
  */
68
118
  export function gitEnvironment(
69
119
  env: Record<string, string | undefined> = process.env,
@@ -73,32 +123,270 @@ export function gitEnvironment(
73
123
  GIT_WORK_TREE: _gitWorkTree,
74
124
  GIT_COMMON_DIR: _gitCommonDir,
75
125
  GIT_INDEX_FILE: _gitIndexFile,
76
- GIT_TERMINAL_PROMPT: _gitTerminalPrompt,
77
126
  ...rest
78
127
  } = env;
79
- return { ...rest, GIT_TERMINAL_PROMPT: "0" };
128
+ return rest;
129
+ }
130
+
131
+ /**
132
+ * Who may answer a prompt. One decision covers Git credential prompts and SSH
133
+ * passphrase and host-key prompts together; `if-terminal` without a TTY is
134
+ * `never`.
135
+ */
136
+ export type GitPromptIntent = "never" | "if-terminal";
137
+
138
+ export type GitTransport = "ssh" | "http" | "other";
139
+
140
+ export interface NetworkGitResult extends GitResult {
141
+ /** Transport of the attempt whose result this is. */
142
+ transport: GitTransport;
80
143
  }
81
144
 
82
- /** Never throws: an absent Git binary and an exceeded bound are ordinary results. */
83
- export function runGitSync(
145
+ export interface CompanionGitOptions {
146
+ prompt: GitPromptIntent;
147
+ /** Bound on the whole operation, every command and fallback included. Unbounded when absent. */
148
+ budgetMs?: number;
149
+ /** Bound on each local command, applied within `budgetMs`. */
150
+ commandCapMs?: number;
151
+ env?: Record<string, string | undefined>;
152
+ }
153
+
154
+ export interface CompanionGit {
155
+ /** Local command, captured. */
156
+ run(args: readonly string[]): Promise<GitResult>;
157
+ /** `git fetch <args>`, SSH first for HTTP(S) remotes. */
158
+ fetch(args?: readonly string[]): Promise<NetworkGitResult>;
159
+ /** `git push <args>`, SSH first for HTTP(S) remotes. */
160
+ push(args?: readonly string[]): Promise<NetworkGitResult>;
161
+ /** Clones `url` into `destination` (relative to the operation's directory), SSH first for HTTP(S). */
162
+ clone(url: string, destination: string, options?: { branch?: string }): Promise<NetworkGitResult>;
163
+ upstreamTarget(): Promise<UpstreamTarget | null>;
164
+ /** Against `ref`, else the resolved upstream target. Local refs only; never fetches. */
165
+ forkState(ref?: string): Promise<CompanionForkState | null>;
166
+ }
167
+
168
+ export const companionGitDeps = {
169
+ isTerminal: (): boolean => Boolean(process.stdin.isTTY && process.stdout.isTTY),
170
+ };
171
+
172
+ const SSH_URL = /^(?:ssh:\/\/|[^/@:\s]+@[^/:\s]+:)/i;
173
+
174
+ function transportOf(url: string): GitTransport {
175
+ if (/^https?:\/\//i.test(url)) return "http";
176
+ return SSH_URL.test(url) ? "ssh" : "other";
177
+ }
178
+
179
+ /** Of `REMOTE_URLS_QUERY` lines: SSH if any remote uses it, else HTTP if any does. */
180
+ function configuredTransport(remoteUrlLines: string[]): GitTransport {
181
+ const transports = new Set(remoteUrlLines.map((line) => transportOf(line.split(" ")[1] ?? "")));
182
+ if (transports.has("ssh")) return "ssh";
183
+ if (transports.has("http")) return "http";
184
+ return "other";
185
+ }
186
+
187
+ function shellQuote(value: string): string {
188
+ return `'${value.replaceAll("'", `'\\''`)}'`;
189
+ }
190
+
191
+ function decode(chunks: Buffer[]): string {
192
+ return Buffer.concat(chunks).toString("utf8");
193
+ }
194
+
195
+ function spawnGit(
84
196
  cwd: string,
85
197
  args: readonly string[],
86
- timeoutMs: number = GIT_QUERY_TIMEOUT_MS,
87
- ): GitResult {
88
- const result = spawnSync("git", [...args], {
89
- cwd,
90
- encoding: "utf8",
91
- env: gitEnvironment(),
92
- maxBuffer: GIT_MAX_BUFFER,
93
- timeout: Math.max(1, timeoutMs),
198
+ env: Record<string, string | undefined>,
199
+ options: { interactive: boolean; timeoutMs?: number },
200
+ ): Promise<GitResult> {
201
+ return new Promise((resolve) => {
202
+ let settled = false;
203
+ let timer: ReturnType<typeof setTimeout> | undefined;
204
+ const stdout: Buffer[] = [];
205
+ const stderr: Buffer[] = [];
206
+ const finish = (result: GitResult) => {
207
+ if (settled) return;
208
+ settled = true;
209
+ if (timer) clearTimeout(timer);
210
+ resolve(result);
211
+ };
212
+
213
+ let child: ChildProcess;
214
+ try {
215
+ child = spawn("git", [...args], {
216
+ cwd,
217
+ env,
218
+ /** Interactive output goes to stderr so a caller's stdout (e.g. `--json`) stays clean. */
219
+ stdio: options.interactive ? ["inherit", 2, "inherit"] : ["ignore", "pipe", "pipe"],
220
+ });
221
+ } catch (error) {
222
+ finish({ status: 1, stdout: "", stderr: (error as Error).message });
223
+ return;
224
+ }
225
+ child.stdout?.on("data", (chunk: Buffer) => stdout.push(chunk));
226
+ child.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk));
227
+ child.once("error", (error) => finish({ status: 1, stdout: "", stderr: error.message }));
228
+ child.once("close", (status) =>
229
+ finish({ status: status ?? 1, stdout: decode(stdout), stderr: decode(stderr) }),
230
+ );
231
+ if (options.timeoutMs !== undefined) {
232
+ /** Resolved without awaiting `close`: an SSH grandchild may hold the pipes open. */
233
+ timer = setTimeout(
234
+ () => {
235
+ child.kill("SIGKILL");
236
+ finish({
237
+ status: 1,
238
+ stdout: decode(stdout),
239
+ stderr:
240
+ `${decode(stderr)}\ngit ${args.join(" ")}: exceeded the operation's time bound`.trim(),
241
+ timedOut: true,
242
+ });
243
+ },
244
+ Math.max(1, options.timeoutMs),
245
+ );
246
+ }
94
247
  });
95
- if (result.error) {
96
- return { status: 1, stdout: result.stdout ?? "", stderr: result.error.message };
248
+ }
249
+
250
+ /**
251
+ * `GIT_TERMINAL_PROMPT=0` leaves askpass helpers (an editor's credential UI)
252
+ * free to prompt, so `never` clears every askpass source: both variables, and
253
+ * `core.askPass` through an appended `GIT_CONFIG_*` entry.
254
+ */
255
+ function withoutAskPass(
256
+ env: Record<string, string | undefined>,
257
+ ): Record<string, string | undefined> {
258
+ const { GIT_ASKPASS: _gitAskPass, SSH_ASKPASS: _sshAskPass, ...rest } = env;
259
+ const count = Number.parseInt(rest.GIT_CONFIG_COUNT ?? "0", 10) || 0;
260
+ return {
261
+ ...rest,
262
+ SSH_ASKPASS_REQUIRE: "never",
263
+ GIT_CONFIG_COUNT: String(count + 1),
264
+ [`GIT_CONFIG_KEY_${count}`]: "core.askPass",
265
+ [`GIT_CONFIG_VALUE_${count}`]: "",
266
+ };
267
+ }
268
+
269
+ /** The operation's policy is fixed when it is opened; every step below inherits it. */
270
+ export function companionGit(
271
+ cwd: string,
272
+ options: CompanionGitOptions,
273
+ deps: typeof companionGitDeps = companionGitDeps,
274
+ ): CompanionGit {
275
+ const baseEnv = gitEnvironment(options.env ?? process.env);
276
+ const mayPrompt = options.prompt === "if-terminal" && deps.isTerminal();
277
+ const deadline =
278
+ options.budgetMs === undefined ? Number.POSITIVE_INFINITY : Date.now() + options.budgetMs;
279
+ const capturedEnv = mayPrompt
280
+ ? { ...baseEnv, GIT_TERMINAL_PROMPT: "0" }
281
+ : withoutAskPass({ ...baseEnv, GIT_TERMINAL_PROMPT: "0" });
282
+ const { GIT_TERMINAL_PROMPT: _prompt, ...promptingEnv } = baseEnv;
283
+ let networkEnv: Promise<Record<string, string | undefined>> | undefined;
284
+
285
+ async function exec(
286
+ args: readonly string[],
287
+ env: Record<string, string | undefined>,
288
+ { interactive = false, capMs }: { interactive?: boolean; capMs?: number } = {},
289
+ ): Promise<GitResult> {
290
+ const remaining = deadline - Date.now();
291
+ if (remaining <= 0) {
292
+ return {
293
+ status: 1,
294
+ stdout: "",
295
+ stderr: `git ${args.join(" ")}: not started, the operation's time bound is spent`,
296
+ timedOut: true,
297
+ };
298
+ }
299
+ const timeoutMs = Math.min(remaining, capMs ?? Number.POSITIVE_INFINITY);
300
+ return spawnGit(cwd, args, env, {
301
+ interactive,
302
+ timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : undefined,
303
+ });
304
+ }
305
+
306
+ const run = (args: readonly string[]) => exec(args, capturedEnv, { capMs: options.commandCapMs });
307
+
308
+ /**
309
+ * `never` appends `BatchMode=yes` to the SSH command Git would use anyway
310
+ * (`GIT_SSH_COMMAND`, `GIT_SSH`, `core.sshCommand`, then `ssh`), so SSH
311
+ * neither asks for a passphrase nor confirms a host key.
312
+ */
313
+ function sshEnv(): Promise<Record<string, string | undefined>> {
314
+ networkEnv ??= (async () => {
315
+ if (mayPrompt) return capturedEnv;
316
+ let command = baseEnv.GIT_SSH_COMMAND;
317
+ if (!command && baseEnv.GIT_SSH) command = shellQuote(baseEnv.GIT_SSH);
318
+ if (!command) {
319
+ const configured = await run(["config", "--get", "core.sshCommand"]);
320
+ command = configured.status === 0 ? configured.stdout.trim() : "";
321
+ }
322
+ return {
323
+ ...capturedEnv,
324
+ GIT_SSH_COMMAND: `${command || "ssh"} -o BatchMode=yes`,
325
+ };
326
+ })();
327
+ return networkEnv;
328
+ }
329
+
330
+ /** Only the configured-URL attempt may own the terminal; the SSH attempt stays captured. */
331
+ async function attempt(
332
+ args: readonly string[],
333
+ transport: GitTransport,
334
+ configured: boolean,
335
+ ): Promise<NetworkGitResult> {
336
+ const interactive = configured && mayPrompt;
337
+ const env = interactive ? promptingEnv : await sshEnv();
338
+ const result = await exec(args, env, { interactive });
339
+ return { ...result, transport };
340
+ }
341
+
342
+ async function remoteNetwork(args: readonly string[]): Promise<NetworkGitResult> {
343
+ const remotes = await run(REMOTE_URLS_QUERY);
344
+ const rewrite = remotes.status === 0 ? sshRewriteArgs(remotes.stdout) : [];
345
+ if (rewrite.length > 0) {
346
+ const overSsh = await attempt([...rewrite, ...args], "ssh", false);
347
+ if (!shouldRetryWithoutSsh(overSsh) || overSsh.timedOut) return overSsh;
348
+ return attempt(args, "http", true);
349
+ }
350
+ const urls = remotes.status === 0 ? outputLines(remotes.stdout) : [];
351
+ return attempt(args, configuredTransport(urls), true);
352
+ }
353
+
354
+ async function forkStateAt(ref: string): Promise<CompanionForkState | null> {
355
+ const counts = await run(["rev-list", "--left-right", "--count", `${ref}...HEAD`]);
356
+ if (counts.status !== 0) return null;
357
+ const [behind, ahead] = counts.stdout.trim().split(/\s+/).map(Number);
358
+ if (!Number.isFinite(ahead) || !Number.isFinite(behind)) return null;
359
+ return { ahead, behind, forked: ahead > 0 && behind > 0 };
97
360
  }
361
+
362
+ const upstreamTarget = () => resolveUpstreamTarget(run);
363
+
98
364
  return {
99
- status: result.status ?? 1,
100
- stdout: result.stdout ?? "",
101
- stderr: result.stderr ?? "",
365
+ run,
366
+ fetch: (args = []) => remoteNetwork(["fetch", ...args]),
367
+ push: (args = []) => remoteNetwork(["push", ...args]),
368
+ async clone(url, destination, { branch } = {}) {
369
+ const cloneArgs = ["clone", ...(branch ? ["--branch", branch] : []), url, destination];
370
+ const ssh = toSshUrl(url);
371
+ if (ssh) {
372
+ const existed = fs.existsSync(path.resolve(cwd, destination));
373
+ const overSsh = await attempt(
374
+ ["-c", `url.${ssh}.insteadOf=${url}`, ...cloneArgs],
375
+ "ssh",
376
+ false,
377
+ );
378
+ if (!shouldRetryWithoutSsh(overSsh) || overSsh.timedOut) return overSsh;
379
+ if (!existed) fs.rmSync(path.resolve(cwd, destination), { recursive: true, force: true });
380
+ return attempt(cloneArgs, "http", true);
381
+ }
382
+ return attempt(cloneArgs, transportOf(url), true);
383
+ },
384
+ upstreamTarget,
385
+ async forkState(ref) {
386
+ if (ref) return forkStateAt(ref);
387
+ const target = await upstreamTarget();
388
+ return target ? forkStateAt(target.ref) : null;
389
+ },
102
390
  };
103
391
  }
104
392
 
@@ -110,56 +398,30 @@ function parseRemoteRef(stdout: string): UpstreamTarget | undefined {
110
398
  }
111
399
 
112
400
  /**
113
- * The single definition of "which upstream does this companion mean":
114
- * the branch's `@{u}`, then `origin/HEAD`, then an available `origin/main` or
115
- * `origin/master`. Yields argv, receives the result — so a synchronous and an
116
- * asynchronous driver share one decision procedure.
401
+ * The single definition of "which upstream does this companion mean": the
402
+ * branch's `@{u}`, then `origin/HEAD`, then an available `origin/main` or
403
+ * `origin/master`.
117
404
  */
118
- export function* upstreamTargetSteps(): Generator<
119
- readonly string[],
120
- UpstreamTarget | null,
121
- GitResult
122
- > {
123
- const upstream = yield ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"];
405
+ async function resolveUpstreamTarget(
406
+ run: (args: readonly string[]) => Promise<GitResult>,
407
+ ): Promise<UpstreamTarget | null> {
408
+ const upstream = await run(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
124
409
  const configured = parseRemoteRef(upstream.stdout);
125
410
  if (upstream.status === 0 && configured) return configured;
126
411
 
127
- const remoteHead = yield ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"];
412
+ const remoteHead = await run(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
128
413
  const fromRemoteHead = parseRemoteRef(remoteHead.stdout);
129
414
  if (remoteHead.status === 0 && fromRemoteHead) return fromRemoteHead;
130
415
 
131
416
  for (const branch of ["main", "master"]) {
132
- const exists = yield ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`];
417
+ // oxlint-disable-next-line no-await-in-loop -- the steps are a decision chain
418
+ const exists = await run(["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`]);
133
419
  if (exists.status === 0) return { remote: "origin", branch, ref: `origin/${branch}` };
134
420
  }
135
421
 
136
422
  return null;
137
423
  }
138
424
 
139
- export function resolveUpstreamTargetSync(
140
- companionPath: string,
141
- timeoutMs: number = GIT_QUERY_TIMEOUT_MS,
142
- ): UpstreamTarget | null {
143
- const steps = upstreamTargetSteps();
144
- let step = steps.next();
145
- while (!step.done) {
146
- step = steps.next(runGitSync(companionPath, step.value, timeoutMs));
147
- }
148
- return step.value;
149
- }
150
-
151
- export async function resolveUpstreamTargetWith(
152
- run: (args: readonly string[]) => Promise<GitResult>,
153
- ): Promise<UpstreamTarget | null> {
154
- const steps = upstreamTargetSteps();
155
- let step = steps.next();
156
- while (!step.done) {
157
- // oxlint-disable-next-line no-await-in-loop -- the steps are a decision chain
158
- step = steps.next(await run(step.value));
159
- }
160
- return step.value;
161
- }
162
-
163
425
  export interface CompanionForkState {
164
426
  ahead: number;
165
427
  behind: number;
@@ -179,25 +441,6 @@ export interface CompanionForkState {
179
441
  export function companionForkState(
180
442
  companionPath: string,
181
443
  timeoutMs: number = GIT_QUERY_TIMEOUT_MS,
182
- ): CompanionForkState | null {
183
- const target = resolveUpstreamTargetSync(companionPath, timeoutMs);
184
- if (!target) return null;
185
- return forkStateAgainst(companionPath, target.ref, timeoutMs);
186
- }
187
-
188
- export function forkStateAgainst(
189
- companionPath: string,
190
- ref: string,
191
- timeoutMs: number = GIT_QUERY_TIMEOUT_MS,
192
- ): CompanionForkState | null {
193
- const counts = runGitSync(
194
- companionPath,
195
- ["rev-list", "--left-right", "--count", `${ref}...HEAD`],
196
- timeoutMs,
197
- );
198
- if (counts.status !== 0) return null;
199
-
200
- const [behind, ahead] = counts.stdout.trim().split(/\s+/).map(Number);
201
- if (!Number.isFinite(ahead) || !Number.isFinite(behind)) return null;
202
- return { ahead, behind, forked: ahead > 0 && behind > 0 };
444
+ ): Promise<CompanionForkState | null> {
445
+ return companionGit(companionPath, { prompt: "never", commandCapMs: timeoutMs }).forkState();
203
446
  }