@oathe/oathe 0.3.1 → 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 (57) hide show
  1. package/README.md +43 -13
  2. package/assets/oathe-hero.png +0 -0
  3. package/bin/node-floor.mjs +16 -0
  4. package/bin/oathe.mjs +78 -130
  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/notch.mjs +7 -1
  44. package/src/oathe-annotator.mjs +113 -0
  45. package/src/pager.mjs +75 -37
  46. package/src/runtime/provider.mjs +2 -2
  47. package/src/session-host.mjs +1 -1
  48. package/src/sessions.mjs +8 -1
  49. package/src/speaker.mjs +54 -26
  50. package/src/statements.mjs +120 -2
  51. package/src/substrate.mjs +3 -3
  52. package/src/successor.mjs +2 -3
  53. package/src/trace-census.mjs +96 -0
  54. package/src/traces.mjs +98 -6
  55. package/src/uninstall.mjs +4 -1
  56. package/src/verifier.mjs +37 -19
  57. package/assets/oathe-hero.svg +0 -92
package/src/pager.mjs CHANGED
@@ -1,27 +1,49 @@
1
1
  // oathe — the breach pager (R-PAGER): the session-start digest of promises BREACHED anywhere
2
- // on this machine. Condition-based and stateless — three org-wide reads over facts the
2
+ // on this machine. Condition-based and stateless — four org-wide reads over facts the
3
3
  // substrate already holds, no cursor, no read-state, no auto-yield; a breach repeats every
4
4
  // session until its condition clears, because the condition is the fact.
5
5
  //
6
- // overdue a completion asserted and still unverified past its verify_by
7
- // (cell.unverified_past_verify_by — the R2 clock leg, at the injected instant)
8
6
  // reopened a rejection nobody reclaimed: origin `reopened`, and the task's latest claim
9
7
  // predates its latest rejected verification (016's next claimant never came)
8
+ // stalled a verification that died before a verdict (engine or evidence) and released
9
+ // its claim — the promise waits on a retry
10
+ // overdue a completion asserted and still unverified past its verify_by
11
+ // (cell.unverified_past_verify_by — the R2 clock leg, at the injected instant)
10
12
  // quiet an active claim whose holder has said nothing (no non-trace progress statement)
11
13
  // for longer than pagerQuietHours — the claim itself counts as the first word
12
14
  //
13
- // A lapsed lease is lifecycle, not a breach. A task appears once, under its sharpest breach.
14
- // Homes render as folders through the registry (raw ref when unregistered, `homeless` for
15
- // a synthetic mint). The board renderers own the voice; this module owns the facts.
15
+ // A lapsed lease is lifecycle, not a breach. A task appears once, under its sharpest breach;
16
+ // the kinds, their sharpness order (BREACH_KINDS) and the ONE comparator (breachOrder) live
17
+ // with the digest (src/breach-digest.mjs) and are re-exported here beside the facts. Homes
18
+ // render as folders through the registry (raw ref when unregistered, `homeless` for a
19
+ // synthetic mint) and the raw ref rides beside the label. The data is whole — a verdict or
20
+ // an engine's words are never clipped here; clipping is the renderer's business. This
21
+ // module owns the facts, not the voice; `digest()` hands them to the one budget.
16
22
 
17
23
  import { HomeBoard } from './home.mjs';
18
24
  import { VERIFICATION_PREFIX } from './plans.mjs';
19
- import { isEngineFailureSql, latestVerdictSql, latestProgressSql } from './statements.mjs';
25
+ import { isEngineFailureSql, isVerifyStallSql, latestVerdictSql, latestProgressSql, spawnParentSql } from './statements.mjs';
26
+ import { verifierCapable } from './harnesses/catalog.mjs';
27
+ import { BreachDigest, breachOrder } from './breach-digest.mjs';
20
28
 
21
- export const BREACH_KINDS = Object.freeze(['overdue', 'reopened', 'quiet']);
29
+ export { BREACH_KINDS, breachOrder } from './breach-digest.mjs';
22
30
  export const HOMELESS_LABEL = 'homeless';
23
31
  const STAMP = "'YYYY-MM-DD HH24:MI'";
24
32
 
33
+ /**
34
+ * A stall's detail: the verify child's own failure words, whole, then the retry gesture — on
35
+ * another engine only when an engine (not the record) died, named concretely from the catalog.
36
+ * The failed engine is read from the stall statement's fixed opening (`engine <name> failed…`,
37
+ * src/verifier.mjs) — the one place that wording is minted. The kind word ("verify failed")
38
+ * rides beside every rendering of this detail, so the detail does not repeat it; the retry
39
+ * leads, so a renderer's clip only ever shortens the engine's words, never the act.
40
+ */
41
+ function stallDetail({ task_id, proposition, engine_stage }) {
42
+ const failed = engine_stage ? /^engine (\S+) failed/.exec(proposition)?.[1] ?? null : null;
43
+ const other = engine_stage ? verifierCapable().find((engine) => engine !== failed) ?? null : null;
44
+ return `retry: /oathe:verify ${task_id}${other ? ` ${other}` : ''} — ${proposition}`;
45
+ }
46
+
25
47
  export class Pager {
26
48
  /**
27
49
  * @param {{client: {query: Function}, identity: {orgId: string}, config: {get: Function},
@@ -38,9 +60,11 @@ export class Pager {
38
60
  }
39
61
 
40
62
  /**
41
- * @returns {Promise<Array<{kind: 'overdue'|'reopened'|'quiet', task_id: string, objective: string,
42
- * home: string, detail: string, at: string}>>} kind-ordered, oldest first within a kind;
43
- * `at` is the breach's own clock (UTC) — ages render from it, never from the sentence
63
+ * @returns {Promise<Array<{kind: 'reopened'|'stalled'|'overdue'|'quiet', task_id: string,
64
+ * objective: string, home: string, home_ref: string|null, detail: string,
65
+ * at: string}>>} in breachOrder; `at` is the breach's own clock (UTC) —
66
+ * ages render from it, never from the sentence; `home_ref` is the raw ref a digest
67
+ * scopes on, `home` the folder a person reads
44
68
  */
45
69
  async breaches() {
46
70
  const asOf = this.clock().toISOString();
@@ -48,17 +72,21 @@ export class Pager {
48
72
  const reopened = await this.#reopened();
49
73
  const stalled = await this.#stalled();
50
74
  const quiet = await this.#quiet(asOf);
51
- // A rejected-and-unreclaimed task is also "asserted past verify_by" — but the verdict
52
- // landed; what is breached is the reclaim. One line per task, the sharper fact wins —
53
- // and the SHARPEST kinds lead the list (ruling 2026-08-31): rejected and stalled work
54
- // needs a person; never-verified drains itself now that done dispatches its own
55
- // judgment. Every consumer (digest, splash, glass) inherits this one order.
56
- const reopenedIds = new Set(reopened.map((r) => r.task_id));
57
- const stalledIds = new Set(stalled.map((r) => r.task_id));
58
- return [...reopened, ...stalled,
59
- ...overdue.filter((r) => !reopenedIds.has(r.task_id) && !stalledIds.has(r.task_id)),
60
- ...quiet]
61
- .map(({ kind, task_id, objective, home, detail, at }) => ({ kind, task_id, objective, home: this.#homeLabel(home), detail, at }));
75
+ // A rejected-and-unreclaimed or stalled task is also "asserted past verify_by" — but the
76
+ // verdict (or the attempt at one) landed; what is breached is the reclaim or the retry.
77
+ // One row per task, the sharper fact wins; the order is breachOrder's, nowhere else's.
78
+ const judged = new Set([...reopened, ...stalled].map((r) => r.task_id));
79
+ return [...reopened, ...stalled, ...overdue.filter((r) => !judged.has(r.task_id)), ...quiet]
80
+ .map(({ kind, task_id, objective, home, detail, at, parent, parent_objective }) => ({
81
+ kind, task_id, objective, home: this.#homeLabel(home), home_ref: home ?? null, detail, at,
82
+ parent: parent ?? null, parent_objective: parent_objective ?? null,
83
+ }))
84
+ .sort(breachOrder);
85
+ }
86
+
87
+ /** The one budget over the facts — every surface that shows a breach renders this. */
88
+ async digest() {
89
+ return new BreachDigest({ breaches: await this.breaches() });
62
90
  }
63
91
 
64
92
  #homeLabel(ref) {
@@ -75,9 +103,11 @@ export class Pager {
75
103
  const { rows } = await this.client.query(
76
104
  `SELECT 'overdue' AS kind, o.task_id, t.objective, ${HomeBoard.homeSql('t')} AS home,
77
105
  'verification overdue since ' || to_char(o.verify_by, ${STAMP}) AS detail,
78
- to_char(o.verify_by AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at
106
+ to_char(o.verify_by AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at,
107
+ sp.parent_task_id AS parent, sp.parent_objective
79
108
  FROM cell.unverified_past_verify_by($2::timestamptz) o
80
109
  JOIN cell.task t ON t.org_id = o.org_id AND t.task_id = o.task_id
110
+ LEFT JOIN LATERAL (${spawnParentSql({ task: 't' })}) sp ON true
81
111
  WHERE o.org_id = $1 AND t.task_id NOT LIKE '${VERIFICATION_PREFIX}%'
82
112
  AND NOT EXISTS (
83
113
  SELECT 1 FROM cell.verification v
@@ -92,14 +122,16 @@ export class Pager {
92
122
  async #reopened() {
93
123
  // Pages while nobody is REDOING the work: no active claim, and no fresh assertion
94
124
  // since the last rejection. A reclaim silences it only while it stays active — a
95
- // reclaim-then-yield returns here (it used to flip to "overdue" and offer re-judgment
96
- // of the already-rejected assertion). The verdict rides WHOLE: the reason is one
125
+ // reclaim-then-yield returns here, never to "overdue" (the rejected assertion is not
126
+ // owed a second judgment). The verdict rides WHOLE: the reason is one
97
127
  // sentence by the verdict contract; clipping is the renderer's business, not the data's.
98
128
  const { rows } = await this.client.query(
99
129
  `SELECT 'reopened' AS kind, t.task_id, t.objective, ${HomeBoard.homeSql('t')} AS home,
100
130
  coalesce(v.verdict || ' — ', '') || 'nobody has reclaimed it (last held by ' || w.principal_id || ')' AS detail,
101
- to_char(r.last_rejected AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at
131
+ to_char(r.last_rejected AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at,
132
+ sp.parent_task_id AS parent, sp.parent_objective
102
133
  FROM cell.task t
134
+ LEFT JOIN LATERAL (${spawnParentSql({ task: 't' })}) sp ON true
103
135
  JOIN LATERAL (
104
136
  SELECT max(v2.recorded_at) AS last_rejected FROM cell.verification v2
105
137
  WHERE v2.org_id = t.org_id AND v2.task_id = t.task_id AND v2.result = 'rejected'
@@ -128,22 +160,26 @@ export class Pager {
128
160
  return rows;
129
161
  }
130
162
 
131
- // A verification whose engine died before a verdict (the run recorded the failure and
132
- // RELEASED its claim — ruling 2026-08-30): the promise is stalled on an engine, and the
133
- // page names the retry gesture on another one.
163
+ // A verification that died before a verdict (the run recorded the failure and RELEASED its
164
+ // claim — ruling 2026-08-30): the promise is stalled, and the page names the retry gesture.
165
+ // Only an ENGINE-stage death advises another engine — a CONCRETE one, asked of the catalog
166
+ // — because an unreadable record (evidence stage) fails every engine alike, so its retry is
167
+ // the same command after the cause is fixed. The engine's own words ride whole.
134
168
  async #stalled() {
135
169
  const { rows } = await this.client.query(
136
170
  `SELECT 'stalled' AS kind, substring(t.task_id from 8) AS task_id, p.objective,
137
- ${HomeBoard.homeSql('p')} AS home,
138
- 'verification stalled — ' || left(s.proposition, 120)
139
- || '; retry: /oathe:verify ' || substring(t.task_id from 8) || ' <another engine>' AS detail,
140
- to_char(s.asserted_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at
171
+ ${HomeBoard.homeSql('p')} AS home, s.proposition, s.engine_stage,
172
+ to_char(s.asserted_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at,
173
+ sp.parent_task_id AS parent, sp.parent_objective
141
174
  FROM cell.task t
142
175
  JOIN cell.task p ON p.org_id = t.org_id AND p.task_id = substring(t.task_id from 8)
176
+ LEFT JOIN LATERAL (${spawnParentSql({ task: 'p' })}) sp ON true
143
177
  JOIN LATERAL (
144
- SELECT st.proposition, st.asserted_at FROM cell.agent_statement st
178
+ SELECT st.proposition, st.asserted_at,
179
+ ${isEngineFailureSql('st.evidence_refs')} AS engine_stage
180
+ FROM cell.agent_statement st
145
181
  WHERE st.org_id = t.org_id AND st.task_id = t.task_id
146
- AND ${isEngineFailureSql('st.evidence_refs')}
182
+ AND ${isVerifyStallSql('st.evidence_refs')}
147
183
  ORDER BY st.asserted_at DESC LIMIT 1
148
184
  ) s ON true
149
185
  WHERE t.org_id = $1 AND t.task_id LIKE 'verify:%'
@@ -155,7 +191,7 @@ export class Pager {
155
191
  AND c2.settled_at IS NOT NULL), 'epoch')
156
192
  ORDER BY s.asserted_at`,
157
193
  [this.orgId]);
158
- return rows;
194
+ return rows.map(({ proposition, engine_stage, ...row }) => ({ ...row, detail: stallDetail({ ...row, proposition, engine_stage }) }));
159
195
  }
160
196
 
161
197
  async #quiet(asOf) {
@@ -164,9 +200,11 @@ export class Pager {
164
200
  w.principal_id || ' holds it, quiet for '
165
201
  || floor(extract(epoch FROM ($2::timestamptz - last.at)) / 3600)::int || 'h (last word '
166
202
  || to_char(last.at, ${STAMP}) || ')' AS detail,
167
- to_char(last.at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at
203
+ to_char(last.at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI"Z"') AS at,
204
+ sp.parent_task_id AS parent, sp.parent_objective
168
205
  FROM cell.work_claim w
169
206
  JOIN cell.task t USING (org_id, task_id)
207
+ LEFT JOIN LATERAL (${spawnParentSql({ task: 't' })}) sp ON true
170
208
  LEFT JOIN LATERAL (${latestProgressSql({ task: 't', claim: 'w' })}) p ON true
171
209
  CROSS JOIN LATERAL (SELECT coalesce(p.asserted_at, w.claimed_at) AS at) last
172
210
  WHERE w.org_id = $1 AND w.state = 'active' AND w.settled_at IS NULL
@@ -77,8 +77,8 @@ export class OatheRuntimeProvider {
77
77
  }
78
78
 
79
79
  /** THIN WRAPPER (ruling, 2026-08-26): no composition logic lives here. The runtime
80
- * package owns the whole acceptance build — including the recorded-verdict checker wiring
81
- * that previously lived in this method — and lands as `oathe-runtime/seam` exporting
80
+ * package owns the whole acceptance build — the recorded-verdict checker wiring included —
81
+ * as `oathe-runtime/seam` exporting
82
82
  * `buildAcceptanceRuntime({ pool }) → { SETTLE, laneFor(seatPrincipal) }`. */
83
83
  async acceptanceRuntime({ pool }) {
84
84
  this.#assertResolves();
@@ -56,7 +56,7 @@ export class SessionHost {
56
56
  await this.tickInFlight;
57
57
  }
58
58
 
59
- /** The observed clean exit: stop renewing AND say so on every claim this session held. */
59
+ /** The observed clean exit: halt the watch AND say so on every claim this session held. */
60
60
  async stop({ exitCode }) {
61
61
  this.#halt();
62
62
  await this.tickInFlight;
package/src/sessions.mjs CHANGED
@@ -148,9 +148,16 @@ export class SessionRegistry {
148
148
  byAncestry(ancestry) {
149
149
  const { sessions } = this.load();
150
150
  for (const { pid } of ancestry) {
151
+ // Several rows can share a pid (a resume, a session rotation under one process) —
152
+ // attribution follows the FRESHEST row, never JSON insertion order.
153
+ let best = null;
151
154
  for (const [sessionId, row] of Object.entries(sessions)) {
152
- if (row.pid === pid) return { sessionId, row };
155
+ if (row.pid !== pid) continue;
156
+ if (!best || String(row.last_seen_at ?? '') > String(best.row.last_seen_at ?? '')) {
157
+ best = { sessionId, row };
158
+ }
153
159
  }
160
+ if (best) return best;
154
161
  }
155
162
  return null;
156
163
  }
package/src/speaker.mjs CHANGED
@@ -18,8 +18,10 @@
18
18
  // the PORTABLE fact (which session spoke — written by linkTrace at the act); this device's
19
19
  // sessions.json keeps the DEVICE fact (which process embodies it now).
20
20
 
21
+ import fs from 'node:fs';
22
+
21
23
  import { processAncestry, nearestAppBundle, SessionRegistry } from './sessions.mjs';
22
- import { surfaceForSession, harnessForClient, ownerOfTracePath, ownedAncestorIndex, HARNESS_CLASSES } from './harnesses/catalog.mjs';
24
+ import { surfaceForSession, harnessForClient, ownerOfTracePath, ownedAncestorIndex, transcriptFor, HARNESS_CLASSES } from './harnesses/catalog.mjs';
23
25
 
24
26
  /**
25
27
  * @param {{pid?: number, sessionsPath: string, clientName?: string|null,
@@ -28,38 +30,64 @@ import { surfaceForSession, harnessForClient, ownerOfTracePath, ownedAncestorInd
28
30
  * session: {sessionId: string, transcriptPath: string|null, harness: string}|null}}
29
31
  */
30
32
  export function resolveSpeaker({ pid = process.pid, sessionsPath, clientName = null, exec, platform } = {}) {
33
+ // The ancestry is a fact of the PROCESS: walked once (one ps call), never per act.
31
34
  const walk = processAncestry({
32
35
  pid,
33
36
  ...(exec !== undefined && { exec }),
34
37
  ...(platform !== undefined && { platform }),
35
38
  });
36
- const hit = sessionsPath ? new SessionRegistry({ sessionsPath }).byAncestry(walk) : null;
37
- if (hit) {
38
- const { row } = hit;
39
- const ownedRow = ownedAncestorIndex(row.ancestry ?? []);
40
- const harnessExec = (ownedRow === -1 ? row.ancestry?.[0]?.exec : row.ancestry[ownedRow].exec) ?? '';
41
- return {
42
- surface: surfaceForSession({ ancestry: row.ancestry ?? [], app: row.app ?? null, transcriptPath: row.transcript_path ?? null })
43
- ?? harnessForClient(clientName),
44
- app: row.app ?? nearestAppBundle(walk),
45
- session: {
46
- sessionId: hit.sessionId,
47
- transcriptPath: row.transcript_path ?? null,
48
- // The adapter that owns the session: its trace store first, else its own process.
49
- harness: ownerOfTracePath(row.transcript_path ?? '')
50
- ?? HARNESS_CLASSES.find((C) => C.surfaces?.ownsExec(harnessExec))?.harnessName
39
+ const registry = sessionsPath ? new SessionRegistry({ sessionsPath }) : null;
40
+
41
+ const shape = () => {
42
+ const hit = registry ? registry.byAncestry(walk) : null;
43
+ if (hit) {
44
+ const { row } = hit;
45
+ const ownedRow = ownedAncestorIndex(row.ancestry ?? []);
46
+ const harnessExec = (ownedRow === -1 ? row.ancestry?.[0]?.exec : row.ancestry[ownedRow].exec) ?? '';
47
+ return {
48
+ surface: surfaceForSession({ ancestry: row.ancestry ?? [], app: row.app ?? null, transcriptPath: row.transcript_path ?? null })
51
49
  ?? harnessForClient(clientName),
52
- },
50
+ app: row.app ?? nearestAppBundle(walk),
51
+ session: {
52
+ sessionId: hit.sessionId,
53
+ // The file the session's rows live in — the registry holds what the hook was told,
54
+ // which a resume or compaction rotates away from (the store resolves; see traces.mjs).
55
+ transcriptPath: transcriptFor({ sessionId: hit.sessionId, reportedPath: row.transcript_path ?? null }),
56
+ // The adapter that owns the session: its trace store first, else its own process.
57
+ harness: ownerOfTracePath(row.transcript_path ?? '')
58
+ ?? HARNESS_CLASSES.find((C) => C.surfaces?.ownsExec(harnessExec))?.harnessName
59
+ ?? harnessForClient(clientName),
60
+ },
61
+ };
62
+ }
63
+ // No registered session — name what the chain itself shows, sliced at the nearest
64
+ // adapter-owned ancestor (the harness above us); the client's word is the last fallback.
65
+ const owned = ownedAncestorIndex(walk);
66
+ const ancestry = owned === -1 ? walk : walk.slice(owned);
67
+ const app = nearestAppBundle(ancestry);
68
+ return {
69
+ surface: (owned === -1 ? null : surfaceForSession({ ancestry, app })) ?? harnessForClient(clientName),
70
+ app,
71
+ session: null,
53
72
  };
54
- }
55
- // No registered session — name what the chain itself shows, sliced at the nearest
56
- // adapter-owned ancestor (the harness above us); the client's word is the last fallback.
57
- const owned = ownedAncestorIndex(walk);
58
- const ancestry = owned === -1 ? walk : walk.slice(owned);
59
- const app = nearestAppBundle(ancestry);
73
+ };
74
+
75
+ // The session is a fact of the ACT (ruling 2026-09-03): a /clear or a resume registers a new
76
+ // id under the same process, and the next act must speak as it. A long-lived writer — the
77
+ // MCP server, whose context lives until a config change — used to keep the session it
78
+ // resolved at its first tool call and stamp it on every later act. So every read looks the
79
+ // registry up afresh, re-shaped only when the registry file changed (one stat per read).
80
+ let cached = null;
81
+ let stamp = null;
82
+ const current = () => {
83
+ let now = null;
84
+ try { now = sessionsPath ? fs.statSync(sessionsPath, { bigint: true }).mtimeNs : null; } catch { now = null; }
85
+ if (cached === null || now !== stamp) { cached = shape(); stamp = now; }
86
+ return cached;
87
+ };
60
88
  return {
61
- surface: (owned === -1 ? null : surfaceForSession({ ancestry, app })) ?? harnessForClient(clientName),
62
- app,
63
- session: null,
89
+ get surface() { return current().surface; },
90
+ get app() { return current().app; },
91
+ get session() { return current().session; },
64
92
  };
65
93
  }
@@ -5,6 +5,8 @@
5
5
  // heartbeat is custody evidence, not a word from the holder (the board and the pager both
6
6
  // read "last word" through this one fragment).
7
7
 
8
+ import fs from 'node:fs';
9
+
8
10
  export const TRACE_SUBJECT_PREFIX = 'trace:';
9
11
 
10
12
  /** The subject_ref of the statement linking a session transcript to a claim. */
@@ -23,13 +25,19 @@ export function isTraceSubjectSql(column) {
23
25
  * one link per claim × session, idempotent by (work_claim_id, subject_ref), so the write
24
26
  * wrapper stamps it at the act and the turn-end heartbeat's sweep is a no-op for it.
25
27
  * A session with no transcript store (cursor) attributes with empty evidence — honestly.
26
- * No open claim of this principal on the task → nothing to link, {linked: false}.
28
+ * No open claim of this principal on the task → nothing to link, {linked: false}. A
29
+ * transcript the harness named but has not written (a resumed session before its first
30
+ * turn end) is NOT linked: a link names a file a verifier can read, or it waits for the
31
+ * heartbeat — {linked: false, why} so the act can disclose it.
27
32
  * Failures THROW — attribution is part of the act, not a courtesy (retries are idempotent).
28
33
  * @param {{client: {query: Function}, identity: {orgId: string, principalId: string},
29
34
  * taskId: string, session: {sessionId: string, transcriptPath: string|null, harness: string|null}}} o
30
- * @returns {Promise<{linked: boolean}>}
35
+ * @returns {Promise<{linked: boolean, why?: string}>}
31
36
  */
32
37
  export async function linkTrace({ client, identity, taskId, session }) {
38
+ if (session.transcriptPath && !fs.existsSync(session.transcriptPath)) {
39
+ return { linked: false, why: `transcript not on disk yet (${session.transcriptPath}) — the turn-end heartbeat links the file the session writes` };
40
+ }
33
41
  const { rows } = await client.query(
34
42
  `SELECT work_claim_id FROM cell.work_claim
35
43
  WHERE org_id = $1 AND principal_id = $2 AND task_id = $3 AND settled_at IS NULL
@@ -76,12 +84,122 @@ export function isEngineFailureSql(column) {
76
84
  return `EXISTS (SELECT 1 FROM jsonb_array_elements_text(${column}) er WHERE er LIKE 'engine-failure:%')`;
77
85
  }
78
86
 
87
+ /** Evidence-failure shape: 'evidence-failure:<code>' — a verify child that could not READ the
88
+ * record (trace projection died before any engine launched) records this before releasing.
89
+ * No engine ran, so its stall must never blame one or advise swapping one. */
90
+ export function evidenceFailureRef(code) {
91
+ return `evidence-failure:${code || 'unknown'}`;
92
+ }
93
+ /** Either stall shape — the pager and the attention lines page BOTH kinds of stalled verify. */
94
+ export function isVerifyStallSql(column) {
95
+ return `EXISTS (SELECT 1 FROM jsonb_array_elements_text(${column}) er
96
+ WHERE er LIKE 'engine-failure:%' OR er LIKE 'evidence-failure:%')`;
97
+ }
98
+
79
99
  /** R-AMEND: the amendment trail's subject shape — 'amend:<task_id>', owned here alone. */
80
100
  export const AMEND_SUBJECT_PREFIX = 'amend:';
81
101
  export function amendSubjectRef(taskId) {
82
102
  return `${AMEND_SUBJECT_PREFIX}${taskId}`;
83
103
  }
84
104
 
105
+ /**
106
+ * LINEAGE (founder ruling 2026-09-01: provenance now, delegation later). Work claimed while
107
+ * a session holds a claim is recorded as SPAWNED under it: one observation statement on the
108
+ * parent's claim — subject 'spawn:<child>', evidence ['task:<child>'] — riding the statement
109
+ * transport every fact rides, so Cloud State carries it unchanged. The delegation column
110
+ * (cell.work_claim.parent_work_claim_id — 010's forward contract, assert_children_verified)
111
+ * stays reserved for accountable cross-principal delegation; spawnParentSql is the ONE read
112
+ * that will union both edges when the delegate verb ships, so display never knows which
113
+ * edge it read. Limitation, stated: nested fan-out inside one session attaches to the
114
+ * session's root claim — the trace's spawn tree is the exact record.
115
+ */
116
+ export const SPAWN_SUBJECT_PREFIX = 'spawn:';
117
+ export function spawnSubjectRef(childTaskId) {
118
+ return `${SPAWN_SUBJECT_PREFIX}${childTaskId}`;
119
+ }
120
+
121
+ export class SpawnParentError extends Error {
122
+ constructor(parent, why) {
123
+ super(`'${parent}' cannot be the parent: ${why} — pass the id of a claim you hold, or parent: null for standalone work`);
124
+ this.name = 'SpawnParentError';
125
+ this.code = 'OATHE_SPAWN_PARENT_NOT_HELD';
126
+ this.parent = parent;
127
+ }
128
+ }
129
+
130
+ /**
131
+ * LATERAL body: the parent `task` was spawned under (the latest spawn statement naming it)
132
+ * with the parent's objective — `parent_task_id` / `parent_objective`, NULL for a root.
133
+ * @param {{task: string}} aliases the cell.task alias in scope
134
+ */
135
+ export function spawnParentSql({ task }) {
136
+ return `SELECT s.task_id AS parent_task_id, pt.objective AS parent_objective
137
+ FROM cell.agent_statement s
138
+ JOIN cell.task pt ON pt.org_id = s.org_id AND pt.task_id = s.task_id
139
+ WHERE s.org_id = ${task}.org_id AND s.subject_ref = '${SPAWN_SUBJECT_PREFIX}' || ${task}.task_id
140
+ ORDER BY s.asserted_at DESC LIMIT 1`;
141
+ }
142
+
143
+ /** This principal's active claim on `taskId`, else null. */
144
+ async function heldClaim(client, identity, taskId) {
145
+ const { rows } = await client.query(
146
+ `SELECT work_claim_id FROM cell.work_claim
147
+ WHERE org_id = $1 AND principal_id = $2 AND task_id = $3 AND state = 'active' AND settled_at IS NULL
148
+ ORDER BY claimed_at DESC LIMIT 1`,
149
+ [identity.orgId, identity.principalId, taskId]);
150
+ return rows[0]?.work_claim_id ?? null;
151
+ }
152
+
153
+ /**
154
+ * Which claim a new claim is spawned under — decided BEFORE the claim lands, so a refusal
155
+ * leaves nothing behind. `parent` an id: that claim, which this principal must hold (never
156
+ * the task itself). `parent` null: standalone, on purpose. `parent` omitted: the session's
157
+ * root — the oldest active claim this principal holds that is linked to this session,
158
+ * excluding recorded children; no session, no lineage.
159
+ * @returns {Promise<{parent: string}|null>}
160
+ */
161
+ export async function spawnParentFor({ client, identity, session, taskId, parent }) {
162
+ if (parent === null) return null;
163
+ if (parent !== undefined) {
164
+ if (parent === taskId) throw new SpawnParentError(parent, 'a task cannot spawn itself');
165
+ if (await heldClaim(client, identity, parent) === null) throw new SpawnParentError(parent, `${identity.principalId} holds no active claim on it`);
166
+ return { parent };
167
+ }
168
+ if (!session) return null;
169
+ const { rows } = await client.query(
170
+ `SELECT c.task_id FROM cell.work_claim c
171
+ WHERE c.org_id = $1 AND c.principal_id = $2 AND c.task_id <> $3
172
+ AND c.state = 'active' AND c.settled_at IS NULL
173
+ AND EXISTS (SELECT 1 FROM cell.agent_statement s
174
+ WHERE s.org_id = c.org_id AND s.work_claim_id = c.work_claim_id AND s.subject_ref = $4)
175
+ AND NOT EXISTS (SELECT 1 FROM cell.agent_statement sp
176
+ WHERE sp.org_id = c.org_id AND sp.subject_ref = $5 || c.task_id)
177
+ ORDER BY c.claimed_at LIMIT 1`,
178
+ [identity.orgId, identity.principalId, taskId, traceSubjectRef(session.sessionId), SPAWN_SUBJECT_PREFIX]);
179
+ return rows.length > 0 ? { parent: rows[0].task_id } : null;
180
+ }
181
+
182
+ /**
183
+ * THE spawn writer: the observation on the parent's active claim, idempotent by
184
+ * (work_claim_id, subject_ref) — a yield-and-reclaim of the child leaves one record.
185
+ * Failures THROW — lineage is part of the act, not a courtesy.
186
+ */
187
+ export async function linkSpawn({ client, identity, parent, childTaskId, actor }) {
188
+ const workClaimId = await heldClaim(client, identity, parent);
189
+ if (workClaimId === null) throw new SpawnParentError(parent, `${identity.principalId} holds no active claim on it`);
190
+ const { randomUUID } = await import('node:crypto');
191
+ await client.query(
192
+ `INSERT INTO cell.agent_statement (statement_id, org_id, task_id, work_claim_id,
193
+ execution_actor, claim_principal, statement_type, subject_ref, proposition,
194
+ evidence_refs, epistemic_status, asserted_at)
195
+ SELECT $1, $2, $3, $4, $5, $6, 'observation', $7, $8, $9::jsonb, 'observed', now()
196
+ WHERE NOT EXISTS (
197
+ SELECT 1 FROM cell.agent_statement
198
+ WHERE org_id = $2 AND work_claim_id = $4 AND subject_ref = $7)`,
199
+ [randomUUID(), identity.orgId, parent, workClaimId, actor, identity.principalId,
200
+ spawnSubjectRef(childTaskId), `spawned '${childTaskId}' under this claim`, JSON.stringify([`task:${childTaskId}`])]);
201
+ }
202
+
85
203
  export function latestVerdictSql({ task }) {
86
204
  return `SELECT s.proposition AS verdict, s.asserted_at AS verdict_at
87
205
  FROM cell.agent_statement s
package/src/substrate.mjs CHANGED
@@ -115,9 +115,9 @@ export class Substrate {
115
115
  }
116
116
 
117
117
  // The transaction gate: BEGIN..COMMIT spans hold it, every outside query waits at it.
118
- // One shared connection + concurrent MCP tool calls used to interleave an acknowledged
119
- // write into an open transaction (swallowed by its ROLLBACK) — the review's sharpest
120
- // finding. The gate makes that impossible; a transaction's own queries ride `tx`.
118
+ // Without it, concurrent MCP tool calls on the one shared connection interleave an
119
+ // acknowledged write into an open transaction, where its ROLLBACK swallows the write.
120
+ // The gate makes that impossible; a transaction's own queries ride `tx`.
121
121
  #txnGate = Promise.resolve();
122
122
 
123
123
  async query(sql, params) {
package/src/successor.mjs CHANGED
@@ -7,9 +7,8 @@
7
7
  // lands behind `oathe-runtime/seam`, which must export
8
8
  // buildSuccessor({ substrate, identity, paths }) →
9
9
  // { pickup({ task_id, work_claim_id }) → object, close() → void }
10
- // The runtime-env synthesis and compiler wiring that previously lived here move into that
11
- // package (they are its concern, not the interface's); this file only delegates or refuses
12
- // TYPED and LOUD.
10
+ // The runtime-env synthesis and compiler wiring are that package's concern, not the
11
+ // interface's; this file only delegates or refuses TYPED and LOUD.
13
12
 
14
13
  import { RuntimeError } from './runtime/provider.mjs';
15
14
 
@@ -0,0 +1,96 @@
1
+ // oathe — the trace census: the ONE engine behind `oathe doctor`'s store sweep, the
2
+ // scripts/trace-census.mjs lane, and the unit tests (one implementation per concept). Two
3
+ // questions, both born 2026-08-31: does the store contain row types outside the adapter's
4
+ // declared roster (an addition the roster review has not seen — DRIFT), and does the
5
+ // projection CARRY what the raw record carries (fidelity — a projector that "didn't throw"
6
+ // rendered every codex action as exec({}) for days).
7
+
8
+ export class TraceCensusError extends Error {
9
+ constructor(code, message, details = {}) {
10
+ super(message);
11
+ this.name = 'TraceCensusError';
12
+ this.code = code;
13
+ this.details = details;
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Classify every row of every file against the adapter's declared roster.
19
+ * @returns {{swept: number, counts: object, undeclared: Array<{channel, type, count, example}>,
20
+ * unusedHandled: Array<{channel, type}>}}
21
+ */
22
+ export function censusOf({ store, roster, kindOf, files }) {
23
+ if (!roster || typeof kindOf !== 'function') {
24
+ throw new TraceCensusError('OATHE_TRACE_CENSUS_ROSTER_MISSING',
25
+ `the '${store?.harness}' traces capability declares no ${!roster ? 'roster' : 'kindOf classifier'} — `
26
+ + 'a store without its declared contract can never census green', { harness: store?.harness });
27
+ }
28
+ const counts = {};
29
+ const undeclared = new Map();
30
+ for (const file of files) {
31
+ for (const row of store.entries(file)) {
32
+ const { channel, type } = kindOf(row);
33
+ counts[channel] ??= {};
34
+ counts[channel][type] = (counts[channel][type] ?? 0) + 1;
35
+ const lane = roster[channel];
36
+ if (lane && (lane.handled.includes(type) || lane.ignored[type] !== undefined)) continue;
37
+ const key = `${channel}.${type}`;
38
+ const entry = undeclared.get(key) ?? { channel, type, count: 0, example: file };
39
+ entry.count += 1;
40
+ undeclared.set(key, entry);
41
+ }
42
+ }
43
+ const unusedHandled = [];
44
+ for (const [channel, lane] of Object.entries(roster)) {
45
+ for (const type of lane.handled) {
46
+ if (!counts[channel]?.[type]) unusedHandled.push({ channel, type });
47
+ }
48
+ }
49
+ return {
50
+ swept: files.length,
51
+ counts,
52
+ undeclared: [...undeclared.values()].sort((a, b) => `${a.channel}.${a.type}`.localeCompare(`${b.channel}.${b.type}`)),
53
+ unusedHandled,
54
+ };
55
+ }
56
+
57
+ /**
58
+ * Project every file and run the adapter's fidelity probes against raw + projection.
59
+ * `project(file)` is the one read the consumers perform — the converter, then the annotation
60
+ * (a probe judges the annotated trajectory; claim events are the annotator's). `traceStatus`
61
+ * is injected (the RUNTIME/DRIFT split is the doctor's concept) — a projection or probe
62
+ * error is classified, never lost.
63
+ * @returns {Promise<{probes: Array<{probe, applicable, failed: Array<{file, detail}>}>,
64
+ * projectionErrors: Array<{file, status, detail}>}>}
65
+ */
66
+ export async function fidelityOf({ store, project, fidelity, files, traceStatus }) {
67
+ const probes = Object.keys(fidelity ?? {}).map((name) => ({ probe: name, applicable: 0, failed: [] }));
68
+ if (probes.length === 0) {
69
+ throw new TraceCensusError('OATHE_TRACE_CENSUS_ROSTER_MISSING',
70
+ `the '${store?.harness}' traces capability declares no fidelity probes`, { harness: store?.harness });
71
+ }
72
+ const projectionErrors = [];
73
+ for (const file of files) {
74
+ let trajectory;
75
+ try {
76
+ trajectory = await project(file);
77
+ } catch (e) {
78
+ // An empty session (opened, nothing said) is a real store state, not drift.
79
+ const status = e?.code === 'ATIF_NO_STEPS' ? 'empty' : traceStatus(e);
80
+ projectionErrors.push({ file, status, detail: String(e?.message || e) });
81
+ continue;
82
+ }
83
+ const entries = store.entries(file);
84
+ for (const row of probes) {
85
+ try {
86
+ const seen = await fidelity[row.probe](entries, trajectory, { store, file });
87
+ if (!seen.applicable) continue;
88
+ row.applicable += 1;
89
+ if (!seen.ok) row.failed.push({ file, detail: seen.detail });
90
+ } catch (e) {
91
+ row.failed.push({ file, detail: `${traceStatus(e)}: ${String(e?.message || e)}` });
92
+ }
93
+ }
94
+ }
95
+ return { probes, projectionErrors };
96
+ }