@oathe/oathe 0.4.1 → 0.4.4

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.
package/bin/oathe.mjs CHANGED
@@ -8,7 +8,7 @@ import { parseArgs } from 'node:util';
8
8
  import { isTraceSubjectSql } from '../src/statements.mjs';
9
9
  import { byName, launchable, verifierCapable } from '../src/harnesses/catalog.mjs';
10
10
 
11
- const VERBS = ['init', ...launchable(), 'claim', 'ls', 'note', 'amend', 'done', 'verify', 'trace', 'notch', 'yield', 'config', 'doctor', 'uninstall', 'status', 'version', 'hook', 'mcp'];
11
+ const VERBS = ['init', ...launchable(), 'claim', 'ls', 'note', 'amend', 'done', 'verify', 'trace', 'notch', 'yield', 'config', 'doctor', 'uninstall', 'status', 'version', 'update', 'hook', 'mcp'];
12
12
 
13
13
  const USAGE = `usage: oathe <verb> [args]
14
14
 
@@ -26,7 +26,8 @@ ${launchable().map((name) => ` ${name.padEnd(6)} [--hermetic] [args…] ${byNa
26
26
  yield <task-id> <note> yield: the task goes back on the board, unowned
27
27
  doctor [--surface] verify every managed surface (--surface: the resolution report only)
28
28
  status the substrate half of doctor
29
- version the package version (upgrade: npm i -g @oathe/oathe@latest && oathe init)
29
+ version the package version on PATH
30
+ update [--yes] [--harness a,b] the upgrade as one verb: npm i -g @oathe/oathe@latest through this node's npm, then init through the new bin
30
31
  config <key> [value] [--global] read or write a config key (workspace scope by default)
31
32
  uninstall [--purge-db] remove exactly what init recorded (the database stays put)
32
33
  hook <name> · mcp internal: the plugin's hook/server entry points (bin-addressed)
@@ -127,6 +128,14 @@ const handlers = {
127
128
  process.stdout.write(` substrate: db up, ddl ${s.ddl_applied}/${s.ddl_expected} applied `
128
129
  + `(source: ${s.ddl_source}), yield cause ${s.yield_cause_registered ? 'registered' : 'MISSING'}\n`);
129
130
  process.stdout.write(` principal: ${result.principal.principal_id} (${result.principal.role})\n`);
131
+ // The notch is a surface the person looks at: its state is said from launchd, and a dead
132
+ // one is attention, never folded into ok.
133
+ const glass = result.actions.find((a) => a.harness === 'notch' && /^notch-(running|not-running)$/.test(a.action));
134
+ if (glass) {
135
+ process.stdout.write(glass.action === 'notch-running'
136
+ ? ` notch: running (pid ${glass.pid})\n`
137
+ : ` notch: NOT RUNNING — launchd: ${glass.detail} (${glass.label}); run \`oathe init\` again, or \`oathe doctor\`\n`);
138
+ }
130
139
  // The surface note lives here, once: the screen showed only the row.
131
140
  for (const surface of result.surfaces.filter((x) => x.detected)) {
132
141
  process.stdout.write(`\n${surface.displayName} — detected; nothing to wire:\n${surface.steps.split('\n').map((l) => ` ${l}`).join('\n')}\n`);
@@ -137,7 +146,7 @@ const handlers = {
137
146
  // The harness itself is the way in — the plugin rides every session (the launcher is the notch's).
138
147
  const bins = launchable().map((name) => byName(name).launch.bin);
139
148
  process.stdout.write(`\n Next: ${B}${bins.slice(0, -1).join(', ')} or ${bins.at(-1)}${R} in any project — the board rides every session.\n`);
140
- summary('init', 'ok');
149
+ summary('init', glass?.action === 'notch-not-running' ? 'attention' : 'ok');
141
150
  },
142
151
 
143
152
 
@@ -540,6 +549,21 @@ const handlers = {
540
549
  summary('version', 'ok');
541
550
  },
542
551
 
552
+ async update(argv) {
553
+ const { values } = parseFlags('update', {
554
+ args: argv, options: { yes: { type: 'boolean', default: false }, harness: { type: 'string' } }, allowPositionals: false,
555
+ });
556
+ const [{ runUpdate }, { buildPaths }] = await Promise.all([import('../src/update.mjs'), import('../src/paths.mjs')]);
557
+ const initArgs = [...(values.yes ? ['--yes'] : []), ...(values.harness ? ['--harness', values.harness] : [])];
558
+ const out = runUpdate({ packageRoot: buildPaths(process.env).packageRoot, args: initArgs });
559
+ if (out.initStatus !== 0) {
560
+ const e = new Error(`update installed ${out.after} but the new bin's init exited ${out.initStatus} — read its output above and run \`oathe init\` again`);
561
+ e.code = 'OATHE_UPDATE_INIT_FAILED';
562
+ throw e;
563
+ }
564
+ summary('update', out.notch && out.notch.pid === null ? 'attention' : 'ok');
565
+ },
566
+
543
567
  async doctor(argv) {
544
568
  const { values } = parseFlags('doctor', {
545
569
  args: argv, options: { surface: { type: 'boolean', default: false } }, allowPositionals: false,
@@ -6,7 +6,7 @@
6
6
  <key>CFBundleName</key><string>Oathe Notch</string>
7
7
  <key>CFBundleExecutable</key><string>OatheNotch</string>
8
8
  <key>CFBundlePackageType</key><string>APPL</string>
9
- <key>CFBundleShortVersionString</key><string>0.4.1</string>
9
+ <key>CFBundleShortVersionString</key><string>0.4.4</string>
10
10
  <key>LSMinimumSystemVersion</key><string>14.0</string>
11
11
  <key>LSUIElement</key><true/>
12
12
  </dict>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oathe/oathe",
3
- "version": "0.4.1",
3
+ "version": "0.4.4",
4
4
  "description": "Auto save and verified completion for AI coding agents — a durable local task board that outlives any one session. D0 preview.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -12,8 +12,8 @@
12
12
  "scripts": {
13
13
  "preinstall": "node bin/node-floor.mjs",
14
14
  "test": "npm run test:unit && npm run test:heavy",
15
- "test:unit": "node --test tests/activation.test.mjs tests/atif.test.mjs tests/blocks.test.mjs tests/board-render.test.mjs tests/breach-digest.test.mjs tests/config.test.mjs tests/cursor-harness.test.mjs tests/discharge.test.mjs tests/evidence-budget.test.mjs tests/fslock.test.mjs tests/harness-contract.test.mjs tests/harness-docs.test.mjs tests/harness-docs-drift.test.mjs tests/harbor-conformance.test.mjs tests/harness.test.mjs tests/notch-frame.test.mjs tests/home.test.mjs tests/horizon-census.test.mjs tests/manifest.test.mjs tests/mcp-connection.test.mjs tests/node-floor.test.mjs tests/notch.test.mjs tests/packaging.test.mjs tests/paths.test.mjs tests/registry.test.mjs tests/runtime-provider.test.mjs tests/sessions.test.mjs tests/setup.test.mjs tests/speaker.test.mjs tests/successor.test.mjs tests/trace-census.test.mjs tests/trace-fixture-tools.test.mjs tests/trace-fixtures.test.mjs tests/traces.test.mjs tests/ux-contract.test.mjs tests/verify-dispatch.test.mjs tests/welcome.test.mjs tests/workspace-resolver.test.mjs tests/workspace.test.mjs",
16
- "test:heavy": "node --test --test-concurrency=2 tests/amend.test.mjs tests/cli.test.mjs tests/harness-install-contract.test.mjs tests/harness-live-contract.test.mjs tests/init.test.mjs tests/integration.test.mjs tests/launch.test.mjs tests/lineage.test.mjs tests/oathe-tools.test.mjs tests/pager.test.mjs tests/plugin.test.mjs tests/session-host.test.mjs tests/simple-cage.test.mjs tests/sql-acceptance-lane.test.mjs tests/substrate.test.mjs tests/vendor-scripts.test.mjs tests/verifier.test.mjs",
15
+ "test:unit": "node --test tests/exec-results.test.mjs tests/activation.test.mjs tests/atif.test.mjs tests/blocks.test.mjs tests/board-render.test.mjs tests/breach-digest.test.mjs tests/config.test.mjs tests/cursor-harness.test.mjs tests/discharge.test.mjs tests/evidence-budget.test.mjs tests/fslock.test.mjs tests/harness-contract.test.mjs tests/harness-docs.test.mjs tests/harness-docs-drift.test.mjs tests/harbor-conformance.test.mjs tests/harness.test.mjs tests/notch-frame.test.mjs tests/home.test.mjs tests/horizon-census.test.mjs tests/manifest.test.mjs tests/mcp-connection.test.mjs tests/node-floor.test.mjs tests/notch.test.mjs tests/packaging.test.mjs tests/paths.test.mjs tests/registry.test.mjs tests/runtime-provider.test.mjs tests/sessions.test.mjs tests/setup.test.mjs tests/speaker.test.mjs tests/successor.test.mjs tests/trace-census.test.mjs tests/trace-fixture-tools.test.mjs tests/trace-fixtures.test.mjs tests/update.test.mjs tests/traces.test.mjs tests/ux-contract.test.mjs tests/verify-dispatch.test.mjs tests/welcome.test.mjs tests/workspace-resolver.test.mjs tests/workspace.test.mjs",
16
+ "test:heavy": "node --test --test-concurrency=2 tests/amend.test.mjs tests/cli.test.mjs tests/harness-install-contract.test.mjs tests/harness-live-contract.test.mjs tests/init.test.mjs tests/integration.test.mjs tests/launch.test.mjs tests/lineage.test.mjs tests/oathe-tools.test.mjs tests/pager.test.mjs tests/plugin.test.mjs tests/session-host.test.mjs tests/simple-cage.test.mjs tests/sql-acceptance-lane.test.mjs tests/substrate.test.mjs tests/vendor-scripts.test.mjs tests/verifier.test.mjs tests/notch-launchd.test.mjs",
17
17
  "lint": "npx -y eslint@10.9.1 .",
18
18
  "pack:dry-run": "npm pack --dry-run --ignore-scripts",
19
19
  "prepack": "node scripts/pack-notch.mjs",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "oathe",
3
3
  "displayName": "Oathe",
4
- "version": "0.4.1",
4
+ "version": "0.4.4",
5
5
  "description": "Claims are speech acts: your session opens on this folder's board, records progress as statements, and yields what it cannot finish. Horizons move only by deliberate acts — never by session liveness.",
6
6
  "author": {
7
7
  "name": "Oathe"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oathe",
3
- "version": "0.4.1",
3
+ "version": "0.4.4",
4
4
  "description": "Claims are speech acts: your session opens on this folder's board, records progress as statements, and yields what it cannot finish. Horizons move only by deliberate acts — never by session liveness.",
5
5
  "author": {
6
6
  "name": "Oathe"
package/src/config.mjs CHANGED
@@ -74,6 +74,12 @@ const KEYS = Object.freeze({
74
74
  // The notch feed's drift guard: `oathe notch --serve` recomputes a frame this often even
75
75
  // when no wire event arrives (the push path is pg_notify; this is the belt to its braces).
76
76
  notchHeartbeatSeconds: { default: 300, env: 'OATHE_NOTCH_HEARTBEAT_SECONDS', check: positiveInt },
77
+ // The notch restart budget: launchd's bootout returns before the old job is gone, and a
78
+ // bootstrap in that window is refused ("5: Input/output error") — init re-tries inside
79
+ // this budget, asking this often, and says NOT RUNNING past it (the 0.4.3 update left
80
+ // every re-wired notch unloaded because the one attempt's refusal went unread).
81
+ notchRestartSeconds: { default: 10, env: 'OATHE_NOTCH_RESTART_SECONDS', check: positiveInt },
82
+ notchRestartPollMs: { default: 100, env: 'OATHE_NOTCH_RESTART_POLL_MS', check: positiveInt },
77
83
  });
78
84
 
79
85
  function nonEmptyString(v) {
package/src/doctor.mjs CHANGED
@@ -8,6 +8,8 @@ import path from 'node:path';
8
8
  import { buildContext, packageVersion } from './context.mjs';
9
9
  import { FencedBlock, FENCE_STYLES, JsonEntries } from './blocks.mjs';
10
10
  import { sha256Hex } from './manifest.mjs';
11
+ import { launchdJob } from './notch.mjs';
12
+ import { defaultExec } from './harnesses/harness.mjs';
11
13
 
12
14
  function verifyJsonRow(row) {
13
15
  if (!fs.existsSync(row.file)) return 'file-missing';
@@ -66,9 +68,12 @@ export function traceStatusOf(error) {
66
68
  // A LaunchAgent is a whole-file write: present and byte-identical to what init recorded, or
67
69
  // user-edited; gone is gone. (The notch ships with the package — every darwin manifest
68
70
  // carries this row now.)
69
- function verifyLaunchAgentRow(row) {
71
+ // …and "ok" means launchd RUNS it: an agent on disk that launchd dropped (the asynchronous
72
+ // bootout race, a bootout by hand) is the not-running notch the person is staring at.
73
+ function verifyLaunchAgentRow(row, { launchd }) {
70
74
  if (!fs.existsSync(row.file)) return 'file-missing';
71
- return sha256Hex(fs.readFileSync(row.file, 'utf8')) === row.sha256 ? 'ok' : 'user-edited';
75
+ if (sha256Hex(fs.readFileSync(row.file, 'utf8')) !== row.sha256) return 'user-edited';
76
+ return launchd(path.basename(row.file, '.plist')).pid !== null ? 'ok' : 'not-running';
72
77
  }
73
78
 
74
79
  // The materialized notch copy: the row's detail names the binary inside the key dir; ok
@@ -115,7 +120,8 @@ export async function runSurfaceReport({ env = process.env, cwd = () => process.
115
120
  }
116
121
 
117
122
  /** @returns {Promise<{rows: object[], substrate: object, plugin: {resolves: boolean, detail: string|null}}>} */
118
- export async function runDoctor({ env = process.env } = {}) {
123
+ export async function runDoctor({ env = process.env, exec = defaultExec } = {}) {
124
+ const launchd = (label) => launchdJob({ label, exec });
119
125
  const ctx = buildContext({ env });
120
126
  const { manifest, substrate, paths, harnesses } = ctx;
121
127
  try {
@@ -130,7 +136,7 @@ export async function runDoctor({ env = process.env } = {}) {
130
136
  file: row.file,
131
137
  kind: row.kind,
132
138
  block_version: row.block_version,
133
- status: (VERIFIERS[row.kind] ?? (() => 'unknown-kind'))(row),
139
+ status: (VERIFIERS[row.kind] ?? (() => 'unknown-kind'))(row, { launchd }),
134
140
  }));
135
141
  // The trace-contract monitor: both vendors disclaim transcript-schema stability, so the
136
142
  // doctor validates the NEWEST live record in each engine's store against docs/traces.md and
@@ -195,7 +195,7 @@ export class CodexHarness extends Harness {
195
195
  // marketplace "already added from a different source". Re-register from this root: the
196
196
  // undo the manifest already records, then the add again, proof-checked below.
197
197
  if (result.status !== 0 && /already added from a different source/.test(result.stderr)) {
198
- this.exec.run('codex', reg.undo);
198
+ this.exec.run('codex', reg.undo); // result unread: the add that follows is the proof — its failure is the typed refusal below, and the config's proof string is checked after it
199
199
  result = this.exec.run('codex', reg.add);
200
200
  }
201
201
  if (result.status !== 0) {
package/src/notch.mjs CHANGED
@@ -95,7 +95,22 @@ export function materializeNotchApp({ home, appBinary, version }) {
95
95
  }
96
96
 
97
97
  /** @returns {object[]} action rows for the init report; [] only off-darwin */
98
- export function wireNotch({ home, manifest, config, version, exec = defaultExec, uid = process.getuid(), packageRoot }) {
98
+ /** launchd's word on one label: loaded, and the pid it runs — the only "running" oathe reports. */
99
+ export function launchdJob({ label, exec = defaultExec, uid = process.getuid() }) {
100
+ const r = exec.run('launchctl', ['print', `gui/${uid}/${label}`]);
101
+ const pid = r.status === 0 ? Number(/^\s*pid = (\d+)/m.exec(r.stdout)?.[1] ?? NaN) : NaN;
102
+ return { label, loaded: r.status === 0, pid: Number.isFinite(pid) ? pid : null };
103
+ }
104
+
105
+ /** The same word for this home's notch agent. */
106
+ export function notchStatus({ home, exec = defaultExec, uid = process.getuid() }) {
107
+ return launchdJob({ label: notchLabel(home), exec, uid });
108
+ }
109
+
110
+ /** A synchronous pause — init is a straight line, and launchd is asked, not raced. */
111
+ const blockingSleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
112
+
113
+ export function wireNotch({ home, manifest, config, version, exec = defaultExec, uid = process.getuid(), packageRoot, sleep = blockingSleep }) {
99
114
  if (process.platform !== 'darwin') return [];
100
115
  const source = config.get('notchApp') ?? packagedNotchApp(packageRoot);
101
116
  if (!fs.existsSync(source)) return [{ action: 'notch-binary-missing', file: source }];
@@ -119,7 +134,7 @@ export function wireNotch({ home, manifest, config, version, exec = defaultExec,
119
134
  // out and removed here — otherwise the old job lingers loaded beside the new one.
120
135
  for (const row of manifest.removeWhere((r) => r.kind === 'launch-agent' || r.kind === 'notch-app')) {
121
136
  if (row.kind === 'launch-agent' && row.file !== file) {
122
- exec.run('launchctl', ['bootout', `gui/${uid}/${path.basename(row.file, '.plist')}`]);
137
+ exec.run('launchctl', ['bootout', `gui/${uid}/${path.basename(row.file, '.plist')}`]); // result unread: a legacy label that is not loaded answers 'Could not find service' — nothing to do either way
123
138
  if (fs.existsSync(row.file)) fs.rmSync(row.file);
124
139
  }
125
140
  }
@@ -134,21 +149,43 @@ export function wireNotch({ home, manifest, config, version, exec = defaultExec,
134
149
 
135
150
  // A re-run is the restart: bootout is allowed to fail (not loaded), bootstrap must land.
136
151
  // Prune stale keys BETWEEN the two — launchd is off the old copy, the new one not yet up.
137
- exec.run('launchctl', ['bootout', `gui/${uid}/${label}`]);
152
+ exec.run('launchctl', ['bootout', `gui/${uid}/${label}`]); // result unread: a first install has no job to boot out; whether the OLD job is gone is asked below, by retrying bootstrap until launchd takes the new one
138
153
  for (const key of fs.readdirSync(materializedNotchRoot(home))) {
139
154
  const stale = path.join(materializedNotchRoot(home), key);
140
155
  if (stale !== app.dir) fs.rmSync(stale, { recursive: true, force: true });
141
156
  }
142
- exec.run('launchctl', ['bootstrap', `gui/${uid}`, file]);
143
- return [{ action: 'launch-agent-written', file }];
157
+ // bootout is asynchronous: launchd answers before the old job is torn down, and a
158
+ // bootstrap inside that window is refused (5: Input/output error). Ask again inside the
159
+ // budget; then confirm from launchd itself that the job has a pid. Past the budget the
160
+ // row says NOT RUNNING with launchd's last word — a silent "written" over a dead notch
161
+ // is what shipped in 0.4.3.
162
+ const deadline = Date.now() + config.get('notchRestartSeconds') * 1000;
163
+ // A poll never sleeps past the deadline — the budget is the budget (Greptile P1 on #34).
164
+ const poll = () => Math.max(0, Math.min(config.get('notchRestartPollMs'), deadline - Date.now()));
165
+ let last = exec.run('launchctl', ['bootstrap', `gui/${uid}`, file]);
166
+ while (last.status !== 0 && Date.now() < deadline) {
167
+ sleep(poll());
168
+ last = exec.run('launchctl', ['bootstrap', `gui/${uid}`, file]);
169
+ }
170
+ let status = notchStatus({ home, exec, uid });
171
+ while (last.status === 0 && status.pid === null && Date.now() < deadline) {
172
+ sleep(poll());
173
+ status = notchStatus({ home, exec, uid });
174
+ }
175
+ const outcome = status.pid !== null
176
+ ? { action: 'notch-running', pid: status.pid, label }
177
+ : { action: 'notch-not-running', file, label, detail: lastLine(last.stderr) || (status.loaded ? 'loaded, no pid yet' : 'not loaded') };
178
+ return [{ action: 'launch-agent-written', file }, outcome];
144
179
  }
145
180
 
181
+ const lastLine = (text) => String(text ?? '').trim().split('\n').filter((l) => l && !/^Try re-running/.test(l)).at(-1) ?? '';
182
+
146
183
  /** @returns {object[]} action rows for the uninstall report */
147
184
  export function unwireNotch({ manifest, exec = defaultExec, uid = process.getuid() }) {
148
185
  const actions = [];
149
186
  for (const row of manifest.removeWhere((r) => r.kind === 'launch-agent')) {
150
187
  // The label rides the recorded file name — unwire boots out exactly what wire named.
151
- exec.run('launchctl', ['bootout', `gui/${uid}/${path.basename(row.file, '.plist')}`]);
188
+ exec.run('launchctl', ['bootout', `gui/${uid}/${path.basename(row.file, '.plist')}`]); // result unread: an agent already gone answers 'Could not find service'; the removal below is what uninstall promises
152
189
  if (fs.existsSync(row.file)) fs.rmSync(row.file);
153
190
  actions.push({ action: 'launch-agent-removed', file: row.file });
154
191
  }
package/src/update.mjs ADDED
@@ -0,0 +1,102 @@
1
+ // oathe — `oathe update`: the documented upgrade, `npm i -g @oathe/oathe@latest && oathe init`,
2
+ // as one verb (founder's word, 2026-09-03). Three facts it holds:
3
+ // - the npm it calls is the one BESIDE the node running this bin (process.execPath), never
4
+ // PATH's — on an nvm machine PATH can lead to another node's npm, and then the upgrade lands
5
+ // somewhere this bin never looks (the trap the 0.4.1 trial hit);
6
+ // - init runs through the NEW bin — the one under npm's global PREFIX (`npm prefix -g`),
7
+ // which is node's own directory by default but not with `npm config set prefix …` (a
8
+ // Greptile P1 on PR #33 caught the execPath-sibling shortcut) — as a child with the terminal
9
+ // attached: this process still holds the old modules, and init's one screen needs the TTY;
10
+ // - a checkout is refused typed — it updates by git — and npm's failure is refused with npm's
11
+ // own last word, never a bland "done".
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { spawnSync } from 'node:child_process';
16
+
17
+ import { defaultExec } from './harnesses/harness.mjs';
18
+ import { notchStatus } from './notch.mjs';
19
+ import { homeOf } from './paths.mjs';
20
+
21
+ export class UpdateError extends Error {
22
+ constructor(code, message, details = {}) {
23
+ super(message);
24
+ this.name = 'UpdateError';
25
+ this.code = code;
26
+ this.details = details;
27
+ }
28
+ }
29
+
30
+ /** A sibling of the node that runs this process — npm ships with node, so this is npm's own home. */
31
+ export function siblingBin(name, { execPath = process.execPath } = {}) {
32
+ return path.join(path.dirname(execPath), name);
33
+ }
34
+
35
+ /** One npm query, refused typed when npm cannot answer it. */
36
+ function npmQuery(exec, npm, args, code) {
37
+ const r = exec.run(npm, args);
38
+ if (r.status !== 0) {
39
+ throw new UpdateError(code, `update refused — \`${npm} ${args.join(' ')}\` failed: ${lastLine(r.stderr) || `exit ${r.status}`}`, { npm, args });
40
+ }
41
+ return r.stdout.trim();
42
+ }
43
+
44
+ /** The new bin, with the terminal attached — init's screen must reach the person. */
45
+ function defaultHandoff(bin, args, { env }) {
46
+ const r = spawnSync(bin, args, { stdio: 'inherit', env });
47
+ return { status: r.status ?? 1 };
48
+ }
49
+
50
+ /** launchd's word on the notch after init — darwin only; elsewhere there is no notch to report. */
51
+ function defaultNotch({ env }) {
52
+ return process.platform === 'darwin' ? notchStatus({ home: homeOf(env) }) : null;
53
+ }
54
+
55
+ const lastLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).at(-1) ?? '';
56
+ const realpathOrSelf = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
57
+
58
+ /**
59
+ * @param {{packageRoot: string, execPath?: string, exec?: {run: Function}, handoff?: Function,
60
+ * env?: NodeJS.ProcessEnv, args?: string[], out?: {write: Function}, tag?: string,
61
+ * notch?: Function}} o
62
+ * @returns {{before: string, after: string, initStatus: number,
63
+ * notch: {label: string, loaded: boolean, pid: number|null}|null}}
64
+ */
65
+ export function runUpdate({
66
+ packageRoot, execPath = process.execPath, exec = defaultExec, handoff = defaultHandoff,
67
+ env = process.env, args = [], out = process.stdout, tag = 'latest', notch = defaultNotch,
68
+ }) {
69
+ const readPkg = () => JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
70
+ const pkg = readPkg();
71
+ const npm = siblingBin('npm', { execPath });
72
+ const globalRoot = path.join(npmQuery(exec, npm, ['root', '-g'], 'OATHE_UPDATE_NPM_UNAVAILABLE'), ...pkg.name.split('/'));
73
+ if (realpathOrSelf(globalRoot) !== realpathOrSelf(packageRoot)) {
74
+ throw new UpdateError('OATHE_UPDATE_NOT_GLOBAL',
75
+ `update refused — this oathe runs from ${packageRoot}, not from npm's global install `
76
+ + `(${globalRoot}); a checkout updates with git, and \`npm i -g ${pkg.name}@${tag}\` installs the published package`,
77
+ { packageRoot, globalRoot });
78
+ }
79
+ const before = pkg.version;
80
+ out.write(`update: ${pkg.name} ${before} → @${tag} (${npm})\n`);
81
+ const install = exec.run(npm, ['i', '-g', `${pkg.name}@${tag}`]);
82
+ if (install.status !== 0) {
83
+ throw new UpdateError('OATHE_UPDATE_FAILED',
84
+ `update refused — \`npm i -g ${pkg.name}@${tag}\` failed (exit ${install.status}): ${lastLine(install.stderr) || lastLine(install.stdout)}`,
85
+ { status: install.status });
86
+ }
87
+ if (lastLine(install.stdout)) out.write(`update: ${lastLine(install.stdout)}\n`);
88
+ const after = readPkg().version; // npm replaced the files under this same root
89
+ out.write(`update: ${before} → ${after}${after === before ? ' (already current)' : ''} — running init through the new bin\n`);
90
+ // The new bin lives under npm's global prefix — node's directory by default, elsewhere with a
91
+ // custom prefix — never assumed from where node is.
92
+ const prefix = npmQuery(exec, npm, ['prefix', '-g'], 'OATHE_UPDATE_NPM_UNAVAILABLE');
93
+ const init = handoff(path.join(prefix, 'bin', 'oathe'), ['init', ...args], { env });
94
+ if (init.status !== 0) return { before, after, initStatus: init.status, notch: null };
95
+ // The last word is the one the person needs: the version live NOW, and whether the notch
96
+ // they look at is the new one — read from launchd after init re-wired it, never assumed.
97
+ const glass = notch({ env });
98
+ if (glass === null) out.write(`update successful — oathe v${after}\n`);
99
+ else if (glass.pid !== null) out.write(`update successful — oathe v${after} · notch running (pid ${glass.pid})\n`);
100
+ else out.write(`update installed oathe v${after} — but the notch is NOT running (launchd: ${glass.loaded ? 'loaded, no pid' : 'not loaded'}); run \`oathe init\` and read its notch line\n`);
101
+ return { before, after, initStatus: init.status, notch: glass };
102
+ }