@oathe/oathe 0.3.2 → 0.4.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 (56) hide show
  1. package/README.md +42 -12
  2. package/assets/oathe-hero.png +0 -0
  3. package/bin/node-floor.mjs +16 -0
  4. package/bin/oathe.mjs +78 -134
  5. package/docs/PRIVACY.md +7 -6
  6. package/notch/Oathe Notch.app/Contents/Info.plist +1 -1
  7. package/notch/Oathe Notch.app/Contents/MacOS/OatheNotch +0 -0
  8. package/notch/README.md +33 -18
  9. package/package.json +9 -5
  10. package/plugin/.claude-plugin/plugin.json +2 -2
  11. package/plugin/.cursor-plugin/plugin.json +2 -2
  12. package/plugin/commands/verify.md +6 -5
  13. package/plugin/hooks/heartbeat.mjs +14 -5
  14. package/plugin/hooks/hooks.json +1 -1
  15. package/plugin/hooks/lib.mjs +7 -5
  16. package/plugin/hooks/render-board.mjs +3 -3
  17. package/plugin/skills/oathe-work/SKILL.md +4 -1
  18. package/src/activation.mjs +3 -0
  19. package/src/atif.mjs +182 -348
  20. package/src/board-render.mjs +46 -42
  21. package/src/breach-digest.mjs +183 -0
  22. package/src/config.mjs +15 -3
  23. package/src/context.mjs +1 -1
  24. package/src/doctor.mjs +30 -8
  25. package/src/evidence.mjs +153 -0
  26. package/src/harnesses/catalog.mjs +12 -1
  27. package/src/harnesses/claude-roster.mjs +49 -0
  28. package/src/harnesses/claude-transcript.mjs +174 -0
  29. package/src/harnesses/claude.mjs +35 -2
  30. package/src/harnesses/codex-rollout.mjs +610 -0
  31. package/src/harnesses/codex-roster.mjs +88 -0
  32. package/src/harnesses/codex.mjs +72 -2
  33. package/src/harnesses/cursor.mjs +10 -8
  34. package/src/harnesses/fidelity.mjs +123 -0
  35. package/src/init.mjs +5 -1
  36. package/src/launch-env.mjs +5 -5
  37. package/src/launch.mjs +5 -6
  38. package/src/manifest.mjs +35 -0
  39. package/src/mcp/connection.mjs +9 -7
  40. package/src/mcp/oathe-tools.mjs +135 -75
  41. package/src/node-floor.mjs +44 -0
  42. package/src/notch-frame.mjs +152 -0
  43. package/src/oathe-annotator.mjs +113 -0
  44. package/src/pager.mjs +75 -37
  45. package/src/runtime/provider.mjs +2 -2
  46. package/src/session-host.mjs +1 -1
  47. package/src/sessions.mjs +8 -1
  48. package/src/speaker.mjs +54 -26
  49. package/src/statements.mjs +120 -2
  50. package/src/substrate.mjs +3 -3
  51. package/src/successor.mjs +2 -3
  52. package/src/trace-census.mjs +96 -0
  53. package/src/traces.mjs +98 -6
  54. package/src/uninstall.mjs +4 -1
  55. package/src/verifier.mjs +37 -19
  56. package/assets/oathe-hero.svg +0 -92
@@ -16,7 +16,12 @@ import crypto from 'node:crypto';
16
16
  import { standardPlan, verificationTaskId, verificationObjective, isVerificationTask } from '../plans.mjs';
17
17
  import { verifierCapable } from '../harnesses/catalog.mjs';
18
18
  import { ContractRef, HomeBoard } from '../home.mjs';
19
- import { amendSubjectRef, isEngineFailureSql, isTraceSubjectSql, latestVerdictSql, latestProgressSql, latestTracePathSql, linkTrace } from '../statements.mjs';
19
+ import {
20
+ amendSubjectRef, isTraceSubjectSql, latestVerdictSql, latestProgressSql, latestTracePathSql, linkTrace,
21
+ spawnParentSql, spawnParentFor, linkSpawn,
22
+ } from '../statements.mjs';
23
+ import { Pager } from '../pager.mjs';
24
+ import { KINDS, clipDetail, pullPointer } from '../breach-digest.mjs';
20
25
  import { WIRE_KINDS, LINKABLE, emit, restoredReceipt } from '../wire.mjs';
21
26
 
22
27
  export const PROTOCOL_VERSION = '2025-06-18';
@@ -46,12 +51,17 @@ export function makeToolDefs() {
46
51
  description:
47
52
  'Claim a task on the cell board (minting it if new — with plan_status honestly "unknown", '
48
53
  + 'never a fabricated plan). A claim is a speech act: it takes responsibility, it does not '
49
- + 'do the work. A second claimant is refused by the substrate. Args: {task_id, objective}.',
54
+ + 'do the work. A second claimant is refused by the substrate. Args: {task_id, objective, parent?}.',
50
55
  inputSchema: {
51
56
  type: 'object',
52
57
  properties: {
53
58
  task_id: { type: 'string', description: 'the task to claim' },
54
59
  objective: { type: 'string', description: 'what done means, in one line (required to mint a new task)' },
60
+ parent: {
61
+ type: ['string', 'null'],
62
+ description: 'omit: recorded as spawned under the claim this session already holds (its root); '
63
+ + 'an id: that claim, which you must hold; null: standalone work',
64
+ },
55
65
  },
56
66
  required: ['task_id'],
57
67
  },
@@ -175,54 +185,33 @@ export function createOatheTools({
175
185
  // wire and stamp attribution) refuses construction without it. Internal read-only
176
186
  // compositions (board render, the verifier's own seat) build no wrapper and carry none.
177
187
  speaker = null,
188
+ // ATTENTION (UX rule 19) is served on every tool response; a read-only composition (the
189
+ // board renderer, which carries its own digest) passes attention:false and reads no breach.
190
+ attention = true,
178
191
  }) {
179
192
  const { orgId, principalId, department } = identity;
180
193
  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.
194
+ // The breaches are the pager's conditions read per call — stateless: a line repeats while
195
+ // its condition holds and vanishes when it clears — under the ONE digest (src/breach-
196
+ // digest.mjs): scoped to this board (a synthetic surface sees the machine), grouped,
197
+ // ordered, budgeted. Attention words the fix bucket for the model's response channel —
198
+ // rejected and verify-failed work, the one thing a session can act on now — so a background
199
+ // rejection reaches it at its next act; the SessionStart hook covers new sessions.
200
+ if (attention && !config) {
201
+ throw new OatheToolError('OATHE_ATTENTION_NEEDS_CONFIG',
202
+ 'attention reads the pager, whose thresholds come from config — pass config, or attention:false for a read-only composition');
203
+ }
204
+ const pager = attention ? new Pager({ client, identity, config }) : null;
205
+ const breachesFor = async (machine) => (await pager.digest()).scoped(machine ? null : workspace);
185
206
  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];
207
+ const fix = (await breachesFor(synthetic)).filter((row) => KINDS[row.kind].bucket === 'fix');
208
+ const lines = fix.rows.map((row) => (row.group
209
+ ? `spawned under '${row.task_id}': ${row.kind_word} — the children and their verdicts are in `
210
+ + 'oathe_board.breaches; reclaim each (oathe_claim <child>), retry a failed verify with /oathe:verify <child>'
211
+ : `${row.kind_word}: '${row.task_id}' — ${clipDetail(row.detail)}`
212
+ + (row.kind === 'reopened' ? ' — reclaim it (oathe_claim) for the bundle' : '')));
213
+ const more = pullPointer('attention', fix.more);
214
+ return more ? [...lines, more] : lines;
226
215
  };
227
216
  const leaseHours = config?.get('leaseHours') ?? 4;
228
217
  const verifyByHours = config?.get('verifyByHours') ?? 24;
@@ -363,9 +352,11 @@ export function createOatheTools({
363
352
  // task, not a history lesson — statements carry the history).
364
353
  const { rows } = await client.query(
365
354
  `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 (
355
+ lease_until, last_progress, last_progress_at, last_word_at, trace_path, trace_session_id, rejected_after,
356
+ parent, parent_objective FROM (
367
357
  SELECT DISTINCT ON (t.task_id)
368
358
  t.task_id, t.objective, t.created_at, t.origin, w.state, w.principal_id, w.contract_ref,
359
+ sp.parent_task_id AS parent, sp.parent_objective,
369
360
  EXISTS (SELECT 1 FROM cell.verification v
370
361
  WHERE v.org_id = t.org_id AND v.task_id = t.task_id
371
362
  AND v.result = 'rejected' AND v.recorded_at > w.claimed_at) AS rejected_after,
@@ -380,26 +371,35 @@ export function createOatheTools({
380
371
  FROM cell.task t LEFT JOIN cell.work_claim w USING (org_id, task_id)
381
372
  LEFT JOIN LATERAL (${latestProgressSql({ task: 't', claim: 'w' })}) p ON true
382
373
  LEFT JOIN LATERAL (${latestTracePathSql({ task: 't' })}) tr ON true
374
+ LEFT JOIN LATERAL (${spawnParentSql({ task: 't' })}) sp ON true
383
375
  WHERE t.org_id = $1
384
376
  ORDER BY t.task_id, w.claimed_at DESC NULLS LAST
385
377
  ) latest WHERE true ${filter} ORDER BY created_at DESC`,
386
378
  params);
379
+ // Lineage (UX rule 21): a child never surfaces top-level while its parent is in view —
380
+ // it is counted on the parent's row. A child whose parent is off the board (settled,
381
+ // or homed elsewhere) stands on its own.
382
+ const inView = new Set(rows.filter((r) => !r.settled_at).map((r) => r.task_id));
383
+ const childrenOf = new Map();
384
+ for (const row of rows) {
385
+ if (row.parent && inView.has(row.parent)) childrenOf.set(row.parent, [...(childrenOf.get(row.parent) ?? []), row]);
386
+ }
387
387
  // ONE classification, consumed by every render: active-yours / active-theirs /
388
388
  // asserted-awaiting-verdict / open. Asserted is NOT open — it awaits verification.
389
389
  const sections = { mine: [], open: [], asserted: [], held: [] };
390
390
  for (const row of rows) {
391
391
  if (row.settled_at) continue; // settled: the obligation is CLOSED — off the board
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);
398
- else if (row.origin === 'reopened') sections.open.push({ ...row, state: 'reopened' }); // R8: back on the board
399
- else if (row.state === 'completion_asserted') sections.asserted.push(row);
400
- else sections.open.push(row);
392
+ if (row.parent && inView.has(row.parent)) continue;
393
+ const [bucket, entry] = classify(row, principalId);
394
+ const kids = childrenOf.get(row.task_id);
395
+ sections[bucket].push(kids ? { ...entry, children: childrenSummary(kids, principalId) } : entry);
401
396
  }
402
- return { workspace: full ? null : workspace, board: rows, sections };
397
+ // The pull (UX rule 19): every breach on this board — every kind, grouped, ordered,
398
+ // uncapped — where a `+N more` sends the model.
399
+ return {
400
+ workspace: full ? null : workspace, board: rows, sections,
401
+ ...(pager ? { breaches: (await breachesFor(full)).groups } : {}),
402
+ };
403
403
  },
404
404
 
405
405
  async oathe_statement({ task_id, proposition, evidence_ref }) {
@@ -419,6 +419,14 @@ export function createOatheTools({
419
419
  },
420
420
 
421
421
  async oathe_yield({ task_id, note }) {
422
+ // The schema requires `note`, but the server enforces no schema (tools/call hands the
423
+ // arguments straight here): a client that ignores `required` must still hear WHY in the
424
+ // tool's own words — not FC141's sentence about yield bases from plpgsql (2026-09-03).
425
+ if (typeof note !== 'string' || note.trim() === '') {
426
+ throw new OatheToolError('OATHE_YIELD_NOTE_REQUIRED',
427
+ `yield refused — '${task_id}' cannot go back on the board without its cause: pass note `
428
+ + '(why you are stopping, for whoever picks it up)', { task_id });
429
+ }
422
430
  const workClaimId = await activeClaim(task_id);
423
431
  await client.query(
424
432
  'SELECT cell.oathe_yield_operator($1::uuid, $2, now(), $3::uuid)',
@@ -496,7 +504,7 @@ export function createOatheTools({
496
504
  async oathe_done({ task_id, proposition, evidence_ref }) {
497
505
  // ONE transaction, claim row locked FIRST (the same discipline as oathe_amend): the
498
506
  // 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.
507
+ // exact, and a completion statement never lands without its terminal.
500
508
  const workClaimId = await activeClaim(task_id);
501
509
  const statementId = crypto.randomUUID();
502
510
  await inTransaction(client, async (tx) => {
@@ -610,17 +618,18 @@ export function createOatheTools({
610
618
 
611
619
  // Attention rides EVERY response, activation or not: the act succeeded — a failing
612
620
  // 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;
621
+ if (pager) {
622
+ toolMap = Object.fromEntries(Object.entries(toolMap).map(([name, fn]) => [name, async (args) => {
623
+ const out = await fn(args);
624
+ try {
625
+ const lines = await attentionLines();
626
+ if (lines.length > 0) out.attention = lines;
627
+ } catch (e) {
628
+ out.attention_error = `the attention read failed: ${String(e?.message ?? e).slice(0, 160)}`;
629
+ }
630
+ return out;
631
+ }]));
632
+ }
624
633
 
625
634
  if (!activation) return toolMap;
626
635
  if (!speaker) {
@@ -635,10 +644,25 @@ export function createOatheTools({
635
644
  // (linkTrace — a failure throws typed; retries are idempotent), the wire nudges the glass,
636
645
  // and the result discloses who spoke. Reads stamp and emit nothing.
637
646
  return Object.fromEntries(Object.entries(toolMap).map(([name, fn]) => [name, async (args) => {
647
+ // Lineage is decided BEFORE a claim lands (a refused parent leaves nothing behind) and
648
+ // recorded right after it, on the parent's claim — the `spawn:<child>` observation.
649
+ const spawn = name === 'oathe_claim'
650
+ ? await spawnParentFor({ client, identity, session: speaker.session, taskId: args.task_id, parent: args.parent })
651
+ : null;
638
652
  const out = await fn(args);
639
653
  if (WIRE_KINDS[name]) {
640
654
  if (speaker.session && args?.task_id && LINKABLE.has(name)) {
641
- await linkTrace({ client, identity, taskId: args.task_id, session: speaker.session });
655
+ const link = await linkTrace({ client, identity, taskId: args.task_id, session: speaker.session });
656
+ if (link.why) out.trace_link = link; // a link that waits is disclosed, never assumed
657
+ }
658
+ if (name === 'oathe_claim') {
659
+ if (spawn) {
660
+ await linkSpawn({
661
+ client, identity, parent: spawn.parent, childTaskId: args.task_id,
662
+ actor: speaker.session ? `session:${speaker.session.sessionId}` : actor,
663
+ });
664
+ }
665
+ out.lineage = spawn;
642
666
  }
643
667
  // The trust boundary is the blocking boundary (ruling 2026-08-31): on your own
644
668
  // machine, done OWES its verdict and waits for it — the seam dispatches the detached
@@ -668,6 +692,41 @@ export function createOatheTools({
668
692
  }]));
669
693
  }
670
694
 
695
+ /**
696
+ * The board's ONE classification of an unsettled row: [bucket, row]. The discriminator is a
697
+ * REJECTION AFTER the latest claim: with one, the task is back on the board (R8); without
698
+ * one, origin='reopened' is stale history and the truth is asserted-awaiting-verification (a
699
+ * no-verdict engine failure must not read as reopened — live, 2026-08-30).
700
+ */
701
+ function classify(row, principalId) {
702
+ if (row.state === 'active') return [row.principal_id === principalId ? 'mine' : 'held', row];
703
+ if (row.state === 'completion_asserted' && !row.rejected_after) return ['asserted', row];
704
+ if (row.origin === 'reopened') return ['open', { ...row, state: 'reopened' }]; // R8: back on the board
705
+ if (row.state === 'completion_asserted') return ['asserted', row];
706
+ return ['open', row];
707
+ }
708
+
709
+ /** A spawned child's one word on its parent's row, in the order the line speaks them. */
710
+ const CHILD_WORDS = ['active', 'asserted', 'reopened', 'open', 'settled'];
711
+ function childWord(row, principalId) {
712
+ if (row.settled_at) return 'settled';
713
+ const [bucket, entry] = classify(row, principalId);
714
+ if (bucket === 'mine' || bucket === 'held') return 'active';
715
+ if (bucket === 'asserted') return 'asserted';
716
+ return entry.state === 'reopened' ? 'reopened' : 'open';
717
+ }
718
+
719
+ /** `spawned 3 — 2 active · 1 settled`: the parent's counts line, zero counts omitted. */
720
+ function childrenSummary(kids, principalId) {
721
+ const by = {};
722
+ for (const kid of kids) {
723
+ const word = childWord(kid, principalId);
724
+ by[word] = (by[word] ?? 0) + 1;
725
+ }
726
+ const parts = CHILD_WORDS.filter((word) => by[word]).map((word) => `${by[word]} ${word}`);
727
+ return { n: kids.length, by, line: `spawned ${kids.length} — ${parts.join(' · ')}` };
728
+ }
729
+
671
730
  /**
672
731
  * ONE transaction idiom for the write verbs: the real substrate's withTransaction holds
673
732
  * the interleave gate for the whole span; a bare {query} client (test fakes, spies) gets
@@ -713,8 +772,8 @@ export async function handleToolCall(params, tools) {
713
772
  * Lazily-served tools: the same tool NAMES, each call routed through `loader` so the real
714
773
  * context (workspace resolution, config, substrate) is built on FIRST USE, once, never at
715
774
  * 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).
775
+ * that call's typed error — the server itself never dies for it. Resolution is the gate; the
776
+ * launched-harness env var is custody-only.
718
777
  */
719
778
  export function lazyTools(loader, { names = makeToolDefs().map((t) => t.name) } = {}) {
720
779
  // No memo here: deduplication (and invalidation) is the LOADER's job — one cache, one owner.
@@ -724,8 +783,9 @@ export function lazyTools(loader, { names = makeToolDefs().map((t) => t.name) }
724
783
  }]));
725
784
  }
726
785
 
727
- /** The pure JSON-RPC dispatcher — a response object, or null for a notification. */
728
- export async function dispatch(msg, { tools }) {
786
+ /** The pure JSON-RPC dispatcher — a response object, or null for a notification. `version`
787
+ * is the package version the server names at initialize (the connection reads it once). */
788
+ export async function dispatch(msg, { tools, version }) {
729
789
  const { id, method, params } = msg || {};
730
790
  const isNotification = id === undefined || id === null;
731
791
  if (method === 'notifications/initialized' || method === 'initialized') return null;
@@ -735,7 +795,7 @@ export async function dispatch(msg, { tools }) {
735
795
  return {
736
796
  protocolVersion: PROTOCOL_VERSION,
737
797
  capabilities: { tools: {} },
738
- serverInfo: { name: SERVER_NAME, version: '0.1.0' },
798
+ serverInfo: { name: SERVER_NAME, version },
739
799
  };
740
800
  case 'tools/list':
741
801
  return { tools: makeToolDefs() };
@@ -0,0 +1,44 @@
1
+ // R-NODE-FLOOR (2026-08-31): the engines.node floor, EXECUTED. npm treats `engines` as a
2
+ // warning — a below-floor node installs and runs, until the codex trace lane asks for
3
+ // node:sqlite (unflagged only from 22.13.0 / 23.4.0) and every verify on the machine stalls.
4
+ // The bin refuses first, reading the one declaration in package.json — a rule that is not
5
+ // executed is a rule that drifts.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ export class NodeFloorError extends Error {
11
+ constructor(code, message, details = {}) {
12
+ super(message);
13
+ this.code = code;
14
+ this.details = details;
15
+ }
16
+ }
17
+
18
+ /** The floor package.json declares, parsed or refused — never guessed. */
19
+ export function nodeFloor({ packageRoot }) {
20
+ const raw = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'))?.engines?.node;
21
+ const m = /^>=\s*(\d+)\.(\d+)\.(\d+)$/.exec(raw ?? '');
22
+ if (!m) {
23
+ throw new NodeFloorError('OATHE_ENGINES_UNREADABLE',
24
+ `engines.node '${raw}' is not a '>=x.y.z' floor — the runtime gate cannot read it`, { raw });
25
+ }
26
+ return { raw, parts: m.slice(1, 4).map(Number) };
27
+ }
28
+
29
+ /** The gate at the bin door: the running node meets the declared floor, or the run is refused. */
30
+ export function assertNodeFloor({ version = process.version, packageRoot }) {
31
+ const floor = nodeFloor({ packageRoot });
32
+ const v = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version)?.slice(1, 4).map(Number);
33
+ if (!v) {
34
+ throw new NodeFloorError('OATHE_ENGINES_UNREADABLE',
35
+ `node version '${version}' cannot be read against the floor`, { version });
36
+ }
37
+ if ((v[0] - floor.parts[0] || v[1] - floor.parts[1] || v[2] - floor.parts[2]) < 0) {
38
+ throw new NodeFloorError('ERROR_NODE_VERSION',
39
+ `node ${version} refused — oathe needs node ${floor.raw} (package.json engines.node): below it `
40
+ + 'node:sqlite is unavailable and the codex thread index cannot be read. Upgrade node '
41
+ + '(nvm: `nvm install 24 && nvm alias default 24`) and re-run.',
42
+ { version, floor: floor.raw });
43
+ }
44
+ }
@@ -0,0 +1,152 @@
1
+ // oathe — the notch frame: the glass's one truth, assembled from fetched facts. `oathe notch`
2
+ // fetches (the board, the pager's digest, the device session registry) and serves; this
3
+ // module decides what the glass shows and every word it shows (UX rule 20): the digest's
4
+ // rows with their kind words and act words, the count beyond the budget, work in motion
5
+ // with its resumption, the objective and the children line for the card. The glass reads
6
+ // no config and composes no sentence — tests/notch-frame.test.mjs holds a frame built here
7
+ // to Feed.swift's own decoder.
8
+ //
9
+ // MOTION (founder ruling, 2026-08-30): a row on the glass means a LIVE session — a claim
10
+ // whose last word is younger than notchMotionMinutes, or one the wire just heard (hear(),
11
+ // ephemeral by design). Idle-held work is `oathe ls`'s business.
12
+
13
+ import { launchable, ownerOfTracePath, surfaceForSession } from './harnesses/catalog.mjs';
14
+ import { pidAlive } from './sessions.mjs';
15
+ import { KINDS, CONTINUE_ACT } from './breach-digest.mjs';
16
+
17
+ /** The system terminal — an OS fact, the fallback when no session names its own. */
18
+ export const TERMINAL_FALLBACK = '/System/Applications/Utilities/Terminal.app';
19
+
20
+ const shellQuote = (s) => `'${String(s).replaceAll("'", "'\\''")}'`;
21
+ /** A kind whose one act is a judgment (never-judged, engine-failed) rather than a resumption. */
22
+ const judges = (kind) => KINDS[kind].act !== CONTINUE_ACT;
23
+
24
+ export class NotchFrame {
25
+ #heard = new Map(); // task → {at, via, app}: what the wire heard, ephemeral by design
26
+ #launchables = launchable();
27
+
28
+ /**
29
+ * @param {{registry: {rootOf: Function}, sessions: () => object, defaultAgent: string|null,
30
+ * motionWindowMs: number, operatorHome: string, now?: () => number}} o
31
+ * sessions — the device session registry, read per frame (its failure is the caller's
32
+ * fail-soft: an empty map costs the frame its session refs, never the frame);
33
+ * operatorHome — where a homeless judgment runs.
34
+ */
35
+ constructor({ registry, sessions, defaultAgent, motionWindowMs, operatorHome, now = () => Date.now() }) {
36
+ this.registry = registry;
37
+ this.sessions = sessions;
38
+ this.defaultAgent = this.#launchables.includes(defaultAgent) ? defaultAgent : null;
39
+ this.motionWindowMs = motionWindowMs;
40
+ this.operatorHome = operatorHome;
41
+ this.now = now;
42
+ }
43
+
44
+ /** The wire IS liveness: a task heard on the wire is in motion until the window passes. */
45
+ hear(taskId, { at, via, app }) {
46
+ this.#heard.set(taskId, { at, via, app });
47
+ }
48
+
49
+ moving(row) {
50
+ const since = this.now() - this.motionWindowMs;
51
+ return (this.#heard.get(row.task_id)?.at ?? 0) > since
52
+ || (row.last_word_at && Date.parse(row.last_word_at) > since);
53
+ }
54
+
55
+ /**
56
+ * Continue is a RESUMPTION, never a shrug (founder ruling 2026-08-30): activate the living
57
+ * app; else spawn the agent at the task's home in a terminal; else open the desktop app;
58
+ * else the clipboard is the act. The package decides — the glass executes.
59
+ */
60
+ resumeFor(base, ref) {
61
+ const word = CONTINUE_ACT;
62
+ if (ref?.alive && ref.app_pid !== null && ref.app_pid !== undefined) {
63
+ // The bundle rides along: macOS may deny a background app's activate (cooperative
64
+ // activation) — opening the bundle is the permission-free fallback that still switches.
65
+ return { kind: 'activate', app_pid: ref.app_pid, bundle: ref.bundle ?? null, word };
66
+ }
67
+ const surface = ref?.surface ?? base.surface;
68
+ const agent = this.#launchables.includes(surface) ? surface : this.defaultAgent;
69
+ if (agent && typeof base.home_path === 'string' && base.home_path.startsWith('/')) {
70
+ return {
71
+ kind: 'spawn-terminal',
72
+ command: `oathe ${agent} ${shellQuote(`continue ${base.task_id}`)}`,
73
+ cwd: base.home_path,
74
+ terminal_bundle: ref?.bundle ?? TERMINAL_FALLBACK,
75
+ word,
76
+ };
77
+ }
78
+ if (ref?.bundle) return { kind: 'open-app', bundle: ref.bundle, word };
79
+ return { kind: 'copy-only', word };
80
+ }
81
+
82
+ glassRow(r, sess) {
83
+ const row = (r.trace_session_id && sess[r.trace_session_id]) || null;
84
+ const heard = this.#heard.get(r.task_id);
85
+ // The durable registry row outranks the wire's ephemeral word; either way the ref
86
+ // carries surface + the focusable app, so a HOMELESS task heard from a living app
87
+ // (ChatGPT's embedded codex — no hooks, no registry row) still resolves to a switch.
88
+ const ref = row !== null ? {
89
+ surface: surfaceForSession({ ancestry: row.ancestry, app: row.app, transcriptPath: row.transcript_path }),
90
+ app_pid: row.app?.pid ?? null,
91
+ bundle: row.app?.bundle ?? null,
92
+ alive: pidAlive(row.pid),
93
+ } : (heard?.app ? {
94
+ surface: heard.via ?? null,
95
+ app_pid: heard.app.pid ?? null,
96
+ bundle: heard.app.bundle ?? null,
97
+ alive: heard.app.pid !== null && heard.app.pid !== undefined && pidAlive(heard.app.pid),
98
+ } : null);
99
+ const base = {
100
+ task_id: r.task_id, objective: r.objective, holder: r.principal_id, state: r.state,
101
+ last_word_at: r.last_word_at, last_progress: r.last_progress,
102
+ children_line: r.children?.line ?? null,
103
+ home_path: this.registry.rootOf(r.home) ?? r.home ?? 'homeless',
104
+ // The surface speaking on the claim: the wire's live word wins; the durable fallback
105
+ // is the latest trace-link statement's transcript, mapped by its owning store.
106
+ surface: heard?.via ?? (r.trace_path ? ownerOfTracePath(r.trace_path) : null),
107
+ };
108
+ return { ...base, session: ref, resume: this.resumeFor(base, ref) };
109
+ }
110
+
111
+ /**
112
+ * A breach row carries the ONE act that can change its truth (ruling 2026-08-31): never-
113
+ * judged and engine-failed → dispatch the judgment, DETACHED (closing the window can't
114
+ * orphan it) — for a sibling group, on its oldest child of the leading kind (children ride
115
+ * in breach order); judged-rejected and gone-quiet → CONTINUE into the work, at the parent
116
+ * for a group (the reclaim bundle carries the verdict — re-judging a judged assertion is
117
+ * the one act that can never help). The act's WORD is the kinds table's; the act's KIND is
118
+ * decided here, from the environment. Home is the ONE resolver's answer; a homeless
119
+ * judgment runs from the operator's home.
120
+ */
121
+ glassBreach(b) {
122
+ const home = typeof b.home === 'string' && b.home.startsWith('/') ? b.home : null;
123
+ const word = KINDS[b.kind].act;
124
+ if (judges(b.kind)) {
125
+ const target = b.group ? b.group.children[0] : b.task_id;
126
+ return { ...b, act: { kind: 'spawn-terminal', command: `oathe verify --detach ${shellQuote(target)}`, cwd: home ?? this.operatorHome, terminal_bundle: TERMINAL_FALLBACK, word } };
127
+ }
128
+ if (home !== null && this.defaultAgent) {
129
+ return { ...b, act: { kind: 'spawn-terminal', command: `oathe ${this.defaultAgent} ${shellQuote(`continue ${b.task_id}`)}`, cwd: home, terminal_bundle: TERMINAL_FALLBACK, word } };
130
+ }
131
+ return { ...b, act: { kind: 'copy-only', word } };
132
+ }
133
+
134
+ /**
135
+ * The frame: the digest's rows and the count beyond them (the bar is color + count; the
136
+ * sheet's rows carry the words), work in motion (anyone's active claim with a recent word,
137
+ * or heard live), your idle-held claims after it, the one classification, and the machine's
138
+ * chosen agent (the glass reads no config; null when onboarding never chose one).
139
+ */
140
+ build({ digest, sections }) {
141
+ const sess = this.sessions();
142
+ const row = (r) => this.glassRow(r, sess);
143
+ return {
144
+ breaches: digest.rows.map((b) => this.glassBreach(b)),
145
+ more: digest.more,
146
+ motion: [...sections.mine, ...sections.held].filter((r) => this.moving(r)).map(row),
147
+ idle: sections.mine.filter((r) => !this.moving(r)).map(row),
148
+ sections,
149
+ default_agent: this.defaultAgent,
150
+ };
151
+ }
152
+ }
@@ -0,0 +1,113 @@
1
+ // oathe — the annotator: oathe's claims-vs-actions layer, applied over ANY valid ATIF
2
+ // trajectory. The converters (src/atif.mjs, src/harnesses/codex-rollout.mjs) emit pure ATIF —
3
+ // what a Harbor converter could also emit — and this module adds what oathe knows, in the
4
+ // spec's one sanctioned slot, namespaced `extra.oathe` (docs/atif-oathe.md, convention 2):
5
+ //
6
+ // root oathe_convention, and on export the OBLIGATION this trajectory is
7
+ // evidence for (org_id, task_id, work_claim_id, contract_ref, workspace,
8
+ // verdict)
9
+ // step claim_events — the oathe speech acts among the step's tool calls
10
+ // tool call files — the paths the call's arguments aim at
11
+ // observation observed — facts the output text STATES (an exit code), never inferred
12
+ //
13
+ // The annotation is a copy: annotated − extra.oathe deep-equals the input. Invalid input is
14
+ // a typed refusal (the annotator judges nothing it cannot validate). projectAnnotated is the
15
+ // one read every oathe consumer performs — the verifier, the heartbeat, the census, the
16
+ // export — so no consumer ever reads a converter output and finds the layer missing.
17
+
18
+ import { AtifValidator, AtifError } from './atif.mjs';
19
+ import { makeToolDefs } from './mcp/oathe-tools.mjs';
20
+ import { projectorFor } from './harnesses/catalog.mjs';
21
+
22
+ export const OATHE_CONVENTION_VERSION = 2;
23
+
24
+ /** The oathe speech-act verbs — derived from the server's own tool defs, never retyped. */
25
+ export const OATHE_VERBS = Object.freeze(makeToolDefs().map((t) => t.name));
26
+
27
+ // The output's OWN final status line — never a mention inside content. Measured 2026-09-01
28
+ // on four real records (25 occurrences): every "Exit code N" was inside a printed file or
29
+ // log; a match anywhere in the text was a false observation, so only the last line counts.
30
+ const EXIT_CODE_PATTERN = /[Ee]xit code:?\s+(\d+)\s*$/;
31
+
32
+ /** oathe verb name for a tool call, when the call IS an oathe speech act (MCP-prefixed), else null. */
33
+ export function oatheVerbFor(functionName) {
34
+ const name = String(functionName ?? '');
35
+ return OATHE_VERBS.find((verb) => name === verb || name.endsWith(`__${verb}`)) ?? null;
36
+ }
37
+
38
+ /** The exit code an output TEXT states as its own last line ("Exit code N"), else null — never inferred. */
39
+ export function statedExitCode(text) {
40
+ const match = String(text ?? '').trimEnd().split('\n').at(-1).match(EXIT_CODE_PATTERN);
41
+ return match ? Number(match[1]) : null;
42
+ }
43
+
44
+ /**
45
+ * The conservative observed facts of an observation result: what the RECORD states
46
+ * structurally (a converter's extra.record.exit_code, decoded by the harness itself) outranks
47
+ * what the output text says; the text parse is the fallback, and only what it actually states.
48
+ */
49
+ export function observedFacts(result) {
50
+ const structural = result?.extra?.record?.exit_code;
51
+ if (Number.isInteger(structural)) return { exit_code: structural };
52
+ const stated = statedExitCode(result?.content);
53
+ return stated === null ? null : { exit_code: stated };
54
+ }
55
+
56
+ const withOathe = (node, fields) => ({ ...(node.extra ?? {}), oathe: { ...(node.extra?.oathe ?? {}), ...fields } });
57
+
58
+ export class OatheAnnotator {
59
+ /**
60
+ * @param {object} trajectory a valid ATIF trajectory (a converter's output)
61
+ * @param {{obligation?: object|null}} o the obligation stamped on the ROOT on export
62
+ * @returns {object} an annotated copy — the input is untouched
63
+ */
64
+ annotate(trajectory, { obligation = null } = {}) {
65
+ const seen = new AtifValidator().validate(trajectory);
66
+ if (!seen.ok) {
67
+ throw new AtifError('ATIF_ANNOTATE_INVALID_INPUT',
68
+ `the annotator takes a valid ATIF trajectory — ${seen.detail}`, { detail: seen.detail });
69
+ }
70
+ const out = structuredClone(trajectory);
71
+ this.#trajectory(out, obligation);
72
+ return out;
73
+ }
74
+
75
+ #trajectory(t, obligation) {
76
+ t.extra = withOathe(t, { oathe_convention: OATHE_CONVENTION_VERSION, ...(obligation ?? {}) });
77
+ for (const step of t.steps) this.#step(step);
78
+ for (const child of t.subagent_trajectories ?? []) this.#trajectory(child, null);
79
+ }
80
+
81
+ #step(step) {
82
+ // A speech act is a tool call by an oathe verb — or, on codex, an act the record decoded
83
+ // INSIDE an exec source that ran several things (extra.record.executions[].tool): the
84
+ // exec stays one call, the act stays on the record. A step this trajectory INHERITED
85
+ // (is_copied_context — a forked child's copy of the parent's turn) carries the parent's
86
+ // acts, never this agent's claim events.
87
+ const acts = step.is_copied_context === true ? [] : [
88
+ ...(step.tool_calls ?? []).map((call) => ({ name: call.function_name, args: call.arguments })),
89
+ ...(step.observation?.results ?? []).flatMap((result) => (result.extra?.record?.executions ?? [])
90
+ .filter((ran) => ran.tool).map((ran) => ({ name: ran.tool, args: ran.arguments }))),
91
+ ];
92
+ const events = acts
93
+ .map(({ name, args }) => {
94
+ const verb = oatheVerbFor(name);
95
+ return verb ? { verb, task_id: args?.task_id } : null;
96
+ })
97
+ .filter(Boolean);
98
+ if (events.length > 0) step.extra = withOathe(step, { claim_events: events });
99
+ for (const call of step.tool_calls ?? []) {
100
+ if (typeof call.arguments?.file_path === 'string') call.extra = withOathe(call, { files: [call.arguments.file_path] });
101
+ }
102
+ for (const result of step.observation?.results ?? []) {
103
+ const observed = observedFacts(result);
104
+ if (observed) result.extra = withOathe(result, { observed });
105
+ }
106
+ }
107
+ }
108
+
109
+ /** The one read every oathe consumer performs: the owning store's converter, then the annotation. */
110
+ export async function projectAnnotated(file, { home, obligation = null } = {}) {
111
+ const trajectory = (await projectorFor(file, { home })).project(file);
112
+ return new OatheAnnotator().annotate(trajectory, { obligation });
113
+ }