@awebai/oats 0.55.1 → 0.57.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 (82) hide show
  1. package/bin/oats.mjs +96 -72
  2. package/docs/capabilities.md +67 -3
  3. package/docs/design/2026-09-23-workspace-module-contracts.md +27 -3
  4. package/docs/desktop-cli-api.md +375 -37
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +65 -11
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +153 -11
  10. package/docs/integrations.md +5 -3
  11. package/docs/knowledge.md +117 -43
  12. package/docs/official-catalog.md +3 -3
  13. package/docs/packages.md +12 -12
  14. package/docs/release-lane.md +26 -1
  15. package/docs/release-notes/v0.56.0.md +699 -0
  16. package/docs/release-notes/v0.57.0.md +283 -0
  17. package/docs/schedules.md +8 -3
  18. package/docs/servers.md +21 -5
  19. package/docs/souls-and-instances.md +134 -19
  20. package/docs/tui.md +215 -31
  21. package/docs/upgrading.md +4 -1
  22. package/docs/workspaces.md +26 -6
  23. package/lib/automations.mjs +3 -4
  24. package/lib/bounded-read.mjs +18 -0
  25. package/lib/capability-show.mjs +13 -2
  26. package/lib/claim.mjs +3 -4
  27. package/lib/core.mjs +919 -278
  28. package/lib/errors.mjs +39 -0
  29. package/lib/harness-trust-write.mjs +119 -40
  30. package/lib/harness-trust.mjs +31 -18
  31. package/lib/instance-inspect.mjs +160 -11
  32. package/lib/instance-lifecycle.mjs +90 -37
  33. package/lib/packages.mjs +8 -5
  34. package/lib/pi-bridge.mjs +18 -19
  35. package/lib/remote.mjs +88 -51
  36. package/lib/retire-output.mjs +9 -4
  37. package/lib/schedule.mjs +3 -4
  38. package/lib/servers.mjs +39 -6
  39. package/lib/session-viewer.mjs +25 -1
  40. package/lib/triggers.mjs +3 -4
  41. package/lib/workspace.mjs +6 -6
  42. package/lib/worktree.mjs +33 -8
  43. package/lib/write-through-private-file.mjs +26 -0
  44. package/package-catalog.json +2 -2
  45. package/package.json +1 -1
  46. package/packages/client/cli-adapter.mjs +108 -13
  47. package/packages/client/cli-locator.mjs +16 -14
  48. package/packages/client/deployment-panel.mjs +4 -3
  49. package/packages/client/display-text.mjs +2 -1
  50. package/packages/client/instance-events-contract.mjs +4 -3
  51. package/packages/client/instance-lifecycle.mjs +235 -0
  52. package/packages/client/instance-presentation.mjs +9 -0
  53. package/packages/client/instance-tree.mjs +10 -8
  54. package/packages/client/kernel-lines.mjs +3 -3
  55. package/packages/client/launch-contract.mjs +11 -0
  56. package/packages/client/launch-prompt-outcome.mjs +1 -1
  57. package/packages/client/lifecycle-cli.mjs +12 -6
  58. package/packages/client/lifecycle-confirmation.mjs +407 -0
  59. package/packages/client/lifecycle-contract.mjs +6 -2
  60. package/packages/client/own-codes.mjs +1 -0
  61. package/packages/client/panel-views.mjs +39 -2
  62. package/packages/client/readiness-contract.mjs +2 -2
  63. package/packages/client/remote-roster.mjs +50 -5
  64. package/packages/client/roster-sections.mjs +3 -3
  65. package/packages/client/session-start.mjs +98 -0
  66. package/packages/client/start-gate.mjs +46 -0
  67. package/packages/client/start-messages.mjs +17 -0
  68. package/packages/client/workspace-views.mjs +2 -2
  69. package/packages/tui/README.md +21 -8
  70. package/packages/tui/lib/actions.mjs +11 -2
  71. package/packages/tui/lib/client.mjs +9 -2
  72. package/packages/tui/lib/config.mjs +39 -9
  73. package/packages/tui/lib/main.mjs +168 -20
  74. package/packages/tui/lib/model.mjs +315 -13
  75. package/packages/tui/lib/open.mjs +45 -0
  76. package/packages/tui/lib/read.mjs +171 -16
  77. package/packages/tui/lib/store.mjs +171 -10
  78. package/packages/tui/lib/term/tty.mjs +71 -12
  79. package/packages/tui/lib/views/act.mjs +85 -0
  80. package/packages/tui/lib/views/frame.mjs +145 -33
  81. package/packages/tui/lib/views/help.mjs +46 -11
  82. package/skills/oats-getting-started/SKILL.md +6 -3
@@ -8,13 +8,14 @@
8
8
  * make a retried apply return the first receipt rather than act twice.
9
9
  * Unknown is reported as unknown — never as "clean" or "no children". */
10
10
  import { createHash } from "node:crypto";
11
- import { existsSync, lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
+ import { existsSync, lstatSync, readFileSync, rmSync } from "node:fs";
12
12
  import { basename, join } from "node:path";
13
13
  import { attachedWorkLink, claimHomeFor, extraWorktreePlan, findInstanceHomes, homeClaimHolder, identifiedHomeRecord, inspectInstanceSession, instanceWork, listAgents, listInstances, observeSessionWithoutReceipt, readHomeRecord, READ_CLAIM_WHEN_UNWRITABLE, releaseHomeClaim, requireStopGrace, retireClaimPath, retirePendingMarkerPath, retirementRecoveryFacts, shq, stillRunningOf, stopInstanceSession, STOP_UNDER_CLAIM } from "./core.mjs";
14
14
  import { groupedByOwner } from "./retire-output.mjs";
15
15
  import { observeInstanceGit } from "./instance-git.mjs";
16
16
  import { appendEvent } from "./instance-events.mjs";
17
17
  import { afterFirstEffect, isAnswerCode, kernelCode, lifecycleBusy, oatsError, reportDefect } from "./errors.mjs";
18
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
18
19
 
19
20
  export const LIFECYCLE_API = 1;
20
21
  const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -105,6 +106,21 @@ function sessionFacts(home) {
105
106
  try { const s = inspectInstanceSession(home); return { state: s.state, present: s.present, backend: s.backend ?? null, established: true }; }
106
107
  catch (e) { return { state: "unestablished", present: null, backend: null, established: false, reason: kernelCode(e, "E_SESSION_UNAVAILABLE") }; }
107
108
  }
109
+ /** The instances attached to `tree`, a tree of the home of the instance `name` under `root` (its
110
+ * `work/` or an extra tree; #964) → [{ instance, home, session }]. `session` is the session as a
111
+ * stop plan reads it (sessionFacts), in one word: "running", "stopped", or "unknown" when it could
112
+ * not be established, which is never taken for stopped. Who is looked at: the recorded
113
+ * descendants of `name`, as a plan lists them, and the instances that record `name` as their
114
+ * parent under a name that is not unique (a plan's `ambiguous`). Lineage does not make an
115
+ * instance attached: its `work` link does (core attachedWorkLink), so these are read too. For
116
+ * `oats worktree remove`, which removes a tree under nobody's running session. Read-only. */
117
+ export function attachedToTree(root, name, tree) {
118
+ const kids = descendantsOf(root, name);
119
+ return [...kids, ...(kids.ambiguous || [])].filter((c) => attachedWorkLink(c.home, tree) !== null).map((c) => {
120
+ const s = sessionFacts(c.home);
121
+ return { instance: c.instance, home: c.home, session: running(s) ? "running" : s.established ? "stopped" : "unknown" };
122
+ });
123
+ }
108
124
  /** Retire's view of a home without its session receipt (before 0.25.9): the
109
125
  * retirement needs only absence, which it can observe — `{state: "absent",
110
126
  * present: false, established: true, note}`; live or ambiguous stays
@@ -295,19 +311,13 @@ export function applyStop(ctx, root, name, { home, recursive = true, planRevisio
295
311
  }
296
312
  }
297
313
 
298
- /** Write `value` as JSON at `path` through a private file beside it, renamed over it. When the
299
- * write or the rename fails the private file is removed and the error thrown is that failure's
300
- * (awebai/oats#963, as core.mjs writeJsonAtomic). The removal's own failure is not answered.
301
- * Exported for its test alone (test/stop-private-files.test.mjs): its one caller keeps the error
302
- * to itself, so nothing but a call of it shows what it throws. */
314
+ /** Write `value` as JSON at `path` through a private file beside it (`<path>.<pid>.tmp`), renamed
315
+ * over it, by the kernel's one such writer (lib/write-through-private-file.mjs): when the write or
316
+ * the rename fails the private file is removed and the error thrown is that failure's
317
+ * (awebai/oats#963, #1076). Exported for its test alone (test/stop-private-files.test.mjs): its one
318
+ * caller keeps the error to itself, so nothing but a call of it shows what it throws. */
303
319
  export function writeFileSyncAtomic(path, value) {
304
- const tmp = `${path}.${process.pid}.tmp`;
305
- try {
306
- writeFileSync(tmp, JSON.stringify(value, null, 2)); renameSync(tmp, path);
307
- } catch (e) {
308
- try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
309
- throw e;
310
- }
320
+ writeThroughPrivateFile(path, `${path}.${process.pid}.tmp`, JSON.stringify(value, null, 2));
311
321
  }
312
322
 
313
323
  /** The sentence a stop's text closes with, chosen from the receipt's rows as a client reads them
@@ -358,21 +368,31 @@ function fitParts(render, parts) {
358
368
 
359
369
  /** A retire plan's note for one extra tree (core extraWorktreePlan row). Too long for the Desktop, its
360
370
  * longest parts go to the plan JSON, longest first; the tree's path stays whole, or the note says it
361
- * is too long and where it is. */
362
- function extraWorktreeNote(t) {
371
+ * is too long and where it is. `attached`: the names of the recorded children whose work is this
372
+ * tree (#964). The note names them and says what the retire leaves each with: its link repointed to
373
+ * the tree where it is re-homed, or pointing at a path that is gone where the tree is removed. A
374
+ * tree the retire refuses is neither moved nor removed, and nothing is said of them. `others`: the
375
+ * names of the instances attached to it that the plan lists under `ambiguous`. The retire does not
376
+ * act on them, and the note says what that leaves them with, in a clause of its own. */
377
+ function extraWorktreeNote(t, attached = [], others = []) {
378
+ const said = t.disposition !== "refuse";
379
+ const kids = attached.length && said ? (p) => `; attached child instance(s) ${p.kids} use it as their work, and ${t.disposition === "remove" ? "their work link would then point at a path that is gone" : "the retire repoints their work link to it"}` : () => "";
380
+ const rest = others.length && said ? (p) => `; attached instance(s) ${p.others}, listed under ambiguous, use it as their work: ${t.disposition === "remove" ? "the retire does not stop them, and their work link would then point at a path that is gone" : `the retire neither stops them nor repoints their work link, which would then point at a path that is gone (the tree would be at ${p.movedTo})`}` : () => "";
363
381
  const parts = {
382
+ ...(attached.length ? { kids: [listWithin(attached, (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? String(attached.length), `${attached.length} of the recorded children`] } : {}),
383
+ ...(others.length ? { others: [listWithin(others, (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? String(others.length), `(${others.length} of them)`] } : {}),
364
384
  at: [t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt.slice(0, 12)}` : "a HEAD that could not be read", `its HEAD: see ${SEE_EXTRA}`],
365
385
  repo: [t.repo, `its repository (see ${SEE_EXTRA})`],
366
386
  movedTo: [t.movedTo, `the path ${SEE_EXTRA} names`],
367
387
  reason: [t.reason, `${SEE_EXTRA} says why`],
368
388
  };
369
- const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}`
370
- : t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}`
389
+ const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}${kids(p)}${rest(p)}`
390
+ : t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}${kids(p)}${rest(p)}`
371
391
  : `extra worktree ${t.path} (${p.at}): retire refuses, ${p.reason}`;
372
392
  const note = fitParts(render, parts);
373
393
  if (note !== null) return note;
374
394
  const outcome = t.disposition === "remove" ? "would be removed" : t.disposition === "retain" ? "would be re-homed" : "makes retire refuse";
375
- return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it`;
395
+ return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it${kids({ kids: `${attached.length} of the recorded children` })}${rest({ others: `(${others.length} of them)`, movedTo: `the path ${SEE_EXTRA} names` })}`;
376
396
  }
377
397
  /** The plan's note when the worktree is not on the recorded branch: both names, or, too long for the
378
398
  * note, pointers to the plan JSON fields that hold them. */
@@ -448,29 +468,61 @@ export function planRetire(ctx, root, name, { home } = {}) {
448
468
  const defaults = { retainWorktree: ownTree, deleteBranch: false, stopChildren: true, retainChildren: true };
449
469
  // The repository the retire would read from Git for an own tree whose record names none.
450
470
  const repoFromGit = ownTree && !meta.repo ? workIs.tree?.repo ?? null : null;
451
- const byModeAlone = meta.work === "worktree" ? "own-tree" : meta.work === "directory" ? "directory-mode" : workIs.at;
452
- const workBinding = workIs.is !== byModeAlone || repoFromGit ? { work: workIs.is, repo: repoFromGit } : null;
453
- const safety = [me.home, target.session.state, target.launched, facts.work.observed ? [facts.work.revision, facts.work.branch, facts.work.changed, facts.work.untracked] : null, kids.map((c) => c.home),
454
- // Only when there are any: a home without extra trees keeps the revision it had.
455
- ...(extraWorktrees.length ? [extraWorktrees] : []),
456
- // What work/ is decides what the retire does with it (#962), so it is part of the revision: a
457
- // guarded apply refuses as stale when an own tree became a directory of the home, or the other
458
- // way round, since the plan was shown, and when the repository read from Git changed. A link
459
- // under a record that says `worktree` is bound the same way (#973): a plan read while work/ was
460
- // a link is stale once work/ is the instance's own tree, and the other way round. Only where
461
- // the answer is not the one the record's mode alone gives: every other home keeps the revision
462
- // it had.
463
- ...(workBinding ? [workBinding] : [])];
464
- // What retire would preserve and where, read from the spawn baseline and the
465
- // work mode: nothing is hashed, and the plan revision does not depend on it.
466
- // The declared roots are listed as written, bounded so one note stays short.
467
- const recovery = retirementRecoveryFacts(me.home);
468
471
  // Attached children whose work is this home's work/ (#718): a retire that keeps the worktree
469
472
  // repoints them to it. One note holds whatever the dialog then picks.
470
- const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, me.home) !== null) : [];
473
+ const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, join(me.home, "work")) !== null) : [];
474
+ // The instances attached to a tree of this home that record it as their parent under a name that
475
+ // is not unique (`ambiguous`): the retire does not act on them, so each tree's note says what the
476
+ // retire leaves them with (#964). Lineage does not make an instance attached: its link does.
477
+ const attachedAmbiguous = (tree) => (kids.ambiguous || []).filter((c) => attachedWorkLink(c.home, tree) !== null);
478
+ const ambiguousOnWork = ownTree ? attachedAmbiguous(join(me.home, "work")) : [];
479
+ // Each extra tree's attached instances, as its note names them: the recorded children, and those
480
+ // of an ambiguous name.
481
+ const extraAttached = extraWorktrees.map((t) => ({ kids: kids.filter((c) => attachedWorkLink(c.home, t.path) !== null), others: attachedAmbiguous(t.path) }));
482
+ // The session as the plan shows it, whole: its state, and the reason or the note of one that is
483
+ // not established, which the record's launch and endpoint fields decide (awebai/oats#1065). The
484
+ // children as the plan names them (a child's agent is the name its soul's file gives, which its
485
+ // home's path does not hold), and with them what the plan shows of other homes' records: the edges
486
+ // it could not follow (facts.ambiguous, whole: each edge's reason counts the homes of the name)
487
+ // and the instances attached to this work and to each extra tree, which the notes name (#964;
488
+ // attached instances are made by spawns, so they do not move by themselves). Where Git gives no answer for work/, the
489
+ // reason the plan shows for that (facts.work.reason): nothing at work/ and a file there are one
490
+ // answer of the reading under a record that says `worktree`, and two plans. Where Git answers,
491
+ // what the plan shows of the tree that does not move by itself: the commit, the branch and
492
+ // whether HEAD is detached, whether that branch is not the record's (drift, as shown: it comes
493
+ // from a second read of the record, after this plan's, in observeInstanceGit, so it is not
494
+ // derived from facts.recordedBranch), the counts of changed and untracked files, and what
495
+ // the clone's configuration names (the branch's upstream, the remote's host and path). Left
496
+ // out, because a fetch by anyone who shares the clone moves it: the counts against the upstream
497
+ // and the default branch, and the default branch's name (a fetch creates a missing origin/HEAD).
498
+ // docs/desktop-cli-api.md names what is left out, and why.
499
+ const tree = facts.work.observed ? [facts.work.revision, facts.work.branch, facts.work.changed, facts.work.untracked, facts.work.detached, facts.work.drift, facts.work.upstream.ref, facts.work.remote] : { unobserved: facts.work.reason };
500
+ // What retire would preserve and where, read from the spawn baseline and the work mode. A plan
501
+ // hashes no file for it. The declared roots are listed in a note as written, bounded so one
502
+ // note stays short, and are part of the plan's revision (awebai/oats#1065).
503
+ const recovery = retirementRecoveryFacts(me.home);
504
+ const safety = [me.home, target.session, target.launched, tree, kids.map((c) => [c.instance, c.agent, c.home]),
505
+ { ambiguous: facts.ambiguous, attached: attached.map((c) => c.home), ambiguousOnWork: ambiguousOnWork.map((c) => c.home),
506
+ extra: extraWorktrees.map((t, i) => [t.path, extraAttached[i].kids.map((c) => c.home), extraAttached[i].others.map((c) => c.home)]) },
507
+ // The home's extra trees, when there are any.
508
+ ...(extraWorktrees.length ? [extraWorktrees] : []),
509
+ // What the plan reports of the record about work/ (its work mode, its repository, its branch),
510
+ // which the instance can write, and what work/ is by the reading the retire makes too (#962,
511
+ // #973), with the repository Git names for work/ wherever it is a registered work tree: all
512
+ // of it is part of every retire plan's revision, in every home (awebai/oats#1065). So no two
513
+ // plans of one home that the record or the reading makes different, in a fact, a default, a
514
+ // note or the text's line, share a revision, and a guarded apply refuses as stale when one of
515
+ // them moved since the plan was shown. Unconditional: no home, no value of the record and no
516
+ // answer of the reading is left out. A field of the record that a plan comes to show joins
517
+ // this binding (test/retire-plan-revision.test.mjs rewrites each in turn).
518
+ { mode: facts.workMode, repo: facts.repo, branch: facts.recordedBranch, work: workIs.is, tree: workIs.tree?.repo ?? null },
519
+ // Where a recovery would be written and the declared roots it leaves out, as the spawn's
520
+ // receipt gives them: the roots with their owners, not the note made from them, which is
521
+ // shortened past its budget and then reads alike for two lists of one length.
522
+ recovery];
471
523
  appendEvent(me.home, { kind: "retire-planned", data: { planRevision: planRevision(safety), children: kids.length, dirty: facts.work.observed ? facts.work.changed + facts.work.untracked : null } }, { workspaceOnly: true });
472
524
  const plan = { lifecycleApi: LIFECYCLE_API, action: "retire", instance: name, home: me.home, at: new Date().toISOString(), facts, defaults, planRevision: planRevision(safety),
473
- notes: boundedNotes(extraWorktrees.map(extraWorktreeNote), [
525
+ notes: boundedNotes(extraWorktrees.map((t, i) => extraWorktreeNote(t, extraAttached[i].kids.map((c) => c.instance), extraAttached[i].others.map((c) => c.instance))), [
474
526
  // The two notes about a worktree that is retained are for the instance's own tree alone (#973).
475
527
  // Not for a directory of the home (what it holds is copied and removed), not for a directory
476
528
  // instance whose work/ is a repository of its own (the recovery note below says what is done),
@@ -485,6 +537,7 @@ export function planRetire(ctx, root, name, { home } = {}) {
485
537
  ], [
486
538
  ...(kids.length ? [`${kids.length} recorded child instance(s) are stopped first (bounded SIGTERM, never escalated) and retained (their homes are not removed); a child still running after the grace refuses the retirement`] : []),
487
539
  ...(attached.length ? [`attached child instance(s) ${listWithin(attached.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? attached.length} use this home's work/ as their work: a retire that keeps the worktree repoints their work link to it; with --discard-worktree the worktree is removed and their work link will dangle`] : []),
540
+ ...(ambiguousOnWork.length ? [`attached instance(s) ${listWithin(ambiguousOnWork.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? ambiguousOnWork.length}, listed under ambiguous, use this home's work/ as their work: the retire neither stops them nor repoints their work link, which will then point at a path that is gone, whether the worktree is retained (the receipt names where) or removed with --discard-worktree`] : []),
488
541
  ...((kids.ambiguous || []).length ? [`${kids.ambiguous.length} instance(s) record this name as parent but the name is not unique under this root; they are listed under ambiguous and NOT acted on`] : []),
489
542
  ...(target.session.note ? [sessionNote(target.session)] : []),
490
543
  "pull request state is unknown to the kernel; the ADE reports it when a forge connection exists",
package/lib/packages.mjs CHANGED
@@ -115,7 +115,10 @@ export function writeFileAtomic(file, contents, { mode } = {}) {
115
115
  try { fchmodSync(fd, mode); writeFileSync(fd, contents); } finally { closeSync(fd); }
116
116
  }
117
117
  renameSync(tmp, file);
118
- } finally { rmSync(tmp, { force: true }); }
118
+ } finally {
119
+ // A failed removal is not answered: when the write or the rename failed, that error is (#1076).
120
+ try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
121
+ }
119
122
  }
120
123
 
121
124
  /** Exact copy via `writeFileAtomic` (copyFileSync would follow a destination symlink). */
@@ -290,10 +293,10 @@ export function parsePackageRequest(id, value, catalog) {
290
293
  const c = classifyPackageValue(value);
291
294
  if (c.problem) {
292
295
  const code = typeof value === "string" && value.trim().startsWith("git:") ? "E_REPO_REF" : "E_WORKSPACE_SCHEMA";
293
- const safe = { id, value: defaultRemote.redactUrl(value, null, { reference: true }), path: `/packages/${id}`,
294
- problems: [defaultRemote.redactUrl(c.problem, value, { known: false })] };
295
- const message = defaultRemote.redactUrl(`packages.${safe.id}: ${safe.problems[0]}, got ${JSON.stringify(safe.value)}`,
296
- value, { known: false, refusal: true });
296
+ const safe = { id, value: defaultRemote.displayRepoRef(value), path: `/packages/${id}`,
297
+ problems: [defaultRemote.displayDiagnosticText(c.problem, value)] };
298
+ const message = defaultRemote.displayDiagnosticText(`packages.${safe.id}: ${safe.problems[0]}, got ${JSON.stringify(safe.value)}`,
299
+ value, { refusal: true });
297
300
  throw oatsError(code, message, safe);
298
301
  }
299
302
  if (c.kind === "git") return { kind: "git", remoteRef: c.repo, at: c.at, path: DEFAULT_PACKAGE_PATH };
package/lib/pi-bridge.mjs CHANGED
@@ -26,16 +26,15 @@ import { isAbsolute, join, resolve } from "node:path";
26
26
  import { homedir } from "node:os";
27
27
  import { compareVersions, parseVersion } from "./resolve.mjs";
28
28
  import { safeText } from "./refused-text.mjs";
29
+ import { HARNESS_FOLDER_VAR, launchConfigFolder } from "./harness-trust.mjs";
29
30
 
30
31
  export const PI_BRIDGE = "@awebai/oats-pi";
31
32
  const KERNEL_PACKAGE = "@awebai/oats";
32
33
  /** The variable that moves pi's folder. */
33
- export const PI_FOLDER_VAR = "PI_CODING_AGENT_DIR";
34
+ export const PI_FOLDER_VAR = HARNESS_FOLDER_VAR.pi;
34
35
 
35
36
  const real = (p) => { try { return realpathSync.native(p); } catch { return resolve(p); } };
36
37
  const userHome = (env) => env.HOME || homedir();
37
- /** A leading `~` is the user's home, as the kernel reads it for pi's resource folder (core.mjs). */
38
- const expandHome = (p, env) => p.replace(/^~(?=$|\/)/, () => userHome(env));
39
38
  /** One shell word: as is when it needs no quoting, else single-quoted. */
40
39
  const shellWord = (value) => /^[A-Za-z0-9_\/.,:@%+=-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\"'\"'") + "'";
41
40
  const bridgeSpec = (target) => `npm:${PI_BRIDGE}@${target}`;
@@ -101,6 +100,20 @@ export function planCliUpdate(installed, registry) {
101
100
  return { installed, registry, target: registry, ahead: false, step: { argv, display: argv.join(" ") } };
102
101
  }
103
102
 
103
+ /** The line `oats update` prints under its steps when the CLI's install (`cli`, from
104
+ * planCliUpdate) moves it to another minor or major version: a Desktop accepts a CLI up to its
105
+ * own minor version and refuses a newer one (docs/upgrading.md, "Why the Desktop goes first").
106
+ * Fixed text, whether or not a Desktop is installed here: one on another host, or installed
107
+ * another way, would not be seen. Prerelease and build metadata do not count (0.56.0-rc.1 to
108
+ * 0.56.0 says nothing); an installed version that cannot be read is another minor.
109
+ * → the line, or null when there is no install or it stays within the minor. */
110
+ export function desktopFirstLine(cli) {
111
+ if (!cli.step) return null;
112
+ const from = parseVersion(cli.installed), to = parseVersion(cli.target);
113
+ if (from && to && from.major === to.major && from.minor === to.minor) return null;
114
+ return `OATS Desktop refuses a CLI newer than its own minor version: if you use it, install OATS Desktop ${cli.target} first.`;
115
+ }
116
+
104
117
  /** The lookup `oats update` makes before any step, as arguments: the bridge's exact version on
105
118
  * the registry, with npm told to revalidate its cache (awebai/oats#852). */
106
119
  export const bridgeLookup = (target) => ["npm", "view", `${PI_BRIDGE}@${target}`, "version", "--prefer-online"];
@@ -123,20 +136,6 @@ export function bridgeLookupProblem(ran, cli) {
123
136
  return `${notSeen}: a version is listed a few minutes after it is published. Nothing was changed, and every bridge is in place. Run \`oats update\` again in a few minutes.`;
124
137
  }
125
138
 
126
- /** The pi folder a launch configuration's `env` names: `{dir}` from a literal or a {fromEnv}
127
- * resolved from the host `base`; `{problem}` when the reference is not set on this host or the
128
- * path is not absolute; null when the configuration leaves it to the host. The rule and the
129
- * wording of `launchConfigDir` (harness-trust.mjs), which is keyed by the harnesses that have
130
- * folder trust and so cannot name pi. */
131
- export function launchConfigPiFolder(configEnv = {}, base = process.env) {
132
- if (!Object.hasOwn(configEnv || {}, PI_FOLDER_VAR)) return null;
133
- const v = configEnv[PI_FOLDER_VAR];
134
- const named = typeof v === "string" ? v : base[v?.fromEnv];
135
- if (named === undefined) return { problem: `${PI_FOLDER_VAR} references ${v?.fromEnv}, not set on this host`, fromEnv: v?.fromEnv };
136
- const dir = expandHome(named, base);
137
- return isAbsolute(dir) ? { dir } : { problem: `${PI_FOLDER_VAR} ${JSON.stringify(named)} is not an absolute path` };
138
- }
139
-
140
139
  /** The pi folders of a deployment, in a fixed order: the default, this process's own, then each
141
140
  * pi launch configuration's in name order. Folders are deduplicated by real path; one keeps
142
141
  * every reason it is listed for, and the path it was first named by. A folder that cannot be
@@ -155,11 +154,11 @@ export function piFolders({ env = process.env, launchConfigs = {} } = {}) {
155
154
  add(join(userHome(env), ".pi", "agent"), { kind: "default" });
156
155
  // An empty value is not set, as core.mjs reads it (piAgentDir).
157
156
  if (env[PI_FOLDER_VAR]) {
158
- const found = launchConfigPiFolder({ [PI_FOLDER_VAR]: env[PI_FOLDER_VAR] }, env);
157
+ const found = launchConfigFolder(PI_FOLDER_VAR, { [PI_FOLDER_VAR]: env[PI_FOLDER_VAR] }, env);
159
158
  if (found.problem) unresolved({ kind: "shell" }, found); else add(found.dir, { kind: "shell" });
160
159
  }
161
160
  for (const config of Object.values(launchConfigs).filter((c) => c.harness === "pi").sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
162
- const found = launchConfigPiFolder(config.env, env);
161
+ const found = launchConfigFolder(PI_FOLDER_VAR, config.env, env);
163
162
  if (!found) continue;
164
163
  // A relative executable is a path against the deployment directory, as a launch resolves it.
165
164
  const executable = config.executable?.includes("/") && !isAbsolute(config.executable) && config.source ? resolve(config.source, config.executable) : config.executable;
package/lib/remote.mjs CHANGED
@@ -173,6 +173,7 @@ import { fileURLToPath } from "node:url";
173
173
  import { oatsError } from "./errors.mjs";
174
174
  import { REFUSED_TEXT } from "./refused-text.mjs";
175
175
  import { killGroup, signalGroup, terminateGroup, watchGroup } from "./process-group.mjs";
176
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
176
177
 
177
178
  export const FILE_BUDGET = 4 * 1024 * 1024; // readRemoteFile: 4 MiB per file
178
179
  export const TREE_BUDGET = 64 * 1024 * 1024; // fetchRemoteTree: 64 MiB per subtree
@@ -217,19 +218,19 @@ function fail(code, message, details, { rejected = [] } = {}) {
217
218
  // Only the refusing boundary selects other rejected inputs; successful values
218
219
  // with the same field names remain operational and exact.
219
220
  const source = [details?.url, details?.ref, ...rejected.map(field => details?.[field])];
220
- const safe = { details: details && Object.fromEntries(Object.entries(details).map(([field, value]) => [field, redactUrl(value, source, { known: false })])) };
221
+ const safe = { details: details && Object.fromEntries(Object.entries(details).map(([field, value]) => [field, displayDiagnosticText(value, source)])) };
221
222
  for (const field of ["url", "ref", ...rejected]) if (details && field in details) {
222
- safe.details[field] = redactUrl(details[field], null, { reference: true, rejectedValue: rejected.includes(field) });
223
+ safe.details[field] = displayRepoRef(details[field], { rejectedValue: rejected.includes(field) });
223
224
  }
224
225
  // Malformed userinfo may already have been split by the parser into host/path.
225
226
  if (code === "E_REPO_REF") for (const field of ["host", "path"]) if (!rejected.includes(field) && details && field in details) {
226
- safe.details[field] = redactUrl(details[field], source, { fragment: true, known: false });
227
+ safe.details[field] = displayDiagnosticText(details[field], source, { fragment: true });
227
228
  }
228
229
  // Refused-input sentences can format the selected display directly. This keeps
229
230
  // a rejected word/key (such as "commit" or "https") from replacing fixed reason
230
231
  // text that happens to contain the same word. The renderer still owns the clause.
231
- safe.message = redactUrl(typeof message === "function" ? message(safe.details) : message, source,
232
- { known: false, refusal: code === "E_REPO_REF", substitute: rejected.length === 0, rejectedValue: rejected.length > 0 });
232
+ safe.message = displayDiagnosticText(typeof message === "function" ? message(safe.details) : message, source,
233
+ { refusal: code === "E_REPO_REF", substitute: rejected.length === 0, rejectedValue: rejected.length > 0 });
233
234
  const e = oatsError(code, safe.message, safe.details);
234
235
  if (details) e.details = safe.details;
235
236
  return e;
@@ -502,7 +503,7 @@ const ANSI_SEQUENCE_RE = /\x1b\[[0-9;?]*[ -\/]*[@-~]/g;
502
503
  export function scrubGitLine(line, url = null) {
503
504
  const original = String(line ?? "");
504
505
  if (!original.trim()) return "";
505
- const text = redactUrl(original, url);
506
+ const text = renderRemoteDisplay(original, url, { known: true });
506
507
  const points = [...text.replace(ANSI_SEQUENCE_RE, "").replace(/\s+/g, " ").replace(REFUSED_TEXT_ALL, "").trim()];
507
508
  return points.length > GIT_LINE_MAX ? `${points.slice(0, GIT_LINE_MAX - 1).join("")}…` : points.join("");
508
509
  }
@@ -527,7 +528,7 @@ export function keychainHint({ platform = process.platform, stdinIsTTY = process
527
528
  }
528
529
 
529
530
  /** A failed git call as E_REMOTE_UNREADABLE, by its reason (classifyRemoteFailure). The message prints the
530
- * url as every message of the cache does, without its user information (redactUrl); `details.url` carries that
531
+ * url as every message of the cache does, without its user information (displayRepoRef); `details.url` carries that
531
532
  * rendered url too. A failure the kernel cannot classify (`unknown`) carries the permitted last Git
532
533
  * line or the renderer's fixed notice (scrubGitLine). With no text, an output over its budget is said,
533
534
  * and otherwise the message ends at the reason. */
@@ -536,7 +537,7 @@ function unreadable(ref, error, extra = {}) {
536
537
  if (reason === "cache") return cacheFailure(ref, error, extra);
537
538
  const hint = keychainHint({ reason });
538
539
  const said = reason === "unknown" ? gitLastLine(error, ref.url) || (error?.overflowed === true ? "git's output exceeded its budget" : "") : "";
539
- return fail("E_REMOTE_UNREADABLE", `cannot read remote ${redactUrl(ref.url, null, { reference: true })} (${reason})${killed ? `: git was killed (signal ${error.signal})` : ""}${said ? `: ${said}` : ""}${hint ? `: ${KEYCHAIN_REMEDY}` : ""}`,
540
+ return fail("E_REMOTE_UNREADABLE", `cannot read remote ${displayRepoRef(ref.url)} (${reason})${killed ? `: git was killed (signal ${error.signal})` : ""}${said ? `: ${said}` : ""}${hint ? `: ${KEYCHAIN_REMEDY}` : ""}`,
540
541
  { url: ref.url, key: ref.key, reason, ...(killed ? { signal: error.signal } : {}), ...(hint ? { hint, remedy: KEYCHAIN_REMEDY } : {}), ...extra });
541
542
  }
542
543
 
@@ -561,7 +562,7 @@ const isLocalWriteFailure = (error) => /cannot open '[^']+': |unable to create t
561
562
  * any other failure carries the permitted Git line or fixed notice. `extra.stage` says which write
562
563
  * (init, pin, config, fetch). */
563
564
  function cacheFailure(ref, error, extra = {}) {
564
- const url = redactUrl(ref.url, null, { reference: true });
565
+ const url = displayRepoRef(ref.url);
565
566
  if (error?.timedOut) return fail("E_REMOTE_UNREADABLE", `cannot write the cache of ${url} (timeout)`, { url: ref.url, key: ref.key, reason: "timeout", ...extra });
566
567
  const where = extra.cacheDir ? ` at ${extra.cacheDir}` : "";
567
568
  const lock = isLockRace(error) ? lockFileOf(error, extra.cacheDir) : null;
@@ -666,7 +667,7 @@ async function withCacheWriteLock(ref, dir, stage, session, fn) {
666
667
  const signal = session?.signal;
667
668
  const lock = cacheWriteLockOf(dir);
668
669
  const owner = { pid: process.pid, token: randomBytes(12).toString("hex"), startedAt: new Date().toISOString() };
669
- const url = redactUrl(ref.url, null, { reference: true });
670
+ const url = displayRepoRef(ref.url);
670
671
  const refuse = (message, extra = {}) => fail("E_REMOTE_UNREADABLE", `cannot write the cache of ${url} at ${dir} (cache, ${stage}): ${message}`,
671
672
  { url: ref.url, key: ref.key, reason: "cache", stage, cacheDir: dir, lock, ...extra });
672
673
  try { mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }); } catch (error) { throw refuse(`cannot create ${dirname(lock)} (${error.code ?? error.message})`); }
@@ -774,7 +775,7 @@ async function cacheGit(repo, args, opts = {}) {
774
775
  catch (error) {
775
776
  const lockFile = isLockRace(error) ? lockFileOf(error, repo.dir) : null;
776
777
  if (!lockFile || !reclaimGitLock(repo, lockFile)) throw error;
777
- repo.session?.notices.push(redactUrl(`removed a stale git lock ${lockFile} (left by a git process that was killed mid-write)`, null, { known: false }));
778
+ repo.session?.notices.push(displayDiagnosticText(`removed a stale git lock ${lockFile} (left by a git process that was killed mid-write)`, null));
778
779
  return await run();
779
780
  }
780
781
  }
@@ -783,14 +784,27 @@ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
783
784
  const cacheRootOf = (options) => options.cacheDir ?? defaultCacheRoot();
784
785
  const cacheDirOf = (root, ref) => join(root, sha256(ref.key));
785
786
 
787
+ /** Display selected repository references or rejected values, including nested keys/values.
788
+ * Pinned context takes the complete `<ref>@<commit>` value and validates both components strictly;
789
+ * `pinned` is true to split that value, or { ref, commit } to supply its original components. */
790
+ export function displayRepoRef(value, { pinned = false, rejectedValue = false } = {}) {
791
+ return renderRemoteDisplay(value, null, { reference: true, known: false, pinned, rejectedValue });
792
+ }
793
+
794
+ /** Display kernel-authored diagnostic text using its original selected source values.
795
+ * Fragments and refusal explanations share the reference constructor; this is never Git prose. */
796
+ export function displayDiagnosticText(value, source = null, { fragment = false, refusal = false, substitute = true, rejectedValue = false } = {}) {
797
+ return renderRemoteDisplay(value, source, { known: false, fragment, refusal, substitute, rejectedValue });
798
+ }
799
+
786
800
  /** Diagnostic display policy. Selected values are constructed from recognised components,
787
801
  * or withheld whole; bounded plain selected values retain their original spelling.
788
802
  * Unvalidated fragments require a plain original source, never a fragment-only check.
789
803
  * Raw parser results and transport never pass through this display-only function.
790
804
  * Untrusted Git prose is displayed only with unchanged operation references and no @.
791
- * Kernel/schema prose explicitly selects known:false and replaces only its source.
805
+ * Kernel/schema prose replaces only its selected source; public entries fix their context.
792
806
  */
793
- export function redactUrl(value, source = null, { reference = false, fragment = false, known = true, refusal = false, substitute = true, rejectedValue = false, pinned = false } = {}) {
807
+ function renderRemoteDisplay(value, source, { reference = false, fragment = false, known, refusal = false, substitute = true, rejectedValue = false, pinned = false }) {
794
808
  const withheld = "[repository reference withheld]";
795
809
  const valueWithheld = "[value withheld]";
796
810
  const valueWithholding = "(the value was withheld)";
@@ -996,7 +1010,7 @@ async function initCacheRepo(ref, dir, exec, session = null) {
996
1010
  try {
997
1011
  try { mkdirSync(tmp, { recursive: true, mode: 0o700 }); } catch (error) { throw failInit(error); }
998
1012
  try { await sessionExec(exec, session, ["init", "-q", "--bare", tmp]); } catch (error) { throw failInit(error); }
999
- try { writeFileSync(join(tmp, "oats-remote.json"), JSON.stringify({ key: ref.key, url: redactUrl(ref.url, null, { reference: true }) }, null, 2) + "\n"); } catch {}
1013
+ try { writeFileSync(join(tmp, "oats-remote.json"), JSON.stringify({ key: ref.key, url: displayRepoRef(ref.url) }, null, 2) + "\n"); } catch {}
1000
1014
  const deadline = Date.now() + HALF_INIT_WAIT_MS;
1001
1015
  for (;;) {
1002
1016
  try { renameSync(tmp, dir); return; } // replaces nothing, or an EMPTY directory
@@ -1240,9 +1254,15 @@ function encodeCacheable(value) {
1240
1254
  }
1241
1255
  /** A URL that may carry a secret: any userinfo on http(s) (a bare token), or a `user:password` userinfo on any
1242
1256
  * scheme. Repo content can hold one (a member ref written with credentials); such a value is never written
1243
- * to the parsed cache. `ssh://git@host/…` (a user, no password) is not a secret. */
1244
- const CREDENTIAL_URL_RE = /\bhttps?:\/\/[^\s"'\/@]+@|\b[a-z][a-z0-9+.-]*:\/\/[^\s"'\/@:]+:[^\s"'\/@]*@/i;
1257
+ * to the parsed cache. `ssh://git@host/…` (a user, no password) is not a secret.
1258
+ * Each alternative finds `://` first and looks behind it for the scheme (#1036): written scheme first, it
1259
+ * read a run of scheme characters once from each word boundary in it, so its time grew with the square of
1260
+ * the run. Now each `://` reads back only its own run and forward only to the next `/`, so the time grows
1261
+ * with the length of the text. test/credential-url-time.test.mjs holds it to the scheme-first form. */
1262
+ const CREDENTIAL_URL_RE = /:\/\/(?<=\bhttps?:\/\/)[^\s"'\/@]+@|:\/\/(?<=\b[a-z][a-z0-9+.-]*:\/\/)[^\s"'\/@:]+:[^\s"'\/@]*@/i;
1245
1263
  function carriesCredential(text) { return CREDENTIAL_URL_RE.test(text); }
1264
+ /** For the tests only: the check, outside the parsed cache. */
1265
+ export { carriesCredential as carriesCredentialForTests };
1246
1266
  function reviveCached(data, nullProto) {
1247
1267
  if (!nullProto.length) return data;
1248
1268
  const wanted = new Set(nullProto);
@@ -1268,11 +1288,10 @@ function writeAtomicQuiet(file, text) {
1268
1288
  const tmp = join(dir, `.${file.slice(dir.length + 1)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
1269
1289
  try {
1270
1290
  mkdirSync(dir, { recursive: true, mode: 0o700 });
1271
- writeFileSync(tmp, text, { mode: 0o600 });
1272
- renameSync(tmp, file);
1291
+ // A failed write or rename removes the private file (#1076).
1292
+ writeThroughPrivateFile(file, tmp, text, 0o600);
1273
1293
  return true;
1274
1294
  } catch {
1275
- try { rmSync(tmp, { force: true }); } catch { /* nothing */ }
1276
1295
  return false;
1277
1296
  }
1278
1297
  }
@@ -1478,7 +1497,7 @@ async function ensureCommit(ref, oid, options) {
1478
1497
  if (!commit) {
1479
1498
  // The peel answered: the object is missing or not a commit (a peel the deadline ended was thrown above).
1480
1499
  const type = await asReadTimeout(repo, objectType(repo, oid));
1481
- throw fail("E_REMOTE_UNREADABLE", `${oid} in ${redactUrl(ref.url, null, { reference: true })} is ${type ? `a ${type}` : "missing"}, not a commit`, { url: ref.url, key: ref.key, reason: "not-found", commit: oid, type });
1500
+ throw fail("E_REMOTE_UNREADABLE", `${oid} in ${displayRepoRef(ref.url)} is ${type ? `a ${type}` : "missing"}, not a commit`, { url: ref.url, key: ref.key, reason: "not-found", commit: oid, type });
1482
1501
  }
1483
1502
  await writePin(repo, ref, pinRef(commit), commit, commit);
1484
1503
  if (commit !== oid) await writePin(repo, ref, `refs/oats/tags/${oid}`, oid, commit);
@@ -1551,49 +1570,67 @@ async function writeConfig(repo, ref, key, value) {
1551
1570
 
1552
1571
  /** This cache fetches whole trees from now on (its server cannot serve partial fetches, or this git cannot keep
1553
1572
  * a partial cache): recorded, and said once (the session's notices; the CLI prints them when the command ends). */
1554
- async function recordFullFetches(repo, ref, notice = `${redactUrl(ref.url, null, { reference: true })} does not serve partial fetches; OATS fetches whole trees from it`) {
1573
+ async function recordFullFetches(repo, ref, notice = `${displayRepoRef(ref.url)} does not serve partial fetches; OATS fetches whole trees from it`) {
1555
1574
  await writeConfig(repo, ref, "oats.fetch", "full");
1556
- repo.session?.notices.push(redactUrl(notice, ref.url, { known: false }));
1575
+ repo.session?.notices.push(displayDiagnosticText(notice, ref.url));
1557
1576
  return "full";
1558
1577
  }
1559
1578
 
1560
1579
  const olderGitNotice = (version, ref) =>
1561
- `git ${version?.text ?? "(unknown version)"} cannot keep a partial cache (it needs ${PARTIAL_FETCH_GIT.join(".")}); OATS fetches whole trees from ${redactUrl(ref.url, null, { reference: true })}`;
1580
+ `git ${version?.text ?? "(unknown version)"} cannot keep a partial cache (it needs ${PARTIAL_FETCH_GIT.join(".")}); OATS fetches whole trees from ${displayRepoRef(ref.url)}`;
1562
1581
 
1563
- /** `git --version` of the git `exec` runs, asked once per exec: → { text: "2.54.0", major, minor } | null.
1564
- * `opts` (a timeout, a signal) go to the call that asks. A call that timed out says nothing about this git:
1565
- * it answers null to its waiters and is asked again next time. */
1582
+ /** One strict probe per exec: share in-flight work and retain only parsed success. A failed or abandoned
1583
+ * probe cannot authorize rebuilding a cache, nor erase a newer probe installed by a retry. */
1566
1584
  const gitVersions = new WeakMap();
1567
- export function gitVersion(exec = runGit, opts = undefined) {
1585
+ async function probeGitVersion(exec, opts = undefined) {
1586
+ if (opts?.signal?.aborted) throw abortError(opts.signal);
1568
1587
  let version = gitVersions.get(exec);
1588
+ const forget = () => { if (gitVersions.get(exec) === version) gitVersions.delete(exec); };
1569
1589
  if (!version) {
1570
1590
  version = Promise.resolve().then(() => exec(["--version"], ...(opts ? [opts] : []))).then((out) => {
1571
1591
  const m = /git version ((\d+)\.(\d+)[^\s]*)/.exec(out.stdout.toString("utf8"));
1572
- return m ? { text: m[1], major: Number(m[2]), minor: Number(m[3]) } : null;
1573
- }, (error) => {
1574
- if (error?.timedOut && gitVersions.get(exec) === version) gitVersions.delete(exec);
1575
- return null;
1576
- });
1592
+ if (!m) throw new Error("Git version could not be parsed");
1593
+ return { text: m[1], major: Number(m[2]), minor: Number(m[3]) };
1594
+ }).catch((error) => { forget(); throw error; });
1577
1595
  gitVersions.set(exec, version);
1578
1596
  }
1579
- return version;
1597
+ // The launching caller supplies exec's timeout/signal: a failure there reaches every remaining waiter.
1598
+ // Each waiter can also leave earlier on its own bound/cancellation, forgetting only this probe;
1599
+ // other waiters still receive its original outcome.
1600
+ let timer, onAbort;
1601
+ const stopped = new Promise((resolve, reject) => {
1602
+ const timeout = opts?.timeout ?? GIT_TIMEOUT_MS;
1603
+ if (timeout > 0) timer = setTimeout(() => reject(deadlineError(["--version"])), timeout);
1604
+ if (opts?.signal) {
1605
+ onAbort = () => reject(abortError(opts.signal));
1606
+ opts.signal.addEventListener("abort", onAbort, { once: true });
1607
+ }
1608
+ });
1609
+ try { return await Promise.race([version, stopped]); }
1610
+ catch (error) { forget(); throw error; }
1611
+ finally {
1612
+ clearTimeout(timer);
1613
+ if (onAbort) opts.signal.removeEventListener("abort", onAbort);
1614
+ }
1615
+ }
1616
+
1617
+ /** Compatibility helper: parsed git version { text, major, minor }, or null on any failed probe/wait.
1618
+ * Failures are never memoized. Operational cache decisions use the strict probe instead. */
1619
+ export function gitVersion(exec = runGit, opts = undefined) {
1620
+ return probeGitVersion(exec, opts).catch(() => null);
1580
1621
  }
1581
- /** gitVersion for a read of `ref` in `repo`'s session. Under a deadline the probe gets what is left of it, and
1582
- * is waited for no longer (another caller may own the probe): a version the deadline left unknown is the
1583
- * read's timeout, never taken for an older git (which would rebuild a partial cache). */
1622
+
1623
+ /** A read keeps the probe's failure facts, including a timeout before its session's deadline. Unknown
1624
+ * versions never reach the old-git rebuild decision. Each waiter uses its own session's remaining time. */
1584
1625
  async function readVersion(repo, ref) {
1585
1626
  const session = repo.session;
1586
- if (session?.deadline == null) return gitVersion(repo.exec);
1587
- const ended = () => unreadable(ref, deadlineError(["--version"]), { cacheDir: repo.dir, stage: "fetch" });
1588
- const left = session.remaining(GIT_TIMEOUT_MS);
1589
- if (left <= 0) throw ended();
1590
- let timer;
1591
- const late = new Promise((resolvePromise) => { timer = setTimeout(() => resolvePromise(ended), left); });
1592
1627
  try {
1593
- const version = await Promise.race([gitVersion(repo.exec, { timeout: left, signal: session.signal }), late]);
1594
- if (version === ended || (version === null && session.expired())) throw ended();
1595
- return version;
1596
- } finally { clearTimeout(timer); }
1628
+ const timeout = session?.remaining(GIT_TIMEOUT_MS) ?? GIT_TIMEOUT_MS;
1629
+ if (timeout <= 0) throw deadlineError(["--version"]);
1630
+ return await probeGitVersion(repo.exec, { timeout, signal: session?.signal });
1631
+ } catch (error) {
1632
+ throw unreadable(ref, error, { cacheDir: repo.dir, stage: "fetch" });
1633
+ }
1597
1634
  }
1598
1635
  /** Whether this git keeps a partial cache honest (GIT_NO_LAZY_FETCH): an unknown version does not. */
1599
1636
  export function keepsPartialCache(version) {
@@ -1715,7 +1752,7 @@ async function fetchInto(repo, ref, args, { what, commit, input, raw = false } =
1715
1752
  catch (error) { lastError = error; }
1716
1753
  if (lastError?.timedOut) {
1717
1754
  const elapsedMs = Date.now() - started;
1718
- throw fail("E_REMOTE_UNREADABLE", `cannot read remote ${redactUrl(ref.url, null, { reference: true })} (timeout): git fetch of ${what} timed out after ${Math.round(elapsedMs / 1000)} s`,
1755
+ throw fail("E_REMOTE_UNREADABLE", `cannot read remote ${displayRepoRef(ref.url)} (timeout): git fetch of ${what} timed out after ${Math.round(elapsedMs / 1000)} s`,
1719
1756
  { url: ref.url, key: ref.key, reason: "timeout", commit, operation: "fetch", elapsedMs });
1720
1757
  }
1721
1758
  throw raw ? lastError : fetchFailure(repo, ref, lastError, commit);
@@ -1769,7 +1806,7 @@ async function ensureBlobs(repo, ref, commit, entries) {
1769
1806
  }
1770
1807
  sizes = await blobSizes(repo, oids);
1771
1808
  const still = oids.find((o) => sizes.get(o) === null);
1772
- if (still) throw fail("E_REMOTE_UNREADABLE", `cannot read remote ${redactUrl(ref.url, null, { reference: true })} (not-found): blob ${still} at ${commit} was not fetched`, { url: ref.url, key: ref.key, reason: "not-found", commit, oid: still });
1809
+ if (still) throw fail("E_REMOTE_UNREADABLE", `cannot read remote ${displayRepoRef(ref.url)} (not-found): blob ${still} at ${commit} was not fetched`, { url: ref.url, key: ref.key, reason: "not-found", commit, oid: still });
1773
1810
  });
1774
1811
  for (const e of unknown) e.size = sizes.get(e.oid);
1775
1812
  });
@@ -1992,7 +2029,7 @@ async function observeLive(ref, args, at, options) {
1992
2029
  const run = (argv, extra = {}) => sessionExec(exec, session, argv, { timeout: GIT_TIMEOUT_MS, ...(signal ? { signal } : {}), ...extra });
1993
2030
  const root = cacheRootOf(options);
1994
2031
  const now = () => (session ? session.now() : Date.now());
1995
- const url = redactUrl(ref.url, null, { reference: true });
2032
+ const url = displayRepoRef(ref.url);
1996
2033
  const say = (notice) => { if (session && !session.notices.includes(notice)) session.notices.push(notice); };
1997
2034
  let out = null, retried = null;
1998
2035
  const v0 = isHeadAt(at) && !lsRemoteV2Recorded(root, ref, now()) && !(await protocolPinned(exec, session));
@@ -2026,8 +2063,8 @@ async function observeLive(ref, args, at, options) {
2026
2063
  }
2027
2064
  const parsed = parseLsRemote(out.stdout);
2028
2065
  const hit = resolveAt(parsed, at);
2029
- if (!hit) throw fail("E_REMOTE_UNREADABLE", `remote ${redactUrl(ref.url, null, { reference: true })} has no ref matching ${at ?? "HEAD"}`, { url: ref.url, key: ref.key, reason: "not-found", at: at ?? null });
2030
- if (!OID_RE.test(hit.commit)) throw fail("E_REMOTE_UNREADABLE", `remote ${redactUrl(ref.url, null, { reference: true })} returned a non-OID for ${at ?? "HEAD"}`, { url: ref.url, key: ref.key, reason: "not-found", at: at ?? null });
2066
+ if (!hit) throw fail("E_REMOTE_UNREADABLE", `remote ${displayRepoRef(ref.url)} has no ref matching ${at ?? "HEAD"}`, { url: ref.url, key: ref.key, reason: "not-found", at: at ?? null });
2067
+ if (!OID_RE.test(hit.commit)) throw fail("E_REMOTE_UNREADABLE", `remote ${displayRepoRef(ref.url)} returned a non-OID for ${at ?? "HEAD"}`, { url: ref.url, key: ref.key, reason: "not-found", at: at ?? null });
2031
2068
  const { commit } = await ensureCommit(ref, hit.commit, options);
2032
2069
  if (retried) say(`${url} failed under protocol v0 (${retried}); observed with protocol v2`);
2033
2070
  return { key: ref.key, url: ref.url, commit, ref: hit.ref, observedAt: new Date().toISOString() };