opencode-model-router 2.9.1 → 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.
Files changed (59) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/README.md +4 -2
  3. package/package.json +12 -5
  4. package/src/compat/background.ts +56 -19
  5. package/src/compat/child-history.ts +134 -0
  6. package/src/compat/child-report.ts +185 -0
  7. package/src/compat/child-session.ts +10 -0
  8. package/src/compat/session-lookup.ts +21 -0
  9. package/src/compat/v2-client.ts +124 -6
  10. package/src/compat/v2-hooks.ts +525 -203
  11. package/src/compat/v2-observations.ts +1 -0
  12. package/src/compat/v2-vocabulary.ts +14 -0
  13. package/src/executor/create.ts +47 -28
  14. package/src/executor/git.ts +226 -30
  15. package/src/executor/integrate/checks.ts +29 -11
  16. package/src/executor/integrate/land.ts +32 -2
  17. package/src/executor/integrate/queue.ts +95 -13
  18. package/src/executor/ledger.ts +16 -12
  19. package/src/executor/lfs-restore.ts +492 -0
  20. package/src/executor/paths.ts +7 -2
  21. package/src/executor/recovery.ts +2 -1
  22. package/src/executor/runtime.ts +1062 -243
  23. package/src/executor/slots/pool.ts +120 -19
  24. package/src/executor/slots/provision.ts +111 -23
  25. package/src/executor/slots/root.ts +81 -0
  26. package/src/executor/types.ts +28 -2
  27. package/src/executor/unattended.ts +6 -1
  28. package/src/executor/verify-trees.ts +507 -0
  29. package/src/guard/enforce.ts +2 -1
  30. package/src/guard/fingerprint.ts +9 -0
  31. package/src/guard/guards.ts +7 -1
  32. package/src/index.ts +191 -31
  33. package/src/router/answer-dedup.ts +198 -0
  34. package/src/router/common-dir.ts +241 -0
  35. package/src/router/config.ts +228 -40
  36. package/src/router/diff-handles.ts +322 -0
  37. package/src/router/diff-summary.ts +318 -0
  38. package/src/router/git-metadata-guard.ts +317 -0
  39. package/src/router/git-tools.ts +1136 -49
  40. package/src/router/read-only.ts +37 -13
  41. package/src/router/role-agents.ts +100 -36
  42. package/src/router/run-summary.ts +253 -0
  43. package/src/router/run-tools.ts +177 -25
  44. package/src/router/sessions.ts +23 -1
  45. package/src/router/tool-paths.ts +62 -4
  46. package/src/routing/classify/rules.ts +93 -14
  47. package/src/routing/roles/read-set.ts +10 -1
  48. package/src/routing/roles/work-root.ts +20 -3
  49. package/src/routing/wire/hint.ts +9 -2
  50. package/src/v2.ts +3 -1
  51. package/src/verify/exec.ts +454 -2
  52. package/src/verify/head.ts +6 -1
  53. package/src/verify/pending.ts +14 -1
  54. package/src/verify/plan-task.ts +86 -26
  55. package/src/verify/reference.ts +60 -7
  56. package/src/verify/runner.ts +14 -6
  57. package/src/verify/tree.ts +34 -10
  58. package/src/verify/types.ts +44 -0
  59. package/src/verify/wiring.ts +134 -22
@@ -50,6 +50,7 @@
50
50
  * - launch-step-end {taskId,attempt,result}; orchestrator {event}
51
51
  * - runtime-attach, activation, activation-end, promote, schedule, abort, dispose,
52
52
  * detach, lease-released-notification: detail=null.
53
+ * - close-wait-slow {waitedMs,pending:[label]}: a plan close still waits for its cut attachment's work.
53
54
  * Other raw states: capacity-init {maxParallel,providers:[{provider,limit,holdUntilMs,
54
55
  * lastSignalAtMs,pausedUntilMs}]}; provider {provider,change,from,to,until};
55
56
  * lease-acquire {taskRef,ok}; lease-release {taskRef}.
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The router's own v1 tool vocabulary, translated at the OpenCode v2 boundary (`Task(` -> `subagent(`, `subagent_type` ->
3
+ * `agent`, `task_id` -> `sessionID`). Pure and dependency-free: the v2 adapter (src/compat/v2-hooks.ts, which re-exports it)
4
+ * and the plugin's v2-only finish API (src/index.ts, the held verdict text, #191) apply the same translation.
5
+ */
6
+ export function v2Instructions(text: string): string {
7
+ return text
8
+ .replace(/\bTask(?=\s*\()/g, "subagent")
9
+ .replace(/\bTask (calls?|tool)\b/g, "subagent $1")
10
+ .replace(/\btask tool\b/g, "subagent tool")
11
+ .replace(/`task`/g, "`subagent`")
12
+ .replace(/\bsubagent_type\b/g, "agent")
13
+ .replace(/\btask_id\b/g, "sessionID");
14
+ }
@@ -15,7 +15,7 @@ import { runArgv } from "../verify/exec";
15
15
  import { hardeningArgs, spawnBounded, workRootGuards } from "../router/git-tools";
16
16
  import { createCapacityController } from "./capacity";
17
17
  import { createPlanCompiler, type CompilerDeps } from "./compile";
18
- import { createGitOps, createGitRunner } from "./git";
18
+ import { createGitOps, createGitRunner, readCommitIdentity, withRepositoryDrivers } from "./git";
19
19
  import { BackgroundRuns, createIntegrateGit, createIntegrationChecks, createWriteGuard } from "./integrate/checks";
20
20
  import { createLander } from "./integrate/land";
21
21
  import { createPhaseSuiteRunner } from "./integrate/phase-suite";
@@ -31,6 +31,7 @@ import type { V2Observations } from "../compat/v2-observations";
31
31
  import { createScheduler } from "./schedule";
32
32
  import { countPlanMarkers, createSlotPool, defaultSlotsDir, type SlotPoolOpenOptions } from "./slots/pool";
33
33
  import { createProvisioner } from "./slots/provision";
34
+ import { createVerifyTrees } from "./verify-trees";
34
35
  import { ExecutorError, type ExecutorRuntime, type LedgerStore, type LedgerV1, type PlanId, type SlotPool, type Spawner } from "./types";
35
36
 
36
37
  /** Process adapter over the router's bounded, no-shell runner. */
@@ -143,6 +144,11 @@ export class PlanSlotPools {
143
144
  return view;
144
145
  }
145
146
 
147
+ /** A newly created plan may reuse an id; old views retain their own closed entry and stay fenced. */
148
+ forget(planId: PlanId): void {
149
+ if (this.entries.get(planId)?.closed === true) this.entries.delete(planId);
150
+ }
151
+
146
152
  async gc(finished: Parameters<SlotPool["gc"]>[0], opts?: Parameters<SlotPool["gc"]>[1]): ReturnType<SlotPool["gc"]> {
147
153
  const removed: string[] = [], reported: string[] = [];
148
154
  for (const plan of await this.deps.store.list()) {
@@ -234,27 +240,31 @@ async function checkBase(git: RuntimeDeps["git"], repo: LedgerV1["repo"]): Promi
234
240
  }
235
241
  }
236
242
 
237
- const processClaimKey = Symbol.for("omr.executor.claim.v1");
243
+ const processClaimKey = Symbol.for("omr.executor.claim.v2");
238
244
  /**
239
245
  * QA-5.1-20: the retry callbacks of copies refused by the claim (a hot reload starts the new copy before the old one has
240
- * disposed). Kept beside the claim on the same global record, under its own key, so the claim's shape stays what every
241
- * loaded copy reads; a release calls each waiter once, and the waiters race for the claim through the same token check.
246
+ * disposed). Both maps are process-wide across module copies, keyed by the canonical executor home shared by linked
247
+ * worktrees. A release calls only that home's waiters; they race for its claim through the same token check.
248
+ * v2 keys keep older loaded copies from misreading the new map shapes.
242
249
  */
243
- const processClaimWaitersKey = Symbol.for("omr.executor.claim.waiters.v1");
250
+ const processClaimWaitersKey = Symbol.for("omr.executor.claim.waiters.v2");
244
251
  const processClaims = globalThis as typeof globalThis & {
245
- [processClaimKey]?: { token: symbol; toplevel: string };
246
- [processClaimWaitersKey]?: Set<() => void>;
252
+ [processClaimKey]?: Map<string, { token: symbol; toplevel: string }>;
253
+ [processClaimWaitersKey]?: Map<string, Set<() => void>>;
247
254
  };
248
255
 
249
- function claimWaiters(): Set<() => void> {
250
- return processClaims[processClaimWaitersKey] ??= new Set();
256
+ function claimWaiters(home: string): Set<() => void> {
257
+ const waiters = processClaims[processClaimWaitersKey] ??= new Map();
258
+ let own = waiters.get(home);
259
+ if (own === undefined) { own = new Set(); waiters.set(home, own); }
260
+ return own;
251
261
  }
252
262
 
253
- /** Frees the claim `token` holds (no-op for another holder's), then tells every refused copy that it may retry. */
254
- function releaseClaim(token: symbol): void {
255
- if (processClaims[processClaimKey]?.token !== token) return;
256
- delete processClaims[processClaimKey];
257
- for (const retry of [...claimWaiters()]) {
263
+ /** Frees the home's claim `token` holds (no-op for another holder's), then tells its refused copies they may retry. */
264
+ function releaseClaim(home: string, token: symbol): void {
265
+ if (processClaims[processClaimKey]?.get(home)?.token !== token) return;
266
+ processClaims[processClaimKey]?.delete(home);
267
+ for (const retry of [...(processClaims[processClaimWaitersKey]?.get(home) ?? [])]) {
258
268
  try { retry(); } catch { /* A waiter's failure is its own (it logs and clears its access). */ }
259
269
  }
260
270
  }
@@ -299,26 +309,27 @@ export function createExecutor(
299
309
 
300
310
  /**
301
311
  * QA-5.1-20: a copy refused only by the process claim keeps its inputs and retries the assembly once the claim is free: at
302
- * the release (the holder's dispose calls every waiter) or, failing that, the first time its `lateRuntime` is used. The
303
- * waiters race for the claim through the same token check, so one wins; the others stay waiters.
312
+ * the release (the holder's dispose calls that home's waiters) or, failing that, the first time its `lateRuntime` is used.
313
+ * The waiters race for the home's claim through the same token check, so one wins; the others stay waiters.
304
314
  * QA-5.1-26: the winner is handed to its adapter (`host.onExecutor`), which adopts it through the same path as an executor
305
315
  * built at start: it registers the executor's providers and hooks, starts it once (its recovery runs once) and disposes it in
306
316
  * the W7 order. A winner its adapter does not adopt (the adapter is already disposing) gets the safety dispose here.
307
317
  */
308
- function waitForClaim(context: { directory: string }, options: CreateExecutorOptions): void {
318
+ function waitForClaim(home: string, context: { directory: string }, options: CreateExecutorOptions): void {
309
319
  const { access, host } = options;
310
320
  const lifetime = host.lifetime;
311
321
  if (access.deferRetry === undefined || lifetime.aborted) return;
312
- const waiters = claimWaiters();
322
+ const waiters = claimWaiters(home);
313
323
  let spent = false;
314
324
  // A copy that ends while it waits stops waiting: no executor is ever assembled for a disposed copy.
315
325
  function forget(): void {
316
326
  spent = true;
317
327
  waiters.delete(retry);
328
+ if (waiters.size === 0) processClaims[processClaimWaitersKey]?.delete(home);
318
329
  access.deferRetry?.(null);
319
330
  }
320
331
  function retry(): void {
321
- if (spent || lifetime.aborted || processClaims[processClaimKey] !== undefined) return;
332
+ if (spent || lifetime.aborted || processClaims[processClaimKey]?.has(home)) return;
322
333
  lifetime.removeEventListener("abort", forget);
323
334
  forget();
324
335
  const built = assembleExecutor(context, options);
@@ -362,14 +373,15 @@ function assembleExecutor(context: { directory: string }, options: CreateExecuto
362
373
  if (!prepared.ok) return absent(prepared.reason);
363
374
  if (host.leases === null) return absent("the lease registry is not available");
364
375
  if (host.runner === null) return absent("the child runner is not available");
365
- if (processClaims[processClaimKey] !== undefined) {
376
+ const { toplevel, home } = prepared;
377
+ const claims = processClaims[processClaimKey] ??= new Map();
378
+ if (claims.has(home)) {
366
379
  // QA-5.1-20: refused only by the claim (a hot reload's new copy, while the old one disposes): wait for its release.
367
- waitForClaim(context, options);
368
- return absent("another plan executor already owns this process");
380
+ waitForClaim(home, context, options);
381
+ return absent("another plan executor already owns this repository in this process");
369
382
  }
370
383
  const claim = Symbol("plan executor");
371
- const { toplevel, home } = prepared;
372
- processClaims[processClaimKey] = { token: claim, toplevel };
384
+ claims.set(home, { token: claim, toplevel });
373
385
  const clock = createNodeClock();
374
386
  const fs = createNodeFileSystem();
375
387
  const spawner = nodeSpawner();
@@ -382,7 +394,10 @@ function assembleExecutor(context: { directory: string }, options: CreateExecuto
382
394
  let launcher: ReturnType<typeof createTaskLauncher> | null = null;
383
395
  try {
384
396
  const rawGit = createGitRunner({ mode: "hardened", toplevel });
385
- const git: RuntimeDeps["git"] = { run: (args, opts) => rawGit.run([...hardeningArgs(), ...args], opts) };
397
+ // Every executor git call (GitOps, the runtime's commits/WIP/reset/clean, igit, the lander's probes, the compiler): the
398
+ // hardening, then the repository-only driver blanking read afresh for that call (required=true: git refuses rather than
399
+ // writing unfiltered content).
400
+ const git: RuntimeDeps["git"] = withRepositoryDrivers({ run: (args, opts) => rawGit.run([...hardeningArgs(), ...args], opts) }, toplevel);
386
401
  const userGit = createGitRunner({ mode: "user", toplevel });
387
402
  const store = createLedgerStore({ home, observations: options.observations });
388
403
  const opsOf = (planId: PlanId) => createGitOps({ git, userGit, fs, planId, toplevel, executorHome: home });
@@ -527,9 +542,13 @@ function assembleExecutor(context: { directory: string }, options: CreateExecuto
527
542
  };
528
543
  const self = processIdentity();
529
544
  runtime = createExecutorRuntime({ store, compiler, self, executorHome: home,
545
+ // #189 R2-pre-2: plan-task verifications journal their process trees; activation ends what a dead server left.
546
+ verifyTrees: createVerifyTrees({ home, self, isAlive: spawner.isAlive, log }),
530
547
  observations: options.observations,
531
548
  slots: planPools.facade, slotsFor: (id) => planPools.of(id), purgeSlots: (id, finished) => planPools.purge(id, finished),
532
- scheduler: createScheduler(), launcher: taskLauncher, routes, verifier: host.verifier, git, hosts: host.hosts, bindings: host.bindings, clock,
549
+ forgetSlots: (id) => planPools.forget(id),
550
+ scheduler: createScheduler(), launcher: taskLauncher, routes, verifier: host.verifier, git,
551
+ commitIdentity: () => readCommitIdentity(userGit, toplevel), hosts: host.hosts, bindings: host.bindings, clock,
533
552
  leaseRegistry: { acquireWrite: (owner, writes) => {
534
553
  const result = leases.registry.acquireWrite(owner, writes);
535
554
  if (result.ok) return { ok: true };
@@ -571,7 +590,7 @@ function assembleExecutor(context: { directory: string }, options: CreateExecuto
571
590
  try { await innerRuntime.dispose(); }
572
591
  finally {
573
592
  try { await planPools.closeAll(); }
574
- finally { for (const timer of timers) clock.clearTimer(timer); timers.clear(); releaseClaim(claim); }
593
+ finally { for (const timer of timers) clock.clearTimer(timer); timers.clear(); releaseClaim(home, claim); }
575
594
  }
576
595
  })();
577
596
  return disposal;
@@ -583,7 +602,7 @@ function assembleExecutor(context: { directory: string }, options: CreateExecuto
583
602
  void pools?.closeAll();
584
603
  for (const timer of timers) clock.clearTimer(timer);
585
604
  const failed = absent(`assembly failed: ${error instanceof Error ? error.message : String(error)}`);
586
- releaseClaim(claim);
605
+ releaseClaim(home, claim);
587
606
  return failed;
588
607
  }
589
608
  }
@@ -1,14 +1,15 @@
1
1
  // src/executor/git.ts
2
2
  // Phase 2.4.2: hardened git operations for the executor (design memo 2.4.1 §2 in
3
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
4
+ // spawns a shell; hooks never run (`core.hooksPath` is an empty regular file), signing and editors are off, and an in-slot call
5
5
  // never trusts the slot's own `.git` (explicit `--git-dir`/`--work-tree` after `verifySlotPointers`).
6
6
 
7
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
8
  import {
9
- gitEnvironment, gitExecutable, gitPointers, hardeningArgs, isNetworkOrDevicePath, spawnBounded, stripUrlUserinfo,
10
- workRootGuards,
9
+ gitEnvironment, gitExecutable, gitPointers, hardeningArgs, isNetworkOrDevicePath, repositoryDriverArgs,
10
+ spawnBounded, stripUrlUserinfo, workRootGuards,
11
11
  } from "../router/git-tools";
12
+ import { lfsRestoreTarget, restoreLocalLfsObjects, type LfsRestoreGit, type LfsRestoreTarget } from "./lfs-restore";
12
13
  import {
13
14
  ExecutorError, GIT_ID_PATTERN, PLAN_ID_PATTERN, WIP_TRAILER,
14
15
  type FileSystem, type GitRunner, type JsonValue, type PhaseId, type PlanId, type ProcessResult, type ProcOpts,
@@ -107,8 +108,11 @@ export function createGitRunner(o: { mode: "hardened" | "user"; toplevel: string
107
108
  }
108
109
 
109
110
  export interface GitContext {
110
- /** `<home>\git\no-hooks`: an empty real directory created by the executor. */
111
- hooksDir: string;
111
+ /**
112
+ * `<home>\git\hooks-off`: an empty regular file created by the executor. Git looks for `<file>/<hook>` and finds none, and
113
+ * Git LFS, which installs its hooks into `core.hooksPath` whenever it runs a filter, cannot create them under a file (#215).
114
+ */
115
+ hooksPath: string;
112
116
  /** `<home>\git\slot-excludes`. */
113
117
  excludesFile: string;
114
118
  /** DV6 snapshot of the user's line-ending configuration. */
@@ -119,12 +123,12 @@ export interface GitContext {
119
123
  * `hardeningArgs()` (git-tools) then, in this order (a later `-c` wins over the NUL hooksPath it sets):
120
124
  * core.longpaths, core.hooksPath, core.excludesFile, core.editor, sequence.editor, the signing switches, the
121
125
  * rebase/merge switches, rerere, submodule.recurse, advice.detachedHead, user.useConfigOnly, then core.autocrlf and
122
- * core.eol when the snapshot has them.
126
+ * core.eol when the snapshot has them. The repository-only driver blanking is the runner's ({@link withRepositoryDrivers}).
123
127
  */
124
128
  export function executorGitArgs(c: GitContext): string[] {
125
129
  const args = [
126
130
  ...hardeningArgs(),
127
- "-c", "core.longpaths=true", "-c", `core.hooksPath=${c.hooksDir}`, "-c", `core.excludesFile=${c.excludesFile}`,
131
+ "-c", "core.longpaths=true", "-c", `core.hooksPath=${c.hooksPath}`, "-c", `core.excludesFile=${c.excludesFile}`,
128
132
  "-c", "core.editor=:", "-c", "sequence.editor=:",
129
133
  "-c", "commit.gpgSign=false", "-c", "tag.gpgSign=false", "-c", "tag.forceSignAnnotated=false",
130
134
  "-c", "rebase.updateRefs=false", "-c", "rebase.autoStash=false", "-c", "rebase.autoSquash=false",
@@ -137,9 +141,127 @@ export function executorGitArgs(c: GitContext): string[] {
137
141
  return args;
138
142
  }
139
143
 
140
- /** Fixed content of `slot-excludes` (DV5): ignore rules never affect tracked files. */
144
+ /** Bound of one driver listing (its include reads included) before an executor git call. */
145
+ const DRIVER_LISTING_TIMEOUT_MS = 15_000;
146
+
147
+ /** #208: the local LFS restore's warnings, each distinct message once per process. */
148
+ const lfsRestoreWarnings = new Set<string>();
149
+ function warnOnce(message: string): void {
150
+ if (lfsRestoreWarnings.has(message)) return;
151
+ lfsRestoreWarnings.add(message);
152
+ console.warn(`[model-router] executor: ${message}`);
153
+ }
154
+
155
+ /**
156
+ * #208: set on every executor git call, over a caller's own value. Git LFS skips its smudge, so it never downloads an object:
157
+ * no endpoint is asked (not even one a `.lfsconfig` written by the same checkout names) and no transfer program the
158
+ * repository's configuration names (`lfs.customtransfer.*`) is started. Git writes every LFS file as its pointer file;
159
+ * {@link withRepositoryDrivers} then restores, offline, those whose object is in the local LFS store (executor/lfs-restore.ts).
160
+ * The clean filter (commit) is unchanged.
161
+ */
162
+ export const EXECUTOR_GIT_ENV: Readonly<Record<string, string>> = Object.freeze({ GIT_LFS_SKIP_SMUDGE: "1" });
163
+
164
+ /**
165
+ * Where an executor git call runs: `cwd` after a leading `-C <dir>`, and the `--git-dir=`/`--work-tree=` options it passes
166
+ * (in-slot calls), read from the global options before the subcommand. A bare `--git-dir`/`--work-tree` (the value as the
167
+ * next argument) throws `E_GIT`: only the `=` form is located.
168
+ */
169
+ export function gitCallLocation(args: readonly string[], cwd: string): { cwd: string; location: string[] } {
170
+ let at = cwd;
171
+ const location: string[] = [];
172
+ for (let index = 0; index < args.length; index++) {
173
+ const arg = args[index] ?? "";
174
+ if (arg === "-c") { index++; continue; }
175
+ if (arg === "-C") { at = resolve(at, args[++index] ?? ""); continue; }
176
+ if (arg.startsWith("--git-dir=") || arg.startsWith("--work-tree=")) { location.push(arg); continue; }
177
+ // The separate-value form would be skipped as a flag and its value read as the subcommand: the listing would run elsewhere.
178
+ if (arg === "--git-dir" || arg === "--work-tree") {
179
+ throw new ExecutorError("E_GIT", `git ${arg} must carry its value after '=' (${arg}=<path>)`, { op: "config", code: null, stderr: "" });
180
+ }
181
+ if (arg.startsWith("-")) continue; // another global option (--no-pager, --no-optional-locks, --literal-pathspecs)
182
+ break;
183
+ }
184
+ return { cwd: at, location };
185
+ }
186
+
187
+ /**
188
+ * A hardened `GitRunner` (`createGitRunner({ mode: "hardened" })`, possibly with a hardening prefix) whose every call first
189
+ * blanks the filter/merge drivers only the repository's own configuration names and sets its own `protocol.<name>.allow` to
190
+ * `never` (git-tools `repositoryDriverArgs`, include targets of any condition included), placed before the call's own
191
+ * arguments. The configuration is read again for every call (one `git config` process, plus one per include target): a
192
+ * driver added or changed mid-plan (a hook-less `git config` in a slot, a checkout that switches an `onbranch:` include) is
193
+ * never missed, and it costs far less than the call it protects. The listing runs where the call runs (its `-C`, `--git-dir`,
194
+ * `--work-tree`) in the call's own environment with the user's system/global configuration visible, so a global LFS filter
195
+ * and its `git lfs install --local` copy are kept. `filter.<name>.required=true`: a blanked filter makes git refuse
196
+ * (commit, cherry-pick, checkout, reset, clean) instead of writing unfiltered content. The hardened environment hides the
197
+ * system and global configuration, so every filter clean/smudge/process/required and merge driver whose effective value is
198
+ * the user's (system, global, command line) is passed on with `-c` (`forwardUser`, #162): a filter set only globally (Git
199
+ * LFS, git-crypt) applies as with plain git. A user value `-c` cannot carry as git read it (a line break, a byte that is not
200
+ * UTF-8) is not passed on: that filter is blanked and required, so only calls that use it fail. A forwarded filter program
201
+ * (git-lfs) reads the repository's configuration and `.lfsconfig` itself, line by line, so every key it would derive there as
202
+ * an extension command, a custom transfer agent, the standalone agent, `core.sshCommand`, `core.askPass` or `lfs.storage` is
203
+ * blanked, and a credential helper resets the helper list (#184, git-tools `repositoryOnlyDriverArgs`). A configuration that
204
+ * cannot be read, a user driver name with a `=`, such a key `-c` cannot name, a repository include target inside a work tree
205
+ * (the call itself may write it before git-lfs reads it), a `.lfsconfig` that is a link, not a regular file or includes
206
+ * another file, or a config-based hook (`hook.<name>.command|event`, which the hooks-off `core.hooksPath` does not disable)
207
+ * in the repository's configuration, is `E_GIT`, and the call does not run. Not covered: a `.lfsconfig` the call itself
208
+ * writes (a checkout, cherry-pick or rebase) before git-lfs starts, though under {@link EXECUTOR_GIT_ENV} that git-lfs asks
209
+ * no server it names. Every call (and its listing) carries {@link EXECUTOR_GIT_ENV} in its environment: Git LFS never
210
+ * smudges, so it never downloads (#208). After a successful call that can write a work tree (checkout, switch, restore,
211
+ * `reset --hard`, cherry-pick, rebase, revert, merge …), the LFS files whose object is in the local LFS store are restored
212
+ * there through this runner (`restoreLocalLfsObjects`; GitOps asks for the new work tree of `worktree add` with
213
+ * `restoreLocalLfs`), so the restore's own git calls get the same blanking and `hook.*` refusal. A restore never changes the
214
+ * call's result: what it leaves as pointer files is one warning (each distinct message once per process).
215
+ */
216
+ export function withRepositoryDrivers(inner: GitRunner, toplevel: string): GitRunner {
217
+ let executable: string | undefined;
218
+ const restore = async (target: LfsRestoreTarget, o: { timeoutMs: number; env?: Readonly<Record<string, string>>; signal?: AbortSignal }) => {
219
+ const call: LfsRestoreGit = (args, extra) => runner.run(args, {
220
+ cwd: target.cwd, timeoutMs: o.timeoutMs, ...(extra?.maxOutputBytes === undefined ? {} : { maxOutputBytes: extra.maxOutputBytes }),
221
+ ...(o.env === undefined ? {} : { env: o.env }), ...(o.signal === undefined ? {} : { signal: o.signal }),
222
+ });
223
+ let warning: string | undefined;
224
+ try {
225
+ warning = (await restoreLocalLfsObjects(call, target, o.signal === undefined ? {} : { signal: o.signal })).warning;
226
+ } catch (error) {
227
+ warning = `local LFS restore in ${target.cwd}: ${errorText(error)}`;
228
+ }
229
+ if (warning !== undefined) warnOnce(warning);
230
+ };
231
+ const runner: GitRunner = {
232
+ async restoreLocalLfs(prefix: readonly string[], cwd: string, o: { timeoutMs: number; signal?: AbortSignal }): Promise<void> {
233
+ await restore({ prefix: [...prefix], cwd }, o);
234
+ },
235
+ async run(args: readonly string[], p: ProcOpts): Promise<ProcessResult> {
236
+ const { cwd, location } = gitCallLocation(args, p.cwd);
237
+ const env = { ...(p.env ?? {}), ...EXECUTOR_GIT_ENV };
238
+ let drivers: string[];
239
+ try {
240
+ executable ??= gitExecutable(workRootGuards(toplevel));
241
+ drivers = await repositoryDriverArgs(cwd, {
242
+ executable, env: hardenedEnvironment(env), required: true, forwardUser: true, location,
243
+ timeoutMs: Math.min(p.timeoutMs, DRIVER_LISTING_TIMEOUT_MS), ...(p.signal === undefined ? {} : { signal: p.signal }),
244
+ });
245
+ } catch (error) {
246
+ throw new ExecutorError("E_GIT", `git driver configuration could not be read: ${stripUrlUserinfo(errorText(error)).slice(0, 300)}`,
247
+ { op: "config", code: null, stderr: "" });
248
+ }
249
+ const result = await inner.run([...drivers, ...args], { ...p, env });
250
+ const target = result.code === 0 ? lfsRestoreTarget(args, p.cwd) : undefined;
251
+ if (target !== undefined) await restore(target, p);
252
+ return result;
253
+ },
254
+ };
255
+ return runner;
256
+ }
257
+
258
+ /**
259
+ * Fixed content of `slot-excludes` (DV5): ignore rules never affect tracked files. `.omr-lfs-*` (#208): a temporary or
260
+ * pointer backup file the local LFS restore could not remove is never staged by a slot's `add -A`.
261
+ */
141
262
  export const SLOT_EXCLUDES_CONTENT = [
142
263
  "node_modules/", "/.venv/", "/.yarn/cache/", "/.yarn/unplugged/", "/.yarn/install-state.gz", "/.pnp.*", "*.egg-info/",
264
+ ".omr-lfs-*",
143
265
  ].join("\n") + "\n";
144
266
 
145
267
  // ---------------------------------------------------------------------------------------------------------------
@@ -173,11 +295,39 @@ function splitNul(text: string): string[] {
173
295
  return text.split("\0").filter(part => part !== "");
174
296
  }
175
297
 
298
+ /** Sanitize before clipping, so a clipped credential cannot lose the marker identifying it. */
299
+ export function sanitizeGitDiagnostic(text: string): string {
300
+ let clean = stripUrlUserinfo(text)
301
+ .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g, "[redacted key]")
302
+ .replace(/\b(Bearer|Basic)\s+\S+/gi, "$1 ***")
303
+ .replace(/\b([\w.-]{0,64}(?:token|password|passwd|secret|api[_-]?key|credential)[\w.-]{0,64}\s{0,64}[=:]\s{0,64})(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;]+)/gi, "$1***");
304
+ for (const [key, value] of Object.entries(process.env)) {
305
+ if (value !== undefined && value.length >= 4 && /token|password|passwd|secret|api[_-]?key|credential/i.test(key)) clean = clean.split(value).join("***");
306
+ }
307
+ return clean.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim();
308
+ }
309
+
310
+ export function gitStderrTail(text: string): string {
311
+ return sanitizeGitDiagnostic(text).slice(-500);
312
+ }
313
+
314
+ const IDENTITY_FAILURE = /please tell me who you are|unable to auto-detect|empty ident|(?:author|committer) identity unknown|no email was given/i;
315
+ const IDENTITY_HINT = "git has no commit identity in the executor's environment (global config is not read by hardened git): " +
316
+ "set user.name/user.email in the repository, or configure them in your user/global config for the executor's identity resolver. The executor never invents one.";
317
+
176
318
  function gitFailure(op: string, r: ProcessResult): ExecutorError {
177
319
  const stderr = tailBytes(stripUrlUserinfo(r.stderr), GIT_STDERR_TAIL_BYTES);
178
320
  return new ExecutorError("E_GIT", `git ${op} failed (exit ${r.code ?? r.signal ?? "unknown"})`, { op, code: r.code, stderr });
179
321
  }
180
322
 
323
+ export function gitCommitFailure(op: string, r: ProcessResult): ExecutorError {
324
+ const stderr = gitStderrTail(r.stderr);
325
+ const identity = IDENTITY_FAILURE.test(r.stderr);
326
+ return new ExecutorError(identity ? "E_IDENTITY" : "E_GIT",
327
+ `git ${op} failed (exit ${r.code ?? r.signal ?? "unknown"})${identity ? `; ${IDENTITY_HINT}` : ""}${stderr === "" ? "" : `; stderr: ${stderr}`}`,
328
+ { op, code: r.code, stderr });
329
+ }
330
+
181
331
  function requireCommit(value: string, what: string): string {
182
332
  if (!GIT_ID_PATTERN.test(value)) throw invalid(`${what} is not a full git object id`, { value: value.slice(0, 80) });
183
333
  return value;
@@ -189,6 +339,30 @@ function requireCommit(value: string, what: string): string {
189
339
 
190
340
  export interface CommitIdentity { name: string; email: string }
191
341
 
342
+ /** The same explicit identity injection used by GitOps.commit and the runtime's two commit paths. */
343
+ function commitIdentityArgs(identity: CommitIdentity): string[] {
344
+ return ["-c", `user.name=${identity.name}`, "-c", `user.email=${identity.email}`];
345
+ }
346
+
347
+ export type ResolveCommitIdentity = () => Promise<CommitIdentity>;
348
+
349
+ export async function slotCommitIdentityArgs(
350
+ git: GitRunner, o: { cwd: string; timeoutMs: number }, identity: ResolveCommitIdentity | undefined,
351
+ ): Promise<string[]> {
352
+ if (identity === undefined) return []; // Injected test runners may already supply their own identity.
353
+ try {
354
+ return commitIdentityArgs(await identity());
355
+ } catch (error) {
356
+ if (!(error instanceof ExecutorError) || error.code !== "E_IDENTITY") throw error;
357
+ // Read-only probe: retain git's actual exit/stderr without attempting a commit with a guessed identity.
358
+ const r = await git.run(["-c", "user.useConfigOnly=true", "var", "GIT_COMMITTER_IDENT"], o);
359
+ const stderr = gitStderrTail(r.stderr);
360
+ const resolverMessage = sanitizeGitDiagnostic(error.message).slice(0, 1200);
361
+ throw new ExecutorError("E_IDENTITY", `${resolverMessage}; ${IDENTITY_HINT} (git identity probe exit ${r.code ?? "unknown"})${stderr === "" ? "" : `; stderr: ${stderr}`}`,
362
+ { op: "identity", code: r.code, stderr, resolverMessage });
363
+ }
364
+ }
365
+
192
366
  const identityCache = new WeakMap<GitRunner, Map<string, Promise<CommitIdentity & { conversion: GitContext["conversion"] }>>>();
193
367
 
194
368
  async function readConfig(userGit: GitRunner, toplevel: string, key: string): Promise<string | null> {
@@ -380,7 +554,7 @@ async function slotRun(git: GitRunner, o: SlotCall, op: string, args: readonly s
380
554
  return await git.run(args, { cwd: o.cwd, timeoutMs: o.timeoutMs, maxOutputBytes: GIT_MAX_OUTPUT_BYTES });
381
555
  } catch (error) {
382
556
  if (error instanceof ExecutorError) throw error;
383
- throw new ExecutorError("E_GIT", `git ${op} could not run: ${stripUrlUserinfo(errorText(error)).slice(0, 300)}`,
557
+ throw new ExecutorError("E_GIT", `git ${op} could not run: ${gitStderrTail(errorText(error))}`,
384
558
  { op, code: errorCode(error) ?? null, stderr: "" });
385
559
  }
386
560
  }
@@ -398,8 +572,12 @@ async function refCommit(git: GitRunner, o: SlotCall, ref: string): Promise<stri
398
572
  return r.code === 0 && GIT_ID_PATTERN.test(oid) ? oid : null;
399
573
  }
400
574
 
401
- /** QA-PDF21-3: a snapshot step that failed on a leftover `index.lock`. */
402
- const SLOT_INDEX_LOCK_PATTERN = /index\.lock/i;
575
+ /**
576
+ * QA-PDF21-3, #189 L7: a step that failed on a leftover `index.lock`, as git reports it (`Unable to create '…index.lock':
577
+ * File exists`). Any other failure that merely mentions the lock never removes it.
578
+ */
579
+ export const STALE_INDEX_LOCK_PATTERN = /Unable to create '[^'\r\n]*index\.lock': File exists/i;
580
+ const SLOT_INDEX_LOCK_PATTERN = STALE_INDEX_LOCK_PATTERN;
403
581
 
404
582
  /**
405
583
  * pdf2-1 (b): saves the slot's work (tracked changes and untracked, non-ignored files) at `refs/heads/<ref>` without
@@ -417,7 +595,7 @@ export async function snapshotSlotWork(
417
595
  git: GitRunner,
418
596
  i: {
419
597
  cwd: string; ref: string; message: string; trailer: string; timeoutMs: number;
420
- base?: string; fallbackRef?: string; removeIndexLock?: () => Promise<boolean>;
598
+ base?: string; fallbackRef?: string; removeIndexLock?: () => Promise<boolean>; identity?: ResolveCommitIdentity;
421
599
  },
422
600
  ): Promise<WipSnapshot> {
423
601
  const o: SlotCall = { cwd: i.cwd, timeoutMs: i.timeoutMs };
@@ -428,7 +606,7 @@ export async function snapshotSlotWork(
428
606
  lockRemoved = true;
429
607
  if (await i.removeIndexLock()) r = await slotRun(git, o, op, args);
430
608
  }
431
- if (r.code !== 0) throw gitFailure(op, r);
609
+ if (r.code !== 0) throw gitCommitFailure(op, r);
432
610
  return r.stdout;
433
611
  };
434
612
  const status = await must("status", ["status", "--porcelain", "--untracked-files=all"]);
@@ -464,7 +642,8 @@ export async function snapshotSlotWork(
464
642
  }
465
643
  }
466
644
  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();
645
+ const identity = await slotCommitIdentityArgs(git, o, i.identity);
646
+ const commit = (await must("commit-tree", [...identity, "commit-tree", "--no-gpg-sign", tree, "-p", parent, "-m", i.message, "-m", i.trailer])).trim();
468
647
  requireCommit(commit, "WIP commit");
469
648
  const zero = "0".repeat(commit.length);
470
649
  const update = ["update-ref", "--no-deref", `refs/heads/${i.ref}`, commit, old ?? zero];
@@ -482,7 +661,7 @@ export async function snapshotSlotWork(
482
661
  }
483
662
  }
484
663
  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,
664
+ op: "update-ref", code: r.code, stderr: gitStderrTail(r.stderr), commit, keptAt,
486
665
  });
487
666
  }
488
667
  }
@@ -633,14 +812,15 @@ export function createGitOps(d: GitOpsDeps): GitOps {
633
812
  const timeoutMs = d.timeoutMs ?? GIT_OP_TIMEOUT_MS;
634
813
  const toplevel = d.toplevel;
635
814
  const gitHome = join(d.executorHome, "git");
636
- const hooksDir = join(gitHome, "no-hooks");
815
+ // #215: a regular file, not the former `no-hooks` directory (an old home keeps that one, unused).
816
+ const hooksPath = join(gitHome, "hooks-off");
637
817
  const excludesFile = join(gitHome, "slot-excludes");
638
818
  const refFormatCache = new Map<string, boolean>();
639
819
  let versionCache: string | undefined;
640
820
  let contextPromise: Promise<OpsContext> | undefined;
641
821
  let commonCache: string | undefined;
642
822
 
643
- // ---- context: hooks directory, excludes file, identity and conversion snapshot ----
823
+ // ---- context: hooks path, excludes file, identity and conversion snapshot ----
644
824
 
645
825
  async function ensureDir(p: string): Promise<void> {
646
826
  const st = await d.fs.lstat(p);
@@ -656,10 +836,12 @@ export function createGitOps(d: GitOpsDeps): GitOps {
656
836
  async function prepareFiles(): Promise<void> {
657
837
  await ensureDir(d.executorHome);
658
838
  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 });
839
+ if ((await d.fs.lstat(hooksPath)) === null) {
840
+ try { await d.fs.writeText(hooksPath, "", { exclusive: true, fsync: true }); } catch (error) {
841
+ if (errorCode(error) !== "EEXIST") throw error;
842
+ }
843
+ }
844
+ await assertHooksOff();
663
845
  const existing = await d.fs.lstat(excludesFile);
664
846
  if (existing !== null && existing.kind !== "file") throw new ExecutorError("E_GIT", "slot excludes path is not a file", { path: excludesFile });
665
847
  if (existing === null || (await d.fs.readText(excludesFile)) !== SLOT_EXCLUDES_CONTENT) {
@@ -672,7 +854,7 @@ export function createGitOps(d: GitOpsDeps): GitOps {
672
854
  const pending = (async (): Promise<OpsContext> => {
673
855
  await prepareFiles();
674
856
  const { conversion, ...identity } = await readCommitIdentity(d.userGit, toplevel);
675
- return { args: executorGitArgs({ hooksDir, excludesFile, conversion }), identity };
857
+ return { args: executorGitArgs({ hooksPath, excludesFile, conversion }), identity };
676
858
  })();
677
859
  contextPromise = pending;
678
860
  pending.catch(() => { if (contextPromise === pending) contextPromise = undefined; });
@@ -706,20 +888,22 @@ export function createGitOps(d: GitOpsDeps): GitOps {
706
888
  }
707
889
 
708
890
  function identityArgs(x: OpsContext, wanted: boolean | undefined): string[] {
709
- return wanted === true ? ["-c", `user.name=${x.identity.name}`, "-c", `user.email=${x.identity.email}`] : [];
891
+ return wanted === true ? commitIdentityArgs(x.identity) : [];
710
892
  }
711
893
 
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 });
894
+ /**
895
+ * The hooks path is re-checked before every call: an op could run a hook only if it were replaced by a directory. Not a link,
896
+ * not a directory, zero bytes.
897
+ */
898
+ async function assertHooksOff(): Promise<void> {
899
+ const st = await d.fs.lstat(hooksPath);
900
+ if (st === null || st.kind !== "file" || st.size !== 0) throw new ExecutorError("E_GIT", "hooks path is not an empty regular file", { path: hooksPath });
717
901
  }
718
902
 
719
903
  /** cwd = toplevel. */
720
904
  async function inRepo(c: Call): Promise<ProcessResult> {
721
905
  const x = await context();
722
- await assertHooksEmpty();
906
+ await assertHooksOff();
723
907
  return exec(c.op, toplevel, [...x.args, ...identityArgs(x, c.identity), ...c.args], c.timeoutMs ?? timeoutMs, c.service);
724
908
  }
725
909
 
@@ -727,7 +911,7 @@ export function createGitOps(d: GitOpsDeps): GitOps {
727
911
  async function inSlot(slot: string, c: Call): Promise<ProcessResult> {
728
912
  const { gitdir } = await verifySlotPointers(slot);
729
913
  const x = await context();
730
- await assertHooksEmpty();
914
+ await assertHooksOff();
731
915
  const scope = [`--git-dir=${gitdir}`, `--work-tree=${slot}`];
732
916
  return exec(c.op, slot, [...x.args, ...identityArgs(x, c.identity), ...scope, ...c.args], c.timeoutMs ?? timeoutMs, c.service);
733
917
  }
@@ -875,6 +1059,18 @@ export function createGitOps(d: GitOpsDeps): GitOps {
875
1059
  op: "worktree add", timeoutMs: GIT_WORKTREE_ADD_TIMEOUT_MS, identity: true,
876
1060
  args: ["worktree", "add", "--detach", "--lock", "--reason", lockReason, path, commit],
877
1061
  }), "worktree add");
1062
+ // #208: the new work tree's local LFS objects, restored through its explicit --git-dir/--work-tree (as inSlot), never
1063
+ // repository discovery. A slot whose pointers do not verify is left to the checks that report it, with one warning.
1064
+ if (d.git.restoreLocalLfs === undefined) return;
1065
+ let gitdir: string;
1066
+ try { ({ gitdir } = await verifySlotPointers(path)); } catch (error) {
1067
+ warnOnce(`local LFS restore in ${path}: skipped, its git pointers do not verify (${stripUrlUserinfo(errorText(error)).slice(0, 300)}); `
1068
+ + "its LFS files stay pointer files (`git lfs checkout` there restores them)");
1069
+ return;
1070
+ }
1071
+ const x = await context();
1072
+ await assertHooksOff();
1073
+ await d.git.restoreLocalLfs([...x.args, `--git-dir=${gitdir}`, `--work-tree=${path}`], path, { timeoutMs: GIT_WORKTREE_ADD_TIMEOUT_MS });
878
1074
  }
879
1075
 
880
1076
  async function worktreeRemove(path: string, lockReason: string): Promise<void> {