@oathe/oathe 0.4.4 → 0.4.5

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 (59) hide show
  1. package/.claude-plugin/marketplace.json +18 -2
  2. package/README.md +4 -1
  3. package/bin/oathe.mjs +199 -35
  4. package/docs/PRIVACY.md +26 -4
  5. package/notch/Oathe Notch.app/Contents/Info.plist +1 -1
  6. package/notch/Oathe Notch.app/Contents/MacOS/OatheNotch +0 -0
  7. package/notch/README.md +4 -3
  8. package/package.json +3 -3
  9. package/plugin/.claude-plugin/plugin.json +21 -3
  10. package/plugin/.cursor-plugin/plugin.json +2 -2
  11. package/plugin/hooks/hooks.json +4 -4
  12. package/plugin/hooks/lib.mjs +9 -0
  13. package/plugin/hooks/render-board.mjs +4 -2
  14. package/src/blocks.mjs +10 -1
  15. package/src/board-render.mjs +7 -4
  16. package/src/breach-digest.mjs +75 -10
  17. package/src/config.mjs +18 -0
  18. package/src/context.mjs +1 -1
  19. package/src/device.mjs +106 -0
  20. package/src/doctor.mjs +101 -6
  21. package/src/engine-update.mjs +170 -0
  22. package/src/evidence-discovery.mjs +170 -0
  23. package/src/fence.mjs +3 -3
  24. package/src/harnesses/catalog.mjs +46 -4
  25. package/src/harnesses/claude.mjs +56 -4
  26. package/src/harnesses/codex-rollout.mjs +110 -21
  27. package/src/harnesses/codex.mjs +106 -19
  28. package/src/harnesses/cursor.mjs +31 -18
  29. package/src/harnesses/harness.mjs +82 -13
  30. package/src/harnesses/surfaces.mjs +2 -2
  31. package/src/home.mjs +174 -52
  32. package/src/init.mjs +27 -2
  33. package/src/launch.mjs +7 -9
  34. package/src/launchd.mjs +100 -0
  35. package/src/manifest.mjs +48 -6
  36. package/src/mcp/connection.mjs +73 -7
  37. package/src/mcp/daemon.mjs +123 -0
  38. package/src/mcp/forwarder.mjs +99 -0
  39. package/src/mcp/oathe-tools.mjs +392 -145
  40. package/src/notch-frame.mjs +118 -42
  41. package/src/notch.mjs +34 -68
  42. package/src/oathe-annotator.mjs +10 -10
  43. package/src/pager.mjs +144 -40
  44. package/src/paths.mjs +1 -0
  45. package/src/plans.mjs +44 -5
  46. package/src/registry.mjs +10 -2
  47. package/src/serve.mjs +82 -0
  48. package/src/session-host.mjs +1 -1
  49. package/src/sessions.mjs +39 -8
  50. package/src/shim.mjs +110 -0
  51. package/src/speaker.mjs +24 -5
  52. package/src/statements.mjs +116 -2
  53. package/src/traces.mjs +61 -19
  54. package/src/uninstall.mjs +20 -3
  55. package/src/update.mjs +35 -7
  56. package/src/verifier.mjs +215 -105
  57. package/src/verify-dispatch.mjs +86 -32
  58. package/src/wire.mjs +7 -1
  59. package/plugin/.mcp.json +0 -10
package/src/manifest.mjs CHANGED
@@ -12,7 +12,16 @@ export function sha256Hex(text) {
12
12
  return crypto.createHash('sha256').update(text).digest('hex');
13
13
  }
14
14
 
15
- const MANIFEST_FORMAT = 1;
15
+ export const MANIFEST_FORMAT = 1;
16
+
17
+ export class InstallManifestError extends Error {
18
+ constructor(code, message, details = {}) {
19
+ super(message);
20
+ this.name = 'InstallManifestError';
21
+ this.code = code;
22
+ this.details = details;
23
+ }
24
+ }
16
25
 
17
26
  export class InstallManifest {
18
27
  /** @param {{manifestPath: string, backupsDir: string, clock?: () => string}} o */
@@ -29,9 +38,23 @@ export class InstallManifest {
29
38
  static load({ manifestPath, backupsDir, clock }) {
30
39
  const manifest = new InstallManifest({ manifestPath, backupsDir, clock });
31
40
  if (fs.existsSync(manifestPath)) {
32
- const doc = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
33
- manifest.rows = doc.rows ?? [];
34
- manifest.backups = doc.backups ?? [];
41
+ let doc;
42
+ try {
43
+ doc = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
44
+ } catch (e) {
45
+ throw new InstallManifestError('OATHE_MANIFEST_MALFORMED',
46
+ `${manifestPath} is not valid JSON (${e.message}) — move it aside and run oathe init (or uninstall with the oathe that wrote it)`, { file: manifestPath });
47
+ }
48
+ // The format is the GATE (zero legacy, founder 2026-09-05): a manifest another oathe wrote
49
+ // is refused by name, never read as an empty one — doctor would say "nothing wired" and
50
+ // uninstall would remove nothing.
51
+ if (doc?.format !== MANIFEST_FORMAT || !Array.isArray(doc.rows) || !Array.isArray(doc.backups)) {
52
+ throw new InstallManifestError('OATHE_MANIFEST_FORMAT',
53
+ `${manifestPath} is format ${JSON.stringify(doc?.format)}; this oathe reads format ${MANIFEST_FORMAT} — `
54
+ + 'uninstall with the oathe that wrote it, then run oathe init', { file: manifestPath, found: doc?.format, expected: MANIFEST_FORMAT });
55
+ }
56
+ manifest.rows = doc.rows;
57
+ manifest.backups = doc.backups;
35
58
  }
36
59
  return manifest;
37
60
  }
@@ -48,7 +71,7 @@ export class InstallManifest {
48
71
  * bring them back from a disk copy that predates the removal. */
49
72
  #removed = new Set();
50
73
 
51
- /** One row per (harness, file, kind, detail identity); a re-run replaces its own row. */
74
+ /** One row per (harness, file, kind, detail identity — `detail.id` when named); a re-run replaces its own row. */
52
75
  upsert({ harness, file, kind, scope = 'user', detail = null, blockVersion, sha256 }) {
53
76
  const key = this.#key({ harness, file, kind, detail });
54
77
  const row = {
@@ -58,12 +81,31 @@ export class InstallManifest {
58
81
  const at = this.rows.findIndex((r) => this.#key(r) === key);
59
82
  if (at === -1) this.rows.push(row);
60
83
  else this.rows[at] = row;
84
+ // Converge: every OTHER row with this identity goes too — twins an earlier writer left behind
85
+ // (the live 2026-09-05 manifest carried three copies of one codex stanza row).
86
+ this.rows = this.rows.filter((r, i) => i === (at === -1 ? this.rows.length - 1 : at) || this.#key(r) !== key);
61
87
  this.#removed.delete(key); // written again in the same run: a row, not a removal
62
88
  return row;
63
89
  }
64
90
 
91
+ /**
92
+ * The rows that mean a harness is WIRED — everything but its `cli-address` row, which is a
93
+ * measurement of the machine (recorded for wired and unwired harnesses alike), never a write.
94
+ * Every "is it onboarded?" question asks this, so an address alone wires nothing.
95
+ */
96
+ wiringRowsFor(harness) {
97
+ return this.rows.filter((r) => r.harness === harness && r.kind !== 'cli-address');
98
+ }
99
+
100
+ /** The address init measured for a harness's CLI (its `cli-address` row), or null. */
101
+ cliAddressFor(harness) {
102
+ return this.rows.find((r) => r.kind === 'cli-address' && r.harness === harness)?.file ?? null;
103
+ }
104
+
105
+ /** A row's identity: the writer's `detail.id` when it names one (so a re-init whose detail changed
106
+ * shape REPLACES the row — zero legacy, 2026-09-05), else the whole detail. */
65
107
  #key({ harness, file, kind, detail }) {
66
- return JSON.stringify([harness, file, kind, detail ?? null]);
108
+ return JSON.stringify([harness, file, kind, detail?.id !== undefined ? { id: detail.id } : detail ?? null]);
67
109
  }
68
110
 
69
111
  /** @returns {object[]} the removed rows */
@@ -40,21 +40,54 @@ export class McpConnection {
40
40
  this.resolver = null;
41
41
  this.contextPromise = null;
42
42
  this.currentContext = null;
43
+ this.closed = false;
44
+ this.rl = null;
43
45
  this.served = lazyTools(() => this.#context());
44
46
  }
45
47
 
46
48
  start() {
47
- const rl = readline.createInterface({ input: this.input });
48
- rl.on('line', async (line) => {
49
+ this.rl = readline.createInterface({ input: this.input });
50
+ this.rl.on('line', (line) => {
49
51
  const s = line.trim();
50
52
  if (!s) return;
51
53
  let msg;
52
54
  try { msg = JSON.parse(s); } catch { return; }
53
- await this.#onMessage(msg);
55
+ void this.handleMessage(msg);
54
56
  });
55
57
  return this;
56
58
  }
57
59
 
60
+ /**
61
+ * The ONE entry for a parsed frame — the daemon feeds its per-socket lines here. It never
62
+ * throws: in a one-shot stdio process an unhandled rejection was a crash the client
63
+ * noticed; in a daemon it would take every other session down with it (phase 2).
64
+ */
65
+ async handleMessage(msg) {
66
+ try {
67
+ await this.#onMessage(msg);
68
+ } catch (e) {
69
+ this.err.write(`oathe mcp: ${String(e?.message || e).slice(0, 300)}\n`);
70
+ let id;
71
+ try { id = msg?.id; } catch { id = undefined; }
72
+ if (id !== undefined && id !== null) {
73
+ this.#tryWrite({ jsonrpc: '2.0', id, error: { code: -32603, message: 'internal error — the server lives; detail on stderr' } });
74
+ }
75
+ }
76
+ }
77
+
78
+ /** End this connection: park nothing, leak nothing. Idempotent — the daemon closes on
79
+ * socket end AND on error, whichever comes first. */
80
+ async close() {
81
+ if (this.closed) return;
82
+ this.closed = true;
83
+ this.rl?.close();
84
+ for (const [id, entry] of this.pending) {
85
+ entry.reject(new Error(`connection closed before ${id} was answered`));
86
+ }
87
+ this.pending.clear();
88
+ await this.#invalidate();
89
+ }
90
+
58
91
  /** A server→client request; the response routes back by id. */
59
92
  request(method, params = {}) {
60
93
  const id = `srv-${++this.requestSeq}`;
@@ -82,14 +115,34 @@ export class McpConnection {
82
115
  await this.#invalidate();
83
116
  return;
84
117
  }
85
- const out = await dispatch(msg, { tools: this.served, version: this.version });
118
+ const out = await dispatch(msg, { tools: this.served, version: this.version, progress: this.#progressFor(msg) });
86
119
  if (out) this.#write(out);
87
120
  }
88
121
 
122
+ /**
123
+ * Standard MCP progress for a request that asked for it (`params._meta.progressToken`): the
124
+ * emitter a long tool call (a blocking done awaiting its verdict) ticks, each tick one
125
+ * `notifications/progress` on the client's token with a rising counter and Node's words —
126
+ * the client's per-tool clock learns the judgment is still running. No token, no emitter.
127
+ */
128
+ #progressFor(msg) {
129
+ const token = msg?.params?._meta?.progressToken;
130
+ if (token === undefined || token === null) return null;
131
+ let n = 0;
132
+ return (message) => this.#tryWrite({
133
+ jsonrpc: '2.0', method: 'notifications/progress', params: { progressToken: token, progress: ++n, message },
134
+ });
135
+ }
136
+
89
137
  #write(obj) {
90
138
  this.output.write(`${JSON.stringify(obj)}\n`);
91
139
  }
92
140
 
141
+ /** A write to a transport that may already be gone — close() owns the cleanup either way. */
142
+ #tryWrite(obj) {
143
+ try { this.#write(obj); } catch { /* transport gone */ }
144
+ }
145
+
93
146
  /**
94
147
  * The one lazily-built context per resolution — rebuilt when the roots change OR when a
95
148
  * config layer file's clock moves (two stats per call): `oathe config verifier cursor`
@@ -140,6 +193,11 @@ export class McpConnection {
140
193
  // only cause one extra rebuild next call, never a missed change.
141
194
  const configStamp = this.#configStamp(resolution.root ?? null);
142
195
  const context = await this.factory({ resolution, client: this.client });
196
+ if (this.closed) {
197
+ // close() raced the build: the context that finished late is not a leaked pg client.
198
+ await context.close?.().catch?.(() => {});
199
+ throw new Error('connection closed during context build');
200
+ }
143
201
  this.currentContext = context;
144
202
  return { resolution, tools: context.tools, context, configStamp };
145
203
  }
@@ -155,8 +213,11 @@ export class McpConnection {
155
213
 
156
214
  /** The production context: config from the resolved root, real substrate, and the ONE
157
215
  * activation seam (src/activation.mjs) — the resolution's `synthetic` fact rides into both
158
- * the tools (board scope) and the seam (no registration, no fences). */
159
- export function defaultToolContextFactory({ env }) {
216
+ * the tools (board scope) and the seam (no registration, no fences). `speakerPid` is the
217
+ * process whose ancestry IS the speaker: the daemon passes its forwarder's hello pid (the
218
+ * walk is measured; the pid is the client's word inside the same-user socket boundary) or
219
+ * null (nothing to walk — the gate refuses its claims); absent, the speaker is this process. */
220
+ export function defaultToolContextFactory({ env, speakerPid = undefined }) {
160
221
  return async ({ resolution, client }) => {
161
222
  const [
162
223
  { Substrate }, { buildPaths }, { OatheConfig }, { WorkspaceRegistry }, { InstallManifest },
@@ -191,11 +252,15 @@ export function defaultToolContextFactory({ env }) {
191
252
  config,
192
253
  workspace: resolution.ref,
193
254
  synthetic: resolution.synthetic,
255
+ dir: resolution.dir, // the directory the surface speaks from — an app pickup records it as evidence
194
256
  activation,
195
257
  // The SPEAKER primitive — resolved FRESH per context build: our own ancestry never
196
258
  // changes, but the device session registry does (a /clear, a rotation), and a stale
197
259
  // memo would stamp the first session's id on every later act (found 2026-09-01).
198
- speaker: resolveSpeaker({ clientName: client?.info?.name, sessionsPath: paths.sessionsPath }),
260
+ speaker: resolveSpeaker({
261
+ clientName: client?.info?.name, sessionsPath: paths.sessionsPath, devicePath: paths.devicePath,
262
+ ...(speakerPid !== undefined && { pid: speakerPid }), // null = nothing to walk
263
+ }),
199
264
 
200
265
  // Verification over MCP DISPATCHES — the engine never runs inside the server (a run is
201
266
  // minutes; the server must keep answering). ONE seam, every surface (verifierSeam).
@@ -204,6 +269,7 @@ export function defaultToolContextFactory({ env }) {
204
269
  query: (sql, params) => substrate.query(sql, params),
205
270
  paths,
206
271
  cwd: resolution.dir,
272
+ progressIntervalMs: config.get('mcpProgressIntervalSec') * 1000, // the wait says it is still judging
207
273
  }),
208
274
  successor: async (o) => {
209
275
  if (!successorPromise) {
@@ -0,0 +1,123 @@
1
+ // oathe — the serve daemon (connection-lane phase 2): the device's one oathe presence. It
2
+ // listens on a 0600 unix socket under the oathe home (fs perms ARE the auth — no port, no
3
+ // per-user collision; ports return at the cloud seam) and serves each forwarder connection
4
+ // with the SAME McpConnection the stdio server runs — a socket is a duplex stream, so there
5
+ // is one connection implementation and two transports, by construction. Per connection: the
6
+ // hello's env slice overlays the daemon's env, its cwd seeds the resolution ladder, and its
7
+ // pid seeds the SPEAKER: the daemon walks THAT pid's ancestry on this machine. The walk is
8
+ // measured; the starting pid is the forwarder's own word, accepted because only this OS user
9
+ // can reach the 0600 socket — no peer credential (SO_PEERCRED/getpeereid) is read. A hello
10
+ // with no usable pid, or none at all, is served with NOTHING walked (speakerPid null) and its
11
+ // claims are refused at the gate — never resolved from this daemon's own ancestry (ruling
12
+ // 2026-09-04). launchd owns this process's liveness (src/serve.mjs
13
+ // wires the agent through the shared launchd machinery); a replaced install restarts it,
14
+ // and every forwarder's pipe ends with it — sessions respawn against the new daemon.
15
+
16
+ import fs from 'node:fs';
17
+ import net from 'node:net';
18
+ import readline from 'node:readline';
19
+
20
+ import { McpConnection, defaultToolContextFactory } from './connection.mjs';
21
+ import { connectDaemon } from './forwarder.mjs';
22
+
23
+ export class OatheServeError extends Error {
24
+ constructor(code, message, details = {}) {
25
+ super(message);
26
+ this.code = code;
27
+ this.details = details;
28
+ }
29
+ }
30
+
31
+ export class OatheDaemon {
32
+ /**
33
+ * @param {{env: NodeJS.ProcessEnv, socketPath: string, err?: {write: Function},
34
+ * toolContextFactory?: (o: {env: object, speakerPid: number|null}) => Function,
35
+ * onHello?: (hello: object) => void}} o
36
+ * toolContextFactory — the per-connection factory builder; the default is the production
37
+ * one (real substrate). onHello is a test seam.
38
+ */
39
+ constructor({ env, socketPath, err = process.stderr, toolContextFactory = defaultToolContextFactory, onHello = null }) {
40
+ this.env = env;
41
+ this.socketPath = socketPath;
42
+ this.err = err;
43
+ this.toolContextFactory = toolContextFactory;
44
+ this.onHello = onHello;
45
+ this.server = null;
46
+ this.connections = new Set();
47
+ this.sockets = new Set();
48
+ }
49
+
50
+ async start() {
51
+ // One daemon per socket: a LIVE daemon is a typed refusal, a stale file (nothing
52
+ // answering) is replaced — the crash/kill leftover must never brick the restart.
53
+ const alive = await connectDaemon({ socketPath: this.socketPath, timeoutMs: 500 });
54
+ if (alive) {
55
+ alive.destroy();
56
+ throw new OatheServeError('OATHE_SERVE_RUNNING',
57
+ `a daemon is already serving on ${this.socketPath} — two would race the socket; stop it (launchctl, or oathe uninstall) before starting another`);
58
+ }
59
+ fs.rmSync(this.socketPath, { force: true });
60
+ this.server = net.createServer((socket) => this.#serve(socket));
61
+ await new Promise((resolve, reject) => {
62
+ this.server.once('error', (e) => reject(new OatheServeError('OATHE_SERVE_LISTEN',
63
+ `cannot listen on ${this.socketPath}: ${String(e?.message || e)}`)));
64
+ this.server.listen(this.socketPath, resolve);
65
+ });
66
+ fs.chmodSync(this.socketPath, 0o600); // this user's alone — the socket's perms are the auth
67
+ return this;
68
+ }
69
+
70
+ #serve(socket) {
71
+ this.sockets.add(socket);
72
+ const rl = readline.createInterface({ input: socket });
73
+ let connection = null;
74
+ rl.on('line', (line) => {
75
+ const s = line.trim();
76
+ if (!s) return;
77
+ let msg;
78
+ try { msg = JSON.parse(s); } catch { return; }
79
+ if (connection === null) {
80
+ const hello = msg?.oathe === 'hello' ? msg : null;
81
+ if (hello) this.onHello?.(hello);
82
+ connection = this.#connectionFor({ hello, socket });
83
+ this.connections.add(connection);
84
+ if (hello) return; // the hello is the binding, not a frame
85
+ }
86
+ void connection.handleMessage(msg);
87
+ });
88
+ socket.on('error', () => socket.destroy());
89
+ socket.on('close', () => {
90
+ this.sockets.delete(socket);
91
+ if (connection) {
92
+ this.connections.delete(connection);
93
+ void connection.close();
94
+ }
95
+ });
96
+ }
97
+
98
+ #connectionFor({ hello, socket }) {
99
+ // The hello's slice OVERLAYS the daemon's env — same-user trust boundary (the socket is
100
+ // 0600), and exactly what the stdio server saw when it inherited the session's env.
101
+ const env = { ...this.env, ...(hello?.env ?? {}) };
102
+ return new McpConnection({
103
+ env,
104
+ input: socket,
105
+ output: socket,
106
+ err: this.err,
107
+ ...(hello?.cwd ? { cwd: () => hello.cwd } : {}),
108
+ // The forwarder's own pid, walked by the daemon — or NULL when no hello named a usable
109
+ // one: nothing to walk, and never this daemon's own ancestry (ruling 2026-09-04).
110
+ toolContextFactory: this.toolContextFactory({ env, speakerPid: Number.isInteger(hello?.pid) && hello.pid > 0 ? hello.pid : null }),
111
+ });
112
+ // NOTE: start() is never called — the daemon owns the socket's line loop (#serve); the
113
+ // connection only ever sees parsed frames through handleMessage.
114
+ }
115
+
116
+ async close() {
117
+ for (const socket of this.sockets) socket.destroy();
118
+ await Promise.all([...this.connections].map((c) => c.close()));
119
+ this.connections.clear();
120
+ if (this.server) await new Promise((resolve) => this.server.close(resolve));
121
+ fs.rmSync(this.socketPath, { force: true }); // the address does not outlive the daemon
122
+ }
123
+ }
@@ -0,0 +1,99 @@
1
+ // oathe — the forwarder (connection-lane phase 2): the session side of the daemon seam.
2
+ // `oathe mcp` stays the per-session child every harness spawns (its process ancestry is the
3
+ // speaker's measurable identity — the deepest fact the stdio design got right), but when the
4
+ // device daemon answers on its socket the child becomes a THIN PIPE: one hello line naming
5
+ // its pid, cwd, and the resolution-relevant env slice, then bytes both ways, verbatim. The
6
+ // daemon walks the hello's pid on this machine (src/speaker.mjs); the pid itself is this
7
+ // process's word, held inside the same-OS-user boundary the 0600 socket draws — the walk is
8
+ // measured, the starting point is trusted with the socket. No daemon answering → null:
9
+ // the mode is a measured fact, never config, and the caller runs today's standalone server.
10
+
11
+ import fs from 'node:fs';
12
+ import net from 'node:net';
13
+
14
+ import { projectDirEnvVars } from '../harnesses/catalog.mjs';
15
+
16
+ /**
17
+ * The env the workspace-resolution ladder and the tools actually read: OATHE_* and each
18
+ * harness's project-dir variable — never the whole environment (the hello is a resolution
19
+ * fact, not an environment dump).
20
+ */
21
+ export function resolutionEnvSlice(env) {
22
+ const ladder = new Set(projectDirEnvVars().map(([, envVar]) => envVar));
23
+ return Object.fromEntries(Object.entries(env)
24
+ .filter(([k, v]) => v !== undefined && (k.startsWith('OATHE_') || ladder.has(k))));
25
+ }
26
+
27
+ /**
28
+ * One connect attempt inside the budget. NULL means "no daemon" — an absent file, a stale
29
+ * socket nobody serves, a refused connect: all the same measured fact, never an error.
30
+ * @returns {Promise<net.Socket|null>}
31
+ */
32
+ export function connectDaemon({ socketPath, timeoutMs }) {
33
+ return new Promise((resolve) => {
34
+ if (!fs.existsSync(socketPath)) return resolve(null);
35
+ const socket = net.connect(socketPath);
36
+ const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);
37
+ socket.once('connect', () => { clearTimeout(timer); resolve(socket); });
38
+ socket.once('error', () => { clearTimeout(timer); socket.destroy(); resolve(null); });
39
+ return undefined;
40
+ });
41
+ }
42
+
43
+ /**
44
+ * The doctor's probe: a bare connect proves a LISTENER, not a server (the verifier's catch,
45
+ * 2026-09-04 — a wedged process squatting the socket must never read as ok). The proof is a
46
+ * real MCP initialize answered inside the budget, and the report names WHO answered.
47
+ * @returns {Promise<{answering: boolean, server: {name: string, version: string}|null}>}
48
+ */
49
+ export async function probeDaemon({ socketPath, timeoutMs }) {
50
+ const socket = await connectDaemon({ socketPath, timeoutMs });
51
+ if (!socket) return { answering: false, server: null };
52
+ return new Promise((resolve) => {
53
+ let buffer = '';
54
+ const done = (out) => { socket.destroy(); resolve(out); };
55
+ const timer = setTimeout(() => done({ answering: false, server: null }), timeoutMs);
56
+ socket.on('data', (chunk) => {
57
+ buffer += String(chunk);
58
+ let i;
59
+ while ((i = buffer.indexOf('\n')) !== -1) {
60
+ const line = buffer.slice(0, i).trim();
61
+ buffer = buffer.slice(i + 1);
62
+ if (!line) continue;
63
+ let msg;
64
+ try { msg = JSON.parse(line); } catch { continue; }
65
+ if (msg.id === 'oathe-doctor-probe' && msg.result?.serverInfo?.name) {
66
+ clearTimeout(timer);
67
+ return done({ answering: true, server: { name: msg.result.serverInfo.name, version: msg.result.serverInfo.version } });
68
+ }
69
+ }
70
+ return undefined;
71
+ });
72
+ socket.on('error', () => { clearTimeout(timer); done({ answering: false, server: null }); });
73
+ socket.write(`${JSON.stringify({
74
+ jsonrpc: '2.0', id: 'oathe-doctor-probe', method: 'initialize',
75
+ params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'oathe-doctor', version: '0' } },
76
+ })}\n`);
77
+ });
78
+ }
79
+
80
+ export class McpForwarder {
81
+ /** @param {{socket: net.Socket, input: NodeJS.ReadableStream, output: NodeJS.WritableStream,
82
+ * env: NodeJS.ProcessEnv, cwd: string, pid: number}} o */
83
+ constructor({ socket, input, output, env, cwd, pid }) {
84
+ this.socket = socket;
85
+ this.input = input;
86
+ this.output = output;
87
+ this.hello = { oathe: 'hello', pid, cwd, env: resolutionEnvSlice(env) };
88
+ }
89
+
90
+ start() {
91
+ this.socket.write(`${JSON.stringify(this.hello)}\n`);
92
+ this.input.pipe(this.socket);
93
+ // The daemon hanging up (an upgrade's restart) ends this pipe: the harness sees its
94
+ // server die and respawns a fresh forwarder against the new daemon — never a half-alive
95
+ // session on stale state.
96
+ this.socket.pipe(this.output);
97
+ return this;
98
+ }
99
+ }