@awebai/oats 0.55.1 → 0.56.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 (78) hide show
  1. package/bin/oats.mjs +78 -62
  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 +317 -35
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +54 -7
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +54 -7
  10. package/docs/integrations.md +1 -1
  11. package/docs/knowledge.md +35 -16
  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/servers.md +21 -5
  17. package/docs/souls-and-instances.md +8 -4
  18. package/docs/tui.md +99 -26
  19. package/docs/upgrading.md +4 -1
  20. package/docs/workspaces.md +26 -6
  21. package/lib/automations.mjs +3 -4
  22. package/lib/bounded-read.mjs +18 -0
  23. package/lib/capability-show.mjs +13 -2
  24. package/lib/claim.mjs +3 -4
  25. package/lib/core.mjs +480 -152
  26. package/lib/errors.mjs +39 -0
  27. package/lib/harness-trust-write.mjs +119 -40
  28. package/lib/harness-trust.mjs +31 -18
  29. package/lib/instance-inspect.mjs +160 -11
  30. package/lib/instance-lifecycle.mjs +47 -30
  31. package/lib/packages.mjs +8 -5
  32. package/lib/pi-bridge.mjs +18 -19
  33. package/lib/remote.mjs +88 -51
  34. package/lib/retire-output.mjs +9 -4
  35. package/lib/schedule.mjs +3 -4
  36. package/lib/servers.mjs +39 -6
  37. package/lib/session-viewer.mjs +25 -1
  38. package/lib/triggers.mjs +3 -4
  39. package/lib/workspace.mjs +6 -6
  40. package/lib/worktree.mjs +10 -6
  41. package/lib/write-through-private-file.mjs +26 -0
  42. package/package-catalog.json +2 -2
  43. package/package.json +1 -1
  44. package/packages/client/cli-adapter.mjs +108 -13
  45. package/packages/client/cli-locator.mjs +16 -14
  46. package/packages/client/deployment-panel.mjs +4 -3
  47. package/packages/client/display-text.mjs +2 -1
  48. package/packages/client/instance-events-contract.mjs +4 -3
  49. package/packages/client/instance-lifecycle.mjs +228 -0
  50. package/packages/client/instance-presentation.mjs +9 -0
  51. package/packages/client/instance-tree.mjs +10 -8
  52. package/packages/client/kernel-lines.mjs +3 -3
  53. package/packages/client/launch-contract.mjs +11 -0
  54. package/packages/client/lifecycle-cli.mjs +12 -6
  55. package/packages/client/lifecycle-confirmation.mjs +407 -0
  56. package/packages/client/lifecycle-contract.mjs +6 -2
  57. package/packages/client/own-codes.mjs +1 -0
  58. package/packages/client/panel-views.mjs +39 -2
  59. package/packages/client/readiness-contract.mjs +2 -2
  60. package/packages/client/remote-roster.mjs +50 -5
  61. package/packages/client/roster-sections.mjs +3 -3
  62. package/packages/client/session-start.mjs +98 -0
  63. package/packages/client/start-gate.mjs +46 -0
  64. package/packages/client/start-messages.mjs +17 -0
  65. package/packages/client/workspace-views.mjs +2 -2
  66. package/packages/tui/README.md +10 -6
  67. package/packages/tui/lib/actions.mjs +4 -2
  68. package/packages/tui/lib/client.mjs +5 -2
  69. package/packages/tui/lib/config.mjs +39 -9
  70. package/packages/tui/lib/main.mjs +83 -13
  71. package/packages/tui/lib/model.mjs +116 -11
  72. package/packages/tui/lib/open.mjs +45 -0
  73. package/packages/tui/lib/read.mjs +46 -10
  74. package/packages/tui/lib/store.mjs +64 -9
  75. package/packages/tui/lib/term/tty.mjs +71 -12
  76. package/packages/tui/lib/views/frame.mjs +115 -33
  77. package/packages/tui/lib/views/help.mjs +37 -8
  78. 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}$/;
@@ -295,19 +296,13 @@ export function applyStop(ctx, root, name, { home, recursive = true, planRevisio
295
296
  }
296
297
  }
297
298
 
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. */
299
+ /** Write `value` as JSON at `path` through a private file beside it (`<path>.<pid>.tmp`), renamed
300
+ * over it, by the kernel's one such writer (lib/write-through-private-file.mjs): when the write or
301
+ * the rename fails the private file is removed and the error thrown is that failure's
302
+ * (awebai/oats#963, #1076). Exported for its test alone (test/stop-private-files.test.mjs): its one
303
+ * caller keeps the error to itself, so nothing but a call of it shows what it throws. */
303
304
  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
- }
305
+ writeThroughPrivateFile(path, `${path}.${process.pid}.tmp`, JSON.stringify(value, null, 2));
311
306
  }
312
307
 
313
308
  /** The sentence a stop's text closes with, chosen from the receipt's rows as a client reads them
@@ -448,26 +443,48 @@ export function planRetire(ctx, root, name, { home } = {}) {
448
443
  const defaults = { retainWorktree: ownTree, deleteBranch: false, stopChildren: true, retainChildren: true };
449
444
  // The repository the retire would read from Git for an own tree whose record names none.
450
445
  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
446
  // Attached children whose work is this home's work/ (#718): a retire that keeps the worktree
469
447
  // repoints them to it. One note holds whatever the dialog then picks.
470
448
  const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, me.home) !== null) : [];
449
+ // The session as the plan shows it, whole: its state, and the reason or the note of one that is
450
+ // not established, which the record's launch and endpoint fields decide (awebai/oats#1065). The
451
+ // children as the plan names them (a child's agent is the name its soul's file gives, which its
452
+ // home's path does not hold), and with them what the plan shows of other homes' records: the edges
453
+ // it could not follow (facts.ambiguous, whole: each edge's reason counts the homes of the name)
454
+ // and the children attached to this work (a note). Where Git gives no answer for work/, the
455
+ // reason the plan shows for that (facts.work.reason): nothing at work/ and a file there are one
456
+ // answer of the reading under a record that says `worktree`, and two plans. Where Git answers,
457
+ // what the plan shows of the tree that does not move by itself: the commit, the branch and
458
+ // whether HEAD is detached, whether that branch is not the record's (drift, as shown: it comes
459
+ // from a second read of the record, after this plan's, in observeInstanceGit, so it is not
460
+ // derived from facts.recordedBranch), the counts of changed and untracked files, and what
461
+ // the clone's configuration names (the branch's upstream, the remote's host and path). Left
462
+ // out, because a fetch by anyone who shares the clone moves it: the counts against the upstream
463
+ // and the default branch, and the default branch's name (a fetch creates a missing origin/HEAD).
464
+ // docs/desktop-cli-api.md names what is left out, and why.
465
+ 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 };
466
+ // What retire would preserve and where, read from the spawn baseline and the work mode. A plan
467
+ // hashes no file for it. The declared roots are listed in a note as written, bounded so one
468
+ // note stays short, and are part of the plan's revision (awebai/oats#1065).
469
+ const recovery = retirementRecoveryFacts(me.home);
470
+ const safety = [me.home, target.session, target.launched, tree, kids.map((c) => [c.instance, c.agent, c.home]),
471
+ { ambiguous: facts.ambiguous, attached: attached.map((c) => c.home) },
472
+ // The home's extra trees, when there are any.
473
+ ...(extraWorktrees.length ? [extraWorktrees] : []),
474
+ // What the plan reports of the record about work/ (its work mode, its repository, its branch),
475
+ // which the instance can write, and what work/ is by the reading the retire makes too (#962,
476
+ // #973), with the repository Git names for work/ wherever it is a registered work tree: all
477
+ // of it is part of every retire plan's revision, in every home (awebai/oats#1065). So no two
478
+ // plans of one home that the record or the reading makes different, in a fact, a default, a
479
+ // note or the text's line, share a revision, and a guarded apply refuses as stale when one of
480
+ // them moved since the plan was shown. Unconditional: no home, no value of the record and no
481
+ // answer of the reading is left out. A field of the record that a plan comes to show joins
482
+ // this binding (test/retire-plan-revision.test.mjs rewrites each in turn).
483
+ { mode: facts.workMode, repo: facts.repo, branch: facts.recordedBranch, work: workIs.is, tree: workIs.tree?.repo ?? null },
484
+ // Where a recovery would be written and the declared roots it leaves out, as the spawn's
485
+ // receipt gives them: the roots with their owners, not the note made from them, which is
486
+ // shortened past its budget and then reads alike for two lists of one length.
487
+ recovery];
471
488
  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
489
  const plan = { lifecycleApi: LIFECYCLE_API, action: "retire", instance: name, home: me.home, at: new Date().toISOString(), facts, defaults, planRevision: planRevision(safety),
473
490
  notes: boundedNotes(extraWorktrees.map(extraWorktreeNote), [
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() };
@@ -3,7 +3,12 @@
3
3
  * receipt's `workRecovery` (lib/core.mjs, retireInstance); another renders
4
4
  * its `extraWorktrees`. A receipt from an
5
5
  * older kernel, or a stored one, may carry `workRecoveries[]` instead: one
6
- * block is printed per entry. A third renders its `warnings`. Dependency-free. */
6
+ * block is printed per entry. A third renders its `warnings`. Their lines hold
7
+ * text the kernel did not write (paths as the system or Git names them, a
8
+ * hook's words, the names a capability declares), so each line goes to the
9
+ * terminal through terminalText (lib/refused-text.mjs): a name cannot clear the
10
+ * screen or write a line of its own. The receipt's JSON is never passed
11
+ * through it. Dependency-free. */
7
12
  import { terminalText } from "./refused-text.mjs";
8
13
 
9
14
  export const formatBytes = (n) => n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`;
@@ -53,7 +58,7 @@ export function workRecoveryLines(receipt, { host } = {}) {
53
58
  if (again.length) lines.push(` after the retire hooks: ${again.join(" and ")} copied again under after-hooks/`);
54
59
  }
55
60
  if (lines.length) lines.push(RECOVERY_POINTER);
56
- return lines;
61
+ return lines.map((line) => terminalText(line));
57
62
  }
58
63
 
59
64
  /** The lines `oats retire` prints for the home's extra trees it handled
@@ -62,9 +67,9 @@ export function extraWorktreeLines(receipt, { host } = {}) {
62
67
  const rows = Array.isArray(receipt?.extraWorktrees) ? receipt.extraWorktrees : [];
63
68
  return rows.map((t) => {
64
69
  const at = t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt}` : "a HEAD that could not be read";
65
- return t.outcome === "removed"
70
+ return terminalText(t.outcome === "removed"
66
71
  ? `Extra worktree ${t.path} removed (${at}); its branch and commits stay in ${t.repo}${host ? ` on ${host}` : ""}`
67
- : `Extra worktree ${t.path} re-homed${host ? ` on ${host}` : ""} to ${t.movedTo} (${at}): ${t.reason}`;
72
+ : `Extra worktree ${t.path} re-homed${host ? ` on ${host}` : ""} to ${t.movedTo} (${at}): ${t.reason}`);
68
73
  });
69
74
  }
70
75
 
package/lib/schedule.mjs CHANGED
@@ -22,7 +22,7 @@
22
22
  * `unknown`, its job blocked until `reconcile` proves what happened; it keeps
23
23
  * its host slot too, unless it is a command whose process exit was observed. */
24
24
  import { runScheduleCommand } from "./schedule-command.mjs";
25
- import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
25
+ import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
26
26
  import { createHash } from "node:crypto";
27
27
  import { homedir } from "node:os";
28
28
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
@@ -36,6 +36,7 @@ import { pollSourced, tickTriggers } from "./triggers.mjs";
36
36
  import { resolveMemberClone } from "./instance-resolution.mjs";
37
37
  import { SCHEDULE_NAME_RE, HOST_NAME_RE, readSnapshot, hostOf, trusted, parseOwner, MODEL_RE, automationContext, automationError, baseRow, localEntry, localId, soulOriginOf, splitId, validateDescription } from "./automations.mjs";
38
38
  import { RESERVED_LAUNCH_ENV, MAX_INSTANCE_NAME, shq, shellWord, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, sessionServerGone, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
39
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
39
40
 
40
41
  export const SCHEDULE_FILE = "oats-schedules.json";
41
42
  export const SCHEDULE_API = 2;
@@ -142,9 +143,7 @@ function readJsonBounded(path, fallback, label, { atomicReplace = false } = {})
142
143
  function readJson(path, fallback) { return readJsonBounded(path, fallback, basename(path)).value; }
143
144
  function writeJson(path, value) {
144
145
  mkdirSync(dirname(path), { recursive: true });
145
- const tmp = `${path}.tmp-${process.pid}`;
146
- writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n");
147
- renameSync(tmp, path);
146
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, JSON.stringify(value, null, 2) + "\n");
148
147
  }
149
148
  export function readDefinitions(ws) {
150
149
  const doc = readJsonBounded(definitionsPath(ws), { version: 1, jobs: {} }, "definitions").value;