@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
package/src/config.mjs CHANGED
@@ -7,6 +7,8 @@ import fs from 'node:fs';
7
7
  import os from 'node:os';
8
8
  import path from 'node:path';
9
9
 
10
+ import { launchable, verifierCapable } from './harnesses/catalog.mjs';
11
+
10
12
  export class ConfigError extends Error {
11
13
  constructor(code, message, details = {}) {
12
14
  super(message);
@@ -16,7 +18,7 @@ export class ConfigError extends Error {
16
18
  }
17
19
  }
18
20
 
19
- const ENGINES = ['claude', 'codex'];
21
+ const ENGINES = verifierCapable();
20
22
 
21
23
  /** Every key: default, env var, validator. Adding a tunable means adding a row HERE. */
22
24
  const KEYS = Object.freeze({
@@ -35,13 +37,31 @@ const KEYS = Object.freeze({
35
37
  pgPort: { default: 5432, env: 'OATHE_PG_PORT', check: positiveInt },
36
38
  leaseHours: { default: 4, env: 'OATHE_LEASE_HOURS', check: positiveInt },
37
39
  verifyByHours: { default: 24, env: 'OATHE_VERIFY_BY_HOURS', check: positiveInt },
38
- verifier: { default: 'claude', env: 'OATHE_VERIFIER', check: oneOf(ENGINES) },
40
+ verifier: { default: ENGINES[0], env: 'OATHE_VERIFIER', check: oneOf(ENGINES) },
41
+ // Who picks your work back up (the notch's continue, resumption spawning): chosen at
42
+ // onboarding — the init question ABOVE the verifier question (founder ruling 2026-08-30).
43
+ defaultAgent: { default: null, env: 'OATHE_DEFAULT_AGENT', check: nullOrOneOf(launchable()) },
39
44
  verifierPrincipal: { default: 'oathe-verifier', env: 'OATHE_VERIFIER_PRINCIPAL', check: nonEmptyString },
40
45
  verifierEvidenceBudget: { default: 24000, env: 'OATHE_VERIFIER_EVIDENCE_BUDGET', check: positiveInt },
41
46
  runtimeProvider: { default: 'auto', env: 'OATHE_RUNTIME_PROVIDER', check: oneOf(['auto', 'oathe', 'standalone']) },
42
- starUrl: {
43
- default: 'https://github.com/oathe-ai/oathe', env: 'OATHE_STAR_URL', check: httpsUrl,
44
- },
47
+ // Activation (registry row + context-file fences) on first use in a workspace: the off
48
+ // switch for machines that want register-only sessions.
49
+ autoActivate: { default: true, env: 'OATHE_AUTO_ACTIVATE', check: boolean },
50
+ // How long the MCP server waits on a client's roots/list answer before falling down the
51
+ // resolution ladder.
52
+ rootsTimeoutMs: { default: 2000, env: 'OATHE_ROOTS_TIMEOUT_MS', check: positiveInt },
53
+ // R-PAGER: an active claim with no non-trace progress statement inside this many hours is
54
+ // a breached promise (paged at session start). Lifecycle facts like a lapsed lease are not.
55
+ pagerQuietHours: { default: 24, env: 'OATHE_PAGER_QUIET_HOURS', check: positiveInt },
56
+ // The notch app: the machine opts in by naming its binary — init then owns the
57
+ // LaunchAgent (src/notch.mjs). D1 packaging will default this to a bundled binary.
58
+ notchApp: { default: null, env: 'OATHE_NOTCH_APP', check: nullOrString },
59
+ // What "in motion" means on the glass: a claim whose last word (statement, or the claim
60
+ // itself) is younger than this earns a row; idle-held work stays in `oathe ls`.
61
+ notchMotionMinutes: { default: 60, env: 'OATHE_NOTCH_MOTION_MINUTES', check: positiveInt },
62
+ // The notch feed's drift guard: `oathe notch --serve` recomputes a frame this often even
63
+ // when no wire event arrives (the push path is pg_notify; this is the belt to its braces).
64
+ notchHeartbeatSeconds: { default: 300, env: 'OATHE_NOTCH_HEARTBEAT_SECONDS', check: positiveInt },
45
65
  });
46
66
 
47
67
  function nonEmptyString(v) {
@@ -53,15 +73,31 @@ function nullOrString(v) {
53
73
  function positiveInt(v) {
54
74
  return Number.isInteger(v) && v > 0;
55
75
  }
76
+ function boolean(v) {
77
+ return v === true || v === false;
78
+ }
79
+ boolean.expected = 'true|false';
80
+
81
+ /** Env strings for boolean keys: 'true'/'1' and 'false'/'0'; anything else stays a string and refuses. */
82
+ function coerceEnv(spec, raw) {
83
+ if (typeof spec.default === 'number') return Number(raw);
84
+ if (typeof spec.default === 'boolean') {
85
+ if (raw === 'true' || raw === '1') return true;
86
+ if (raw === 'false' || raw === '0') return false;
87
+ return raw;
88
+ }
89
+ return raw;
90
+ }
56
91
  function oneOf(allowed) {
57
92
  const check = (v) => allowed.includes(v);
58
93
  check.expected = allowed.join('|');
59
94
  return check;
60
95
  }
61
- function httpsUrl(v) {
62
- return typeof v === 'string' && v.startsWith('https://');
96
+ function nullOrOneOf(allowed) {
97
+ const check = (v) => v === null || allowed.includes(v);
98
+ check.expected = `null|${allowed.join('|')}`;
99
+ return check;
63
100
  }
64
-
65
101
  /** Walk up from `dir` to the workspace root (the dir holding .git), else `dir` itself. */
66
102
  function workspaceRoot(dir) {
67
103
  let current = dir;
@@ -74,25 +110,32 @@ function workspaceRoot(dir) {
74
110
  }
75
111
 
76
112
  export const CONFIG_KEYS = Object.freeze(Object.keys(KEYS));
77
- export const VERIFIER_ENGINES = Object.freeze([...ENGINES]);
78
113
 
79
114
  export class OatheConfig {
80
- /** @param {{env?: NodeJS.ProcessEnv, cwd?: string}} o */
115
+ /** @param {{env?: NodeJS.ProcessEnv, cwd?: string|null}} o cwd:null = global-only (no workspace layer) */
81
116
  constructor({ env = process.env, cwd = process.cwd() } = {}) {
117
+ // A cwd that does not exist would walk to / and pick a silently-wrong config root — the
118
+ // exact shape of an unexpanded ${...} template reaching us. Refuse at construction.
119
+ if (cwd !== null && !fs.existsSync(cwd)) {
120
+ throw new ConfigError('OATHE_CONFIG_CWD_INVALID',
121
+ `config cwd '${cwd}' is not an existing directory — refusing to guess a workspace root`, { cwd });
122
+ }
82
123
  this.env = env;
83
- this.globalPath = path.join(env.OATHE_HOME || path.join(env.HOME || os.homedir(), '.oathe'), 'config.json');
84
- this.workspacePath = path.join(workspaceRoot(cwd), '.oathe.json');
124
+ const files = OatheConfig.filesFor({ env, cwd });
125
+ this.globalPath = files[0];
126
+ this.workspacePath = files[1] ?? null;
85
127
  this.values = { ...Object.fromEntries(Object.entries(KEYS).map(([k, spec]) => [k, spec.default])) };
86
128
  this.sources = Object.fromEntries(Object.keys(KEYS).map((k) => [k, 'default']));
87
- for (const [file, layer] of [[this.globalPath, 'global'], [this.workspacePath, 'workspace']]) {
129
+ const layers = [[this.globalPath, 'global']];
130
+ if (this.workspacePath !== null) layers.push([this.workspacePath, 'workspace']);
131
+ for (const [file, layer] of layers) {
88
132
  const loaded = this.#loadFile(file);
89
133
  Object.assign(this.values, loaded);
90
134
  for (const key of Object.keys(loaded)) this.sources[key] = layer;
91
135
  }
92
136
  for (const [key, spec] of Object.entries(KEYS)) {
93
137
  if (spec.env && env[spec.env] !== undefined) {
94
- const raw = env[spec.env];
95
- const value = typeof spec.default === 'number' ? Number(raw) : raw;
138
+ const value = coerceEnv(spec, env[spec.env]);
96
139
  this.#checkValue(key, value, `env ${spec.env}`);
97
140
  this.values[key] = value;
98
141
  this.sources[key] = 'env';
@@ -100,6 +143,44 @@ export class OatheConfig {
100
143
  }
101
144
  }
102
145
 
146
+ /** Defaults → global file → env, with NO workspace layer — the pre-resolution bootstrap. */
147
+ static global({ env = process.env } = {}) {
148
+ return new OatheConfig({ env, cwd: null });
149
+ }
150
+
151
+ /**
152
+ * Coerce a CLI word into `key`'s own value shape — booleans take true/false, numbers
153
+ * take digits, nullable keys take the word null. The one coercion (shared with the env
154
+ * layer's rules); set() still validates, so a wrong word stays a typed refusal. The
155
+ * digits-only rule this replaces made the documented `oathe config autoActivate false`
156
+ * refuse — a config surface that cannot speak its own keys' types.
157
+ */
158
+ static coerce(key, raw) {
159
+ const spec = KEYS[key];
160
+ if (!spec) {
161
+ throw new ConfigError('OATHE_CONFIG_KEY_UNKNOWN',
162
+ `unknown config key '${key}' — known keys: ${CONFIG_KEYS.join(', ')}`, { key });
163
+ }
164
+ if (raw === 'null' && spec.check(null)) return null;
165
+ if (typeof spec.default === 'boolean' || spec.check === boolean) {
166
+ if (raw === 'true' || raw === '1') return true;
167
+ if (raw === 'false' || raw === '0') return false;
168
+ return raw;
169
+ }
170
+ return /^\d+$/.test(raw) ? Number(raw) : raw;
171
+ }
172
+
173
+ /**
174
+ * The config LAYER FILES for an (env, cwd) — the one path logic, shared by the
175
+ * constructor and by staleness watchers (the MCP connection stamps these files' clocks
176
+ * so a long-lived server follows `oathe config`, never its startup snapshot).
177
+ * @returns {string[]} [globalPath] or [globalPath, workspacePath]
178
+ */
179
+ static filesFor({ env = process.env, cwd = null } = {}) {
180
+ const globalPath = path.join(env.OATHE_HOME || path.join(env.HOME || os.homedir(), '.oathe'), 'config.json');
181
+ return cwd === null ? [globalPath] : [globalPath, path.join(workspaceRoot(cwd), '.oathe.json')];
182
+ }
183
+
103
184
  /** Where a key's value came from: 'default' | 'global' | 'workspace' | 'env'. */
104
185
  source(key) {
105
186
  if (!(key in KEYS)) {
@@ -158,6 +239,10 @@ export class OatheConfig {
158
239
  throw new ConfigError('OATHE_CONFIG_SCOPE_UNKNOWN',
159
240
  `unknown scope '${scope}' — use 'global' or 'workspace'`, { scope });
160
241
  })();
242
+ if (file === null) {
243
+ throw new ConfigError('OATHE_CONFIG_SCOPE_UNKNOWN',
244
+ 'this config was built global-only (no workspace) — workspace scope has no file here', { scope });
245
+ }
161
246
  const doc = this.#loadFile(file);
162
247
  doc[key] = value;
163
248
  fs.mkdirSync(path.dirname(file), { recursive: true });
package/src/context.mjs CHANGED
@@ -3,13 +3,12 @@
3
3
  // a scratch database without monkey-patching anything.
4
4
 
5
5
  import fs from 'node:fs';
6
- import os from 'node:os';
7
6
  import path from 'node:path';
8
7
 
9
- import { buildPaths } from './paths.mjs';
8
+ import { buildPaths, homeOf } from './paths.mjs';
10
9
  import { OatheConfig } from './config.mjs';
11
10
  import { InstallManifest } from './manifest.mjs';
12
- import { ClaudeHarness, CodexHarness } from './harness.mjs';
11
+ import { buildAll } from './harnesses/catalog.mjs';
13
12
  import { Substrate } from './substrate.mjs';
14
13
 
15
14
  export function packageVersion(paths) {
@@ -18,13 +17,10 @@ export function packageVersion(paths) {
18
17
 
19
18
  export function buildContext({ env = process.env, exec, cwd = process.cwd() } = {}) {
20
19
  const paths = buildPaths(env);
21
- const home = env.HOME || os.homedir();
20
+ const home = homeOf(env);
22
21
  const config = new OatheConfig({ env, cwd });
23
22
  const manifest = InstallManifest.load({ manifestPath: paths.manifestPath, backupsDir: paths.backupsDir });
24
- const harnesses = [
25
- new ClaudeHarness({ home, envPath: env.PATH, paths, exec }),
26
- new CodexHarness({ home, envPath: env.PATH, paths, exec }),
27
- ];
23
+ const harnesses = buildAll({ home, envPath: env.PATH, paths, exec }); // the ONE roster; consumers filter by capability
28
24
  const substrate = new Substrate({ database: config.get('db'), paths, env, config });
29
25
  const identity = {
30
26
  orgId: config.get('org'),
package/src/doctor.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
 
8
- import { buildContext } from './context.mjs';
8
+ import { buildContext, packageVersion } from './context.mjs';
9
9
  import { FencedBlock, FENCE_STYLES, JsonEntries } from './blocks.mjs';
10
10
  import { sha256Hex } from './manifest.mjs';
11
11
 
@@ -35,13 +35,95 @@ function verifyCliRow(row) {
35
35
  return fs.readFileSync(row.file, 'utf8').includes(row.detail?.proof) ? 'ok' : 'removed';
36
36
  }
37
37
 
38
- const VERIFIERS = { 'json-path': verifyJsonRow, fence: verifyFenceRow, 'cli-managed': verifyCliRow };
38
+ function verifyJsonArrayRow(row) {
39
+ if (!fs.existsSync(row.file)) return 'file-missing';
40
+ let doc;
41
+ try { doc = JSON.parse(fs.readFileSync(row.file, 'utf8')); } catch { return 'user-edited'; }
42
+ const present = (entry) => {
43
+ let node = doc;
44
+ for (const key of entry.path) {
45
+ if (node === null || typeof node !== 'object' || !(key in node)) return false;
46
+ node = node[key];
47
+ }
48
+ return Array.isArray(node) && node.some((el) => el?.command === entry.match);
49
+ };
50
+ return (row.detail?.entries ?? []).every(present) ? 'ok' : 'removed';
51
+ }
52
+
53
+ /** The trace-layer refusals that mean "this runtime cannot read the store" — not a format change. */
54
+ const RUNTIME_BOUND_CODES = new Set(['TRACE_CODEX_SQLITE_UNSUPPORTED']);
55
+
56
+ /**
57
+ * The trace-contract status for a failed projection: a runtime bound (node:sqlite missing on
58
+ * Node < 22.5 — the store never got to read the record) is RUNTIME; anything else is format
59
+ * DRIFT. Both stay loud; the drift lanes need them told apart.
60
+ */
61
+ export function traceStatusOf(error) {
62
+ return RUNTIME_BOUND_CODES.has(error?.code) ? 'RUNTIME' : 'DRIFT';
63
+ }
64
+
65
+ // A LaunchAgent is a whole-file write: present and byte-identical to what init recorded, or
66
+ // user-edited; gone is gone. (The notch ships with the package — every darwin manifest
67
+ // carries this row now.)
68
+ function verifyLaunchAgentRow(row) {
69
+ if (!fs.existsSync(row.file)) return 'file-missing';
70
+ return sha256Hex(fs.readFileSync(row.file, 'utf8')) === row.sha256 ? 'ok' : 'user-edited';
71
+ }
72
+
73
+ // The materialized notch copy: the row's detail names the binary inside the key dir; ok
74
+ // means those exact bytes. A replaced binary under the same key is a drift the same way an
75
+ // edited plist is — materialization promises immutability per key.
76
+ function verifyNotchAppRow(row) {
77
+ const binary = row.detail?.binary;
78
+ if (!binary || !fs.existsSync(binary)) return 'file-missing';
79
+ return sha256Hex(fs.readFileSync(binary)) === row.sha256 ? 'ok' : 'user-edited';
80
+ }
81
+
82
+ const VERIFIERS = {
83
+ 'json-path': verifyJsonRow, fence: verifyFenceRow, 'cli-managed': verifyCliRow, 'json-array': verifyJsonArrayRow,
84
+ 'launch-agent': verifyLaunchAgentRow, 'notch-app': verifyNotchAppRow,
85
+ };
86
+
87
+ /**
88
+ * The per-surface resolution report (`oathe doctor --surface`): what the ladder received,
89
+ * which rung won, and whether the workspace is registered — no substrate contact, so it
90
+ * answers even on a machine whose database is down. This is the empirical probe the unknown
91
+ * surfaces (Cowork, ChatGPT desktop) get pointed at.
92
+ * @returns {Promise<{resolved: boolean, resolution: object|null, refusal: string|null,
93
+ * registered: boolean|null, env_slice: object}>}
94
+ */
95
+ export async function runSurfaceReport({ env = process.env, cwd = () => process.cwd() } = {}) {
96
+ const { WorkspaceResolver } = await import('./workspace-resolver.mjs');
97
+ const { projectDirEnvVars } = await import('./harnesses/catalog.mjs');
98
+ const { WorkspaceRegistry } = await import('./registry.mjs');
99
+ const { buildPaths } = await import('./paths.mjs');
100
+ const paths = buildPaths(env);
101
+ const envSlice = Object.fromEntries(
102
+ ['OATHE_WORKSPACE_DIR', ...projectDirEnvVars().map(([, envVar]) => envVar), 'OATHE_LAUNCHED_HARNESS']
103
+ .map((name) => [name, env[name] ?? null]));
104
+ try {
105
+ const resolution = await new WorkspaceResolver({ env, cwd }).resolve();
106
+ let registered = null;
107
+ try {
108
+ registered = new WorkspaceRegistry({ registryPath: paths.registryPath }).get(resolution.ref) !== null;
109
+ } catch { registered = null; }
110
+ return { resolved: true, resolution, refusal: null, registered, env_slice: envSlice };
111
+ } catch (e) {
112
+ return { resolved: false, resolution: null, refusal: String(e?.message || e), registered: null, env_slice: envSlice };
113
+ }
114
+ }
39
115
 
40
116
  /** @returns {Promise<{rows: object[], substrate: object, plugin: {resolves: boolean, detail: string|null}}>} */
41
117
  export async function runDoctor({ env = process.env } = {}) {
42
118
  const ctx = buildContext({ env });
43
- const { manifest, substrate, paths } = ctx;
119
+ const { manifest, substrate, paths, harnesses } = ctx;
44
120
  try {
121
+ // Version FACTS, not a check: the code that runs is the bin on PATH (this package); what
122
+ // each harness has cached is its own manifests-only copy. Upgrade = reinstall + `oathe init`.
123
+ const version = {
124
+ package: packageVersion(paths),
125
+ plugin: Object.fromEntries(harnesses.filter((h) => h.constructor.wiring !== null).map((h) => [h.name, h.installedPluginVersion()])),
126
+ };
45
127
  const rows = manifest.rows.map((row) => ({
46
128
  harness: row.harness,
47
129
  file: row.file,
@@ -50,29 +132,28 @@ export async function runDoctor({ env = process.env } = {}) {
50
132
  status: (VERIFIERS[row.kind] ?? (() => 'unknown-kind'))(row),
51
133
  }));
52
134
  // The trace-contract monitor: both vendors disclaim transcript-schema stability, so the
53
- // doctor validates the NEWEST live record in each store against docs/traces.md and
135
+ // doctor validates the NEWEST live record in each engine's store against docs/traces.md and
54
136
  // reports DRIFT loudly. An absent store is a distinct, visible status — never a silent skip.
55
- const { ClaudeTraceStore, CodexTraceStore } = await import('./traces.mjs');
56
- const { ClaudeAtifProjector, CodexAtifProjector, AtifValidator } = await import('./atif.mjs');
137
+ // Store, newest-record lookup, and projector are each engine adapter's own facts.
138
+ const { byName, traceStores } = await import('./harnesses/catalog.mjs');
139
+ const { AtifValidator } = await import('./atif.mjs');
57
140
  const home = ctx.home;
58
141
  const traces = {};
59
- for (const [name, store] of Object.entries({
60
- claude: new ClaudeTraceStore({ home }),
61
- codex: new CodexTraceStore({ home }),
62
- })) {
63
- const newest = name === 'claude' ? store.newestTranscript() : store.newestRollout();
142
+ for (const name of traceStores()) {
143
+ const { traces: capability } = byName(name);
144
+ const store = await capability.store({ home });
145
+ const newest = capability.newest(store);
64
146
  if (!newest) {
65
147
  traces[name] = { status: 'store-absent', newest: null, detail: 'no session records found' };
66
148
  continue;
67
149
  }
68
150
  // Full projection + validation — the deepest read the verifier itself performs.
69
151
  try {
70
- const projector = name === 'claude'
71
- ? new ClaudeAtifProjector({ store }) : new CodexAtifProjector({ store });
152
+ const projector = await capability.projector({ store });
72
153
  new AtifValidator().assert(projector.project(newest), { file: newest });
73
154
  traces[name] = { status: 'ok', newest, detail: null };
74
155
  } catch (e) {
75
- traces[name] = { status: 'DRIFT', newest, detail: String(e?.message || e) };
156
+ traces[name] = { status: traceStatusOf(e), newest, detail: String(e?.message || e) };
76
157
  }
77
158
  }
78
159
 
@@ -101,7 +182,7 @@ export async function runDoctor({ env = process.env } = {}) {
101
182
  capabilities: null, error: String(e?.message || e), probe: null };
102
183
  }
103
184
 
104
- return { rows, substrate: await substrate.status(), plugin, traces, runtime };
185
+ return { version, rows, substrate: await substrate.status(), plugin, traces, runtime };
105
186
  } finally {
106
187
  await substrate.close();
107
188
  }
package/src/fence.mjs ADDED
@@ -0,0 +1,85 @@
1
+ // oathe — the managed fence, owned once: the two bodies (a folder's, and the GLOBAL one an
2
+ // adapter's instructions file carries for sessions that open with no folder at all) and THE
3
+ // write that puts a block into a file — backup once, apply, manifest row. activateWorkspace
4
+ // (folder fences) and Harness.installGlobalFence (`oathe init`) both write through here, so
5
+ // the bytes on disk and the manifest rows that make them reversible can never drift apart.
6
+
7
+ import fs from 'node:fs';
8
+
9
+ import { FencedBlock, FENCE_STYLES } from './blocks.mjs';
10
+ import { sha256Hex } from './manifest.mjs';
11
+
12
+ /** The rule, in one sentence, everywhere it is spoken (fences, the board render). */
13
+ export const SPEECH_ACT_RULE = 'Claims are speech acts: claim before you build, record progress as statements, '
14
+ + 'yield what you cannot finish — via the `oathe_*` MCP tools.';
15
+
16
+ /** The folder fence: an H2 inside HTML-comment fences (the `>>> <<<` shell-profile convention,
17
+ * in a form Markdown renders as nothing). Surface-neutral by design: hooks may not fire on every harness, so the fence promises
18
+ * only what every surface delivers. (Byte-stable: every activated folder carries it.) */
19
+ export function fenceBody(workspace) {
20
+ return [
21
+ '## Oathe',
22
+ '',
23
+ `This folder has an Oathe board (workspace \`${workspace}\`). Claims are speech acts:`,
24
+ 'claim before you build, record progress as statements, yield what you cannot finish —',
25
+ 'via the `oathe_*` MCP tools. Where your session opens on this folder, the board loads',
26
+ 'with it; `continue <task>` picks work back up.',
27
+ ].join('\n');
28
+ }
29
+
30
+ /**
31
+ * The GLOBAL fence (R-BOARD-SCOPE follow-up): an adapter's global instructions file is read
32
+ * by every one of its sessions — including those that open on a staging directory with no
33
+ * project folder (ChatGPT desktop), where no folder fence can exist. It must be true in a
34
+ * folder session too, so it describes both cases and names no workspace.
35
+ */
36
+ export function globalFenceBody() {
37
+ return [
38
+ '## Oathe',
39
+ '',
40
+ wrap(`Every session on this machine has an Oathe board. ${SPEECH_ACT_RULE} Where a session opens `
41
+ + 'on a project folder, that folder\'s board loads with it. A session with no project folder '
42
+ + '(ChatGPT desktop runs from a staging directory) sees the machine-wide board, and a task '
43
+ + 'claimed there is homeless until a real folder claims it — which adopts it onto that '
44
+ + 'folder\'s board. `continue <task>` picks work back up.'),
45
+ ].join('\n');
46
+ }
47
+
48
+ /** Word-wrap one paragraph to `width` columns — the fence files are read by people too. */
49
+ function wrap(paragraph, width = 90) {
50
+ const lines = [];
51
+ let line = '';
52
+ for (const word of paragraph.split(' ')) {
53
+ if (line !== '' && `${line} ${word}`.length > width) { lines.push(line); line = word; }
54
+ else line = line === '' ? word : `${line} ${word}`;
55
+ }
56
+ if (line !== '') lines.push(line);
57
+ return lines.join('\n');
58
+ }
59
+
60
+ /**
61
+ * THE fence write: put the managed block into `file` and record it. Idempotent — an unchanged
62
+ * block writes nothing; the manifest row is keyed so a re-run replaces its own.
63
+ * @param {{manifest: object, file: string, version: string, body: string, scope: 'project'|'user',
64
+ * harness?: string}} o harness — the row's owner label ('project' for folder fences,
65
+ * 'global' for an adapter's instructions file; never an adapter name, so an adapter's
66
+ * offboard cannot drop the row without stripping the block)
67
+ * @returns {{file: string, changed: boolean}}
68
+ */
69
+ export function writeFence({ manifest, file, version, body, scope, harness = 'project' }) {
70
+ const block = new FencedBlock({ style: FENCE_STYLES.html });
71
+ manifest.backupOnce(file);
72
+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
73
+ const { content, changed } = block.apply(before, { version, body });
74
+ if (changed) fs.writeFileSync(file, content);
75
+ manifest.upsert({
76
+ harness,
77
+ file,
78
+ kind: 'fence',
79
+ scope,
80
+ detail: { style: 'html' },
81
+ blockVersion: version,
82
+ sha256: sha256Hex(block.read(content).blockText),
83
+ });
84
+ return { file, changed };
85
+ }
package/src/fslock.mjs ADDED
@@ -0,0 +1,51 @@
1
+ // oathe — shared-file concurrency: atomic JSON writes plus a bounded advisory lock. Many
2
+ // sessions' hooks and MCP servers write ~/.oathe files at once; a reader must never see a torn
3
+ // file, and a hook must never deadlock a session on somebody else's lock. Rename is the only
4
+ // publish; the lock is a lockdir spin (mkdir is atomic on POSIX) that gives up after the bound
5
+ // and proceeds — every caller's mutation is idempotent by contract, so a lost race self-heals.
6
+
7
+ import crypto from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ /** Write `doc` as pretty JSON + trailing newline via temp-then-rename in the same directory. */
12
+ export function atomicWriteJson(file, doc) {
13
+ fs.mkdirSync(path.dirname(file), { recursive: true });
14
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`);
15
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`);
16
+ fs.renameSync(tmp, file);
17
+ }
18
+
19
+ /**
20
+ * Run `fn` under an advisory lockdir beside `file`. A lockdir older than `staleMs` is broken
21
+ * (its holder died); a live foreign lock is waited on for at most `timeoutMs`, then `fn` runs
22
+ * lock-free rather than blocking the caller.
23
+ */
24
+ export async function withFileLock(file, fn, { timeoutMs = 2000, staleMs = 10_000 } = {}) {
25
+ const lockDir = `${file}.lock`;
26
+ fs.mkdirSync(path.dirname(lockDir), { recursive: true });
27
+ const deadline = Date.now() + timeoutMs;
28
+ let acquired = false;
29
+ for (;;) {
30
+ try {
31
+ fs.mkdirSync(lockDir);
32
+ acquired = true;
33
+ break;
34
+ } catch (e) {
35
+ if (e.code !== 'EEXIST') throw e;
36
+ try {
37
+ if (Date.now() - fs.statSync(lockDir).mtimeMs > staleMs) {
38
+ fs.rmdirSync(lockDir);
39
+ continue;
40
+ }
41
+ } catch { /* the holder released between stat and rmdir — retry */ }
42
+ if (Date.now() >= deadline) break;
43
+ await new Promise((resolve) => { setTimeout(resolve, 25); });
44
+ }
45
+ }
46
+ try {
47
+ return await fn();
48
+ } finally {
49
+ if (acquired) fs.rmSync(lockDir, { recursive: true, force: true });
50
+ }
51
+ }