opencode-model-router 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
@@ -0,0 +1,876 @@
1
+ /**
2
+ * Cross-repo Phase 4: the store of repositories outside `routing.repoParents` that a human approved
3
+ * with `/router approve` (design `docs/design/cross-repo-phase4-plan.md`, SD-P4-1..3, -8, -9).
4
+ *
5
+ * No git runs in this file. The store is a small JSON file next to the router state:
6
+ * `{version: 1, approvals: [{path, commonDir, roots[], origin, approvedAt, lastUsedAt}]}` (times in
7
+ * epoch ms). A file that is not valid as a whole (JSON, version, size, entry count) means no approvals
8
+ * (fail closed) and one notice. A single invalid entry is dropped when read. Writes run one at a time
9
+ * in the process, re-read the file, apply one operation and go through a tmp file and a rename.
10
+ */
11
+ import * as fs from "node:fs";
12
+ import * as os from "node:os";
13
+ import * as path from "node:path";
14
+
15
+ import { configPath, overridePath, statePath } from "../../router/config";
16
+ import { REPO_APPROVAL_CAP_DAYS } from "../../router/roles-config";
17
+ import { permissionMatches } from "../../router/read-only";
18
+ // Static, not `await import`: dynamic imports made a bundle split src/router/config.ts into a chunk where its tiers.json
19
+ // lookup fails. The cycle with admission.ts is safe: each side uses the other only inside functions.
20
+ import * as admission from "./admission";
21
+ import { displaySafe } from "./read-set";
22
+
23
+ export const APPROVALS_FILE_NAME = "opencode-model-router.repo-approvals.json";
24
+ export const APPROVALS_VERSION = 1;
25
+ /** At most this many entries; a file with more is invalid, and `put` refuses at this count. */
26
+ export const MAX_APPROVALS = 32;
27
+ /** The store file is at most this many bytes; checked with `stat` before reading. */
28
+ export const MAX_APPROVALS_BYTES = 256 * 1024;
29
+ /** A stored time further than this in the future invalidates its entry. */
30
+ export const MAX_FUTURE_SKEW_MS = 5 * 60_000;
31
+ /** `touch` writes at most once per this interval per path. */
32
+ export const TOUCH_INTERVAL_MS = 60 * 60_000;
33
+ /** Shown when there is no origin. */
34
+ export const NO_ORIGIN = "none";
35
+ /** Origins shown to the human are capped at this many characters. */
36
+ export const MAX_ORIGIN_CHARS = 200;
37
+
38
+ const DAY_MS = 86_400_000;
39
+ const MAX_PATH_CHARS = 1024;
40
+ const MAX_ROOTS = 64;
41
+ const HEX_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
42
+ const ENTRY_KEYS = new Set(["path", "commonDir", "roots", "origin", "approvedAt", "lastUsedAt"]);
43
+
44
+ /** One approved repository (a main worktree). */
45
+ export interface RepoApproval {
46
+ /** Canonical path of the main worktree, as text. */
47
+ readonly path: string;
48
+ /** Canonical git common dir (`<path>\.git`). */
49
+ readonly commonDir: string;
50
+ /** Sorted root commits (`git rev-list --max-parents=0 HEAD`). */
51
+ readonly roots: readonly string[];
52
+ /** Sanitized origin ({@link sanitizeOrigin}); `none` when absent. */
53
+ readonly origin: string;
54
+ readonly approvedAt: number;
55
+ readonly lastUsedAt: number;
56
+ }
57
+
58
+ /** Fields of a new approval; the store sets the times. */
59
+ export interface NewRepoApproval {
60
+ readonly path: string;
61
+ readonly commonDir: string;
62
+ readonly roots: readonly string[];
63
+ /** Raw or sanitized origin; stored through {@link sanitizeOrigin}. */
64
+ readonly origin?: string;
65
+ }
66
+
67
+ /** Injectable environment, for tests. */
68
+ export interface ApprovalsEnv {
69
+ /** Directory of the store; default `dirname(statePath())`. */
70
+ readonly dir?: string;
71
+ /** Clock in epoch ms; default `Date.now`. */
72
+ readonly now?: () => number;
73
+ /** Sink for the one notice about an invalid file; default `console.warn`. */
74
+ readonly warn?: (message: string) => void;
75
+ /** Test only: runs after the tmp file is written and before the rename (throw to simulate a crash). */
76
+ readonly beforeRename?: (tmp: string) => void;
77
+ }
78
+
79
+ export interface ApprovalsRead {
80
+ /** The store file. */
81
+ readonly file: string;
82
+ /** Valid entries (expired ones included; see {@link isApprovalValid}). Empty when `invalid` is set. */
83
+ readonly approvals: readonly RepoApproval[];
84
+ /** Set when the file as a whole is invalid: no approvals apply and `put`/`delete` refuse. */
85
+ readonly invalid?: string;
86
+ /** One line per entry dropped by the per-entry validation. */
87
+ readonly dropped: readonly string[];
88
+ }
89
+
90
+ export type ApprovalOp =
91
+ | { readonly kind: "put"; readonly approval: NewRepoApproval; readonly days: number }
92
+ | { readonly kind: "delete"; readonly path: string }
93
+ | { readonly kind: "touch"; readonly path: string; readonly roots: readonly string[]; readonly days: number };
94
+
95
+ export type ApplyOutcome =
96
+ | { readonly status: "written"; readonly file: string; readonly entry?: RepoApproval }
97
+ | { readonly status: "unchanged"; readonly file: string; readonly reason: "absent" | "mismatch" | "expired" | "throttled" }
98
+ | {
99
+ readonly status: "refused";
100
+ readonly file: string;
101
+ readonly reason: "invalid-store" | "invalid-entry" | "full" | "io" | "read-back";
102
+ readonly message: string;
103
+ };
104
+
105
+ const warned = new Set<string>();
106
+ const lastTouched = new Map<string, number>();
107
+ const queues = new Map<string, Promise<unknown>>();
108
+
109
+ /** Test only: re-arm the invalid-file notice and forget the in-memory touch throttle and the identity caches. */
110
+ export function resetApprovalsState(): void {
111
+ warned.clear();
112
+ lastTouched.clear();
113
+ resetIdentityCaches();
114
+ }
115
+
116
+ /** The store file: `dirname(statePath())/opencode-model-router.repo-approvals.json`. */
117
+ export function approvalsPath(env: ApprovalsEnv = {}): string {
118
+ return path.join(env.dir ?? path.dirname(statePath()), APPROVALS_FILE_NAME);
119
+ }
120
+
121
+ function clock(env: ApprovalsEnv): number {
122
+ return (env.now ?? Date.now)();
123
+ }
124
+
125
+ /** Comparison key of a path: case-insensitive on Windows. */
126
+ function pathKey(p: string): string {
127
+ return process.platform === "win32" ? p.toLowerCase() : p;
128
+ }
129
+
130
+ function clampDays(days: number): number {
131
+ if (!Number.isFinite(days)) return 1;
132
+ return Math.min(Math.max(Math.trunc(days), 1), REPO_APPROVAL_CAP_DAYS);
133
+ }
134
+
135
+ /** `min(lastUsedAt + days, approvedAt + 90 days)`, in epoch ms. */
136
+ export function expiresAt(entry: Pick<RepoApproval, "approvedAt" | "lastUsedAt">, days: number): number {
137
+ return Math.min(entry.lastUsedAt + clampDays(days) * DAY_MS, entry.approvedAt + REPO_APPROVAL_CAP_DAYS * DAY_MS);
138
+ }
139
+
140
+ /** An approval is valid iff `now < expiresAt(entry, days)`. */
141
+ export function isApprovalValid(entry: Pick<RepoApproval, "approvedAt" | "lastUsedAt">, days: number, now: number): boolean {
142
+ return now < expiresAt(entry, days);
143
+ }
144
+
145
+ /** Problem with a stored path text, or undefined: absolute, already normalized, no device prefix, no glob or control characters. */
146
+ function storedPathProblem(p: unknown): string | undefined {
147
+ if (typeof p !== "string" || p === "") return "is not a non-empty string";
148
+ if (p.length > MAX_PATH_CHARS) return `is longer than ${MAX_PATH_CHARS} characters`;
149
+ // eslint-disable-next-line no-control-regex
150
+ if (/[\u0000-\u001f\u007f]/.test(p)) return "contains a control character";
151
+ if (/[*?"<>|]/.test(p)) return "contains a glob or reserved character";
152
+ if (p.startsWith("\\\\?\\") || p.startsWith("\\\\.\\") || p.startsWith("//?/") || p.startsWith("//./")) return "is a device path";
153
+ if (!path.isAbsolute(p)) return "is not absolute";
154
+ if (path.resolve(p) !== p) return "is not in normalized form";
155
+ return undefined;
156
+ }
157
+
158
+ function isPlainRecord(v: unknown): v is Record<string, unknown> {
159
+ return typeof v === "object" && v !== null && !Array.isArray(v);
160
+ }
161
+
162
+ function isTime(v: unknown): v is number {
163
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
164
+ }
165
+
166
+ function rootsProblem(roots: unknown): string | undefined {
167
+ if (!Array.isArray(roots) || roots.length === 0) return "roots is not a non-empty array";
168
+ if (roots.length > MAX_ROOTS) return `roots has more than ${MAX_ROOTS} entries`;
169
+ const seen = new Set<string>();
170
+ for (const r of roots as unknown[]) {
171
+ if (typeof r !== "string" || !HEX_SHA.test(r)) return "roots holds a value that is not a hex SHA";
172
+ if (seen.has(r)) return "roots holds a duplicate";
173
+ seen.add(r);
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ function entryProblem(raw: unknown, now: number): string | undefined {
179
+ if (!isPlainRecord(raw)) return "is not an object";
180
+ for (const key of Object.keys(raw)) if (!ENTRY_KEYS.has(key)) return `has an unknown field ${JSON.stringify(key)}`;
181
+ const p = storedPathProblem(raw.path);
182
+ if (p !== undefined) return `path ${p}`;
183
+ const c = storedPathProblem(raw.commonDir);
184
+ if (c !== undefined) return `commonDir ${c}`;
185
+ const r = rootsProblem(raw.roots);
186
+ if (r !== undefined) return r;
187
+ if (typeof raw.origin !== "string" || raw.origin.length > MAX_ORIGIN_CHARS || sanitizeOrigin(raw.origin) !== raw.origin) {
188
+ return "origin is not a sanitized origin";
189
+ }
190
+ if (!isTime(raw.approvedAt) || !isTime(raw.lastUsedAt)) return "a time is not an epoch-ms integer";
191
+ if (raw.approvedAt > raw.lastUsedAt) return "approvedAt is after lastUsedAt";
192
+ if (raw.lastUsedAt > now + MAX_FUTURE_SKEW_MS) return "a time is more than 5 minutes in the future";
193
+ return undefined;
194
+ }
195
+
196
+ function toEntry(raw: Record<string, unknown>): RepoApproval {
197
+ return Object.freeze({
198
+ path: raw.path as string,
199
+ commonDir: raw.commonDir as string,
200
+ roots: Object.freeze([...(raw.roots as string[])].sort()),
201
+ origin: raw.origin as string,
202
+ approvedAt: raw.approvedAt as number,
203
+ lastUsedAt: raw.lastUsedAt as number,
204
+ });
205
+ }
206
+
207
+ function notice(env: ApprovalsEnv, file: string, problem: string): void {
208
+ const key = `${file}\u0000${problem}`;
209
+ if (warned.has(key)) return;
210
+ warned.add(key);
211
+ const message = `repository approvals file ${file} is invalid (${problem}); no approvals apply until it is fixed or removed`;
212
+ if (env.warn) env.warn(message);
213
+ else console.warn(`[model-router] ${message}`);
214
+ }
215
+
216
+ function invalidRead(env: ApprovalsEnv, file: string, problem: string): ApprovalsRead {
217
+ notice(env, file, problem);
218
+ return Object.freeze({ file, approvals: Object.freeze([]), invalid: problem, dropped: Object.freeze([]) });
219
+ }
220
+
221
+ function errCode(e: unknown): string | undefined {
222
+ return isPlainRecord(e) && typeof e.code === "string" ? e.code : undefined;
223
+ }
224
+
225
+ /**
226
+ * Reads the store without git. A missing file is an empty store. A file that is not a regular file,
227
+ * is larger than {@link MAX_APPROVALS_BYTES} (checked with `stat` first), is not JSON, has another
228
+ * version or more than {@link MAX_APPROVALS} entries gives no approvals, `invalid` set and one notice.
229
+ * An invalid entry is dropped; two entries with the same path are both dropped.
230
+ */
231
+ export function readApprovals(env: ApprovalsEnv = {}): ApprovalsRead {
232
+ const file = approvalsPath(env);
233
+ let stat: fs.Stats;
234
+ try {
235
+ // lstat: a link in place of the store is not a regular file (fail closed).
236
+ stat = fs.lstatSync(file);
237
+ } catch (e) {
238
+ if (errCode(e) === "ENOENT") return Object.freeze({ file, approvals: Object.freeze([]), dropped: Object.freeze([]) });
239
+ return invalidRead(env, file, `cannot be read: ${errCode(e) ?? "error"}`);
240
+ }
241
+ if (!stat.isFile()) return invalidRead(env, file, "is not a regular file");
242
+ if (stat.size > MAX_APPROVALS_BYTES) return invalidRead(env, file, `is larger than ${MAX_APPROVALS_BYTES / 1024} KiB`);
243
+ let buf: Buffer;
244
+ try {
245
+ buf = fs.readFileSync(file);
246
+ } catch (e) {
247
+ if (errCode(e) === "ENOENT") return Object.freeze({ file, approvals: Object.freeze([]), dropped: Object.freeze([]) });
248
+ return invalidRead(env, file, `cannot be read: ${errCode(e) ?? "error"}`);
249
+ }
250
+ if (buf.length > MAX_APPROVALS_BYTES) return invalidRead(env, file, `is larger than ${MAX_APPROVALS_BYTES / 1024} KiB`);
251
+ let data: unknown;
252
+ try {
253
+ data = JSON.parse(buf.toString("utf8"));
254
+ } catch {
255
+ return invalidRead(env, file, "is not valid JSON");
256
+ }
257
+ if (!isPlainRecord(data)) return invalidRead(env, file, "is not a JSON object");
258
+ if (data.version !== APPROVALS_VERSION) return invalidRead(env, file, `has an unknown version (expected ${APPROVALS_VERSION})`);
259
+ const list = data.approvals;
260
+ if (!Array.isArray(list)) return invalidRead(env, file, "has no approvals array");
261
+ if (list.length > MAX_APPROVALS) return invalidRead(env, file, `has more than ${MAX_APPROVALS} entries`);
262
+
263
+ const now = clock(env);
264
+ const dropped: string[] = [];
265
+ const valid: { index: number; entry: RepoApproval }[] = [];
266
+ (list as unknown[]).forEach((raw, index) => {
267
+ const problem = entryProblem(raw, now);
268
+ if (problem !== undefined) dropped.push(`approvals[${index}] ${problem}; dropped`);
269
+ else valid.push({ index, entry: toEntry(raw as Record<string, unknown>) });
270
+ });
271
+ const counts = new Map<string, number>();
272
+ for (const { entry } of valid) counts.set(pathKey(entry.path), (counts.get(pathKey(entry.path)) ?? 0) + 1);
273
+ const approvals: RepoApproval[] = [];
274
+ for (const { index, entry } of valid) {
275
+ if ((counts.get(pathKey(entry.path)) ?? 0) > 1) dropped.push(`approvals[${index}] path is a duplicate; dropped`);
276
+ else approvals.push(entry);
277
+ }
278
+ return Object.freeze({ file, approvals: Object.freeze(approvals), dropped: Object.freeze(dropped) });
279
+ }
280
+
281
+ function sameRoots(a: readonly string[], b: readonly string[]): boolean {
282
+ const x = [...a].sort();
283
+ const y = [...b].sort();
284
+ return x.length === y.length && x.every((v, i) => v === y[i]);
285
+ }
286
+
287
+ function sameEntry(a: RepoApproval, b: RepoApproval): boolean {
288
+ return a.path === b.path && a.commonDir === b.commonDir && sameRoots(a.roots, b.roots) && a.origin === b.origin
289
+ && a.approvedAt === b.approvedAt && a.lastUsedAt === b.lastUsedAt;
290
+ }
291
+
292
+ /**
293
+ * Writes the store through a tmp file and a rename, like `writeState` (config.ts). Returns an error
294
+ * message, or undefined. A crash before the rename leaves the previous file as it was.
295
+ */
296
+ function writeStore(env: ApprovalsEnv, file: string, approvals: readonly RepoApproval[]): string | undefined {
297
+ const body = `${JSON.stringify({ version: APPROVALS_VERSION, approvals }, null, 2)}\n`;
298
+ if (Buffer.byteLength(body, "utf8") > MAX_APPROVALS_BYTES) return `the store would be larger than ${MAX_APPROVALS_BYTES / 1024} KiB`;
299
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
300
+ try {
301
+ fs.mkdirSync(path.dirname(file), { recursive: true });
302
+ fs.writeFileSync(tmp, body, { encoding: "utf8", flag: "wx", mode: 0o600 });
303
+ env.beforeRename?.(tmp);
304
+ fs.renameSync(tmp, file);
305
+ return undefined;
306
+ } catch (e) {
307
+ try {
308
+ fs.unlinkSync(tmp);
309
+ } catch {
310
+ // the tmp file may not exist
311
+ }
312
+ return `cannot write ${file}: ${errCode(e) ?? (e instanceof Error ? e.message : "error")}`;
313
+ }
314
+ }
315
+
316
+ function serialized<T>(file: string, fn: () => T): Promise<T> {
317
+ const key = pathKey(file);
318
+ const prev = queues.get(key) ?? Promise.resolve();
319
+ const run = prev.then(fn, fn);
320
+ const tail = run.then(() => undefined, () => undefined);
321
+ queues.set(key, tail);
322
+ void tail.then(() => {
323
+ if (queues.get(key) === tail) queues.delete(key);
324
+ });
325
+ return run;
326
+ }
327
+
328
+ function applyNow(op: ApprovalOp, env: ApprovalsEnv): ApplyOutcome {
329
+ const file = approvalsPath(env);
330
+ const now = clock(env);
331
+
332
+ if (op.kind === "touch") {
333
+ // In memory: the last known `lastUsedAt` of the path, so a touch within the hour needs no I/O at all.
334
+ const throttleKey = `${pathKey(file)}\u0000${op.path}`;
335
+ const last = lastTouched.get(throttleKey);
336
+ if (last !== undefined && now >= last && now - last < TOUCH_INTERVAL_MS) return { status: "unchanged", file, reason: "throttled" };
337
+ const current = readApprovals(env);
338
+ if (current.invalid !== undefined) return { status: "unchanged", file, reason: "absent" };
339
+ const entry = current.approvals.find((a) => a.path === op.path);
340
+ if (entry === undefined) return { status: "unchanged", file, reason: "absent" };
341
+ if (!sameRoots(entry.roots, op.roots)) return { status: "unchanged", file, reason: "mismatch" };
342
+ if (!isApprovalValid(entry, op.days, now)) return { status: "unchanged", file, reason: "expired" };
343
+ if (now - entry.lastUsedAt < TOUCH_INTERVAL_MS) {
344
+ if (now >= entry.lastUsedAt) lastTouched.set(throttleKey, entry.lastUsedAt);
345
+ return { status: "unchanged", file, reason: "throttled" };
346
+ }
347
+ const next: RepoApproval = Object.freeze({ ...entry, lastUsedAt: now });
348
+ const problem = writeStore(env, file, current.approvals.map((a) => (a === entry ? next : a)));
349
+ if (problem !== undefined) return { status: "refused", file, reason: "io", message: problem };
350
+ lastTouched.set(throttleKey, now);
351
+ return { status: "written", file, entry: next };
352
+ }
353
+
354
+ const current = readApprovals(env);
355
+ if (current.invalid !== undefined) {
356
+ return {
357
+ status: "refused",
358
+ file,
359
+ reason: "invalid-store",
360
+ message: `the approvals file ${file} is invalid (${current.invalid}); fix or remove it first`,
361
+ };
362
+ }
363
+
364
+ if (op.kind === "delete") {
365
+ const key = pathKey(op.path);
366
+ if (!current.approvals.some((a) => pathKey(a.path) === key)) return { status: "unchanged", file, reason: "absent" };
367
+ const problem = writeStore(env, file, current.approvals.filter((a) => pathKey(a.path) !== key));
368
+ if (problem !== undefined) return { status: "refused", file, reason: "io", message: problem };
369
+ const back = readApprovals(env);
370
+ if (back.invalid !== undefined || back.approvals.some((a) => pathKey(a.path) === key)) {
371
+ return { status: "refused", file, reason: "read-back", message: `the approval is still in ${file} after the write` };
372
+ }
373
+ return { status: "written", file };
374
+ }
375
+
376
+ const raw = {
377
+ path: op.approval.path,
378
+ commonDir: op.approval.commonDir,
379
+ roots: [...new Set(op.approval.roots)].sort(),
380
+ origin: sanitizeOrigin(op.approval.origin),
381
+ approvedAt: now,
382
+ lastUsedAt: now,
383
+ };
384
+ const problem = entryProblem(raw, now);
385
+ if (problem !== undefined) return { status: "refused", file, reason: "invalid-entry", message: `the approval ${problem}` };
386
+ const entry = toEntry(raw);
387
+ const key = pathKey(entry.path);
388
+ const kept = current.approvals.filter((a) => pathKey(a.path) !== key && isApprovalValid(a, op.days, now));
389
+ if (kept.length >= MAX_APPROVALS) {
390
+ return {
391
+ status: "refused",
392
+ file,
393
+ reason: "full",
394
+ message: `${file} already holds ${MAX_APPROVALS} approvals; revoke one first`,
395
+ };
396
+ }
397
+ const writeProblem = writeStore(env, file, [...kept, entry]);
398
+ if (writeProblem !== undefined) return { status: "refused", file, reason: "io", message: writeProblem };
399
+ const back = readApprovals(env);
400
+ const stored = back.approvals.find((a) => pathKey(a.path) === key);
401
+ if (back.invalid !== undefined || stored === undefined || !sameEntry(stored, entry)) {
402
+ return { status: "refused", file, reason: "read-back", message: `the approval is not in ${file} after the write` };
403
+ }
404
+ return { status: "written", file, entry: stored };
405
+ }
406
+
407
+ /**
408
+ * Applies one operation to the store, one at a time in the process. Each operation reads the file
409
+ * again first. `put` replaces the entry of the same path (resetting `approvedAt`), drops expired
410
+ * entries and refuses at {@link MAX_APPROVALS}; `delete` removes the entry of a path; both read the
411
+ * file back. `touch` moves `lastUsedAt` to now only when the entry still has the same path and roots
412
+ * and is still valid, at most once per {@link TOUCH_INTERVAL_MS} per path, so it never resurrects a
413
+ * revoked or expired entry. `put` and `delete` refuse on an invalid file; `touch` leaves it alone.
414
+ * Never throws.
415
+ */
416
+ export function applyApproval(op: ApprovalOp, env: ApprovalsEnv = {}): Promise<ApplyOutcome> {
417
+ const file = approvalsPath(env);
418
+ return serialized(file, () => {
419
+ try {
420
+ return applyNow(op, env);
421
+ } catch (e) {
422
+ const outcome: ApplyOutcome = {
423
+ status: "refused",
424
+ file,
425
+ reason: "io",
426
+ message: `cannot update ${file}: ${e instanceof Error ? e.message : String(e)}`,
427
+ };
428
+ return outcome;
429
+ }
430
+ });
431
+ }
432
+
433
+ // ---------------------------------------------------------------------------------------------
434
+ // Protected locations (SD-P4-8)
435
+
436
+ /** How a protected location relates to a candidate it refuses. */
437
+ export type ProtectedMode = "any" | "equal-or-ancestor";
438
+
439
+ export interface ProtectedLocation {
440
+ readonly label: string;
441
+ readonly dir: string;
442
+ /** `any`: equal, ancestor or inside is refused; `equal-or-ancestor`: inside is allowed. */
443
+ readonly mode: ProtectedMode;
444
+ }
445
+
446
+ /** An absolute directory from an environment variable, or undefined. */
447
+ function envDir(name: string): string | undefined {
448
+ const v = process.env[name];
449
+ return v !== undefined && v !== "" && path.isAbsolute(v) ? v : undefined;
450
+ }
451
+
452
+ /** `$XDG_<kind>_HOME/opencode` when set, and always `~/<fallback>/opencode` (opencode's xdg-basedir layout). */
453
+ function opencodeDirs(xdgVar: string, ...fallback: string[]): string[] {
454
+ const dirs = [path.join(os.homedir(), ...fallback, "opencode")];
455
+ const xdg = envDir(xdgVar);
456
+ if (xdg !== undefined) dirs.push(path.join(xdg, "opencode"));
457
+ return dirs;
458
+ }
459
+
460
+ /**
461
+ * The directory of the config file named by `OPENCODE_CONFIG` (resolved against the working directory,
462
+ * as opencode reads it), or undefined when the variable is unset or empty.
463
+ */
464
+ function opencodeConfigFileDir(): string | undefined {
465
+ const v = process.env.OPENCODE_CONFIG;
466
+ return v !== undefined && v.trim() !== "" ? path.dirname(path.resolve(v)) : undefined;
467
+ }
468
+
469
+ /**
470
+ * The protected locations: the opencode config dir (the router's `dirname(overridePath())`, plus
471
+ * `$XDG_CONFIG_HOME/opencode`), `OPENCODE_CONFIG_DIR`, the directory of the `OPENCODE_CONFIG` file and
472
+ * `~/.opencode`, the opencode data, state and cache dirs, this plugin's install dir
473
+ * (`dirname(configPath())`) and the store's dir (equal, ancestor or inside), and the user profile
474
+ * (equal or ancestor). Filesystem roots are checked separately by {@link protectedProblem}.
475
+ */
476
+ export function protectedLocations(env: ApprovalsEnv = {}): ProtectedLocation[] {
477
+ const out: ProtectedLocation[] = [];
478
+ const add = (label: string, dir: string, mode: ProtectedMode = "any"): void => {
479
+ if (!out.some((l) => l.label === label && cmpForm(l.dir) === cmpForm(dir))) out.push({ label, dir, mode });
480
+ };
481
+ add("the opencode config directory", path.dirname(overridePath()));
482
+ for (const d of opencodeDirs("XDG_CONFIG_HOME", ".config")) add("the opencode config directory", d);
483
+ const custom = envDir("OPENCODE_CONFIG_DIR");
484
+ if (custom !== undefined) add("OPENCODE_CONFIG_DIR", custom);
485
+ const configFileDir = opencodeConfigFileDir();
486
+ if (configFileDir !== undefined) add("the directory of OPENCODE_CONFIG", configFileDir);
487
+ add("the ~/.opencode directory", path.join(os.homedir(), ".opencode"));
488
+ for (const d of opencodeDirs("XDG_DATA_HOME", ".local", "share")) add("the opencode data directory", d);
489
+ for (const d of opencodeDirs("XDG_STATE_HOME", ".local", "state")) add("the opencode state directory", d);
490
+ for (const d of opencodeDirs("XDG_CACHE_HOME", ".cache")) add("the opencode cache directory", d);
491
+ add("the plugin install directory", path.dirname(configPath()));
492
+ add("the approvals store directory", path.dirname(approvalsPath(env)));
493
+ add("the user profile", os.homedir(), "equal-or-ancestor");
494
+ return out;
495
+ }
496
+
497
+ /** Normalized comparison form: resolved, no trailing separator except at a root, case-folded on Windows. */
498
+ function cmpForm(p: string): string {
499
+ let r = path.resolve(p);
500
+ const root = path.parse(r).root;
501
+ while (r.length > root.length && (r.endsWith(path.sep) || r.endsWith("/"))) r = r.slice(0, -1);
502
+ return pathKey(r);
503
+ }
504
+
505
+ function within(child: string, parent: string): boolean {
506
+ const prefix = parent.endsWith(path.sep) || parent.endsWith("/") ? parent : `${parent}${path.sep}`;
507
+ return child !== parent && child.startsWith(prefix);
508
+ }
509
+
510
+ function realOrSelf(p: string): string {
511
+ try {
512
+ return fs.realpathSync.native(p);
513
+ } catch {
514
+ return p;
515
+ }
516
+ }
517
+
518
+ /**
519
+ * Why a candidate may not be approved because of where it is, or undefined. `text` is what the human
520
+ * typed (absolute), `canonical` its realpath; both are checked against every protected location
521
+ * (literal and canonical forms) and against filesystem roots. No git.
522
+ */
523
+ export function protectedProblem(text: string, canonical: string, env: ApprovalsEnv = {}): string | undefined {
524
+ const candidates = [...new Set([text, canonical].filter((c) => c !== "" && path.isAbsolute(c)).map(cmpForm))];
525
+ if (candidates.length === 0) return "is not an absolute path";
526
+ for (const c of candidates) {
527
+ if (cmpForm(path.parse(c).root) === c) return "is a drive or filesystem root";
528
+ }
529
+ const locations = protectedLocations(env).map((loc) => ({
530
+ loc,
531
+ forms: [...new Set([cmpForm(loc.dir), cmpForm(realOrSelf(loc.dir))])],
532
+ }));
533
+ // Equality first, so the message names the location itself rather than one it contains.
534
+ for (const { loc, forms } of locations) {
535
+ if (candidates.some((c) => forms.includes(c))) return `is ${loc.label} (${loc.dir})`;
536
+ }
537
+ for (const { loc, forms } of locations) {
538
+ for (const c of candidates) {
539
+ for (const d of forms) {
540
+ if (within(d, c)) return `contains ${loc.label} (${loc.dir})`;
541
+ if (loc.mode === "any" && within(c, d)) return `is inside ${loc.label} (${loc.dir})`;
542
+ }
543
+ }
544
+ }
545
+ return undefined;
546
+ }
547
+
548
+ // ---------------------------------------------------------------------------------------------
549
+ // Origin shown to the human (SD-P4-9)
550
+
551
+ const URL_FORM = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)/;
552
+
553
+ /**
554
+ * The origin as shown to the human and stored. URL forms lose user-info, query and fragment; the scp
555
+ * form (`user@host:path`) and local paths are kept. Then `displaySafe`, capped at
556
+ * {@link MAX_ORIGIN_CHARS} characters; `none` when there is no origin.
557
+ */
558
+ export function sanitizeOrigin(raw: string | undefined): string {
559
+ if (raw === undefined) return NO_ORIGIN;
560
+ let text = raw.trim();
561
+ if (text === "") return NO_ORIGIN;
562
+ const m = URL_FORM.exec(text);
563
+ if (m !== null) {
564
+ const authority = m[2] ?? "";
565
+ const at = authority.lastIndexOf("@");
566
+ const host = at === -1 ? authority : authority.slice(at + 1);
567
+ text = `${m[1]}://${host}${m[3] ?? ""}`;
568
+ }
569
+ let shown = displaySafe(text);
570
+ if (shown.trim() === "") return NO_ORIGIN;
571
+ if (shown.length > MAX_ORIGIN_CHARS) shown = `${shown.slice(0, MAX_ORIGIN_CHARS - 1)}…`;
572
+ return shown;
573
+ }
574
+
575
+ // ---------------------------------------------------------------------------------------------
576
+ // Candidate inspection and identity check (SD-P4-4, -6, -8)
577
+
578
+ /** {@link inspectCandidate} results are cached this long per path (SD-P4-8). */
579
+ export const INSPECT_CACHE_MS = 5_000;
580
+
581
+ /** What git says about a candidate main worktree (SD-P4-4, -8, -9). */
582
+ export interface CandidateIdentity {
583
+ /** Canonical path of the main worktree. */
584
+ readonly path: string;
585
+ /** Canonical git common dir (`<path>\.git`). */
586
+ readonly commonDir: string;
587
+ /** Sorted root commits (`git rev-list --max-parents=0 HEAD`). */
588
+ readonly roots: readonly string[];
589
+ /** Sanitized origin ({@link sanitizeOrigin}); `none` when absent. */
590
+ readonly origin: string;
591
+ /** Current branch, display-safe; `(detached)` when `HEAD` is detached. */
592
+ readonly branch: string;
593
+ /** HEAD commit, display-safe. */
594
+ readonly head: string;
595
+ }
596
+
597
+ /** The parts of `fs.Stats` that {@link inspectCandidate} and {@link verifyIdentity} use. */
598
+ export interface EntryStat {
599
+ isDirectory(): boolean;
600
+ isSymbolicLink(): boolean;
601
+ }
602
+
603
+ /** Injectable I/O of {@link verifyIdentity} (and {@link inspectCandidate}); every member defaults to the real one. */
604
+ export interface IdentityDeps {
605
+ /** `realpathSync.native`; throws when the path does not resolve. */
606
+ readonly realpath?: (p: string) => string;
607
+ /** `lstatSync` (links are not followed); throws when the entry is absent. */
608
+ readonly lstat?: (p: string) => EntryStat;
609
+ /** Hardened `git rev-parse --show-toplevel` in `cwd`; undefined on failure. */
610
+ readonly showToplevel?: (cwd: string) => Promise<string | undefined>;
611
+ /** Hardened `git rev-parse --git-common-dir` in `cwd`, absolute; undefined on failure. */
612
+ readonly commonDir?: (cwd: string) => Promise<string | undefined>;
613
+ /** Hardened sorted root commits of `HEAD`; undefined on failure and without commits. */
614
+ readonly rootCommits?: (cwd: string) => Promise<string[] | undefined>;
615
+ /** Hardened raw `remote.origin.url`; undefined when unset and on failure. */
616
+ readonly origin?: (cwd: string) => Promise<string | undefined>;
617
+ /** Hardened `HEAD` commit and branch; undefined on failure and without commits. */
618
+ readonly headInfo?: (cwd: string) => Promise<import("./admission").GitHeadInfo | undefined>;
619
+ /** Options of the default git helpers (tests: an injected spawn or a shorter bound). */
620
+ readonly git?: import("./admission").GitBoundedOptions;
621
+ /** Clock of the caches; default `Date.now`. */
622
+ readonly now?: () => number;
623
+ /** Default `process.platform`. */
624
+ readonly platform?: NodeJS.Platform;
625
+ }
626
+
627
+ /** Injectable I/O and configuration of {@link inspectCandidate}. */
628
+ export interface InspectDeps extends IdentityDeps {
629
+ /** `routing.repoExclude`: absolute globs matched against the text and the canonical form of the candidate. */
630
+ readonly exclude?: readonly string[];
631
+ /** Store environment: the store's directory is a protected location. */
632
+ readonly env?: ApprovalsEnv;
633
+ /**
634
+ * Ask git now, never a cached result (`/router approve`, S2: what is stored comes from git at approve time). The fresh
635
+ * result still replaces the cached one.
636
+ */
637
+ readonly fresh?: boolean;
638
+ }
639
+
640
+ /** The end of every refusal of a candidate that is not a main worktree (SD-P4-4). */
641
+ export const APPROVE_MAIN_WORKTREE = "approve the main worktree";
642
+
643
+ type AdmissionModule = typeof admission;
644
+
645
+ interface TimedResult<T> { readonly at: number; readonly value: Promise<T> }
646
+ const IDENTITY_CACHE_MAX = 64;
647
+ const inspected = new Map<string, TimedResult<string | CandidateIdentity>>();
648
+ const rootsByHead = new Map<string, Promise<string[] | undefined>>();
649
+
650
+ /** Test only: forget the {@link inspectCandidate} results and the root commits cached per (common dir, HEAD). */
651
+ export function resetIdentityCaches(): void {
652
+ inspected.clear();
653
+ rootsByHead.clear();
654
+ }
655
+
656
+ function remember<V>(cache: Map<string, V>, key: string, value: V): void {
657
+ cache.delete(key);
658
+ cache.set(key, value);
659
+ while (cache.size > IDENTITY_CACHE_MAX) {
660
+ const oldest = cache.keys().next().value;
661
+ if (oldest === undefined) break;
662
+ cache.delete(oldest);
663
+ }
664
+ }
665
+
666
+ async function settle<T>(run: () => Promise<T | undefined>): Promise<T | undefined> {
667
+ try {
668
+ return await run();
669
+ } catch {
670
+ return undefined;
671
+ }
672
+ }
673
+
674
+ function realpathOf(deps: IdentityDeps): (p: string) => string {
675
+ return deps.realpath ?? ((p: string) => fs.realpathSync.native(p));
676
+ }
677
+
678
+ /** The git helpers: the injected ones, else the hardened ones of `admission.ts` (bounded, `deps.git` options). */
679
+ function gitIo(deps: IdentityDeps, adm: AdmissionModule): Required<Pick<IdentityDeps, "showToplevel" | "commonDir" | "rootCommits" | "origin" | "headInfo">> {
680
+ const git = deps.git;
681
+ return {
682
+ showToplevel: deps.showToplevel ?? ((cwd: string) => adm.gitShowToplevel(cwd, git)),
683
+ commonDir: deps.commonDir ?? ((cwd: string) => adm.gitCommonDir(cwd, git)),
684
+ rootCommits: deps.rootCommits ?? ((cwd: string) => adm.gitRootCommits(cwd, git)),
685
+ origin: deps.origin ?? ((cwd: string) => adm.gitOrigin(cwd, git)),
686
+ headInfo: deps.headInfo ?? ((cwd: string) => adm.gitHeadInfo(cwd, git)),
687
+ };
688
+ }
689
+
690
+ /** Whether git's absolute `listed` path names `real` (canonical): text first, `realpath` only when the text differs. */
691
+ function samePlace(listed: string, real: string, realpath: (p: string) => string): boolean {
692
+ if (!path.isAbsolute(listed)) return false;
693
+ if (cmpForm(listed) === cmpForm(real)) return true;
694
+ try {
695
+ return cmpForm(realpath(listed)) === cmpForm(real);
696
+ } catch {
697
+ return false;
698
+ }
699
+ }
700
+
701
+ /** SD-P4-4: `<real>\.git` must be a local directory (`lstat`: not a link, not a gitfile). No git. */
702
+ function gitDirectoryProblem(real: string, deps: IdentityDeps): string | undefined {
703
+ const lstat = deps.lstat ?? ((p: string) => fs.lstatSync(p));
704
+ let stat: EntryStat;
705
+ try {
706
+ stat = lstat(path.join(real, ".git"));
707
+ } catch {
708
+ return `has no .git directory (it is not the main worktree of a git repository); ${APPROVE_MAIN_WORKTREE}`;
709
+ }
710
+ if (stat.isSymbolicLink()) return `has a .git link instead of a .git directory; ${APPROVE_MAIN_WORKTREE}`;
711
+ if (!stat.isDirectory()) {
712
+ return `has a .git file (a linked worktree, a submodule or a separate git dir) instead of a .git directory; ${APPROVE_MAIN_WORKTREE}`;
713
+ }
714
+ return undefined;
715
+ }
716
+
717
+ /** `routing.repoExclude` pattern matching `p` (as given and, on win32, with native separators), or undefined. */
718
+ function excludedBy(p: string, exclude: readonly string[], win: boolean, matches: (input: string, pattern: string) => boolean): string | undefined {
719
+ const forms = win && p.includes("/") ? [p, p.replace(/\//g, "\\")] : [p];
720
+ for (const form of forms) {
721
+ const input = win ? form.toLowerCase() : form;
722
+ const hit = exclude.find((pattern) => pattern.trim() !== "" && matches(input, win ? pattern.toLowerCase() : pattern));
723
+ if (hit !== undefined) return hit;
724
+ }
725
+ return undefined;
726
+ }
727
+
728
+ /** The git part of {@link inspectCandidate}, in the canonical main worktree `real` whose `.git` directory was checked. */
729
+ async function inspectGit(real: string, deps: IdentityDeps, adm: AdmissionModule): Promise<string | CandidateIdentity> {
730
+ const realpath = realpathOf(deps);
731
+ const io = gitIo(deps, adm);
732
+ // All five are hardened and bounded; run together, the whole inspection stays within one bound.
733
+ const [top, common, roots, origin, head] = await Promise.all([
734
+ settle(() => io.showToplevel(real)),
735
+ settle(() => io.commonDir(real)),
736
+ settle(() => io.rootCommits(real)),
737
+ settle(() => io.origin(real)),
738
+ settle(() => io.headInfo(real)),
739
+ ]);
740
+ if (top === undefined) return "is not a repository git can read (git rev-parse --show-toplevel failed or timed out)";
741
+ if (!samePlace(top, real, realpath)) return `is not the top level of its git repository (git names ${displaySafe(top)}); ${APPROVE_MAIN_WORKTREE}`;
742
+ if (common === undefined) return "is not a repository git can read (git rev-parse --git-common-dir failed or timed out)";
743
+ let commonReal: string;
744
+ try {
745
+ commonReal = realpath(common);
746
+ } catch {
747
+ return `has a git common dir that does not resolve (${displaySafe(common)}); ${APPROVE_MAIN_WORKTREE}`;
748
+ }
749
+ if (cmpForm(commonReal) !== cmpForm(path.join(real, ".git"))) {
750
+ return `uses the git directory ${displaySafe(commonReal)}, not its own .git directory; ${APPROVE_MAIN_WORKTREE}`;
751
+ }
752
+ if (roots === undefined || roots.length === 0) return "has no commits yet, or git rev-list --max-parents=0 HEAD failed or timed out";
753
+ if (head === undefined) return "has no HEAD commit git can report (git rev-parse HEAD failed or timed out)";
754
+ return Object.freeze({
755
+ path: real,
756
+ commonDir: commonReal,
757
+ roots: Object.freeze([...new Set(roots)].sort()),
758
+ origin: sanitizeOrigin(origin),
759
+ branch: head.branch === undefined ? "(detached)" : displaySafe(head.branch),
760
+ head: displaySafe(head.head),
761
+ });
762
+ }
763
+
764
+ /**
765
+ * What git says about the candidate `text` (SD-P4-4, -8, -9): a problem phrase (to follow the path, as in "D:\x <problem>"), or
766
+ * the identity of its canonical main worktree. Before any git call: {@link rootTextProblem} (admission.ts) on the text and on
767
+ * the canonical form, `routing.repoExclude` on both, {@link protectedProblem}, and `<canonical>\.git` must be a local directory
768
+ * (`lstat`: not a link, not a gitfile). Then hardened, bounded git: the canonical form must be the top level, its canonical common
769
+ * dir must be `<canonical>\.git`, and it must have at least one commit. The git part is cached {@link INSPECT_CACHE_MS} per
770
+ * canonical path (`deps.fresh` skips the cached result); the checks before it run every time. Never throws.
771
+ */
772
+ export async function inspectCandidate(text: string, deps: InspectDeps = {}): Promise<string | CandidateIdentity> {
773
+ try {
774
+ const adm: AdmissionModule = admission;
775
+ const platform = deps.platform ?? process.platform;
776
+ const win = platform === "win32";
777
+ const exclude = deps.exclude ?? [];
778
+ const shown = text.trim();
779
+ const textProblem = adm.rootTextProblem(shown, platform);
780
+ if (textProblem !== undefined) return textProblem;
781
+ const byText = excludedBy(shown, exclude, win, permissionMatches);
782
+ if (byText !== undefined) return `is excluded by routing.repoExclude (${byText})`;
783
+ let real: string;
784
+ try {
785
+ real = realpathOf(deps)(shown);
786
+ } catch {
787
+ return "does not resolve to an existing directory";
788
+ }
789
+ if (typeof real !== "string" || real === "") return "does not resolve to an existing directory";
790
+ const realProblem = adm.rootTextProblem(real, platform);
791
+ if (realProblem !== undefined) return `resolves to ${displaySafe(real)}, which ${realProblem}`;
792
+ const byReal = excludedBy(real, exclude, win, permissionMatches);
793
+ if (byReal !== undefined) return `resolves to ${displaySafe(real)}, which is excluded by routing.repoExclude (${byReal})`;
794
+ const placed = protectedProblem(shown, real, deps.env);
795
+ if (placed !== undefined) return placed;
796
+ const gitDir = gitDirectoryProblem(real, deps);
797
+ if (gitDir !== undefined) return gitDir;
798
+
799
+ const now = (deps.now ?? Date.now)();
800
+ const key = cmpForm(real);
801
+ const hit = deps.fresh === true ? undefined : inspected.get(key);
802
+ if (hit !== undefined && now >= hit.at && now - hit.at < INSPECT_CACHE_MS) return await hit.value;
803
+ const value = inspectGit(real, deps, adm);
804
+ remember(inspected, key, { at: now, value });
805
+ return await value;
806
+ } catch (e) {
807
+ return `could not be inspected (${e instanceof Error ? e.message : String(e)})`;
808
+ }
809
+ }
810
+
811
+ /**
812
+ * SD-P4-6: why `entry` no longer names the approved repository, as a phrase (to follow "the approved repository <path>"), or
813
+ * undefined when it still does: `realpath(path)` is `path` (comparison form), `<path>\.git` is a local directory, git names
814
+ * `path` as the top level, the canonical common dir is the stored one and the sorted root commits of `HEAD` are the stored ones.
815
+ * The root commits are cached per (common dir, HEAD commit); pass cached `showToplevel` / `commonDir` for the 5 s caches. Never
816
+ * throws.
817
+ */
818
+ export async function verifyIdentity(entry: Pick<RepoApproval, "path" | "commonDir" | "roots">, deps: IdentityDeps = {}): Promise<string | undefined> {
819
+ try {
820
+ const adm: AdmissionModule = admission;
821
+ const platform = deps.platform ?? process.platform;
822
+ const textProblem = adm.rootTextProblem(entry.path, platform);
823
+ if (textProblem !== undefined) return `has a path that ${textProblem}`;
824
+ const realpath = realpathOf(deps);
825
+ let real: string;
826
+ try {
827
+ real = realpath(entry.path);
828
+ } catch {
829
+ return "no longer resolves";
830
+ }
831
+ if (typeof real !== "string" || cmpForm(real) !== cmpForm(entry.path)) return `now resolves to ${displaySafe(String(real))}`;
832
+ const gitDir = gitDirectoryProblem(entry.path, deps);
833
+ if (gitDir !== undefined) return gitDir;
834
+ const io = gitIo(deps, adm);
835
+ const [top, common, head] = await Promise.all([
836
+ settle(() => io.showToplevel(entry.path)),
837
+ settle(() => io.commonDir(entry.path)),
838
+ settle(() => io.headInfo(entry.path)),
839
+ ]);
840
+ if (top === undefined || !samePlace(top, entry.path, realpath)) return "is no longer the top level of a git repository (or git failed)";
841
+ if (common === undefined) return "has no git common dir git can report (git failed or timed out)";
842
+ let commonReal: string;
843
+ try {
844
+ commonReal = realpath(common);
845
+ } catch {
846
+ return "has a git common dir that does not resolve";
847
+ }
848
+ if (cmpForm(commonReal) !== cmpForm(entry.commonDir)) return `now uses the git directory ${displaySafe(commonReal)}, not ${entry.commonDir}`;
849
+ if (head === undefined) return "has no HEAD commit git can report (git failed or timed out)";
850
+ const key = `${cmpForm(commonReal)}\u0000${head.head}`;
851
+ let roots = rootsByHead.get(key);
852
+ if (roots === undefined) {
853
+ const loaded = settle(() => io.rootCommits(entry.path));
854
+ roots = loaded;
855
+ remember(rootsByHead, key, loaded);
856
+ // A failure is not reused.
857
+ void loaded.then((value) => {
858
+ if (value === undefined && rootsByHead.get(key) === loaded) rootsByHead.delete(key);
859
+ });
860
+ }
861
+ const current = await roots;
862
+ if (current === undefined) return "has root commits git cannot list (git rev-list --max-parents=0 HEAD failed or timed out)";
863
+ if (!sameRoots(current, entry.roots)) {
864
+ return "has other root commits than when it was approved (another repository at the same path, an orphan branch, a deepened clone or rewritten history)";
865
+ }
866
+ return undefined;
867
+ } catch (e) {
868
+ return `could not be verified (${e instanceof Error ? e.message : String(e)})`;
869
+ }
870
+ }
871
+
872
+ /** The approvals that apply now (no git): a valid store's entries with `now < expiresAt(entry, days)`. */
873
+ export function validApprovals(days: number, env: ApprovalsEnv = {}): readonly RepoApproval[] {
874
+ const now = clock(env);
875
+ return readApprovals(env).approvals.filter((entry) => isApprovalValid(entry, days, now));
876
+ }