@oathe/oathe 0.2.3 → 0.3.2

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 +401 -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 +160 -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,180 @@
1
+ // oathe — the harness catalog: the ONE registry over every adapter, and the sweeps that answer
2
+ // every "which harness can…?" BY CAPABILITY. Nothing else in the tree keys on a harness name or
3
+ // a flag: the verifier asks verifierCapable(), the doctor asks traceStores(), the launcher asks
4
+ // launchable(), init asks wireable() and verifiers(census). Adding a harness means adding an
5
+ // adapter file and one entry HERE — the contract suite's golden capability table is the spec.
6
+
7
+ import { Harness, HarnessOnboardError, census } from './harness.mjs';
8
+ import { DIALECTS } from './dialects.mjs';
9
+ import { TraceContractError } from '../traces.mjs';
10
+ import { ClaudeHarness } from './claude.mjs';
11
+ import { CodexHarness } from './codex.mjs';
12
+ import { CursorHarness } from './cursor.mjs';
13
+ import { ChatGptWebSurface, CoworkSurface } from './surfaces.mjs';
14
+
15
+ export { Harness, HarnessOnboardError, census, ClaudeHarness, CodexHarness, CursorHarness, CoworkSurface, ChatGptWebSurface };
16
+
17
+ /** Every surface oathe knows — wired harnesses and detect-only surfaces, one hierarchy. */
18
+ export const HARNESS_CLASSES = Object.freeze([ClaudeHarness, CodexHarness, CursorHarness, CoworkSurface, ChatGptWebSurface]);
19
+
20
+ /** @returns {typeof Harness} */
21
+ export function byName(name) {
22
+ const found = HARNESS_CLASSES.find((C) => C.harnessName === name);
23
+ if (!found) {
24
+ throw new Error(`no harness '${name}' — known harnesses: ${HARNESS_CLASSES.map((C) => C.harnessName).join(', ')}`);
25
+ }
26
+ return found;
27
+ }
28
+
29
+ const names = (predicate) => HARNESS_CLASSES.filter(predicate).map((C) => C.harnessName);
30
+
31
+ /** The harnesses an installer can wire (the wiring capability). */
32
+ export function wireable() {
33
+ return names((C) => C.wiring !== null);
34
+ }
35
+
36
+ /** The harnesses `oathe <name>` can launch inside the cage (the launch capability). */
37
+ export function launchable() {
38
+ return names((C) => C.launch !== null);
39
+ }
40
+
41
+ /** The harnesses that can judge completed work — every one with a headless run. Validates config. */
42
+ export function verifierCapable() {
43
+ return names((C) => C.headless !== null);
44
+ }
45
+
46
+ /** The verifier candidates on THIS machine: headless-capable AND the CLI is actually present. */
47
+ export function verifiers(seen) {
48
+ const present = new Map(seen.map((d) => [d.name, d]));
49
+ return verifierCapable().filter((name) => present.get(name)?.presence?.cli === true);
50
+ }
51
+
52
+ /** The harnesses with a session-record store the verifier and doctor read (the traces capability). */
53
+ export function traceStores() {
54
+ return names((C) => C.traces !== null);
55
+ }
56
+
57
+ /** The harnesses with a REAL CLI the install-contract lane can install and prove against. */
58
+ export function installable() {
59
+ return names((C) => C.install !== null);
60
+ }
61
+
62
+ /** The harnesses with a headless run the live-behaviour lane can drive. */
63
+ export function liveTestable() {
64
+ return names((C) => C.headless !== null);
65
+ }
66
+
67
+ /**
68
+ * The golden capability table — harness → which capabilities it possesses. The contract suite
69
+ * pins it row for row: a supported harness has every touchpoint mapped, and a row change is a
70
+ * reviewed change (PLAN.md R-HARNESS-TOUCHPOINTS).
71
+ */
72
+ export function capabilityTable() {
73
+ return Object.fromEntries(HARNESS_CLASSES.map((C) => [C.harnessName, {
74
+ wiring: C.wiring !== null,
75
+ hooks: C.hooks !== null,
76
+ launch: C.launch !== null,
77
+ headless: C.headless !== null,
78
+ traces: C.traces !== null,
79
+ surfaces: C.surfaces !== null,
80
+ contextFiles: C.contextFiles.length > 0,
81
+ globalContextFiles: C.globalContextFiles.length > 0,
82
+ synthetic: C.isSyntheticWorkspaceDir !== Harness.isSyntheticWorkspaceDir,
83
+ install: C.install !== null,
84
+ docs: C.docs.length > 0,
85
+ }]));
86
+ }
87
+
88
+ /** [name, envVar] pairs for every adapter that documents a project-dir env var. */
89
+ export function projectDirEnvVars() {
90
+ return HARNESS_CLASSES.filter((C) => C.projectDirEnvVar !== null)
91
+ .map((C) => [C.harnessName, C.projectDirEnvVar]);
92
+ }
93
+
94
+ /** R-BOARD-SCOPE: does ANY adapter stage `dir` as a synthetic workspace? Asked once, by the resolver. */
95
+ export function isSyntheticWorkspace({ dir, home }) {
96
+ return HARNESS_CLASSES.some((C) => C.isSyntheticWorkspaceDir({ dir, home }));
97
+ }
98
+
99
+ /** Drift: the adapters and surfaces whose facts derive from the snapshot page `key`. */
100
+ export function docsDependents(key) {
101
+ return names((C) => C.docs.includes(key));
102
+ }
103
+
104
+ /** The hook dialect whose sniff accepts `input`, or null — shapes, not harness identity. */
105
+ export function dialectFor(input) {
106
+ return DIALECTS.find((d) => d.matches(input)) ?? null;
107
+ }
108
+
109
+ /** The harness an MCP client is, from its declared clientNames — or null. */
110
+ export function harnessForClient(clientName) {
111
+ const name = String(clientName ?? '').toLowerCase();
112
+ if (name === '') return null;
113
+ return HARNESS_CLASSES.find((C) => C.clientNames.some((c) => name.includes(c)))?.harnessName ?? null;
114
+ }
115
+
116
+ /** Which store owns a session record — each store's own predicate; null when nobody's. */
117
+ export function ownerOfTracePath(file) {
118
+ return HARNESS_CLASSES.find((C) => C.traces?.ownsPath(file))?.harnessName ?? null;
119
+ }
120
+
121
+ /**
122
+ * The NEAREST adapter-owned process in an ancestry chain — the harness the chain speaks
123
+ * for. Harnesses interpose helpers between themselves and their children (cursor-agent
124
+ * runs hooks through a /bin/zsh; MCP servers are node), so ownership is never decided by
125
+ * the chain's head alone. -1 when nobody in the chain is a harness. ONE implementation:
126
+ * surface naming, speaker resolution, and hook registration all ask here.
127
+ */
128
+ export function ownedAncestorIndex(ancestry) {
129
+ return ancestry.findIndex((a) => HARNESS_CLASSES.some((C) => C.surfaces?.ownsExec(a?.exec ?? '')));
130
+ }
131
+
132
+ /**
133
+ * NAME the surface a registered session speaks from — facts in, name out, at read time
134
+ * (the sessions file stores facts only, so naming evolves without rewriting history).
135
+ * Ownership: the trace store that owns the transcript wins (environment-independent);
136
+ * else the adapter owning the NEAREST harness process in the chain. Nobody's process is
137
+ * null — never a guess.
138
+ */
139
+ export function surfaceForSession({ ancestry = [], app = null, transcriptPath = null }) {
140
+ const idx = ownedAncestorIndex(ancestry);
141
+ const exec = (idx === -1 ? ancestry[0]?.exec : ancestry[idx].exec) ?? '';
142
+ const owner = ownerOfTracePath(transcriptPath ?? '')
143
+ ?? (idx === -1 ? null : HARNESS_CLASSES.find((C) => C.surfaces?.ownsExec(exec))?.harnessName) ?? null;
144
+ if (owner === null) return null;
145
+ const { surfaces } = byName(owner);
146
+ return surfaces === null ? owner : surfaces.name({ exec, appBundle: app?.bundle ?? null });
147
+ }
148
+
149
+ /**
150
+ * The ATIF projector for a session record, from the store that owns it — or a typed refusal:
151
+ * a file no store owns is not evidence, never "probably Claude".
152
+ */
153
+ export async function projectorFor(file, { home } = {}) {
154
+ const owner = ownerOfTracePath(file);
155
+ if (owner === null) {
156
+ throw new TraceContractError('TRACE_OWNER_UNKNOWN',
157
+ `no trace store owns '${file}' — known stores: ${traceStores().join(', ')}`, { file });
158
+ }
159
+ const { traces } = byName(owner);
160
+ const store = await traces.store({ home });
161
+ return traces.projector({ store });
162
+ }
163
+
164
+ /** Instantiate every adapter whose wiring exists — the init/uninstall roster. */
165
+ export function buildWireable({ home, envPath, paths, exec }) {
166
+ return HARNESS_CLASSES.filter((C) => C.wiring !== null).map((C) => new C({ home, envPath, paths, exec }));
167
+ }
168
+
169
+ /** Instantiate every adapter — detection sweeps (the picker census) see them all. */
170
+ export function buildAll({ home, envPath, paths, exec }) {
171
+ return HARNESS_CLASSES.map((C) => new C({ home, envPath, paths, exec }));
172
+ }
173
+
174
+ /** The detect-only surfaces as the picker prints them: detected + the manual steps. */
175
+ export function detectOnlySurfaces({ home, platform = process.platform }) {
176
+ return HARNESS_CLASSES.filter((C) => C.wiring === null).map((C) => {
177
+ const surface = new C({ home, platform });
178
+ return { name: C.harnessName, displayName: C.displayName, detected: surface.detect().installed, steps: C.note };
179
+ });
180
+ }
@@ -0,0 +1,196 @@
1
+ // oathe — the Claude Code adapter: owned JSON paths in ~/.claude/settings.json declare the
2
+ // install, the claude CLI materializes it, and the CLI's own plugin registry is the proof.
3
+ // Every Claude-specific fact — context file, project-dir env var, hook dialect, verifier
4
+ // command line, trace store — is a named member HERE.
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ import { Harness, HarnessOnboardError } from './harness.mjs';
10
+ import { cwdDialect } from './dialects.mjs';
11
+ import { JsonEntries } from '../blocks.mjs';
12
+ import { sha256Hex } from '../manifest.mjs';
13
+
14
+ export class ClaudeHarness extends Harness {
15
+ static harnessName = 'claude';
16
+ static displayName = 'Claude Code';
17
+ static covers = 'CLI'; // the desktop app exists but the row stays CLI (ruling 2026-08-29 — no confusion)
18
+ static bin = 'claude';
19
+ static clientNames = Object.freeze(['claude-code', 'claude']);
20
+ static contextFiles = Object.freeze(['CLAUDE.md']);
21
+ // Claude Code sets this directly in every spawned stdio server's and hook's environment —
22
+ // the documented way a server learns the project root on this harness.
23
+ static projectDirEnvVar = 'CLAUDE_PROJECT_DIR';
24
+ static wiring = Object.freeze({ needsCli: true });
25
+ static hooks = Object.freeze({ dialect: cwdDialect });
26
+ // Claude Code shows the systemMessage banner inside its own TUI — no scrollback splash needed.
27
+ static launch = Object.freeze({ splash: false, bin: 'claude' });
28
+ // One name everywhere claude runs (founder ruling 2026-08-30: no desktop/CLI split).
29
+ static surfaces = Object.freeze({
30
+ ownsExec: (exec) => path.basename(exec) === 'claude',
31
+ name: () => 'claude',
32
+ });
33
+ static install = Object.freeze({ npm: '@anthropic-ai/claude-code', bin: 'claude', versionArgs: ['--version'] });
34
+ // Non-interactive auth: ANTHROPIC_API_KEY (claude-code/headless.md, pinned 2026-08-29).
35
+ static headless = Object.freeze({
36
+ auth: ['ANTHROPIC_API_KEY'],
37
+ command: (prompt, model = null) => ['claude', ['-p', prompt, '--output-format', 'json', ...(model ? ['--model', model] : [])]],
38
+ extract: (stdout) => ClaudeHarness.extractJsonResult(stdout),
39
+ });
40
+ static traces = Object.freeze({
41
+ store: async ({ home }) => new (await import('../traces.mjs')).ClaudeTraceStore({ home, harness: this.harnessName }),
42
+ newest: (store) => store.newestTranscript(),
43
+ projector: async ({ store }) => new (await import('../atif.mjs')).ClaudeAtifProjector({ store }),
44
+ ownsPath: (file) => String(file).includes(`${path.sep}.claude${path.sep}`),
45
+ });
46
+ static docs = Object.freeze([
47
+ 'claude-code/mcp', 'claude-code/plugins', 'claude-code/plugins-reference', 'claude-code/hooks',
48
+ 'claude-code/settings', 'claude-code/desktop', 'claude-code/memory', 'claude-code/managed-mcp',
49
+ 'claude-code/cli-reference', 'claude-code/headless',
50
+ ]);
51
+
52
+ constructor(o) {
53
+ super({ ...o, name: 'claude' });
54
+ this.entries = new JsonEntries();
55
+ }
56
+
57
+ get settingsPath() {
58
+ return path.join(this.configHome, 'settings.json');
59
+ }
60
+
61
+ /** The exact keys oathe owns in settings.json — the whole Claude install. */
62
+ #ownedEntries() {
63
+ return [
64
+ {
65
+ // "directory" is what the INSTALLED CLI's settings schema accepts (verified empirically
66
+ // on 2.1.241: the pre-existing custom-plugins entry validates, a "local" entry is
67
+ // rejected with "Invalid input" and the whole file is skipped). The docs say "local";
68
+ // the binary outranks the docs.
69
+ path: ['extraKnownMarketplaces', 'oathe'],
70
+ value: { source: { source: 'directory', path: this.paths.packageRoot } },
71
+ },
72
+ { path: ['enabledPlugins', 'oathe@oathe'], value: true },
73
+ ];
74
+ }
75
+
76
+ get registryDir() {
77
+ return path.join(this.configHome, 'plugins');
78
+ }
79
+
80
+ get installedFile() {
81
+ return path.join(this.registryDir, 'installed_plugins.json');
82
+ }
83
+
84
+ #readRegistry(file) {
85
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
86
+ }
87
+
88
+ #installedVersion() {
89
+ return this.#readRegistry(this.installedFile)?.plugins?.['oathe@oathe']?.[0]?.version ?? null;
90
+ }
91
+
92
+ /** The path the CLI's registry records for the oathe marketplace, or null when unknown. */
93
+ #marketplacePath() {
94
+ return this.#readRegistry(path.join(this.registryDir, 'known_marketplaces.json'))?.oathe?.source?.path ?? null;
95
+ }
96
+
97
+ installedPluginVersion() {
98
+ return this.#installedVersion();
99
+ }
100
+
101
+ #cli(args) {
102
+ const result = this.exec.run('claude', args);
103
+ if (result.status !== 0) {
104
+ throw new HarnessOnboardError('CLAUDE_CLI_FAILED',
105
+ `claude ${args.join(' ')} exited ${result.status}: ${result.stderr.trim()}`, { args });
106
+ }
107
+ return result;
108
+ }
109
+
110
+ /** What init writes — from the owned entries and the registry the CLI materializes into. */
111
+ describe() {
112
+ return [
113
+ `${this.settingsPath}: owns ${this.#ownedEntries().map((e) => e.path.join('.')).join(' and ')}`,
114
+ `\`claude plugin install oathe@oathe\` — the Oathe plugin (board at session start, auto-save hooks, the oathe_* MCP tools), recorded in ${this.installedFile}`,
115
+ ];
116
+ }
117
+
118
+ onboard({ manifest, version }) {
119
+ const entries = this.#ownedEntries();
120
+ const before = fs.existsSync(this.settingsPath) ? fs.readFileSync(this.settingsPath, 'utf8') : '';
121
+ manifest.backupOnce(this.settingsPath);
122
+ const { content, changed } = this.entries.apply(before, entries);
123
+ if (changed) {
124
+ fs.mkdirSync(path.dirname(this.settingsPath), { recursive: true });
125
+ fs.writeFileSync(this.settingsPath, content);
126
+ }
127
+ manifest.upsert({
128
+ harness: this.name,
129
+ file: this.settingsPath,
130
+ kind: 'json-path',
131
+ detail: { paths: entries.map((e) => e.path) },
132
+ blockVersion: version,
133
+ sha256: sha256Hex(JSON.stringify(entries)),
134
+ });
135
+
136
+ // MATERIALIZE via the CLI. The settings entries above are the declarative pin, but the CLI's
137
+ // own registry (installed_plugins.json) is what sessions load from — and the install is a
138
+ // CACHED COPY keyed by version, so a version change must evict the stale copy.
139
+ const installed = this.#installedVersion();
140
+ // UPGRADE PATH: the package root MOVES between installs (an nvm node switch, npm link). A
141
+ // marketplace known at another path materializes stale code — even at the same version —
142
+ // so a moved source is a materialization exactly like a version change: re-register the
143
+ // marketplace from this root, then reinstall the plugin from it.
144
+ const known = this.#marketplacePath();
145
+ const moved = known !== null && known !== this.paths.packageRoot;
146
+ let materialized = false;
147
+ if (installed !== version || moved) {
148
+ if (moved) this.#cli(['plugin', 'marketplace', 'remove', 'oathe']);
149
+ if (known === null || moved) this.#cli(['plugin', 'marketplace', 'add', this.paths.packageRoot]);
150
+ // Removing a marketplace takes the plugins installed from it along (observed on the real
151
+ // CLI, 2026-08-29) — decide the uninstall on what is installed NOW, not what was.
152
+ if (this.#installedVersion() !== null) this.#cli(['plugin', 'uninstall', 'oathe@oathe']);
153
+ this.#cli(['plugin', 'install', 'oathe@oathe']);
154
+ if (this.#installedVersion() !== version) {
155
+ throw new HarnessOnboardError('CLAUDE_VERIFICATION_FAILED',
156
+ 'verification failed: `claude plugin install oathe@oathe` reported success but '
157
+ + `${this.installedFile} does not record version ${version} — refusing to record an `
158
+ + 'install that cannot be proven');
159
+ }
160
+ materialized = true;
161
+ }
162
+ manifest.upsert({
163
+ harness: this.name,
164
+ file: this.installedFile,
165
+ kind: 'cli-managed',
166
+ detail: {
167
+ id: 'plugin-install',
168
+ proof: 'oathe@oathe',
169
+ undo: [['plugin', 'uninstall', 'oathe@oathe'], ['plugin', 'marketplace', 'remove', 'oathe']],
170
+ },
171
+ blockVersion: version,
172
+ sha256: sha256Hex('oathe@oathe'),
173
+ });
174
+ return [
175
+ { action: 'settings-owned-paths', file: this.settingsPath, changed },
176
+ { action: materialized ? 'plugin-installed' : 'plugin-already-current', file: this.installedFile },
177
+ ];
178
+ }
179
+
180
+ offboard({ manifest }) {
181
+ const rows = manifest.removeWhere((r) => r.harness === this.name);
182
+ const actions = [];
183
+ for (const row of rows.filter((r) => r.kind === 'cli-managed')) {
184
+ for (const undo of row.detail?.undo ?? []) {
185
+ const result = this.exec.run('claude', undo);
186
+ actions.push({ action: `claude-undo-${undo.join('-')}`, status: result.status });
187
+ }
188
+ }
189
+ if (!fs.existsSync(this.settingsPath)) return [...actions, { action: 'settings-absent' }];
190
+ const before = fs.readFileSync(this.settingsPath, 'utf8');
191
+ const ownedPaths = rows.flatMap((r) => r.detail?.paths ?? []);
192
+ const { content, changed } = this.entries.remove(before, ownedPaths);
193
+ if (changed) fs.writeFileSync(this.settingsPath, content);
194
+ return [...actions, { action: 'settings-owned-paths-removed', file: this.settingsPath, changed }];
195
+ }
196
+ }
@@ -0,0 +1,188 @@
1
+ // oathe — the OpenAI Codex adapter (one host serves the CLI, the IDE extension, and the
2
+ // ChatGPT desktop app): three sanctioned CLIs register the install, and the config.toml
3
+ // stanza each one writes is the proof (its stanzas are Codex-managed bookkeeping — writing
4
+ // them by hand is how two managers end up owning one file). Every Codex-specific fact is a
5
+ // named member HERE. Codex allowlist-filters the env it hands MCP servers and documents no
6
+ // project-dir variable — the resolution ladder's cwd/refusal steps carry this harness.
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ import { Harness, HarnessOnboardError } from './harness.mjs';
12
+ import { cwdDialect } from './dialects.mjs';
13
+ import { sha256Hex } from '../manifest.mjs';
14
+
15
+ // The id Codex knows the plugin by (plugin@marketplace) — the registrations install it and
16
+ // Codex keys its own hook-trust bookkeeping under it.
17
+ const PLUGIN_ID = 'oathe@oathe';
18
+
19
+ /** realpath when the path exists (macOS aliases /var → /private/var), else the normalized path. */
20
+ function realpathOr(p) {
21
+ try { return fs.realpathSync(p); } catch { return path.resolve(p); }
22
+ }
23
+
24
+ export class CodexHarness extends Harness {
25
+ static harnessName = 'codex';
26
+ static displayName = 'Codex';
27
+ static covers = 'CLI/Desktop App'; // ChatGPT desktop rides the same ~/.codex wiring
28
+ static bin = 'codex';
29
+ static clientNames = Object.freeze(['codex']);
30
+ static contextFiles = Object.freeze(['AGENTS.md']);
31
+ static projectDirEnvVar = null;
32
+ static wiring = Object.freeze({ needsCli: true });
33
+ static hooks = Object.freeze({ dialect: cwdDialect });
34
+ // Codex buries hook output in its ctrl+T transcript overlay, unrendered — the launcher's
35
+ // ANSI splash into terminal scrollback is this harness's quirk.
36
+ static launch = Object.freeze({ splash: true, bin: 'codex' });
37
+ // The ChatGPT desktop app embeds codex (…/ChatGPT.app/Contents/Resources/codex, live
38
+ // trace 2026-08-30) — the SURFACE is chatgpt there, codex in a terminal.
39
+ static surfaces = Object.freeze({
40
+ ownsExec: (exec) => path.basename(exec) === 'codex',
41
+ name: ({ appBundle }) => (appBundle !== null && path.basename(appBundle) === 'ChatGPT.app' ? 'chatgpt' : 'codex'),
42
+ });
43
+ // Codex reads its global instructions before any work, in EVERY session — the one channel
44
+ // that reaches a ChatGPT-desktop session, whose staging cwd carries no folder fence. Its
45
+ // rule (docs, agents-md): AGENTS.override.md if it exists, otherwise AGENTS.md.
46
+ static globalContextFiles = Object.freeze(['AGENTS.override.md', 'AGENTS.md']);
47
+ // The ChatGPT desktop app runs every conversation from a directory it stages under the
48
+ // config home — not a project folder. Sessions there serve the FULL board and are never
49
+ // activated (R-BOARD-SCOPE); this member is the only place the staging path is spelled.
50
+ static syntheticWorkspaceParent = '.chatgpt-projects';
51
+
52
+ static isSyntheticWorkspaceDir({ dir, home }) {
53
+ const parent = realpathOr(path.join(this.configHomeFor(home), this.syntheticWorkspaceParent));
54
+ return realpathOr(dir).startsWith(`${parent}${path.sep}`);
55
+ }
56
+
57
+ static install = Object.freeze({ npm: '@openai/codex', bin: 'codex', versionArgs: ['--version'] });
58
+ // Non-interactive auth: CODEX_API_KEY "provides an API key to a non-interactive Codex
59
+ // process" (codex/environment-variables.md:49, pinned 2026-08-29).
60
+ static headless = Object.freeze({
61
+ auth: ['CODEX_API_KEY'],
62
+ command: (prompt, model = null) => ['codex', ['exec', '--skip-git-repo-check', ...(model ? ['-m', model] : []), prompt]],
63
+ extract: (stdout) => stdout,
64
+ });
65
+ static traces = Object.freeze({
66
+ store: async ({ home }) => new (await import('../traces.mjs')).CodexTraceStore({ home, harness: this.harnessName }),
67
+ newest: (store) => store.newestRollout(),
68
+ projector: async ({ store }) => new (await import('../atif.mjs')).CodexAtifProjector({ store }),
69
+ ownsPath: (file) => String(file).includes(`${path.sep}.codex${path.sep}`),
70
+ });
71
+ static docs = Object.freeze([
72
+ 'codex/mcp', 'codex/config-reference', 'codex/environment-variables', 'codex/agents-md', 'codex/hooks',
73
+ 'codex/projects', 'codex/plugins', 'codex/submit-claude-plugin',
74
+ ]);
75
+
76
+ constructor(o) {
77
+ super({ ...o, name: 'codex' });
78
+ }
79
+
80
+ get configPath() {
81
+ return path.join(this.configHome, 'config.toml');
82
+ }
83
+
84
+ /**
85
+ * The sanctioned registrations, each with the CLI that makes it, the config.toml stanza that
86
+ * proves it landed, and the CLI that undoes it.
87
+ */
88
+ #registrations() {
89
+ return [
90
+ {
91
+ id: 'marketplace',
92
+ add: ['plugin', 'marketplace', 'add', this.paths.packageRoot],
93
+ proof: '[marketplaces.oathe]',
94
+ undo: ['plugin', 'marketplace', 'remove', 'oathe'],
95
+ },
96
+ {
97
+ id: 'plugin',
98
+ add: ['plugin', 'add', PLUGIN_ID],
99
+ proof: `[plugins."${PLUGIN_ID}"]`,
100
+ undo: ['plugin', 'remove', PLUGIN_ID],
101
+ },
102
+ {
103
+ id: 'mcp-server',
104
+ add: ['mcp', 'add', 'oathe', '--', 'oathe', 'mcp'],
105
+ proof: '[mcp_servers.oathe]',
106
+ undo: ['mcp', 'remove', 'oathe'],
107
+ },
108
+ ];
109
+ }
110
+
111
+ /** What init writes — from the registrations the CLI makes and the global fence target. */
112
+ describe() {
113
+ const globals = this.constructor.globalContextFiles.map((f) => path.join(this.configHome, f)).join(' (or ');
114
+ return [
115
+ `${this.configPath}: ${this.#registrations().map((r) => r.proof).join(', ')} via the codex CLI (marketplace, plugin, MCP server)`,
116
+ `${globals}${this.constructor.globalContextFiles.length > 1 ? ')' : ''}: the standing Oathe rule for every Codex session — ChatGPT desktop reads it too`,
117
+ ];
118
+ }
119
+
120
+ onboard({ manifest, version }) {
121
+ manifest.backupOnce(this.configPath);
122
+ for (const reg of this.#registrations()) {
123
+ let result = this.exec.run('codex', reg.add);
124
+ // UPGRADE PATH: the package root MOVED (an nvm node switch, npm link) — the CLI refuses a
125
+ // marketplace "already added from a different source". Re-register from this root: the
126
+ // undo the manifest already records, then the add again, proof-checked below.
127
+ if (result.status !== 0 && /already added from a different source/.test(result.stderr)) {
128
+ this.exec.run('codex', reg.undo);
129
+ result = this.exec.run('codex', reg.add);
130
+ }
131
+ if (result.status !== 0) {
132
+ throw new HarnessOnboardError('CODEX_CLI_FAILED',
133
+ `codex ${reg.add.join(' ')} exited ${result.status}: ${result.stderr.trim()}`, { reg: reg.id });
134
+ }
135
+ const config = fs.existsSync(this.configPath) ? fs.readFileSync(this.configPath, 'utf8') : '';
136
+ if (!config.includes(reg.proof)) {
137
+ throw new HarnessOnboardError('CODEX_VERIFICATION_FAILED',
138
+ `verification failed: codex ${reg.add.join(' ')} reported success but ${this.configPath} `
139
+ + `carries no ${reg.proof} stanza — refusing to record an install that cannot be proven`,
140
+ { reg: reg.id });
141
+ }
142
+ manifest.upsert({
143
+ harness: this.name,
144
+ file: this.configPath,
145
+ kind: 'cli-managed',
146
+ detail: { id: reg.id, proof: reg.proof, undo: reg.undo },
147
+ blockVersion: version,
148
+ sha256: sha256Hex(reg.proof),
149
+ });
150
+ }
151
+ return this.#registrations().map((r) => ({ action: `codex-${r.id}` }));
152
+ }
153
+
154
+ offboard({ manifest }) {
155
+ const rows = manifest.removeWhere((r) => r.harness === this.name);
156
+ const actions = [];
157
+ // Undo in reverse install order, so the plugin is gone before its marketplace is.
158
+ for (const row of rows.reverse()) {
159
+ const undo = row.detail?.undo;
160
+ if (!undo) continue;
161
+ const result = this.exec.run('codex', undo);
162
+ actions.push({ action: `codex-undo-${row.detail.id}`, status: result.status });
163
+ }
164
+ // Codex keys hook-trust records under our plugin id; the undo CLIs orphan them, and an
165
+ // orphan carrying 'oathe' is still an oathe entry on this surface (ruling 2026-08-29:
166
+ // delete exactly the keys prefixed by our id, touch nothing else).
167
+ if (this.#clearHooksState() > 0) actions.push({ action: 'codex-hooks-state-cleared', status: 0 });
168
+ return actions;
169
+ }
170
+
171
+ /** Remove the `[hooks.state."<PLUGIN_ID>:…"]` tables from config.toml; every other line stays. */
172
+ #clearHooksState() {
173
+ if (!fs.existsSync(this.configPath)) return 0;
174
+ const prefix = `[hooks.state."${PLUGIN_ID}:`;
175
+ const kept = [];
176
+ let removed = 0;
177
+ let skipping = false;
178
+ for (const line of fs.readFileSync(this.configPath, 'utf8').split('\n')) {
179
+ if (line.trimStart().startsWith('[')) {
180
+ skipping = line.trimStart().startsWith(prefix);
181
+ if (skipping) removed += 1;
182
+ }
183
+ if (!skipping) kept.push(line);
184
+ }
185
+ if (removed > 0) fs.writeFileSync(this.configPath, kept.join('\n'));
186
+ return removed;
187
+ }
188
+ }