@awebai/oats 0.51.0 → 0.53.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 (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
package/lib/remote.mjs CHANGED
@@ -13,8 +13,12 @@
13
13
  * commit locally. `ensureCommit` does a shallow, partial
14
14
  * `git fetch --depth 1 --no-tags --filter=blob:limit=64k origin <oid>` into a
15
15
  * content-addressed BARE cache repo under `<cacheRoot>/<sha256(key)>/` and then
16
- * pins the commit with `refs/oats/commits/<oid>` so `gc` cannot prune it (the
17
- * pins are also what a later fetch advertises as `have`, so it is incremental).
16
+ * pins the commit with `refs/oats/commits/<oid>` so `gc` cannot prune it. The
17
+ * pins are also what a later fetch advertises as `have`, so it is incremental:
18
+ * a new head beside the last one arrives in a few kilobytes. An incremental pack
19
+ * may refer to a blob the filter left out of the cache, and git then cannot
20
+ * complete it; that fetch is made once more without negotiation, which brings
21
+ * the commit whole (fetchCommit, awebai/oats#1059).
18
22
  * The commit arrives with ALL its trees (every listing is complete) and the blobs
19
23
  * up to SMALL_BLOB_LIMIT: every file discovery reads, in one round trip.
20
24
  * 3. Reads are then local plumbing: `git ls-tree -r -t -l -z` for listing and
@@ -66,6 +70,12 @@
66
70
  * `error.overflowed`. A listing failure git does not explain is never a raw
67
71
  * Node error escaping this module: it is E_REMOTE_UNREADABLE { reason: "unknown" }.
68
72
  *
73
+ * UNKNOWN vs NETWORK (awebai/oats#1059): a failed git call whose text shows nothing the
74
+ * kernel recognises is `unknown`, never `network`: `network` is what the text shows to
75
+ * be the network (classifyText). The message of an `unknown` failure carries git's own
76
+ * line (the last for a remote call, the first for a listing) through one scrub
77
+ * (scrubGitLine): one line, bounded, no control characters, no url's user information.
78
+ *
69
79
  * TREE SAFETY: every entry name git reports is validated BEFORE anything touches
70
80
  * the disk. A component that is empty, `.`, `..`, `.git` (any case) or contains
71
81
  * `\` / NUL is E_REMOTE_TREE_UNSAFE { why: "path" } — a crafted tree object can
@@ -83,8 +93,12 @@
83
93
  * kernel's live write (retried briefly) or to a git that was killed: one older than the
84
94
  * longest fetch, inside the cache and a regular file, is removed (a session notice says
85
95
  * so) and the write made once more; any other is E_REMOTE_UNREADABLE { reason: "cache" }
86
- * naming it. git is ended with SIGTERM first (it removes its own locks), SIGKILL after a
87
- * grace unless its group is seen empty first (process-group.mjs terminateGroup, watchGroup).
96
+ * naming it. Every fetch first removes the temporary files of the object store that are
97
+ * older than the longest fetch (a failed fetch's pack, which git does not remove), and
98
+ * no younger one: it may be another git's (removeStaleTemporaryFiles; temporaryStaleMs
99
+ * says what the longest fetch is). git is ended with
100
+ * SIGTERM first (it removes its own locks), SIGKILL after a grace unless its
101
+ * group is seen empty first (process-group.mjs terminateGroup, watchGroup).
88
102
  *
89
103
  * CACHE PIN vs OBJECTS: the pin ref is the fast-path marker, but a wiped or
90
104
  * pruned object store is detected (`rev-parse <oid>^{commit}`) and refetched;
@@ -156,6 +170,7 @@ import { homedir } from "node:os";
156
170
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
157
171
  import { fileURLToPath } from "node:url";
158
172
  import { oatsError } from "./errors.mjs";
173
+ import { REFUSED_TEXT } from "./refused-text.mjs";
159
174
  import { killGroup, signalGroup, terminateGroup, watchGroup } from "./process-group.mjs";
160
175
 
161
176
  export const FILE_BUDGET = 4 * 1024 * 1024; // readRemoteFile: 4 MiB per file
@@ -417,30 +432,84 @@ function stderrText(error) {
417
432
  return Buffer.isBuffer(s) ? s.toString("utf8") : typeof s === "string" ? s : String(error?.message ?? "");
418
433
  }
419
434
 
420
- /** Classify a failed network git call into the contract's reasons. A `maxBuffer`
421
- * overflow is never a timeout (the child is killed in both cases; only the timeout kill
422
- * counts) — it falls through to the stderr text, else "network". A timeout is our own
423
- * timer's kill (`timedOut`), whatever signal it sent. A git lock still held by another
424
- * process (a lost race that outlived retryLockRace, or a dead process's stale lock) is
425
- * "cache": a local cache write failed, nothing about the remote. Any other signal exit is
426
- * "killed" (the system killed git, e.g. out of memory). */
435
+ /** Classify a failed git call into the contract's reasons. A `maxBuffer` overflow is never
436
+ * a timeout (the child is killed in both cases; only the timeout kill counts): it is what
437
+ * its stderr text shows. A timeout is our own timer's kill (`timedOut`), whatever signal it
438
+ * sent. A git lock still held by another process (a lost race that outlived retryLockRace,
439
+ * or a dead process's stale lock) is "cache": a local cache write failed, nothing about the
440
+ * remote. Any other signal exit is "killed" (the system killed git, e.g. out of memory).
441
+ * Otherwise the text decides, and a text that shows nothing the kernel recognises is
442
+ * "unknown" (awebai/oats#1059): "network" is only what the text shows to be the network. */
427
443
  export function classifyRemoteFailure(error) {
428
- if (error?.overflowed === true || error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return classifyText(error) ?? "network";
444
+ if (error?.overflowed === true || error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return classifyText(error) ?? "unknown";
429
445
  if (error?.timedOut) return "timeout";
430
446
  if (isLockRace(error) || isLocalWriteFailure(error)) return "cache";
431
447
  if (typeof error?.signal === "string" && error.signal) return "killed";
432
- return classifyText(error) ?? "network";
448
+ return classifyText(error) ?? "unknown";
433
449
  }
434
450
 
435
- /** The stderr-text half of classifyRemoteFailure; null when the text says nothing recognisable. */
451
+ /** An object id as git prints it (SHA-1 or SHA-256). */
452
+ const OBJECT_ID_RE = /\b[0-9a-f]{40}(?:[0-9a-f]{24})?\b/g;
453
+ /** The stderr-text half of classifyRemoteFailure; null when the text says nothing recognisable. The object
454
+ * ids git names are taken out first: an id is evidence of nothing, and one that holds `403` must not read
455
+ * as a refusal of the operator's credentials. The network texts are git's own and its transports' (libcurl's
456
+ * come after git's "unable to access"; ssh's and getaddrinfo's are named). */
436
457
  function classifyText(error) {
437
- const text = stderrText(error).toLowerCase();
458
+ const text = stderrText(error).toLowerCase().replace(OBJECT_ID_RE, "");
438
459
  if (/authentication failed|could not read username|could not read password|permission denied|publickey|403|forbidden|terminal prompts disabled|invalid username or password|access denied|unauthori[sz]ed/.test(text)) return "auth";
439
460
  if (/repository not found|repository '.*' not found|not found|does not appear to be a git repository|no such file or directory|not our ref|unadvertised object|couldn't find remote ref|remote ref .* not found|not a valid object name|not a tree object|bad object|is not a valid revision|no such ref/.test(text)) return "not-found";
440
- if (/could not resolve host|connection refused|connection timed out|network is unreachable|unable to access|early eof|remote end hung up|connection reset|ssl|tls|unable to connect/.test(text)) return "network";
461
+ if (/could not resolve host|could not resolve proxy|name or service not known|temporary failure in name resolution|connection refused|connection timed out|operation timed out|network is unreachable|no route to host|unable to access|early eof|remote end hung up|unexpected disconnect|connection reset|connection closed by|ssl|tls|unable to connect|failed to connect/.test(text)) return "network";
441
462
  return null;
442
463
  }
443
464
 
465
+ /** How much of one line of git's is printed in a message. */
466
+ export const GIT_LINE_MAX = 300;
467
+ const REFUSED_TEXT_ALL = new RegExp(REFUSED_TEXT.source, "gu");
468
+ /** A terminal's control sequence (a colour, a cursor move), which goes whole and not only its escape character. */
469
+ const ANSI_SEQUENCE_RE = /\x1b\[[0-9;?]*[ -\/]*[@-~]/g;
470
+ /** The user information of a url, wherever a text holds one: `scheme://user:secret@host` → `scheme://host`. */
471
+ const URL_USERINFO_RE = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s\/]*@/gi;
472
+ /**
473
+ * What a line about the fetch of `url` must not repeat, by the module's own rule of a url that carries a
474
+ * secret (CREDENTIAL_URL_RE): the user information, as written and decoded, and with it
475
+ * - on http(s), each of its parts: there the user alone is a secret (a forge token is put in a url as
476
+ * `https://<token>@host`, or as the user before a fixed password), so the whole of it goes whether or
477
+ * not it holds a colon;
478
+ * - on another scheme, its password alone, and nothing where it holds no colon: a user name alone
479
+ * (`ssh://git@host`) is no secret and stays.
480
+ * The longest first, so that no part of a secret is left by removing a shorter one inside it. The cost of
481
+ * removing each part: a user that is a common word goes from git's line wherever the line repeats it, and a
482
+ * mangled line is better than a printed token.
483
+ */
484
+ function urlSecrets(url) {
485
+ const m = typeof url === "string" ? /^([a-z][a-z0-9+.-]*):\/\/([^\s\/]*)@/i.exec(url) : null;
486
+ if (!m) return [];
487
+ const http = /^https?$/i.test(m[1]), info = m[2], colon = info.indexOf(":");
488
+ if (colon < 0 && !http) return [];
489
+ const parts = colon < 0 ? [] : http ? [info.slice(0, colon), info.slice(colon + 1)] : [info.slice(colon + 1)];
490
+ const forms = (text) => { try { return [text, decodeURIComponent(text)]; } catch { return [text]; } };
491
+ return [...new Set([info, ...parts].flatMap(forms))].filter(Boolean).sort((a, b) => b.length - a.length);
492
+ }
493
+ /**
494
+ * One line of git's own words, made fit to print in a message (a failure message is an output channel:
495
+ * the fetch url is on git's command line, may carry credentials, and git or its transport can echo it).
496
+ * The user information of every url in it is removed, and that of `url` (the fetch url) wherever it
497
+ * appears; a terminal's control sequences, control characters and the other characters the kernel never
498
+ * prints (lib/refused-text.mjs) are removed, runs of white space become one space, and the line is cut to
499
+ * GIT_LINE_MAX characters. "" when nothing is left.
500
+ */
501
+ export function scrubGitLine(line, url = null) {
502
+ let text = String(line ?? "").replace(URL_USERINFO_RE, "$1");
503
+ for (const secret of urlSecrets(url)) text = text.split(secret).join("");
504
+ const points = [...text.replace(ANSI_SEQUENCE_RE, "").replace(/\s+/g, " ").replace(REFUSED_TEXT_ALL, "").trim()];
505
+ return points.length > GIT_LINE_MAX ? `${points.slice(0, GIT_LINE_MAX - 1).join("")}…` : points.join("");
506
+ }
507
+ /** The last line git wrote that says anything (a progress line ends with a carriage return), scrubbed. */
508
+ function gitLastLine(error, url) {
509
+ const lines = stderrText(error).split(/[\r\n]+/).map((line) => scrubGitLine(line, url)).filter(Boolean);
510
+ return lines.length ? lines[lines.length - 1] : "";
511
+ }
512
+
444
513
  /** What to do when git on a macOS host cannot reach its keychain: the credentials git uses must live
445
514
  * somewhere a session without a terminal can read. */
446
515
  export const KEYCHAIN_REMEDY = "on macOS a session without a terminal (an ssh command, a background job) cannot open the login keychain where git's credential helper keeps the forge token; store git credentials outside the keychain (`gh auth login --insecure-storage`, then `gh auth setup-git`), or use an SSH key the session can reach: one without a passphrase, or the desktop login's ssh-agent (point SSH_AUTH_SOCK at it in the shell's startup file)";
@@ -453,11 +522,17 @@ export function keychainHint({ platform = process.platform, stdinIsTTY = process
453
522
  return !stdinIsTTY || !!env.SSH_CONNECTION ? "keychain-non-interactive" : null;
454
523
  }
455
524
 
525
+ /** A failed git call as E_REMOTE_UNREADABLE, by its reason (classifyRemoteFailure). The message prints the
526
+ * url as every message of the cache does, without its user information (redactUrl); `details.url` is the
527
+ * url as written. A failure the kernel cannot classify (`unknown`) carries git's own last line, scrubbed
528
+ * (scrubGitLine), so that the message shows what the kernel could not name; with no line, an output over
529
+ * its budget is said, and otherwise the message ends at the reason. */
456
530
  function unreadable(ref, error, extra = {}) {
457
531
  const reason = classifyRemoteFailure(error), killed = reason === "killed";
458
532
  if (reason === "cache") return cacheFailure(ref, error, extra);
459
533
  const hint = keychainHint({ reason });
460
- return fail("E_REMOTE_UNREADABLE", `cannot read remote ${ref.url} (${reason})${killed ? `: git was killed (signal ${error.signal})` : ""}${hint ? `: ${KEYCHAIN_REMEDY}` : ""}`,
534
+ const said = reason === "unknown" ? gitLastLine(error, ref.url) || (error?.overflowed === true ? "git's output exceeded its budget" : "") : "";
535
+ return fail("E_REMOTE_UNREADABLE", `cannot read remote ${redactUrl(ref.url)} (${reason})${killed ? `: git was killed (signal ${error.signal})` : ""}${said ? `: ${said}` : ""}${hint ? `: ${KEYCHAIN_REMEDY}` : ""}`,
461
536
  { url: ref.url, key: ref.key, reason, ...(killed ? { signal: error.signal } : {}), ...(hint ? { hint, remedy: KEYCHAIN_REMEDY } : {}), ...extra });
462
537
  }
463
538
 
@@ -703,7 +778,8 @@ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
703
778
  const cacheRootOf = (options) => options.cacheDir ?? defaultCacheRoot();
704
779
  const cacheDirOf = (root, ref) => join(root, sha256(ref.key));
705
780
 
706
- /** A url without its userinfo (`ssh://user:secret@host/…` → `ssh://host/…`): what may be written to disk. */
781
+ /** A url without its userinfo (`ssh://user:secret@host/…` → `ssh://host/…`): what may be written to disk,
782
+ * and how a message prints a url. The one function for it. */
707
783
  function redactUrl(url) {
708
784
  return typeof url === "string" ? url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]*@/i, "$1") : url;
709
785
  }
@@ -1216,7 +1292,7 @@ async function ensureCommit(ref, oid, options) {
1216
1292
  const mode = await fetchMode(repo)
1217
1293
  ?? (keepsPartialCache(version) ? await startPartialFetches(repo, ref) : await recordFullFetches(repo, ref, olderGitNotice(version, ref)));
1218
1294
  const filter = mode === "partial" ? [`--filter=${PARTIAL_FILTER}`] : ["--no-filter"];
1219
- const { stderr } = await fetchInto(repo, ref, ["fetch", "-q", "--depth", "1", "--no-tags", "--no-recurse-submodules", ...filter, "origin", oid], { what: oid, commit: oid });
1295
+ const { stderr } = await fetchCommit(repo, ref, ["fetch", "-q", "--depth", "1", "--no-tags", "--no-recurse-submodules", ...filter, "origin", oid], oid);
1220
1296
  // A server without filters says so and sends the whole tree: nothing is lost, the cache remembers.
1221
1297
  if (mode === "partial" && /filtering not recognized by server/i.test(stderr.toString("utf8"))) await recordFullFetches(repo, ref);
1222
1298
  const commit = await asReadTimeout(repo, peelCommit(repo, oid));
@@ -1232,6 +1308,32 @@ async function ensureCommit(ref, oid, options) {
1232
1308
  });
1233
1309
  }
1234
1310
 
1311
+ /**
1312
+ * The fetch of a commit into the cache (awebai/oats#1059). The fetch negotiates: git tells the server the
1313
+ * commits the cache holds (its pins), and the pack holds only what they lack, a few kilobytes for a new head
1314
+ * beside the last one. But the server may then send an object as a delta against one it takes the cache to
1315
+ * hold, and the cache does not hold the blobs its filter left out (nor, in a cache that turned to whole
1316
+ * trees, those of the commits fetched before): the pack cannot be completed, git may not fetch the missing
1317
+ * base on its own (GIT_NO_LAZY_FETCH), and the fetch dies with words the kernel cannot classify. `git fetch`
1318
+ * has no way to ask for a pack that is complete by itself while negotiating. So a fetch whose failure the
1319
+ * kernel cannot classify (`unknown`: never by git's wording) is made once more without negotiation
1320
+ * (`fetch.negotiationAlgorithm=noop`, as the fetch of blobs by id): the server is told nothing of what the
1321
+ * cache holds and sends the commit whole, which is complete whatever the cache holds. One second attempt,
1322
+ * never a third; if it fails, its failure is the answer. The first attempt's temporary pack stays in the
1323
+ * object store until a later fetch finds it old enough (removeStaleTemporaryFiles): one pack per commit that
1324
+ * needed its second attempt, since that commit is then present and never fetched again.
1325
+ * → { stdout, stderr } of the fetch that succeeded.
1326
+ */
1327
+ async function fetchCommit(repo, ref, args, oid) {
1328
+ try { return await fetchInto(repo, ref, args, { what: oid, commit: oid, raw: true }); }
1329
+ catch (error) {
1330
+ if (typeof error?.code === "string" && error.code.startsWith("E_")) throw error; // the fetch's timeout
1331
+ // A command that gave the read up is not asked again; neither is a failure the kernel can name.
1332
+ if (error?.code === "ABORT_ERR" || repo.session?.signal?.aborted || classifyRemoteFailure(error) !== "unknown") throw fetchFailure(repo, ref, error, oid);
1333
+ }
1334
+ return fetchInto(repo, ref, ["-c", "fetch.negotiationAlgorithm=noop", ...args], { what: oid, commit: oid });
1335
+ }
1336
+
1235
1337
  /** Pin `name` to `oid` in the cache repo. Two processes pinning one commit write the same value: a lost lock
1236
1338
  * race is retried, and a ref that already holds `oid` (another process's write) counts as written. */
1237
1339
  async function writePin(repo, ref, name, oid, commit) {
@@ -1362,11 +1464,73 @@ function markCacheDamaged(repo, why) {
1362
1464
  /** The repository carries a damage mark this session did not set: the next fetch rebuilds it first. */
1363
1465
  const toRebuild = (dir, session) => existsSync(join(dir, DAMAGED_MARK)) && !session?.damaged.has(dir);
1364
1466
 
1365
- /** `git fetch` from the remote into the cache (args start at the subcommand and name the remote "origin"):
1366
- * a lost on-disk `.lock` race is retried, a timeout names the fetch (`what`) and how long it ran, any other
1367
- * failure is E_REMOTE_UNREADABLE (`raw`: the git error itself, for a caller that reads its stderr). → { stdout, stderr } */
1467
+ /**
1468
+ * THE LONGEST FETCH, the age past which a fetch may remove a temporary file of git's: 11 minutes, which is the
1469
+ * 10 minutes any kernel gives the fetch of a commit (GIT_FETCH_TIMEOUT_MS) and one minute of margin, the
1470
+ * constant a stale git lock is judged by (GIT_LOCK_STALE_MS); or, when the session making this fetch was given
1471
+ * a longer fetch timeout of its own, that timeout and the same minute (`fetchTimeoutMs`; no caller in the
1472
+ * kernel gives one). No fetch a kernel started can still be writing a file that old: git is ended at the
1473
+ * timeout, and an older kernel's fetch, which takes no write lock, has the same 10 minutes.
1474
+ */
1475
+ const temporaryStaleMs = (session) => Math.max(GIT_LOCK_STALE_MS, (session?.fetchTimeoutMs ?? 0) + 60_000);
1476
+ /**
1477
+ * The temporary files git has in the cache's object store: → Map path → mtimeMs. A fetch receives
1478
+ * its pack into `objects/pack/tmp_pack_*` (index-pack; its index and reverse index are written as
1479
+ * `tmp_idx_*` and `tmp_rev_*` there), and a pack small enough to be unpacked writes each object as
1480
+ * `objects/<xx>/tmp_obj_*` first; git's own `prune` looks for `tmp_*` in `objects`, `objects/pack` and those
1481
+ * directories, and so does this. index-pack does not remove its file when it dies, and nothing else in the
1482
+ * cache ever would (it runs no gc). Regular files only, and only inside the cache entry: no symbolic link
1483
+ * is followed below it (the rule of reclaimGitLock), so a directory that is one, or that lies behind one,
1484
+ * holds none, as does a directory that cannot be read.
1485
+ */
1486
+ function gitTemporaryFiles(repo) {
1487
+ const found = new Map();
1488
+ let root;
1489
+ try { root = realpathSync(repo.dir); } catch { return found; }
1490
+ const scan = (...below) => {
1491
+ const dir = join(root, ...below);
1492
+ let names;
1493
+ try {
1494
+ if (!lstatSync(dir).isDirectory() || realpathSync(dir) !== dir) return [];
1495
+ names = readdirSync(dir);
1496
+ } catch { return []; }
1497
+ for (const name of names) {
1498
+ if (!name.startsWith("tmp_")) continue;
1499
+ try { const st = lstatSync(join(dir, name)); if (st.isFile()) found.set(join(dir, name), st.mtimeMs); } catch { /* gone meanwhile */ }
1500
+ }
1501
+ return names;
1502
+ };
1503
+ for (const name of scan("objects")) if (/^[0-9a-f]{2}$/.test(name)) scan("objects", name);
1504
+ scan("objects", "pack");
1505
+ return found;
1506
+ }
1507
+ /**
1508
+ * Before a fetch, under the cache's write lock: remove the temporary files of the object store that are older
1509
+ * than the longest fetch (temporaryStaleMs says what that is). That is the only rule, for a failed fetch's own leftovers too:
1510
+ * a file that appeared during a fetch cannot be told from one another git is writing (an older kernel's fetch
1511
+ * takes no write lock, git names its pack file itself, and nothing says who holds a file open), so none is
1512
+ * removed for having appeared; git's own `prune` goes by age for the same reason. A failed fetch's pack
1513
+ * therefore stays until a fetch into this entry finds it old enough.
1514
+ */
1515
+ function removeStaleTemporaryFiles(repo) {
1516
+ const staleMs = temporaryStaleMs(repo.session), now = Date.now();
1517
+ for (const [file, mtimeMs] of gitTemporaryFiles(repo)) {
1518
+ if (now - mtimeMs <= staleMs) continue;
1519
+ try { unlinkSync(file); } catch { /* a later fetch finds it again */ }
1520
+ }
1521
+ }
1522
+
1523
+ /** A failed fetch as E_REMOTE_UNREADABLE: a failed write of the cache says where and at which stage. */
1524
+ const fetchFailure = (repo, ref, error, commit) => unreadable(ref, error, { commit, ...(classifyRemoteFailure(error) === "cache" ? { cacheDir: repo.dir, stage: "fetch" } : {}) });
1525
+
1526
+ /** `git fetch` from the remote into the cache (args start at the subcommand and name the remote "origin"),
1527
+ * made under the cache's write lock: a lost on-disk `.lock` race is retried, a timeout names the fetch
1528
+ * (`what`) and how long it ran, any other failure is E_REMOTE_UNREADABLE (`raw`: the git error itself, for
1529
+ * a caller that reads it). Every fetch first removes the temporary files earlier fetches left in the object
1530
+ * store, by their age (removeStaleTemporaryFiles). → { stdout, stderr } */
1368
1531
  async function fetchInto(repo, ref, args, { what, commit, input, raw = false } = {}) {
1369
1532
  const started = Date.now();
1533
+ removeStaleTemporaryFiles(repo);
1370
1534
  let lastError;
1371
1535
  try { return await cacheGit(repo, ["-c", `remote.origin.url=${ref.url}`, ...args], { timeout: repo.session?.fetchTimeoutMs ?? GIT_FETCH_TIMEOUT_MS, ...(input !== undefined ? { input } : {}) }); }
1372
1536
  catch (error) { lastError = error; }
@@ -1375,7 +1539,7 @@ async function fetchInto(repo, ref, args, { what, commit, input, raw = false } =
1375
1539
  throw fail("E_REMOTE_UNREADABLE", `cannot read remote ${ref.url} (timeout): git fetch of ${what} timed out after ${Math.round(elapsedMs / 1000)} s`,
1376
1540
  { url: ref.url, key: ref.key, reason: "timeout", commit, operation: "fetch", elapsedMs });
1377
1541
  }
1378
- throw raw ? lastError : unreadable(ref, lastError, { commit, ...(classifyRemoteFailure(lastError) === "cache" ? { cacheDir: repo.dir, stage: "fetch" } : {}) });
1542
+ throw raw ? lastError : fetchFailure(repo, ref, lastError, commit);
1379
1543
  }
1380
1544
 
1381
1545
  /** The sizes of `oids` in the cache, one `cat-file --batch-check`: → Map oid → size, null when the cache lacks it. */
@@ -1419,7 +1583,7 @@ async function ensureBlobs(repo, ref, commit, entries) {
1419
1583
  { what, commit, input: wanted.map((o) => `${o}\n`).join(""), raw: true });
1420
1584
  } catch (error) {
1421
1585
  if (typeof error?.code === "string" && error.code.startsWith("E_")) throw error;
1422
- if (!isRefusedWant(error)) throw unreadable(ref, error, { commit, ...(classifyRemoteFailure(error) === "cache" ? { cacheDir: repo.dir, stage: "fetch" } : {}) });
1586
+ if (!isRefusedWant(error)) throw fetchFailure(repo, ref, error, commit);
1423
1587
  await refetch();
1424
1588
  await recordFullFetches(repo, ref);
1425
1589
  }
@@ -1788,7 +1952,8 @@ function listingUnreadable(error, { repo, spec, path, ref, commit }) {
1788
1952
  if (missingObject) markCacheDamaged(repo, `${spec}: ${text.trim().split("\n")[0]}`);
1789
1953
  const killed = !error?.timedOut && !error?.overflowed && typeof error?.signal === "string" && error.signal !== "";
1790
1954
  const reason = error?.timedOut ? "timeout" : killed ? "killed" : missingObject ? "cache" : "unknown";
1791
- const why = error?.overflowed ? "listing exceeded the output budget" : killed ? `git was killed (signal ${error.signal})` : (text.trim().split("\n")[0] || error?.code || error?.message || "git ls-tree failed");
1955
+ // git's first line, as before, through the one scrub (scrubGitLine); a message of Node's when git said nothing.
1956
+ const why = error?.overflowed ? "listing exceeded the output budget" : killed ? `git was killed (signal ${error.signal})` : (scrubGitLine(text.trim().split("\n")[0], ref?.url) || error?.code || scrubGitLine(error?.message, ref?.url) || "git ls-tree failed");
1792
1957
  return fail("E_REMOTE_UNREADABLE", `cannot list ${spec}${path !== undefined ? ` -- ${path}` : ""} in ${ref?.key ?? repo.dir} (${reason}: ${why})`, { url: ref?.url ?? null, key: ref?.key ?? null, reason, commit: commit ?? null, spec, path: path ?? null, cause: error?.code ?? null, overflowed: error?.overflowed === true, ...(killed ? { signal: error.signal } : {}) });
1793
1958
  }
1794
1959
 
package/lib/resolve.mjs CHANGED
@@ -227,7 +227,8 @@ export function parseVersion(text) {
227
227
  prerelease: m[4] ? m[4].split(".").map((p) => (/^\d+$/.test(p) ? Number(p) : p)) : [],
228
228
  };
229
229
  }
230
- function compareVersions(a, b) {
230
+ /** Two parsed versions (parseVersion) in semver order: negative, zero or positive. */
231
+ export function compareVersions(a, b) {
231
232
  for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
232
233
  if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
233
234
  if (a.prerelease.length === 0) return 1; // a release outranks any prerelease of the same triple
@@ -16,7 +16,7 @@
16
16
  * control characters escaped. */
17
17
  import { closeSync, constants as fsConstants, fstatSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync } from "node:fs";
18
18
  import { isAbsolute, join } from "node:path";
19
- import { instancesDirs, RECOVERABLE_GIT_ADMIN, retainedWorktreesRoot, retirementRecoveryRoot } from "./core.mjs";
19
+ import { gitOperationInProgress, instancesDirs, retainedWorktreesRoot, retirementRecoveryRoot } from "./core.mjs";
20
20
  import { gitRead, gitRepoRead } from "./instance-git.mjs";
21
21
  import { formatBytes } from "./retire-output.mjs";
22
22
  import { joinBytes } from "./tree-copy.mjs";
@@ -210,7 +210,7 @@ function uncommittedClasses(z) {
210
210
  * (`--ignore-submodules=dirty` compares only the commit a submodule is at). */
211
211
  function cleanFacts(path, gitDir) {
212
212
  const classes = [];
213
- if (RECOVERABLE_GIT_ADMIN.some((name) => typeof kindOf(join(gitDir, name)) === "string")) classes.push("an operation in progress");
213
+ if (gitOperationInProgress(gitDir, path)) classes.push("an operation in progress");
214
214
  const uncommitted = classes.length ? `; uncommitted: ${classes.join(", ")}` : "";
215
215
  const filters = contentFilters(path);
216
216
  if (filters.error) return [`clean: unknown (its configuration could not be read: ${shown(filters.error)})${uncommitted}`];
@@ -3,7 +3,8 @@
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. Dependency-free. */
6
+ * block is printed per entry. A third renders its `warnings`. Dependency-free. */
7
+ import { terminalText } from "./refused-text.mjs";
7
8
 
8
9
  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`;
9
10
 
@@ -66,3 +67,13 @@ export function extraWorktreeLines(receipt, { host } = {}) {
66
67
  : `Extra worktree ${t.path} re-homed${host ? ` on ${host}` : ""} to ${t.movedTo} (${at}): ${t.reason}`;
67
68
  });
68
69
  }
70
+
71
+ /** The lines `oats retire` prints for a receipt's `warnings`, one per warning. A warning can hold
72
+ * text the kernel did not write: a path as the system resolves it (where a link at `work/` led,
73
+ * awebai/oats#973; the repository Git names for a tree), a hook's own words. Each goes to the
74
+ * terminal through terminalText (lib/refused-text.mjs), so that a name cannot clear the screen or
75
+ * write a line of its own. The receipt's JSON holds each warning as it is. */
76
+ export function warningLines(receipt) {
77
+ const warnings = Array.isArray(receipt?.warnings) ? receipt.warnings : [];
78
+ return warnings.map((w) => ` WARNING: ${terminalText(w)}`);
79
+ }
@@ -3,32 +3,57 @@
3
3
  * installed unless `oats schedule host install` is run explicitly, and
4
4
  * status reports what the OS says is loaded, never what a file implies. */
5
5
  import { execFileSync } from "node:child_process";
6
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
7
7
  import { homedir, platform, userInfo } from "node:os";
8
- import { dirname, join } from "node:path";
8
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { hostScheduleDir, scheduleError } from "./schedule.mjs";
11
+ import { stableNode as stableNodeRule, unitPathEntries } from "./stable-node.mjs";
11
12
 
12
13
  export const LAUNCHD_LABEL = "ai.oats.schedule-tick";
13
14
  export const SYSTEMD_UNIT = "oats-schedule-tick";
14
15
  const OATS_BIN = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "oats.mjs");
16
+ /** The usual prefixes every unit PATH ends with, whether or not this host has them. */
17
+ const FALLBACK_PATH = ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"];
18
+ const REINSTALL = "run `oats schedule host install` again from the operator's shell (not from an instance home)";
15
19
 
16
20
  function escapeXml(s) { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
21
+ function unescapeXml(s) { return String(s).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&"); }
22
+
23
+ export { unitPathEntries };
24
+ function realpathOrNull(p) { try { return realpathSync(p); } catch { return null; } }
25
+ /** The node a unit runs: the rule of lib/stable-node.mjs, its warning worded
26
+ * for the timer. */
27
+ export function stableNode(o = {}) {
28
+ return stableNodeRule({ ...o, consequence: "the timer stops when it goes away", remedy: "run `oats schedule host install` again" });
29
+ }
17
30
 
18
31
  /** launchd and systemd start units with a short PATH that has no Homebrew
19
32
  * tmux and no installed harness. The unit therefore carries an explicit
20
- * PATH: the installer's own PATH (the operator's tool environment) plus
21
- * the node running the installer and the usual prefixes. */
22
- export function hostPath({ node = process.execPath, envPath = process.env.PATH || "" } = {}) {
33
+ * PATH: the dir of the node it runs, the installer's own PATH (the
34
+ * operator's tool environment) without its hazards (unitPathEntries), and the
35
+ * usual prefixes. */
36
+ export function hostPath({ node = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
23
37
  const seen = new Set();
24
38
  const out = [];
25
- for (const p of [dirname(node), ...envPath.split(":"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"]) {
39
+ for (const p of [dirname(node), ...unitPathEntries(envPath, { instanceHome }), ...FALLBACK_PATH]) {
26
40
  if (p && !seen.has(p)) { seen.add(p); out.push(p); }
27
41
  }
28
42
  return out.join(":");
29
43
  }
44
+ /** What `install` renders from the installer's environment: the stable node,
45
+ * the unit PATH, and the warnings the install answer carries. */
46
+ export function hostUnitPlan({ execPath = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
47
+ const { node, warning } = stableNode({ execPath, envPath, instanceHome });
48
+ return { node, path: hostPath({ node, envPath, instanceHome }), warnings: warning ? [warning] : [] };
49
+ }
30
50
 
31
- export function renderLaunchdPlist({ node = process.execPath, oatsBin = OATS_BIN, logDir = join(hostScheduleDir(), "log"), intervalSec = 60, oatsHomeDir = process.env.OATS_HOME_DIR, path = hostPath({ node }) } = {}) {
51
+ /** An empty StartCalendarInterval dict fires at second 0 of every minute.
52
+ * ProcessType Standard: a Background job's start is throttled, and under
53
+ * load its node started long after the fire, past its minute. */
54
+ export function renderLaunchdPlist({ node, oatsBin = OATS_BIN, logDir = join(hostScheduleDir(), "log"), oatsHomeDir = process.env.OATS_HOME_DIR, path } = {}) {
55
+ if (node === undefined) node = hostUnitPlan().node;
56
+ if (path === undefined) path = hostPath({ node });
32
57
  const env = `\n <key>EnvironmentVariables</key>\n <dict>\n <key>PATH</key><string>${escapeXml(path)}</string>${oatsHomeDir ? `\n <key>OATS_HOME_DIR</key><string>${escapeXml(oatsHomeDir)}</string>` : ""}\n </dict>`;
33
58
  return `<?xml version="1.0" encoding="UTF-8"?>
34
59
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -44,9 +69,9 @@ export function renderLaunchdPlist({ node = process.execPath, oatsBin = OATS_BIN
44
69
  <string>--host</string>
45
70
  <string>--json</string>
46
71
  </array>
47
- <key>StartInterval</key><integer>${intervalSec}</integer>
72
+ <key>StartCalendarInterval</key><dict/>
48
73
  <key>RunAtLoad</key><false/>
49
- <key>ProcessType</key><string>Background</string>
74
+ <key>ProcessType</key><string>Standard</string>
50
75
  <key>StandardOutPath</key><string>${escapeXml(join(logDir, "tick.log"))}</string>
51
76
  <key>StandardErrorPath</key><string>${escapeXml(join(logDir, "tick.err"))}</string>${env}
52
77
  </dict>
@@ -58,14 +83,71 @@ export function renderLaunchdPlist({ node = process.execPath, oatsBin = OATS_BIN
58
83
  export function systemdQuote(value) {
59
84
  return `"${String(value).replace(/%/g, "%%").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
60
85
  }
61
- export function renderSystemdUnits({ node = process.execPath, oatsBin = OATS_BIN, intervalSec = 60, oatsHomeDir = process.env.OATS_HOME_DIR, path = hostPath({ node }) } = {}) {
86
+ /** A calendar timer at second 0 of every minute; a minute missed while the
87
+ * machine was off or asleep is not run at wake (Persistent=false). */
88
+ export function renderSystemdUnits({ node, oatsBin = OATS_BIN, oatsHomeDir = process.env.OATS_HOME_DIR, path } = {}) {
89
+ if (node === undefined) node = hostUnitPlan().node;
90
+ if (path === undefined) path = hostPath({ node });
62
91
  const env = `Environment=${systemdQuote(`PATH=${path}`)}\n${oatsHomeDir ? `Environment=${systemdQuote(`OATS_HOME_DIR=${oatsHomeDir}`)}\n` : ""}`;
63
92
  return {
64
93
  service: `[Unit]\nDescription=OATS schedule tick\n\n[Service]\nType=oneshot\n${env}ExecStart=${systemdQuote(node)} ${systemdQuote(oatsBin)} schedule tick --host --json\n`,
65
- timer: `[Unit]\nDescription=OATS schedule tick every ${intervalSec}s\n\n[Timer]\nOnBootSec=${intervalSec}\nOnUnitActiveSec=${intervalSec}\nAccuracySec=5\nUnit=${SYSTEMD_UNIT}.service\n\n[Install]\nWantedBy=timers.target\n`,
94
+ timer: `[Unit]\nDescription=OATS schedule tick\n\n[Timer]\nOnCalendar=*-*-* *:*:00\nAccuracySec=1s\nPersistent=false\nUnit=${SYSTEMD_UNIT}.service\n\n[Install]\nWantedBy=timers.target\n`,
66
95
  };
67
96
  }
68
97
 
98
+ function systemdUnquote(quoted) {
99
+ return quoted.slice(1, -1).replace(/\\(.)/g, "$1").replace(/%%/g, "%");
100
+ }
101
+ const SYSTEMD_QUOTED = String.raw`"(?:[^"\\]|\\.)*"`;
102
+ /** The values an installed unit records, read from the file alone (never the
103
+ * caller's environment); null when the file is not in the shape oats renders. */
104
+ function recordedUnit(p) {
105
+ if (p.kind === "launchd") {
106
+ const text = readFileSync(p.plist, "utf8");
107
+ const value = (key) => { const m = new RegExp(`<key>${key}</key><string>([^<]*)</string>`).exec(text); return m ? unescapeXml(m[1]) : undefined; };
108
+ const args = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>\s*<string>([^<]*)<\/string>/.exec(text);
109
+ const out = value("StandardOutPath");
110
+ const legacy = /<key>StartInterval<\/key>/.test(text);
111
+ if (!args || value("PATH") === undefined || out === undefined) return { legacy, unit: null };
112
+ // An absent OATS_HOME_DIR is "" (rendered as none), never the caller's.
113
+ const unit = { node: unescapeXml(args[1]), oatsBin: unescapeXml(args[2]), path: value("PATH"), oatsHomeDir: value("OATS_HOME_DIR") ?? "", logDir: dirname(out) };
114
+ return { legacy, unit, same: renderLaunchdPlist(unit) === text };
115
+ }
116
+ const service = readFileSync(p.service, "utf8"), timer = readFileSync(p.timer, "utf8");
117
+ const legacy = /^(OnBootSec|OnUnitActiveSec)=/m.test(timer);
118
+ const exec = new RegExp(`^ExecStart=(${SYSTEMD_QUOTED}) (${SYSTEMD_QUOTED}) `, "m").exec(service);
119
+ const env = (name) => { const m = new RegExp(`^Environment=("${name}=(?:[^"\\\\]|\\\\.)*")$`, "m").exec(service); return m ? systemdUnquote(m[1]).slice(name.length + 1) : undefined; };
120
+ if (!exec || env("PATH") === undefined) return { legacy, unit: null };
121
+ const unit = { node: systemdUnquote(exec[1]), oatsBin: systemdUnquote(exec[2]), path: env("PATH"), oatsHomeDir: env("OATS_HOME_DIR") ?? "" };
122
+ const rendered = renderSystemdUnits(unit);
123
+ return { legacy, unit, same: rendered.service === service && rendered.timer === timer };
124
+ }
125
+
126
+ /** What would stop or mislead the installed timer, as warnings: a recorded
127
+ * node or oats that is gone, a PATH entry that is gone (the fallback
128
+ * prefixes are not checked: not every host has them), and a unit that is
129
+ * not what this kernel renders from those same recorded values. */
130
+ function unitProblems(p) {
131
+ let read;
132
+ try { read = recordedUnit(p); } catch (e) { return [{ code: "unit-outdated", message: `the unit cannot be read: ${e.message}`, fix: REINSTALL }]; }
133
+ const problems = [];
134
+ const { unit } = read;
135
+ if (unit) {
136
+ const nodeMissing = !existsSync(unit.node);
137
+ if (nodeMissing) problems.push({ code: "node-missing", message: `the unit runs node at ${unit.node}, which does not exist`, fix: REINSTALL });
138
+ if (!existsSync(unit.oatsBin)) problems.push({ code: "oats-bin-missing", message: `the unit runs oats at ${unit.oatsBin}, which does not exist`, fix: REINSTALL });
139
+ for (const entry of unit.path.split(":")) {
140
+ // A gone node's own directory is node-missing's cause, not a PATH entry to remove.
141
+ if (nodeMissing && entry === dirname(unit.node)) continue;
142
+ if (entry && !FALLBACK_PATH.includes(entry) && !existsSync(entry)) problems.push({ code: "path-entry-missing", message: `the unit's PATH entry ${entry} does not exist`, fix: `restore ${entry}, or remove it from the operator's PATH and ${REINSTALL}` });
143
+ }
144
+ }
145
+ if (read.legacy) problems.push({ code: "unit-outdated", message: "the unit runs the tick on an interval, not at second 0 of every minute", fix: REINSTALL });
146
+ else if (!unit) problems.push({ code: "unit-outdated", message: "the unit is not in the shape oats renders", fix: REINSTALL });
147
+ else if (!read.same) problems.push({ code: "unit-outdated", message: "the unit differs from what this oats renders for it", fix: REINSTALL });
148
+ return problems;
149
+ }
150
+
69
151
  /** `unitDir` overrides the OS location (tests never touch a live timer's files). */
70
152
  export function hostUnitPaths(os = platform(), { unitDir } = {}) {
71
153
  if (os === "darwin") return { kind: "launchd", plist: join(unitDir || join(homedir(), "Library", "LaunchAgents"), `${LAUNCHD_LABEL}.plist`) };
@@ -78,46 +160,67 @@ function run(exec, argv) {
78
160
  catch (e) { return { ok: false, out: String(e.stdout || ""), err: String(e.stderr || e.message || "").trim() }; }
79
161
  }
80
162
 
81
- /** installed = the unit file exists; active = the OS reports it loaded/active. */
163
+ /** installed = the unit file exists; active = the OS reports it loaded/active;
164
+ * problems = unitProblems, warnings that never change installed or active. */
82
165
  export function hostUnitStatus({ exec, os = platform(), unitDir } = {}) {
83
166
  const p = hostUnitPaths(os, { unitDir });
84
167
  if (p.kind === "launchd") {
85
168
  const installed = existsSync(p.plist);
86
169
  const r = run(exec, ["launchctl", "print", `gui/${userInfo().uid}/${LAUNCHD_LABEL}`]);
87
- return { kind: p.kind, unit: p.plist, installed, active: r.ok };
170
+ return { kind: p.kind, unit: p.plist, installed, active: r.ok, problems: installed ? unitProblems(p) : [] };
88
171
  }
89
172
  if (p.kind === "systemd") {
90
173
  const installed = existsSync(p.timer) && existsSync(p.service);
91
174
  const r = run(exec, ["systemctl", "--user", "is-active", `${SYSTEMD_UNIT}.timer`]);
92
- return { kind: p.kind, unit: p.timer, installed, active: r.ok && r.out.trim() === "active" };
175
+ return { kind: p.kind, unit: p.timer, installed, active: r.ok && r.out.trim() === "active", problems: installed ? unitProblems(p) : [] };
93
176
  }
94
- return { kind: "unsupported", installed: false, active: false };
177
+ return { kind: "unsupported", installed: false, active: false, problems: [] };
95
178
  }
96
179
 
97
- export function installHostUnit({ exec, os = platform(), intervalSec = 60, unitDir } = {}) {
180
+ /** The unit files install writes for `os`, rendered from the installer's
181
+ * environment (hostUnitPlan): { kind, files: { <path>: <content> }, warnings }.
182
+ * Renders only: nothing is written and the OS is not asked. */
183
+ export function hostUnitFiles({ os = platform(), unitDir, execPath = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME, oatsBin = OATS_BIN } = {}) {
98
184
  const p = hostUnitPaths(os, { unitDir });
185
+ const { node, path, warnings } = hostUnitPlan({ execPath, envPath, instanceHome });
186
+ // The unit runs the oats that ran install: one inside an instance home goes away when that instance retires.
187
+ // The home's work counts as resolved too: an attached instance's work is a link into its owner's home.
188
+ if (instanceHome && isAbsolute(instanceHome)) {
189
+ const bin = realpathOrNull(oatsBin) ?? resolve(oatsBin);
190
+ const homes = [realpathOrNull(instanceHome) ?? resolve(instanceHome), realpathOrNull(join(instanceHome, "work"))].filter(Boolean);
191
+ if (homes.some((home) => bin === home || bin.startsWith(home + sep))) warnings.push(`the unit would run ${oatsBin}, inside the instance home ${instanceHome}: the timer stops when that instance retires; run \`oats schedule host install\` with the operator's installed oats, from the operator's own shell`);
192
+ }
193
+ if (p.kind === "launchd") return { kind: p.kind, files: { [p.plist]: renderLaunchdPlist({ node, path, oatsBin }) }, warnings };
194
+ if (p.kind === "systemd") { const units = renderSystemdUnits({ node, path, oatsBin }); return { kind: p.kind, files: { [p.service]: units.service, [p.timer]: units.timer }, warnings }; }
195
+ throw scheduleError("E_SCHEDULE_HOST", `no host timer support on ${os}`);
196
+ }
197
+
198
+ /** Writes hostUnitFiles and loads them; the answer is the status plus their warnings. */
199
+ export function installHostUnit({ exec, os = platform(), unitDir, execPath = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
200
+ const p = hostUnitPaths(os, { unitDir });
201
+ const { files, warnings } = hostUnitFiles({ os, unitDir, execPath, envPath, instanceHome });
99
202
  mkdirSync(join(hostScheduleDir(), "log"), { recursive: true });
100
203
  if (p.kind === "launchd") {
101
204
  mkdirSync(dirname(p.plist), { recursive: true });
102
205
  const status = hostUnitStatus({ exec, os, unitDir });
103
- const rendered = renderLaunchdPlist({ intervalSec });
206
+ const rendered = files[p.plist];
104
207
  // Idempotent: registering another scope while the same timer is active
105
208
  // must not unload an in-flight tick just to rewrite identical bytes.
106
- if (status.active && existsSync(p.plist) && readFileSync(p.plist, "utf8") === rendered) return status;
209
+ if (status.active && existsSync(p.plist) && readFileSync(p.plist, "utf8") === rendered) return { ...status, warnings };
107
210
  if (status.active) { const r = run(exec, ["launchctl", "bootout", `gui/${userInfo().uid}/${LAUNCHD_LABEL}`]); if (!r.ok) throw scheduleError("E_SCHEDULE_HOST", `launchctl bootout failed before reinstall: ${r.err}`); }
108
211
  writeFileSync(p.plist, rendered);
109
212
  const r = run(exec, ["launchctl", "bootstrap", `gui/${userInfo().uid}`, p.plist]);
110
213
  if (!r.ok) throw scheduleError("E_SCHEDULE_HOST", `launchctl bootstrap failed: ${r.err}`);
111
- return hostUnitStatus({ exec, os, unitDir });
214
+ return { ...hostUnitStatus({ exec, os, unitDir }), warnings };
112
215
  }
113
216
  if (p.kind === "systemd") {
114
217
  mkdirSync(dirname(p.timer), { recursive: true });
115
- const units = renderSystemdUnits({ intervalSec });
218
+ const units = { service: files[p.service], timer: files[p.timer] };
116
219
  const status = hostUnitStatus({ exec, os, unitDir });
117
- if (status.active && existsSync(p.service) && existsSync(p.timer) && readFileSync(p.service, "utf8") === units.service && readFileSync(p.timer, "utf8") === units.timer) return status;
220
+ if (status.active && existsSync(p.service) && existsSync(p.timer) && readFileSync(p.service, "utf8") === units.service && readFileSync(p.timer, "utf8") === units.timer) return { ...status, warnings };
118
221
  writeFileSync(p.service, units.service); writeFileSync(p.timer, units.timer);
119
222
  for (const argv of [["systemctl", "--user", "daemon-reload"], ["systemctl", "--user", "enable", "--now", `${SYSTEMD_UNIT}.timer`]]) { const r = run(exec, argv); if (!r.ok) throw scheduleError("E_SCHEDULE_HOST", `${argv.join(" ")} failed: ${r.err}`); }
120
- return hostUnitStatus({ exec, os, unitDir });
223
+ return { ...hostUnitStatus({ exec, os, unitDir }), warnings };
121
224
  }
122
225
  throw scheduleError("E_SCHEDULE_HOST", `no host timer support on ${os}`);
123
226
  }