@oathe/oathe 0.2.3 → 0.3.1

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 (74) hide show
  1. package/NOTICE +3 -4
  2. package/README.md +15 -45
  3. package/assets/oathe-hero.svg +92 -0
  4. package/bin/oathe.mjs +397 -59
  5. package/docs/PRIVACY.md +13 -5
  6. package/notch/Oathe Notch.app/Contents/Info.plist +13 -0
  7. package/notch/Oathe Notch.app/Contents/MacOS/OatheNotch +0 -0
  8. package/notch/Oathe Notch.app/Contents/_CodeSignature/CodeResources +115 -0
  9. package/notch/README.md +88 -0
  10. package/package.json +13 -4
  11. package/plugin/.claude-plugin/plugin.json +1 -1
  12. package/plugin/.cursor-plugin/plugin.json +36 -0
  13. package/plugin/.mcp.json +1 -4
  14. package/plugin/commands/verify.md +18 -0
  15. package/plugin/hooks/frame-note.mjs +5 -3
  16. package/plugin/hooks/heartbeat.mjs +21 -25
  17. package/plugin/hooks/lib.mjs +96 -33
  18. package/plugin/hooks/render-board.mjs +47 -7
  19. package/src/activation.mjs +126 -0
  20. package/src/atif.mjs +4 -13
  21. package/src/blocks.mjs +113 -8
  22. package/src/board-render.mjs +55 -29
  23. package/src/config.mjs +100 -15
  24. package/src/context.mjs +4 -8
  25. package/src/doctor.mjs +96 -15
  26. package/src/fence.mjs +85 -0
  27. package/src/fslock.mjs +51 -0
  28. package/src/harnesses/catalog.mjs +180 -0
  29. package/src/harnesses/claude.mjs +196 -0
  30. package/src/harnesses/codex.mjs +188 -0
  31. package/src/harnesses/cursor.mjs +234 -0
  32. package/src/harnesses/dialects.mjs +52 -0
  33. package/src/harnesses/harness.mjs +203 -0
  34. package/src/harnesses/surfaces.mjs +71 -0
  35. package/src/home.mjs +107 -0
  36. package/src/init.mjs +101 -21
  37. package/src/launch-env.mjs +1 -51
  38. package/src/launch.mjs +36 -105
  39. package/src/manifest.mjs +7 -3
  40. package/src/mcp/connection.mjs +218 -0
  41. package/src/mcp/oathe-tools.mjs +380 -141
  42. package/src/notch.mjs +154 -0
  43. package/src/pager.mjs +178 -0
  44. package/src/paths.mjs +13 -1
  45. package/src/plans.mjs +10 -2
  46. package/src/registry.mjs +110 -0
  47. package/src/runtime/discharge.mjs +1 -1
  48. package/src/runtime/provider.mjs +10 -7
  49. package/src/runtime/simple-cage.mjs +18 -9
  50. package/src/runtime/sql-acceptance-lane.mjs +1 -1
  51. package/src/session-host.mjs +8 -6
  52. package/src/sessions.mjs +168 -0
  53. package/src/setup.mjs +494 -0
  54. package/src/speaker.mjs +65 -0
  55. package/src/statements.mjs +113 -0
  56. package/src/substrate.mjs +44 -0
  57. package/src/successor.mjs +1 -1
  58. package/src/traces.mjs +8 -8
  59. package/src/uninstall.mjs +10 -2
  60. package/src/verifier.mjs +135 -47
  61. package/src/verify-dispatch.mjs +169 -0
  62. package/src/welcome.mjs +32 -0
  63. package/src/wire.mjs +64 -0
  64. package/src/workspace-resolver.mjs +178 -0
  65. package/src/workspace.mjs +16 -5
  66. package/vendor/ddl/001_core.sql +1 -1
  67. package/vendor/ddl/004_delegation.sql +1 -1
  68. package/vendor/ddl/006_dependency.sql +1 -1
  69. package/vendor/ddl/008_effect_receipt.sql +1 -1
  70. package/vendor/ddl/009_verified_edge.sql +1 -1
  71. package/vendor/ddl/011_confirm.sql +2 -2
  72. package/vendor/ddl/manifest.json +8 -8
  73. package/assets/handoff-splash.png +0 -0
  74. package/src/harness.mjs +0 -271
@@ -0,0 +1,168 @@
1
+ // oathe — the session liveness registry (~/.oathe/sessions.json): which LIVING process
2
+ // speaks for each harness session on THIS device. Written by hooks (SessionStart and the
3
+ // heartbeat both speak ensure() — the one convergence verb), read by the notch feed. FACTS
4
+ // ONLY —
5
+ // pids, exec paths, the nearest focusable app bundle; surface NAMES are resolved at read
6
+ // time by the harness adapters, so naming evolves without rewriting history.
7
+ //
8
+ // Liveness is device-local by ruling (2026-08-30): pids mean nothing off-device, so when
9
+ // the substrate moves to the cloud this file stays beside the processes it describes.
10
+ // It cleans itself: register() sweeps dead rows in the same mutation, and every reader
11
+ // checks pid-aliveness — no cron, no migration, no dead-process ledger.
12
+
13
+ import fs from 'node:fs';
14
+
15
+ import { atomicWriteJson, withFileLock } from './fslock.mjs';
16
+ import { defaultExec } from './harnesses/harness.mjs';
17
+
18
+ const SESSIONS_FORMAT = 1;
19
+ const ANCESTRY_DEPTH_CAP = 32; // loop guard for a corrupt ps snapshot — a bound, not a tunable
20
+
21
+ export class SessionRegistryError extends Error {
22
+ constructor(code, message, details = {}) {
23
+ super(message);
24
+ this.name = 'SessionRegistryError';
25
+ this.code = code;
26
+ this.details = details;
27
+ }
28
+ }
29
+
30
+ export function pidAlive(pid) {
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * The process ancestry of `pid` to pid 1 — ONE `ps` snapshot walked in memory. A darwin
41
+ * fact (`comm=` is the full exec path there; elsewhere it truncates): other platforms get
42
+ * `[]`, and so does any ps failure — the walk is fail-soft, a session without ancestry
43
+ * still registers and its pid-aliveness still serves.
44
+ * @returns {Array<{pid: number, exec: string}>} ancestry[0] is `pid` itself
45
+ */
46
+ export function processAncestry({ pid, exec = defaultExec, platform = process.platform }) {
47
+ if (platform !== 'darwin') return [];
48
+ const out = exec.run('ps', ['-axo', 'pid=,ppid=,comm=']);
49
+ if (out.status !== 0) return [];
50
+ const table = new Map();
51
+ for (const line of out.stdout.split('\n')) {
52
+ const m = line.match(/^\s*(\d+)\s+(\d+)\s+(.+)$/);
53
+ if (m) table.set(Number(m[1]), { ppid: Number(m[2]), exec: m[3] });
54
+ }
55
+ const chain = [];
56
+ let cursor = pid;
57
+ for (let depth = 0; depth < ANCESTRY_DEPTH_CAP; depth += 1) {
58
+ const row = table.get(cursor);
59
+ if (!row) break;
60
+ chain.push({ pid: cursor, exec: row.exec });
61
+ if (cursor === 1 || row.ppid === 0) break;
62
+ cursor = row.ppid;
63
+ }
64
+ return chain;
65
+ }
66
+
67
+ /**
68
+ * The nearest FOCUSABLE app process in an ancestry: exec inside `<bundle>.app/Contents/MacOS/`
69
+ * where the bundle itself is not nested inside another bundle — a helper's own `.app` is
70
+ * skipped for its host (Cursor Helper → Cursor.app). null: nothing focusable (a daemon).
71
+ * @returns {{bundle: string, pid: number}|null}
72
+ */
73
+ export function nearestAppBundle(ancestry) {
74
+ for (const { pid, exec } of ancestry) {
75
+ const m = exec.match(/^(.*\.app)\/Contents\/MacOS\/[^/]+$/);
76
+ if (m && !m[1].slice(0, -4).includes('.app/')) return { bundle: m[1], pid };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ export class SessionRegistry {
82
+ /** @param {{sessionsPath: string, clock?: () => string, isAlive?: (pid: number) => boolean}} o */
83
+ constructor({ sessionsPath, clock = () => new Date().toISOString(), isAlive = pidAlive }) {
84
+ this.sessionsPath = sessionsPath;
85
+ this.clock = clock;
86
+ this.isAlive = isAlive;
87
+ }
88
+
89
+ /** @returns {{format: number, saved_at?: string, sessions: object}} */
90
+ load() {
91
+ if (!fs.existsSync(this.sessionsPath)) return { format: SESSIONS_FORMAT, sessions: {} };
92
+ try {
93
+ return JSON.parse(fs.readFileSync(this.sessionsPath, 'utf8'));
94
+ } catch (e) {
95
+ throw new SessionRegistryError('OATHE_SESSIONS_MALFORMED',
96
+ `${this.sessionsPath} is not valid JSON: ${e.message}`, { file: this.sessionsPath });
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The ONE convergence verb — "this session is alive right now", from whichever hook
102
+ * fires. Unknown row → full register (the facts thunk pays for its one ps walk, and the
103
+ * same mutation sweeps every row whose pid has died — the file cleans itself). Known row
104
+ * in a NEW body (a resumed harness: same session, different pid) → re-register: process
105
+ * facts refresh, registered_at survives (first-seen is the session's birthday), and a
106
+ * fact this observer cannot know survives from the old row. Known row, same pid → a
107
+ * cheap beat: last_seen_at only, the thunk never runs.
108
+ *
109
+ * A registry with a single write moment is not a registry: a session that outlives a
110
+ * deploy, or whose file was wiped, must become visible again at its next signal.
111
+ * @param {{sessionId: string, pid: number,
112
+ * facts: () => {ancestry?: Array, app?: object|null, transcriptPath?: string, workspace?: string}}} o
113
+ */
114
+ async ensure({ sessionId, pid, facts }) {
115
+ return this.#mutate((doc, now) => {
116
+ const existing = doc.sessions[sessionId];
117
+ if (existing && existing.pid === pid) {
118
+ existing.last_seen_at = now;
119
+ return existing;
120
+ }
121
+ for (const [sid, row] of Object.entries(doc.sessions)) {
122
+ if (!this.isAlive(row.pid)) delete doc.sessions[sid];
123
+ }
124
+ const { ancestry = [], app = null, transcriptPath, workspace } = facts() ?? {};
125
+ const next = {
126
+ pid, ancestry, app,
127
+ transcript_path: transcriptPath ?? existing?.transcript_path ?? null,
128
+ workspace: workspace ?? existing?.workspace ?? null,
129
+ registered_at: existing?.registered_at ?? now,
130
+ last_seen_at: now,
131
+ };
132
+ doc.sessions[sessionId] = next;
133
+ return next;
134
+ });
135
+ }
136
+
137
+ /** @returns {object|null} */
138
+ get(sessionId) {
139
+ return this.load().sessions[sessionId] ?? null;
140
+ }
141
+
142
+ /**
143
+ * The writer's self-identification: which registered session's pid appears in MY OWN
144
+ * ancestry (nearest ancestor wins — the harness process is the speaker's parent chain).
145
+ * An unknown chain is null, never a guess; a malformed file refuses typed via load().
146
+ * @returns {{sessionId: string, row: object}|null}
147
+ */
148
+ byAncestry(ancestry) {
149
+ const { sessions } = this.load();
150
+ for (const { pid } of ancestry) {
151
+ for (const [sessionId, row] of Object.entries(sessions)) {
152
+ if (row.pid === pid) return { sessionId, row };
153
+ }
154
+ }
155
+ return null;
156
+ }
157
+
158
+ // One clock read per mutation: row timestamps and saved_at describe the same instant.
159
+ async #mutate(fn) {
160
+ return withFileLock(this.sessionsPath, () => {
161
+ const doc = this.load();
162
+ const now = this.clock();
163
+ const result = fn(doc, now);
164
+ atomicWriteJson(this.sessionsPath, { format: SESSIONS_FORMAT, saved_at: now, sessions: doc.sessions });
165
+ return result;
166
+ });
167
+ }
168
+ }
package/src/setup.mjs ADDED
@@ -0,0 +1,494 @@
1
+ // oathe init as DATA. A SetupPlan is everything the machine owner is asked and everything init
2
+ // will do: one step per wiring adapter, each step's "what yes writes" taken from the adapter's
3
+ // own describe() (the same data its onboard() writes — the prompt cannot promise what the
4
+ // write does not do), the verifier candidates from the census (headless-capable AND the CLI is
5
+ // here), the detect-only surfaces as explanations. A SetupPrompter renders the plan on a TTY:
6
+ // one explained yes/no per installed harness, the verifier by NAME, Enter = default, an
7
+ // unrecognized answer refused and re-asked. --yes and no-TTY apply the plan's defaults to the
8
+ // SAME plan and announce them. Nothing in this file writes anything. The rules every line here
9
+ // follows are docs/UX.md; tests/setup.test.mjs holds them.
10
+
11
+ import { launchable, verifiers } from './harnesses/catalog.mjs';
12
+
13
+ export class OatheInitError extends Error {
14
+ constructor(code, message, details = {}) {
15
+ super(message);
16
+ this.name = 'OatheInitError';
17
+ this.code = code;
18
+ this.details = details;
19
+ }
20
+ }
21
+
22
+ /** `~` for the home prefix — every path a person reads in a prompt or a summary. */
23
+ export function tilde(text, home) {
24
+ return home ? String(text).split(home).join('~') : String(text);
25
+ }
26
+
27
+ /** Why a step was skipped, as a sentence for people — never the token. */
28
+ const SKIP_REASONS = Object.freeze({
29
+ 'not-installed': 'not installed',
30
+ 'not-wired': 'not wired',
31
+ 'harness-filter': 'not named by --harness',
32
+ answered: 'you said no',
33
+ });
34
+
35
+ export class SetupStep {
36
+ constructor({ name, displayName, covers, wired = false, presence, installed, writes, configHome, cliBins }) {
37
+ this.name = name;
38
+ this.displayName = displayName;
39
+ this.covers = covers;
40
+ this.wired = wired;
41
+ this.presence = presence;
42
+ this.installed = installed;
43
+ this.writes = writes;
44
+ this.configHome = configHome;
45
+ this.cliBins = cliBins;
46
+ /** null = unanswered; a harness that is not here is never a question. */
47
+ this.selected = installed ? null : false;
48
+ this.reason = installed ? null : 'not-installed';
49
+ }
50
+
51
+ decide(selected, reason) {
52
+ this.selected = selected;
53
+ this.reason = reason;
54
+ }
55
+
56
+ /** Presence as facts: what was found — or, when nothing was, what was looked for. */
57
+ presenceLine(home) {
58
+ const found = [];
59
+ if (this.presence.app === true) found.push('app installed');
60
+ if (this.presence.cli) found.push('CLI on PATH');
61
+ if (this.presence.configHome) found.push(`config at ${tilde(this.presence.configHome, home)}`);
62
+ if (this.installed) {
63
+ const noCli = !this.presence.cli && this.cliBins.length > 0 ? ` (no ${this.cliBins.join('/')} on PATH)` : '';
64
+ return `found: ${found.join(', ')}${noCli}`;
65
+ }
66
+ const lookedFor = [];
67
+ if (this.cliBins.length > 0) lookedFor.push(`no ${this.cliBins.join('/')} on PATH`);
68
+ lookedFor.push(`no ${tilde(this.configHome, home)}`);
69
+ return `not found (${lookedFor.join(', ')})`;
70
+ }
71
+ }
72
+
73
+ export class SetupPlan {
74
+ constructor({ home, fresh = true, configPath, manifestPath, steps, verifier, agent, surfaces }) {
75
+ this.home = home;
76
+ /** No wiring exists yet — the screen defaults everything detected ON; else it shows the state. */
77
+ this.fresh = fresh;
78
+ this.configPath = configPath;
79
+ this.manifestPath = manifestPath;
80
+ this.steps = steps;
81
+ this.verifier = verifier;
82
+ this.agent = agent;
83
+ this.surfaces = surfaces;
84
+ /** Set when defaults were applied instead of answers: 'assume-yes' | 'no-tty' | … */
85
+ this.defaultsReason = null;
86
+ }
87
+
88
+ /**
89
+ * @param {{adapters: object[], census: object[], surfaces: object[], machine: import('./config.mjs').OatheConfig,
90
+ * home: string, paths: {manifestPath: string}, fallbackVerifier: string}} o — `machine` is the GLOBAL config layer: the
91
+ * verifier is a machine-wide choice, and only that layer says whether it was made.
92
+ */
93
+ static from({ adapters, census, surfaces, machine, home, paths, fallbackVerifier, wiredNow = new Set() }) {
94
+ const steps = adapters.map((adapter) => {
95
+ const seen = census.find((c) => c.name === adapter.name);
96
+ return new SetupStep({
97
+ name: adapter.name,
98
+ displayName: adapter.constructor.displayName,
99
+ covers: adapter.constructor.covers,
100
+ wired: wiredNow.has(adapter.name),
101
+ presence: seen.presence,
102
+ installed: seen.installed,
103
+ writes: adapter.describe(),
104
+ configHome: adapter.configHome,
105
+ cliBins: adapter.constructor.cliBins,
106
+ });
107
+ });
108
+ const candidates = verifiers(census);
109
+ const alreadyChosen = machine.source('verifier') !== 'default'
110
+ ? { value: machine.get('verifier'), file: machine.globalPath }
111
+ : null;
112
+ const fresh = wiredNow.size === 0;
113
+ const verifier = {
114
+ candidates,
115
+ default: candidates[0] ?? fallbackVerifier,
116
+ alreadyChosen,
117
+ chosen: alreadyChosen?.value ?? null,
118
+ asked: false,
119
+ };
120
+ // The default agent (who picks your work back up — the notch's continue): the same
121
+ // question shape as the verifier, asked ABOVE it (founder ruling 2026-08-30).
122
+ const agentCandidates = launchable().filter((n) => census.find((c) => c.name === n)?.installed);
123
+ const agentChosen = machine.source('defaultAgent') !== 'default'
124
+ ? { value: machine.get('defaultAgent'), file: machine.globalPath }
125
+ : null;
126
+ const agent = {
127
+ candidates: agentCandidates,
128
+ default: agentCandidates[0] ?? null,
129
+ alreadyChosen: agentChosen,
130
+ chosen: agentChosen?.value ?? null,
131
+ asked: false,
132
+ };
133
+ return new SetupPlan({
134
+ home,
135
+ fresh,
136
+ configPath: machine.globalPath,
137
+ manifestPath: paths.manifestPath,
138
+ steps,
139
+ verifier,
140
+ agent,
141
+ surfaces: surfaces.filter((s) => s.detected)
142
+ .map((s) => ({ name: s.name, displayName: s.displayName, detected: true, note: s.steps })),
143
+ });
144
+ }
145
+
146
+ step(name) {
147
+ return this.steps.find((s) => s.name === name);
148
+ }
149
+
150
+ /** --harness a,b: exactly the named — an unknown name or one not on this machine is a refusal. */
151
+ narrow(names) {
152
+ const wireable = this.steps.map((s) => s.name);
153
+ const unknown = names.filter((n) => !wireable.includes(n));
154
+ if (unknown.length > 0) {
155
+ throw new OatheInitError('OATHE_INIT_HARNESS_UNKNOWN',
156
+ `--harness names ${unknown.join(', ')} — init wires: ${wireable.join(', ')}`, { unknown });
157
+ }
158
+ const absent = names.filter((n) => !this.step(n).installed);
159
+ if (absent.length > 0) {
160
+ throw new OatheInitError('OATHE_INIT_HARNESS_ABSENT',
161
+ `--harness names ${absent.map((n) => `${n}, which is ${this.step(n).presenceLine(this.home)}`).join('; ')}`
162
+ + ' — nothing to wire; install it first or drop it from --harness', { absent });
163
+ }
164
+ for (const step of this.steps.filter((s) => s.installed)) step.decide(names.includes(step.name), 'harness-filter');
165
+ return this;
166
+ }
167
+
168
+ /** Answer every open question with its default — the CURRENT state (a fresh machine: all on). Never unwires. */
169
+ applyDefaults(reason) {
170
+ for (const step of this.steps) {
171
+ if (!step.installed || step.selected !== null) continue;
172
+ if (this.fresh || step.wired) step.decide(true, reason);
173
+ else step.decide(false, 'not-wired');
174
+ }
175
+ if (this.verifier.chosen === null) this.verifier.chosen = this.verifier.default;
176
+ if (this.agent.chosen === null) this.agent.chosen = this.agent.default;
177
+ this.defaultsReason = reason;
178
+ return this;
179
+ }
180
+
181
+ get wired() {
182
+ return this.steps.filter((s) => s.selected === true).map((s) => s.name);
183
+ }
184
+
185
+ /** The wired harnesses the SCREEN unchecked — the only path that unwires (--yes/--harness never do). */
186
+ get toUnwire() {
187
+ return this.steps.filter((s) => s.wired && s.selected === false && s.reason === 'answered').map((s) => s.name);
188
+ }
189
+
190
+ get answered() {
191
+ return this.steps.every((s) => s.selected !== null) && this.verifier.chosen !== null
192
+ && (this.agent.chosen !== null || this.agent.candidates.length === 0);
193
+ }
194
+
195
+ /** What was applied, one clause each — the line --yes and no-TTY print. */
196
+ announceLines() {
197
+ const lines = [];
198
+ if (this.wired.length > 0) lines.push(`wire: ${this.wired.join(', ')}`);
199
+ const skipped = new Map();
200
+ for (const s of this.steps.filter((x) => x.selected === false)) {
201
+ const why = SKIP_REASONS[s.reason] ?? s.reason;
202
+ skipped.set(why, [...(skipped.get(why) ?? []), s.name]);
203
+ }
204
+ for (const [why, names] of skipped) lines.push(`skip: ${names.join(', ')} (${why})`);
205
+ if (this.agent.chosen !== null) {
206
+ lines.push(`default agent: ${this.agent.chosen}${this.agent.alreadyChosen ? ' (already chosen machine-wide)' : ''}`);
207
+ }
208
+ lines.push(`verifier: ${this.verifier.chosen}${this.verifier.alreadyChosen ? ' (already chosen machine-wide)' : ''}`);
209
+ return lines;
210
+ }
211
+
212
+ /** The plan plus what landed: one row per step, files under ~, reasons as sentences. */
213
+ outcomes(actions) {
214
+ return this.steps.map((step) => {
215
+ const mine = actions.filter((a) => a.harness === step.name && !/^skipped/.test(a.action));
216
+ const files = [...new Set(mine.filter((a) => a.file).map((a) => tilde(a.file, this.home)))];
217
+ const landed = files.length > 0 ? files : mine.map((a) => a.action);
218
+ if (step.selected === true) return { name: step.name, displayName: step.displayName, outcome: 'wired', reason: null, landed };
219
+ if (this.toUnwire.includes(step.name)) return { name: step.name, displayName: step.displayName, outcome: 'unwired', reason: null, landed };
220
+ return { name: step.name, displayName: step.displayName, outcome: 'skipped', reason: SKIP_REASONS[step.reason] ?? step.reason, landed: [] };
221
+ });
222
+ }
223
+ }
224
+
225
+ // ------------------------------------------------------------------ the one-screen checklist
226
+ // Raw-mode keys, plain ANSI, no TUI dependency. Every detected harness is a pre-selected row;
227
+ // ↑↓ move, space toggles, the verifier is a radio row (← →), Enter installs the selection —
228
+ // one keypress for the common case (docs/UX.md rule 1). Nothing here writes anything.
229
+
230
+ const ANSI = Object.freeze({
231
+ dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m', hide: '\x1b[?25l', show: '\x1b[?25h',
232
+ up: (n) => `\x1b[${n}A`, clear: '\x1b[J',
233
+ });
234
+ const LEGEND = '↑↓ move · space toggle · enter install';
235
+ const OPENING = 'oathe init — reversible (oathe uninstall)';
236
+
237
+ const KEY_NAMES = Object.freeze({
238
+ '\x1b[A': 'up', '\x1bOA': 'up', k: 'up',
239
+ '\x1b[B': 'down', '\x1bOB': 'down', j: 'down',
240
+ '\x1b[C': 'right', '\x1bOC': 'right', l: 'right',
241
+ '\x1b[D': 'left', '\x1bOD': 'left', h: 'left',
242
+ ' ': 'toggle', '\r': 'enter', '\n': 'enter',
243
+ '\x03': 'abort', q: 'abort', '\x1b': 'abort',
244
+ });
245
+
246
+ /** Raw bytes → key names; a chunk may carry several keys (a paste, a piped line); unknown bytes do nothing (rule 5). */
247
+ export function decodeKeys(chunk) {
248
+ const text = String(chunk);
249
+ const keys = [];
250
+ for (let at = 0; at < text.length;) {
251
+ if (text[at] === '\x1b' && (text[at + 1] === '[' || text[at + 1] === 'O') && at + 2 < text.length) {
252
+ const name = KEY_NAMES[text.slice(at, at + 3)];
253
+ if (name) keys.push(name);
254
+ at += 3;
255
+ continue;
256
+ }
257
+ const name = KEY_NAMES[text[at]];
258
+ if (name) keys.push(name);
259
+ at += 1;
260
+ }
261
+ return keys;
262
+ }
263
+
264
+ class SetupScreen {
265
+ constructor(plan, { columns }) {
266
+ this.plan = plan;
267
+ this.columns = columns;
268
+ this.t = (x) => tilde(x, plan.home);
269
+ // The live picks: only steps the plan has not already decided (installed and unanswered).
270
+ this.picks = new Map(plan.steps.filter((s) => s.installed && s.selected === null).map((s) => [s.name, plan.fresh || s.wired]));
271
+ const v = plan.verifier;
272
+ this.radio = v.candidates.length > 1; // a recorded choice PRESETS the radio — re-running init is how you change it
273
+ this.verifierAt = Math.max(0, v.candidates.indexOf(
274
+ v.alreadyChosen !== null && v.candidates.includes(v.alreadyChosen.value) ? v.alreadyChosen.value : v.default));
275
+ const a = plan.agent;
276
+ this.agentRadio = a.candidates.length > 1;
277
+ this.agentAt = Math.max(0, a.candidates.indexOf(
278
+ a.alreadyChosen !== null && a.candidates.includes(a.alreadyChosen.value) ? a.alreadyChosen.value : a.default));
279
+ // The rows the cursor can reach: toggleable steps, then the agent, then the verifier
280
+ // (the agent question sits ABOVE the verifier — founder ruling 2026-08-30).
281
+ this.movable = [
282
+ ...plan.steps.filter((s) => this.picks.has(s.name)).map((s) => ({ kind: 'step', step: s })),
283
+ ...(this.agentRadio ? [{ kind: 'agent' }] : []),
284
+ ...(this.radio ? [{ kind: 'verifier' }] : []),
285
+ ];
286
+ this.cursor = 0;
287
+ }
288
+
289
+ get current() {
290
+ return this.movable[this.cursor] ?? null;
291
+ }
292
+
293
+ move(delta) {
294
+ if (this.movable.length > 0) this.cursor = (this.cursor + delta + this.movable.length) % this.movable.length;
295
+ }
296
+
297
+ toggle() {
298
+ const row = this.current;
299
+ if (!row) return;
300
+ if (row.kind === 'step') this.picks.set(row.step.name, !this.picks.get(row.step.name));
301
+ else this.cycle(1);
302
+ }
303
+
304
+ cycle(delta) {
305
+ if (this.current?.kind === 'agent') {
306
+ const n = this.plan.agent.candidates.length;
307
+ this.agentAt = (this.agentAt + delta + n) % n;
308
+ return;
309
+ }
310
+ if (this.current?.kind !== 'verifier') return;
311
+ const n = this.plan.verifier.candidates.length;
312
+ this.verifierAt = (this.verifierAt + delta + n) % n;
313
+ }
314
+
315
+ #stepRow(step) {
316
+ const label = step.displayName.padEnd(12);
317
+ if (!step.installed) return { text: ` ${label} ${step.presenceLine(this.plan.home)}`, fixed: true, step };
318
+ const covers = `(${step.covers})`;
319
+ if (this.picks.has(step.name)) {
320
+ return { text: `[${this.picks.get(step.name) ? 'x' : ' '}] ${label} ${covers}`, fixed: false, step };
321
+ }
322
+ const why = step.selected === true ? '(--harness)' : (SKIP_REASONS[step.reason] ?? step.reason);
323
+ return { text: `[${step.selected === true ? 'x' : ' '}] ${label} ${covers} ${why}`, fixed: true, step };
324
+ }
325
+
326
+ #agentRow() {
327
+ const a = this.plan.agent;
328
+ const label = 'default agent'.padEnd(12);
329
+ if (a.candidates.length === 0) return null; // no launchable agent installed — not a question
330
+ if (a.candidates.length === 1) {
331
+ return { text: ` ${label} ${a.candidates[0]}`, fixed: true };
332
+ }
333
+ const radio = a.candidates.map((c, i) => `(${i === this.agentAt ? '•' : ' '}) ${c}`).join(' ');
334
+ return {
335
+ text: ` ${label} ${radio}`,
336
+ fixed: false,
337
+ kind: 'agent',
338
+ hint: '← → choose · who picks your work back up (the notch\'s continue opens this agent)',
339
+ };
340
+ }
341
+
342
+ #verifierRow() {
343
+ const v = this.plan.verifier;
344
+ const label = 'verifier'.padEnd(12);
345
+ if (v.candidates.length <= 1) {
346
+ return { text: ` ${label} ${v.candidates[0] ?? v.default}`, fixed: true };
347
+ }
348
+ const radio = v.candidates.map((c, i) => `(${i === this.verifierAt ? '•' : ' '}) ${c}`).join(' ');
349
+ return {
350
+ text: ` ${label} ${radio}`,
351
+ fixed: false,
352
+ kind: 'verifier',
353
+ hint: '← → choose · judges finished work in a fresh headless run under a non-author seat; tip: the one you use less',
354
+ };
355
+ }
356
+
357
+ rows() {
358
+ return [
359
+ ...this.plan.steps.map((s) => this.#stepRow(s)),
360
+ ...this.plan.surfaces.map((s) => ({ text: ` ${s.displayName.padEnd(12)} detected — nothing to wire`, fixed: true })),
361
+ ...(this.#agentRow() ? [this.#agentRow()] : []),
362
+ this.#verifierRow(),
363
+ ];
364
+ }
365
+
366
+ #fit(text) {
367
+ return text.length >= this.columns ? `${text.slice(0, this.columns - 2)}…` : text;
368
+ }
369
+
370
+ /** The live screen: opening, legend, rows with the cursor, the highlighted row's full writes. */
371
+ render() {
372
+ const cur = this.current;
373
+ const lines = [OPENING, ` ${ANSI.dim}${LEGEND}${ANSI.reset}`, ''];
374
+ for (const row of this.rows()) {
375
+ const here = cur !== null
376
+ && ((cur.kind === 'step' && row.step === cur.step) || (row.kind !== undefined && row.kind === cur.kind));
377
+ const body = this.#fit(row.text);
378
+ lines.push(here ? `${ANSI.bold}› ${body}${ANSI.reset}` : row.fixed ? `${ANSI.dim} ${body}${ANSI.reset}` : ` ${body}`);
379
+ }
380
+ lines.push('');
381
+ if (cur?.kind === 'step') for (const w of cur.step.writes) lines.push(` ${ANSI.dim}${this.#fit(this.t(w))}${ANSI.reset}`);
382
+ if (cur?.kind === 'verifier') lines.push(` ${ANSI.dim}${this.#fit(this.rows().at(-1).hint)}${ANSI.reset}`);
383
+ return lines;
384
+ }
385
+
386
+ /** What stays in scrollback once the choice is made: the rows, plain, no legend. */
387
+ final() {
388
+ return [OPENING, '', ...this.rows().map((row) => (row.fixed
389
+ ? `${ANSI.dim} ${this.#fit(row.text)}${ANSI.reset}`
390
+ : ` ${this.#fit(row.text)}`)), ''];
391
+ }
392
+
393
+ /** Apply the picks to the plan. */
394
+ commit() {
395
+ for (const [name, on] of this.picks) this.plan.step(name).decide(on, 'answered');
396
+ const v = this.plan.verifier;
397
+ if (this.radio) {
398
+ v.chosen = v.candidates[this.verifierAt];
399
+ v.asked = true;
400
+ } else {
401
+ v.chosen = v.alreadyChosen?.value ?? v.candidates[0] ?? v.default;
402
+ }
403
+ const a = this.plan.agent;
404
+ if (this.agentRadio) {
405
+ a.chosen = a.candidates[this.agentAt];
406
+ a.asked = true;
407
+ } else {
408
+ a.chosen = a.alreadyChosen?.value ?? a.candidates[0] ?? a.default;
409
+ }
410
+ return this.plan;
411
+ }
412
+ }
413
+
414
+ /** The one-screen setup over a SetupPlan on a TTY. */
415
+ export class SetupPrompter {
416
+ constructor({ stdin, out }) {
417
+ this.stdin = stdin;
418
+ this.out = out;
419
+ }
420
+
421
+ static isInteractive({ stdin, out }) {
422
+ return stdin?.isTTY === true && out?.isTTY === true;
423
+ }
424
+
425
+ /** Show the screen, take keys until Enter, return the answered plan; Esc/q/ctrl-c and EOF are typed refusals. */
426
+ ask(plan) {
427
+ const screen = new SetupScreen(plan, { columns: this.out.columns || 100 });
428
+ let drawn = 0;
429
+ const columns = this.out.columns || 100;
430
+ const fit = (line) => {
431
+ const plain = line.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
432
+ if (plain.length <= columns) return line;
433
+ // Clamp by VISIBLE length: a wrapped line occupies two rows while the redraw counts one.
434
+ let visible = 0;
435
+ let out = '';
436
+ for (let at = 0; at < line.length && visible < columns - 1;) {
437
+ const esc = /^\x1b\[[0-9;?]*[A-Za-z]/.exec(line.slice(at));
438
+ if (esc) { out += esc[0]; at += esc[0].length; continue; }
439
+ out += line[at]; at += 1; visible += 1;
440
+ }
441
+ return `${out}…${line.includes(ANSI.reset) ? ANSI.reset : ''}`;
442
+ };
443
+ const draw = (lines) => {
444
+ this.out.write(`${drawn > 0 ? ANSI.up(drawn) + ANSI.clear : ''}${lines.map(fit).join('\n')}\n`);
445
+ drawn = lines.length;
446
+ };
447
+ return new Promise((resolve, reject) => {
448
+ const stop = () => {
449
+ this.stdin.removeListener('data', onData);
450
+ this.stdin.removeListener('end', onEnd);
451
+ this.stdin.removeListener('close', onEnd);
452
+ this.stdin.setRawMode?.(false);
453
+ this.stdin.pause?.();
454
+ this.out.write(ANSI.show);
455
+ };
456
+ const finish = () => {
457
+ draw(screen.final());
458
+ stop();
459
+ resolve(screen.commit());
460
+ };
461
+ const refuse = (code, message) => {
462
+ draw(screen.final());
463
+ stop();
464
+ reject(new OatheInitError(code, message));
465
+ };
466
+ const onData = (chunk) => {
467
+ for (const key of decodeKeys(chunk)) {
468
+ if (key === 'enter') return finish();
469
+ if (key === 'abort') {
470
+ return refuse('OATHE_INIT_ABORTED',
471
+ 'setup aborted at the keyboard — nothing was written; run `oathe init` again, or `oathe init --yes` for the defaults');
472
+ }
473
+ if (key === 'up') screen.move(-1);
474
+ else if (key === 'down') screen.move(1);
475
+ else if (key === 'toggle') screen.toggle();
476
+ else if (key === 'right') screen.cycle(1);
477
+ else if (key === 'left') screen.cycle(-1);
478
+ }
479
+ draw(screen.render());
480
+ return undefined;
481
+ };
482
+ const onEnd = () => refuse('OATHE_INIT_INPUT_CLOSED',
483
+ 'stdin closed before Enter — nothing was written; run `oathe init` on a terminal, or `oathe init --yes` for a '
484
+ + 'non-interactive setup (it announces the defaults it applies)');
485
+ this.stdin.setRawMode?.(true);
486
+ this.stdin.on('data', onData);
487
+ this.stdin.on('end', onEnd);
488
+ this.stdin.on('close', onEnd);
489
+ this.stdin.resume?.();
490
+ this.out.write(ANSI.hide);
491
+ draw(screen.render());
492
+ });
493
+ }
494
+ }