@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
@@ -10,16 +10,23 @@
10
10
  // Protocol: legacy initialize handshake advertising 2025-06-18 — the maximally compatible target
11
11
  // (2026-07-28 "modern" clients probe server/discover, read our -32601, and fall back).
12
12
 
13
- import readline from 'node:readline';
14
13
  import { pathToFileURL } from 'node:url';
15
14
  import crypto from 'node:crypto';
16
15
 
17
16
  import { standardPlan, verificationTaskId, verificationObjective, isVerificationTask } from '../plans.mjs';
18
- import { launchedHarness, liveSessionMarker } from '../launch-env.mjs';
17
+ import { verifierCapable } from '../harnesses/catalog.mjs';
18
+ import { ContractRef, HomeBoard } from '../home.mjs';
19
+ import { amendSubjectRef, isEngineFailureSql, isTraceSubjectSql, latestVerdictSql, latestProgressSql, latestTracePathSql, linkTrace } from '../statements.mjs';
20
+ import { WIRE_KINDS, LINKABLE, emit, restoredReceipt } from '../wire.mjs';
19
21
 
20
22
  export const PROTOCOL_VERSION = '2025-06-18';
21
23
  export const SERVER_NAME = 'oathe-tools';
22
24
 
25
+ /** The only two honest moves after a rejection (ruling 2026-08-31) — ONE wording, spoken
26
+ * by the blocked done's result and the reclaim bundle alike. */
27
+ export const REJECTION_FORK = 'prove it (do the missing work, assert done again) or descope it '
28
+ + '(oathe_amend — the objective shrinks on the record); verification re-runs either way';
29
+
23
30
  // Durations flow from OatheConfig (founder ruling: never hardcode); SQL uses make_interval
24
31
  // with a parameter, so the value is data, not a spliced literal.
25
32
 
@@ -71,6 +78,20 @@ export function makeToolDefs() {
71
78
  required: ['task_id', 'proposition'],
72
79
  },
73
80
  },
81
+ {
82
+ name: 'oathe_amend',
83
+ description:
84
+ "Change what done means, on the record: amends the ACTIVE claim's objective — this "
85
+ + 'changes the expected outcome; the original definition stays on record in the '
86
+ + 'amendment trail, and verification judges the version in force at assertion WITH '
87
+ + 'the trail visible. Open-claim only, acceptance-seat only, never the verifier. '
88
+ + 'Args: {task_id, objective, why}.',
89
+ inputSchema: {
90
+ type: 'object',
91
+ properties: { task_id: { type: 'string' }, objective: { type: 'string' }, why: { type: 'string' } },
92
+ required: ['task_id', 'objective', 'why'],
93
+ },
94
+ },
74
95
  {
75
96
  name: 'oathe_yield',
76
97
  description:
@@ -101,15 +122,17 @@ export function makeToolDefs() {
101
122
  {
102
123
  name: 'oathe_verify',
103
124
  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?}.',
125
+ 'Verify an asserted task and RETURN THE VERDICT — a fresh headless engine (assigned '
126
+ + 'at claim time) judges the completion against its recorded traces and the files in '
127
+ + 'the task workspace, in a detached process this call waits on (local substrate: '
128
+ + 'blocking is the contract; the verdict lands durably either way). Accepted settles '
129
+ + 'the claim; rejected reopens the task with the reason. A review already running is '
130
+ + 'a typed OATHE_VERIFY_IN_FLIGHT refusal. Args: {task_id, engine?}.',
108
131
  inputSchema: {
109
132
  type: 'object',
110
133
  properties: {
111
134
  task_id: { type: 'string' },
112
- engine: { type: 'string', description: 'override the assigned engine (claude|codex)' },
135
+ engine: { type: 'string', description: `override the assigned engine (${verifierCapable().join('|')})` },
113
136
  },
114
137
  required: ['task_id'],
115
138
  },
@@ -135,10 +158,72 @@ export function makeToolDefs() {
135
158
  *
136
159
  * @param {{client: {query: Function}, identity: {orgId: string, principalId: string, department: string},
137
160
  * workspace: string, executionActor?: string,
138
- * successor?: (o: {task_id: string, work_claim_id: string}) => Promise<object>}} o
161
+ * successor?: (o: {task_id: string, work_claim_id: string}) => Promise<object>,
162
+ * activation?: {register: (source: string) => Promise<object>,
163
+ * activate: (source: string) => Promise<object>}}} o
164
+ * activation — the central-registry seam (src/activation.mjs ActivationSeam): every
165
+ * successful call registers the workspace; oathe_claim activates through the ONE writer.
166
+ * oathe_claim (write intent) activates it, and the claim result discloses what happened.
167
+ * synthetic — the session sits on a synthetic workspace (R-BOARD-SCOPE): its mints are
168
+ * HOMELESS and its claims never adopt (R-HOME-BOARD).
139
169
  */
140
- export function createOatheTools({ client, identity, workspace, executionActor, successor, config, verifier }) {
170
+ export function createOatheTools({
171
+ client, identity, workspace, executionActor, successor, config, verifier, activation, synthetic = false,
172
+ // The SPEAKER primitive (founder ruling 2026-08-30): who is speaking — {surface, app,
173
+ // session} resolved from the writer's own ancestry (src/speaker.mjs). REQUIRED wherever
174
+ // it is consumed: a serving surface (one with the activation seam, whose writes ride the
175
+ // wire and stamp attribution) refuses construction without it. Internal read-only
176
+ // compositions (board render, the verifier's own seat) build no wrapper and carry none.
177
+ speaker = null,
178
+ }) {
141
179
  const { orgId, principalId, department } = identity;
180
+ const homeBoard = new HomeBoard({ client, orgId });
181
+ // ATTENTION: rejected-and-unreclaimed tasks on THIS board — the verdict's words, computed
182
+ // per call (stateless, repeats while true, vanishes on reclaim). Rides every tool response
183
+ // so a background rejection reaches the session at its next act; the pager covers new
184
+ // sessions. One ms-query per call.
185
+ const attentionLines = async () => {
186
+ const { rows } = await client.query(
187
+ `SELECT t.task_id, left(v.verdict, 140) AS verdict
188
+ FROM cell.task t
189
+ JOIN LATERAL (SELECT c.principal_id, c.claimed_at FROM cell.work_claim c
190
+ WHERE c.org_id = t.org_id AND c.task_id = t.task_id
191
+ ORDER BY c.claimed_at DESC LIMIT 1) w ON true
192
+ LEFT JOIN LATERAL (${latestVerdictSql({ task: 't' })}) v ON true
193
+ WHERE t.org_id = $1 AND t.origin = 'reopened' AND ${HomeBoard.homeSql('t')} = $2
194
+ AND w.claimed_at < (SELECT max(vr.recorded_at) FROM cell.verification vr
195
+ WHERE vr.org_id = t.org_id AND vr.task_id = t.task_id AND vr.result = 'rejected')
196
+ ORDER BY w.claimed_at`,
197
+ [orgId, workspace]);
198
+ const rejectedLines = rows.map((r) => `verification of '${r.task_id}' ${r.verdict ?? 'was rejected'} — reclaim it (oathe_claim) to see the bundle and pick the work back up`);
199
+ // Stalled verifications: the engine died before a verdict and the run RELEASED its claim.
200
+ // The retry is one line, on another engine — the verifier is just another harness.
201
+ const { rows: stalled } = await client.query(
202
+ `SELECT t.task_id, s.proposition
203
+ FROM cell.task t
204
+ JOIN LATERAL (
205
+ SELECT st.proposition, st.asserted_at FROM cell.agent_statement st
206
+ WHERE st.org_id = t.org_id AND st.task_id = t.task_id
207
+ AND ${isEngineFailureSql('st.evidence_refs')}
208
+ ORDER BY st.asserted_at DESC LIMIT 1
209
+ ) s ON true
210
+ WHERE t.org_id = $1 AND t.task_id LIKE 'verify:%'
211
+ AND NOT EXISTS (SELECT 1 FROM cell.work_claim c
212
+ WHERE c.org_id = t.org_id AND c.task_id = t.task_id
213
+ AND (c.state = 'active' OR c.settled_at IS NOT NULL))
214
+ AND s.asserted_at > coalesce((SELECT max(c2.claimed_at) FROM cell.work_claim c2
215
+ WHERE c2.org_id = t.org_id AND c2.task_id = t.task_id
216
+ AND c2.settled_at IS NOT NULL), 'epoch')`,
217
+ [orgId]);
218
+ const { verifierCapable } = await import('../harnesses/catalog.mjs');
219
+ const stalledLines = stalled.map((r) => {
220
+ const parent = r.task_id.slice('verify:'.length);
221
+ const failed = r.proposition.match(/^engine (\S+) failed/)?.[1];
222
+ const others = verifierCapable().filter((e) => e !== failed);
223
+ return `verification of '${parent}' STALLED — ${r.proposition.slice(0, 160)}; retry on another engine: /oathe:verify ${parent} ${others[0] ?? ''}`.trim();
224
+ });
225
+ return [...rejectedLines, ...stalledLines];
226
+ };
142
227
  const leaseHours = config?.get('leaseHours') ?? 4;
143
228
  const verifyByHours = config?.get('verifyByHours') ?? 24;
144
229
  const actor = executionActor
@@ -158,11 +243,18 @@ export function createOatheTools({ client, identity, workspace, executionActor,
158
243
  return rows[0].work_claim_id;
159
244
  }
160
245
 
161
- return {
246
+ let toolMap = {
162
247
  async oathe_claim({ task_id, objective }) {
163
- const contractRef = `workspace:${workspace};contract:${orgId}/${task_id}@v1`;
164
248
  const { rows: existing } = await client.query(
165
249
  'SELECT origin FROM cell.task WHERE org_id = $1 AND task_id = $2', [orgId, task_id]);
250
+ // R-HOME-BOARD: an existing task keeps the home its ledger already decided; a homeless
251
+ // task is ADOPTED by the first real folder that claims it; a synthetic surface neither
252
+ // stamps nor adopts — its mints and re-claims stay homeless.
253
+ const priorHome = existing.length > 0 ? await homeBoard.of(task_id) : null;
254
+ const home = priorHome ?? (synthetic ? null : workspace);
255
+ const adopted = existing.length > 0 && priorHome === null && home !== null;
256
+ let contractRef = String(new ContractRef({ workspace: home, orgId, taskId: task_id }));
257
+ let rejection = null; // the recovery bundle, set on a reclaim of rejected work
166
258
  if (existing.length === 0) {
167
259
  if (!objective) {
168
260
  throw new OatheToolError('OATHE_OBJECTIVE_REQUIRED',
@@ -189,6 +281,32 @@ export function createOatheTools({ client, identity, workspace, executionActor,
189
281
  `'${task_id}' is reopened but could not be resumed (a live owner already holds it)`,
190
282
  { task_id });
191
283
  }
284
+ // The reclaim verb TRANSCRIBES the prior interval's ref (016) — report that, not ours.
285
+ const { rows: seated } = await client.query(
286
+ 'SELECT contract_ref FROM cell.work_claim WHERE work_claim_id = $1', [workClaimId]);
287
+ contractRef = seated[0].contract_ref;
288
+ // The recovery bundle: what was missed and where the work stood when verification began.
289
+ const { rows: verdictRows } = await client.query(
290
+ `SELECT v.verdict, v.verdict_at FROM cell.task t
291
+ LEFT JOIN LATERAL (${latestVerdictSql({ task: 't' })}) v ON true
292
+ WHERE t.org_id = $1 AND t.task_id = $2`, [orgId, task_id]);
293
+ const { rows: vtask } = await client.query(
294
+ "SELECT created_at FROM cell.task WHERE org_id = $1 AND task_id = 'verify:' || $2", [orgId, task_id]);
295
+ const { rows: priorWords } = await client.query(
296
+ `SELECT proposition FROM cell.agent_statement s
297
+ WHERE s.org_id = $1 AND s.task_id = $2 AND NOT ${isTraceSubjectSql('s.subject_ref')}
298
+ ORDER BY s.asserted_at DESC LIMIT 3`, [orgId, task_id]);
299
+ const { rows: traceRows } = await client.query(
300
+ `SELECT DISTINCT evidence_refs FROM cell.agent_statement s
301
+ WHERE s.org_id = $1 AND s.task_id = $2 AND ${isTraceSubjectSql('s.subject_ref')}
302
+ ORDER BY evidence_refs LIMIT 2`, [orgId, task_id]);
303
+ rejection = {
304
+ reason: verdictRows[0]?.verdict ?? null,
305
+ verification_started_at: vtask[0]?.created_at ?? null,
306
+ last_statements: priorWords.map((r) => r.proposition),
307
+ trace_refs: traceRows.flatMap((r) => (Array.isArray(r.evidence_refs) ? r.evidence_refs : [])),
308
+ your_options: REJECTION_FORK,
309
+ };
192
310
  } else {
193
311
  await client.query(
194
312
  `SELECT cell.claim_work($1, $2, $3, NULL, NULL, $4, $5, 'exclusive',
@@ -197,7 +315,9 @@ export function createOatheTools({ client, identity, workspace, executionActor,
197
315
  }
198
316
  // Verifier assignment happens AT CLAIM (founder direction 2026-08-25): the engine that
199
317
  // will judge this work is named before the work starts, from config, on the record.
200
- const verifier = config?.get('verifier') ?? 'claude';
318
+ // No fallback literal: config names the verifier or the claim refuses — never a judge
319
+ // nobody chose.
320
+ const verifier = config.get('verifier');
201
321
  await client.query(
202
322
  `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
203
323
  execution_actor, claim_principal, statement_type, subject_ref, proposition,
@@ -207,46 +327,62 @@ export function createOatheTools({ client, identity, workspace, executionActor,
207
327
  `verifier:${verifier}`,
208
328
  `verification of this claim is assigned to the ${verifier} engine (bound at claim time)`,
209
329
  JSON.stringify([`config:verifier=${verifier}`])]);
330
+ const effective = ContractRef.parse(contractRef);
331
+ const note = existing.length === 0
332
+ ? (effective.isHomeless
333
+ ? "task minted HOMELESS from a synthetic workspace — the first real folder to claim it adopts it; plan_status is honestly 'unknown'"
334
+ : "task minted at claim — plan_status is honestly 'unknown'; a real cell pages you at verify_by")
335
+ : adopted
336
+ ? `existing homeless task claimed and ADOPTED onto this folder's board (${effective.workspace})`
337
+ : effective.isHomeless
338
+ ? 'existing homeless task claimed — still homeless (a synthetic surface never adopts)'
339
+ : 'existing task claimed';
210
340
  return {
211
341
  claimed: true,
212
342
  task_id,
343
+ ...(rejection !== null && { rejection }),
213
344
  work_claim_id: workClaimId,
214
345
  contract_ref: contractRef,
346
+ home: effective.workspace,
215
347
  lease: `${leaseHours} hours`,
216
348
  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',
349
+ note,
220
350
  };
221
351
  },
222
352
 
223
353
  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};%`];
354
+ // R-BOARD-SCOPE: scope is a per-surface fact. A synthetic workspace has no folder to
355
+ // lens through, so it serves the full board whatever the caller asked.
356
+ const full = all || synthetic;
357
+ // R-HOME-BOARD: a task's board is its HOME (the home rule, src/home.mjs, projected into
358
+ // SQL once). The scoped board = tasks homed here + homeless tasks (unclaimed or minted
359
+ // from a synthetic surface — visible everywhere so a real folder can adopt them).
360
+ const filter = full ? '' : 'AND (latest.home = $2 OR latest.home IS NULL)';
361
+ const params = full ? [orgId] : [orgId, workspace];
228
362
  // ONE row per task: the latest claim in view wins (a task reclaimed after a yield is one
229
363
  // task, not a history lesson — statements carry the history).
230
364
  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 (
365
+ `SELECT task_id, objective, origin, state, principal_id, contract_ref, home, settled_at,
366
+ lease_until, last_progress, last_progress_at, last_word_at, trace_path, trace_session_id, rejected_after FROM (
233
367
  SELECT DISTINCT ON (t.task_id)
234
368
  t.task_id, t.objective, t.created_at, t.origin, w.state, w.principal_id, w.contract_ref,
369
+ EXISTS (SELECT 1 FROM cell.verification v
370
+ WHERE v.org_id = t.org_id AND v.task_id = t.task_id
371
+ AND v.result = 'rejected' AND v.recorded_at > w.claimed_at) AS rejected_after,
372
+ ${HomeBoard.homeSql('t')} AS home,
235
373
  w.settled_at,
236
- to_char(w.ownership_valid_until, 'YYYY-MM-DD HH24:MI') AS lease_until,
374
+ to_char(w.ownership_valid_until AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI\"Z\"') AS lease_until,
237
375
  p.proposition AS last_progress,
238
- to_char(p.asserted_at, 'YYYY-MM-DD HH24:MI') AS last_progress_at
376
+ to_char(p.asserted_at, 'YYYY-MM-DD HH24:MI') AS last_progress_at,
377
+ to_char(coalesce(p.asserted_at, w.claimed_at) AT TIME ZONE 'UTC',
378
+ 'YYYY-MM-DD"T"HH24:MI"Z"') AS last_word_at,
379
+ tr.trace_path, tr.trace_session_id
239
380
  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}
381
+ LEFT JOIN LATERAL (${latestProgressSql({ task: 't', claim: 'w' })}) p ON true
382
+ LEFT JOIN LATERAL (${latestTracePathSql({ task: 't' })}) tr ON true
383
+ WHERE t.org_id = $1
248
384
  ORDER BY t.task_id, w.claimed_at DESC NULLS LAST
249
- ) latest ORDER BY created_at DESC`,
385
+ ) latest WHERE true ${filter} ORDER BY created_at DESC`,
250
386
  params);
251
387
  // ONE classification, consumed by every render: active-yours / active-theirs /
252
388
  // asserted-awaiting-verdict / open. Asserted is NOT open — it awaits verification.
@@ -254,11 +390,16 @@ export function createOatheTools({ client, identity, workspace, executionActor,
254
390
  for (const row of rows) {
255
391
  if (row.settled_at) continue; // settled: the obligation is CLOSED — off the board
256
392
  if (row.state === 'active') sections[row.principal_id === principalId ? 'mine' : 'held'].push(row);
393
+ // The discriminator is a REJECTION AFTER the latest claim: with one, the task is back
394
+ // on the board (R8); without one, origin='reopened' is stale history and the truth is
395
+ // asserted-awaiting-verification (a no-verdict engine failure must not read as
396
+ // reopened — live, 2026-08-30).
397
+ else if (row.state === 'completion_asserted' && !row.rejected_after) sections.asserted.push(row);
257
398
  else if (row.origin === 'reopened') sections.open.push({ ...row, state: 'reopened' }); // R8: back on the board
258
399
  else if (row.state === 'completion_asserted') sections.asserted.push(row);
259
400
  else sections.open.push(row);
260
401
  }
261
- return { workspace: all ? null : workspace, board: rows, sections };
402
+ return { workspace: full ? null : workspace, board: rows, sections };
262
403
  },
263
404
 
264
405
  async oathe_statement({ task_id, proposition, evidence_ref }) {
@@ -288,35 +429,111 @@ export function createOatheTools({ client, identity, workspace, executionActor,
288
429
  };
289
430
  },
290
431
 
432
+ async oathe_amend({ task_id, objective, why }) {
433
+ // R-AMEND: "Oathe does not prevent people from changing their minds. It prevents them
434
+ // from pretending the old obligation was completed." Open-claim only, seat-signed,
435
+ // never the judge; the trail is the record and the version derives from it. The claim
436
+ // row is locked FIRST — the amend-vs-done race is decided by the lock, not by luck.
437
+ if (!objective || !String(objective).trim()) {
438
+ throw new OatheToolError('OATHE_OBJECTIVE_REQUIRED', 'an amendment states the NEW definition of done', { task_id });
439
+ }
440
+ if (!why || !String(why).trim()) {
441
+ throw new OatheToolError('OATHE_AMEND_WHY_REQUIRED', 'an amendment records WHY the definition moved', { task_id });
442
+ }
443
+ if (isVerificationTask(task_id)) {
444
+ throw new OatheToolError('OATHE_AMEND_VERIFY_TASK',
445
+ `'${task_id}' is a verification task — its objective is generated (src/plans.mjs), never amended`, { task_id });
446
+ }
447
+ const { rows: authority } = await client.query(
448
+ 'SELECT seats FROM cell.acceptance_authority WHERE org_id = $1', [orgId]);
449
+ if (authority.length === 0) {
450
+ throw new OatheToolError('OATHE_AMEND_UNAUTHORIZED',
451
+ `no acceptance authority is registered for org '${orgId}' — an absent row is not lawful; run oathe init`, { task_id });
452
+ }
453
+ if (!authority[0].seats.includes(principalId)) {
454
+ throw new OatheToolError('OATHE_AMEND_UNAUTHORIZED',
455
+ `'${principalId}' is not in the seats roster [${authority[0].seats.join(', ')}] — an amendment is signed by the acceptance seat`, { task_id });
456
+ }
457
+ if (principalId === (config?.get('verifierPrincipal') ?? 'oathe-verifier')) {
458
+ throw new OatheToolError('OATHE_AMEND_UNAUTHORIZED',
459
+ `'${principalId}' is the verifier — the judge must not move the bar it judges`, { task_id });
460
+ }
461
+ return inTransaction(client, async (tx) => {
462
+ const { rows: locked } = await tx.query(
463
+ `SELECT work_claim_id FROM cell.work_claim
464
+ WHERE org_id = $1 AND task_id = $2 AND state = 'active' AND settled_at IS NULL
465
+ ORDER BY claimed_at DESC LIMIT 1 FOR UPDATE`, [orgId, task_id]);
466
+ if (locked.length === 0) {
467
+ throw new OatheToolError('OATHE_AMEND_AFTER_DONE',
468
+ `'${task_id}' has no ACTIVE claim — the definition of done is amendable only while the work is held `
469
+ + '(after done it is frozen at assertion; unclaimed work has nobody to renegotiate with — claim it first)', { task_id });
470
+ }
471
+ const { rows: taskRows } = await tx.query(
472
+ 'SELECT objective FROM cell.task WHERE org_id = $1 AND task_id = $2', [orgId, task_id]);
473
+ const { rows: countRows } = await tx.query(
474
+ `SELECT count(*)::int AS n FROM cell.agent_statement
475
+ WHERE org_id = $1 AND task_id = $2 AND subject_ref = $3`, [orgId, task_id, amendSubjectRef(task_id)]);
476
+ const version = countRows[0].n + 2; // v1 is the mint; v2 = the first amendment — derived, never stamped
477
+ await tx.query(
478
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
479
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
480
+ evidence_refs, epistemic_status, asserted_at)
481
+ VALUES ($1, $2, $3, $4, $5, $6, 'observation', $7, $8, '[]'::jsonb, 'observed', now())`,
482
+ [crypto.randomUUID(), orgId, task_id, locked[0].work_claim_id, actor, principalId,
483
+ amendSubjectRef(task_id),
484
+ `objective amended to v${version} by ${principalId} — ${why}\nOLD: ${taskRows[0].objective}\nNEW: ${objective}`]);
485
+ await tx.query(
486
+ 'UPDATE cell.task SET objective = $3 WHERE org_id = $1 AND task_id = $2', [orgId, task_id, objective]);
487
+ return {
488
+ amended: true,
489
+ task_id,
490
+ version,
491
+ note: `the definition of done moved to v${version}; the original definition stays on record in the amendment trail — verification judges the version in force at assertion and SEES the trail`,
492
+ };
493
+ });
494
+ },
495
+
291
496
  async oathe_done({ task_id, proposition, evidence_ref }) {
497
+ // ONE transaction, claim row locked FIRST (the same discipline as oathe_amend): the
498
+ // amend-vs-done race is decided by the lock, "the version in force at assertion" is
499
+ // exact, and the old crash hole (statement without terminal) is closed.
292
500
  const workClaimId = await activeClaim(task_id);
501
+ const statementId = crypto.randomUUID();
502
+ await inTransaction(client, async (tx) => {
503
+ const { rows: lockRows } = await tx.query(
504
+ "SELECT work_claim_id FROM cell.work_claim WHERE work_claim_id = $1 AND state = 'active' FOR UPDATE",
505
+ [workClaimId]);
506
+ if (lockRows.length === 0) {
507
+ throw new OatheToolError('OATHE_NO_ACTIVE_CLAIM',
508
+ `the claim on '${task_id}' left the active state while this done was in flight — read the board`, { task_id });
509
+ }
293
510
 
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
- }
511
+ // 1. G2-b: work may not finish until a plan exists. If the plan is still honestly
512
+ // unknown, the POLICY binder supplies the standard plan — via the substrate's own
513
+ // amend verb (an explicit CONTRACT_CHANGED event), which FC161 permits only while
514
+ // the claim is ACTIVE, i.e. exactly now, before the completion terminal.
515
+ const { rows: taskRows } = await tx.query(
516
+ 'SELECT verification_plan AS plan FROM cell.task WHERE org_id = $1 AND task_id = $2',
517
+ [orgId, task_id]);
518
+ if (taskRows[0].plan?.plan_status !== 'declared') {
519
+ await tx.query(
520
+ 'SELECT cell.amend_verification_contract($1, $2, $3::jsonb, now(), $4::uuid, $5)',
521
+ [orgId, task_id, JSON.stringify(standardPlan()), crypto.randomUUID(),
522
+ 'oathe policy-standard plan bound at completion (G2-b policy binder)']);
523
+ }
307
524
 
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()]);
525
+ // 2. The completion statement + the substrate's terminal (as before).
526
+ await tx.query(
527
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
528
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
529
+ evidence_refs, epistemic_status, asserted_at)
530
+ VALUES ($1, $2, $3, $4, $5, $6, 'completion', $7, $8, $9::jsonb, 'observed', now())`,
531
+ [statementId, orgId, task_id, workClaimId, actor, principalId,
532
+ `task:${task_id}`, proposition, JSON.stringify([evidence_ref ?? 'note:session'])]);
533
+ await tx.query(
534
+ 'SELECT cell.assert_claim_completion($1::uuid, $2::uuid)',
535
+ [statementId, crypto.randomUUID()]);
536
+ });
320
537
 
321
538
  // 3. Verification is ordinary work: mint the verification task, open on the board,
322
539
  // carrying the engine assigned at claim time. A verification task does not mint a
@@ -329,7 +546,7 @@ export function createOatheTools({ client, identity, workspace, executionActor,
329
546
  ORDER BY asserted_at DESC LIMIT 1`,
330
547
  [orgId, workClaimId]);
331
548
  const engine = engineRows[0]?.subject_ref.slice('verifier:'.length)
332
- ?? config?.get('verifier') ?? 'claude';
549
+ ?? config.get('verifier');
333
550
  verificationTask = verificationTaskId(task_id);
334
551
  await client.query(
335
552
  `INSERT INTO cell.task (org_id, task_id, department, objective, origin, verification_plan,
@@ -379,13 +596,94 @@ export function createOatheTools({ client, identity, workspace, executionActor,
379
596
  if (!successor) {
380
597
  throw new OatheToolError('OATHE_PICKUP_UNAVAILABLE',
381
598
  '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).'
383
- + ' Continue the task directly instead: its objective and recorded progress are on the board (oathe_board), so inspect the workspace, keep working, record progress with oathe_statement, and assert completion with oathe_done — the claim is already yours. Pickup '
384
- + 'cannot pretend', { task_id });
599
+ + 'this session (a preview limitation of sessions without the runtime seam). Claim the '
600
+ + 'task instead (oathe_claim): a reclaim of rejected work returns the recovery bundle — '
601
+ + 'the rejection reason, the prior interval\'s statements, and its trace refs — and the '
602
+ + 'board (oathe_board) carries the objective and progress; pickup cannot pretend',
603
+ { task_id });
385
604
  }
386
- return successor({ task_id, work_claim_id: latest.work_claim_id });
605
+ const frame = await successor({ task_id, work_claim_id: latest.work_claim_id });
606
+ // R-QUIET: the restored-state banner rides the pickup — the one moment it is news.
607
+ return { ...frame, receipt: restoredReceipt(task_id) };
387
608
  },
388
609
  };
610
+
611
+ // Attention rides EVERY response, activation or not: the act succeeded — a failing
612
+ // attention read is reported beside it (attention_error), never converted into a tool error.
613
+ const withAttention = Object.fromEntries(Object.entries(toolMap).map(([name, fn]) => [name, async (args) => {
614
+ const out = await fn(args);
615
+ try {
616
+ const lines = await attentionLines();
617
+ if (lines.length > 0) out.attention = lines;
618
+ } catch (e) {
619
+ out.attention_error = `the attention read failed: ${String(e?.message ?? e).slice(0, 160)}`;
620
+ }
621
+ return out;
622
+ }]));
623
+ toolMap = withAttention;
624
+
625
+ if (!activation) return toolMap;
626
+ if (!speaker) {
627
+ throw new OatheToolError('OATHE_SPEAKER_REQUIRED',
628
+ 'a serving tool surface must know who is speaking — pass speaker: resolveSpeaker(...) '
629
+ + '(src/speaker.mjs); the SPEAKER primitive is required, never assumed');
630
+ }
631
+ // Registration rides every SUCCESSFUL call; claim, the write-intent act, activates and
632
+ // discloses. The seam receives the bare tool name — each surface (mcp:, cli:) labels its
633
+ // own source. A failing registry is a typed error, not a silent skip — fail loud.
634
+ // Every successful WRITE carries its speaker: the durable trace-link lands WITH the act
635
+ // (linkTrace — a failure throws typed; retries are idempotent), the wire nudges the glass,
636
+ // and the result discloses who spoke. Reads stamp and emit nothing.
637
+ return Object.fromEntries(Object.entries(toolMap).map(([name, fn]) => [name, async (args) => {
638
+ const out = await fn(args);
639
+ if (WIRE_KINDS[name]) {
640
+ if (speaker.session && args?.task_id && LINKABLE.has(name)) {
641
+ await linkTrace({ client, identity, taskId: args.task_id, session: speaker.session });
642
+ }
643
+ // The trust boundary is the blocking boundary (ruling 2026-08-31): on your own
644
+ // machine, done OWES its verdict and waits for it — the seam dispatches the detached
645
+ // engine and awaits the substrate's answer (a remote substrate flips the seam to
646
+ // dispatch-and-return when the cloud lands; never a knob here). The assertion STANDS
647
+ // whatever happens — a seam failure is disclosed, and the pager pages the miss.
648
+ if (name === 'oathe_done' && verifier) {
649
+ try {
650
+ const outcome = await verifier({ taskId: args.task_id });
651
+ out.verification = outcome?.verdict === 'rejected'
652
+ ? { ...outcome, your_options: REJECTION_FORK }
653
+ : outcome;
654
+ } catch (e) {
655
+ out.verification = { failed: true, reason: `${e?.code ? `[${e.code}] ` : ''}${String(e?.message ?? e).slice(0, 200)}` };
656
+ }
657
+ }
658
+ out.spoken_from = {
659
+ surface: speaker.surface,
660
+ app: speaker.app?.bundle ?? null,
661
+ session: speaker.session?.sessionId ?? null,
662
+ };
663
+ await emit(client, { kind: WIRE_KINDS[name], task_id: args?.task_id, via: speaker.surface, app: speaker.app });
664
+ }
665
+ if (name === 'oathe_claim') out.activation = await activation.activate(name);
666
+ else await activation.register(name);
667
+ return out;
668
+ }]));
669
+ }
670
+
671
+ /**
672
+ * ONE transaction idiom for the write verbs: the real substrate's withTransaction holds
673
+ * the interleave gate for the whole span; a bare {query} client (test fakes, spies) gets
674
+ * the inline BEGIN..COMMIT with identical semantics on its single connection.
675
+ */
676
+ async function inTransaction(client, fn) {
677
+ if (typeof client.withTransaction === 'function') return client.withTransaction(fn);
678
+ await client.query('BEGIN');
679
+ try {
680
+ const out = await fn({ query: (sql, params) => client.query(sql, params) });
681
+ await client.query('COMMIT');
682
+ return out;
683
+ } catch (e) {
684
+ await client.query('ROLLBACK').catch(() => {});
685
+ throw e;
686
+ }
389
687
  }
390
688
 
391
689
  const okText = (obj) => ({ content: [{ type: 'text', text: JSON.stringify(obj) }], isError: false });
@@ -412,19 +710,18 @@ export async function handleToolCall(params, tools) {
412
710
  }
413
711
 
414
712
  /**
415
- * The opt-in gate for the served tools map. A session the oathe launcher started passes
416
- * through untouched; anything else gets the same tool NAMES whose every call is the typed
417
- * OATHE_NOT_LAUNCHED refusal — loud to the model (a called tool must answer), inert to the
418
- * substrate (an unlaunched session never touches the board).
713
+ * Lazily-served tools: the same tool NAMES, each call routed through `loader` so the real
714
+ * context (workspace resolution, config, substrate) is built on FIRST USE, once, never at
715
+ * process startup. A loader refusal (e.g. OATHE_WORKSPACE_UNRESOLVED) surfaces per call as
716
+ * that call's typed error — the server itself never dies for it. The old launch gate lived
717
+ * here; resolution replaced it (the marker env var remains custody-only).
419
718
  */
420
- export function withLaunchGate(tools, env = process.env, { launched = false } = {}) {
421
- if (launchedHarness(env) || launched) return tools;
422
- const refuse = async () => {
423
- throw new OatheToolError('OATHE_NOT_LAUNCHED',
424
- 'this session was not launched through oathe, so the board is not bound to it — start the '
425
- + 'session with `oathe claude` or `oathe codex` to opt in');
426
- };
427
- return Object.fromEntries(Object.keys(tools).map((name) => [name, refuse]));
719
+ export function lazyTools(loader, { names = makeToolDefs().map((t) => t.name) } = {}) {
720
+ // No memo here: deduplication (and invalidation) is the LOADER's job — one cache, one owner.
721
+ return Object.fromEntries(names.map((name) => [name, async (args) => {
722
+ const context = await loader();
723
+ return context.tools[name](args);
724
+ }]));
428
725
  }
429
726
 
430
727
  /** The pure JSON-RPC dispatcher — a response object, or null for a notification. */
@@ -457,73 +754,15 @@ export async function dispatch(msg, { tools }) {
457
754
  return { jsonrpc: '2.0', id, result };
458
755
  }
459
756
 
460
- /** Start the ndjson JSON-RPC loop over stdio. Only runs when launched as the entrypoint. */
757
+ /**
758
+ * Start the server over stdio. The transport, server-initiated requests (roots/list), and the
759
+ * LAZY per-connection tool context live in McpConnection (./connection.mjs) — nothing beyond
760
+ * the transport is built at startup, so a poisoned environment surfaces per call, typed,
761
+ * never as a startup crash.
762
+ */
461
763
  export async function main(env = process.env) {
462
- const { Substrate } = await import('../substrate.mjs');
463
- const { buildPaths } = await import('../paths.mjs');
464
- const { workspaceRef } = await import('../workspace.mjs');
465
- let paths = buildPaths(env);
466
- // Codex builds MCP child environments from its own config, so the launcher's env block
467
- // never crosses that boundary. A live session marker for this cwd's workspace is the
468
- // harness-agnostic transport: adopt its recorded wiring (identity included) and re-derive.
469
- let markerLaunched = false;
470
- if (!env.OATHE_LAUNCHED_HARNESS) {
471
- const marker = liveSessionMarker({
472
- oatheHome: paths.oatheHome, workspace: workspaceRef(process.cwd()) });
473
- if (marker) {
474
- env = { ...env, ...marker.wiring, OATHE_LAUNCHED_HARNESS: marker.harness };
475
- paths = buildPaths(env);
476
- markerLaunched = true;
477
- }
478
- }
479
- const { OatheConfig } = await import('../config.mjs');
480
- const config = new OatheConfig({ env, cwd: env.OATHE_WORKSPACE_DIR || process.cwd() });
481
- const substrate = new Substrate({ database: config.get('db'), paths, env, config });
482
- const identity = {
483
- orgId: config.get('org'),
484
- principalId: config.get('principal') || env.USER || 'operator',
485
- department: config.get('department'),
486
- };
487
- // The successor is built LAZILY on the first pickup: a session that never picks up never pays
488
- // for the runtime wiring, and a wiring failure surfaces as that call's typed error.
489
- let successorPromise = null;
490
- let verifierInstance = null;
491
- const tools = createOatheTools({
492
- client: substrate,
493
- identity,
494
- config,
495
- workspace: workspaceRef(env.OATHE_WORKSPACE_DIR || process.cwd()),
496
- verifier: async (o) => {
497
- if (!verifierInstance) {
498
- const { Verifier } = await import('../verifier.mjs');
499
- verifierInstance = new Verifier({
500
- substrate, paths, config,
501
- workspace: workspaceRef(env.OATHE_WORKSPACE_DIR || process.cwd()),
502
- operatorPrincipal: identity.principalId,
503
- });
504
- }
505
- return verifierInstance.verify(o);
506
- },
507
- successor: async (o) => {
508
- if (!successorPromise) {
509
- successorPromise = import('../runtime/provider.mjs')
510
- .then(({ resolveRuntimeProvider }) => resolveRuntimeProvider({ config, paths })
511
- .successor({ substrate, identity, paths }));
512
- successorPromise.catch(() => { successorPromise = null; }); // a failed build must not poison retries
513
- }
514
- return (await successorPromise).pickup(o);
515
- },
516
- });
517
- const served = withLaunchGate(tools, env, { launched: markerLaunched });
518
- const rl = readline.createInterface({ input: process.stdin });
519
- rl.on('line', async (line) => {
520
- const s = line.trim();
521
- if (!s) return;
522
- let msg;
523
- try { msg = JSON.parse(s); } catch { return; }
524
- const out = await dispatch(msg, { tools: served });
525
- if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
526
- });
764
+ const { McpConnection } = await import('./connection.mjs');
765
+ new McpConnection({ env }).start();
527
766
  }
528
767
 
529
768
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {