@oathe/oathe 0.0.1 → 0.2.0

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 (70) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +7 -0
  3. package/README.md +99 -12
  4. package/assets/oathe-hero.svg +92 -0
  5. package/bin/oathe.mjs +376 -0
  6. package/docs/PRIVACY.md +45 -0
  7. package/package.json +32 -23
  8. package/plugin/.claude-plugin/plugin.json +10 -0
  9. package/plugin/.mcp.json +13 -0
  10. package/plugin/hooks/frame-note.mjs +24 -0
  11. package/plugin/hooks/heartbeat.mjs +49 -0
  12. package/plugin/hooks/hooks.json +39 -0
  13. package/plugin/hooks/lib.mjs +83 -0
  14. package/plugin/hooks/render-board.mjs +11 -0
  15. package/plugin/skills/oathe-work/SKILL.md +33 -0
  16. package/src/atif.mjs +633 -0
  17. package/src/blocks.mjs +192 -0
  18. package/src/board-render.mjs +106 -0
  19. package/src/config.mjs +169 -0
  20. package/src/context.mjs +35 -0
  21. package/src/doctor.mjs +108 -0
  22. package/src/harness.mjs +271 -0
  23. package/src/init.mjs +92 -0
  24. package/src/launch-env.mjs +25 -0
  25. package/src/launch.mjs +259 -0
  26. package/src/manifest.mjs +89 -0
  27. package/src/mcp/oathe-tools.mjs +517 -0
  28. package/src/paths.mjs +49 -0
  29. package/src/plans.mjs +50 -0
  30. package/src/runtime/discharge.mjs +57 -0
  31. package/src/runtime/provider.mjs +154 -0
  32. package/src/runtime/simple-cage.mjs +67 -0
  33. package/src/runtime/sql-acceptance-lane.mjs +89 -0
  34. package/src/session-host.mjs +81 -0
  35. package/src/substrate.mjs +337 -0
  36. package/src/successor.mjs +31 -0
  37. package/src/traces.mjs +242 -0
  38. package/src/uninstall.mjs +45 -0
  39. package/src/verifier.mjs +322 -0
  40. package/src/workspace.mjs +47 -0
  41. package/vendor/ddl/001_core.sql +312 -0
  42. package/vendor/ddl/002_claim.sql +438 -0
  43. package/vendor/ddl/003_verification.sql +480 -0
  44. package/vendor/ddl/004_delegation.sql +397 -0
  45. package/vendor/ddl/005_escalation.sql +303 -0
  46. package/vendor/ddl/006_dependency.sql +384 -0
  47. package/vendor/ddl/007_assignment.sql +502 -0
  48. package/vendor/ddl/008_effect_receipt.sql +290 -0
  49. package/vendor/ddl/009_verified_edge.sql +452 -0
  50. package/vendor/ddl/010_parent_child_verification.sql +320 -0
  51. package/vendor/ddl/011_confirm.sql +288 -0
  52. package/vendor/ddl/012_evaluator_lane.sql +444 -0
  53. package/vendor/ddl/013_claim_terminal.sql +279 -0
  54. package/vendor/ddl/014_claim_settlement.sql +327 -0
  55. package/vendor/ddl/015_claim_yield.sql +213 -0
  56. package/vendor/ddl/016_reopened_reclaim.sql +285 -0
  57. package/vendor/ddl/017_claim_yield_causes.sql +357 -0
  58. package/vendor/ddl/018_receiptless_unknown.sql +249 -0
  59. package/vendor/ddl/019_verification_contract_freeze.sql +335 -0
  60. package/vendor/ddl/020_context_compilation.sql +105 -0
  61. package/vendor/ddl/021_execution_attempt_closure.sql +95 -0
  62. package/vendor/ddl/022_verification_clause.sql +106 -0
  63. package/vendor/ddl/023_executor_role.sql +66 -0
  64. package/vendor/ddl/024_executor_role_hardening.sql +439 -0
  65. package/vendor/ddl/025_running_attempt_uniqueness.sql +102 -0
  66. package/vendor/ddl/026_acceptance_authority.sql +230 -0
  67. package/vendor/ddl/027_ownership_return.sql +836 -0
  68. package/vendor/ddl/028_attempt_bind_ownership.sql +173 -0
  69. package/vendor/ddl/manifest.json +183 -0
  70. package/index.js +0 -33
@@ -0,0 +1,89 @@
1
+ // oathe — the install manifest: the durable record of every write oathe has made to a user
2
+ // surface. `doctor` verifies against it, `uninstall` removes exactly what it lists, and
3
+ // `backupOnce` keeps the pre-first-write copy that makes any of this reversible.
4
+
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ export function sha256Hex(text) {
10
+ return crypto.createHash('sha256').update(text).digest('hex');
11
+ }
12
+
13
+ const MANIFEST_FORMAT = 1;
14
+
15
+ export class InstallManifest {
16
+ /** @param {{manifestPath: string, backupsDir: string, clock?: () => string}} o */
17
+ constructor({ manifestPath, backupsDir, clock = () => new Date().toISOString() }) {
18
+ this.manifestPath = manifestPath;
19
+ this.backupsDir = backupsDir;
20
+ this.clock = clock;
21
+ /** @type {Array<{harness: string, file: string, kind: string, scope: string, detail: object|null, block_version: string, sha256: string, installed_at: string}>} */
22
+ this.rows = [];
23
+ /** @type {Array<{file: string, backup: string|null, absent_before: boolean, taken_at: string}>} */
24
+ this.backups = [];
25
+ }
26
+
27
+ static load({ manifestPath, backupsDir, clock }) {
28
+ const manifest = new InstallManifest({ manifestPath, backupsDir, clock });
29
+ if (fs.existsSync(manifestPath)) {
30
+ const doc = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
31
+ manifest.rows = doc.rows ?? [];
32
+ manifest.backups = doc.backups ?? [];
33
+ }
34
+ return manifest;
35
+ }
36
+
37
+ save() {
38
+ fs.mkdirSync(path.dirname(this.manifestPath), { recursive: true });
39
+ const doc = { format: MANIFEST_FORMAT, saved_at: this.clock(), rows: this.rows, backups: this.backups };
40
+ fs.writeFileSync(this.manifestPath, `${JSON.stringify(doc, null, 2)}\n`);
41
+ }
42
+
43
+ /** One row per (harness, file, kind, detail identity); a re-run replaces its own row. */
44
+ upsert({ harness, file, kind, scope = 'user', detail = null, blockVersion, sha256 }) {
45
+ const key = this.#key({ harness, file, kind, detail });
46
+ const row = {
47
+ harness, file, kind, scope, detail,
48
+ block_version: blockVersion, sha256, installed_at: this.clock(),
49
+ };
50
+ const at = this.rows.findIndex((r) => this.#key(r) === key);
51
+ if (at === -1) this.rows.push(row);
52
+ else this.rows[at] = row;
53
+ return row;
54
+ }
55
+
56
+ #key({ harness, file, kind, detail }) {
57
+ return JSON.stringify([harness, file, kind, detail ?? null]);
58
+ }
59
+
60
+ /** @returns {object[]} the removed rows */
61
+ removeWhere(predicate) {
62
+ const dropped = this.rows.filter(predicate);
63
+ this.rows = this.rows.filter((r) => !predicate(r));
64
+ return dropped;
65
+ }
66
+
67
+ /**
68
+ * Copy `file` into backups/ before oathe's FIRST write to it — later calls are no-ops, so the
69
+ * backup is always the pre-oathe state. A file that does not exist yet is recorded as
70
+ * absent_before (uninstall may then delete what init created).
71
+ * @returns {string|null} the backup path, or null when the file did not exist
72
+ */
73
+ backupOnce(file) {
74
+ const existing = this.backups.find((b) => b.file === file);
75
+ if (existing) return existing.backup;
76
+ let entry;
77
+ if (!fs.existsSync(file)) {
78
+ entry = { file, backup: null, absent_before: true, taken_at: this.clock() };
79
+ } else {
80
+ const content = fs.readFileSync(file, 'utf8');
81
+ fs.mkdirSync(this.backupsDir, { recursive: true });
82
+ const backup = path.join(this.backupsDir, `${sha256Hex(content).slice(0, 12)}-${path.basename(file)}`);
83
+ fs.writeFileSync(backup, content);
84
+ entry = { file, backup, absent_before: false, taken_at: this.clock() };
85
+ }
86
+ this.backups.push(entry);
87
+ return entry.backup;
88
+ }
89
+ }
@@ -0,0 +1,517 @@
1
+ // oathe — the claim/board/statement/yield/pickup MCP server. The SHAPE is copied from
2
+ // oathe-runtime's governed-effect-mcp-server (unpinned): newline-delimited JSON-RPC 2.0 over
3
+ // stdio, NO SDK, a pure dispatch() that unit-tests with a fake tools map, and a run-as-main
4
+ // guard so importing never reads stdin or opens a connection.
5
+ //
6
+ // FAIL-LOUD: every substrate refusal (a second claimant, a yield with no claim, a statement
7
+ // against nothing) comes back isError:true with a typed code. The substrate's refusals are the
8
+ // product — they must reach the model as refusals, never as bland empties.
9
+ //
10
+ // Protocol: legacy initialize handshake advertising 2025-06-18 — the maximally compatible target
11
+ // (2026-07-28 "modern" clients probe server/discover, read our -32601, and fall back).
12
+
13
+ import readline from 'node:readline';
14
+ import { pathToFileURL } from 'node:url';
15
+ import crypto from 'node:crypto';
16
+
17
+ import { standardPlan, verificationTaskId, verificationObjective, isVerificationTask } from '../plans.mjs';
18
+ import { launchedHarness } from '../launch-env.mjs';
19
+
20
+ export const PROTOCOL_VERSION = '2025-06-18';
21
+ export const SERVER_NAME = 'oathe-tools';
22
+
23
+ // Durations flow from OatheConfig (founder ruling: never hardcode); SQL uses make_interval
24
+ // with a parameter, so the value is data, not a spliced literal.
25
+
26
+ export class OatheToolError extends Error {
27
+ constructor(code, message, details = {}) {
28
+ super(message);
29
+ this.name = 'OatheToolError';
30
+ this.code = code;
31
+ this.details = details;
32
+ }
33
+ }
34
+
35
+ export function makeToolDefs() {
36
+ return [
37
+ {
38
+ name: 'oathe_claim',
39
+ description:
40
+ 'Claim a task on the cell board (minting it if new — with plan_status honestly "unknown", '
41
+ + 'never a fabricated plan). A claim is a speech act: it takes responsibility, it does not '
42
+ + 'do the work. A second claimant is refused by the substrate. Args: {task_id, objective}.',
43
+ inputSchema: {
44
+ type: 'object',
45
+ properties: {
46
+ task_id: { type: 'string', description: 'the task to claim' },
47
+ objective: { type: 'string', description: 'what done means, in one line (required to mint a new task)' },
48
+ },
49
+ required: ['task_id'],
50
+ },
51
+ },
52
+ {
53
+ name: 'oathe_board',
54
+ description:
55
+ "The Oathe board: this folder's open tasks — yours, open, or held by someone else. "
56
+ + 'Args: {all?: true} to see every workspace.',
57
+ inputSchema: { type: 'object', properties: { all: { type: 'boolean' } } },
58
+ },
59
+ {
60
+ name: 'oathe_statement',
61
+ description:
62
+ 'Record a progress statement against your active claim — a statement, not truth; nothing '
63
+ + 'settles. Args: {task_id, proposition, evidence_ref?}.',
64
+ inputSchema: {
65
+ type: 'object',
66
+ properties: {
67
+ task_id: { type: 'string' },
68
+ proposition: { type: 'string' },
69
+ evidence_ref: { type: 'string' },
70
+ },
71
+ required: ['task_id', 'proposition'],
72
+ },
73
+ },
74
+ {
75
+ name: 'oathe_yield',
76
+ description:
77
+ 'Yield your active claim with the declared operator cause: the obligation goes back on the '
78
+ + 'board, unowned. Args: {task_id, note}.',
79
+ inputSchema: {
80
+ type: 'object',
81
+ properties: { task_id: { type: 'string' }, note: { type: 'string' } },
82
+ required: ['task_id', 'note'],
83
+ },
84
+ },
85
+ {
86
+ name: 'oathe_done',
87
+ description:
88
+ 'Assert completion of your active claim: records a completion statement and moves the '
89
+ + 'claim terminal through the substrate\'s own verb. Asserted, NOT settled — verification '
90
+ + 'is still owed at verify_by. Args: {task_id, proposition, evidence_ref?}.',
91
+ inputSchema: {
92
+ type: 'object',
93
+ properties: {
94
+ task_id: { type: 'string' },
95
+ proposition: { type: 'string', description: 'what was done, as the completion assertion' },
96
+ evidence_ref: { type: 'string' },
97
+ },
98
+ required: ['task_id', 'proposition'],
99
+ },
100
+ },
101
+ {
102
+ name: 'oathe_verify',
103
+ description:
104
+ 'Run the verification lane for an asserted task: a fresh headless engine (assigned at '
105
+ + 'claim time) judges the completion against its recorded traces, the verdict lands as '
106
+ + 'durable evidence, and the deterministic acceptance lane settles (accepted) or '
107
+ + 'reopens (rejected) under a NON-AUTHOR seat. Args: {task_id, engine?}.',
108
+ inputSchema: {
109
+ type: 'object',
110
+ properties: {
111
+ task_id: { type: 'string' },
112
+ engine: { type: 'string', description: 'override the assigned engine (claude|codex)' },
113
+ },
114
+ required: ['task_id'],
115
+ },
116
+ },
117
+ {
118
+ name: 'oathe_pickup',
119
+ description:
120
+ 'Pick up prior work on a claim: runs the successor sequence (read prior attempt → '
121
+ + 'reallocate → recompiled frame) and returns the compiled context. The obligation, not '
122
+ + 'the conversation, is what comes back. Args: {task_id}.',
123
+ inputSchema: {
124
+ type: 'object',
125
+ properties: { task_id: { type: 'string' } },
126
+ required: ['task_id'],
127
+ },
128
+ },
129
+ ];
130
+ }
131
+
132
+ /**
133
+ * The tool implementations over a substrate client ({query}). Identity comes from the
134
+ * environment the launcher stamped, never from the model.
135
+ *
136
+ * @param {{client: {query: Function}, identity: {orgId: string, principalId: string, department: string},
137
+ * workspace: string, executionActor?: string,
138
+ * successor?: (o: {task_id: string, work_claim_id: string}) => Promise<object>}} o
139
+ */
140
+ export function createOatheTools({ client, identity, workspace, executionActor, successor, config, verifier }) {
141
+ const { orgId, principalId, department } = identity;
142
+ const leaseHours = config?.get('leaseHours') ?? 4;
143
+ const verifyByHours = config?.get('verifyByHours') ?? 24;
144
+ const actor = executionActor
145
+ ?? (process.env.OATHE_EXECUTION_ATTEMPT_ID
146
+ ? `attempt:${process.env.OATHE_EXECUTION_ATTEMPT_ID}`
147
+ : 'oathe-operator');
148
+
149
+ async function activeClaim(taskId) {
150
+ const { rows } = await client.query(
151
+ `SELECT work_claim_id FROM cell.work_claim
152
+ WHERE org_id = $1 AND task_id = $2 AND state = 'active' LIMIT 1`,
153
+ [orgId, taskId]);
154
+ if (rows.length === 0) {
155
+ throw new OatheToolError('OATHE_NO_ACTIVE_CLAIM',
156
+ `no active claim on '${taskId}' — nothing to speak against`, { task_id: taskId });
157
+ }
158
+ return rows[0].work_claim_id;
159
+ }
160
+
161
+ return {
162
+ async oathe_claim({ task_id, objective }) {
163
+ const contractRef = `workspace:${workspace};contract:${orgId}/${task_id}@v1`;
164
+ const { rows: existing } = await client.query(
165
+ 'SELECT origin FROM cell.task WHERE org_id = $1 AND task_id = $2', [orgId, task_id]);
166
+ if (existing.length === 0) {
167
+ if (!objective) {
168
+ throw new OatheToolError('OATHE_OBJECTIVE_REQUIRED',
169
+ `task '${task_id}' does not exist yet; minting it needs an objective — what does done mean?`,
170
+ { task_id });
171
+ }
172
+ await client.query(
173
+ `INSERT INTO cell.task (org_id, task_id, department, objective, origin, verification_plan,
174
+ verify_by, claim_mode, created_at)
175
+ VALUES ($1, $2, $3, $4, 'minted_at_claim', '{"plan_status":"unknown"}'::jsonb,
176
+ now() + make_interval(hours => $5), 'exclusive', now())
177
+ ON CONFLICT DO NOTHING`,
178
+ [orgId, task_id, department, objective, verifyByHours]);
179
+ }
180
+ const workClaimId = crypto.randomUUID();
181
+ if (existing[0]?.origin === 'reopened') {
182
+ // R8's second half: reopened work is RESUMED, not re-claimed — the evaluator lane's
183
+ // verb seats the prior interval's principal (the one who answers for this work next).
184
+ const { rows: reclaimed } = await client.query(
185
+ 'SELECT cell.reclaim_reopened_task($1, $2, $3, now(), $4) AS seated',
186
+ [orgId, task_id, workClaimId, crypto.randomUUID()]);
187
+ if (reclaimed[0].seated !== true) {
188
+ throw new OatheToolError('OATHE_RECLAIM_REFUSED',
189
+ `'${task_id}' is reopened but could not be resumed (a live owner already holds it)`,
190
+ { task_id });
191
+ }
192
+ } else {
193
+ await client.query(
194
+ `SELECT cell.claim_work($1, $2, $3, NULL, NULL, $4, $5, 'exclusive',
195
+ now() + make_interval(hours => $6), $7, now(), $8)`,
196
+ [orgId, task_id, workClaimId, principalId, department, leaseHours, contractRef, crypto.randomUUID()]);
197
+ }
198
+ // Verifier assignment happens AT CLAIM (founder direction 2026-08-25): the engine that
199
+ // will judge this work is named before the work starts, from config, on the record.
200
+ const verifier = config?.get('verifier') ?? 'claude';
201
+ await client.query(
202
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
203
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
204
+ evidence_refs, epistemic_status, asserted_at)
205
+ VALUES ($1, $2, $3, $4, $5, $6, 'observation', $7, $8, $9::jsonb, 'observed', now())`,
206
+ [crypto.randomUUID(), orgId, task_id, workClaimId, actor, principalId,
207
+ `verifier:${verifier}`,
208
+ `verification of this claim is assigned to the ${verifier} engine (bound at claim time)`,
209
+ JSON.stringify([`config:verifier=${verifier}`])]);
210
+ return {
211
+ claimed: true,
212
+ task_id,
213
+ work_claim_id: workClaimId,
214
+ contract_ref: contractRef,
215
+ lease: `${leaseHours} hours`,
216
+ verifier,
217
+ note: existing.length === 0
218
+ ? "task minted at claim — plan_status is honestly 'unknown'; a real cell pages you at verify_by"
219
+ : 'existing task claimed',
220
+ };
221
+ },
222
+
223
+ async oathe_board({ all = false } = {}) {
224
+ // Workspace scope rides the claim's contract_ref (W1 convention). Unclaimed tasks carry no
225
+ // workspace yet, so the scoped board still shows them: they are the offered, claimable ones.
226
+ const filter = all ? '' : 'AND (w.contract_ref LIKE $2 OR w.contract_ref IS NULL)';
227
+ const params = all ? [orgId] : [orgId, `workspace:${workspace};%`];
228
+ // ONE row per task: the latest claim in view wins (a task reclaimed after a yield is one
229
+ // task, not a history lesson — statements carry the history).
230
+ const { rows } = await client.query(
231
+ `SELECT task_id, objective, origin, state, principal_id, contract_ref, settled_at, lease_until,
232
+ last_progress, last_progress_at FROM (
233
+ SELECT DISTINCT ON (t.task_id)
234
+ t.task_id, t.objective, t.created_at, t.origin, w.state, w.principal_id, w.contract_ref,
235
+ w.settled_at,
236
+ to_char(w.ownership_valid_until, 'YYYY-MM-DD HH24:MI') AS lease_until,
237
+ p.proposition AS last_progress,
238
+ to_char(p.asserted_at, 'YYYY-MM-DD HH24:MI') AS last_progress_at
239
+ FROM cell.task t LEFT JOIN cell.work_claim w USING (org_id, task_id)
240
+ LEFT JOIN LATERAL (
241
+ SELECT proposition, asserted_at FROM cell.agent_statement s
242
+ WHERE s.org_id = t.org_id AND s.task_id = t.task_id
243
+ AND s.work_claim_id = w.work_claim_id
244
+ AND s.statement_type = 'progress' AND s.subject_ref NOT LIKE 'trace:%'
245
+ ORDER BY s.asserted_at DESC LIMIT 1
246
+ ) p ON true
247
+ WHERE t.org_id = $1 ${filter}
248
+ ORDER BY t.task_id, w.claimed_at DESC NULLS LAST
249
+ ) latest ORDER BY created_at DESC`,
250
+ params);
251
+ // ONE classification, consumed by every render: active-yours / active-theirs /
252
+ // asserted-awaiting-verdict / open. Asserted is NOT open — it awaits verification.
253
+ const sections = { mine: [], open: [], asserted: [], held: [] };
254
+ for (const row of rows) {
255
+ if (row.settled_at) continue; // settled: the obligation is CLOSED — off the board
256
+ if (row.state === 'active') sections[row.principal_id === principalId ? 'mine' : 'held'].push(row);
257
+ else if (row.origin === 'reopened') sections.open.push({ ...row, state: 'reopened' }); // R8: back on the board
258
+ else if (row.state === 'completion_asserted') sections.asserted.push(row);
259
+ else sections.open.push(row);
260
+ }
261
+ return { workspace: all ? null : workspace, board: rows, sections };
262
+ },
263
+
264
+ async oathe_statement({ task_id, proposition, evidence_ref }) {
265
+ const workClaimId = await activeClaim(task_id);
266
+ const statementId = crypto.randomUUID();
267
+ await client.query(
268
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
269
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
270
+ evidence_refs, epistemic_status, asserted_at)
271
+ VALUES ($1, $2, $3, $4, $5, $6, 'progress', $7, $8, $9::jsonb, 'observed', now())`,
272
+ [statementId, orgId, task_id, workClaimId, actor, principalId,
273
+ `task:${task_id}`, proposition, JSON.stringify([evidence_ref ?? 'note:session'])]);
274
+ return {
275
+ recorded: true, statement_id: statementId,
276
+ note: 'a statement, not truth — nothing settled',
277
+ };
278
+ },
279
+
280
+ async oathe_yield({ task_id, note }) {
281
+ const workClaimId = await activeClaim(task_id);
282
+ await client.query(
283
+ 'SELECT cell.oathe_yield_operator($1::uuid, $2, now(), $3::uuid)',
284
+ [workClaimId, note, crypto.randomUUID()]);
285
+ return {
286
+ yielded: true, task_id, work_claim_id: workClaimId,
287
+ note: 'the obligation is back on the board, unowned',
288
+ };
289
+ },
290
+
291
+ async oathe_done({ task_id, proposition, evidence_ref }) {
292
+ const workClaimId = await activeClaim(task_id);
293
+
294
+ // 1. G2-b: work may not finish until a plan exists. If the plan is still honestly
295
+ // unknown, the POLICY binder supplies the standard plan — via the substrate's own
296
+ // amend verb (an explicit CONTRACT_CHANGED event), which FC161 permits only while
297
+ // the claim is ACTIVE, i.e. exactly now, before the completion terminal.
298
+ const { rows: taskRows } = await client.query(
299
+ 'SELECT verification_plan AS plan FROM cell.task WHERE org_id = $1 AND task_id = $2',
300
+ [orgId, task_id]);
301
+ if (taskRows[0].plan?.plan_status !== 'declared') {
302
+ await client.query(
303
+ 'SELECT cell.amend_verification_contract($1, $2, $3::jsonb, now(), $4::uuid, $5)',
304
+ [orgId, task_id, JSON.stringify(standardPlan()), crypto.randomUUID(),
305
+ 'oathe policy-standard plan bound at completion (G2-b policy binder)']);
306
+ }
307
+
308
+ // 2. The completion statement + the substrate's terminal (as before).
309
+ const statementId = crypto.randomUUID();
310
+ await client.query(
311
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
312
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
313
+ evidence_refs, epistemic_status, asserted_at)
314
+ VALUES ($1, $2, $3, $4, $5, $6, 'completion', $7, $8, $9::jsonb, 'observed', now())`,
315
+ [statementId, orgId, task_id, workClaimId, actor, principalId,
316
+ `task:${task_id}`, proposition, JSON.stringify([evidence_ref ?? 'note:session'])]);
317
+ await client.query(
318
+ 'SELECT cell.assert_claim_completion($1::uuid, $2::uuid)',
319
+ [statementId, crypto.randomUUID()]);
320
+
321
+ // 3. Verification is ordinary work: mint the verification task, open on the board,
322
+ // carrying the engine assigned at claim time. A verification task does not mint a
323
+ // verifier for ITSELF — that regress ends at the deterministic bar.
324
+ let verificationTask = null;
325
+ if (!isVerificationTask(task_id)) {
326
+ const { rows: engineRows } = await client.query(
327
+ `SELECT subject_ref FROM cell.agent_statement
328
+ WHERE org_id = $1 AND work_claim_id = $2 AND subject_ref LIKE 'verifier:%'
329
+ ORDER BY asserted_at DESC LIMIT 1`,
330
+ [orgId, workClaimId]);
331
+ const engine = engineRows[0]?.subject_ref.slice('verifier:'.length)
332
+ ?? config?.get('verifier') ?? 'claude';
333
+ verificationTask = verificationTaskId(task_id);
334
+ await client.query(
335
+ `INSERT INTO cell.task (org_id, task_id, department, objective, origin, verification_plan,
336
+ verify_by, claim_mode, created_at)
337
+ VALUES ($1, $2, $3, $4, 'minted_at_claim', $5::jsonb,
338
+ now() + make_interval(hours => $6), 'exclusive', now())
339
+ ON CONFLICT DO NOTHING`,
340
+ [orgId, verificationTask, department, verificationObjective(task_id),
341
+ JSON.stringify(standardPlan({ verifierEngine: engine })), verifyByHours]);
342
+ }
343
+
344
+ return {
345
+ done: true, task_id, work_claim_id: workClaimId, statement_id: statementId,
346
+ verification_task: verificationTask,
347
+ note: verificationTask
348
+ ? `completion ASSERTED, not settled. Verification task '${verificationTask}' is on the `
349
+ + 'board. A DIFFERENT principal must verify (FC010 — you cannot verify your own work, '
350
+ + 'including via your own sub-agents): run `oathe verify` from any terminal, or leave '
351
+ + 'it for another session to claim.'
352
+ : 'completion ASSERTED, not settled — the deterministic acceptance bar settles verification tasks',
353
+ };
354
+ },
355
+
356
+ async oathe_verify({ task_id, engine }) {
357
+ if (!verifier) {
358
+ throw new OatheToolError('OATHE_VERIFY_UNAVAILABLE',
359
+ 'the verification lane is not wired into this server — run `oathe verify` from a '
360
+ + 'terminal instead; verification cannot pretend', { task_id });
361
+ }
362
+ return verifier({ taskId: task_id, engine });
363
+ },
364
+
365
+ async oathe_pickup({ task_id }) {
366
+ const { rows } = await client.query(
367
+ `SELECT work_claim_id, state FROM cell.work_claim
368
+ WHERE org_id = $1 AND task_id = $2 ORDER BY claimed_at DESC LIMIT 1`,
369
+ [orgId, task_id]);
370
+ const latest = rows[0];
371
+ if (!latest || latest.state !== 'active') {
372
+ // The refusal coaches the recovery a session actually needs mid-conversation.
373
+ const hint = latest
374
+ ? `the latest claim on '${task_id}' is ${latest.state} — claim it again (oathe_claim), `
375
+ + 'then oathe_pickup follows the task\'s history'
376
+ : `no claim exists on '${task_id}' — nothing to pick up`;
377
+ throw new OatheToolError('OATHE_NO_ACTIVE_CLAIM', hint, { task_id, state: latest?.state ?? null });
378
+ }
379
+ if (!successor) {
380
+ throw new OatheToolError('OATHE_PICKUP_UNAVAILABLE',
381
+ 'pickup is not wired into this tools server — the successor sequence is unavailable in '
382
+ + 'this session (a preview limitation of sessions without the runtime seam); pickup '
383
+ + 'cannot pretend', { task_id });
384
+ }
385
+ return successor({ task_id, work_claim_id: latest.work_claim_id });
386
+ },
387
+ };
388
+ }
389
+
390
+ const okText = (obj) => ({ content: [{ type: 'text', text: JSON.stringify(obj) }], isError: false });
391
+ const errText = (obj) => ({ content: [{ type: 'text', text: JSON.stringify(obj) }], isError: true });
392
+
393
+ /** One tools/call: a throwing tool becomes a TYPED tool error — never a bland success. */
394
+ export async function handleToolCall(params, tools) {
395
+ const name = params?.name;
396
+ const fn = tools[name];
397
+ if (typeof fn !== 'function') {
398
+ return errText({ status: 'ERROR', error_type: 'unknown_tool', reason: `no such oathe tool '${name}'` });
399
+ }
400
+ try {
401
+ return okText(await fn(params?.arguments || {}));
402
+ } catch (e) {
403
+ return errText({
404
+ status: 'ERROR',
405
+ error_type: e?.name || 'Error',
406
+ error_code: e?.code ?? null,
407
+ reason: String(e?.message || e).slice(0, 400),
408
+ fail_loud: true,
409
+ });
410
+ }
411
+ }
412
+
413
+ /**
414
+ * The opt-in gate for the served tools map. A session the oathe launcher started passes
415
+ * through untouched; anything else gets the same tool NAMES whose every call is the typed
416
+ * OATHE_NOT_LAUNCHED refusal — loud to the model (a called tool must answer), inert to the
417
+ * substrate (an unlaunched session never touches the board).
418
+ */
419
+ export function withLaunchGate(tools, env = process.env) {
420
+ if (launchedHarness(env)) return tools;
421
+ const refuse = async () => {
422
+ throw new OatheToolError('OATHE_NOT_LAUNCHED',
423
+ 'this session was not launched through oathe, so the board is not bound to it — start the '
424
+ + 'session with `oathe claude` or `oathe codex` to opt in');
425
+ };
426
+ return Object.fromEntries(Object.keys(tools).map((name) => [name, refuse]));
427
+ }
428
+
429
+ /** The pure JSON-RPC dispatcher — a response object, or null for a notification. */
430
+ export async function dispatch(msg, { tools }) {
431
+ const { id, method, params } = msg || {};
432
+ const isNotification = id === undefined || id === null;
433
+ if (method === 'notifications/initialized' || method === 'initialized') return null;
434
+ const result = await (async () => {
435
+ switch (method) {
436
+ case 'initialize':
437
+ return {
438
+ protocolVersion: PROTOCOL_VERSION,
439
+ capabilities: { tools: {} },
440
+ serverInfo: { name: SERVER_NAME, version: '0.1.0' },
441
+ };
442
+ case 'tools/list':
443
+ return { tools: makeToolDefs() };
444
+ case 'tools/call':
445
+ return handleToolCall(params, tools);
446
+ case 'ping':
447
+ return {};
448
+ default:
449
+ return undefined;
450
+ }
451
+ })();
452
+ if (isNotification) return null;
453
+ if (result === undefined) {
454
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } };
455
+ }
456
+ return { jsonrpc: '2.0', id, result };
457
+ }
458
+
459
+ /** Start the ndjson JSON-RPC loop over stdio. Only runs when launched as the entrypoint. */
460
+ export async function main(env = process.env) {
461
+ const { Substrate } = await import('../substrate.mjs');
462
+ const { buildPaths } = await import('../paths.mjs');
463
+ const { workspaceRef } = await import('../workspace.mjs');
464
+ const paths = buildPaths(env);
465
+ const { OatheConfig } = await import('../config.mjs');
466
+ const config = new OatheConfig({ env, cwd: env.OATHE_WORKSPACE_DIR || process.cwd() });
467
+ const substrate = new Substrate({ database: config.get('db'), paths, env, config });
468
+ const identity = {
469
+ orgId: config.get('org'),
470
+ principalId: config.get('principal') || env.USER || 'operator',
471
+ department: config.get('department'),
472
+ };
473
+ // The successor is built LAZILY on the first pickup: a session that never picks up never pays
474
+ // for the runtime wiring, and a wiring failure surfaces as that call's typed error.
475
+ let successorPromise = null;
476
+ let verifierInstance = null;
477
+ const tools = createOatheTools({
478
+ client: substrate,
479
+ identity,
480
+ config,
481
+ workspace: workspaceRef(env.OATHE_WORKSPACE_DIR || process.cwd()),
482
+ verifier: async (o) => {
483
+ if (!verifierInstance) {
484
+ const { Verifier } = await import('../verifier.mjs');
485
+ verifierInstance = new Verifier({
486
+ substrate, paths, config,
487
+ workspace: workspaceRef(env.OATHE_WORKSPACE_DIR || process.cwd()),
488
+ operatorPrincipal: identity.principalId,
489
+ });
490
+ }
491
+ return verifierInstance.verify(o);
492
+ },
493
+ successor: async (o) => {
494
+ if (!successorPromise) {
495
+ successorPromise = import('../runtime/provider.mjs')
496
+ .then(({ resolveRuntimeProvider }) => resolveRuntimeProvider({ config, paths })
497
+ .successor({ substrate, identity, paths }));
498
+ successorPromise.catch(() => { successorPromise = null; }); // a failed build must not poison retries
499
+ }
500
+ return (await successorPromise).pickup(o);
501
+ },
502
+ });
503
+ const served = withLaunchGate(tools, env);
504
+ const rl = readline.createInterface({ input: process.stdin });
505
+ rl.on('line', async (line) => {
506
+ const s = line.trim();
507
+ if (!s) return;
508
+ let msg;
509
+ try { msg = JSON.parse(s); } catch { return; }
510
+ const out = await dispatch(msg, { tools: served });
511
+ if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
512
+ });
513
+ }
514
+
515
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
516
+ main();
517
+ }
package/src/paths.mjs ADDED
@@ -0,0 +1,49 @@
1
+ // oathe — every filesystem location the package reaches, named once, env-overridable.
2
+ //
3
+ // The monorepo is consumed READ-ONLY (episode freeze: importing pinned modules is harmless,
4
+ // editing is forbidden); the cage lives outside oathe-runtime's exports map, so it is imported
5
+ // by PATH — `cagePath` is that one sanctioned pre-extraction address.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import os from 'node:os';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+
13
+ /**
14
+ * @param {NodeJS.ProcessEnv} env
15
+ * @returns {{monorepo: string|null, ddlDir: string|null, ddlSource: ('OATHE_DDL_DIR'|'vendor'|'monorepo'|null),
16
+ * cagePath: string|null, oatheHome: string,
17
+ * manifestPath: string, backupsDir: string, artifactDir: string, workRoot: string,
18
+ * packageRoot: string, pluginDir: string, mcpServerPath: string}}
19
+ */
20
+ export function buildPaths(env = process.env) {
21
+ // R-D (amended for the public tree): the runtime checkout is named ONLY by env —
22
+ // no baked-in machine default. '' means "none".
23
+ const monorepo = env.OATHE_MONOREPO || null;
24
+ const oatheHome = env.OATHE_HOME || path.join(os.homedir(), '.oathe');
25
+ const packageRoot = path.resolve(fileURLToPath(import.meta.url), '../..');
26
+ const vendorDdl = path.join(packageRoot, 'vendor/ddl');
27
+ const vendorDdlExists = fs.existsSync(vendorDdl);
28
+ const monorepoDdl = monorepo ? path.join(monorepo, 'packages/oathe-cell-domain/oathe_cell_domain/ddl') : null;
29
+ // One resolution, two facts: ddlDir and ddlSource walk the SAME OATHE_DDL_DIR > vendor/ddl >
30
+ // monorepo > null order, so a caller can never see a dir without a matching, named source.
31
+ const ddlDir = env.OATHE_DDL_DIR || (vendorDdlExists ? vendorDdl : null) || monorepoDdl;
32
+ const ddlSource = env.OATHE_DDL_DIR
33
+ ? 'OATHE_DDL_DIR'
34
+ : (vendorDdlExists ? 'vendor' : (monorepoDdl ? 'monorepo' : null));
35
+ return Object.freeze({
36
+ monorepo,
37
+ ddlDir,
38
+ ddlSource,
39
+ cagePath: monorepo ? path.join(monorepo, 'packages/oathe-runtime/falsifiers/acp-probe/acp-cage.mjs') : null,
40
+ oatheHome,
41
+ manifestPath: path.join(oatheHome, 'install-manifest.json'),
42
+ backupsDir: path.join(oatheHome, 'backups'),
43
+ artifactDir: path.join(oatheHome, 'artifacts'),
44
+ workRoot: path.join(oatheHome, 'work'),
45
+ packageRoot,
46
+ pluginDir: path.join(packageRoot, 'plugin'),
47
+ mcpServerPath: path.join(packageRoot, 'src/mcp/oathe-tools.mjs'),
48
+ });
49
+ }