opencode-model-router 2.10.0 → 2.11.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 +306 -0
- package/README.md +3 -2
- package/package.json +8 -1
- package/src/compat/background.ts +5 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-hooks.ts +256 -88
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +3 -0
- package/src/executor/git.ts +110 -26
- package/src/executor/integrate/checks.ts +29 -11
- package/src/executor/integrate/queue.ts +95 -13
- package/src/executor/ledger.ts +16 -12
- package/src/executor/lfs-restore.ts +492 -0
- package/src/executor/paths.ts +7 -2
- package/src/executor/recovery.ts +2 -1
- package/src/executor/runtime.ts +1010 -226
- package/src/executor/slots/pool.ts +120 -19
- package/src/executor/slots/provision.ts +111 -23
- package/src/executor/slots/root.ts +81 -0
- package/src/executor/types.ts +28 -2
- package/src/executor/unattended.ts +6 -1
- package/src/executor/verify-trees.ts +507 -0
- package/src/guard/enforce.ts +2 -1
- package/src/guard/fingerprint.ts +9 -0
- package/src/guard/guards.ts +7 -1
- package/src/index.ts +107 -27
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +71 -12
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +144 -7
- package/src/router/git-tools.ts +930 -73
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +145 -23
- package/src/router/sessions.ts +14 -1
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +5 -1
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +87 -10
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
// src/executor/lfs-restore.ts
|
|
2
|
+
// #208: the executor's git skips the Git LFS smudge (`GIT_LFS_SKIP_SMUDGE=1`, executor/git.ts EXECUTOR_GIT_ENV), so it never
|
|
3
|
+
// downloads an object and every LFS file it writes is a pointer file. After a call that can write a work tree,
|
|
4
|
+
// `restoreLocalLfsObjects` writes back the content of each such pointer whose object is already in the repository's local LFS
|
|
5
|
+
// store. The copy is its own (no Git LFS command), so no endpoint is asked and no transfer, credential or ssh program starts.
|
|
6
|
+
// Git LFS then runs only as git's clean filter, when `git update-index` re-hashes the restored files; because clean runs every
|
|
7
|
+
// configured `lfs.extension.<name>.clean` program, nothing is restored when the configuration names an extension. The restore
|
|
8
|
+
// never fails the call: what it cannot restore stays a pointer file and is reported as a warning. `git lfs checkout` was not
|
|
9
|
+
// used: it runs `lfs.extension.<name>.smudge` programs for an object in the local store (observed with git-lfs 3.7.0).
|
|
10
|
+
|
|
11
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
12
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
13
|
+
import * as fsp from "node:fs/promises";
|
|
14
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
15
|
+
import { Transform } from "node:stream";
|
|
16
|
+
import { pipeline } from "node:stream/promises";
|
|
17
|
+
import type { ProcessResult } from "./types";
|
|
18
|
+
|
|
19
|
+
/** Bounds of one restore; over either, nothing is restored (a warning, never a failed call). */
|
|
20
|
+
export const LFS_RESTORE_MAX_FILES = 10_000;
|
|
21
|
+
export const LFS_RESTORE_MAX_BYTES = 4 * 1024 ** 3;
|
|
22
|
+
/** Output bound of the restore's own LFS file listings (the runner's default is 4 MiB, about 37,000 entries). */
|
|
23
|
+
export const LFS_LISTING_MAX_BYTES = 64 * 1024 * 1024;
|
|
24
|
+
/** A Git LFS pointer file is at most this long (spec v1). */
|
|
25
|
+
const POINTER_MAX_BYTES = 1024;
|
|
26
|
+
/** Characters of paths per `update-index` call (Windows command lines end at 32767). */
|
|
27
|
+
const UPDATE_INDEX_BATCH_CHARS = 8_000;
|
|
28
|
+
/** A rename or removal refused by a transient lock (an indexer or antivirus on Windows) is retried after these delays. */
|
|
29
|
+
const RENAME_RETRY_DELAYS_MS = [25, 50, 100, 200, 400] as const;
|
|
30
|
+
/**
|
|
31
|
+
* Every `lfs.*` key: git matches `--get-regexp` case-sensitively on its canonical key, whose subsection keeps its case
|
|
32
|
+
* (`lfs.Extension.x.clean`), so extension keys are picked out afterwards, after case folding ({@link extensionName}).
|
|
33
|
+
*/
|
|
34
|
+
const LFS_CONFIG_KEYS = "^(filter\\.lfs\\.(process|clean|smudge)|lfs\\..+)$";
|
|
35
|
+
const LFS_EXTENSION_PREFIX = "lfs.extension.";
|
|
36
|
+
const NULL_DEVICES: ReadonlySet<string> = new Set(["nul", "/dev/null"]);
|
|
37
|
+
|
|
38
|
+
/** Subcommands that can write files of a work tree (`reset` only with `--hard`, `--merge` or `--keep`). `worktree add` is
|
|
39
|
+
* restored by GitOps through the new work tree's own `--git-dir`/`--work-tree`. */
|
|
40
|
+
const WORK_TREE_COMMANDS: ReadonlySet<string> = new Set([
|
|
41
|
+
"checkout", "switch", "restore", "cherry-pick", "rebase", "revert", "merge", "pull", "am", "stash", "read-tree", "checkout-index",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
/** Where a restore runs: the triggering call's global options (its `-c`, `-C`, `--git-dir=`, `--work-tree=`) and directory. */
|
|
45
|
+
export interface LfsRestoreTarget { prefix: string[]; cwd: string }
|
|
46
|
+
|
|
47
|
+
/** One restore git call, through the same runner as the call that triggered it. */
|
|
48
|
+
export type LfsRestoreGit = (args: readonly string[], o?: { maxOutputBytes?: number }) => Promise<ProcessResult>;
|
|
49
|
+
|
|
50
|
+
export interface LfsRestoreOptions { maxFiles?: number; maxBytes?: number; signal?: AbortSignal }
|
|
51
|
+
|
|
52
|
+
/** What was restored; `warning` when LFS files were left (or put back) as pointer files for a reason the user should know. */
|
|
53
|
+
export interface LfsRestoreResult { restored: string[]; warning?: string }
|
|
54
|
+
|
|
55
|
+
/** The restore a git call needs, or undefined when it cannot write a work tree. */
|
|
56
|
+
export function lfsRestoreTarget(args: readonly string[], cwd: string): LfsRestoreTarget | undefined {
|
|
57
|
+
let index = 0;
|
|
58
|
+
for (; index < args.length; index++) {
|
|
59
|
+
const arg = args[index] ?? "";
|
|
60
|
+
if (arg === "-C" || arg === "-c") { index++; continue; }
|
|
61
|
+
if (arg.startsWith("-")) continue;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
const command = args[index];
|
|
65
|
+
if (command === undefined) return undefined;
|
|
66
|
+
const prefix = args.slice(0, index);
|
|
67
|
+
const rest = args.slice(index + 1);
|
|
68
|
+
if (command === "reset") return rest.some(a => a === "--hard" || a === "--merge" || a === "--keep") ? { prefix, cwd } : undefined;
|
|
69
|
+
return WORK_TREE_COMMANDS.has(command) ? { prefix, cwd } : undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The oid and size of a canonical Git LFS pointer (spec v1, no extension), or undefined. A pointer of size 0 is undefined too:
|
|
74
|
+
* Git LFS cleans an empty file to an empty blob, never to a pointer, so its re-hash would always change the index entry.
|
|
75
|
+
*/
|
|
76
|
+
export function parseLfsPointer(text: string): { oid: string; size: number } | undefined {
|
|
77
|
+
const m = /^version https:\/\/git-lfs\.github\.com\/spec\/v1\noid sha256:([0-9a-f]{64})\nsize ([1-9][0-9]{0,14})\n$/.exec(text);
|
|
78
|
+
return m === null ? undefined : { oid: m[1] ?? "", size: Number(m[2]) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function globRegex(glob: string, foldCase: boolean): RegExp {
|
|
82
|
+
let re = "";
|
|
83
|
+
for (let i = 0; i < glob.length; i++) {
|
|
84
|
+
const c = glob.charAt(i);
|
|
85
|
+
if (c === "*" && glob.charAt(i + 1) === "*") {
|
|
86
|
+
if (glob.charAt(i + 2) === "/") { re += "(?:.*/)?"; i += 2; } else { re += ".*"; i++; }
|
|
87
|
+
} else if (c === "*") re += "[^/]*";
|
|
88
|
+
else if (c === "?") re += "[^/]";
|
|
89
|
+
else if (c === "[" && glob.indexOf("]", i + 2) > i) {
|
|
90
|
+
const end = glob.indexOf("]", i + 2);
|
|
91
|
+
const body = glob.slice(i + 1, end).replace(/\\/g, "\\\\");
|
|
92
|
+
re += `[${body.startsWith("!") ? `^${body.slice(1)}` : body}]`;
|
|
93
|
+
i = end;
|
|
94
|
+
} else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
95
|
+
}
|
|
96
|
+
return new RegExp(`^${re}$`, foldCase ? "i" : "");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Whether `path` matches one `lfs.fetchinclude` or `lfs.fetchexclude` pattern (gitignore-style); each side errs toward keeping
|
|
101
|
+
* pointer files. An `include` is read conservatively, so it may restore less than Git LFS would smudge, never more: matched
|
|
102
|
+
* case-sensitively; a pattern with a `/` (other than a trailing one) is anchored at the work tree root and matches the file or
|
|
103
|
+
* a directory above it; one without matches a single component at any depth; a trailing `/` matches directories only. An
|
|
104
|
+
* `exclude` is read generously, so it leaves more pointer files, never fewer: case-insensitively on Windows, and the pattern
|
|
105
|
+
* may name the file, any directory above it, or (unless it starts with `/`) any run of components.
|
|
106
|
+
*/
|
|
107
|
+
export function matchesLfsFetchPattern(path: string, raw: string, kind: "include" | "exclude"): boolean {
|
|
108
|
+
let p = raw.trim().replaceAll("\\", "/");
|
|
109
|
+
if (p.startsWith("./")) p = p.slice(2);
|
|
110
|
+
const rooted = p.startsWith("/");
|
|
111
|
+
const directoryOnly = /[^/]\/+$/.test(p);
|
|
112
|
+
p = p.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
113
|
+
if (p === "" || p === "*" || p === "." || p === "**") return true;
|
|
114
|
+
const parts = path.split("/");
|
|
115
|
+
if (kind === "include") {
|
|
116
|
+
const re = globRegex(p, false);
|
|
117
|
+
const last = directoryOnly ? parts.length - 1 : parts.length;
|
|
118
|
+
if (rooted || p.includes("/")) {
|
|
119
|
+
for (let end = 1; end <= last; end++) if (re.test(parts.slice(0, end).join("/"))) return true;
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
for (let at = 0; at < last; at++) if (re.test(parts[at] ?? "")) return true;
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
const re = globRegex(p, process.platform === "win32");
|
|
126
|
+
for (let start = 0; start < parts.length && !(rooted && start > 0); start++) {
|
|
127
|
+
for (let end = start + 1; end <= parts.length; end++) if (re.test(parts.slice(start, end).join("/"))) return true;
|
|
128
|
+
}
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface IndexEntry { mode: string; oid: string; path: string }
|
|
133
|
+
interface Planned { path: string; target: string; object: string; oid: string; size: number; pointer: Buffer; mode: number; indexMode: string }
|
|
134
|
+
interface LfsConfig { filter: boolean; skip: boolean; extensions: string[]; include: string[]; exclude: string[] }
|
|
135
|
+
|
|
136
|
+
function errorText(error: unknown): string {
|
|
137
|
+
return error instanceof Error ? error.message : String(error);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function codeOf(error: unknown): string {
|
|
141
|
+
return typeof error === "object" && error !== null && "code" in error ? String(Reflect.get(error, "code")) : "";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function foldCase(p: string): string {
|
|
145
|
+
return process.platform === "win32" ? p.toLowerCase() : p;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function inside(root: string, p: string): boolean {
|
|
149
|
+
const rel = relative(root, p);
|
|
150
|
+
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const sleep = (ms: number) => new Promise<void>(done => { setTimeout(done, ms); });
|
|
154
|
+
|
|
155
|
+
async function must(git: LfsRestoreGit, args: readonly string[], op: string, o?: { maxOutputBytes?: number }): Promise<string> {
|
|
156
|
+
const r = await git(args, o);
|
|
157
|
+
if (r.code !== 0) throw new Error(`git ${op} failed (exit ${r.code ?? "unknown"})${r.stderr.trim() === "" ? "" : `: ${r.stderr.trim().slice(-300)}`}`);
|
|
158
|
+
return r.stdout;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The extension a key names when it folds to `lfs.extension.<name>.<variable>`, or undefined. Folded as Go's `strings.ToLower`
|
|
163
|
+
* would (simple case mapping: U+0130 to `i`, U+212A to `k`) and, as a superset, as JavaScript's `toLowerCase` (git-tools
|
|
164
|
+
* `foldings`, #184), so a subsection in any case (`lfs.Extension.x.clean`) counts as git-lfs would count it.
|
|
165
|
+
*/
|
|
166
|
+
function extensionName(key: string): string | undefined {
|
|
167
|
+
for (const folded of [Array.from(key, c => (c === "\u0130" ? "i" : c.toLowerCase())).join(""), key.toLowerCase()]) {
|
|
168
|
+
if (folded.startsWith(LFS_EXTENSION_PREFIX)) return folded.slice(LFS_EXTENSION_PREFIX.length).replace(/\.[^.]*$/, "");
|
|
169
|
+
}
|
|
170
|
+
return undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The call's effective Git LFS configuration (repository, worktree, include and command-line scopes), or undefined if none. */
|
|
174
|
+
async function lfsConfig(git: LfsRestoreGit, prefix: readonly string[]): Promise<LfsConfig | undefined> {
|
|
175
|
+
const r = await git([...prefix, "config", "-z", "--get-regexp", LFS_CONFIG_KEYS]);
|
|
176
|
+
if (r.code === 1) return undefined;
|
|
177
|
+
if (r.code !== 0) throw new Error(`git config failed (exit ${r.code ?? "unknown"})`);
|
|
178
|
+
const values = new Map<string, string>();
|
|
179
|
+
const extensions = new Set<string>();
|
|
180
|
+
for (const record of r.stdout.split("\0")) {
|
|
181
|
+
const newline = record.indexOf("\n");
|
|
182
|
+
const raw = newline < 0 ? record : record.slice(0, newline);
|
|
183
|
+
if (raw === "") continue;
|
|
184
|
+
const extension = extensionName(raw);
|
|
185
|
+
if (extension !== undefined) extensions.add(extension);
|
|
186
|
+
else values.set(raw.toLowerCase(), newline < 0 ? "" : record.slice(newline + 1).trim());
|
|
187
|
+
}
|
|
188
|
+
const skip = (v: string | undefined) => /(^|\s)--skip(\s|$)/.test(v ?? "");
|
|
189
|
+
const patterns = (v: string | undefined) => (v ?? "").split(",").map(s => s.trim()).filter(s => s !== "");
|
|
190
|
+
return {
|
|
191
|
+
filter: (values.get("filter.lfs.process") ?? "") !== "" || (values.get("filter.lfs.clean") ?? "") !== "",
|
|
192
|
+
skip: skip(values.get("filter.lfs.process")) || skip(values.get("filter.lfs.smudge")),
|
|
193
|
+
extensions: [...extensions], include: patterns(values.get("lfs.fetchinclude")), exclude: patterns(values.get("lfs.fetchexclude")),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Index entries (stage 0, regular files) the `filter=lfs` attribute selects. */
|
|
198
|
+
async function lfsEntries(git: LfsRestoreGit, prefix: readonly string[]): Promise<IndexEntry[]> {
|
|
199
|
+
const listed = await must(git, [...prefix, "ls-files", "-s", "-z", "--full-name", "--", ":(top,attr:filter=lfs)"], "ls-files",
|
|
200
|
+
{ maxOutputBytes: LFS_LISTING_MAX_BYTES });
|
|
201
|
+
const entries: IndexEntry[] = [];
|
|
202
|
+
for (const record of listed.split("\0")) {
|
|
203
|
+
const m = /^(100644|100755) ([0-9a-f]{40}|[0-9a-f]{64}) 0\t([\s\S]+)$/.exec(record);
|
|
204
|
+
if (m !== null) entries.push({ mode: m[1] ?? "", oid: m[2] ?? "", path: m[3] ?? "" });
|
|
205
|
+
}
|
|
206
|
+
return entries;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The directory above `target` resolves to itself: no link anywhere between the work tree root and the file. */
|
|
210
|
+
async function parentIntact(target: string, top: string, realTop: string): Promise<boolean> {
|
|
211
|
+
const parent = await fsp.realpath(dirname(target)).catch(() => null);
|
|
212
|
+
return parent !== null && foldCase(parent) === foldCase(join(realTop, relative(top, dirname(target))));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The pointer the work tree file holds, when it is exactly the index's blob; never through a link. */
|
|
216
|
+
async function pointerOf(entry: IndexEntry, top: string, realTop: string): Promise<Omit<Planned, "object"> | undefined> {
|
|
217
|
+
const segments = entry.path.split("/");
|
|
218
|
+
if (isAbsolute(entry.path) || segments.some(s => s === "" || s === "." || s === "..")) return undefined;
|
|
219
|
+
// NTFS: a `:` names an alternate data stream and a `\` another directory.
|
|
220
|
+
if (process.platform === "win32" && segments.some(s => s.includes(":") || s.includes("\\"))) return undefined;
|
|
221
|
+
const target = join(top, ...segments);
|
|
222
|
+
if (!inside(top, target)) return undefined;
|
|
223
|
+
const st = await fsp.lstat(target).catch(() => null);
|
|
224
|
+
if (st === null || !st.isFile() || st.size > POINTER_MAX_BYTES) return undefined;
|
|
225
|
+
if (!(await parentIntact(target, top, realTop))) return undefined;
|
|
226
|
+
const content = await fsp.readFile(target);
|
|
227
|
+
const blob = createHash(entry.oid.length === 40 ? "sha1" : "sha256").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
228
|
+
if (blob !== entry.oid) return undefined; // changed since git wrote it
|
|
229
|
+
const pointer = parseLfsPointer(content.toString("latin1"));
|
|
230
|
+
if (pointer === undefined) return undefined; // not canonical, with extensions, or of size 0: stays a pointer
|
|
231
|
+
return { path: entry.path, target, oid: pointer.oid, size: pointer.size, pointer: content, mode: st.mode, indexMode: entry.mode };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Copies at most `size` bytes of the object to `temp` (created exclusively) and checks its sha256 and size on the way. */
|
|
235
|
+
async function copyVerified(p: Planned, temp: string, signal: AbortSignal | undefined): Promise<void> {
|
|
236
|
+
const hash = createHash("sha256");
|
|
237
|
+
let bytes = 0;
|
|
238
|
+
// `size` is at least 1 (parseLfsPointer): a size-0 pointer is never planned.
|
|
239
|
+
const tap = new Transform({
|
|
240
|
+
transform(chunk: Buffer, _encoding, done) { hash.update(chunk); bytes += chunk.length; done(null, chunk); },
|
|
241
|
+
});
|
|
242
|
+
await pipeline(createReadStream(p.object, { start: 0, end: p.size - 1 }), tap, createWriteStream(temp, { flags: "wx" }),
|
|
243
|
+
signal === undefined ? {} : { signal });
|
|
244
|
+
if (bytes !== p.size || hash.digest("hex") !== p.oid) throw new Error(`the local object of ${p.path} does not match its oid`);
|
|
245
|
+
if (process.platform !== "win32") await fsp.chmod(temp, p.mode & 0o7777);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function renameRetrying(from: string, to: string): Promise<void> {
|
|
249
|
+
for (let attempt = 0; ; attempt++) {
|
|
250
|
+
try {
|
|
251
|
+
await fsp.rename(from, to);
|
|
252
|
+
return;
|
|
253
|
+
} catch (error) {
|
|
254
|
+
const code = codeOf(error);
|
|
255
|
+
const transient = code === "EBUSY" || (process.platform === "win32" && (code === "EPERM" || code === "EACCES"));
|
|
256
|
+
const delay = RENAME_RETRY_DELAYS_MS[attempt];
|
|
257
|
+
if (!transient || delay === undefined) throw error;
|
|
258
|
+
await sleep(delay);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** L2: removes a temporary or backup file, retrying a transient lock as {@link renameRetrying} does; throws once it gives up. */
|
|
264
|
+
async function rmRetrying(path: string): Promise<void> {
|
|
265
|
+
for (let attempt = 0; ; attempt++) {
|
|
266
|
+
try {
|
|
267
|
+
await fsp.rm(path, { force: true });
|
|
268
|
+
return;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
const code = codeOf(error);
|
|
271
|
+
const transient = code === "EBUSY" || (process.platform === "win32" && (code === "EPERM" || code === "EACCES"));
|
|
272
|
+
const delay = RENAME_RETRY_DELAYS_MS[attempt];
|
|
273
|
+
if (!transient || delay === undefined) throw error;
|
|
274
|
+
await sleep(delay);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function tempNextTo(target: string): string {
|
|
280
|
+
return join(dirname(target), `.omr-lfs-${randomBytes(6).toString("hex")}`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The last `core.hooksPath` the call sets, when it names a real file to check (not the null device). */
|
|
284
|
+
function hooksPathOf(prefix: readonly string[]): string | undefined {
|
|
285
|
+
let value: string | undefined;
|
|
286
|
+
for (let n = 0; n < prefix.length; n++) {
|
|
287
|
+
if (prefix[n] !== "-c") continue;
|
|
288
|
+
const setting = prefix[++n] ?? "";
|
|
289
|
+
if (setting.toLowerCase().startsWith("core.hookspath=")) value = setting.slice("core.hooksPath=".length);
|
|
290
|
+
}
|
|
291
|
+
return value !== undefined && isAbsolute(value) && !NULL_DEVICES.has(value.toLowerCase()) ? value : undefined;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Restores, in the work tree `target` names, every LFS file that is still the pointer git wrote and whose object is in the
|
|
296
|
+
* repository's local LFS store (`<common dir>/lfs/objects/<aa>/<bb>/<oid>`, regular file, size and sha256 verified).
|
|
297
|
+
* Nothing is restored when the call's configuration has no Git LFS clean filter, opts out (`--skip` in `filter.lfs.process`
|
|
298
|
+
* or `filter.lfs.smudge`) or names an extension; `lfs.fetchinclude`/`lfs.fetchexclude` select the files. Pointers with
|
|
299
|
+
* extensions, non-canonical pointers, files changed since git wrote them, paths under a link and missing objects stay as they
|
|
300
|
+
* are. Every object is copied and verified next to its file first; each file is then replaced by a rename (a copy of its
|
|
301
|
+
* pointer kept beside it), and `git update-index -- <paths>` re-hashes them so git sees them unchanged. It never throws: over
|
|
302
|
+
* its bounds, on an oversized listing or on any error it leaves pointer files and returns a warning; after a failed
|
|
303
|
+
* replacement or re-hash it renames the pointers it replaced back and restores their index entries.
|
|
304
|
+
*/
|
|
305
|
+
export async function restoreLocalLfsObjects(
|
|
306
|
+
git: LfsRestoreGit, target: LfsRestoreTarget, options: LfsRestoreOptions = {},
|
|
307
|
+
): Promise<LfsRestoreResult> {
|
|
308
|
+
const { prefix, cwd } = target;
|
|
309
|
+
const { signal } = options;
|
|
310
|
+
const left = (reason: string): LfsRestoreResult =>
|
|
311
|
+
({ restored: [], warning: `local LFS restore in ${cwd}: ${reason}; its LFS files stay pointer files (\`git lfs checkout\` there restores them)` });
|
|
312
|
+
// Every git call the restore makes is preceded by the executor's hooks check (as GitOps' assertHooksOff).
|
|
313
|
+
const hooks = hooksPathOf(prefix);
|
|
314
|
+
const call: LfsRestoreGit = async (args, o) => {
|
|
315
|
+
if (hooks !== undefined) {
|
|
316
|
+
const st = await fsp.lstat(hooks).catch(() => null);
|
|
317
|
+
if (st === null || !st.isFile() || st.size !== 0) throw new Error(`the hooks path ${hooks} is not an empty regular file`);
|
|
318
|
+
}
|
|
319
|
+
return git(args, o);
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
let config: LfsConfig | undefined;
|
|
323
|
+
let entries: IndexEntry[];
|
|
324
|
+
let top: string;
|
|
325
|
+
let common: string;
|
|
326
|
+
let realTop: string;
|
|
327
|
+
const planned: Planned[] = [];
|
|
328
|
+
try {
|
|
329
|
+
config = await lfsConfig(call, prefix);
|
|
330
|
+
if (config === undefined || !config.filter || config.skip) return { restored: [] };
|
|
331
|
+
if (config.extensions.length > 0) {
|
|
332
|
+
return left(`the configuration names Git LFS extensions (${config.extensions.join(", ")}), whose programs git's clean filter would run`);
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
entries = await lfsEntries(call, prefix);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (codeOf(error) === "EOUTPUT") return left(`its LFS file listing exceeds ${LFS_LISTING_MAX_BYTES} bytes`);
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
if (entries.length === 0) return { restored: [] };
|
|
341
|
+
const located = (await must(call, [...prefix, "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"], "rev-parse"))
|
|
342
|
+
.split(/\r?\n/).filter(line => line !== "");
|
|
343
|
+
[top = "", common = ""] = located;
|
|
344
|
+
if (!isAbsolute(top) || !isAbsolute(common)) return left("git rev-parse did not name the work tree and the common directory");
|
|
345
|
+
realTop = await fsp.realpath(top);
|
|
346
|
+
const { include, exclude } = config;
|
|
347
|
+
let bytes = 0;
|
|
348
|
+
for (const entry of entries) {
|
|
349
|
+
if (include.length > 0 && !include.some(p => matchesLfsFetchPattern(entry.path, p, "include"))) continue;
|
|
350
|
+
if (exclude.some(p => matchesLfsFetchPattern(entry.path, p, "exclude"))) continue;
|
|
351
|
+
const found = await pointerOf(entry, top, realTop);
|
|
352
|
+
if (found === undefined) continue;
|
|
353
|
+
const object = join(common, "lfs", "objects", found.oid.slice(0, 2), found.oid.slice(2, 4), found.oid);
|
|
354
|
+
const st = await fsp.lstat(object).catch(() => null);
|
|
355
|
+
if (st === null || !st.isFile() || st.size !== found.size) continue; // not local: stays a pointer
|
|
356
|
+
planned.push({ ...found, object });
|
|
357
|
+
bytes += found.size;
|
|
358
|
+
}
|
|
359
|
+
if (planned.length === 0) return { restored: [] };
|
|
360
|
+
const maxFiles = options.maxFiles ?? LFS_RESTORE_MAX_FILES;
|
|
361
|
+
const maxBytes = options.maxBytes ?? LFS_RESTORE_MAX_BYTES;
|
|
362
|
+
if (planned.length > maxFiles || bytes > maxBytes) {
|
|
363
|
+
return left(`${planned.length} file(s) (${bytes} bytes) exceed its bound of ${maxFiles} files and ${maxBytes} bytes`);
|
|
364
|
+
}
|
|
365
|
+
} catch (error) {
|
|
366
|
+
return left(errorText(error));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// From here files change: every failure renames back the pointers this restore replaced.
|
|
370
|
+
const staged: Array<{ p: Planned; temp: string }> = [];
|
|
371
|
+
const replaced: Array<{ p: Planned; backup: string }> = [];
|
|
372
|
+
const putBack = async (which: ReadonlyArray<{ p: Planned; backup: string }>): Promise<string[]> => {
|
|
373
|
+
const failed: string[] = [];
|
|
374
|
+
for (const r of [...which].reverse()) {
|
|
375
|
+
try {
|
|
376
|
+
if (!(await parentIntact(r.p.target, top, realTop))) throw new Error("a link appeared above it");
|
|
377
|
+
await renameRetrying(r.backup, r.p.target);
|
|
378
|
+
} catch (error) {
|
|
379
|
+
failed.push(`${r.p.path} (${errorText(error)})`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return failed;
|
|
383
|
+
};
|
|
384
|
+
const describe = (reason: string, failed: readonly string[]): LfsRestoreResult => ({
|
|
385
|
+
restored: [],
|
|
386
|
+
warning: `${left(reason).warning ?? ""}${failed.length === 0 ? "" : `; ${failed.length} file(s) could not be put back and keep their content: ${failed.join(", ")}`}`,
|
|
387
|
+
});
|
|
388
|
+
// L2: a temporary or backup file still there after the retries is named in the warning (and `.omr-lfs-*` is in the slots'
|
|
389
|
+
// excludes, so `add -A` never stages it).
|
|
390
|
+
const leftover: string[] = [];
|
|
391
|
+
const removeAll = async (paths: readonly string[]) => {
|
|
392
|
+
for (const path of paths) await rmRetrying(path).catch(() => { leftover.push(path); });
|
|
393
|
+
};
|
|
394
|
+
const noting = (r: LfsRestoreResult): LfsRestoreResult => leftover.length === 0 ? r : {
|
|
395
|
+
...r,
|
|
396
|
+
warning: `${r.warning ?? `local LFS restore in ${cwd}: restored ${r.restored.length} file(s)`}; `
|
|
397
|
+
+ `${leftover.length} temporary file(s) could not be removed: ${leftover.join(", ")}`,
|
|
398
|
+
};
|
|
399
|
+
try {
|
|
400
|
+
for (const p of planned) {
|
|
401
|
+
if (signal?.aborted === true) throw new Error("aborted");
|
|
402
|
+
const temp = tempNextTo(p.target);
|
|
403
|
+
staged.push({ p, temp });
|
|
404
|
+
await copyVerified(p, temp, signal);
|
|
405
|
+
}
|
|
406
|
+
for (const { p, temp } of staged) {
|
|
407
|
+
if (signal?.aborted === true) throw new Error("aborted");
|
|
408
|
+
if (!(await parentIntact(p.target, top, realTop))) throw new Error(`a link appeared above ${p.path}`);
|
|
409
|
+
// Replace only what is still the pointer git wrote; its pointer is kept beside it for a rollback.
|
|
410
|
+
const now = await fsp.readFile(p.target).catch(() => null);
|
|
411
|
+
if (now === null || !now.equals(p.pointer)) continue;
|
|
412
|
+
const backup = tempNextTo(p.target);
|
|
413
|
+
await fsp.writeFile(backup, p.pointer, { flag: "wx" });
|
|
414
|
+
try {
|
|
415
|
+
await renameRetrying(temp, p.target);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
await removeAll([backup]);
|
|
418
|
+
throw error;
|
|
419
|
+
}
|
|
420
|
+
replaced.push({ p, backup });
|
|
421
|
+
}
|
|
422
|
+
} catch (error) {
|
|
423
|
+
const failed = await putBack(replaced);
|
|
424
|
+
await removeAll(staged.map(s => s.temp));
|
|
425
|
+
return noting(describe(errorText(error), failed));
|
|
426
|
+
}
|
|
427
|
+
await removeAll(staged.map(s => s.temp));
|
|
428
|
+
if (replaced.length === 0) return noting({ restored: [] });
|
|
429
|
+
|
|
430
|
+
// Re-hash the restored files so git records their new size: a refresh alone keeps reading them as changed.
|
|
431
|
+
let gitCwd = cwd;
|
|
432
|
+
for (let n = 0; n < prefix.length; n++) if (prefix[n] === "-C") gitCwd = resolve(gitCwd, prefix[++n] ?? "");
|
|
433
|
+
const realCwd = await fsp.realpath(gitCwd).catch(() => gitCwd);
|
|
434
|
+
const relativeTo = (p: Planned): string => foldCase(realCwd) === foldCase(realTop) || !inside(realTop, realCwd)
|
|
435
|
+
? p.path : relative(realCwd, join(realTop, ...p.path.split("/"))).split(sep).join("/");
|
|
436
|
+
const batches: string[][] = [[]];
|
|
437
|
+
let chars = 0;
|
|
438
|
+
for (const { p } of replaced) {
|
|
439
|
+
const path = relativeTo(p);
|
|
440
|
+
if (chars + path.length > UPDATE_INDEX_BATCH_CHARS && (batches[batches.length - 1] ?? []).length > 0) { batches.push([]); chars = 0; }
|
|
441
|
+
batches[batches.length - 1]?.push(path);
|
|
442
|
+
chars += path.length + 1;
|
|
443
|
+
}
|
|
444
|
+
const rehashed: string[][] = [];
|
|
445
|
+
try {
|
|
446
|
+
for (const batch of batches) {
|
|
447
|
+
await must(call, [...prefix, "update-index", "--", ...batch], "update-index");
|
|
448
|
+
rehashed.push(batch);
|
|
449
|
+
}
|
|
450
|
+
} catch (error) {
|
|
451
|
+
const failed = await putBack(replaced);
|
|
452
|
+
// The entries already re-hashed record the content's size: re-hash the pointers back.
|
|
453
|
+
let index = "";
|
|
454
|
+
try {
|
|
455
|
+
for (const batch of rehashed) await must(call, [...prefix, "update-index", "--", ...batch], "update-index");
|
|
456
|
+
} catch (again) {
|
|
457
|
+
index = `; git's index still records the restored size of ${rehashed.flat().join(", ")} (${errorText(again)}): git status may show them modified`;
|
|
458
|
+
}
|
|
459
|
+
await removeAll(replaced.map(r => r.backup));
|
|
460
|
+
const result = describe(errorText(error), failed);
|
|
461
|
+
return noting({ restored: [], warning: `${result.warning ?? ""}${index}` });
|
|
462
|
+
}
|
|
463
|
+
// The index must still name the same pointers: a different clean result would have staged a change.
|
|
464
|
+
const before = new Map(entries.map(e => [e.path, e.oid]));
|
|
465
|
+
let after: Map<string, string>;
|
|
466
|
+
try {
|
|
467
|
+
after = new Map((await lfsEntries(call, prefix)).map(e => [e.path, e.oid]));
|
|
468
|
+
} catch (error) {
|
|
469
|
+
await removeAll(replaced.map(r => r.backup));
|
|
470
|
+
return noting({ restored: replaced.map(r => r.p.path),
|
|
471
|
+
warning: `local LFS restore in ${cwd}: restored ${replaced.length} file(s), but git's index could not be read back to check them: ${errorText(error)}` });
|
|
472
|
+
}
|
|
473
|
+
const changed = replaced.filter(r => after.get(r.p.path) !== before.get(r.p.path));
|
|
474
|
+
let warning: string | undefined;
|
|
475
|
+
if (changed.length > 0) {
|
|
476
|
+
const notes: string[] = [];
|
|
477
|
+
for (const r of changed) {
|
|
478
|
+
try {
|
|
479
|
+
// git reads a `--cacheinfo` path from the work tree's top, never relative to the cwd.
|
|
480
|
+
await must(call, [...prefix, "update-index", "--cacheinfo", `${r.p.indexMode},${before.get(r.p.path) ?? ""},${r.p.path}`], "update-index --cacheinfo");
|
|
481
|
+
} catch (error) {
|
|
482
|
+
notes.push(`the index entry of ${r.p.path} could not be restored (${errorText(error)})`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
const failed = await putBack(changed);
|
|
486
|
+
warning = `${describe(`re-hashing changed the index entry of ${changed.map(r => r.p.path).join(", ")}`, failed).warning ?? ""}`
|
|
487
|
+
+ (notes.length === 0 ? "" : `; ${notes.join("; ")}`);
|
|
488
|
+
}
|
|
489
|
+
await removeAll(replaced.filter(r => !changed.includes(r)).map(r => r.backup));
|
|
490
|
+
const restored = replaced.filter(r => !changed.includes(r)).map(r => r.p.path);
|
|
491
|
+
return noting(warning === undefined ? { restored } : { restored, warning });
|
|
492
|
+
}
|
package/src/executor/paths.ts
CHANGED
|
@@ -27,6 +27,9 @@ export const EXECUTOR_HOME_DIRNAME = "omr-executor";
|
|
|
27
27
|
/** Name of the directory under the executor home that holds the slot markers (2.2.1.b). */
|
|
28
28
|
export const SLOT_MARKERS_DIRNAME = "slots";
|
|
29
29
|
|
|
30
|
+
/** #189 R2-pre-2: the directory under the executor home that holds the verification process journals, one per plan. */
|
|
31
|
+
export const VERIFY_TREES_DIRNAME = "verify-trees";
|
|
32
|
+
|
|
30
33
|
/** Result of one git run: the exit code (null when killed) and both streams as text. */
|
|
31
34
|
export interface GitRunResult {
|
|
32
35
|
code: number | null;
|
|
@@ -101,14 +104,16 @@ export async function resolveExecutorHome(dir: string, deps: ExecutorPathsDeps =
|
|
|
101
104
|
}
|
|
102
105
|
|
|
103
106
|
/**
|
|
104
|
-
* True when `id` is a well-formed plan id (`PLAN_ID_PATTERN`, 2.2.1.c). The slot markers directory name (`slots`)
|
|
105
|
-
* case-insensitively because the home lives on a
|
|
107
|
+
* True when `id` is a well-formed plan id (`PLAN_ID_PATTERN`, 2.2.1.c). The slot markers directory name (`slots`) and the
|
|
108
|
+
* verification journal directory name (`verify-trees`) are reserved, compared case-insensitively because the home lives on a
|
|
109
|
+
* case-insensitive filesystem on Windows: a plan of either name would collide with it.
|
|
106
110
|
*/
|
|
107
111
|
export function isPlanId(id: unknown): id is PlanId {
|
|
108
112
|
return (
|
|
109
113
|
typeof id === "string" &&
|
|
110
114
|
PLAN_ID_PATTERN.test(id) &&
|
|
111
115
|
id.toLowerCase() !== SLOT_MARKERS_DIRNAME &&
|
|
116
|
+
id.toLowerCase() !== VERIFY_TREES_DIRNAME &&
|
|
112
117
|
!WINDOWS_DEVICE_NAME.test(id)
|
|
113
118
|
);
|
|
114
119
|
}
|
package/src/executor/recovery.ts
CHANGED
|
@@ -120,7 +120,8 @@ function inferSharedContext(prompt: string): string | null {
|
|
|
120
120
|
function normalizeToplevel(p: string): string {
|
|
121
121
|
let real = p;
|
|
122
122
|
try {
|
|
123
|
-
|
|
123
|
+
// QA-4.2-42 (#189): the native realpath expands win32 8.3 short names; the JS one keeps them.
|
|
124
|
+
real = realpathSync.native(p);
|
|
124
125
|
} catch {
|
|
125
126
|
// a path that cannot be resolved is compared as written
|
|
126
127
|
}
|