@oathe/oathe 0.0.1 → 0.2.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 (71) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/LICENSE +202 -21
  3. package/NOTICE +7 -0
  4. package/README.md +104 -12
  5. package/assets/oathe-hero.svg +92 -0
  6. package/bin/oathe.mjs +376 -0
  7. package/docs/PRIVACY.md +45 -0
  8. package/package.json +33 -23
  9. package/plugin/.claude-plugin/plugin.json +10 -0
  10. package/plugin/.mcp.json +13 -0
  11. package/plugin/hooks/frame-note.mjs +24 -0
  12. package/plugin/hooks/heartbeat.mjs +49 -0
  13. package/plugin/hooks/hooks.json +39 -0
  14. package/plugin/hooks/lib.mjs +83 -0
  15. package/plugin/hooks/render-board.mjs +11 -0
  16. package/plugin/skills/oathe-work/SKILL.md +33 -0
  17. package/src/atif.mjs +633 -0
  18. package/src/blocks.mjs +192 -0
  19. package/src/board-render.mjs +106 -0
  20. package/src/config.mjs +169 -0
  21. package/src/context.mjs +35 -0
  22. package/src/doctor.mjs +108 -0
  23. package/src/harness.mjs +271 -0
  24. package/src/init.mjs +92 -0
  25. package/src/launch-env.mjs +25 -0
  26. package/src/launch.mjs +259 -0
  27. package/src/manifest.mjs +89 -0
  28. package/src/mcp/oathe-tools.mjs +517 -0
  29. package/src/paths.mjs +49 -0
  30. package/src/plans.mjs +50 -0
  31. package/src/runtime/discharge.mjs +57 -0
  32. package/src/runtime/provider.mjs +154 -0
  33. package/src/runtime/simple-cage.mjs +67 -0
  34. package/src/runtime/sql-acceptance-lane.mjs +89 -0
  35. package/src/session-host.mjs +81 -0
  36. package/src/substrate.mjs +337 -0
  37. package/src/successor.mjs +31 -0
  38. package/src/traces.mjs +242 -0
  39. package/src/uninstall.mjs +45 -0
  40. package/src/verifier.mjs +322 -0
  41. package/src/workspace.mjs +47 -0
  42. package/vendor/ddl/001_core.sql +312 -0
  43. package/vendor/ddl/002_claim.sql +438 -0
  44. package/vendor/ddl/003_verification.sql +480 -0
  45. package/vendor/ddl/004_delegation.sql +397 -0
  46. package/vendor/ddl/005_escalation.sql +303 -0
  47. package/vendor/ddl/006_dependency.sql +384 -0
  48. package/vendor/ddl/007_assignment.sql +502 -0
  49. package/vendor/ddl/008_effect_receipt.sql +290 -0
  50. package/vendor/ddl/009_verified_edge.sql +452 -0
  51. package/vendor/ddl/010_parent_child_verification.sql +320 -0
  52. package/vendor/ddl/011_confirm.sql +288 -0
  53. package/vendor/ddl/012_evaluator_lane.sql +444 -0
  54. package/vendor/ddl/013_claim_terminal.sql +279 -0
  55. package/vendor/ddl/014_claim_settlement.sql +327 -0
  56. package/vendor/ddl/015_claim_yield.sql +213 -0
  57. package/vendor/ddl/016_reopened_reclaim.sql +285 -0
  58. package/vendor/ddl/017_claim_yield_causes.sql +357 -0
  59. package/vendor/ddl/018_receiptless_unknown.sql +249 -0
  60. package/vendor/ddl/019_verification_contract_freeze.sql +335 -0
  61. package/vendor/ddl/020_context_compilation.sql +105 -0
  62. package/vendor/ddl/021_execution_attempt_closure.sql +95 -0
  63. package/vendor/ddl/022_verification_clause.sql +106 -0
  64. package/vendor/ddl/023_executor_role.sql +66 -0
  65. package/vendor/ddl/024_executor_role_hardening.sql +439 -0
  66. package/vendor/ddl/025_running_attempt_uniqueness.sql +102 -0
  67. package/vendor/ddl/026_acceptance_authority.sql +230 -0
  68. package/vendor/ddl/027_ownership_return.sql +836 -0
  69. package/vendor/ddl/028_attempt_bind_ownership.sql +173 -0
  70. package/vendor/ddl/manifest.json +183 -0
  71. package/index.js +0 -33
@@ -0,0 +1,337 @@
1
+ // oathe — the local cell substrate: detect Postgres, create the cell database, apply the shipped
2
+ // DDL additively, seed the operator principal, register the operator yield cause.
3
+ //
4
+ // The DDL source of truth is the monorepo's DDL set, applied in DDL_FILES order — the list is
5
+ // carried here VERBATIM because the DDL README binds "applied in DDL_FILES order from apply.py,
6
+ // never by glob"; a unit test cross-checks this list against both apply.py and the directory, so
7
+ // drift fails the suite rather than reordering a schema. Idempotency is oathe's own bookkeeping
8
+ // (oathe.ddl_applied), not an assumption about the files: an applied file is skipped, an applied
9
+ // file whose bytes CHANGED is a refusal (pinned files do not drift quietly), never DROP anything.
10
+
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { createRequire } from 'node:module';
15
+
16
+ const require = createRequire(import.meta.url);
17
+ const pg = require('pg');
18
+
19
+ import { OatheConfig } from './config.mjs';
20
+
21
+ export const DDL_FILES = Object.freeze([
22
+ '001_core.sql',
23
+ '002_claim.sql',
24
+ '003_verification.sql',
25
+ '004_delegation.sql',
26
+ '005_escalation.sql',
27
+ '006_dependency.sql',
28
+ '007_assignment.sql',
29
+ '008_effect_receipt.sql',
30
+ '009_verified_edge.sql',
31
+ '010_parent_child_verification.sql',
32
+ '011_confirm.sql',
33
+ '012_evaluator_lane.sql',
34
+ '013_claim_terminal.sql',
35
+ '014_claim_settlement.sql',
36
+ '015_claim_yield.sql',
37
+ '016_reopened_reclaim.sql',
38
+ '017_claim_yield_causes.sql',
39
+ '018_receiptless_unknown.sql',
40
+ '019_verification_contract_freeze.sql',
41
+ '020_context_compilation.sql',
42
+ '021_execution_attempt_closure.sql',
43
+ '022_verification_clause.sql',
44
+ '023_executor_role.sql',
45
+ '024_executor_role_hardening.sql',
46
+ '025_running_attempt_uniqueness.sql',
47
+ '026_acceptance_authority.sql',
48
+ '027_ownership_return.sql',
49
+ '028_attempt_bind_ownership.sql',
50
+ ]);
51
+
52
+ const YIELD_CAUSE_FN = 'cell.oathe_yield_operator';
53
+ const YIELD_BASIS_PREFIX = 'operator_decision';
54
+
55
+ export class SubstrateError extends Error {
56
+ constructor(code, message, details = {}) {
57
+ super(message);
58
+ this.name = 'SubstrateError';
59
+ this.code = code;
60
+ this.details = details;
61
+ }
62
+ }
63
+
64
+ export class Substrate {
65
+ /** @param {{database?: string, paths: object, env?: NodeJS.ProcessEnv, config?: import('./config.mjs').OatheConfig}} o */
66
+ constructor({ database, paths, env = process.env, config }) {
67
+ // Connection facts flow from OatheConfig (env overrides ride its env layer) — the only
68
+ // fallback here is constructing that config from env when the caller didn't.
69
+ const cfg = config ?? new OatheConfig({ env, cwd: paths.packageRoot });
70
+ this.database = database ?? cfg.get('db');
71
+ this.paths = paths;
72
+ this.host = cfg.get('pgHost');
73
+ this.port = cfg.get('pgPort');
74
+ // libpq parity the pg client lacks: when neither PGUSER nor USER is in the environment
75
+ // (minimal containers, non-login shells), the username is the OS account — never an
76
+ // empty startup packet the server refuses.
77
+ this.user = env.PGUSER || env.USER || os.userInfo().username;
78
+ /** @type {import('pg').Client|null} */
79
+ this.client = null;
80
+ }
81
+
82
+ connectionConfig(database = this.database) {
83
+ return { host: this.host, port: this.port, database, user: this.user };
84
+ }
85
+
86
+ /** libpq-style connection string for consumers (oathe-runtime config) that want one. */
87
+ connectionString(database = this.database) {
88
+ return `postgresql://localhost/${database}?host=${encodeURIComponent(this.host)}&port=${this.port}`;
89
+ }
90
+
91
+ async #adminClient() {
92
+ const client = new pg.Client(this.connectionConfig('postgres'));
93
+ await client.connect();
94
+ return client;
95
+ }
96
+
97
+ async #cellClient() {
98
+ if (!this.client) {
99
+ this.client = new pg.Client(this.connectionConfig());
100
+ await this.client.connect();
101
+ }
102
+ return this.client;
103
+ }
104
+
105
+ async query(sql, params) {
106
+ const client = await this.#cellClient();
107
+ return client.query(sql, params);
108
+ }
109
+
110
+ /** @returns {Promise<{reachable: boolean, detail: string|null}>} */
111
+ async detect() {
112
+ let admin;
113
+ try {
114
+ admin = await this.#adminClient();
115
+ await admin.query('SELECT 1');
116
+ return { reachable: true, detail: null };
117
+ } catch (e) {
118
+ return { reachable: false, detail: String(e?.message || e) };
119
+ } finally {
120
+ if (admin) await admin.end().catch(() => {});
121
+ }
122
+ }
123
+
124
+ /** @returns {Promise<{created: boolean}>} */
125
+ async ensureDatabase() {
126
+ const admin = await this.#adminClient();
127
+ try {
128
+ const { rows } = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [this.database]);
129
+ if (rows.length > 0) return { created: false };
130
+ // CREATE DATABASE cannot be parameterized; the name is oathe's own constant, quoted anyway.
131
+ await admin.query(`CREATE DATABASE "${this.database.replaceAll('"', '""')}"`);
132
+ return { created: true };
133
+ } finally {
134
+ await admin.end();
135
+ }
136
+ }
137
+
138
+ /** Scratch-test helper only — the product NEVER drops (uninstall keeps the DB sans --purge-db). */
139
+ async dropDatabase() {
140
+ const admin = await this.#adminClient();
141
+ try {
142
+ await admin.query(`DROP DATABASE IF EXISTS "${this.database.replaceAll('"', '""')}"`);
143
+ } finally {
144
+ await admin.end();
145
+ }
146
+ }
147
+
148
+ /**
149
+ * The ONE place that resolves the DDL root — both `shaOf` and `applyDdl` read through it, so a
150
+ * missing source is a single typed refusal, never a raw ENOENT surfacing from either caller.
151
+ */
152
+ #ddlRoot() {
153
+ if (!this.paths.ddlDir) {
154
+ throw new SubstrateError('DDL_SOURCE_UNAVAILABLE',
155
+ 'no DDL source resolves on this machine — set OATHE_DDL_DIR, ship vendor/ddl, or point '
156
+ + 'OATHE_MONOREPO at a checkout; the substrate cannot apply a schema it cannot read',
157
+ { ddlDir: this.paths.ddlDir, ddlSource: this.paths.ddlSource });
158
+ }
159
+ // A NAMED source (e.g. OATHE_DDL_DIR pointed at a typo'd path, or an explicit OATHE_MONOREPO
160
+ // that does not resolve — both lawful under R-D, which takes env verbatim) still has to
161
+ // exist on disk: existence is THIS method's contract, so a wrong dir is caught here as the
162
+ // same typed refusal, never a raw ENOENT surfacing later from shaOf/applyDdl.
163
+ if (!fs.existsSync(this.paths.ddlDir)) {
164
+ throw new SubstrateError('DDL_SOURCE_UNAVAILABLE',
165
+ `${this.paths.ddlSource} names ${this.paths.ddlDir} as the DDL source, but that `
166
+ + 'directory does not exist — the substrate cannot apply a schema it cannot read',
167
+ { ddlDir: this.paths.ddlDir, ddlSource: this.paths.ddlSource });
168
+ }
169
+ return this.paths.ddlDir;
170
+ }
171
+
172
+ shaOf(filename) {
173
+ const bytes = fs.readFileSync(path.join(this.#ddlRoot(), filename));
174
+ return require('node:crypto').createHash('sha256').update(bytes).digest('hex');
175
+ }
176
+
177
+ /**
178
+ * Preflight entry point for callers (init) that want the same typed refusal BEFORE doing any
179
+ * database work — the same resolver `shaOf`/`applyDdl` read through, just called earlier.
180
+ */
181
+ assertDdlSource() {
182
+ this.#ddlRoot();
183
+ }
184
+
185
+ /**
186
+ * Apply DDL_FILES in order. Each file runs in its own transaction and is recorded in
187
+ * oathe.ddl_applied; the first failure is terminal (the README's rule).
188
+ * @returns {Promise<{applied: string[], skipped: string[]}>}
189
+ */
190
+ async applyDdl() {
191
+ // Refuse before touching the database at all — a missing DDL source is caught here, not
192
+ // mid-way through a half-created schema.
193
+ const ddlDir = this.#ddlRoot();
194
+ const client = await this.#cellClient();
195
+ await client.query(`
196
+ CREATE SCHEMA IF NOT EXISTS oathe;
197
+ CREATE TABLE IF NOT EXISTS oathe.ddl_applied (
198
+ filename text PRIMARY KEY,
199
+ sha256 text NOT NULL,
200
+ applied_at timestamptz NOT NULL DEFAULT now()
201
+ )`);
202
+ const { rows } = await client.query('SELECT filename, sha256 FROM oathe.ddl_applied');
203
+ const recorded = new Map(rows.map((r) => [r.filename, r.sha256]));
204
+ const applied = [];
205
+ const skipped = [];
206
+ for (const filename of DDL_FILES) {
207
+ const sha = this.shaOf(filename);
208
+ const prior = recorded.get(filename);
209
+ if (prior === sha) { skipped.push(filename); continue; }
210
+ if (prior !== undefined) {
211
+ throw new SubstrateError('DDL_DRIFT',
212
+ `${filename} was applied with sha ${prior.slice(0, 12)}… but the file on disk now hashes `
213
+ + `${sha.slice(0, 12)}… — a pinned DDL file does not drift quietly; refusing to re-apply`,
214
+ { filename });
215
+ }
216
+ const sql = fs.readFileSync(path.join(ddlDir, filename), 'utf8');
217
+ try {
218
+ await client.query('BEGIN');
219
+ await client.query(sql);
220
+ await client.query('INSERT INTO oathe.ddl_applied (filename, sha256) VALUES ($1, $2)', [filename, sha]);
221
+ await client.query('COMMIT');
222
+ } catch (e) {
223
+ await client.query('ROLLBACK').catch(() => {});
224
+ throw new SubstrateError('DDL_APPLY_FAILED',
225
+ `${filename} failed to apply: ${String(e?.message || e)} — the first failure is terminal`,
226
+ { filename, cause: String(e?.message || e) });
227
+ }
228
+ applied.push(filename);
229
+ }
230
+ return { applied, skipped };
231
+ }
232
+
233
+ /** @returns {Promise<{inserted: boolean}>} */
234
+ /** Seeds the ORG-ROOT principal. Role 'ceo' is the schema's root vocabulary, not an org
235
+ * assumption: 004_delegation's CHECK makes (role='ceo') ⇔ (no assigner), and the 005
236
+ * escalation walk terminates at that seat. Renaming the root role is a substrate/DDL
237
+ * decision (recorded open for the runtime port), not a package default. */
238
+ async seed({ orgId, principalId, department }) {
239
+ const { rowCount } = await this.query(
240
+ `INSERT INTO cell.principal (org_id, principal_id, role, assigner_principal_id, department)
241
+ VALUES ($1, $2, 'ceo', NULL, $3) ON CONFLICT DO NOTHING`,
242
+ [orgId, principalId, department]);
243
+ return { inserted: rowCount === 1 };
244
+ }
245
+
246
+ /**
247
+ * The non-author verifier principal (FC010: a verdict's signer may be neither the claim
248
+ * principal nor the execution actor — the operator cannot verify their own work). Role
249
+ * 'lead', assigned by the operator: the substrate's principal roles are ceo|lead, and a
250
+ * verifier seat is a delegate of the human root, never a second root.
251
+ * @returns {Promise<{inserted: boolean}>}
252
+ */
253
+ async seedVerifier({ orgId, verifierPrincipal, operatorPrincipal, department }) {
254
+ const { rowCount } = await this.query(
255
+ `INSERT INTO cell.principal (org_id, principal_id, role, assigner_principal_id, department)
256
+ VALUES ($1, $2, 'lead', $3, $4) ON CONFLICT DO NOTHING`,
257
+ [orgId, verifierPrincipal, operatorPrincipal, department]);
258
+ return { inserted: rowCount === 1 };
259
+ }
260
+
261
+ /**
262
+ * The acceptance-seat roster, written ONLY through the substrate's governed verb (FC170
263
+ * refuses any other writer). Upserts by org — re-running init re-registers the same truth.
264
+ */
265
+ async registerAcceptanceAuthority({ orgId, seats, clauseSpecs, checkerRefs, registeredBy }) {
266
+ await this.query(
267
+ 'SELECT cell.register_acceptance_authority($1, $2::jsonb, $3::jsonb, $4::jsonb, $5, now())',
268
+ [orgId, JSON.stringify(seats), JSON.stringify(clauseSpecs), JSON.stringify(checkerRefs), registeredBy]);
269
+ return { registered: true };
270
+ }
271
+
272
+ /**
273
+ * The operator yield cause: a real plpgsql function (record_claim_yield resolves its caller off
274
+ * the call stack via cell.written_by) plus its declared basis prefix. The play script's exact
275
+ * pattern, productized under oathe's name.
276
+ */
277
+ async registerYieldCause() {
278
+ await this.query(`
279
+ CREATE OR REPLACE FUNCTION ${YIELD_CAUSE_FN}(
280
+ p_work_claim_id uuid, p_note text, p_at timestamptz, p_event_id uuid
281
+ ) RETURNS void LANGUAGE plpgsql AS $fn$
282
+ BEGIN
283
+ PERFORM cell.record_claim_yield(p_work_claim_id, '${YIELD_BASIS_PREFIX}: ' || p_note, p_at, p_event_id);
284
+ END $fn$`);
285
+ await this.query(
286
+ `INSERT INTO cell.claim_yield_cause (cause, basis_prefix) VALUES ($1, $2)
287
+ ON CONFLICT (cause) DO UPDATE SET basis_prefix = EXCLUDED.basis_prefix`,
288
+ [YIELD_CAUSE_FN, YIELD_BASIS_PREFIX]);
289
+ return { registered: true };
290
+ }
291
+
292
+ async status() {
293
+ // Named once, told everywhere: every branch of this method carries the same ddl_source key
294
+ // so init's summary, doctor, and `oathe status` never disagree about which source is serving.
295
+ const ddlSource = this.paths.ddlSource ?? 'ABSENT';
296
+ const reachable = await this.detect();
297
+ if (!reachable.reachable) {
298
+ return { reachable: false, database_exists: false, ddl_applied: 0, ddl_expected: DDL_FILES.length, ddl_source: ddlSource, yield_cause_registered: false };
299
+ }
300
+ const admin = await this.#adminClient();
301
+ let databaseExists;
302
+ try {
303
+ const { rows } = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [this.database]);
304
+ databaseExists = rows.length > 0;
305
+ } finally {
306
+ await admin.end();
307
+ }
308
+ if (!databaseExists) {
309
+ return { reachable: true, database_exists: false, ddl_applied: 0, ddl_expected: DDL_FILES.length, ddl_source: ddlSource, yield_cause_registered: false };
310
+ }
311
+ const ddl = await this.query(
312
+ "SELECT count(*)::int AS n FROM pg_tables t WHERE schemaname = 'oathe' AND tablename = 'ddl_applied'");
313
+ const ddlApplied = ddl.rows[0].n === 0
314
+ ? 0
315
+ : (await this.query('SELECT count(*)::int AS n FROM oathe.ddl_applied')).rows[0].n;
316
+ // With no DDL there is no cell schema to ask about the yield cause.
317
+ const causeRegistered = ddlApplied > 0
318
+ && (await this.query(
319
+ 'SELECT count(*)::int AS n FROM cell.claim_yield_cause WHERE cause = $1', [YIELD_CAUSE_FN],
320
+ )).rows[0].n === 1;
321
+ return {
322
+ reachable: true,
323
+ database_exists: true,
324
+ ddl_applied: ddlApplied,
325
+ ddl_expected: DDL_FILES.length,
326
+ ddl_source: ddlSource,
327
+ yield_cause_registered: causeRegistered,
328
+ };
329
+ }
330
+
331
+ async close() {
332
+ if (this.client) {
333
+ await this.client.end();
334
+ this.client = null;
335
+ }
336
+ }
337
+ }
@@ -0,0 +1,31 @@
1
+ // oathe — the successor sequence seam (pickup is what "continue task-x" means; the founder
2
+ // ruling: resuming is what launching means, and picking up happens here).
3
+ //
4
+ // THIN WRAPPER (Stage 1 ruling, 2026-08-26): no execution logic lives in this tree. The real
5
+ // three-call sequence — buildProductionDeps → readPriorAttemptStep → reallocateStep, with the
6
+ // RECOMPILE-vs-RESUME decision inside allocate() — ships with the `oathe-runtime` package and
7
+ // lands behind `oathe-runtime/seam`, which must export
8
+ // buildSuccessor({ substrate, identity, paths }) →
9
+ // { pickup({ task_id, work_claim_id }) → object, close() → void }
10
+ // The runtime-env synthesis and compiler wiring that previously lived here move into that
11
+ // package (they are its concern, not the interface's); this file only delegates or refuses
12
+ // TYPED and LOUD.
13
+
14
+ import { RuntimeError } from './runtime/provider.mjs';
15
+
16
+ /**
17
+ * @returns {Promise<{pickup: (o: {task_id: string, work_claim_id: string}) => Promise<object>,
18
+ * close: () => Promise<void>}>}
19
+ */
20
+ export async function buildSuccessor({ substrate, identity, paths }) {
21
+ let seam;
22
+ try {
23
+ seam = await import('oathe-runtime/seam');
24
+ } catch (e) {
25
+ throw new RuntimeError('OATHE_PICKUP_UNAVAILABLE',
26
+ 'the successor sequence needs the oathe runtime, which does not resolve on this machine '
27
+ + '— pickup cannot pretend; this is a preview limitation until oathe-runtime lands',
28
+ { cause: String(e?.message || e) });
29
+ }
30
+ return seam.buildSuccessor({ substrate, identity, paths });
31
+ }
package/src/traces.mjs ADDED
@@ -0,0 +1,242 @@
1
+ // oathe — the trace stores: how both harnesses' session records are found, validated, and
2
+ // read. The CONTRACT lives in docs/traces.md; both vendors disclaim schema stability, so
3
+ // every read validates and REFUSES loudly (TraceContractError) rather than returning less
4
+ // evidence than a claim recorded. Nothing is hardcoded: every path derives from the store's
5
+ // home (env-overridable), every schema expectation is a named rule here.
6
+
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import zlib from 'node:zlib';
11
+
12
+ /** Which harness a trace path belongs to — the codex store dir is the discriminator. */
13
+ export function harnessForTracePath(file) {
14
+ return String(file).includes(`${path.sep}.codex${path.sep}`) ? 'codex' : 'claude';
15
+ }
16
+
17
+ export class TraceContractError extends Error {
18
+ constructor(code, message, details = {}) {
19
+ super(message);
20
+ this.name = 'TraceContractError';
21
+ this.code = code;
22
+ this.details = details;
23
+ }
24
+ }
25
+
26
+ /** Shared machinery: newline-delimited JSON with optional zstd compression. */
27
+ export class TraceStore {
28
+ /** @param {{home?: string}} o home = the user home the store hangs off (default os.homedir()) */
29
+ constructor({ home } = {}) {
30
+ this.home = home || os.homedir();
31
+ }
32
+
33
+ /** Raw lines of a trace file; handles .zst transparently; refuses unreadable files. */
34
+ readLines(file) {
35
+ let bytes;
36
+ try {
37
+ bytes = fs.readFileSync(file);
38
+ } catch (e) {
39
+ throw new TraceContractError('TRACE_UNREADABLE',
40
+ `trace file cannot be read: ${file} (${e.message})`, { file });
41
+ }
42
+ if (file.endsWith('.zst')) {
43
+ if (typeof zlib.zstdDecompressSync !== 'function') {
44
+ throw new TraceContractError('TRACE_ZSTD_UNSUPPORTED',
45
+ `${file} is zstd-compressed and this node build cannot decompress it — refusing to `
46
+ + 'silently skip evidence', { file });
47
+ }
48
+ bytes = zlib.zstdDecompressSync(bytes);
49
+ }
50
+ return bytes.toString('utf8').split('\n').filter((l) => l.trim() !== '');
51
+ }
52
+
53
+ /** Parsed entries; a malformed line is a typed refusal, never a silent drop. */
54
+ entries(file) {
55
+ return this.readLines(file).map((line, at) => {
56
+ try {
57
+ return JSON.parse(line);
58
+ } catch {
59
+ throw new TraceContractError('TRACE_LINE_MALFORMED',
60
+ `${file}:${at + 1} is not valid JSON — the trace contract is broken`, { file, line: at + 1 });
61
+ }
62
+ });
63
+ }
64
+
65
+ /** validate() returns {ok, detail} — the doctor/monitor form of describe()'s refusals. */
66
+ validate(file) {
67
+ try {
68
+ this.describe(file);
69
+ return { ok: true, detail: null };
70
+ } catch (e) {
71
+ return { ok: false, detail: String(e?.message || e) };
72
+ }
73
+ }
74
+
75
+ #newestIn(dir, matches) {
76
+ if (!fs.existsSync(dir)) return null;
77
+ let best = null;
78
+ for (const entry of fs.readdirSync(dir, { recursive: true })) {
79
+ const full = path.join(dir, String(entry));
80
+ if (!matches(String(entry))) continue;
81
+ const stat = fs.statSync(full, { throwIfNoEntry: false });
82
+ if (stat?.isFile() && (!best || stat.mtimeMs > best.mtimeMs)) best = { full, mtimeMs: stat.mtimeMs };
83
+ }
84
+ return best?.full ?? null;
85
+ }
86
+
87
+ /** Protected helper for subclasses. */
88
+ newestFileIn(dir, matches) {
89
+ return this.#newestIn(dir, matches);
90
+ }
91
+ }
92
+
93
+ const CLAUDE_MESSAGE_TYPES = new Set(['user', 'assistant', 'system']);
94
+
95
+ export class ClaudeTraceStore extends TraceStore {
96
+ get projectsRoot() {
97
+ return path.join(this.home, '.claude', 'projects');
98
+ }
99
+
100
+ /** The encoded project dir for a cwd — verified encoding: /, _ and . become '-'. */
101
+ projectDirFor(cwd) {
102
+ return path.join(this.projectsRoot, cwd.replaceAll(/[/_.]/g, '-'));
103
+ }
104
+
105
+ /**
106
+ * @returns {{harness: 'claude', session_id: string, cwd: string|null, title: string|null,
107
+ * git_branch: string|null, entries: number, path: string}}
108
+ */
109
+ describe(file) {
110
+ const rows = this.entries(file);
111
+ const messages = rows.filter((r) => CLAUDE_MESSAGE_TYPES.has(r.type));
112
+ if (messages.length === 0) {
113
+ throw new TraceContractError('TRACE_CLAUDE_NO_MESSAGES',
114
+ `${file}: no user/assistant/system entries — not a transcript this contract knows`, { file });
115
+ }
116
+ const identity = messages.find((r) => r.sessionId);
117
+ if (!identity) {
118
+ throw new TraceContractError('TRACE_CLAUDE_NO_SESSION',
119
+ `${file}: message entries carry no sessionId — the transcript contract drifted`, { file });
120
+ }
121
+ return {
122
+ harness: 'claude',
123
+ session_id: identity.sessionId,
124
+ cwd: messages.find((r) => r.cwd)?.cwd ?? null,
125
+ title: rows.find((r) => r.type === 'ai-title')?.aiTitle ?? null,
126
+ git_branch: messages.find((r) => r.gitBranch)?.gitBranch ?? null,
127
+ entries: rows.length,
128
+ path: file,
129
+ };
130
+ }
131
+
132
+ /** Fan-out traces: <project>/<sessionId>/subagents/agent-<id>.jsonl (+ .meta.json). */
133
+ subagentsFor(transcriptPath) {
134
+ const sessionId = path.basename(transcriptPath).replace(/\.jsonl(\.zst)?$/, '');
135
+ const dir = path.join(path.dirname(transcriptPath), sessionId, 'subagents');
136
+ if (!fs.existsSync(dir)) return [];
137
+ return fs.readdirSync(dir)
138
+ .filter((f) => /^agent-.+\.jsonl$/.test(f))
139
+ .map((f) => {
140
+ const agentId = f.replace(/^agent-/, '').replace(/\.jsonl$/, '');
141
+ const metaPath = path.join(dir, `agent-${agentId}.meta.json`);
142
+ let meta = null;
143
+ if (fs.existsSync(metaPath)) {
144
+ try {
145
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
146
+ } catch (e) {
147
+ throw new TraceContractError('TRACE_CLAUDE_META_MALFORMED',
148
+ `${metaPath}: subagent meta is not valid JSON (${e.message})`, { file: metaPath });
149
+ }
150
+ }
151
+ return { agent_id: agentId, path: path.join(dir, f), meta };
152
+ });
153
+ }
154
+
155
+ newestTranscript() {
156
+ return this.newestFileIn(this.projectsRoot, (p) => /[0-9a-f-]{36}\.jsonl$/.test(p) && !p.includes('subagents'));
157
+ }
158
+ }
159
+
160
+ export class CodexTraceStore extends TraceStore {
161
+ get codexHome() {
162
+ return path.join(this.home, '.codex');
163
+ }
164
+
165
+ get sessionsRoot() {
166
+ return path.join(this.codexHome, 'sessions');
167
+ }
168
+
169
+ get stateDbPath() {
170
+ return path.join(this.codexHome, 'state_5.sqlite');
171
+ }
172
+
173
+ #db() {
174
+ const sqlite = process.getBuiltinModule('node:sqlite');
175
+ if (!sqlite?.DatabaseSync) {
176
+ throw new TraceContractError('TRACE_CODEX_SQLITE_UNSUPPORTED',
177
+ 'node:sqlite is unavailable in this runtime — the codex thread index cannot be read', {});
178
+ }
179
+ if (!fs.existsSync(this.stateDbPath)) {
180
+ throw new TraceContractError('TRACE_CODEX_STATE_ABSENT',
181
+ `codex state db not found at ${this.stateDbPath}`, { path: this.stateDbPath });
182
+ }
183
+ return new sqlite.DatabaseSync(this.stateDbPath, { readOnly: true });
184
+ }
185
+
186
+ /**
187
+ * @returns {{harness: 'codex', session_id: string, cwd: string|null, source: *,
188
+ * entries: number, path: string}}
189
+ */
190
+ describe(file) {
191
+ const rows = this.entries(file);
192
+ const head = rows[0];
193
+ if (head?.type !== 'session_meta') {
194
+ throw new TraceContractError('TRACE_CODEX_NO_META',
195
+ `${file}: first line is '${head?.type}', expected session_meta — the rollout contract drifted`,
196
+ { file });
197
+ }
198
+ const meta = head.payload ?? {};
199
+ if (!meta.id && !meta.session_id) {
200
+ throw new TraceContractError('TRACE_CODEX_NO_ID',
201
+ `${file}: session_meta carries neither id nor session_id`, { file });
202
+ }
203
+ return {
204
+ harness: 'codex',
205
+ session_id: meta.id ?? meta.session_id,
206
+ cwd: meta.cwd ?? null,
207
+ source: meta.source ?? null,
208
+ entries: rows.length,
209
+ path: file,
210
+ };
211
+ }
212
+
213
+ /** The sqlite index row for a thread — rollout path, git identity, tokens. */
214
+ threadRow(threadId) {
215
+ const db = this.#db();
216
+ try {
217
+ return db.prepare(
218
+ 'SELECT id, rollout_path, cwd, title, tokens_used, git_sha, git_branch, source FROM threads WHERE id = ?',
219
+ ).get(threadId) ?? null;
220
+ } finally {
221
+ db.close();
222
+ }
223
+ }
224
+
225
+ /** Fan-out: children of a thread per thread_spawn_edges, joined to their rollout paths. */
226
+ childThreads(threadId) {
227
+ const db = this.#db();
228
+ try {
229
+ return db.prepare(
230
+ `SELECT e.child_thread_id AS thread_id, t.rollout_path, t.cwd, t.title
231
+ FROM thread_spawn_edges e LEFT JOIN threads t ON t.id = e.child_thread_id
232
+ WHERE e.parent_thread_id = ?`,
233
+ ).all(threadId);
234
+ } finally {
235
+ db.close();
236
+ }
237
+ }
238
+
239
+ newestRollout() {
240
+ return this.newestFileIn(this.sessionsRoot, (p) => /rollout-.+\.jsonl(\.zst)?$/.test(p));
241
+ }
242
+ }
@@ -0,0 +1,45 @@
1
+ // oathe uninstall — remove exactly the recorded blocks/entries, restore nothing else, drop
2
+ // nothing (the cell database is the durable record; --purge-db is the one exception, asked
3
+ // for by name).
4
+
5
+ import fs from 'node:fs';
6
+
7
+ import { buildContext } from './context.mjs';
8
+ import { FencedBlock, FENCE_STYLES } from './blocks.mjs';
9
+
10
+ /** @returns {Promise<{actions: object[], database_dropped: boolean}>} */
11
+ export async function runUninstall({ env = process.env, exec, purgeDb = false } = {}) {
12
+ const ctx = buildContext({ env, exec });
13
+ const { manifest, harnesses, substrate } = ctx;
14
+ try {
15
+ const actions = [];
16
+ for (const harness of harnesses) {
17
+ if (!manifest.rows.some((r) => r.harness === harness.name)) continue;
18
+ for (const action of harness.offboard({ manifest })) {
19
+ actions.push({ harness: harness.name, ...action });
20
+ }
21
+ }
22
+ // Project-scope fences (CLAUDE.md/AGENTS.md rows written by launch pre-flights).
23
+ for (const row of manifest.removeWhere((r) => r.kind === 'fence')) {
24
+ if (!fs.existsSync(row.file)) continue;
25
+ const block = new FencedBlock({ style: FENCE_STYLES[row.detail?.style ?? 'hash'] });
26
+ const { content, changed } = block.remove(fs.readFileSync(row.file, 'utf8'));
27
+ if (!changed) continue;
28
+ const createdByUs = manifest.backups.find((b) => b.file === row.file)?.absent_before === true;
29
+ if (createdByUs && content.trim() === '') fs.rmSync(row.file);
30
+ else fs.writeFileSync(row.file, content);
31
+ actions.push({ action: 'fence-removed', file: row.file });
32
+ }
33
+ manifest.save();
34
+
35
+ let databaseDropped = false;
36
+ if (purgeDb) {
37
+ await substrate.close();
38
+ await substrate.dropDatabase();
39
+ databaseDropped = true;
40
+ }
41
+ return { actions, database_dropped: databaseDropped };
42
+ } finally {
43
+ await substrate.close();
44
+ }
45
+ }