@oathe/oathe 0.2.3 → 0.3.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 (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 +397 -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 +154 -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,169 @@
1
+ // oathe — the verification dispatcher. `oathe_verify` over MCP never runs the engine in the
2
+ // server: it launches the existing `oathe verify` bin verb as a DETACHED process (its own
3
+ // group, unref'd — it survives the session; a deliberate, documented exception to the cage's
4
+ // containment) and answers immediately with the durable addresses. Concurrency stays the
5
+ // substrate's: the child claims `verify:<task>` before its engine runs, so a concurrent loser
6
+ // exits on FC003 pre-engine. The only pre-spawn read exists so a live in-flight review is a
7
+ // TYPED refusal naming the holder — never a lying {started: true}. No auto-heal: an expired
8
+ // lease names the manual fix (`oathe yield`) and stops.
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { spawn as nodeSpawn } from 'node:child_process';
13
+
14
+ import { isVerificationTask, verificationTaskId } from './plans.mjs';
15
+ import { isEngineFailureSql } from './statements.mjs';
16
+ import { pidAlive } from './sessions.mjs';
17
+
18
+ export class VerifyDispatchError extends Error {
19
+ constructor(code, message, details = {}) {
20
+ super(message);
21
+ this.name = 'VerifyDispatchError';
22
+ this.code = code;
23
+ this.details = details;
24
+ }
25
+ }
26
+
27
+ /** The env the child gets: the caller's, minus the judged session's provenance stamps —
28
+ * otherwise the verifier's own statements carry the attempt id of the very execution under
29
+ * judgment. */
30
+ function scrubbedEnv(env) {
31
+ const child = { ...env };
32
+ delete child.OATHE_EXECUTION_ATTEMPT_ID;
33
+ delete child.OATHE_LAUNCHED_HARNESS;
34
+ return child;
35
+ }
36
+
37
+ /**
38
+ * @param {{taskId: string, engine?: string, orgId: string,
39
+ * query: (sql: string, params: unknown[]) => Promise<{rows: object[]}>,
40
+ * paths: {packageRoot: string, logsDir: string}, cwd: string, env: object,
41
+ * spawn?: typeof nodeSpawn, clock?: () => Date}} o
42
+ * @returns {Promise<{started: true, task_id: string, verification_task: string, engine: string|null,
43
+ * pid: number, log: string, note: string}>}
44
+ */
45
+ export async function dispatchVerification({
46
+ taskId, engine = null, orgId, query, paths, cwd, env, spawn = nodeSpawn, clock = () => new Date(),
47
+ }) {
48
+ const verificationTask = isVerificationTask(taskId) ? taskId : verificationTaskId(taskId);
49
+ const originalTask = verificationTask.slice('verify:'.length);
50
+
51
+ const { rows } = await query(
52
+ `SELECT principal_id, state, ownership_valid_until
53
+ FROM cell.work_claim WHERE org_id = $1 AND task_id = $2
54
+ ORDER BY claimed_at DESC LIMIT 1`, [orgId, verificationTask]);
55
+ const latest = rows[0];
56
+ if (latest?.state === 'active') {
57
+ const until = latest.ownership_valid_until ? new Date(latest.ownership_valid_until) : null;
58
+ const expired = until !== null && until < clock();
59
+ throw new VerifyDispatchError('OATHE_VERIFY_IN_FLIGHT',
60
+ expired
61
+ ? `a verification of '${originalTask}' is still claimed by ${latest.principal_id} but its `
62
+ + `lease expired ${until.toISOString()} — likely a dead run; \`oathe yield ${verificationTask}\` `
63
+ + 'releases it, then dispatch again'
64
+ : `a verification of '${originalTask}' is already running — claimed by ${latest.principal_id}`
65
+ + `${until ? ` until ${until.toISOString()}` : ''}; its verdict lands on the board`,
66
+ { verification_task: verificationTask, holder: latest.principal_id, expired });
67
+ }
68
+
69
+ fs.mkdirSync(paths.logsDir, { recursive: true });
70
+ const log = path.join(paths.logsDir, `verify-${originalTask.replace(/[^A-Za-z0-9._-]+/g, '-')}.log`);
71
+ const logFd = fs.openSync(log, 'w'); // one log per task, overwritten per run — no retention machinery
72
+ let child;
73
+ try {
74
+ child = spawn(process.execPath,
75
+ [path.join(paths.packageRoot, 'bin/oathe.mjs'), 'verify', originalTask, ...(engine ? ['--engine', engine] : [])],
76
+ { detached: true, cwd, env: scrubbedEnv(env), stdio: ['ignore', logFd, logFd] });
77
+ } finally {
78
+ fs.closeSync(logFd); // the child holds its own copy; the long-lived server must not leak one per dispatch
79
+ }
80
+ child.unref();
81
+
82
+ return {
83
+ started: true,
84
+ task_id: originalTask,
85
+ verification_task: verificationTask,
86
+ engine,
87
+ pid: child.pid,
88
+ log,
89
+ note: `verification of '${originalTask}' started in the background as ${verificationTask} — `
90
+ + 'when it leaves the board the claim settled; a rejection reopens the task with the reason '
91
+ + `recorded on ${verificationTask}'s completion statement. Engine log: ${log}`,
92
+ };
93
+ }
94
+
95
+ /**
96
+ * AWAIT a dispatched judgment's outcome from the substrate — the blocking half of the
97
+ * local rule. The engine still runs in its own detached process; this only reads. The
98
+ * wait is bounded by the CHILD'S OWN LIFE, never an arbitrary budget: verdict recorded →
99
+ * the answer; failure statement recorded → the failure; child dead with neither (one
100
+ * last read closes the exit race) → a typed failed outcome naming the retry.
101
+ * @returns {Promise<{verdict: 'accepted'|'rejected', reason: string}
102
+ * |{failed: true, reason: string}>}
103
+ */
104
+ export async function awaitVerdict({
105
+ taskId, pid, orgId, query, since,
106
+ pollMs = 1000, isAlive = pidAlive, sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
107
+ }) {
108
+ const verificationTask = isVerificationTask(taskId) ? taskId : verificationTaskId(taskId);
109
+ const originalTask = verificationTask.slice('verify:'.length);
110
+ let lastChance = false;
111
+ for (;;) {
112
+ const { rows } = await query(
113
+ `SELECT v.result, s.proposition
114
+ FROM cell.verification v
115
+ LEFT JOIN LATERAL (
116
+ SELECT st.proposition FROM cell.agent_statement st
117
+ WHERE st.org_id = v.org_id AND st.task_id = $3 AND st.statement_type = 'completion'
118
+ ORDER BY st.asserted_at DESC LIMIT 1) s ON true
119
+ WHERE v.org_id = $1 AND v.task_id = $2 AND v.recorded_at > $4
120
+ ORDER BY v.recorded_at DESC LIMIT 1`,
121
+ [orgId, originalTask, verificationTask, since]);
122
+ if (rows[0]) {
123
+ return {
124
+ verdict: rows[0].result === 'rejected' ? 'rejected' : 'accepted',
125
+ // The verdict statement reads "accepted: <reason>" / "rejected: <reason>" — hand back the reason.
126
+ reason: String(rows[0].proposition ?? '').replace(/^(accepted|rejected):\s*/, '') || rows[0].result,
127
+ };
128
+ }
129
+ // The failure is only REPORTABLE once the dead run has RELEASED its claim — returning
130
+ // on the statement alone raced the child's yield and handed the caller a twin still
131
+ // holding the lock (a retry dispatched in that beat read IN_FLIGHT — caught live).
132
+ const { rows: twin } = await query(
133
+ `SELECT state FROM cell.work_claim WHERE org_id = $1 AND task_id = $2
134
+ ORDER BY claimed_at DESC LIMIT 1`, [orgId, verificationTask]);
135
+ if (twin[0] && twin[0].state !== 'active') {
136
+ const { rows: fail } = await query(
137
+ `SELECT proposition FROM cell.agent_statement
138
+ WHERE org_id = $1 AND task_id = $2 AND asserted_at > $3
139
+ AND ${isEngineFailureSql('evidence_refs')}
140
+ ORDER BY asserted_at DESC LIMIT 1`,
141
+ [orgId, verificationTask, since]);
142
+ if (fail[0]) return { failed: true, reason: fail[0].proposition };
143
+ }
144
+ if (lastChance) {
145
+ return {
146
+ failed: true,
147
+ reason: `the verifier (pid ${pid}) died without recording a verdict — retry: oathe verify ${originalTask}`,
148
+ };
149
+ }
150
+ if (!isAlive(pid)) { lastChance = true; continue; } // one final read closes the wrote-then-exited race
151
+ await sleep(pollMs);
152
+ }
153
+ }
154
+
155
+ /**
156
+ * THE verifier seam — how a serving tool surface runs a verification, and WHERE topology
157
+ * decides the blocking rule (founder ruling 2026-08-31: the trust boundary is the blocking
158
+ * boundary). A LOCAL substrate owes the answer in-call — dispatch the detached child, then
159
+ * await its verdict; when the substrate is REMOTE (the cloud), this seam is the one place
160
+ * that flips to dispatch-and-return. Never an engine inside the server either way.
161
+ */
162
+ export function verifierSeam({ orgId, query, paths, cwd, env = process.env }) {
163
+ return async ({ taskId, engine = null }) => {
164
+ const since = new Date().toISOString();
165
+ const out = await dispatchVerification({ taskId, engine, orgId, query, paths, cwd, env });
166
+ const outcome = await awaitVerdict({ taskId, pid: out.pid, orgId, query, since });
167
+ return { ...outcome, log: out.log };
168
+ };
169
+ }
@@ -0,0 +1,32 @@
1
+ // oathe — the one-time welcome. Init plants the marker when it CREATES the database;
2
+ // the serve feed consumes it after a successful frame build and rides the lines on that
3
+ // frame. Consume-on-emit is a ruling: the glass has no ack channel (its stdin to the feed
4
+ // is write-never), so a play lost to a dying app is accepted one-shot loss — the
5
+ // alternative, replay-on-every-KeepAlive-restart, would lie louder. `oathe notch
6
+ // --welcome` is the free replay. Presence is the fact: consume never parses the marker,
7
+ // so a corrupt file has no failure mode.
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ /** The founder copy, verbatim (2026-08-31) — product code, not a tunable. */
13
+ export const WELCOME_LINES = Object.freeze([
14
+ 'welcome to oathe',
15
+ "I'll list your session statuses here.",
16
+ 'you can click to expand in the future.',
17
+ "let's build something great today",
18
+ ]);
19
+
20
+ /** Plant the pending marker. Idempotent — planting over a pending marker is still one welcome. */
21
+ export function plantWelcome({ paths, by = 'init' }) {
22
+ fs.mkdirSync(path.dirname(paths.welcomePath), { recursive: true });
23
+ fs.writeFileSync(paths.welcomePath, `${JSON.stringify({ planted_at: new Date().toISOString(), by })}\n`);
24
+ return { file: paths.welcomePath };
25
+ }
26
+
27
+ /** Take the one shot: the lines if a marker was pending (clearing it), else null. */
28
+ export function consumeWelcome({ paths }) {
29
+ if (!fs.existsSync(paths.welcomePath)) return null;
30
+ fs.rmSync(paths.welcomePath, { force: true });
31
+ return { lines: [...WELCOME_LINES] };
32
+ }
package/src/wire.mjs ADDED
@@ -0,0 +1,64 @@
1
+ // oathe — the wire: one pg_notify per successful speech act, so an ambient surface (the
2
+ // notch feed, `oathe notch --serve`) hears a write the moment it lands instead of polling.
3
+ // The substrate stays the one source of truth — an event is a NUDGE, never a record: the
4
+ // feed recomputes its frame from durable facts on every wake, and a lost notification costs
5
+ // at most one heartbeat of staleness. Reads never emit (a feed that echoed its own reads
6
+ // would ring forever).
7
+ //
8
+ // Emission is fail-soft BY RULING exception: the speech act must stand even when the wire
9
+ // is down — but the failure is reported visibly on stderr, never swallowed.
10
+
11
+ export const WIRE_CHANNEL = 'oathe_wire';
12
+
13
+ /** WRITE tools only — the kind is the speech act's own name in the past tense. */
14
+ export const WIRE_KINDS = Object.freeze({
15
+ oathe_claim: 'claimed',
16
+ oathe_statement: 'progress',
17
+ oathe_amend: 'amended',
18
+ oathe_yield: 'yielded',
19
+ oathe_done: 'asserted',
20
+ oathe_verify: 'verify_dispatched',
21
+ oathe_pickup: 'restored',
22
+ });
23
+
24
+ /**
25
+ * The acts whose speaker session is EVIDENCE on the claim — linkTrace rides these and
26
+ * only these. oathe_verify is excluded on purpose: dispatching judgment is not working
27
+ * the task, and a bystander's transcript must never enter the evidence under judgment.
28
+ */
29
+ export const LINKABLE = Object.freeze(new Set(
30
+ Object.keys(WIRE_KINDS).filter((name) => name !== 'oathe_verify')));
31
+
32
+ /** ONE wording for the restored-state receipt — the pickup result and the feed both speak it. */
33
+ export function restoredReceipt(taskId) {
34
+ return `🎉 Oathe restored your session state — '${taskId}' picked back up.`;
35
+ }
36
+
37
+ /**
38
+ * The wire kinds that surface as an ephemeral NOTICE on the glass — one wording each, one
39
+ * tone each: sage is a receipt riding the act, amber is a deviation that changes what you
40
+ * do next (the verifier rejecting a completion — founder ruling 2026-08-30). The reopened
41
+ * task also stands in the breach list, so the notice can fade without losing the fact.
42
+ * @returns {{text: string, tone: 'sage'|'amber'}|null}
43
+ */
44
+ export function noticeFor(kind, taskId, via = null) {
45
+ if (kind === 'restored') return { text: restoredReceipt(taskId), tone: 'sage' };
46
+ if (kind === 'rejected') return { text: `✗ '${taskId}' reopened — verification rejected.`, tone: 'amber' };
47
+ if (kind === 'settled') return { text: `✓ '${taskId}' verified — settled.`, tone: 'sage' };
48
+ if (kind === 'verify_failed') return { text: `✗ verification of '${taskId}' failed${via ? ` (${via})` : ''} — retry from the glass.`, tone: 'amber' };
49
+ return null;
50
+ }
51
+
52
+ export async function emit(client, { kind, task_id, via, app }) {
53
+ try {
54
+ await client.query('SELECT pg_notify($1, $2)',
55
+ [WIRE_CHANNEL, JSON.stringify({
56
+ kind, task_id: task_id ?? null, via: via ?? null,
57
+ app: app ?? null, // the act's living app {bundle, pid} — a homeless task still knows where it is spoken from
58
+ at: new Date().toISOString(),
59
+ })]);
60
+ } catch (e) {
61
+ process.stderr.write(`oathe wire: emit failed (${String(e?.message || e).slice(0, 120)}) `
62
+ + '— the write stands; the glass catches up on its heartbeat\n');
63
+ }
64
+ }
@@ -0,0 +1,178 @@
1
+ // oathe — the ONE workspace-resolution ladder. Every surface that must answer "which folder is
2
+ // this session about?" — the MCP server, hooks, CLI verbs, doctor — resolves through here,
3
+ // lazily, never at process startup:
4
+ //
5
+ // 1. OATHE_WORKSPACE_DIR (explicit binding; an unexpanded ${...} template is skipped)
6
+ // 2. harness project-dir env vars (the catalog sweep — CLAUDE_PROJECT_DIR, CURSOR_PROJECT_DIR)
7
+ // 3. MCP roots (the protocol's own answer, when the client offers one)
8
+ // 4. process cwd (refused for / and the home directory — a home-dir board is
9
+ // silently wrong, and fail-loud beats a wrong default)
10
+ // 5. OATHE_WORKSPACE_UNRESOLVED (naming every input received verbatim, and the fix)
11
+ //
12
+ // Every skipped rung leaves a diagnostic; the winner's `source` names the rung that decided.
13
+ // A resolution also carries `synthetic` (R-BOARD-SCOPE): whether the directory is one a
14
+ // harness stages for folderless sessions — derived HERE (describe) and threaded everywhere.
15
+
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ import { isSyntheticWorkspace, projectDirEnvVars } from './harnesses/catalog.mjs';
21
+ import { workspaceRef, workspaceRoot } from './workspace.mjs';
22
+
23
+ export class WorkspaceResolveError extends Error {
24
+ constructor(code, message, details = {}) {
25
+ super(message);
26
+ this.name = 'WorkspaceResolveError';
27
+ this.code = code;
28
+ this.details = details;
29
+ }
30
+ }
31
+
32
+ export class WorkspaceResolver {
33
+ /**
34
+ * @param {{env?: NodeJS.ProcessEnv, cwd?: () => string, rootsProvider?: (() => Promise<Array<{uri: string}>>)|null,
35
+ * timeoutMs?: number, home?: string}} o
36
+ * rootsProvider — pass one ONLY when the connected client declared the roots capability.
37
+ */
38
+ constructor({ env = process.env, cwd = () => process.cwd(), rootsProvider = null, timeoutMs = 2000, home = os.homedir() } = {}) {
39
+ this.env = env;
40
+ this.cwd = cwd;
41
+ this.rootsProvider = rootsProvider;
42
+ this.timeoutMs = timeoutMs;
43
+ this.home = home;
44
+ this.cached = null;
45
+ }
46
+
47
+ /**
48
+ * The facts of ONE directory — root, ref, synthetic — derived here and nowhere else. Every
49
+ * accepted rung goes through it, and so does every surface handed a directory by its
50
+ * harness outright (hooks, activation, the CLI) rather than through the ladder. So does the
51
+ * ONE refusal: `/` and the home directory are never a workspace — a board minted there
52
+ * would be silently wrong, and a fence written there would land in `~`.
53
+ * @returns {{dir: string, root: string, ref: string, synthetic: boolean}}
54
+ * @throws {WorkspaceResolveError} OATHE_WORKSPACE_UNRESOLVED for `/` and the home directory
55
+ */
56
+ static describe({ dir, home = os.homedir() }) {
57
+ const real = realdir(dir);
58
+ if (real === '/' || real === realdir(home)) {
59
+ throw new WorkspaceResolveError('OATHE_WORKSPACE_UNRESOLVED',
60
+ `workspace refused: '${dir}' is ${real === '/' ? 'the filesystem root' : 'your home directory'} — `
61
+ + 'almost certainly not the project, and a board minted there would be silently wrong'
62
+ + ' (fix: run from inside the project, or set OATHE_WORKSPACE_DIR)', { dir });
63
+ }
64
+ return { dir, root: workspaceRoot(dir), ref: workspaceRef(dir), synthetic: isSyntheticWorkspace({ dir, home }) };
65
+ }
66
+
67
+ /** Forget the cached resolution (e.g. on notifications/roots/list_changed). */
68
+ invalidate() {
69
+ this.cached = null;
70
+ }
71
+
72
+ /**
73
+ * @returns {Promise<{dir: string, root: string, ref: string, synthetic: boolean, source: string,
74
+ * diagnostics: string[]}>}
75
+ * @throws {WorkspaceResolveError} OATHE_WORKSPACE_UNRESOLVED when no rung yields a directory
76
+ */
77
+ async resolve() {
78
+ if (!this.cached) this.cached = this.#resolveOnce();
79
+ try {
80
+ return await this.cached;
81
+ } catch (e) {
82
+ this.cached = null; // a refusal is not a cache entry — the next call re-consults
83
+ throw e;
84
+ }
85
+ }
86
+
87
+ async #resolveOnce() {
88
+ const diagnostics = [];
89
+ // A rung's directory is accepted through describe(); its refusal (/, home) becomes this
90
+ // rung's diagnostic and the ladder moves on — the final refusal names them all.
91
+ const accept = (dir, source) => {
92
+ try {
93
+ return { ...WorkspaceResolver.describe({ dir, home: this.home }), source, diagnostics };
94
+ } catch (e) {
95
+ if (e?.code !== 'OATHE_WORKSPACE_UNRESOLVED') throw e;
96
+ diagnostics.push(`${source}: ${e.message}`);
97
+ return null;
98
+ }
99
+ };
100
+
101
+ // Rungs 1–2: the explicit binding, then each harness's declared project-dir variable.
102
+ const envRungs = [['OATHE_WORKSPACE_DIR', this.env.OATHE_WORKSPACE_DIR],
103
+ ...projectDirEnvVars().map(([, envVar]) => [envVar, this.env[envVar]])];
104
+ for (const [name, value] of envRungs) {
105
+ if (value === undefined || value === '') continue;
106
+ if (value.includes('${')) {
107
+ diagnostics.push(`${name} ignored: unexpanded template '${value}' — the harness never substituted it`);
108
+ continue;
109
+ }
110
+ if (realdir(value) === null) {
111
+ diagnostics.push(`${name} ignored: '${value}' is not an existing directory`);
112
+ continue;
113
+ }
114
+ const accepted = accept(value, name);
115
+ if (accepted) return accepted;
116
+ }
117
+
118
+ // Rung 3: the MCP client's own answer.
119
+ if (this.rootsProvider === null) {
120
+ diagnostics.push('roots: the client offers no roots capability');
121
+ } else {
122
+ try {
123
+ const roots = await this.#withTimeout(this.rootsProvider(), this.timeoutMs);
124
+ const fileRoot = (roots ?? []).find((r) => String(r?.uri ?? '').startsWith('file://'));
125
+ if (fileRoot) {
126
+ const dir = fileURLToPath(fileRoot.uri);
127
+ if (realdir(dir) === null) {
128
+ diagnostics.push(`roots: '${dir}' is not an existing directory`);
129
+ } else {
130
+ const accepted = accept(dir, 'roots');
131
+ if (accepted) return accepted;
132
+ }
133
+ } else {
134
+ diagnostics.push('roots: the client returned no file:// root');
135
+ }
136
+ } catch (e) {
137
+ diagnostics.push(`roots: ${String(e?.message || e)}`);
138
+ }
139
+ }
140
+
141
+ // Rung 4: the process cwd — describe() refuses / and the home directory.
142
+ const cwd = this.cwd();
143
+ if (realdir(cwd) === null) {
144
+ diagnostics.push(`cwd: '${cwd}' is not an existing directory`);
145
+ } else {
146
+ const accepted = accept(cwd, 'cwd');
147
+ if (accepted) return accepted;
148
+ }
149
+
150
+ throw new WorkspaceResolveError('OATHE_WORKSPACE_UNRESOLVED',
151
+ 'no workspace directory could be resolved for this session:\n'
152
+ + diagnostics.map((d) => ` - ${d}`).join('\n')
153
+ + '\n fix: set OATHE_WORKSPACE_DIR to the project directory, or start the session from '
154
+ + 'inside the project', { diagnostics });
155
+ }
156
+
157
+ #withTimeout(promise, ms) {
158
+ let timer = null;
159
+ return Promise.race([
160
+ promise,
161
+ new Promise((_, reject) => {
162
+ // The timer stays ref'd on purpose: a roots provider that never answers must not let
163
+ // the event loop drain before the bound fires — the ladder needs its turn.
164
+ timer = setTimeout(() => reject(new Error(`roots/list timed out after ${ms}ms`)), ms);
165
+ }),
166
+ ]).finally(() => clearTimeout(timer));
167
+ }
168
+ }
169
+
170
+ /** The real path of an existing directory, or null. */
171
+ function realdir(dir) {
172
+ try {
173
+ const real = fs.realpathSync(dir);
174
+ return fs.statSync(real).isDirectory() ? real : null;
175
+ } catch {
176
+ return null;
177
+ }
178
+ }
package/src/workspace.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // belongs to (git-root realpath + origin-remote url when present; plain dir realpath otherwise),
3
3
  // carried in the claim's contract_ref convention because adding DDL is out of scope for this
4
4
  // package (the vendored cell DDL owns schema numbering — the additive workspace_ref column is the
5
- // flagged post-episode upstream ask).
5
+ // flagged as an upstream ask).
6
6
 
7
7
  import crypto from 'node:crypto';
8
8
  import fs from 'node:fs';
@@ -36,12 +36,23 @@ function originUrl(root) {
36
36
  return null;
37
37
  }
38
38
 
39
- /** @returns {string} `ws-<12hex>` — stable for every path inside one workspace */
40
- export function workspaceRef(cwd) {
39
+ /** @returns {string} the workspace root realpath: the git root when there is one, else the dir. */
40
+ export function workspaceRoot(cwd) {
41
+ const real = fs.realpathSync(cwd);
42
+ const root = gitRoot(real);
43
+ return root === null ? real : fs.realpathSync(root);
44
+ }
45
+
46
+ /** @returns {string} the identity string the ref hashes — one derivation, both facts. */
47
+ export function workspaceIdentity(cwd) {
41
48
  const real = fs.realpathSync(cwd);
42
49
  const root = gitRoot(real);
43
- const identity = root === null
50
+ return root === null
44
51
  ? `dir:${real}`
45
52
  : `git:${fs.realpathSync(root)}|origin:${originUrl(root) ?? ''}`;
46
- return `ws-${crypto.createHash('sha256').update(identity).digest('hex').slice(0, 12)}`;
53
+ }
54
+
55
+ /** @returns {string} `ws-<12hex>` — stable for every path inside one workspace */
56
+ export function workspaceRef(cwd) {
57
+ return `ws-${crypto.createHash('sha256').update(workspaceIdentity(cwd)).digest('hex').slice(0, 12)}`;
47
58
  }
@@ -12,7 +12,7 @@
12
12
  --
13
13
  -- Two standing rules for everything below:
14
14
  --
15
- -- 1. Enforcement lives HERE, not in a service. The estate's measured lesson
15
+ -- 1. Enforcement lives HERE, not in a service. The source system's measured lesson
16
16
  -- (STF-1 / migrations 0047 / 0073) is that a rule with a CLI gate and no
17
17
  -- substrate trigger gets bypassed by direct publish — 23 historical
18
18
  -- `verified` settles did exactly that. A rule this file does not enforce is
@@ -4,7 +4,7 @@
4
4
  -- Contract: docs/a1-cell-work-spine-contract.md §2.3 as amended, FOUNDER RULING
5
5
  -- R5, PRD §13.4 as amended — "the delegator's authority to create work in the
6
6
  -- target scope is checked in the SAME TRANSACTION as the task/dependency
7
- -- creation, against a grants table with a substrate-level check (the estate's
7
+ -- creation, against a grants table with a substrate-level check (the source system's
8
8
  -- proven pattern — STF-1, 0047, 0073 triggers). No new authorization service is
9
9
  -- introduced." Requires 001_core.sql.
10
10
  --
@@ -77,7 +77,7 @@ CREATE TABLE IF NOT EXISTS cell.dep_edge (
77
77
  -- The signer, the kind, and the stamp — all three NOT NULL exactly when the
78
78
  -- edge is satisfied. "Who released this, on what basis, when" is the
79
79
  -- question the Mac's void events could not answer, which is why they had
80
- -- zero readers estate-wide.
80
+ -- zero readers system-wide.
81
81
  settled_by text,
82
82
  settle_kind text,
83
83
  settled_at timestamptz,
@@ -22,7 +22,7 @@
22
22
  -- `unknown` becomes permanent by construction — which is why `evidence_lost` was
23
23
  -- REJECTED as a terminal: it mints an unobserved fact. The receipt row is the
24
24
  -- durable pre-image, written before the effect, surviving the process that wrote
25
- -- it. The estate's own `slack_post_marker` is the measured precedent: built,
25
+ -- it. The source system's own `slack_post_marker` is the measured precedent: built,
26
26
  -- tested, and zero rows, because nothing made it mandatory.
27
27
  --
28
28
  -- The sequence this table stands under (strategy §2):
@@ -217,7 +217,7 @@ $reader_check$;
217
217
 
218
218
  -- ------------------------------------- §4.2 the declare-time evaluability guard
219
219
  --
220
- -- Fail-closed, per the estate's own guard doctrine (migrations 0073/0081).
220
+ -- Fail-closed, per the source system's own guard doctrine (migrations 0073/0081).
221
221
  -- Declaring a `verified` edge whose dep_key matches no registered checker FAILS
222
222
  -- loudly, unless the declarer acknowledges the debt — which mints the typed
223
223
  -- event naming its owner and due date, rather than passing silently.
@@ -47,7 +47,7 @@
47
47
  -- is the shape `cell.unverified_past_verify_by` already uses.
48
48
  --
49
49
  -- 4. A NULL VERDICT PROJECTS `indeterminate`. MEASURED: 217 NULL-verdict rows in
50
- -- the estate. `verdict` is nullable for exactly that case — the contract's
50
+ -- the source system. `verdict` is nullable for exactly that case — the contract's
51
51
  -- §1.4 clause 3 names it — and the projection is a VIEW so that no reader gets
52
52
  -- to decide for itself what a missing verdict meant. Deciding it locally is
53
53
  -- how a non-decision becomes an approval (L13).
@@ -236,7 +236,7 @@ $consume$;
236
236
  --
237
237
  -- `indeterminate` is the answer for a consumed token with no verdict, and it is
238
238
  -- computed here so that no reader can reach its own conclusion about what a
239
- -- missing verdict meant. 217 rows in the estate are exactly this shape.
239
+ -- missing verdict meant. 217 rows in the source system are exactly this shape.
240
240
  -- ---------------------------------------------------------------------------
241
241
  CREATE OR REPLACE VIEW cell.v_confirm_verdict AS
242
242
  SELECT
@@ -3,10 +3,10 @@
3
3
  "source": {
4
4
  "repo": "oathe-runtime-monorepo (private)",
5
5
  "commit": null,
6
- "commit_note": "pre-D0 drop predates commit stamping; per-file source_sha256 pins the exact exported bytes — the commit lands with the next estate regeneration"
6
+ "commit_note": "pre-D0 drop predates commit stamping; per-file source_sha256 pins the exact exported bytes — the commit lands with the next regeneration from source"
7
7
  },
8
8
  "transform": {
9
- "version": "export-clean-1",
9
+ "version": "export-clean-2",
10
10
  "script": "scripts/vendor-ddl.mjs"
11
11
  },
12
12
  "license": "Apache-2.0",
@@ -15,7 +15,7 @@
15
15
  "position": 1,
16
16
  "name": "001_core.sql",
17
17
  "source_sha256": "9537a30072f1aa0dede348f2393602e4631b1b9132a6d6294df286e05a512180",
18
- "public_sha256": "9537a30072f1aa0dede348f2393602e4631b1b9132a6d6294df286e05a512180"
18
+ "public_sha256": "fa2e00bb84e4c7c5581c3f244e7a009bd0134a2d993c26dc10ea74ee42e13c70"
19
19
  },
20
20
  {
21
21
  "position": 2,
@@ -33,7 +33,7 @@
33
33
  "position": 4,
34
34
  "name": "004_delegation.sql",
35
35
  "source_sha256": "e96dc76ab5fd05d222d7987273181c769f735b0b167da39428305fa3537f16a4",
36
- "public_sha256": "e96dc76ab5fd05d222d7987273181c769f735b0b167da39428305fa3537f16a4"
36
+ "public_sha256": "31e93bde29cd8f88665676729a35a7337cd1111ed85590d2e757f77c6d8d1280"
37
37
  },
38
38
  {
39
39
  "position": 5,
@@ -45,7 +45,7 @@
45
45
  "position": 6,
46
46
  "name": "006_dependency.sql",
47
47
  "source_sha256": "6060070147323f8bdc126454acb890221c3d52c56acd1b267222634d7ccab77e",
48
- "public_sha256": "6060070147323f8bdc126454acb890221c3d52c56acd1b267222634d7ccab77e"
48
+ "public_sha256": "afb564f20edf154607457d6e13005deebd1099558b4db2792a41a35c45f3d485"
49
49
  },
50
50
  {
51
51
  "position": 7,
@@ -57,13 +57,13 @@
57
57
  "position": 8,
58
58
  "name": "008_effect_receipt.sql",
59
59
  "source_sha256": "c4c96d55fcb241005d926c6e06637172a4925007a535abfe2ea3a70ba0abe78d",
60
- "public_sha256": "c4c96d55fcb241005d926c6e06637172a4925007a535abfe2ea3a70ba0abe78d"
60
+ "public_sha256": "77b061c0a5c5beb63170f01bce848ba4cdbc9f38dc4c32ac6d1e78075675f2a8"
61
61
  },
62
62
  {
63
63
  "position": 9,
64
64
  "name": "009_verified_edge.sql",
65
65
  "source_sha256": "9c1bcff2d2028b16151fa422237437c820de93e19f6cd76ce21287571ad4e514",
66
- "public_sha256": "9c1bcff2d2028b16151fa422237437c820de93e19f6cd76ce21287571ad4e514"
66
+ "public_sha256": "83b285b538e407f1e6cc04f1bc0ac6d512187d7c59a787b91c0027a11a2806d2"
67
67
  },
68
68
  {
69
69
  "position": 10,
@@ -75,7 +75,7 @@
75
75
  "position": 11,
76
76
  "name": "011_confirm.sql",
77
77
  "source_sha256": "59a608f8828491bffe9d5e3851c2a17a06f6ac8a97e58271e6b76a743668ab8a",
78
- "public_sha256": "59a608f8828491bffe9d5e3851c2a17a06f6ac8a97e58271e6b76a743668ab8a"
78
+ "public_sha256": "882e7bcc1759447af04de2f50ee5dd506eed3b9b3ef4ac807a4e6e0c1cd4d249"
79
79
  },
80
80
  {
81
81
  "position": 12,
Binary file