opencode-model-router 2.8.0 → 2.9.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.
- package/CHANGELOG.md +364 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
|
@@ -0,0 +1,1214 @@
|
|
|
1
|
+
// src/executor/git.ts
|
|
2
|
+
// Phase 2.4.2: hardened git operations for the executor (design memo 2.4.1 §2 in
|
|
3
|
+
// docs/qa/critical-path-execution/phase-2.4.md). Every git call goes through an injected `GitRunner`, which never
|
|
4
|
+
// spawns a shell; hooks never run (empty `core.hooksPath` directory), signing and editors are off, and an in-slot call
|
|
5
|
+
// never trusts the slot's own `.git` (explicit `--git-dir`/`--work-tree` after `verifySlotPointers`).
|
|
6
|
+
|
|
7
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
8
|
+
import {
|
|
9
|
+
gitEnvironment, gitExecutable, gitPointers, hardeningArgs, isNetworkOrDevicePath, spawnBounded, stripUrlUserinfo,
|
|
10
|
+
workRootGuards,
|
|
11
|
+
} from "../router/git-tools";
|
|
12
|
+
import {
|
|
13
|
+
ExecutorError, GIT_ID_PATTERN, PLAN_ID_PATTERN, WIP_TRAILER,
|
|
14
|
+
type FileSystem, type GitRunner, type JsonValue, type PhaseId, type PlanId, type ProcessResult, type ProcOpts,
|
|
15
|
+
type TaskId, type TaskNode,
|
|
16
|
+
} from "./types";
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
19
|
+
// §2.1 Runner and argv
|
|
20
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
export const MIN_GIT_VERSION = [2, 33, 0] as const;
|
|
23
|
+
export const GIT_OP_TIMEOUT_MS = 120_000;
|
|
24
|
+
export const GIT_WORKTREE_ADD_TIMEOUT_MS = 600_000;
|
|
25
|
+
export const GIT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
26
|
+
/** Bytes of stderr kept in an `E_GIT` detail. */
|
|
27
|
+
const GIT_STDERR_TAIL_BYTES = 2048;
|
|
28
|
+
|
|
29
|
+
/** Error a production `GitRunner` throws; `code` is `ETIMEDOUT`, `EOUTPUT` or `ABORT_ERR`. */
|
|
30
|
+
class GitRunnerError extends Error {
|
|
31
|
+
readonly code: "ETIMEDOUT" | "EOUTPUT" | "ABORT_ERR";
|
|
32
|
+
constructor(code: "ETIMEDOUT" | "EOUTPUT" | "ABORT_ERR", message: string) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = "GitRunnerError";
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Variables that would redirect a "user" mode git call to another repository, object store or namespace. */
|
|
40
|
+
const USER_MODE_DROPPED_ENV: ReadonlySet<string> = new Set([
|
|
41
|
+
"GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY",
|
|
42
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE", "GIT_CEILING_DIRECTORIES",
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
function userEnvironment(extra: Readonly<Record<string, string>> | undefined): NodeJS.ProcessEnv {
|
|
46
|
+
const merged: NodeJS.ProcessEnv = { ...process.env, ...(extra ?? {}) };
|
|
47
|
+
const out: NodeJS.ProcessEnv = {};
|
|
48
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
49
|
+
if (!USER_MODE_DROPPED_ENV.has(key.toUpperCase())) out[key] = value;
|
|
50
|
+
}
|
|
51
|
+
out.GIT_TERMINAL_PROMPT = "0";
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Hardened env: `gitEnvironment(extra)` with the C locale forced (`LC_ALL=C`, `LANGUAGE=`), so the git messages the
|
|
57
|
+
* executor parses (`Would remove ...`) are never translated.
|
|
58
|
+
*/
|
|
59
|
+
export function hardenedEnvironment(extra: Readonly<Record<string, string>> | undefined): NodeJS.ProcessEnv {
|
|
60
|
+
const env: NodeJS.ProcessEnv = { ...gitEnvironment({ ...(extra ?? {}) }) };
|
|
61
|
+
for (const key of Object.keys(env)) {
|
|
62
|
+
const upper = key.toUpperCase();
|
|
63
|
+
if (upper === "LC_ALL" || upper === "LANGUAGE") delete env[key];
|
|
64
|
+
}
|
|
65
|
+
env.LC_ALL = "C";
|
|
66
|
+
env.LANGUAGE = "";
|
|
67
|
+
return env;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Production GitRunner: `spawnBounded(gitExecutable(workRootGuards(toplevel)), args, cwd, {env, timeoutMs, maxBytes, signal})`.
|
|
72
|
+
* mode "hardened": env = `gitEnvironment(o.env ?? {})` (`o.env` is EXTRA, never a replacement) with `LC_ALL=C` and an
|
|
73
|
+
* empty `LANGUAGE` forced.
|
|
74
|
+
* mode "user": the process environment minus GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR, GIT_INDEX_FILE,
|
|
75
|
+
* GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES, GIT_NAMESPACE and GIT_CEILING_DIRECTORIES, plus
|
|
76
|
+
* GIT_TERMINAL_PROMPT=0; used for the identity read only.
|
|
77
|
+
* A timeout throws `{code: "ETIMEDOUT"}`, truncated output `{code: "EOUTPUT"}`, an abort `{code: "ABORT_ERR"}`.
|
|
78
|
+
* Never a shell (git-tools `spawnBounded` spawns with `shell: false`).
|
|
79
|
+
*/
|
|
80
|
+
export function createGitRunner(o: { mode: "hardened" | "user"; toplevel: string }): GitRunner {
|
|
81
|
+
let executable: string | undefined;
|
|
82
|
+
return {
|
|
83
|
+
async run(args: readonly string[], p: ProcOpts): Promise<ProcessResult> {
|
|
84
|
+
try { p.service?.prepare(); } catch { /* Diagnostics only. */ }
|
|
85
|
+
try {
|
|
86
|
+
if (p.stdin !== undefined) throw new Error("the git runner does not support stdin");
|
|
87
|
+
executable ??= gitExecutable(workRootGuards(o.toplevel));
|
|
88
|
+
const env = o.mode === "hardened" ? hardenedEnvironment(p.env) : userEnvironment(p.env);
|
|
89
|
+
const started = Date.now();
|
|
90
|
+
const bounds = { env, timeoutMs: p.timeoutMs, maxBytes: p.maxOutputBytes ?? GIT_MAX_OUTPUT_BYTES, settleOnFailure: true,
|
|
91
|
+
...(p.service === undefined ? {} : { service: p.service }) };
|
|
92
|
+
const result = await spawnBounded(executable, args, p.cwd, p.signal === undefined ? bounds : { ...bounds, signal: p.signal });
|
|
93
|
+
if (result.failure !== undefined) {
|
|
94
|
+
throw new GitRunnerError(result.failure.endsWith("timed out") ? "ETIMEDOUT" : "ABORT_ERR", result.failure);
|
|
95
|
+
}
|
|
96
|
+
if (result.truncated) throw new GitRunnerError("EOUTPUT", `git output exceeds ${bounds.maxBytes} bytes`);
|
|
97
|
+
return {
|
|
98
|
+
code: result.code, signal: null, stdout: result.output.toString("utf8"), stderr: result.stderr.toString("utf8"),
|
|
99
|
+
truncated: false, durationMs: Date.now() - started,
|
|
100
|
+
};
|
|
101
|
+
} finally {
|
|
102
|
+
// Preparation can throw before spawnBounded owns the hook. Its completed child is already closed here.
|
|
103
|
+
try { p.service?.end("error"); } catch { /* Diagnostics only. */ }
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface GitContext {
|
|
110
|
+
/** `<home>\git\no-hooks`: an empty real directory created by the executor. */
|
|
111
|
+
hooksDir: string;
|
|
112
|
+
/** `<home>\git\slot-excludes`. */
|
|
113
|
+
excludesFile: string;
|
|
114
|
+
/** DV6 snapshot of the user's line-ending configuration. */
|
|
115
|
+
conversion: { autocrlf: string | null; eol: string | null };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* `hardeningArgs()` (git-tools) then, in this order (a later `-c` wins over the NUL hooksPath it sets):
|
|
120
|
+
* core.longpaths, core.hooksPath, core.excludesFile, core.editor, sequence.editor, the signing switches, the
|
|
121
|
+
* rebase/merge switches, rerere, submodule.recurse, advice.detachedHead, user.useConfigOnly, then core.autocrlf and
|
|
122
|
+
* core.eol when the snapshot has them.
|
|
123
|
+
*/
|
|
124
|
+
export function executorGitArgs(c: GitContext): string[] {
|
|
125
|
+
const args = [
|
|
126
|
+
...hardeningArgs(),
|
|
127
|
+
"-c", "core.longpaths=true", "-c", `core.hooksPath=${c.hooksDir}`, "-c", `core.excludesFile=${c.excludesFile}`,
|
|
128
|
+
"-c", "core.editor=:", "-c", "sequence.editor=:",
|
|
129
|
+
"-c", "commit.gpgSign=false", "-c", "tag.gpgSign=false", "-c", "tag.forceSignAnnotated=false",
|
|
130
|
+
"-c", "rebase.updateRefs=false", "-c", "rebase.autoStash=false", "-c", "rebase.autoSquash=false",
|
|
131
|
+
"-c", "merge.autoStash=false",
|
|
132
|
+
"-c", "rerere.enabled=false", "-c", "submodule.recurse=false", "-c", "advice.detachedHead=false",
|
|
133
|
+
"-c", "user.useConfigOnly=true",
|
|
134
|
+
];
|
|
135
|
+
if (c.conversion.autocrlf !== null) args.push("-c", `core.autocrlf=${c.conversion.autocrlf}`);
|
|
136
|
+
if (c.conversion.eol !== null) args.push("-c", `core.eol=${c.conversion.eol}`);
|
|
137
|
+
return args;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Fixed content of `slot-excludes` (DV5): ignore rules never affect tracked files. */
|
|
141
|
+
export const SLOT_EXCLUDES_CONTENT = [
|
|
142
|
+
"node_modules/", "/.venv/", "/.yarn/cache/", "/.yarn/unplugged/", "/.yarn/install-state.gz", "/.pnp.*", "*.egg-info/",
|
|
143
|
+
].join("\n") + "\n";
|
|
144
|
+
|
|
145
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
146
|
+
// Small helpers
|
|
147
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
148
|
+
|
|
149
|
+
function invalid(message: string, detail: JsonValue = null): ExecutorError {
|
|
150
|
+
return new ExecutorError("E_INVALID_INPUT", message, detail);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function errorCode(error: unknown): string | undefined {
|
|
154
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
|
|
155
|
+
const code = (error as { code: unknown }).code;
|
|
156
|
+
return typeof code === "string" ? code : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function errorText(error: unknown): string {
|
|
160
|
+
return error instanceof Error ? error.message : String(error);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function foldCase(p: string): string {
|
|
164
|
+
return process.platform === "win32" ? p.toLowerCase() : p;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function tailBytes(text: string, max: number): string {
|
|
168
|
+
const bytes = Buffer.from(text, "utf8");
|
|
169
|
+
return bytes.length <= max ? text : bytes.subarray(bytes.length - max).toString("utf8").replace(/^\uFFFD+/, "");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function splitNul(text: string): string[] {
|
|
173
|
+
return text.split("\0").filter(part => part !== "");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function gitFailure(op: string, r: ProcessResult): ExecutorError {
|
|
177
|
+
const stderr = tailBytes(stripUrlUserinfo(r.stderr), GIT_STDERR_TAIL_BYTES);
|
|
178
|
+
return new ExecutorError("E_GIT", `git ${op} failed (exit ${r.code ?? r.signal ?? "unknown"})`, { op, code: r.code, stderr });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function requireCommit(value: string, what: string): string {
|
|
182
|
+
if (!GIT_ID_PATTERN.test(value)) throw invalid(`${what} is not a full git object id`, { value: value.slice(0, 80) });
|
|
183
|
+
return value;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
187
|
+
// §2.3 Identity
|
|
188
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
export interface CommitIdentity { name: string; email: string }
|
|
191
|
+
|
|
192
|
+
const identityCache = new WeakMap<GitRunner, Map<string, Promise<CommitIdentity & { conversion: GitContext["conversion"] }>>>();
|
|
193
|
+
|
|
194
|
+
async function readConfig(userGit: GitRunner, toplevel: string, key: string): Promise<string | null> {
|
|
195
|
+
const r = await userGit.run(["config", "--includes", "--get", key], { cwd: toplevel, timeoutMs: GIT_OP_TIMEOUT_MS, maxOutputBytes: 64 * 1024 });
|
|
196
|
+
if (r.code === 1) return null;
|
|
197
|
+
if (r.code !== 0) throw gitFailure(`config ${key}`, r);
|
|
198
|
+
return r.stdout.replace(/\r?\n$/, "");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function identityValue(raw: string | null, key: string, toplevel: string): string {
|
|
202
|
+
const missing = () => new ExecutorError("E_IDENTITY",
|
|
203
|
+
`No git commit identity for ${toplevel}: run git config user.name "…" and git config user.email "…" (repository or global). ` +
|
|
204
|
+
"The executor never invents one.", { toplevel, key });
|
|
205
|
+
if (raw === null) throw missing();
|
|
206
|
+
if (/[\0\r\n<>]/.test(raw)) throw new ExecutorError("E_IDENTITY", `${key} contains a character that is not allowed in a commit identity`, { toplevel, key });
|
|
207
|
+
const value = raw.trim();
|
|
208
|
+
if (value === "") throw missing();
|
|
209
|
+
return value;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function conversionValue(raw: string | null, key: string): string | null {
|
|
213
|
+
if (raw === null) return null;
|
|
214
|
+
const value = raw.trim();
|
|
215
|
+
if (value === "") return null;
|
|
216
|
+
if (!/^[A-Za-z0-9_-]{1,16}$/.test(value)) throw new ExecutorError("E_GIT", `unsupported ${key} value`, { key });
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Once per runner and toplevel (cached): the user's effective `user.name`/`user.email`
|
|
222
|
+
* (`config --includes --get`, cwd = toplevel). A missing or empty value is `E_IDENTITY`; a value with NUL, CR, LF, `<` or
|
|
223
|
+
* `>` is `E_IDENTITY`. Never `git var` (it can synthesise an identity). The same read snapshots `core.autocrlf`/`core.eol`
|
|
224
|
+
* (DV6). A failed read is not cached.
|
|
225
|
+
*/
|
|
226
|
+
export function readCommitIdentity(userGit: GitRunner, toplevel: string): Promise<CommitIdentity & { conversion: GitContext["conversion"] }> {
|
|
227
|
+
let perRunner = identityCache.get(userGit);
|
|
228
|
+
if (perRunner === undefined) { perRunner = new Map(); identityCache.set(userGit, perRunner); }
|
|
229
|
+
const key = foldCase(toplevel);
|
|
230
|
+
const cached = perRunner.get(key);
|
|
231
|
+
if (cached !== undefined) return cached;
|
|
232
|
+
const pending = (async () => {
|
|
233
|
+
const [name, email, autocrlf, eol] = await Promise.all([
|
|
234
|
+
readConfig(userGit, toplevel, "user.name"), readConfig(userGit, toplevel, "user.email"),
|
|
235
|
+
readConfig(userGit, toplevel, "core.autocrlf"), readConfig(userGit, toplevel, "core.eol"),
|
|
236
|
+
]);
|
|
237
|
+
return {
|
|
238
|
+
name: identityValue(name, "user.name", toplevel), email: identityValue(email, "user.email", toplevel),
|
|
239
|
+
conversion: { autocrlf: conversionValue(autocrlf, "core.autocrlf"), eol: conversionValue(eol, "core.eol") },
|
|
240
|
+
};
|
|
241
|
+
})();
|
|
242
|
+
perRunner.set(key, pending);
|
|
243
|
+
pending.catch(() => { perRunner.delete(key); });
|
|
244
|
+
return pending;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
248
|
+
// §2.4 Commit messages
|
|
249
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
export type CommitType = "feat" | "fix" | "test" | "docs" | "revert";
|
|
252
|
+
export const COMMIT_TITLE_MAX = 72;
|
|
253
|
+
/** Plan 2.4.2.b pattern, applied to the whole subject; `.{1,72}` bounds the TITLE. */
|
|
254
|
+
export const COMMIT_SUBJECT_PATTERN =
|
|
255
|
+
/^(feat|fix|test|docs|revert)\(([\w.-]+)\): (.{1,72}) \[([a-z0-9][a-z0-9-]{2,40}):([A-Za-z0-9][A-Za-z0-9._-]{0,63})\]$/;
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* task -> feat, or docs when `footprint.writes` is non-empty and every path ends in `.md` or starts with `docs/`;
|
|
259
|
+
* fix -> fix; tests -> test; qa -> docs; manual/preflight -> E_INVALID_INPUT (they never commit).
|
|
260
|
+
*/
|
|
261
|
+
export function commitTypeFor(t: Pick<TaskNode, "kind" | "footprint">): Exclude<CommitType, "revert"> {
|
|
262
|
+
switch (t.kind) {
|
|
263
|
+
case "task": {
|
|
264
|
+
const writes = t.footprint.writes;
|
|
265
|
+
return writes.length > 0 && writes.every(w => w.endsWith(".md") || w.startsWith("docs/")) ? "docs" : "feat";
|
|
266
|
+
}
|
|
267
|
+
case "fix": return "fix";
|
|
268
|
+
case "tests": return "test";
|
|
269
|
+
case "qa": return "docs";
|
|
270
|
+
default: throw invalid(`a ${t.kind} task never commits`, { kind: t.kind });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* `<type>(<scope>): <title> [<planId>:<taskId>]`. The title has C0/C1 controls replaced by spaces, whitespace collapsed
|
|
276
|
+
* and is trimmed; if empty it becomes the task id. Longer than 72: cut at the last space at or before 72 when that
|
|
277
|
+
* leaves at least 20 chars, else a hard cut at 72, then trimmed. One line, no body, no trailers. Throws
|
|
278
|
+
* E_INVALID_INPUT when the result fails `COMMIT_SUBJECT_PATTERN`.
|
|
279
|
+
*/
|
|
280
|
+
export function formatCommitMessage(i: { type: CommitType; scope: string; title: string; planId: PlanId; taskId: TaskId }): string {
|
|
281
|
+
let title = i.title.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
|
|
282
|
+
if (title === "") title = i.taskId;
|
|
283
|
+
if (title.length > COMMIT_TITLE_MAX) {
|
|
284
|
+
const space = title.lastIndexOf(" ", COMMIT_TITLE_MAX);
|
|
285
|
+
title = space >= 20 ? title.slice(0, space) : title.slice(0, COMMIT_TITLE_MAX);
|
|
286
|
+
if (/[\ud800-\udbff]$/.test(title)) title = title.slice(0, -1);
|
|
287
|
+
title = title.trimEnd();
|
|
288
|
+
}
|
|
289
|
+
const subject = `${i.type}(${i.scope}): ${title} [${i.planId}:${i.taskId}]`;
|
|
290
|
+
if (!COMMIT_SUBJECT_PATTERN.test(subject)) throw invalid("commit subject does not match the executor pattern", { subject: subject.slice(0, 200) });
|
|
291
|
+
return subject;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
295
|
+
// §2.5 Ref names
|
|
296
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
const REF_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Injective, case-fold-safe encoding of an id into one ref component. Accepts `/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/` only
|
|
302
|
+
* (anything else is E_INVALID_INPUT). Per char: `[a-z0-9-]` kept; `[A-Z]` lower-cased; `_` -> `__`; `.` kept unless the
|
|
303
|
+
* next char is `.` or it is the last char, then `_0`. With any uppercase, `_u` + the lowercase hex of the bitmask of
|
|
304
|
+
* uppercase positions is appended. If the result ends in `.lock`, that `.` becomes `_0`.
|
|
305
|
+
* `1.1.1` -> `1.1.1`; `2.4.QA` -> `2.4.qa_u30`; `a..b` -> `a_0.b`; `x.lock` -> `x_0lock`; `t_1` -> `t__1`.
|
|
306
|
+
*/
|
|
307
|
+
export function encodeRefId(id: string): string {
|
|
308
|
+
if (typeof id !== "string" || !REF_ID_PATTERN.test(id)) throw invalid("id cannot be encoded into a ref name", { id: String(id).slice(0, 80) });
|
|
309
|
+
let out = "";
|
|
310
|
+
let mask = 0n;
|
|
311
|
+
for (let n = 0; n < id.length; n++) {
|
|
312
|
+
const c = id.charAt(n);
|
|
313
|
+
if (c >= "A" && c <= "Z") { out += c.toLowerCase(); mask |= 1n << BigInt(n); }
|
|
314
|
+
else if (c === "_") out += "__";
|
|
315
|
+
else if (c === ".") out += n === id.length - 1 || id.charAt(n + 1) === "." ? "_0" : ".";
|
|
316
|
+
else out += c;
|
|
317
|
+
}
|
|
318
|
+
if (mask !== 0n) out += `_u${mask.toString(16)}`;
|
|
319
|
+
if (out.endsWith(".lock")) out = `${out.slice(0, -5)}_0lock`;
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export function planRefPrefix(planId: PlanId): string {
|
|
324
|
+
if (typeof planId !== "string" || !PLAN_ID_PATTERN.test(planId)) throw invalid("invalid plan id", { planId: String(planId).slice(0, 80) });
|
|
325
|
+
return `omr/${planId}/`;
|
|
326
|
+
}
|
|
327
|
+
/** `omr/<planId>/t/<encoded taskId>`. */
|
|
328
|
+
export function taskBranchName(planId: PlanId, taskId: TaskId): string {
|
|
329
|
+
return `${planRefPrefix(planId)}t/${encodeRefId(taskId)}`;
|
|
330
|
+
}
|
|
331
|
+
/** `omr/<planId>/integration`. */
|
|
332
|
+
export function integrationBranchName(planId: PlanId): string {
|
|
333
|
+
return `${planRefPrefix(planId)}integration`;
|
|
334
|
+
}
|
|
335
|
+
/** `omr/<planId>/phase/<encoded phaseId>`. */
|
|
336
|
+
export function phaseTagName(planId: PlanId, phaseId: PhaseId): string {
|
|
337
|
+
return `${planRefPrefix(planId)}phase/${encodeRefId(phaseId)}`;
|
|
338
|
+
}
|
|
339
|
+
/** pdf2-1 (b): `omr/<planId>/wip/<encoded taskId>`, the saved work of the task's interrupted attempts. */
|
|
340
|
+
export function wipRefName(planId: PlanId, taskId: TaskId): string {
|
|
341
|
+
return `${planRefPrefix(planId)}wip/${encodeRefId(taskId)}`;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* pdf2-1 (b): `omr/<planId>/orphan/<encoded slot>-<ms>[-<nonce>]`, a dirty slot no task of the plan holds any more, or a
|
|
345
|
+
* WIP commit whose own ref could not be written. QA-PDF21-10: `nonce` (lower-case letters and digits, others dropped)
|
|
346
|
+
* keeps two names of the same slot within the same millisecond apart.
|
|
347
|
+
*/
|
|
348
|
+
export function orphanRefName(planId: PlanId, slot: string, ms: number, nonce?: string): string {
|
|
349
|
+
let name: string;
|
|
350
|
+
try {
|
|
351
|
+
name = encodeRefId(slot);
|
|
352
|
+
} catch {
|
|
353
|
+
name = "slot";
|
|
354
|
+
}
|
|
355
|
+
const tag = typeof nonce === "string" ? nonce.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 32) : "";
|
|
356
|
+
return `${planRefPrefix(planId)}orphan/${name}-${Math.max(0, Math.floor(ms))}${tag === "" ? "" : `-${tag}`}`;
|
|
357
|
+
}
|
|
358
|
+
/** pdf2-1 (b): `Omr-Wip: <planId>/<taskId>/<n>/<nonce>`; a WIP commit never carries `Omr-Attempt`. */
|
|
359
|
+
export function wipTrailer(planId: PlanId, taskId: TaskId, n: number, nonce: string): string {
|
|
360
|
+
return `${WIP_TRAILER}: ${planId}/${taskId}/${n}/${nonce}`;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
364
|
+
// pdf2-1 (b) Work-in-progress snapshot and restore (slot cwd, the runtime's hardened runner)
|
|
365
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
366
|
+
|
|
367
|
+
export type WipSnapshot =
|
|
368
|
+
| { saved: false; reason: "clean" | "unchanged" }
|
|
369
|
+
| { saved: true; commit: string; ref: string; files: number };
|
|
370
|
+
|
|
371
|
+
export type WipRestore =
|
|
372
|
+
| { kind: "none" }
|
|
373
|
+
| { kind: "restored"; commit: string; attempt: number; files: number }
|
|
374
|
+
| { kind: "conflict"; commit: string; conflicts: string[] };
|
|
375
|
+
|
|
376
|
+
interface SlotCall { cwd: string; timeoutMs: number }
|
|
377
|
+
|
|
378
|
+
async function slotRun(git: GitRunner, o: SlotCall, op: string, args: readonly string[]): Promise<ProcessResult> {
|
|
379
|
+
try {
|
|
380
|
+
return await git.run(args, { cwd: o.cwd, timeoutMs: o.timeoutMs, maxOutputBytes: GIT_MAX_OUTPUT_BYTES });
|
|
381
|
+
} catch (error) {
|
|
382
|
+
if (error instanceof ExecutorError) throw error;
|
|
383
|
+
throw new ExecutorError("E_GIT", `git ${op} could not run: ${stripUrlUserinfo(errorText(error)).slice(0, 300)}`,
|
|
384
|
+
{ op, code: errorCode(error) ?? null, stderr: "" });
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function slotMust(git: GitRunner, o: SlotCall, op: string, args: readonly string[]): Promise<string> {
|
|
389
|
+
const r = await slotRun(git, o, op, args);
|
|
390
|
+
if (r.code !== 0) throw gitFailure(op, r);
|
|
391
|
+
return r.stdout;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** The commit `refs/heads/<ref>` names, or null when it does not exist. */
|
|
395
|
+
async function refCommit(git: GitRunner, o: SlotCall, ref: string): Promise<string | null> {
|
|
396
|
+
const r = await slotRun(git, o, "rev-parse", ["rev-parse", "--verify", "--quiet", `refs/heads/${ref}^{commit}`]);
|
|
397
|
+
const oid = r.stdout.trim();
|
|
398
|
+
return r.code === 0 && GIT_ID_PATTERN.test(oid) ? oid : null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** QA-PDF21-3: a snapshot step that failed on a leftover `index.lock`. */
|
|
402
|
+
const SLOT_INDEX_LOCK_PATTERN = /index\.lock/i;
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* pdf2-1 (b): saves the slot's work (tracked changes and untracked, non-ignored files) at `refs/heads/<ref>` without
|
|
406
|
+
* leaving a trace on the slot's HEAD: `add -A`, `write-tree`, `commit-tree -p <base>` (message, then the trailer as its
|
|
407
|
+
* own paragraph), a compare-and-swap `update-ref`, then `reset --hard <HEAD>`.
|
|
408
|
+
* QA-PDF21-6: the commit is parented at `base` (the lease's reset commit; default HEAD) and its tree is the worktree, so
|
|
409
|
+
* work the attempt already committed on top of `base` is saved with the uncommitted rest. Nothing to save (the worktree
|
|
410
|
+
* equals `base`): `clean`; a tree equal to the ref's tree: `unchanged` (the slot is still reset to HEAD).
|
|
411
|
+
* QA-PDF21-3: a step that fails on a leftover `index.lock` is retried once after `removeIndexLock` removed it. A failed
|
|
412
|
+
* `update-ref` is retried once; when it fails again the commit is written to `fallbackRef` (a unique name, create-only),
|
|
413
|
+
* the slot is NOT reset and `E_GIT` is thrown with `details.commit` and `details.keptAt` (the fallback ref or null).
|
|
414
|
+
* Throws `E_GIT`; the slot is reset only after the work has a ref.
|
|
415
|
+
*/
|
|
416
|
+
export async function snapshotSlotWork(
|
|
417
|
+
git: GitRunner,
|
|
418
|
+
i: {
|
|
419
|
+
cwd: string; ref: string; message: string; trailer: string; timeoutMs: number;
|
|
420
|
+
base?: string; fallbackRef?: string; removeIndexLock?: () => Promise<boolean>;
|
|
421
|
+
},
|
|
422
|
+
): Promise<WipSnapshot> {
|
|
423
|
+
const o: SlotCall = { cwd: i.cwd, timeoutMs: i.timeoutMs };
|
|
424
|
+
let lockRemoved = false;
|
|
425
|
+
const must = async (op: string, args: readonly string[]): Promise<string> => {
|
|
426
|
+
let r = await slotRun(git, o, op, args);
|
|
427
|
+
if (r.code !== 0 && !lockRemoved && i.removeIndexLock !== undefined && SLOT_INDEX_LOCK_PATTERN.test(`${r.stderr}\n${r.stdout}`)) {
|
|
428
|
+
lockRemoved = true;
|
|
429
|
+
if (await i.removeIndexLock()) r = await slotRun(git, o, op, args);
|
|
430
|
+
}
|
|
431
|
+
if (r.code !== 0) throw gitFailure(op, r);
|
|
432
|
+
return r.stdout;
|
|
433
|
+
};
|
|
434
|
+
const status = await must("status", ["status", "--porcelain", "--untracked-files=all"]);
|
|
435
|
+
const clean = status.trim() === "";
|
|
436
|
+
if (clean && i.base === undefined) return { saved: false, reason: "clean" };
|
|
437
|
+
if (clean) {
|
|
438
|
+
// Only committed work can be left: a HEAD that cannot be read leaves nothing to compare with the base.
|
|
439
|
+
const h = await slotRun(git, o, "rev-parse", ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
|
|
440
|
+
if (h.code !== 0 || !GIT_ID_PATTERN.test(h.stdout.trim())) return { saved: false, reason: "clean" };
|
|
441
|
+
}
|
|
442
|
+
const head = (await must("rev-parse", ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
|
|
443
|
+
requireCommit(head, "HEAD");
|
|
444
|
+
let parent = head;
|
|
445
|
+
if (i.base !== undefined && i.base !== head) {
|
|
446
|
+
const b = await slotRun(git, o, "rev-parse", ["rev-parse", "--verify", "--quiet", `${i.base}^{commit}`]);
|
|
447
|
+
const oid = b.stdout.trim();
|
|
448
|
+
if (b.code === 0 && GIT_ID_PATTERN.test(oid)) parent = oid;
|
|
449
|
+
}
|
|
450
|
+
if (status.trim() === "" && parent === head) return { saved: false, reason: "clean" };
|
|
451
|
+
await must("add", ["add", "-A"]);
|
|
452
|
+
const tree = (await must("write-tree", ["write-tree"])).trim();
|
|
453
|
+
const parentTree = (await must("rev-parse", ["rev-parse", "--verify", `${parent}^{tree}`])).trim();
|
|
454
|
+
if (tree === parentTree) {
|
|
455
|
+
if (status.trim() !== "") await must("reset", ["reset", "--hard", "--quiet", head]);
|
|
456
|
+
return { saved: false, reason: "clean" };
|
|
457
|
+
}
|
|
458
|
+
const old = await refCommit(git, o, i.ref);
|
|
459
|
+
if (old !== null) {
|
|
460
|
+
const oldTree = (await must("rev-parse", ["rev-parse", "--verify", `${old}^{tree}`])).trim();
|
|
461
|
+
if (oldTree === tree) {
|
|
462
|
+
await must("reset", ["reset", "--hard", "--quiet", head]);
|
|
463
|
+
return { saved: false, reason: "unchanged" };
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
const files = splitNul(await must("diff", ["diff", "--cached", "--name-only", "-z", "--no-renames", parent])).length;
|
|
467
|
+
const commit = (await must("commit-tree", ["commit-tree", tree, "-p", parent, "-m", i.message, "-m", i.trailer])).trim();
|
|
468
|
+
requireCommit(commit, "WIP commit");
|
|
469
|
+
const zero = "0".repeat(commit.length);
|
|
470
|
+
const update = ["update-ref", "--no-deref", `refs/heads/${i.ref}`, commit, old ?? zero];
|
|
471
|
+
let r = await slotRun(git, o, "update-ref", update);
|
|
472
|
+
if (r.code !== 0 && (await refCommit(git, o, i.ref).catch(() => null)) !== commit) {
|
|
473
|
+
r = await slotRun(git, o, "update-ref", update);
|
|
474
|
+
if (r.code !== 0 && (await refCommit(git, o, i.ref).catch(() => null)) !== commit) {
|
|
475
|
+
let keptAt: string | null = null;
|
|
476
|
+
if (i.fallbackRef !== undefined) {
|
|
477
|
+
try {
|
|
478
|
+
const f = await slotRun(git, o, "update-ref", ["update-ref", "--no-deref", `refs/heads/${i.fallbackRef}`, commit, zero]);
|
|
479
|
+
if (f.code === 0) keptAt = i.fallbackRef;
|
|
480
|
+
} catch {
|
|
481
|
+
keptAt = null;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
throw new ExecutorError("E_GIT", `git update-ref failed twice; WIP commit ${commit} ${keptAt === null ? "has no ref" : `kept at ${keptAt}`}`, {
|
|
485
|
+
op: "update-ref", code: r.code, stderr: stripUrlUserinfo(r.stderr).slice(0, 2000), commit, keptAt,
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
await must("reset", ["reset", "--hard", "--quiet", head]);
|
|
490
|
+
return { saved: true, commit, ref: i.ref, files };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** The attempt number of an `Omr-Wip:` trailer in `body`, or null. */
|
|
494
|
+
function wipAttemptOf(body: string): number | null {
|
|
495
|
+
for (const line of body.split(/\r?\n/)) {
|
|
496
|
+
const m = new RegExp(`^${WIP_TRAILER}:\\s*[^/\\s]+/[^/\\s]+/(\\d+)/\\S+$`).exec(line.trim());
|
|
497
|
+
if (m !== null && m[1] !== undefined) return Number(m[1]);
|
|
498
|
+
}
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* pdf2-1 (b): restores `refs/heads/<ref>` into a freshly reset slot with `cherry-pick --no-commit`: HEAD stays where it is
|
|
504
|
+
* and the saved work becomes uncommitted changes. `none` when the ref does not exist or adds nothing to HEAD. A conflict
|
|
505
|
+
* aborts the pick and resets the slot to HEAD again; the ref is kept. Throws `E_GIT`.
|
|
506
|
+
*/
|
|
507
|
+
export async function restoreSlotWork(git: GitRunner, i: { cwd: string; ref: string; timeoutMs: number }): Promise<WipRestore> {
|
|
508
|
+
const o: SlotCall = { cwd: i.cwd, timeoutMs: i.timeoutMs };
|
|
509
|
+
const commit = await refCommit(git, o, i.ref);
|
|
510
|
+
if (commit === null) return { kind: "none" };
|
|
511
|
+
const head = (await slotMust(git, o, "rev-parse", ["rev-parse", "--verify", "HEAD^{commit}"])).trim();
|
|
512
|
+
const [wipTree, headTree] = [
|
|
513
|
+
(await slotMust(git, o, "rev-parse", ["rev-parse", "--verify", `${commit}^{tree}`])).trim(),
|
|
514
|
+
(await slotMust(git, o, "rev-parse", ["rev-parse", "--verify", `${head}^{tree}`])).trim(),
|
|
515
|
+
];
|
|
516
|
+
if (wipTree === headTree) return { kind: "none" };
|
|
517
|
+
const picked = await slotRun(git, o, "cherry-pick", ["cherry-pick", "--no-commit", commit]);
|
|
518
|
+
if (picked.code !== 0) {
|
|
519
|
+
const listed = await slotRun(git, o, "diff", ["diff", "--name-only", "--diff-filter=U", "-z"]);
|
|
520
|
+
const conflicts = listed.code === 0 ? [...new Set(splitNul(listed.stdout))] : [];
|
|
521
|
+
await slotRun(git, o, "cherry-pick --abort", ["cherry-pick", "--abort"]);
|
|
522
|
+
await slotMust(git, o, "reset", ["reset", "--hard", "--quiet", head]);
|
|
523
|
+
return { kind: "conflict", commit, conflicts };
|
|
524
|
+
}
|
|
525
|
+
const files = splitNul(await slotMust(git, o, "diff", ["diff", "--cached", "--name-only", "-z", "--no-renames", head])).length;
|
|
526
|
+
const body = await slotRun(git, o, "log", ["log", "-1", "--format=%B", commit]);
|
|
527
|
+
const attempt = body.code === 0 ? (wipAttemptOf(body.stdout) ?? 0) : 0;
|
|
528
|
+
return { kind: "restored", commit, attempt, files };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** pdf2-1 (b): deletes `refs/heads/<ref>`; a missing ref is a no-op. Throws `E_GIT`. */
|
|
532
|
+
export async function deleteSlotRef(git: GitRunner, i: { cwd: string; ref: string; timeoutMs: number }): Promise<boolean> {
|
|
533
|
+
const o: SlotCall = { cwd: i.cwd, timeoutMs: i.timeoutMs };
|
|
534
|
+
const old = await refCommit(git, o, i.ref);
|
|
535
|
+
if (old === null) return false;
|
|
536
|
+
await slotMust(git, o, "update-ref -d", ["update-ref", "-d", "--no-deref", `refs/heads/${i.ref}`, old]);
|
|
537
|
+
return true;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** pdf2-1 (b): the branch names under `refs/heads/<prefix>` (`prefix` ends in "/"), without `refs/heads/`. Throws `E_GIT`. */
|
|
541
|
+
export async function listSlotRefs(git: GitRunner, i: { cwd: string; prefix: string; timeoutMs: number }): Promise<string[]> {
|
|
542
|
+
const out = await slotMust(git, { cwd: i.cwd, timeoutMs: i.timeoutMs }, "for-each-ref", ["for-each-ref", "--format=%(refname)", `refs/heads/${i.prefix}`]);
|
|
543
|
+
const names: string[] = [];
|
|
544
|
+
for (const raw of out.split("\n")) {
|
|
545
|
+
const line = raw.replace(/\r$/, "");
|
|
546
|
+
if (line.startsWith(`refs/heads/${i.prefix}`)) names.push(line.slice("refs/heads/".length));
|
|
547
|
+
}
|
|
548
|
+
return names;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** pdf2-1 (b): whether `refs/heads/<ref>` exists. Throws `E_GIT` when git cannot run. */
|
|
552
|
+
export async function slotRefExists(git: GitRunner, i: { cwd: string; ref: string; timeoutMs: number }): Promise<boolean> {
|
|
553
|
+
return (await refCommit(git, { cwd: i.cwd, timeoutMs: i.timeoutMs }, i.ref)) !== null;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
557
|
+
// §2.6 Operations
|
|
558
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
559
|
+
|
|
560
|
+
export interface GitOpsDeps {
|
|
561
|
+
git: GitRunner; userGit: GitRunner; fs: FileSystem; planId: PlanId;
|
|
562
|
+
toplevel: string; executorHome: string; timeoutMs?: number;
|
|
563
|
+
}
|
|
564
|
+
export type Conflict = { ok: false; conflicts: string[] };
|
|
565
|
+
export interface WorktreeEntry { path: string; head: string | null; /** Full ref, e.g. `refs/heads/x`. */ branch: string | null; /** Lock reason ("" for none given). */ locked: string | null }
|
|
566
|
+
export interface StatusEntry { xy: string; path: string; orig: string | null }
|
|
567
|
+
|
|
568
|
+
export interface GitOps {
|
|
569
|
+
readonly planId: PlanId;
|
|
570
|
+
/** The git version as `major.minor.patch`; E_GIT if it is below MIN_GIT_VERSION. */
|
|
571
|
+
version(): Promise<string>;
|
|
572
|
+
/** `git check-ref-format refs/heads/<name>`, cached per name; E_INVALID_INPUT when invalid. */
|
|
573
|
+
checkRefFormat(name: string): Promise<void>;
|
|
574
|
+
/** Throws E_SLOT_BROKEN unless the slot's `.git` is a linked-worktree pointer into this repository (memo §2.2). */
|
|
575
|
+
verifySlotPointers(slot: string): Promise<{ gitdir: string; common: string }>;
|
|
576
|
+
// cwd = toplevel
|
|
577
|
+
/** `worktree add --detach --lock --reason <lockReason> <path> <commit>`. */
|
|
578
|
+
worktreeAdd(path: string, commit: string, lockReason: string): Promise<void>;
|
|
579
|
+
/**
|
|
580
|
+
* pre: lstat(path) is ENOENT (else E_GIT, never runs). Unlocks when locked with exactly `lockReason`, then
|
|
581
|
+
* `worktree remove --force <path>` (drops the admin entry only). Never `worktree prune`. A path git does not list is a no-op.
|
|
582
|
+
*/
|
|
583
|
+
worktreeRemove(path: string, lockReason: string): Promise<void>;
|
|
584
|
+
worktreeList(): Promise<WorktreeEntry[]>;
|
|
585
|
+
// cwd = slot, explicit --git-dir/--work-tree
|
|
586
|
+
checkoutDetach(slot: string, commit: string): Promise<void>;
|
|
587
|
+
/** `clean -q -ffdx -e <keep>...`: ignored files of the previous owner go too; only `keep` survives. */
|
|
588
|
+
cleanTracked(slot: string, keep: readonly string[]): Promise<void>;
|
|
589
|
+
/**
|
|
590
|
+
* `checkout --force HEAD -- .`, `clean -q -ffdx -e <keep>...`, then nothing may remain to clean and `statusPorcelain` must
|
|
591
|
+
* be empty (E_GIT listing the dirty paths otherwise). Tracked changes are reverted: 3.1 commits before it calls this.
|
|
592
|
+
*/
|
|
593
|
+
cleanForChecks(slot: string, keep: readonly string[]): Promise<void>;
|
|
594
|
+
/** The paths `clean -ffndx -e <keep>...` would remove (same vector as the real clean), "/"-separated, directories end in "/". */
|
|
595
|
+
cleanPreview(slot: string, keep: readonly string[]): Promise<string[]>;
|
|
596
|
+
/** `ls-files -z --cached` (index), optionally limited to literal pathspecs. */
|
|
597
|
+
lsFiles(slot: string, pathspecs?: readonly string[]): Promise<string[]>;
|
|
598
|
+
/** Index entries of mode 120000. */
|
|
599
|
+
trackedLinks(slot: string): Promise<string[]>;
|
|
600
|
+
statusPorcelain(slot: string): Promise<StatusEntry[]>;
|
|
601
|
+
addAll(slot: string): Promise<void>;
|
|
602
|
+
/** Validates `message` against COMMIT_SUBJECT_PATTERN; returns the new HEAD. */
|
|
603
|
+
commit(slot: string, message: string): Promise<string>;
|
|
604
|
+
/** `cwd` is the toplevel or a slot. */
|
|
605
|
+
revParse(cwd: string, rev: string): Promise<string>;
|
|
606
|
+
diffNames(cwd: string, from: string, to: string): Promise<string[]>;
|
|
607
|
+
rebaseOnto(slot: string, onto: string, upstream: string, observation?: ServiceObservation): Promise<{ ok: true; head: string } | Conflict>;
|
|
608
|
+
rebaseAbort(slot: string): Promise<void>;
|
|
609
|
+
cherryPick(slot: string, commits: readonly string[]): Promise<{ ok: true; head: string } | Conflict>;
|
|
610
|
+
revert(slot: string, commit: string, message: string): Promise<{ ok: true; head: string } | Conflict>;
|
|
611
|
+
mergeFfOnly(cwd: string, commit: string, observation?: ServiceObservation): Promise<{ ok: boolean; head: string }>;
|
|
612
|
+
isAncestor(a: string, b: string): Promise<boolean>;
|
|
613
|
+
tag(name: string, commit: string): Promise<void>;
|
|
614
|
+
deleteRefs(prefix: string): Promise<string[]>;
|
|
615
|
+
/**
|
|
616
|
+
* Compare-and-swap move of `refs/heads/<name>` (`update-ref --no-deref`); `expectedOld` is required, `null` meaning the
|
|
617
|
+
* branch must not exist. Refuses a symbolic ref and a branch checked out in any worktree.
|
|
618
|
+
*/
|
|
619
|
+
branchForce(name: string, commit: string, expectedOld: string | null, observation?: ServiceObservation): Promise<void>;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
interface OpsContext { args: string[]; identity: CommitIdentity }
|
|
623
|
+
type ServiceObservation = import("./observations").ServiceObservation;
|
|
624
|
+
interface GitService {
|
|
625
|
+
observation: ServiceObservation; stage: string; preparation: ReturnType<ServiceObservation["start"]>;
|
|
626
|
+
}
|
|
627
|
+
interface Call { op: string; args: readonly string[]; timeoutMs?: number; identity?: boolean; service?: GitService }
|
|
628
|
+
|
|
629
|
+
const LOCK_REASON_PATTERN = /^[\x20\x21\x23-\x5b\x5d-\x7e]{1,200}$/;
|
|
630
|
+
|
|
631
|
+
export function createGitOps(d: GitOpsDeps): GitOps {
|
|
632
|
+
const planPrefix = planRefPrefix(d.planId);
|
|
633
|
+
const timeoutMs = d.timeoutMs ?? GIT_OP_TIMEOUT_MS;
|
|
634
|
+
const toplevel = d.toplevel;
|
|
635
|
+
const gitHome = join(d.executorHome, "git");
|
|
636
|
+
const hooksDir = join(gitHome, "no-hooks");
|
|
637
|
+
const excludesFile = join(gitHome, "slot-excludes");
|
|
638
|
+
const refFormatCache = new Map<string, boolean>();
|
|
639
|
+
let versionCache: string | undefined;
|
|
640
|
+
let contextPromise: Promise<OpsContext> | undefined;
|
|
641
|
+
let commonCache: string | undefined;
|
|
642
|
+
|
|
643
|
+
// ---- context: hooks directory, excludes file, identity and conversion snapshot ----
|
|
644
|
+
|
|
645
|
+
async function ensureDir(p: string): Promise<void> {
|
|
646
|
+
const st = await d.fs.lstat(p);
|
|
647
|
+
if (st !== null) {
|
|
648
|
+
if (st.kind !== "dir") throw new ExecutorError("E_GIT", "executor git directory is not a real directory", { path: p });
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
try { await d.fs.mkdir(p); } catch (error) {
|
|
652
|
+
if (errorCode(error) !== "EEXIST") throw error;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
async function prepareFiles(): Promise<void> {
|
|
657
|
+
await ensureDir(d.executorHome);
|
|
658
|
+
await ensureDir(gitHome);
|
|
659
|
+
await ensureDir(hooksDir);
|
|
660
|
+
const hooks = await d.fs.lstat(hooksDir);
|
|
661
|
+
if (hooks === null || hooks.kind !== "dir") throw new ExecutorError("E_GIT", "hooks directory is not a real directory", { path: hooksDir });
|
|
662
|
+
if ((await d.fs.readdir(hooksDir)).length !== 0) throw new ExecutorError("E_GIT", "hooks directory is not empty", { path: hooksDir });
|
|
663
|
+
const existing = await d.fs.lstat(excludesFile);
|
|
664
|
+
if (existing !== null && existing.kind !== "file") throw new ExecutorError("E_GIT", "slot excludes path is not a file", { path: excludesFile });
|
|
665
|
+
if (existing === null || (await d.fs.readText(excludesFile)) !== SLOT_EXCLUDES_CONTENT) {
|
|
666
|
+
await d.fs.writeText(excludesFile, SLOT_EXCLUDES_CONTENT, { fsync: true });
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function context(): Promise<OpsContext> {
|
|
671
|
+
if (contextPromise !== undefined) return contextPromise;
|
|
672
|
+
const pending = (async (): Promise<OpsContext> => {
|
|
673
|
+
await prepareFiles();
|
|
674
|
+
const { conversion, ...identity } = await readCommitIdentity(d.userGit, toplevel);
|
|
675
|
+
return { args: executorGitArgs({ hooksDir, excludesFile, conversion }), identity };
|
|
676
|
+
})();
|
|
677
|
+
contextPromise = pending;
|
|
678
|
+
pending.catch(() => { if (contextPromise === pending) contextPromise = undefined; });
|
|
679
|
+
return pending;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// ---- running ----
|
|
683
|
+
|
|
684
|
+
function gitService(observation: ServiceObservation | undefined, stage: string): GitService | undefined {
|
|
685
|
+
return observation === undefined ? undefined : { observation, stage, preparation: observation.start("service-prep", "git-preparation") };
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async function exec(op: string, cwd: string, args: readonly string[], limit: number, diagnostic?: GitService): Promise<ProcessResult> {
|
|
689
|
+
let result: ProcessResult;
|
|
690
|
+
diagnostic?.preparation?.end("completed");
|
|
691
|
+
const service = diagnostic?.observation.execution(diagnostic.stage);
|
|
692
|
+
try {
|
|
693
|
+
result = await d.git.run(args, { cwd, timeoutMs: limit, maxOutputBytes: GIT_MAX_OUTPUT_BYTES,
|
|
694
|
+
...(service === undefined ? {} : { service }) });
|
|
695
|
+
service?.end(result.code === 0 && !result.truncated ? "pass" : "fail");
|
|
696
|
+
} catch (error) {
|
|
697
|
+
if (error instanceof ExecutorError) throw error;
|
|
698
|
+
throw new ExecutorError("E_GIT", `git ${op} could not run: ${stripUrlUserinfo(errorText(error)).slice(0, 300)}`,
|
|
699
|
+
{ op, code: errorCode(error) ?? null, stderr: "" });
|
|
700
|
+
} finally {
|
|
701
|
+
service?.end("error");
|
|
702
|
+
if (diagnostic !== undefined) diagnostic.preparation = diagnostic.observation.start("service-prep", "git-result");
|
|
703
|
+
}
|
|
704
|
+
if (result.truncated) throw new ExecutorError("E_GIT", `git ${op} output was truncated`, { op, code: result.code, stderr: "" });
|
|
705
|
+
return result;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function identityArgs(x: OpsContext, wanted: boolean | undefined): string[] {
|
|
709
|
+
return wanted === true ? ["-c", `user.name=${x.identity.name}`, "-c", `user.email=${x.identity.email}`] : [];
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** The hooks directory is re-checked before every call: an op can run a hook only from a non-empty directory. */
|
|
713
|
+
async function assertHooksEmpty(): Promise<void> {
|
|
714
|
+
const st = await d.fs.lstat(hooksDir);
|
|
715
|
+
if (st === null || st.kind !== "dir") throw new ExecutorError("E_GIT", "hooks directory is not a real directory", { path: hooksDir });
|
|
716
|
+
if ((await d.fs.readdir(hooksDir)).length !== 0) throw new ExecutorError("E_GIT", "hooks directory is not empty", { path: hooksDir });
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** cwd = toplevel. */
|
|
720
|
+
async function inRepo(c: Call): Promise<ProcessResult> {
|
|
721
|
+
const x = await context();
|
|
722
|
+
await assertHooksEmpty();
|
|
723
|
+
return exec(c.op, toplevel, [...x.args, ...identityArgs(x, c.identity), ...c.args], c.timeoutMs ?? timeoutMs, c.service);
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** cwd = slot, after the pointer check, with explicit --git-dir/--work-tree. */
|
|
727
|
+
async function inSlot(slot: string, c: Call): Promise<ProcessResult> {
|
|
728
|
+
const { gitdir } = await verifySlotPointers(slot);
|
|
729
|
+
const x = await context();
|
|
730
|
+
await assertHooksEmpty();
|
|
731
|
+
const scope = [`--git-dir=${gitdir}`, `--work-tree=${slot}`];
|
|
732
|
+
return exec(c.op, slot, [...x.args, ...identityArgs(x, c.identity), ...scope, ...c.args], c.timeoutMs ?? timeoutMs, c.service);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** The toplevel itself, otherwise a slot. */
|
|
736
|
+
function inDir(cwd: string, c: Call): Promise<ProcessResult> {
|
|
737
|
+
return foldCase(resolve(cwd)) === foldCase(resolve(toplevel)) ? inRepo(c) : inSlot(cwd, c);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
async function ok(result: Promise<ProcessResult>, op: string): Promise<ProcessResult> {
|
|
741
|
+
const r = await result;
|
|
742
|
+
if (r.code !== 0) throw gitFailure(op, r);
|
|
743
|
+
return r;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// ---- version and ref names ----
|
|
747
|
+
|
|
748
|
+
async function version(): Promise<string> {
|
|
749
|
+
if (versionCache !== undefined) return versionCache;
|
|
750
|
+
const r = await ok(exec("version", toplevel, ["--version"], timeoutMs), "version");
|
|
751
|
+
const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(r.stdout);
|
|
752
|
+
if (m === null) throw new ExecutorError("E_GIT", "cannot parse the git version", { op: "version", code: r.code, stderr: "" });
|
|
753
|
+
const found = [Number(m[1]), Number(m[2]), Number(m[3] ?? "0")];
|
|
754
|
+
const text = found.join(".");
|
|
755
|
+
for (let n = 0; n < MIN_GIT_VERSION.length; n++) {
|
|
756
|
+
const have = found[n] ?? 0;
|
|
757
|
+
const need = MIN_GIT_VERSION[n] ?? 0;
|
|
758
|
+
if (have > need) break;
|
|
759
|
+
if (have < need) throw new ExecutorError("E_GIT", `git ${text} is older than the required ${MIN_GIT_VERSION.join(".")}`, { op: "version", code: 0, stderr: text });
|
|
760
|
+
}
|
|
761
|
+
versionCache = text;
|
|
762
|
+
return text;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
async function checkRefFormat(name: string): Promise<void> {
|
|
766
|
+
const known = refFormatCache.get(name);
|
|
767
|
+
if (known === true) return;
|
|
768
|
+
if (known === false) throw invalid("invalid ref name", { name: name.slice(0, 120) });
|
|
769
|
+
const wellFormed = typeof name === "string" && name !== "" && name.length <= 250 && !name.startsWith("-") && !/[\u0000-\u001f\u007f]/.test(name);
|
|
770
|
+
if (!wellFormed) { refFormatCache.set(String(name), false); throw invalid("invalid ref name", { name: String(name).slice(0, 120) }); }
|
|
771
|
+
const r = await exec("check-ref-format", toplevel, [...hardeningArgs(), "check-ref-format", `refs/heads/${name}`], timeoutMs);
|
|
772
|
+
if (r.code === 0) { refFormatCache.set(name, true); return; }
|
|
773
|
+
if (r.code === 1) { refFormatCache.set(name, false); throw invalid("invalid ref name", { name: name.slice(0, 120) }); }
|
|
774
|
+
throw gitFailure("check-ref-format", r);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
async function planRef(name: string, what: string): Promise<string> {
|
|
778
|
+
if (typeof name !== "string" || !name.startsWith(planPrefix) || name.length === planPrefix.length) {
|
|
779
|
+
throw invalid(`${what} must be under ${planPrefix}`, { name: String(name).slice(0, 120) });
|
|
780
|
+
}
|
|
781
|
+
await checkRefFormat(name);
|
|
782
|
+
return name;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// ---- slot pointers (memo §2.2) ----
|
|
786
|
+
|
|
787
|
+
async function samePath(a: string, b: string): Promise<boolean> {
|
|
788
|
+
if (foldCase(resolve(a)) === foldCase(resolve(b))) return true;
|
|
789
|
+
try {
|
|
790
|
+
return foldCase(await d.fs.realpath(a)) === foldCase(await d.fs.realpath(b));
|
|
791
|
+
} catch (error) {
|
|
792
|
+
const code = errorCode(error);
|
|
793
|
+
if (code === "ENOENT" || code === "ENOTDIR") return false;
|
|
794
|
+
throw error;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
function repoCommonDir(): string {
|
|
799
|
+
if (commonCache !== undefined) return commonCache;
|
|
800
|
+
let pointers;
|
|
801
|
+
try { pointers = gitPointers(toplevel); } catch (error) {
|
|
802
|
+
throw new ExecutorError("E_GIT", `cannot read the repository pointers: ${errorText(error)}`, { toplevel });
|
|
803
|
+
}
|
|
804
|
+
if (pointers === undefined) throw new ExecutorError("E_GIT", "the toplevel is not a git checkout", { toplevel });
|
|
805
|
+
commonCache = pointers.common;
|
|
806
|
+
return pointers.common;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
async function verifySlotPointers(slot: string): Promise<{ gitdir: string; common: string }> {
|
|
810
|
+
if (typeof slot !== "string" || !isAbsolute(slot)) throw invalid("slot path must be absolute", { slot: String(slot).slice(0, 200) });
|
|
811
|
+
const broken = (why: string) => new ExecutorError("E_SLOT_BROKEN", `slot ${slot}: ${why}`, { slot, why });
|
|
812
|
+
const slotStat = await d.fs.lstat(slot);
|
|
813
|
+
if (slotStat === null) throw broken("the slot directory does not exist");
|
|
814
|
+
if (slotStat.kind !== "dir") throw broken(`the slot is not a real directory (${slotStat.kind})`);
|
|
815
|
+
try {
|
|
816
|
+
// The slot itself must not be a link: its real path is its parent's real path plus its own name.
|
|
817
|
+
const parentReal = await d.fs.realpath(dirname(slot));
|
|
818
|
+
if (foldCase(await d.fs.realpath(slot)) !== foldCase(join(parentReal, basename(slot)))) throw broken("the slot resolves through a link");
|
|
819
|
+
} catch (error) {
|
|
820
|
+
if (error instanceof ExecutorError) throw error;
|
|
821
|
+
throw broken(`cannot resolve the slot (${errorText(error)})`);
|
|
822
|
+
}
|
|
823
|
+
let pointers;
|
|
824
|
+
try { pointers = gitPointers(slot); } catch (error) { throw broken(errorText(error)); }
|
|
825
|
+
if (pointers === undefined) throw broken(".git is missing or names no git directory");
|
|
826
|
+
if (!pointers.file) throw broken(".git is not a regular file");
|
|
827
|
+
if (!pointers.linked) throw broken(".git does not name a linked worktree");
|
|
828
|
+
const common = repoCommonDir();
|
|
829
|
+
if (!(await samePath(pointers.common, common))) throw broken("its common directory is not the repository's");
|
|
830
|
+
if (!(await samePath(dirname(pointers.gitdir), join(common, "worktrees"))) || basename(pointers.gitdir) === "") {
|
|
831
|
+
throw broken("its git directory is not under <common>/worktrees");
|
|
832
|
+
}
|
|
833
|
+
let back: string;
|
|
834
|
+
try { back = await d.fs.readText(join(pointers.gitdir, "gitdir")); } catch (error) {
|
|
835
|
+
throw broken(`cannot read the worktree back-pointer (${errorText(error)})`);
|
|
836
|
+
}
|
|
837
|
+
const target = (back.split(/\r?\n/, 1)[0] ?? "").trim();
|
|
838
|
+
if (target === "" || back.length > 4096 || isNetworkOrDevicePath(target)) throw broken("its back-pointer is unusable");
|
|
839
|
+
// Lexical on purpose: a realpath would follow a link planted at the slot's `.git` or at the back-pointer's target.
|
|
840
|
+
if (foldCase(resolve(pointers.gitdir, target)) !== foldCase(resolve(join(slot, ".git")))) throw broken("its back-pointer does not return to the slot");
|
|
841
|
+
return { gitdir: pointers.gitdir, common };
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// ---- worktrees ----
|
|
845
|
+
|
|
846
|
+
async function worktreeList(): Promise<WorktreeEntry[]> {
|
|
847
|
+
const r = await ok(inRepo({ op: "worktree list", args: ["worktree", "list", "--porcelain"] }), "worktree list");
|
|
848
|
+
const entries: WorktreeEntry[] = [];
|
|
849
|
+
let current: WorktreeEntry | undefined;
|
|
850
|
+
for (const raw of r.stdout.split("\n")) {
|
|
851
|
+
const line = raw.replace(/\r$/, "");
|
|
852
|
+
if (line.startsWith("worktree ")) {
|
|
853
|
+
current = { path: resolve(line.slice("worktree ".length)), head: null, branch: null, locked: null };
|
|
854
|
+
entries.push(current);
|
|
855
|
+
} else if (current === undefined) continue;
|
|
856
|
+
else if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length);
|
|
857
|
+
else if (line.startsWith("branch ")) current.branch = line.slice("branch ".length);
|
|
858
|
+
else if (line === "locked") current.locked = "";
|
|
859
|
+
else if (line.startsWith("locked ")) current.locked = line.slice("locked ".length);
|
|
860
|
+
}
|
|
861
|
+
return entries;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function requireLockReason(reason: string): string {
|
|
865
|
+
if (typeof reason !== "string" || !LOCK_REASON_PATTERN.test(reason)) throw invalid("invalid worktree lock reason", { reason: String(reason).slice(0, 80) });
|
|
866
|
+
return reason;
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
async function worktreeAdd(path: string, commit: string, lockReason: string): Promise<void> {
|
|
870
|
+
if (typeof path !== "string" || !isAbsolute(path)) throw invalid("worktree path must be absolute", { path: String(path).slice(0, 200) });
|
|
871
|
+
requireCommit(commit, "commit");
|
|
872
|
+
requireLockReason(lockReason);
|
|
873
|
+
await version();
|
|
874
|
+
await ok(inRepo({
|
|
875
|
+
op: "worktree add", timeoutMs: GIT_WORKTREE_ADD_TIMEOUT_MS, identity: true,
|
|
876
|
+
args: ["worktree", "add", "--detach", "--lock", "--reason", lockReason, path, commit],
|
|
877
|
+
}), "worktree add");
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
async function worktreeRemove(path: string, lockReason: string): Promise<void> {
|
|
881
|
+
if (typeof path !== "string" || !isAbsolute(path)) throw invalid("worktree path must be absolute", { path: String(path).slice(0, 200) });
|
|
882
|
+
requireLockReason(lockReason);
|
|
883
|
+
if ((await d.fs.lstat(path)) !== null) {
|
|
884
|
+
throw new ExecutorError("E_GIT", "worktree directory still exists; remove it before dropping the worktree entry", { op: "worktree remove", path });
|
|
885
|
+
}
|
|
886
|
+
const entry = (await worktreeList()).find(w => foldCase(w.path) === foldCase(resolve(path)));
|
|
887
|
+
if (entry === undefined) return;
|
|
888
|
+
if (entry.locked !== null) {
|
|
889
|
+
if (entry.locked !== lockReason) {
|
|
890
|
+
throw new ExecutorError("E_GIT", "worktree is locked by someone else", { op: "worktree remove", path, reason: entry.locked.slice(0, 200) });
|
|
891
|
+
}
|
|
892
|
+
await ok(inRepo({ op: "worktree unlock", args: ["worktree", "unlock", path] }), "worktree unlock");
|
|
893
|
+
}
|
|
894
|
+
await ok(inRepo({ op: "worktree remove", args: ["worktree", "remove", "--force", path] }), "worktree remove");
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// ---- working tree ----
|
|
898
|
+
|
|
899
|
+
async function exists(p: string): Promise<boolean> {
|
|
900
|
+
return (await d.fs.lstat(p)) !== null;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
async function checkoutDetach(slot: string, commit: string): Promise<void> {
|
|
904
|
+
requireCommit(commit, "commit");
|
|
905
|
+
const { gitdir } = await verifySlotPointers(slot);
|
|
906
|
+
const states: Array<{ files: string[]; quit: string[] }> = [
|
|
907
|
+
{ files: ["rebase-merge", "rebase-apply"], quit: ["rebase", "--quit"] },
|
|
908
|
+
{ files: ["CHERRY_PICK_HEAD", "sequencer"], quit: ["cherry-pick", "--quit"] },
|
|
909
|
+
{ files: ["REVERT_HEAD", "sequencer"], quit: ["revert", "--quit"] },
|
|
910
|
+
{ files: ["MERGE_HEAD"], quit: ["merge", "--quit"] },
|
|
911
|
+
];
|
|
912
|
+
for (const state of states) {
|
|
913
|
+
let present = false;
|
|
914
|
+
for (const file of state.files) present = present || await exists(join(gitdir, file));
|
|
915
|
+
if (present) await ok(inSlot(slot, { op: state.quit.join(" "), args: state.quit }), state.quit.join(" "));
|
|
916
|
+
}
|
|
917
|
+
await ok(inSlot(slot, { op: "checkout", identity: true, args: ["checkout", "--detach", "--force", commit, "--"] }), "checkout");
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function cleanExcludes(keep: readonly string[]): string[] {
|
|
921
|
+
const excludes: string[] = [];
|
|
922
|
+
for (const k of keep) {
|
|
923
|
+
if (typeof k !== "string" || k === "" || k.length > 400 || /[\u0000-\u001f\u007f]/.test(k)) throw invalid("invalid clean exclusion", { keep: String(k).slice(0, 80) });
|
|
924
|
+
excludes.push("-e", k);
|
|
925
|
+
}
|
|
926
|
+
return excludes;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/** Reads one git C-quoted path (`"a\tb"`, octal escapes are UTF-8 bytes) or returns the text unchanged. */
|
|
930
|
+
function unquoteGitPath(text: string): string {
|
|
931
|
+
if (text.length < 2 || !text.startsWith("\"") || !text.endsWith("\"")) return text;
|
|
932
|
+
const bytes: number[] = [];
|
|
933
|
+
const body = text.slice(1, -1);
|
|
934
|
+
const simple: Readonly<Record<string, number>> = { a: 7, b: 8, f: 12, n: 10, r: 13, t: 9, v: 11, "\\": 92, "\"": 34 };
|
|
935
|
+
for (let n = 0; n < body.length; n++) {
|
|
936
|
+
const c = body.charAt(n);
|
|
937
|
+
if (c !== "\\") { bytes.push(...Buffer.from(c, "utf8")); continue; }
|
|
938
|
+
const next = body.charAt(n + 1);
|
|
939
|
+
const octal = /^[0-3][0-7]{2}$/.exec(body.slice(n + 1, n + 4));
|
|
940
|
+
if (octal !== null) { bytes.push(parseInt(octal[0], 8)); n += 3; continue; }
|
|
941
|
+
const code = simple[next];
|
|
942
|
+
if (code === undefined) { bytes.push(92); continue; }
|
|
943
|
+
bytes.push(code);
|
|
944
|
+
n += 1;
|
|
945
|
+
}
|
|
946
|
+
return Buffer.from(bytes).toString("utf8");
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* The paths `git clean -ffndx -e <keep>` would delete, relative to the slot with "/" separators (a directory ends in "/").
|
|
951
|
+
* The same argument vector as the real clean (`cleanTracked`, `cleanForChecks`), so the caller can sweep exactly what git deletes.
|
|
952
|
+
*/
|
|
953
|
+
async function cleanPreview(slot: string, keep: readonly string[]): Promise<string[]> {
|
|
954
|
+
const r = await ok(inSlot(slot, { op: "clean -n", args: ["-c", "core.quotePath=false", "clean", "-ffndx", ...cleanExcludes(keep)] }), "clean -n");
|
|
955
|
+
const out: string[] = [];
|
|
956
|
+
for (const raw of r.stdout.split("\n")) {
|
|
957
|
+
const line = raw.replace(/\r$/, "");
|
|
958
|
+
if (line === "") continue;
|
|
959
|
+
const prefix = line.startsWith("Would remove ") ? "Would remove " : line.startsWith("Would skip repository ") ? "Would skip repository " : null;
|
|
960
|
+
if (prefix === null) throw new ExecutorError("E_GIT", "unparseable git clean preview line", { op: "clean -n", code: 0, stderr: line.slice(0, 200) });
|
|
961
|
+
out.push(unquoteGitPath(line.slice(prefix.length)));
|
|
962
|
+
}
|
|
963
|
+
return out;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/** Reset-time clean: `-x` so ignored files of the previous owner do not carry over; only `keep` survives. */
|
|
967
|
+
async function cleanTracked(slot: string, keep: readonly string[]): Promise<void> {
|
|
968
|
+
await ok(inSlot(slot, { op: "clean", args: ["clean", "-q", "-ffdx", ...cleanExcludes(keep)] }), "clean");
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/**
|
|
972
|
+
* Before the clean: `checkout --force HEAD -- .` restores every tracked file the agent changed or deleted (the 3.1 task
|
|
973
|
+
* runner commits before it calls this, so nothing worth keeping is reverted). After it the status must be empty.
|
|
974
|
+
*/
|
|
975
|
+
async function cleanForChecks(slot: string, keep: readonly string[]): Promise<void> {
|
|
976
|
+
const excludes = cleanExcludes(keep);
|
|
977
|
+
await ok(inSlot(slot, { op: "checkout", identity: true, args: ["checkout", "--force", "HEAD", "--", "."] }), "checkout");
|
|
978
|
+
await ok(inSlot(slot, { op: "clean", args: ["clean", "-q", "-ffdx", ...excludes] }), "clean");
|
|
979
|
+
const left = await ok(inSlot(slot, { op: "clean -n", args: ["clean", "-ffndx", ...excludes] }), "clean -n");
|
|
980
|
+
if (left.stdout.trim() !== "") {
|
|
981
|
+
throw new ExecutorError("E_GIT", "files remain after clean", { op: "clean -n", code: 0, stderr: tailBytes(left.stdout, GIT_STDERR_TAIL_BYTES) });
|
|
982
|
+
}
|
|
983
|
+
const dirty = await statusPorcelain(slot);
|
|
984
|
+
if (dirty.length !== 0) {
|
|
985
|
+
throw new ExecutorError("E_GIT", `${dirty.length} path(s) still differ from HEAD after the clean`, {
|
|
986
|
+
op: "status", code: 0, stderr: dirty.slice(0, 20).map(e => `${e.xy} ${e.path}`).join("\n").slice(0, GIT_STDERR_TAIL_BYTES),
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/** The tracked paths of the index (pathspec-limited with `pathspecs`, matched literally), "/"-separated. */
|
|
992
|
+
async function lsFiles(slot: string, pathspecs: readonly string[] = []): Promise<string[]> {
|
|
993
|
+
for (const p of pathspecs) if (typeof p !== "string" || p === "" || /[\u0000-\u001f\u007f]/.test(p)) throw invalid("invalid pathspec", { pathspec: String(p).slice(0, 80) });
|
|
994
|
+
const r = await ok(inSlot(slot, {
|
|
995
|
+
op: "ls-files", args: ["ls-files", "-z", "--cached", "--full-name", ...(pathspecs.length === 0 ? [] : ["--", ...pathspecs.map(p => `:(literal)${p}`)])],
|
|
996
|
+
}), "ls-files");
|
|
997
|
+
return splitNul(r.stdout);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/** The tracked paths whose index mode is 120000 (symlinks): the only links a sweep must leave in place. */
|
|
1001
|
+
async function trackedLinks(slot: string): Promise<string[]> {
|
|
1002
|
+
const r = await ok(inSlot(slot, { op: "ls-files -s", args: ["ls-files", "-s", "-z", "--full-name"] }), "ls-files -s");
|
|
1003
|
+
const out: string[] = [];
|
|
1004
|
+
for (const entry of splitNul(r.stdout)) {
|
|
1005
|
+
const tab = entry.indexOf("\t");
|
|
1006
|
+
if (tab > 0 && entry.startsWith("120000 ")) out.push(entry.slice(tab + 1));
|
|
1007
|
+
}
|
|
1008
|
+
return out;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
async function statusPorcelain(slot: string): Promise<StatusEntry[]> {
|
|
1012
|
+
const r = await ok(inSlot(slot, {
|
|
1013
|
+
op: "status", args: ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignore-submodules=all"],
|
|
1014
|
+
}), "status");
|
|
1015
|
+
const parts = r.stdout.split("\0");
|
|
1016
|
+
const out: StatusEntry[] = [];
|
|
1017
|
+
for (let n = 0; n < parts.length; n++) {
|
|
1018
|
+
const entry = parts[n] ?? "";
|
|
1019
|
+
if (entry === "") continue;
|
|
1020
|
+
if (entry.length < 4 || entry.charAt(2) !== " ") throw new ExecutorError("E_GIT", "unparseable git status entry", { op: "status", code: 0, stderr: "" });
|
|
1021
|
+
const xy = entry.slice(0, 2);
|
|
1022
|
+
const renamed = xy.includes("R") || xy.includes("C");
|
|
1023
|
+
out.push({ xy, path: entry.slice(3), orig: renamed ? (parts[++n] ?? null) : null });
|
|
1024
|
+
}
|
|
1025
|
+
return out;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// ---- commits ----
|
|
1029
|
+
|
|
1030
|
+
async function addAll(slot: string): Promise<void> {
|
|
1031
|
+
await ok(inSlot(slot, { op: "add", args: ["add", "--all"] }), "add");
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function requireMessage(message: string): string {
|
|
1035
|
+
if (typeof message !== "string" || !COMMIT_SUBJECT_PATTERN.test(message)) throw invalid("commit message does not match the executor pattern", { message: String(message).slice(0, 200) });
|
|
1036
|
+
return message;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
function commitArgs(message: string): string[] {
|
|
1040
|
+
return ["commit", "--no-verify", "--no-gpg-sign", "--cleanup=verbatim", "-m", message];
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
async function revParse(cwd: string, rev: string): Promise<string> {
|
|
1044
|
+
if (typeof rev !== "string" || rev === "" || rev.length > 300 || /[\u0000-\u001f\u007f]/.test(rev)) throw invalid("invalid revision", { rev: String(rev).slice(0, 120) });
|
|
1045
|
+
const r = await ok(inDir(cwd, { op: "rev-parse", args: ["rev-parse", "--verify", "--end-of-options", `${rev}^{commit}`] }), "rev-parse");
|
|
1046
|
+
const oid = r.stdout.trim();
|
|
1047
|
+
if (!GIT_ID_PATTERN.test(oid)) throw new ExecutorError("E_GIT", "rev-parse did not print an object id", { op: "rev-parse", code: r.code, stderr: "" });
|
|
1048
|
+
return oid;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
async function commit(slot: string, message: string): Promise<string> {
|
|
1052
|
+
requireMessage(message);
|
|
1053
|
+
await ok(inSlot(slot, { op: "commit", identity: true, args: commitArgs(message) }), "commit");
|
|
1054
|
+
return revParse(slot, "HEAD");
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
async function diffNames(cwd: string, from: string, to: string): Promise<string[]> {
|
|
1058
|
+
requireCommit(from, "from");
|
|
1059
|
+
requireCommit(to, "to");
|
|
1060
|
+
const r = await ok(inDir(cwd, { op: "diff", args: ["diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", from, to, "--"] }), "diff");
|
|
1061
|
+
return splitNul(r.stdout);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/** After a failed cherry-pick/revert: read the conflicted paths, abort, and report them. */
|
|
1065
|
+
async function conflictOutcome(op: string, slot: string, failed: ProcessResult, abort: readonly string[], resetFallback: boolean): Promise<Conflict> {
|
|
1066
|
+
const listed = await ok(inSlot(slot, { op: `${op} conflicts`, args: ["diff", "--name-only", "--diff-filter=U", "-z"] }), `${op} conflicts`);
|
|
1067
|
+
const conflicts = [...new Set(splitNul(listed.stdout))];
|
|
1068
|
+
const aborted = await inSlot(slot, { op: `${op} --abort`, args: abort });
|
|
1069
|
+
if (aborted.code !== 0) {
|
|
1070
|
+
if (!resetFallback) throw gitFailure(`${op} --abort`, aborted);
|
|
1071
|
+
await ok(inSlot(slot, { op: "reset", args: ["reset", "--hard", "--quiet", "HEAD"] }), "reset");
|
|
1072
|
+
}
|
|
1073
|
+
if (conflicts.length === 0) throw gitFailure(op, failed);
|
|
1074
|
+
return { ok: false, conflicts };
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
async function rebaseOnto(slot: string, onto: string, upstream: string, observation?: ServiceObservation): Promise<{ ok: true; head: string } | Conflict> {
|
|
1078
|
+
const diagnostic = gitService(observation, "rebase");
|
|
1079
|
+
try {
|
|
1080
|
+
requireCommit(onto, "onto");
|
|
1081
|
+
requireCommit(upstream, "upstream");
|
|
1082
|
+
const r = await inSlot(slot, { op: "rebase", identity: true, args: ["rebase", "--onto", onto, upstream], service: diagnostic });
|
|
1083
|
+
if (r.code === 0) return { ok: true, head: await revParse(slot, "HEAD") };
|
|
1084
|
+
const failed = gitFailure("rebase", r);
|
|
1085
|
+
let conflicts: string[] = [];
|
|
1086
|
+
try {
|
|
1087
|
+
// Git can refuse before starting a rebase. An abort then only masks the initiating failure.
|
|
1088
|
+
if (await rebaseInProgress(slot)) {
|
|
1089
|
+
const listed = await ok(inSlot(slot, { op: "rebase conflicts", args: ["diff", "--name-only", "--diff-filter=U", "-z"] }), "rebase conflicts");
|
|
1090
|
+
conflicts = [...new Set(splitNul(listed.stdout))];
|
|
1091
|
+
await rebaseAbort(slot);
|
|
1092
|
+
}
|
|
1093
|
+
} catch (cleanup) {
|
|
1094
|
+
throw new ExecutorError(cleanup instanceof ExecutorError ? cleanup.code : "E_GIT",
|
|
1095
|
+
`${failed.message}; rebase cleanup failed: ${tailBytes(stripUrlUserinfo(errorText(cleanup)), GIT_STDERR_TAIL_BYTES)}`,
|
|
1096
|
+
{ original: failed.detail, cleanup: cleanup instanceof ExecutorError ? cleanup.detail : null });
|
|
1097
|
+
}
|
|
1098
|
+
if (conflicts.length === 0) throw failed;
|
|
1099
|
+
return { ok: false, conflicts };
|
|
1100
|
+
} catch (error) { diagnostic?.preparation?.end("error"); throw error; }
|
|
1101
|
+
finally { diagnostic?.preparation?.end("completed"); }
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
async function rebaseInProgress(slot: string): Promise<boolean> {
|
|
1105
|
+
const { gitdir } = await verifySlotPointers(slot);
|
|
1106
|
+
return await exists(join(gitdir, "rebase-merge")) || await exists(join(gitdir, "rebase-apply"));
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
async function rebaseAbort(slot: string): Promise<void> {
|
|
1110
|
+
if (!(await rebaseInProgress(slot))) return;
|
|
1111
|
+
await ok(inSlot(slot, { op: "rebase --abort", args: ["rebase", "--abort"] }), "rebase --abort");
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
async function cherryPick(slot: string, commits: readonly string[]): Promise<{ ok: true; head: string } | Conflict> {
|
|
1115
|
+
if (commits.length === 0) throw invalid("no commits to cherry-pick");
|
|
1116
|
+
for (const c of commits) requireCommit(c, "commit");
|
|
1117
|
+
const r = await inSlot(slot, { op: "cherry-pick", identity: true, args: ["cherry-pick", "--no-edit", ...commits] });
|
|
1118
|
+
if (r.code === 0) return { ok: true, head: await revParse(slot, "HEAD") };
|
|
1119
|
+
return conflictOutcome("cherry-pick", slot, r, ["cherry-pick", "--abort"], false);
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
async function revert(slot: string, commitId: string, message: string): Promise<{ ok: true; head: string } | Conflict> {
|
|
1123
|
+
requireCommit(commitId, "commit");
|
|
1124
|
+
requireMessage(message);
|
|
1125
|
+
const r = await inSlot(slot, { op: "revert", identity: true, args: ["revert", "--no-commit", commitId] });
|
|
1126
|
+
if (r.code !== 0) return conflictOutcome("revert", slot, r, ["revert", "--abort"], true);
|
|
1127
|
+
await ok(inSlot(slot, { op: "commit", identity: true, args: commitArgs(message) }), "commit");
|
|
1128
|
+
return { ok: true, head: await revParse(slot, "HEAD") };
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
async function isAncestor(a: string, b: string): Promise<boolean> {
|
|
1132
|
+
requireCommit(a, "a");
|
|
1133
|
+
requireCommit(b, "b");
|
|
1134
|
+
const r = await inRepo({ op: "merge-base", args: ["merge-base", "--is-ancestor", a, b] });
|
|
1135
|
+
if (r.code === 0) return true;
|
|
1136
|
+
if (r.code === 1) return false;
|
|
1137
|
+
throw gitFailure("merge-base", r);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
async function mergeFfOnly(cwd: string, commitId: string, observation?: ServiceObservation): Promise<{ ok: boolean; head: string }> {
|
|
1141
|
+
const diagnostic = gitService(observation, "merge");
|
|
1142
|
+
try {
|
|
1143
|
+
requireCommit(commitId, "commit");
|
|
1144
|
+
const before = await revParse(cwd, "HEAD");
|
|
1145
|
+
if (!(await isAncestor(before, commitId))) return { ok: false, head: before };
|
|
1146
|
+
await ok(inDir(cwd, { op: "merge", identity: true, args: ["merge", "--ff-only", "--no-edit", commitId], service: diagnostic }), "merge");
|
|
1147
|
+
return { ok: true, head: await revParse(cwd, "HEAD") };
|
|
1148
|
+
} catch (error) { diagnostic?.preparation?.end("error"); throw error; }
|
|
1149
|
+
finally { diagnostic?.preparation?.end("completed"); }
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// ---- refs ----
|
|
1153
|
+
|
|
1154
|
+
async function tag(name: string, commitId: string): Promise<void> {
|
|
1155
|
+
requireCommit(commitId, "commit");
|
|
1156
|
+
await planRef(name, "tag name");
|
|
1157
|
+
await ok(inRepo({ op: "tag", identity: true, args: ["tag", name, commitId] }), "tag");
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
async function deleteRefs(prefix: string): Promise<string[]> {
|
|
1161
|
+
if (typeof prefix !== "string" || !prefix.startsWith(planPrefix) || !prefix.endsWith("/")) {
|
|
1162
|
+
throw invalid(`prefix must be ${planPrefix} or a deeper "/"-terminated prefix of it`, { prefix: String(prefix).slice(0, 120) });
|
|
1163
|
+
}
|
|
1164
|
+
if (prefix.slice(0, -1).split("/").some(segment => segment === "" || segment.includes(".."))) {
|
|
1165
|
+
throw invalid("prefix has an empty or '..' segment", { prefix: prefix.slice(0, 120) });
|
|
1166
|
+
}
|
|
1167
|
+
await checkRefFormat(`${prefix}x`);
|
|
1168
|
+
const listed = await ok(inRepo({
|
|
1169
|
+
op: "for-each-ref",
|
|
1170
|
+
args: ["for-each-ref", "--format=%(refname)%00%(objectname)", `refs/heads/${prefix}`, `refs/tags/${prefix}`],
|
|
1171
|
+
}), "for-each-ref");
|
|
1172
|
+
const found: Array<{ ref: string; oid: string }> = [];
|
|
1173
|
+
for (const line of listed.stdout.split("\n")) {
|
|
1174
|
+
if (line === "") continue;
|
|
1175
|
+
const [ref = "", oid = ""] = line.replace(/\r$/, "").split("\0");
|
|
1176
|
+
const under = ref.startsWith(`refs/heads/${prefix}`) || ref.startsWith(`refs/tags/${prefix}`);
|
|
1177
|
+
if (!under || !GIT_ID_PATTERN.test(oid)) continue;
|
|
1178
|
+
found.push({ ref, oid });
|
|
1179
|
+
}
|
|
1180
|
+
const checkedOut = new Set((await worktreeList()).map(w => w.branch).filter((b): b is string => b !== null));
|
|
1181
|
+
const deleted: string[] = [];
|
|
1182
|
+
for (const { ref, oid } of found) {
|
|
1183
|
+
if (checkedOut.has(ref)) continue;
|
|
1184
|
+
await ok(inRepo({ op: "update-ref -d", identity: true, args: ["update-ref", "-d", "--no-deref", ref, oid] }), "update-ref -d");
|
|
1185
|
+
deleted.push(ref);
|
|
1186
|
+
}
|
|
1187
|
+
return deleted;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
async function branchForce(name: string, commitId: string, expectedOld: string | null, observation?: ServiceObservation): Promise<void> {
|
|
1191
|
+
const diagnostic = gitService(observation, "cas");
|
|
1192
|
+
try {
|
|
1193
|
+
requireCommit(commitId, "commit");
|
|
1194
|
+
await planRef(name, "branch name");
|
|
1195
|
+
if (expectedOld !== null && (typeof expectedOld !== "string" || expectedOld === "")) throw invalid("expectedOld is required: a full object id, or null for a branch that must not exist");
|
|
1196
|
+
const old = expectedOld === null ? "0".repeat(commitId.length) : requireCommit(expectedOld, "expectedOld");
|
|
1197
|
+
const ref = `refs/heads/${name}`;
|
|
1198
|
+
if ((await worktreeList()).some(w => w.branch === ref)) {
|
|
1199
|
+
throw new ExecutorError("E_GIT", "branch is checked out in a worktree", { op: "update-ref", code: null, stderr: name.slice(0, 200) });
|
|
1200
|
+
}
|
|
1201
|
+
const symbolic = await inRepo({ op: "symbolic-ref", args: ["symbolic-ref", "-q", ref] });
|
|
1202
|
+
if (symbolic.code === 0) throw new ExecutorError("E_GIT", "branch is a symbolic ref", { op: "symbolic-ref", code: 0, stderr: name.slice(0, 200) });
|
|
1203
|
+
if (symbolic.code !== 1) throw gitFailure("symbolic-ref", symbolic);
|
|
1204
|
+
await ok(inRepo({ op: "update-ref", identity: true, args: ["update-ref", "--no-deref", ref, commitId, old], service: diagnostic }), "update-ref");
|
|
1205
|
+
} catch (error) { diagnostic?.preparation?.end("error"); throw error; }
|
|
1206
|
+
finally { diagnostic?.preparation?.end("completed"); }
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
return {
|
|
1210
|
+
planId: d.planId, version, checkRefFormat, verifySlotPointers, worktreeAdd, worktreeRemove, worktreeList,
|
|
1211
|
+
checkoutDetach, cleanTracked, cleanForChecks, cleanPreview, lsFiles, trackedLinks, statusPorcelain, addAll, commit, revParse, diffNames,
|
|
1212
|
+
rebaseOnto, rebaseAbort, cherryPick, revert, mergeFfOnly, isAncestor, tag, deleteRefs, branchForce,
|
|
1213
|
+
};
|
|
1214
|
+
}
|