@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/schedule.mjs CHANGED
@@ -35,7 +35,7 @@ import { withDirLock as withSharedDirLock } from "./dir-lock.mjs";
35
35
  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
- import { RESERVED_LAUNCH_ENV, MAX_INSTANCE_NAME, shq, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
38
+ import { RESERVED_LAUNCH_ENV, MAX_INSTANCE_NAME, shq, shellWord, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, sessionServerGone, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
39
39
 
40
40
  export const SCHEDULE_FILE = "oats-schedules.json";
41
41
  export const SCHEDULE_API = 2;
@@ -493,7 +493,9 @@ export function launchOrderKey(js) { return String(js?.lastLaunchedAt || ""); }
493
493
  /** What a run's instance looks like now. Home gone = ended; a home that is
494
494
  * retiring is still there (its harness may be alive pending teardown) and
495
495
  * keeps its slot; present but no running harness = stopped (needs
496
- * attention, never removed); running = active; not inspectable = unknown. */
496
+ * attention, never removed), and so is one whose recorded tmux server is
497
+ * gone (sessionServerGone: after a reboot or a crash); running = active;
498
+ * not inspectable = unknown. */
497
499
  export function observeHome(home, io) {
498
500
  if (!home) return { outcome: "launched" };
499
501
  if (!existsSync(home)) return { outcome: "ended" };
@@ -507,7 +509,11 @@ export function observeHome(home, io) {
507
509
  // (or with no start receipt at all) is a shell a finished harness.
508
510
  if (s.present && s.state === "shell" && startupInProgress(home)) return { outcome: "starting" };
509
511
  return { outcome: "stopped" };
510
- } catch (e) { return { outcome: "unknown", error: e.message }; }
512
+ } catch (e) {
513
+ const lost = sessionServerGone(home, e.cause);
514
+ if (lost.gone) return { outcome: "stopped", note: "its tmux server is gone" };
515
+ return { outcome: "unknown", error: lost.why ? `cannot inspect session: ${lost.why}` : e.message };
516
+ }
511
517
  }
512
518
  function startupInProgress(home) {
513
519
  const pendingPath = join(home, ".oats-start-pending.json");
@@ -610,12 +616,23 @@ function spawnViaCli(ws, root, agent, opts, context, io) {
610
616
  throw scheduleError(e.code || "E_SPAWN_FAILED", retained ? `${e.message} (home retained; effects unconfirmed)` : String(e.message || "spawn failed"), { details: e.details });
611
617
  }
612
618
  const res = envelope.result || {};
613
- return { instance: res.instance, home: res.home, launched: res.launched, materialized: "workspace" };
619
+ return { instance: res.instance, home: res.home, launched: res.launched, materialized: "workspace", ...runWarnings(res) };
614
620
  }
615
621
  /** Launch one spawn job. `io.spawn(root, agent, opts)` overrides the whole
616
622
  * launcher for tests. Otherwise the kernel's own `oats spawn` runs in the
617
623
  * deployment (workspace materialization: `.oats/modules`, module skills and
618
624
  * injects). */
625
+ /** A launch answer's warnings, for the run's record (feature schedule-run-warnings): present only when
626
+ * there are some. */
627
+ export function runWarnings(answer) {
628
+ const w = Array.isArray(answer?.warnings) ? answer.warnings.filter((x) => typeof x === "string") : [];
629
+ return w.length ? { warnings: w } : {};
630
+ }
631
+ /** A record updated in place by a later run keeps no earlier run's warnings. */
632
+ function withoutWarnings(record) {
633
+ const { warnings: _w, ...rest } = record || {}; void _w;
634
+ return rest;
635
+ }
619
636
  function launchSpawn(ws, def, minute, io) {
620
637
  const { root, agent, discover } = resolveScheduledAgent(ws, def);
621
638
  const purpose = `${def.purpose || def.id}-${purposeSuffix(minute)}`;
@@ -623,7 +640,7 @@ function launchSpawn(ws, def, minute, io) {
623
640
  let r;
624
641
  if (io?.spawn) r = io.spawn(root, agent, opts);
625
642
  else r = spawnViaCli(ws, root, agent, opts, workspaceSpawnContext(ws), io);
626
- const run = { instance: r.instance, home: r.home, launched: !!r.instance, kind: "spawn", ...(r.materialized ? { materialized: r.materialized } : {}) };
643
+ const run = { instance: r.instance, home: r.home, launched: !!r.instance, kind: "spawn", ...(r.materialized ? { materialized: r.materialized } : {}), ...runWarnings(r) };
627
644
  if (def.wake && r.home) {
628
645
  try { run.wakeSchedule = saveWakeForHome(ws, { instance: r.instance, home: r.home, wake: def.wake }); }
629
646
  catch (e) { run.wakeScheduleError = { code: e.code || "E_SCHEDULE_INVALID", message: e.message }; }
@@ -732,7 +749,7 @@ function performWake(def, io, { startIfStopped = true, canStart = true, reserve
732
749
  if (reserve && !reserve()) return { kind: "wake", action: "skipped", reason: "the job's slot is held by another process; delivery pending", pending: true };
733
750
  try {
734
751
  const r = (io?.start || startInstanceSession)(def.home);
735
- return { kind: "wake", action: "started", instance: r.instance, target: r.target, home: def.home, incarnation: incarnationOfHome(def.home), reason: "session was stopped; the message is pending until the session is active", pending: true, startedHarness: true };
752
+ return { kind: "wake", action: "started", instance: r.instance, target: r.target, home: def.home, incarnation: incarnationOfHome(def.home), reason: "session was stopped; the message is pending until the session is active", pending: true, startedHarness: true, ...runWarnings(r) };
736
753
  } catch (e) {
737
754
  return { kind: "wake", action: "skipped", reason: `start did not complete (${e.code || "error"}): ${e.message}; the slot is kept until the session is observed stopped or absent`, error: e.message, errorCode: e.code, pending: true, startedHarness: "unconfirmed" };
738
755
  }
@@ -753,7 +770,8 @@ function performWake(def, io, { startIfStopped = true, canStart = true, reserve
753
770
  * while its started harness is active, starting, unknown or retiring and
754
771
  * released when that harness is proven stopped (the start receipt's exit
755
772
  * marker) or its home is gone: a persistent home outliving its process
756
- * does not keep a slot. */
773
+ * does not keep a slot. Returns a spawn job's observed outcome, as it is
774
+ * recorded (a dry run records nothing), when its previous run is tracked. */
757
775
  function observePrevious(ws, id, def, js, io, now, { mutate }) {
758
776
  // An invalid definition (a stored captured one included) is reported on its
759
777
  // job by the tick and never observed.
@@ -766,7 +784,8 @@ function observePrevious(ws, id, def, js, io, now, { mutate }) {
766
784
  const tracked = def.kind === "wake" ? !!lock : !!home && ["launched", "active", "starting", "stopped", "unknown"].includes(lr?.outcome);
767
785
  if (!tracked || !home) return;
768
786
  const seen = observeHome(home, io);
769
- if (!mutate) return;
787
+ const outcome = seen.outcome === "starting" ? "active" : seen.outcome;
788
+ if (!mutate) return def.kind === "wake" ? undefined : outcome;
770
789
  if (def.kind === "wake") {
771
790
  if (seen.outcome === "ended" || seen.outcome === "stopped") {
772
791
  releaseJobLock(ws, id);
@@ -775,8 +794,19 @@ function observePrevious(ws, id, def, js, io, now, { mutate }) {
775
794
  }
776
795
  return;
777
796
  }
778
- js.lastRun = { ...lr, outcome: seen.outcome === "starting" ? "active" : seen.outcome, ...(seen.error ? { error: seen.error } : {}), ...(seen.outcome === "ended" ? { endedAt: now.toISOString() } : {}) };
797
+ // An observation's error and note replace the previous observation's.
798
+ const { error: _error, note: _note, ...run } = lr;
799
+ js.lastRun = { ...run, outcome, ...(seen.error ? { error: seen.error } : {}), ...(seen.note ? { note: seen.note } : {}), ...(seen.outcome === "ended" ? { endedAt: now.toISOString() } : {}) };
779
800
  if (seen.outcome === "ended") releaseJobLock(ws, id);
801
+ return outcome;
802
+ }
803
+ /** Why a due spawn job whose slot is held is skipped: the instance it
804
+ * launched (`outcome`, as observed) stopped, which needs a person, or it
805
+ * still runs. */
806
+ function heldSlotReason(js, outcome) {
807
+ if (outcome !== "stopped") return "still running";
808
+ const { instance, home } = js.lastRun;
809
+ return `previous instance stopped: retire it (oats retire ${shellWord(instance || basename(home))}) or start it again (oats session start --home ${shellWord(home)})`;
780
810
  }
781
811
 
782
812
  /** Evaluate every enabled job of `ws` for the current minute (or, with
@@ -784,8 +814,10 @@ function observePrevious(ws, id, def, js, io, now, { mutate }) {
784
814
  * reads only: no lock, state or definition is touched. Due jobs are
785
815
  * visited least-recently-launched first so one job cannot monopolize the
786
816
  * slot. An invalid definition is recorded on that job and the rest continue. */
787
- export function tickWorkspace(ws, { now = new Date(), io, reg, wsList, dryRun = false, only, observeOnly = false, candidates, ctx = null } = {}) {
788
- const minute = minuteStart(now);
817
+ /** `firedAt` is when the timer fired this tick (the process start, before any
818
+ * work): the minute evaluated. `now` is the clock for every timestamp. */
819
+ export function tickWorkspace(ws, { now = new Date(), firedAt = now, io, reg, wsList, dryRun = false, only, observeOnly = false, candidates, ctx = null } = {}) {
820
+ const minute = minuteStart(firedAt);
789
821
  const key = minuteKey(minute);
790
822
  const registry = reg || readRegistry();
791
823
  const bound = scheduleCap(registry);
@@ -816,7 +848,7 @@ export function tickWorkspace(ws, { now = new Date(), io, reg, wsList, dryRun =
816
848
  if (shape) { cronError = shape; due = false; }
817
849
  else { try { due = only ? true : dueAt(def, minute); } catch (e) { cronError = e.message; due = false; } }
818
850
  const errorCode = herdr ? { errorCode: herdr.code } : {};
819
- if (cronError) { if (!dryRun) js.lastRun = { ...(js.lastRun || {}), outcome: "invalid", error: `definition cannot be evaluated: ${cronError}`, ...errorCode }; record(id, "invalid", { error: cronError, ...errorCode }); continue; }
851
+ if (cronError) { if (!dryRun) js.lastRun = { ...withoutWarnings(js.lastRun), outcome: "invalid", error: `definition cannot be evaluated: ${cronError}`, ...errorCode }; record(id, "invalid", { error: cronError, ...errorCode }); continue; }
820
852
  if (def.kind === "wake" && js.pendingWake && def.enabled && !dryRun && !only) {
821
853
  const dueNow = due && js.lastAttemptedMinute !== key;
822
854
  const held = !!jobLockInfo(ws, id);
@@ -824,7 +856,7 @@ export function tickWorkspace(ws, { now = new Date(), io, reg, wsList, dryRun =
824
856
  const run = performWake(def, io, { startIfStopped: dueNow, canStart, reserve: () => held || acquireJobLock(ws, id, { scheduledFor: js.pendingWake.scheduledFor, wake: true, home: def.home }) });
825
857
  if (run.startedHarness) js.lastLaunchedAt = now.toISOString();
826
858
  if (!existsSync(def.home)) releaseJobLock(ws, id);
827
- js.lastRun = { ...(js.lastRun || {}), ...run, outcome: run.action, completedPending: run.action === "delivered", pendingSince: js.pendingWake.scheduledFor, startedAt: js.lastRun?.startedAt || now.toISOString() };
859
+ js.lastRun = { ...withoutWarnings(js.lastRun), ...run, outcome: run.action, completedPending: run.action === "delivered", pendingSince: js.pendingWake.scheduledFor, startedAt: js.lastRun?.startedAt || now.toISOString() };
828
860
  if (!run.pending) delete js.pendingWake;
829
861
  if (dueNow) js.lastAttemptedMinute = key;
830
862
  record(id, run.action, { ...(run.reason ? { reason: run.reason } : {}), pending: !!run.pending });
@@ -834,7 +866,8 @@ export function tickWorkspace(ws, { now = new Date(), io, reg, wsList, dryRun =
834
866
  if (js.lastAttemptedMinute === key && !only) continue;
835
867
  if (!due) continue;
836
868
  if (dryRun) {
837
- const reason = js.attempt ? "an earlier launch has no recorded result; run oats schedule reconcile" : jobLockInfo(ws, id) && def.kind !== "wake" ? "still running" : liveLocks(wsAll) >= bound && def.kind !== "wake" ? "host busy" : undefined;
869
+ // A dry run recorded no observation: the held slot's instance is observed here.
870
+ const reason = js.attempt ? "an earlier launch has no recorded result; run oats schedule reconcile" : jobLockInfo(ws, id) && def.kind !== "wake" ? heldSlotReason(js, observePrevious(ws, id, def, js, io, now, { mutate: false })) : liveLocks(wsAll) >= bound && def.kind !== "wake" ? "host busy" : undefined;
838
871
  record(id, reason ? "skipped" : "due", reason ? { reason } : {});
839
872
  continue;
840
873
  }
@@ -862,7 +895,7 @@ export function tickWorkspace(ws, { now = new Date(), io, reg, wsList, dryRun =
862
895
  record(id, run.action, { ...(run.reason ? { reason: run.reason } : {}), pending: !!run.pending });
863
896
  continue;
864
897
  }
865
- if (jobLockInfo(ws, id)) { record(id, "skipped", { reason: "still running" }); continue; }
898
+ if (jobLockInfo(ws, id)) { record(id, "skipped", { reason: heldSlotReason(js, js.lastRun?.outcome) }); continue; }
866
899
  if (liveLocks(wsAll) >= bound) { record(id, "skipped", { reason: "host busy" }); continue; }
867
900
  // Persist the attempt before even reserving the launch slot. A crash in
868
901
  // the following gap leaves an inspectable unresolved attempt, never an
@@ -914,8 +947,15 @@ export function scopeAutomations(ws, { io, now = new Date(), refresh = false, ca
914
947
  const ctx = automationContext(ws, { local, io: { ...(io || {}), childEnv }, now, refresh, cache, clonePathOf });
915
948
  return Object.assign(ctx, { ws, local });
916
949
  }
917
- /** The host tick: every registered scope under the host lock. */
918
- export function tickHost({ now = new Date(), io, dryRun = false } = {}) {
950
+ /** A stored minute key as a time, or null when it is not one. */
951
+ function minuteTime(key) {
952
+ const t = typeof key === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(key) ? Date.parse(`${key}:00Z`) : NaN;
953
+ return Number.isFinite(t) ? t : null;
954
+ }
955
+ /** The host tick: every registered scope under the host lock. It evaluates the
956
+ * minute it was fired for (`firedAt`, see tickWorkspace). */
957
+ export function tickHost({ now = new Date(), firedAt = now, io, dryRun = false } = {}) {
958
+ const minute = minuteStart(firedAt);
919
959
  const reg = readRegistry();
920
960
  const wsList = reg.workspaces.filter((w) => existsSync(w));
921
961
  // When this tick started: no trigger source's poll may end later than 50 s after it; `sourced`
@@ -936,14 +976,14 @@ export function tickHost({ now = new Date(), io, dryRun = false } = {}) {
936
976
  for (const ws of wsList) {
937
977
  const ctx = contexts.get(ws);
938
978
  try {
939
- considered.push(...tickWorkspace(ws, { now, io, reg, wsList, dryRun, observeOnly: true, ctx }));
979
+ considered.push(...tickWorkspace(ws, { now, firedAt, io, reg, wsList, dryRun, observeOnly: true, ctx }));
940
980
  const defs = effectiveDefinitions(ws, ctx), st = readState(ws);
941
981
  for (const [id, def] of Object.entries(defs.jobs)) if (def?.kind !== "trigger") jobs.push({ ws, id, key: launchOrderKey(st.jobs[id]) });
942
982
  } catch (e) { considered.push({ workspace: ws, action: "error", error: e.message }); }
943
983
  }
944
984
  jobs.sort((a, b) => a.key.localeCompare(b.key) || a.ws.localeCompare(b.ws) || a.id.localeCompare(b.id));
945
985
  for (const j of jobs) {
946
- try { considered.push(...tickWorkspace(j.ws, { now, io, reg, wsList, dryRun, candidates: [j.id], ctx: contexts.get(j.ws) })); }
986
+ try { considered.push(...tickWorkspace(j.ws, { now, firedAt, io, reg, wsList, dryRun, candidates: [j.id], ctx: contexts.get(j.ws) })); }
947
987
  catch (e) { considered.push({ workspace: j.ws, id: j.id, action: "error", error: e.message }); }
948
988
  }
949
989
  // Triggers: each scope's event-driven spawns, polled at their own interval (lib/triggers.mjs).
@@ -954,8 +994,14 @@ export function tickHost({ now = new Date(), io, dryRun = false } = {}) {
954
994
  // Capability sources: every scope's in one most-overdue-first order, under the tick's one deadline.
955
995
  try { considered.push(...pollSourced(tick.sourced, { now, io, dryRun, reg, wsList, tickStart: tick.start, reserved: tick.reserved ?? 0 })); }
956
996
  catch (e) { considered.push({ action: "error", error: `trigger sources: ${e.message}` }); }
957
- if (!dryRun) writeHostState({ ...readHostState(), lastTick: now.toISOString(), minute: minuteKey(minuteStart(now)) });
958
- return { tickedAt: now.toISOString(), minute: minuteKey(minuteStart(now)), considered, scheduler: schedulerStatus(undefined, io) };
997
+ // The host's minute only moves forward: a slow tick that finishes after the
998
+ // next minute's tick leaves the later minute.
999
+ if (!dryRun) {
1000
+ const host = readHostState();
1001
+ const stored = minuteTime(host.minute);
1002
+ writeHostState({ ...host, lastTick: now.toISOString(), minute: stored !== null && stored > minute.getTime() ? host.minute : minuteKey(minute) });
1003
+ }
1004
+ return { tickedAt: now.toISOString(), minute: minuteKey(minute), considered, scheduler: schedulerStatus(undefined, io) };
959
1005
  };
960
1006
  return dryRun ? body() : withHostLock(body);
961
1007
  }
@@ -976,7 +1022,10 @@ export function runNow(ws, qid, { now = new Date(), io, force = false, ctx = nul
976
1022
  observePrevious(ws, id, def, js, io, now, { mutate: true });
977
1023
  writeState(ws, st);
978
1024
  if (js.attempt) throw scheduleError("E_SCHEDULE_UNRESOLVED", `schedule ${id} has a launch attempt without a recorded result; run oats schedule reconcile ${id} first`);
979
- if (def.kind !== "wake" && jobLockInfo(ws, id)) throw scheduleError("E_SCHEDULE_RUNNING", `schedule ${id} is still running`);
1025
+ if (def.kind !== "wake" && jobLockInfo(ws, id)) {
1026
+ const reason = heldSlotReason(js, js.lastRun?.outcome);
1027
+ throw scheduleError("E_SCHEDULE_RUNNING", reason === "still running" ? `schedule ${id} is still running` : `schedule ${id}: ${reason}`);
1028
+ }
980
1029
  if (def.kind !== "wake" && liveLocks(wsList) >= scheduleCap(reg)) throw scheduleError("E_SCHEDULER_BUSY", `host concurrency ${scheduleCap(reg)} reached`);
981
1030
  const considered = tickWorkspace(ws, { now, io, reg, wsList, only: id, ctx });
982
1031
  const after = readState(ws);
@@ -1026,7 +1075,7 @@ export function reconcile(ws, qid, { io, now = new Date(), clear = false, ctx =
1026
1075
  delete js.attempt;
1027
1076
  if (adopted) {
1028
1077
  const seen = observeHome(adopted.home, io);
1029
- js.lastRun = { scheduledFor: attempt.scheduledFor, startedAt: js.lastRun?.startedAt || attempt.startedAt, kind: attemptKind, launched: true, ...adopted, outcome: seen.outcome, ...(seen.error ? { error: seen.error } : {}) };
1078
+ js.lastRun = { scheduledFor: attempt.scheduledFor, startedAt: js.lastRun?.startedAt || attempt.startedAt, kind: attemptKind, launched: true, ...adopted, outcome: seen.outcome, ...(seen.error ? { error: seen.error } : {}), ...(seen.note ? { note: seen.note } : {}) };
1030
1079
  if (seen.outcome !== "ended") { if (!jobLockInfo(ws, id)) acquireJobLock(ws, id, { scheduledFor: attempt.scheduledFor, reconciled: true }); } else releaseJobLock(ws, id);
1031
1080
  } else {
1032
1081
  js.lastRun = { scheduledFor: attempt.scheduledFor, startedAt: js.lastRun?.startedAt || attempt.startedAt, kind: attemptKind, launched: false, outcome: "launch-failed", error: clear ? "cleared by the operator after checking by hand" : "no instance found in the scope's roster for the unrecorded attempt" };
@@ -1393,5 +1442,5 @@ export function schedulerStatus(ws, io) {
1393
1442
  const host = readHostState();
1394
1443
  let unit = { installed: false, active: false };
1395
1444
  try { unit = (io?.hostStatus || (() => ({ installed: false, active: false, unavailable: true })))(); } catch (e) { unit = { installed: false, active: false, error: e.message }; }
1396
- return { installed: !!unit.installed, active: !!unit.active, ...(unit.unit ? { unit: unit.unit } : {}), ...(unit.error ? { error: unit.error } : {}), lastTick: host.lastTick || null, maxConcurrent: scheduleCap(reg), triggersMaxConcurrent: reg.triggersMaxConcurrent ?? null, tickIntervalSec: reg.tickIntervalSec, ...(ws ? { workspace: resolve(ws), registered: reg.workspaces.includes(resolve(ws)) } : {}), workspaces: reg.workspaces, live: liveLocks(reg.workspaces.filter((w) => existsSync(w))) };
1445
+ return { installed: !!unit.installed, active: !!unit.active, ...(unit.unit ? { unit: unit.unit } : {}), ...(unit.error ? { error: unit.error } : {}), problems: Array.isArray(unit.problems) ? unit.problems : [], lastTick: host.lastTick || null, maxConcurrent: scheduleCap(reg), triggersMaxConcurrent: reg.triggersMaxConcurrent ?? null, tickIntervalSec: reg.tickIntervalSec, ...(ws ? { workspace: resolve(ws), registered: reg.workspaces.includes(resolve(ws)) } : {}), workspaces: reg.workspaces, live: liveLocks(reg.workspaces.filter((w) => existsSync(w))) };
1397
1446
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * A word of a command line the kernel prints for a person or an agent to paste into a shell. PURE: no
3
+ * I/O and no import, so a module lib/core.mjs imports (lib/launch-preference.mjs) can use the same rule
4
+ * as core, which re-exports both names.
5
+ */
6
+
7
+ /** `s` single-quoted for a POSIX shell. */
8
+ export function shq(s) { return `'${String(s).replace(/'/g, `'\\''`)}'`; }
9
+ /** One word of a command line that a person or an agent pastes into a shell: as it is when it holds
10
+ * only letters, digits and `_./:-`, single-quoted otherwise (an empty string too). The safe set is
11
+ * deliberately small: no `~` (an unquoted leading one expands), no `=` (zsh expands a leading
12
+ * `=word`). */
13
+ export function shellWord(s) { const word = String(s); return /^[A-Za-z0-9_.\/:-]+$/.test(word) ? word : shq(word); }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * `oats soul launch set|remove` (feature `soul-launch`, awebai/oats#990; docs/desktop-cli-api.md
3
+ * "`oats soul launch`"): the supported writer of oats-local.yaml `souls.launch`, a soul's launch preference
4
+ * on this machine (lib/launch-preference.mjs). It writes the key a soul has (soulKeyOf), so it cannot
5
+ * write a key that names no soul; `remove` also takes the exact text of a key in the file, the remedy
6
+ * for a key that names none, and that form works when the workspace's souls cannot be read.
7
+ * The file is rewritten through the path `oats teams` writes it by (lib/local-edit.mjs): one entry set
8
+ * or deleted in the parsed document, every other entry kept with its value and its comments.
9
+ */
10
+ import YAML from "yaml";
11
+ import { oatsError } from "./errors.mjs";
12
+ import { editLocal, readLocal } from "./local-edit.mjs";
13
+ import { LOCAL_FILE, launchKeyAt, launchKeysUnmatched, launchLayers, launchValueOf } from "./launch-preference.mjs";
14
+ import { findSoulEntry, qualifiedSoulName, soulCandidates, soulsOffered } from "./instance-resolution.mjs";
15
+ import { soulKeyOf } from "./teams.mjs";
16
+ import { LAUNCH_HARNESSES, launchConfigsAt, launchReportFor } from "./core.mjs";
17
+
18
+ export const SOUL_LAUNCH_API = 1;
19
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
20
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
21
+ function fail(code, message, details) { const e = oatsError(code, message, details); e.details = details; return e; }
22
+ const isRefusal = (e) => typeof e?.code === "string" && e.code.startsWith("E_");
23
+ const launchOf = (local) => (isObject(local?.souls?.launch) ? local.souls.launch : {});
24
+ const NAMED = 10;
25
+ const named = (list) => (list.length > NAMED ? [...list.slice(0, NAMED), `and ${list.length - NAMED} more`] : list).join(", ");
26
+
27
+ /** The entry `set` writes, from its flags: a launch configuration's name (`none` included), or the inline
28
+ * `{ harness, model? }`. Exactly one of `launchConfig` and `harness`; `model` only with `harness`. */
29
+ export function soulLaunchValue({ launchConfig, harness, model } = {}) {
30
+ if (launchConfig !== undefined && harness !== undefined) throw fail("E_BAD_ARGS", "oats soul launch set takes --launch-config <name>|none or --harness <h>, not both", { flags: ["--launch-config", "--harness"] });
31
+ if (launchConfig === undefined && harness === undefined) throw fail("E_BAD_ARGS", `oats soul launch set needs what to pin the soul to: --launch-config <name>|none, or --harness ${LAUNCH_HARNESSES.join("|")} [--model <id>]`, {});
32
+ if (launchConfig !== undefined) {
33
+ if (model !== undefined) throw fail("E_BAD_ARGS", "--model goes with --harness: a launch configuration carries its own model (oats launch-config set)", { flags: ["--launch-config", "--model"] });
34
+ return launchConfig;
35
+ }
36
+ if (!LAUNCH_HARNESSES.includes(harness)) throw fail("E_BAD_ARGS", `--harness must be one of ${LAUNCH_HARNESSES.join(", ")} (got ${JSON.stringify(harness)})`, { harness });
37
+ if (model !== undefined && !/^[^\s-][^\s]*$/.test(model)) throw fail("E_BAD_ARGS", `--model takes a model id: no whitespace, and no leading "-" (got ${JSON.stringify(model)})`, { model });
38
+ return { harness, ...(model !== undefined ? { model } : {}) };
39
+ }
40
+
41
+ /** Set or delete `souls.launch.<key>` in the document, and nothing else. A map left empty is removed
42
+ * (`souls.launch`, then `souls`). An entry that stays keeps its own key node, so its quoting and comment. */
43
+ function applyEntry(doc, key, value) {
44
+ if (value === null) {
45
+ doc.deleteIn(["souls", "launch", key]);
46
+ for (const path of [["souls", "launch"], ["souls"]]) {
47
+ const node = doc.getIn(path);
48
+ if (YAML.isMap(node) && node.items.length === 0) doc.deleteIn(path);
49
+ }
50
+ return;
51
+ }
52
+ // A key that holds no map (`souls:` with nothing under it) is replaced by the map the entry needs.
53
+ for (const path of [["souls"], ["souls", "launch"]]) if (doc.hasIn(path) && !YAML.isMap(doc.getIn(path))) doc.deleteIn(path);
54
+ doc.setIn(["souls", "launch", key], typeof value === "string" ? value : doc.createNode(value));
55
+ }
56
+ /** The local value this edit must read back as: `before` with the one entry set or deleted (value null). */
57
+ function expectedAfter(before, key, value) {
58
+ const next = structuredClone(before);
59
+ if (value === null) {
60
+ delete next.souls.launch[key];
61
+ if (Object.keys(next.souls.launch).length === 0) delete next.souls.launch;
62
+ if (Object.keys(next.souls).length === 0) delete next.souls;
63
+ return next;
64
+ }
65
+ if (!isObject(next.souls)) next.souls = {};
66
+ if (!isObject(next.souls.launch)) next.souls.launch = {};
67
+ next.souls.launch[key] = structuredClone(value);
68
+ return next;
69
+ }
70
+ /** Where two values differ, as JSON pointers (never the values: this file holds host paths). A map whose
71
+ * keys are the same in another order differs at the map. */
72
+ function differences(a, b, path = "", out = []) {
73
+ if (!isObject(a) || !isObject(b)) { if (!same(a, b)) out.push(path || "/"); return out; }
74
+ const ka = Object.keys(a), kb = Object.keys(b);
75
+ if (!same(ka, kb)) {
76
+ const stray = [...ka.filter((k) => !Object.hasOwn(b, k)), ...kb.filter((k) => !Object.hasOwn(a, k))];
77
+ if (stray.length) for (const k of stray) out.push(`${path}/${String(k).replace(/~/g, "~0").replace(/\//g, "~1")}`);
78
+ else out.push(path || "/");
79
+ }
80
+ for (const k of ka) if (Object.hasOwn(b, k)) differences(a[k], b[k], `${path}/${String(k).replace(/~/g, "~0").replace(/\//g, "~1")}`, out);
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * `oats soul launch set|remove`. `ctx`: { deployment, localPath }. `name`: the command's argument (a soul
86
+ * as a spawn names it, "*", or for `remove` the exact text of a key in the file). `value`: soulLaunchValue's
87
+ * (set only). `plan`: every check, nothing written. `readSouls()` reads the workspace → its discovery
88
+ * (discoverOrStandalone), and throws that read's own error.
89
+ * → the `soulLaunchApi: 1` answer. Every refusal is thrown before a byte of the file changes.
90
+ */
91
+ export async function soulLaunch(ctx, { action, name, value = null, plan = false }, { readSouls }) {
92
+ const star = name === "*";
93
+ // `remove` first tries its argument as the exact text of a key the file has now: that form needs no
94
+ // read of the workspace, so it goes on (and says so: `unread`) when the souls cannot be read.
95
+ const now = action === "remove" ? launchOf(readLocal(ctx.localPath).local) : {};
96
+ const exact = action === "remove" && Object.hasOwn(now, name);
97
+ if (action === "remove" && star && !exact) throw unknownEntry("*", now);
98
+ let discovery = null, unread = null;
99
+ try { discovery = await readSouls(); }
100
+ catch (e) { if (!exact || !isRefusal(e)) throw e; unread = { code: e.code, message: String(e.message) }; }
101
+ const entry = star || exact ? null : findSoulEntry(discovery, name);
102
+ const key = entry ? soulKeyOf(entry) : name;
103
+
104
+ let before = null;
105
+ const result = editLocal(ctx, { verb: `oats soul launch ${action}`, plan }, ({ doc, local }) => {
106
+ const entries = launchOf(local);
107
+ before = Object.hasOwn(entries, key) ? launchValueOf(entries[key]) : null;
108
+ if (action === "remove") { if (!Object.hasOwn(entries, key)) throw unknownEntry(key, entries); }
109
+ else {
110
+ // The same fact a spawn reports, said before the file holds it.
111
+ const configs = isObject(local?.["launch-configs"]) ? local["launch-configs"] : {};
112
+ if (typeof value === "string" && value !== "none" && !Object.hasOwn(configs, value)) {
113
+ throw fail("E_LAUNCH_CONFIG_UNKNOWN", `--launch-config ${JSON.stringify(value)} is no launch configuration ${LOCAL_FILE} declares (launch-configs:); oats launch-config list shows what is; nothing was written`, { name: value, from: star ? "local-default" : "local", at: launchKeyAt(key) });
114
+ }
115
+ if (Object.hasOwn(entries, key) && same(before, launchValueOf(value))) return null;
116
+ }
117
+ const written = action === "remove" ? null : value;
118
+ applyEntry(doc, key, written);
119
+ const expected = expectedAfter(local, key, written);
120
+ return { check: (next) => {
121
+ const differ = differences(expected, next);
122
+ if (differ.length) throw fail("E_WORKSPACE_SCHEMA", `the rewritten ${LOCAL_FILE} would not read back as this edit of souls.launch and nothing else (it differs at ${named(differ)}); nothing was written`, { path: ctx.localPath, reason: "read-back", differs: differ });
123
+ } };
124
+ });
125
+
126
+ const local = result.local;
127
+ const after = Object.hasOwn(launchOf(local), key) ? launchValueOf(launchOf(local)[key]) : null;
128
+ const answer = { soulLaunchApi: SOUL_LAUNCH_API, action, plan, key, souls: null, level: ctx.deployment, file: ctx.localPath, before, after, changed: result.changed, launch: null, unmatched: null, unread };
129
+ if (unread) return answer;
130
+ // What the entry applies to: every offered soul with that key (two members' souls of one bare name share it).
131
+ const applies = star ? [] : soulCandidates(discovery).map((c) => c.entry).filter((e) => soulKeyOf(e) === key)
132
+ .sort((a, b) => (qualifiedSoulName(a) < qualifiedSoulName(b) ? -1 : qualifiedSoulName(a) > qualifiedSoulName(b) ? 1 : 0));
133
+ if (!star) answer.souls = applies.map(qualifiedSoulName);
134
+ // The soul the command named; a key given by its exact text names the first soul it applies to.
135
+ const subject = entry ?? applies[0] ?? null;
136
+ const offered = soulsOffered(discovery);
137
+ if (subject) {
138
+ let launchConfigs = {};
139
+ try { launchConfigs = launchConfigsAt(ctx.deployment); } catch { launchConfigs = {}; }
140
+ // As a spawn of it would decide: a soul left on the fall-through beside a key that names no soul
141
+ // carries that refusal as the report's problem.
142
+ answer.launch = launchReportFor({ layers: launchLayers({ definition: subject.definition, entry: subject, key, local, offered }), launchConfigs, contextDir: ctx.deployment });
143
+ }
144
+ answer.unmatched = launchKeysUnmatched({ local, offered }).unmatched;
145
+ return answer;
146
+ }
147
+
148
+ /** E_LAUNCH_PREFERENCE_UNKNOWN: `remove` of an entry the file does not have. Never "done": a mistyped
149
+ * remove must not leave the entry its operator believes is gone. */
150
+ function unknownEntry(key, entries) {
151
+ const keys = Object.keys(entries).sort();
152
+ return fail("E_LAUNCH_PREFERENCE_UNKNOWN", `${LOCAL_FILE} souls.launch has no entry ${JSON.stringify(key)} (${keys.length ? `it has ${named(keys.map((k) => JSON.stringify(k)))}` : "it has none"}); nothing was written`, { key, keys });
153
+ }
@@ -0,0 +1,62 @@
1
+ /** The one rule for a node path that is written into something that outlives
2
+ * the process (a unit, a harness's settings): a path that survives an upgrade
3
+ * of Node. The host timer's unit (lib/schedule-host.mjs) and OATS_NODE_BIN,
4
+ * which every hook, provider check and dispatched command receives, are both
5
+ * this rule's answer. It imports nothing of the kernel, so any module can. */
6
+ import { realpathSync } from "node:fs";
7
+ import { isAbsolute, join, resolve, sep } from "node:path";
8
+
9
+ /** A versioned Homebrew keg: <prefix>/Cellar/<formula>/<version>/…, gone at the next upgrade. */
10
+ const KEG = /^(.*)\/Cellar\/([^/]+)\/([^/]+)\//;
11
+
12
+ /** The installer's PATH entries a unit may carry. Dropped: entries inside an
13
+ * OATS instance home (an instance's `.oats/bin`, anything under
14
+ * `instanceHome`), entries inside a versioned Homebrew keg, and relative or
15
+ * empty entries. An entry missing today is kept: it may exist when the tick
16
+ * runs, and status reports it while it does not. */
17
+ export function unitPathEntries(envPath, { instanceHome = process.env.OATS_INSTANCE_HOME } = {}) {
18
+ const home = instanceHome && isAbsolute(instanceHome) ? resolve(instanceHome) : null;
19
+ const hazard = (entry) => {
20
+ if (!entry || !isAbsolute(entry)) return true;
21
+ const segments = entry.split(sep);
22
+ if (segments.some((s, i) => s === ".oats" && segments[i + 1] === "bin")) return true;
23
+ if (home && (resolve(entry) === home || resolve(entry).startsWith(home + sep))) return true;
24
+ return KEG.test(entry.endsWith("/") ? entry : `${entry}/`);
25
+ };
26
+ return String(envPath || "").split(":").filter((entry) => !hazard(entry));
27
+ }
28
+
29
+ function realpathOrNull(p) { try { return realpathSync(p); } catch { return null; } }
30
+ /** A node path that survives a Homebrew upgrade. A keg's
31
+ * `<prefix>/opt/<formula>/bin/node` when it is this node, else the first
32
+ * `node` on the filtered PATH that is this node, else `execPath` with a
33
+ * warning that the path is not stable. The warning states the fact; the
34
+ * caller words what it loses (`consequence`) and what to do after installing
35
+ * a stable node (`remedy`). */
36
+ export function stableNode({ execPath = process.execPath, envPath = process.env.PATH || "", instanceHome = process.env.OATS_INSTANCE_HOME, consequence, remedy } = {}) {
37
+ const real = realpathOrNull(execPath);
38
+ const keg = real && KEG.exec(real);
39
+ if (keg) {
40
+ const opt = join(keg[1], "opt", keg[2], "bin", "node");
41
+ if (realpathOrNull(opt) === real) return { node: opt };
42
+ }
43
+ for (const entry of unitPathEntries(envPath, { instanceHome })) {
44
+ const candidate = join(entry, "node");
45
+ if (real && realpathOrNull(candidate) === real) return { node: candidate };
46
+ }
47
+ return { node: execPath, warning: `the node path ${execPath} is not stable (no Homebrew opt link and no node on PATH resolves to it)${consequence ? `: ${consequence}` : ""}${remedy ? `; install a node with a stable path and ${remedy}` : ""}` };
48
+ }
49
+
50
+ let kernel = null;
51
+ /** The rule's answer for the node running this kernel, on the kernel's own
52
+ * PATH: `node` is OATS_NODE_BIN, and `warning` (the third case only) is what a
53
+ * spawn and a start say, worded for a home's hooks. The rule reads the file
54
+ * system, so it is computed once for the node, PATH and instance home this
55
+ * process runs with, not once per hook. */
56
+ export function kernelNode() {
57
+ const key = [process.execPath, process.env.PATH || "", process.env.OATS_INSTANCE_HOME || ""].join("\0");
58
+ if (kernel?.key !== key) {
59
+ kernel = { key, answer: stableNode({ consequence: "what this home's hooks record with it stops working when it goes away", remedy: "restart the instance" }) };
60
+ }
61
+ return kernel.answer;
62
+ }
@@ -0,0 +1,39 @@
1
+ /** System tools: programs the kernel runs from the system's own directories, never from the
2
+ * caller's PATH. A job, a shell or an instance may have changed PATH; what a system tool does
3
+ * (read a process's start, start the OATS tmux server in its own scope) must not depend on it. */
4
+ import { accessSync, constants, statSync } from "node:fs";
5
+ import { isAbsolute, join } from "node:path";
6
+
7
+ /** Where a system tool is looked for, in order. */
8
+ export const SYSTEM_TOOL_DIRS = Object.freeze(["/usr/bin", "/bin"]);
9
+
10
+ /** The directories a system tool is looked for in → { dirs } | { reason }. SYSTEM_TOOL_DIRS, or for a
11
+ * test only, OATS_TEST_SYSTEM_TOOL_DIRS: absolute directories separated by `:`. A seam with any other
12
+ * value names no tool at all, never a PATH-like lookup. */
13
+ export function systemToolDirs() {
14
+ const seam = process.env.OATS_TEST_SYSTEM_TOOL_DIRS;
15
+ if (seam === undefined) return { dirs: SYSTEM_TOOL_DIRS };
16
+ const dirs = seam.split(":");
17
+ if (dirs.some((dir) => !isAbsolute(dir))) return { reason: `OATS_TEST_SYSTEM_TOOL_DIRS is ${JSON.stringify(seam)}, not absolute directories` };
18
+ return { dirs };
19
+ }
20
+
21
+ /** `name` in the system directories (`dirs`, else systemToolDirs) → { file } (the first regular
22
+ * executable file, an absolute path) or { reason } (none, and where it looked). Nothing is run. */
23
+ export function systemTool(name, { dirs } = {}) {
24
+ if (typeof name !== "string" || !/^[A-Za-z0-9._+-]+$/.test(name) || name === "." || name === "..") return { reason: `${JSON.stringify(name)} is not a tool name` };
25
+ if (dirs === undefined) {
26
+ const where = systemToolDirs();
27
+ if (where.reason) return { reason: where.reason };
28
+ dirs = where.dirs;
29
+ }
30
+ for (const dir of dirs) {
31
+ const file = join(dir, name);
32
+ try {
33
+ if (!statSync(file).isFile()) continue;
34
+ accessSync(file, constants.X_OK);
35
+ return { file };
36
+ } catch { /* not here */ }
37
+ }
38
+ return { reason: `no executable ${name} in ${dirs.join(", ")}` };
39
+ }