@oathe/oathe 0.4.4 → 0.4.6

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 +6 -3
  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 +5 -4
  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/shim.mjs ADDED
@@ -0,0 +1,110 @@
1
+ // oathe — the materialized shim: ONE durable address for the oathe bin, $HOME/.oathe/bin/oathe.
2
+ // The connection-lane ruling (launch/2026-09-04-connection-lane-plan.md): harnesses hold an
3
+ // ADDRESS, never a recipe. A bare `oathe` resolved from PATH dies in every GUI-launched
4
+ // session — launchd hands the harness /usr/bin:/bin, no nvm, no node — and a config carrying
5
+ // a raw nvm path is stranded by the next node switch. So init materializes this one address
6
+ // with the running node and package baked in (the notch-app pattern applied to the bin: what
7
+ // other supervisors run is a MATERIALIZED, oathe-home-owned artifact, re-stamped when the
8
+ // world moves, pruned only by uninstall). The plugin's static files may speak this path as
9
+ // "$HOME/.oathe/bin/oathe" (shell form) or "${userHome}/…" (cursor interpolation) — which is
10
+ // why the shim lives under HOME, the one root every dialect can name machine-independently.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import { sha256Hex } from './manifest.mjs';
16
+
17
+ export function shimPath(home) {
18
+ return path.join(home, '.oathe', 'bin', 'oathe');
19
+ }
20
+
21
+ function shimBody({ execPath, packageRoot, version }) {
22
+ const bin = path.join(packageRoot, 'bin/oathe.mjs');
23
+ return '#!/bin/sh\n'
24
+ + `# oathe ${version} — the durable address. Materialized by \`oathe init\`, re-stamped by\n`
25
+ + '# every init/update (a node or package move re-writes this file, never strands it).\n'
26
+ + '# Harness MCP entries and plugin hooks point here; edit nothing — run `oathe init`.\n'
27
+ + `exec "${execPath}" "${bin}" "$@"\n`;
28
+ }
29
+
30
+ /**
31
+ * Materialize (or re-stamp) the shim and record it. Byte-idempotent: an unchanged world
32
+ * writes nothing and says so.
33
+ * @returns {[{action: 'shim-written'|'shim-current', file: string}]}
34
+ */
35
+ export function writeShim({ home, manifest, version, packageRoot, execPath = process.execPath }) {
36
+ const file = shimPath(home);
37
+ const body = shimBody({ execPath, packageRoot, version });
38
+ const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
39
+ const changed = current !== body;
40
+ if (changed) {
41
+ // The dir mode is explicit (review F8): a predictable path every harness executes must
42
+ // never inherit a permissive umask. The write is temp-then-rename (review F6): a harness
43
+ // spawning mid-re-stamp execs whole bytes, old or new — never a truncated script.
44
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
45
+ const tmp = `${file}.tmp-${process.pid}`;
46
+ fs.writeFileSync(tmp, body, { mode: 0o755 });
47
+ fs.renameSync(tmp, file);
48
+ }
49
+ fs.chmodSync(file, 0o755); // a pre-existing file keeps its old mode through the rename path
50
+ // One shim, ONE row (review F1): row identity keys on the full detail, so a node/package
51
+ // move would otherwise mint a second row and doctor would cry user-edited forever on the
52
+ // very nvm-switcher machines this lane serves. A re-stamp replaces.
53
+ manifest.removeWhere((r) => r.kind === 'oathe-shim');
54
+ manifest.upsert({
55
+ harness: 'shim',
56
+ file,
57
+ kind: 'oathe-shim',
58
+ detail: { execPath, packageRoot },
59
+ blockVersion: version,
60
+ sha256: sha256Hex(body),
61
+ });
62
+ return [{ action: changed ? 'shim-written' : 'shim-current', file }];
63
+ }
64
+
65
+ /**
66
+ * Terminate this user's live MCP servers. After an update replaced the tree every running
67
+ * instance serves stale modules; through an uninstall it loses its floor entirely and answers
68
+ * every speech act with raw ENOENT (measured 2026-09-03). "Just get rid of it for them"
69
+ * (founder, 2026-09-04): sweep them; harnesses respawn a fresh server from the shim. The
70
+ * pattern matches the one spawn shape the shim produces — `node …/bin/oathe.mjs mcp` — and
71
+ * deliberately not `oathe notch --serve`, whose launchd job has its own restart story.
72
+ */
73
+ export function sweepMcpServers({ exec }) {
74
+ const uid = process.getuid?.();
75
+ // The pattern cannot match the sweeping process itself: our own cmdline ends in `update`
76
+ // or `uninstall`, never ` mcp`.
77
+ const pgrepArgs = [...(uid === undefined ? [] : ['-u', String(uid)]), '-f', '[/]oathe\\.mjs mcp$'];
78
+ const found = exec.run('pgrep', pgrepArgs);
79
+ // pgrep speaks in exit codes: 1 is "nothing matched"; anything else is "could not look" —
80
+ // and a founder-mandated sweep that cannot look must say so, never shrug (review F4).
81
+ if (found.status === 1) return [{ action: 'mcp-sweep-none' }];
82
+ if (found.status !== 0) {
83
+ return [{ action: 'mcp-sweep-failed', detail: String(found.stderr ?? '').trim().split('\n').at(-1) ?? `pgrep exit ${found.status}` }];
84
+ }
85
+ const pids = found.stdout.split('\n').map((s) => s.trim()).filter(Boolean).map(Number);
86
+ if (pids.length === 0) return [{ action: 'mcp-sweep-none' }];
87
+ for (const pid of pids) {
88
+ // One kill per pid: a target that exited between pgrep and kill (the natural race) must
89
+ // not fail its siblings' sweep (review F5).
90
+ exec.run('kill', [String(pid)]); // result unread: the recheck pgrep below is the read — survivors, not exit codes, are the truth
91
+ }
92
+ const recheck = exec.run('pgrep', pgrepArgs);
93
+ const survivors = recheck.status === 0
94
+ ? recheck.stdout.split('\n').map((s) => s.trim()).filter(Boolean).map(Number)
95
+ : [];
96
+ if (survivors.length > 0) return [{ action: 'mcp-sweep-partial', pids, survivors }];
97
+ return [{ action: 'mcp-swept', pids }];
98
+ }
99
+
100
+ /** Remove exactly what was recorded; absence is a stated action, never silence. */
101
+ export function unwireShim({ manifest }) {
102
+ const rows = manifest.removeWhere((r) => r.kind === 'oathe-shim');
103
+ if (rows.length === 0) return [{ action: 'shim-absent' }];
104
+ const actions = [];
105
+ for (const row of rows) {
106
+ fs.rmSync(row.file, { force: true });
107
+ actions.push({ action: 'shim-removed', file: row.file });
108
+ }
109
+ return actions;
110
+ }
package/src/speaker.mjs CHANGED
@@ -22,16 +22,21 @@ import fs from 'node:fs';
22
22
 
23
23
  import { processAncestry, nearestAppBundle, SessionRegistry } from './sessions.mjs';
24
24
  import { surfaceForSession, harnessForClient, ownerOfTracePath, ownedAncestorIndex, transcriptFor, HARNESS_CLASSES } from './harnesses/catalog.mjs';
25
+ import { readDeviceId } from './device.mjs';
25
26
 
26
27
  /**
27
- * @param {{pid?: number, sessionsPath: string, clientName?: string|null,
28
- * exec?: object, platform?: string}} o — exec/platform are test seams for the walk
28
+ * @param {{pid?: number|null, sessionsPath: string, devicePath?: string|null,
29
+ * clientName?: string|null, exec?: object, platform?: string}} o
30
+ * pid null = NOTHING to walk (a daemon client that named no usable pid) — the speaker is
31
+ * unwalked, never resolved from this process's own ancestry (ruling 2026-09-04);
32
+ * exec/platform are test seams for the walk.
29
33
  * @returns {{surface: string|null, app: {bundle: string, pid: number}|null,
30
- * session: {sessionId: string, transcriptPath: string|null, harness: string}|null}}
34
+ * session: {sessionId: string, transcriptPath: string|null, harness: string}|null,
35
+ * walked: boolean, client: string|null, device: string|null}}
31
36
  */
32
- export function resolveSpeaker({ pid = process.pid, sessionsPath, clientName = null, exec, platform } = {}) {
37
+ export function resolveSpeaker({ pid = process.pid, sessionsPath, devicePath = null, clientName = null, exec, platform } = {}) {
33
38
  // The ancestry is a fact of the PROCESS: walked once (one ps call), never per act.
34
- const walk = processAncestry({
39
+ const walk = pid === null ? [] : processAncestry({
35
40
  pid,
36
41
  ...(exec !== undefined && { exec }),
37
42
  ...(platform !== undefined && { platform }),
@@ -85,9 +90,23 @@ export function resolveSpeaker({ pid = process.pid, sessionsPath, clientName = n
85
90
  if (cached === null || now !== stamp) { cached = shape(); stamp = now; }
86
91
  return cached;
87
92
  };
93
+ // The device is a fact of the INSTALL (ruling 2026-09-04): read once, never invented; a
94
+ // malformed file refuses typed on every read (no fail-soft outside hooks).
95
+ let device;
96
+ let deviceRead = false;
88
97
  return {
89
98
  get surface() { return current().surface; },
90
99
  get app() { return current().app; },
91
100
  get session() { return current().session; },
101
+ /** The pid it was asked to walk — null when there was NOTHING to walk (a daemon client that named none). */
102
+ get pid() { return pid; },
103
+ /** Whether the process tree was actually observed — false for pid null and for a blind walk (ps failed). */
104
+ get walked() { return walk.length > 0; },
105
+ /** The client's own label (MCP clientInfo.name) — the claim gate checks it against the walk. */
106
+ get client() { return clientName; },
107
+ get device() {
108
+ if (!deviceRead) { device = devicePath ? readDeviceId({ devicePath }) : null; deviceRead = true; }
109
+ return device;
110
+ },
92
111
  };
93
112
  }
@@ -6,6 +6,7 @@
6
6
  // read "last word" through this one fragment).
7
7
 
8
8
  import fs from 'node:fs';
9
+ import { SYSTEM_TASKS } from './plans.mjs';
9
10
 
10
11
  export const TRACE_SUBJECT_PREFIX = 'trace:';
11
12
 
@@ -63,6 +64,53 @@ export async function linkTrace({ client, identity, taskId, session }) {
63
64
  return { linked: true };
64
65
  }
65
66
 
67
+ /**
68
+ * WHERE an act was spoken (founder ruling 2026-09-05): the PLACE — a folder (`workspace:<ref>`)
69
+ * or an app (`app:<surface>`, the grammar is src/home.mjs Place) — recorded as ONE observation
70
+ * per claim × place, subject `place:<place>`, evidence the pickup knows (src/home.mjs
71
+ * PlaceEvidence: `app:<bundle>` / `device:<id>` / `dir:<project folder>`, each only when known).
72
+ * `observation`, not `progress`: a place is a fact about the act, never the holder's word, so
73
+ * it stays out of last-word, the quiet clock, and the verifier's reads. Idempotent by
74
+ * (work_claim_id, subject_ref) like the trace link. A statement, so it rides Cloud State
75
+ * unchanged (the `spawn:` argument) — the device on it is why.
76
+ */
77
+ export const PLACE_SUBJECT_PREFIX = 'place:';
78
+ export function placeSubjectRef(place) {
79
+ return `${PLACE_SUBJECT_PREFIX}${place}`;
80
+ }
81
+ /**
82
+ * @param {{client: {query: Function}, identity: {orgId: string, principalId: string}, taskId: string,
83
+ * place: {toString: Function}, evidence: {app: string|null, refs: string[]}, workClaimId?: string}} o
84
+ * workClaimId — the interval to stamp; default: the principal's open claim (active or asserted), as linkTrace picks it
85
+ * @returns {Promise<{linked: boolean}>}
86
+ */
87
+ export async function linkPlace({ client, identity, taskId, place, evidence, workClaimId = null }) {
88
+ let claimId = workClaimId;
89
+ if (claimId === null) {
90
+ const { rows } = await client.query(
91
+ `SELECT work_claim_id FROM cell.work_claim
92
+ WHERE org_id = $1 AND principal_id = $2 AND task_id = $3 AND settled_at IS NULL
93
+ AND state IN ('active', 'completion_asserted')
94
+ ORDER BY claimed_at DESC LIMIT 1`,
95
+ [identity.orgId, identity.principalId, taskId]);
96
+ if (rows.length === 0) return { linked: false };
97
+ claimId = rows[0].work_claim_id;
98
+ }
99
+ const { randomUUID } = await import('node:crypto');
100
+ await client.query(
101
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
102
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
103
+ evidence_refs, epistemic_status, asserted_at)
104
+ SELECT $1, $2, $3, $4, $5, $6, 'observation', $7, $8, $9::jsonb, 'observed', now()
105
+ WHERE NOT EXISTS (
106
+ SELECT 1 FROM cell.agent_statement
107
+ WHERE org_id = $2 AND work_claim_id = $4 AND subject_ref = $7)`,
108
+ [randomUUID(), identity.orgId, taskId, claimId, 'oathe-operator', identity.principalId,
109
+ placeSubjectRef(String(place)), `picked up at ${String(place)}${evidence.app ? ` from ${evidence.app}` : ''}`,
110
+ JSON.stringify(evidence.refs)]);
111
+ return { linked: true };
112
+ }
113
+
66
114
  /**
67
115
  * The latest non-trace progress statement of one claim, as a LATERAL body:
68
116
  * `LEFT JOIN LATERAL (${latestProgressSql({ task: 't', claim: 'w' })}) p ON true` yields
@@ -77,8 +125,22 @@ export async function linkTrace({ client, identity, taskId, session }) {
77
125
  */
78
126
  /** Engine-failure evidence shape: 'engine-failure:<engine>' — a verify child that lost its
79
127
  * engine records this on the verify task before releasing its claim. */
80
- export function engineFailureRef(engine) {
81
- return `engine-failure:${engine}`;
128
+ export function engineFailureRef(engine, cause = null) {
129
+ return `${ENGINE_FAILURE_PREFIX}${engine}${cause ? `:${cause}` : ''}`;
130
+ }
131
+ const ENGINE_FAILURE_PREFIX = 'engine-failure:';
132
+ /** The one reader of the grammar: `{engine, cause}` (cause null when the ref carries none), or null for another ref. */
133
+ export function parseEngineFailure(ref) {
134
+ if (typeof ref !== 'string' || !ref.startsWith(ENGINE_FAILURE_PREFIX)) return null;
135
+ const [engine, cause = null] = ref.slice(ENGINE_FAILURE_PREFIX.length).split(':');
136
+ return { engine, cause };
137
+ }
138
+ /** An engine UPDATE that failed (`oathe engine update`) — the stall grammar's sibling, on the update task's statement. */
139
+ export function updateFailureRef(harness) {
140
+ return `update-failure:${harness}`;
141
+ }
142
+ export function isUpdateFailureSql(column) {
143
+ return `EXISTS (SELECT 1 FROM jsonb_array_elements_text(${column}) er WHERE er LIKE 'update-failure:%')`;
82
144
  }
83
145
  export function isEngineFailureSql(column) {
84
146
  return `EXISTS (SELECT 1 FROM jsonb_array_elements_text(${column}) er WHERE er LIKE 'engine-failure:%')`;
@@ -97,6 +159,17 @@ export function isVerifyStallSql(column) {
97
159
  }
98
160
 
99
161
  /** R-AMEND: the amendment trail's subject shape — 'amend:<task_id>', owned here alone. */
162
+ /**
163
+ * The disclosure an ADMITTED session-less act carries (`trace_link.why`, ruling 2026-09-04):
164
+ * a surface that runs no hooks by design, or a platform where the process tree could not be
165
+ * walked and the client's label stood in. One wording, spoken by the tools; the CLI prints it.
166
+ */
167
+ export function attributionWhy({ surface, walked }) {
168
+ return walked
169
+ ? `no session registered for ${surface} (a surface that runs no hooks): nothing links this act to a transcript — its evidence is discovered by fingerprint at verify`
170
+ : `the process ancestry could not be walked on this platform, so the client's own label (${surface}) stood in: nothing links this act to a transcript — its evidence is discovered by fingerprint at verify`;
171
+ }
172
+
100
173
  export const AMEND_SUBJECT_PREFIX = 'amend:';
101
174
  export function amendSubjectRef(taskId) {
102
175
  return `${AMEND_SUBJECT_PREFIX}${taskId}`;
@@ -200,6 +273,36 @@ export async function linkSpawn({ client, identity, parent, childTaskId, actor }
200
273
  spawnSubjectRef(childTaskId), `spawned '${childTaskId}' under this claim`, JSON.stringify([`task:${childTaskId}`])]);
201
274
  }
202
275
 
276
+ /**
277
+ * THIS interval was judged rejected — the verification row's statement link (003: every
278
+ * verification evaluates a RECORDED statement, and the statement names its claim), never a
279
+ * clock comparison between a verdict and a claim. The one predicate every reader of "was
280
+ * this claim rejected" spells (plan 2026-09-04, Leg A); when the upstream `rejected_at`
281
+ * stamp lands (Leg S) this is the one line that changes.
282
+ */
283
+ export function rejectedIntervalSql({ claim }) {
284
+ return `EXISTS (SELECT 1 FROM cell.verification v
285
+ JOIN cell.agent_statement s
286
+ ON s.org_id = v.org_id AND s.task_id = v.task_id AND s.statement_id = v.statement_id
287
+ WHERE s.work_claim_id = ${claim}.work_claim_id AND v.result = 'rejected')`;
288
+ }
289
+
290
+ /**
291
+ * The hold on a SYSTEM task (UX rule 22 — the ONE in-flight read): an active claim inside its
292
+ * lease on `<kind>:<subject>` (`verify:<task>` → a judge is running; `update:<harness>` → the
293
+ * machine is updating that engine) at `asOf` (a SQL expression — `now()`, or a bound parameter
294
+ * for a clock a caller injects). An active claim past its lease is a holder that died without
295
+ * releasing, not a running one. `orgId`/`subject` are SQL expressions too — a task's own row
296
+ * (`t.org_id`, `t.task_id`) or a literal both fit. The board's `verifying`, the pager's busy rows
297
+ * and the glass all read this and nothing else, so they never disagree.
298
+ */
299
+ export function holdSql({ kind, orgId, subject, asOf }) {
300
+ return `SELECT c.claimed_at FROM cell.work_claim c
301
+ WHERE c.org_id = ${orgId} AND c.task_id = '${SYSTEM_TASKS[kind]}' || ${subject}
302
+ AND c.state = 'active' AND c.settled_at IS NULL AND c.ownership_valid_until > ${asOf}
303
+ ORDER BY c.claimed_at DESC LIMIT 1`;
304
+ }
305
+
203
306
  export function latestVerdictSql({ task }) {
204
307
  return `SELECT s.proposition AS verdict, s.asserted_at AS verdict_at
205
308
  FROM cell.agent_statement s
@@ -222,6 +325,17 @@ export function latestTracePathSql({ task }) {
222
325
  ORDER BY s.asserted_at DESC LIMIT 1`;
223
326
  }
224
327
 
328
+ /**
329
+ * Every trace-link statement on a task, oldest first — evidence is the TASK's record,
330
+ * spanning claims (a re-claim judged blind to its prior interval was a false rejection,
331
+ * live 2026-09-04). The verifier reads it whole; the reclaim bundle shapes it in JS.
332
+ */
333
+ export function taskTraceLinksSql() {
334
+ return `SELECT subject_ref, evidence_refs FROM cell.agent_statement
335
+ WHERE org_id = $1 AND task_id = $2 AND ${isTraceSubjectSql('subject_ref')}
336
+ ORDER BY asserted_at`;
337
+ }
338
+
225
339
  export function latestProgressSql({ task, claim }) {
226
340
  return `SELECT s.proposition, s.asserted_at FROM cell.agent_statement s
227
341
  WHERE s.org_id = ${task}.org_id AND s.task_id = ${task}.task_id
package/src/traces.mjs CHANGED
@@ -30,8 +30,8 @@ export class TraceStore {
30
30
  this.home = home || os.homedir();
31
31
  }
32
32
 
33
- /** Raw lines of a trace file; handles .zst transparently; refuses unreadable files. */
34
- readLines(file) {
33
+ /** Raw bytes of a trace file; handles .zst transparently; refuses unreadable files. */
34
+ #bytes(file) {
35
35
  let bytes;
36
36
  try {
37
37
  bytes = fs.readFileSync(file);
@@ -45,9 +45,30 @@ export class TraceStore {
45
45
  `${file} is zstd-compressed and this node build cannot decompress it — refusing to `
46
46
  + 'silently skip evidence', { file });
47
47
  }
48
- bytes = zlib.zstdDecompressSync(bytes);
48
+ try {
49
+ bytes = zlib.zstdDecompressSync(bytes);
50
+ } catch (e) {
51
+ // A broken archive is "cannot read" like a vanished file or a permission — one grammar,
52
+ // typed, so a discovery loop reports it by name and moves past it (Greptile round 3, PR #37).
53
+ throw new TraceContractError('TRACE_UNREADABLE',
54
+ `trace file cannot be read: ${file} (zstd: ${e.message})`, { file, cause: e.code ?? e.name });
55
+ }
49
56
  }
50
- return bytes.toString('utf8').split('\n').filter((l) => l.trim() !== '');
57
+ return bytes;
58
+ }
59
+
60
+ /** Raw lines of a trace file; handles .zst transparently; refuses unreadable files. */
61
+ readLines(file) {
62
+ return this.#bytes(file).toString('utf8').split('\n').filter((l) => l.trim() !== '');
63
+ }
64
+
65
+ /**
66
+ * Does this file's record carry the needle (a claim UUID — tool results echo it into the
67
+ * transcript, so the record self-fingerprints)? A raw-byte scan: the cheap pre-filter
68
+ * before projection, never a judgment — performing vs mentioning is the projector's call.
69
+ */
70
+ contains(file, needle) {
71
+ return this.#bytes(file).includes(needle);
51
72
  }
52
73
 
53
74
  /** Parsed entries; a malformed line is a typed refusal, never a silent drop. */
@@ -72,21 +93,26 @@ export class TraceStore {
72
93
  }
73
94
  }
74
95
 
75
- #newestIn(dir, matches) {
76
- if (!fs.existsSync(dir)) return null;
77
- let best = null;
96
+ /** ONE walk for every asker: matched files with their mtimes, unordered. */
97
+ #matched(dir, matches) {
98
+ if (!fs.existsSync(dir)) return [];
99
+ const hits = [];
78
100
  for (const entry of fs.readdirSync(dir, { recursive: true })) {
79
101
  const full = path.join(dir, String(entry));
80
102
  if (!matches(String(entry))) continue;
81
103
  const stat = fs.statSync(full, { throwIfNoEntry: false });
82
- if (stat?.isFile() && (!best || stat.mtimeMs > best.mtimeMs)) best = { full, mtimeMs: stat.mtimeMs };
104
+ if (stat?.isFile()) hits.push({ full, mtimeMs: stat.mtimeMs });
83
105
  }
84
- return best?.full ?? null;
106
+ return hits;
85
107
  }
86
108
 
87
109
  /** Protected helper for subclasses. */
88
110
  newestFileIn(dir, matches) {
89
- return this.#newestIn(dir, matches);
111
+ let best = null;
112
+ for (const hit of this.#matched(dir, matches)) {
113
+ if (!best || hit.mtimeMs > best.mtimeMs) best = hit;
114
+ }
115
+ return best?.full ?? null;
90
116
  }
91
117
 
92
118
  /**
@@ -95,19 +121,24 @@ export class TraceStore {
95
121
  * latest record instead of an empty (and therefore silently green) sweep.
96
122
  */
97
123
  recentFilesIn(dir, matches, { days, maxFiles, now = Date.now() }) {
98
- if (!fs.existsSync(dir)) return [];
99
- const hits = [];
100
- for (const entry of fs.readdirSync(dir, { recursive: true })) {
101
- const full = path.join(dir, String(entry));
102
- if (!matches(String(entry))) continue;
103
- const stat = fs.statSync(full, { throwIfNoEntry: false });
104
- if (stat?.isFile()) hits.push({ full, mtimeMs: stat.mtimeMs });
105
- }
106
- hits.sort((a, b) => b.mtimeMs - a.mtimeMs);
124
+ const hits = this.#matched(dir, matches).sort((a, b) => b.mtimeMs - a.mtimeMs);
107
125
  const windowed = hits.filter((h) => h.mtimeMs >= now - days * 86_400_000).slice(0, maxFiles);
108
126
  if (windowed.length === 0 && hits.length > 0) return [hits[0].full];
109
127
  return windowed.map((h) => h.full);
110
128
  }
129
+
130
+ /**
131
+ * Protected: matched files whose mtime is at or after sinceMs, path-ascending (a stable,
132
+ * clock-free order for evidence discovery). The mtime is the ONLY filter on purpose: a
133
+ * long-lived session's file lives in the date partition of its BIRTH and carries today's
134
+ * work (live 2026-09-04) — pruning by path date drops real evidence.
135
+ */
136
+ filesSince(dir, matches, { sinceMs }) {
137
+ return this.#matched(dir, matches)
138
+ .filter((h) => h.mtimeMs >= sinceMs)
139
+ .map((h) => h.full)
140
+ .sort();
141
+ }
111
142
  }
112
143
 
113
144
  const CLAUDE_MESSAGE_TYPES = new Set(['user', 'assistant', 'system']);
@@ -211,6 +242,11 @@ export class ClaudeTraceStore extends TraceStore {
211
242
  recentTranscripts({ days, maxFiles }) {
212
243
  return this.recentFilesIn(this.projectsRoot, ClaudeTraceStore.#isTranscript, { days, maxFiles });
213
244
  }
245
+
246
+ /** Evidence-discovery candidates: root transcripts written since the window opened. */
247
+ evidenceFiles({ sinceMs }) {
248
+ return this.filesSince(this.projectsRoot, ClaudeTraceStore.#isTranscript, { sinceMs });
249
+ }
214
250
  }
215
251
 
216
252
  export class CodexTraceStore extends TraceStore {
@@ -260,6 +296,7 @@ export class CodexTraceStore extends TraceStore {
260
296
  harness: this.harness,
261
297
  session_id: meta.id ?? meta.session_id,
262
298
  cwd: meta.cwd ?? null,
299
+ originator: meta.originator ?? null, // the writer (codex_cli_rs, codex_work_desktop …) — the desktop's staging gate reads it
263
300
  source: meta.source ?? null,
264
301
  entries: rows.length,
265
302
  path: file,
@@ -328,6 +365,11 @@ export class CodexTraceStore extends TraceStore {
328
365
  return this.newestFileIn(this.sessionsRoot, CodexTraceStore.#isRollout);
329
366
  }
330
367
 
368
+ /** Evidence-discovery candidates: rollouts written since the window opened. */
369
+ evidenceFiles({ sinceMs }) {
370
+ return this.filesSince(this.sessionsRoot, CodexTraceStore.#isRollout, { sinceMs });
371
+ }
372
+
331
373
  recentRollouts({ days, maxFiles }) {
332
374
  return this.recentFilesIn(this.sessionsRoot, CodexTraceStore.#isRollout, { days, maxFiles });
333
375
  }
package/src/uninstall.mjs CHANGED
@@ -5,7 +5,8 @@
5
5
  import fs from 'node:fs';
6
6
 
7
7
  import { buildContext } from './context.mjs';
8
- import { FencedBlock, FENCE_STYLES, sweepCreatedResidue } from './blocks.mjs';
8
+ import { FencedBlock, sweepCreatedResidue } from './blocks.mjs';
9
+ import { fenceStyleOf } from './doctor.mjs';
9
10
 
10
11
  /** @returns {Promise<{actions: object[], database_dropped: boolean}>} */
11
12
  export async function runUninstall({ env = process.env, exec, purgeDb = false } = {}) {
@@ -14,16 +15,20 @@ export async function runUninstall({ env = process.env, exec, purgeDb = false }
14
15
  try {
15
16
  const actions = [];
16
17
  for (const harness of harnesses) {
17
- if (!manifest.rows.some((r) => r.harness === harness.name)) continue;
18
+ if (manifest.wiringRowsFor(harness.name).length === 0) continue;
18
19
  for (const action of harness.offboard({ manifest })) {
19
20
  actions.push({ harness: harness.name, ...action });
20
21
  }
21
22
  }
23
+ // The CLI addresses init measured: rows only — the files are the harnesses', never ours.
24
+ for (const row of manifest.removeWhere((r) => r.kind === 'cli-address')) {
25
+ actions.push({ harness: row.harness, action: 'cli-address-forgotten', file: row.file });
26
+ }
22
27
  // Every fence: the folder ones (CLAUDE.md/AGENTS.md written by activation) and the global
23
28
  // one in an adapter's instructions file (written by init) — one row shape, one removal.
24
29
  for (const row of manifest.removeWhere((r) => r.kind === 'fence')) {
25
30
  if (!fs.existsSync(row.file)) continue;
26
- const block = new FencedBlock({ style: FENCE_STYLES[row.detail?.style ?? 'hash'] });
31
+ const block = new FencedBlock({ style: fenceStyleOf(row) });
27
32
  const { content, changed } = block.remove(fs.readFileSync(row.file, 'utf8'));
28
33
  if (!changed) continue;
29
34
  const createdByUs = manifest.backups.find((b) => b.file === row.file)?.absent_before === true;
@@ -38,6 +43,18 @@ export async function runUninstall({ env = process.env, exec, purgeDb = false }
38
43
  // The notch LaunchAgent: booted out and removed exactly as recorded (src/notch.mjs).
39
44
  const { unwireNotch } = await import('./notch.mjs');
40
45
  actions.push(...unwireNotch({ manifest, ...(exec ? { exec } : {}) }));
46
+ // The serve daemon goes the same way — its bootout ends the process, and every
47
+ // forwarder's pipe ends with it.
48
+ const { unwireServe } = await import('./serve.mjs');
49
+ actions.push(...unwireServe({ manifest, ...(exec ? { exec } : {}) }));
50
+ // Live MCP servers would keep answering from a tree whose wiring is now gone — sweep them
51
+ // ("just get rid of it for them", founder 2026-09-04), then remove the durable address
52
+ // last: the offboard CLIs above may still have run through it.
53
+ const { unwireShim, sweepMcpServers } = await import('./shim.mjs');
54
+ actions.push(...sweepMcpServers({ exec: exec ?? (await import('./harnesses/harness.mjs')).defaultExec }));
55
+ actions.push(...unwireShim({ manifest }));
56
+ const { unwireDevice } = await import('./device.mjs');
57
+ actions.push(...unwireDevice({ manifest }));
41
58
  // Same rule as init (B4): rows that landed while the undo CLIs ran are kept, this run's
42
59
  // removals hold, and the save happens under the lock against the file as it is now.
43
60
  const { withFileLock } = await import('./fslock.mjs');
package/src/update.mjs CHANGED
@@ -16,7 +16,9 @@ import { spawnSync } from 'node:child_process';
16
16
 
17
17
  import { defaultExec } from './harnesses/harness.mjs';
18
18
  import { notchStatus } from './notch.mjs';
19
+ import { serveStatus } from './serve.mjs';
19
20
  import { homeOf } from './paths.mjs';
21
+ import { sweepMcpServers } from './shim.mjs';
20
22
 
21
23
  export class UpdateError extends Error {
22
24
  constructor(code, message, details = {}) {
@@ -52,6 +54,11 @@ function defaultNotch({ env }) {
52
54
  return process.platform === 'darwin' ? notchStatus({ home: homeOf(env) }) : null;
53
55
  }
54
56
 
57
+ /** launchd's word on the serve daemon after init — same rule, same source of truth. */
58
+ function defaultServe({ env }) {
59
+ return process.platform === 'darwin' ? serveStatus({ home: homeOf(env) }) : null;
60
+ }
61
+
55
62
  const lastLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).at(-1) ?? '';
56
63
  const realpathOrSelf = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
57
64
 
@@ -65,6 +72,7 @@ const realpathOrSelf = (p) => { try { return fs.realpathSync(p); } catch { retur
65
72
  export function runUpdate({
66
73
  packageRoot, execPath = process.execPath, exec = defaultExec, handoff = defaultHandoff,
67
74
  env = process.env, args = [], out = process.stdout, tag = 'latest', notch = defaultNotch,
75
+ daemon = defaultServe,
68
76
  }) {
69
77
  const readPkg = () => JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
70
78
  const pkg = readPkg();
@@ -86,17 +94,37 @@ export function runUpdate({
86
94
  }
87
95
  if (lastLine(install.stdout)) out.write(`update: ${lastLine(install.stdout)}\n`);
88
96
  const after = readPkg().version; // npm replaced the files under this same root
97
+ // Every MCP server still running was loaded from the tree npm just replaced — stale by
98
+ // definition. Sweep them now; harness sessions respawn a fresh server from the shim.
99
+ const [sweep] = sweepMcpServers({ exec });
100
+ if (sweep.action === 'mcp-swept') {
101
+ out.write(`update: ${sweep.pids.length} stale MCP server(s) from the previous install terminated — sessions reconnect against the new one\n`);
102
+ } else if (sweep.action === 'mcp-sweep-partial') {
103
+ out.write(`update: stale MCP servers partially swept — still running: ${sweep.survivors.join(', ')}; restart those sessions\n`);
104
+ } else if (sweep.action === 'mcp-sweep-failed') {
105
+ out.write(`update: the stale-server sweep could not look (${sweep.detail}) — restart open harness sessions by hand\n`);
106
+ }
89
107
  out.write(`update: ${before} → ${after}${after === before ? ' (already current)' : ''} — running init through the new bin\n`);
90
108
  // The new bin lives under npm's global prefix — node's directory by default, elsewhere with a
91
109
  // custom prefix — never assumed from where node is.
92
110
  const prefix = npmQuery(exec, npm, ['prefix', '-g'], 'OATHE_UPDATE_NPM_UNAVAILABLE');
93
111
  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.
112
+ if (init.status !== 0) return { before, after, initStatus: init.status, notch: null, daemon: null };
113
+ // The last word is the one the person needs: the version live NOW, and whether the two
114
+ // supervised services — the notch they look at and the daemon every session forwards to —
115
+ // are the new ones, read from launchd after init re-wired them, never assumed.
97
116
  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 };
117
+ const dmn = daemon({ env });
118
+ if (glass !== null && glass.pid === null) {
119
+ 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`);
120
+ } else if (dmn !== null && dmn.pid === null) {
121
+ out.write(`update installed oathe v${after} — but the daemon is NOT running (launchd: ${dmn.loaded ? 'loaded, no pid' : 'not loaded'}); every session forwards into nothing — run \`oathe init\` and read its daemon line\n`);
122
+ } else {
123
+ const parts = [
124
+ ...(glass !== null ? [`notch running (pid ${glass.pid})`] : []),
125
+ ...(dmn !== null ? [`daemon running (pid ${dmn.pid})`] : []),
126
+ ];
127
+ out.write(`update successful — oathe v${after}${parts.length > 0 ? ` · ${parts.join(' · ')}` : ''}\n`);
128
+ }
129
+ return { before, after, initStatus: init.status, notch: glass, daemon: dmn };
102
130
  }