@oathe/oathe 0.0.1 → 0.2.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 (71) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/LICENSE +202 -21
  3. package/NOTICE +7 -0
  4. package/README.md +104 -12
  5. package/assets/oathe-hero.svg +92 -0
  6. package/bin/oathe.mjs +376 -0
  7. package/docs/PRIVACY.md +45 -0
  8. package/package.json +33 -23
  9. package/plugin/.claude-plugin/plugin.json +10 -0
  10. package/plugin/.mcp.json +13 -0
  11. package/plugin/hooks/frame-note.mjs +24 -0
  12. package/plugin/hooks/heartbeat.mjs +49 -0
  13. package/plugin/hooks/hooks.json +39 -0
  14. package/plugin/hooks/lib.mjs +83 -0
  15. package/plugin/hooks/render-board.mjs +11 -0
  16. package/plugin/skills/oathe-work/SKILL.md +33 -0
  17. package/src/atif.mjs +633 -0
  18. package/src/blocks.mjs +192 -0
  19. package/src/board-render.mjs +106 -0
  20. package/src/config.mjs +169 -0
  21. package/src/context.mjs +35 -0
  22. package/src/doctor.mjs +108 -0
  23. package/src/harness.mjs +271 -0
  24. package/src/init.mjs +92 -0
  25. package/src/launch-env.mjs +25 -0
  26. package/src/launch.mjs +259 -0
  27. package/src/manifest.mjs +89 -0
  28. package/src/mcp/oathe-tools.mjs +517 -0
  29. package/src/paths.mjs +49 -0
  30. package/src/plans.mjs +50 -0
  31. package/src/runtime/discharge.mjs +57 -0
  32. package/src/runtime/provider.mjs +154 -0
  33. package/src/runtime/simple-cage.mjs +67 -0
  34. package/src/runtime/sql-acceptance-lane.mjs +89 -0
  35. package/src/session-host.mjs +81 -0
  36. package/src/substrate.mjs +337 -0
  37. package/src/successor.mjs +31 -0
  38. package/src/traces.mjs +242 -0
  39. package/src/uninstall.mjs +45 -0
  40. package/src/verifier.mjs +322 -0
  41. package/src/workspace.mjs +47 -0
  42. package/vendor/ddl/001_core.sql +312 -0
  43. package/vendor/ddl/002_claim.sql +438 -0
  44. package/vendor/ddl/003_verification.sql +480 -0
  45. package/vendor/ddl/004_delegation.sql +397 -0
  46. package/vendor/ddl/005_escalation.sql +303 -0
  47. package/vendor/ddl/006_dependency.sql +384 -0
  48. package/vendor/ddl/007_assignment.sql +502 -0
  49. package/vendor/ddl/008_effect_receipt.sql +290 -0
  50. package/vendor/ddl/009_verified_edge.sql +452 -0
  51. package/vendor/ddl/010_parent_child_verification.sql +320 -0
  52. package/vendor/ddl/011_confirm.sql +288 -0
  53. package/vendor/ddl/012_evaluator_lane.sql +444 -0
  54. package/vendor/ddl/013_claim_terminal.sql +279 -0
  55. package/vendor/ddl/014_claim_settlement.sql +327 -0
  56. package/vendor/ddl/015_claim_yield.sql +213 -0
  57. package/vendor/ddl/016_reopened_reclaim.sql +285 -0
  58. package/vendor/ddl/017_claim_yield_causes.sql +357 -0
  59. package/vendor/ddl/018_receiptless_unknown.sql +249 -0
  60. package/vendor/ddl/019_verification_contract_freeze.sql +335 -0
  61. package/vendor/ddl/020_context_compilation.sql +105 -0
  62. package/vendor/ddl/021_execution_attempt_closure.sql +95 -0
  63. package/vendor/ddl/022_verification_clause.sql +106 -0
  64. package/vendor/ddl/023_executor_role.sql +66 -0
  65. package/vendor/ddl/024_executor_role_hardening.sql +439 -0
  66. package/vendor/ddl/025_running_attempt_uniqueness.sql +102 -0
  67. package/vendor/ddl/026_acceptance_authority.sql +230 -0
  68. package/vendor/ddl/027_ownership_return.sql +836 -0
  69. package/vendor/ddl/028_attempt_bind_ownership.sql +173 -0
  70. package/vendor/ddl/manifest.json +183 -0
  71. package/index.js +0 -33
@@ -0,0 +1,322 @@
1
+ // oathe — the allocated-on-demand verifier (the ruled form: an agent evaluator is allocated
2
+ // per obligation, never a standing grader; D0:48 "the runtime never being an agent grading
3
+ // agents" stays intact because the AGENT only produces EVIDENCE — every settlement is signed
4
+ // by a deterministic acceptance lane under a non-author seat, through the substrate's own
5
+ // verbs, refusals and all).
6
+ //
7
+ // The flow, per obligation:
8
+ // claim the verification task (as the verifier principal — visible on the board)
9
+ // → gather the record: objective, frozen plan, completion statement, linked traces (fan-out
10
+ // derived at read time; a trace that fails the contract REFUSES — never less evidence
11
+ // than the claim recorded)
12
+ // → one headless engine run (claude|codex, assigned at claim time) → strict JSON verdict
13
+ // → the verdict lands as the verification task's completion statement (durable, addressable)
14
+ // → the acceptance lane settles the ORIGINAL claim: seat = verifier principal (FC010: not
15
+ // the author), checker = 'oathe-verdict' (deterministic: the standard conditions PLUS the
16
+ // recorded verdict); accepted → verification row + settle_work_claim in ONE txn;
17
+ // rejected → rejected verification row + cell.reopen_rejected_task (R8)
18
+ // → the verification task itself settles under the OPERATOR seat (the review's acceptance
19
+ // is itself non-author — a2a's shape, all the way down).
20
+ //
21
+ // Shallowness, stated on purpose: the deterministic bar checks the verdict's PRESENCE and
22
+ // PROVENANCE; the judgment quality is the engine's, and the linked traces exist precisely so
23
+ // that judgment stays auditable.
24
+
25
+ import crypto from 'node:crypto';
26
+ import path from 'node:path';
27
+ import { createRequire } from 'node:module';
28
+ import { spawnSync } from 'node:child_process';
29
+
30
+ import { createOatheTools } from './mcp/oathe-tools.mjs';
31
+ import { projectorFor, renderEvidenceView, sliceForTask } from './atif.mjs';
32
+ import { verificationTaskId, isVerificationTask, ACCEPTANCE_CLAUSE_KEY } from './plans.mjs';
33
+ import { RECORDED_VERDICT_CHECKER } from './runtime/discharge.mjs';
34
+
35
+ const require = createRequire(import.meta.url);
36
+
37
+ const VERDICTS = ['accepted', 'rejected'];
38
+
39
+ export class VerifierError extends Error {
40
+ constructor(code, message, details = {}) {
41
+ super(message);
42
+ this.name = 'VerifierError';
43
+ this.code = code;
44
+ this.details = details;
45
+ }
46
+ }
47
+
48
+ export class Verifier {
49
+ /**
50
+ * @param {{substrate: import('./substrate.mjs').Substrate, paths: object, workspace: string,
51
+ * config: import('./config.mjs').OatheConfig, operatorPrincipal: string,
52
+ * engineRunner?: ({engine, prompt}) => Promise<{verdict: string, reason: string}>}} o
53
+ */
54
+ constructor({ substrate, paths, workspace, config, operatorPrincipal, engineRunner, provider = null }) {
55
+ this.substrate = substrate;
56
+ this.paths = paths;
57
+ this.workspace = workspace;
58
+ this.config = config;
59
+ this.operatorPrincipal = operatorPrincipal;
60
+ this.verifierPrincipal = config.get('verifierPrincipal');
61
+ this.engineRunner = engineRunner ?? defaultEngineRunner;
62
+ this.orgId = config.get('org');
63
+ this.provider = provider;
64
+ this.tools = createOatheTools({
65
+ client: substrate,
66
+ identity: {
67
+ orgId: this.orgId,
68
+ principalId: this.verifierPrincipal,
69
+ department: 'verification',
70
+ },
71
+ workspace,
72
+ config,
73
+ });
74
+ this.pool = null;
75
+ this.runtime = null;
76
+ }
77
+
78
+ async #runtime() {
79
+ if (this.runtime) return this.runtime;
80
+ const provider = this.provider
81
+ ?? (await import('./runtime/provider.mjs')).resolveRuntimeProvider({
82
+ config: this.config, paths: this.paths });
83
+ const pg = require('pg');
84
+ this.pool = new pg.Pool(this.substrate.connectionConfig());
85
+ this.runtime = await provider.acceptanceRuntime({ pool: this.pool, orgId: this.orgId });
86
+ return this.runtime;
87
+ }
88
+
89
+ /** The latest completion statement for a task — the assertion under judgment. */
90
+ async #completionStatement(taskId) {
91
+ const { rows } = await this.substrate.query(
92
+ `SELECT statement_id, work_claim_id, claim_principal, execution_actor, evidence_refs, proposition
93
+ FROM cell.agent_statement
94
+ WHERE org_id = $1 AND task_id = $2 AND statement_type = 'completion'
95
+ ORDER BY asserted_at DESC LIMIT 1`,
96
+ [this.orgId, taskId]);
97
+ if (rows.length === 0) {
98
+ throw new VerifierError('OATHE_NO_COMPLETION',
99
+ `'${taskId}' has no completion statement — nothing was asserted, nothing to verify`, { taskId });
100
+ }
101
+ return rows[0];
102
+ }
103
+
104
+ /**
105
+ * Linked traces (C1 statements), projected to ATIF at read time — fan-out embedded,
106
+ * validated. Contract/projection failures REFUSE loudly (TraceContractError/AtifError):
107
+ * never less evidence than the claim recorded.
108
+ */
109
+ async #traceEvidence(workClaimId) {
110
+ const { rows } = await this.substrate.query(
111
+ `SELECT subject_ref, evidence_refs FROM cell.agent_statement
112
+ WHERE org_id = $1 AND work_claim_id = $2 AND subject_ref LIKE 'trace:%'`,
113
+ [this.orgId, workClaimId]);
114
+ const traces = [];
115
+ for (const row of rows) {
116
+ for (const file of row.evidence_refs) {
117
+ traces.push({ path: file, trajectory: projectorFor(file).project(file) });
118
+ }
119
+ }
120
+ return traces;
121
+ }
122
+
123
+ #prompt({ taskRow, completion, traces, taskId }) {
124
+ const budget = this.config.get('verifierEvidenceBudget');
125
+ const perTrace = Math.max(1, Math.floor(budget / Math.max(1, traces.length)));
126
+ return [
127
+ 'You are a verification agent. Judge ONE question: do the recorded ACTIONS and OUTCOMES',
128
+ 'support the completion assertion? In the trace views below, SAID lines are the agent\'s',
129
+ 'own claims; CLAIM lines are its on-the-record speech acts; DID lines are the actions it',
130
+ 'actually took; GOT lines are what actually came back. Judge claims against actions and',
131
+ 'outcomes — be strict: absence of evidence is absence.',
132
+ '',
133
+ `TASK: ${taskId}`,
134
+ `OBJECTIVE: ${taskRow.objective}`,
135
+ `VERIFICATION PLAN: ${JSON.stringify(taskRow.verification_plan)}`,
136
+ `COMPLETION ASSERTION: ${completion.proposition}`,
137
+ `ASSERTED EVIDENCE: ${JSON.stringify(completion.evidence_refs)}`,
138
+ '',
139
+ `SESSION TRACES (${traces.length}, sliced to this task's claim intervals where recorded):`,
140
+ ...traces.map(({ trajectory }) => renderEvidenceView(sliceForTask(trajectory, taskId), { budget: perTrace })),
141
+ '',
142
+ 'Reply with ONLY a JSON object, no other text:',
143
+ '{"verdict": "accepted" | "rejected", "reason": "<one sentence naming the evidence>"}',
144
+ ].join('\n');
145
+ }
146
+
147
+ /**
148
+ * The whole lane for one obligation.
149
+ * @param {{taskId: string, engine?: string}} o taskId = the ORIGINAL task (or its verify: task)
150
+ */
151
+ async verify({ taskId, engine: engineOverride }) {
152
+ const verificationTask = isVerificationTask(taskId) ? taskId : verificationTaskId(taskId);
153
+ const originalTask = verificationTask.slice('verify:'.length);
154
+
155
+ const { rows: vtaskRows } = await this.substrate.query(
156
+ 'SELECT objective, verification_plan FROM cell.task WHERE org_id = $1 AND task_id = $2',
157
+ [this.orgId, verificationTask]);
158
+ if (vtaskRows.length === 0) {
159
+ throw new VerifierError('OATHE_NOTHING_TO_VERIFY',
160
+ `no verification task '${verificationTask}' on the board — has '${originalTask}' been `
161
+ + 'asserted done (oathe done) at all?', { taskId });
162
+ }
163
+ const engine = engineOverride ?? vtaskRows[0].verification_plan?.verifier_engine
164
+ ?? this.config.get('verifier');
165
+
166
+ // 1. Claim the review — the verifier principal takes visible responsibility for it.
167
+ const vclaim = await this.tools.oathe_claim({ task_id: verificationTask });
168
+
169
+ // 2. The record under judgment.
170
+ const completion = await this.#completionStatement(originalTask);
171
+ const { rows: taskRows } = await this.substrate.query(
172
+ 'SELECT objective, verification_plan FROM cell.task WHERE org_id = $1 AND task_id = $2',
173
+ [this.orgId, originalTask]);
174
+ const traces = await this.#traceEvidence(completion.work_claim_id);
175
+
176
+ // 3. One engine run — fresh context, different eyes. The verdict must be exact.
177
+ const raw = await this.engineRunner({
178
+ engine,
179
+ prompt: this.#prompt({ taskRow: taskRows[0], completion, traces, taskId: originalTask }),
180
+ });
181
+ if (!raw || !VERDICTS.includes(raw.verdict) || typeof raw.reason !== 'string' || raw.reason.trim() === '') {
182
+ throw new VerifierError('OATHE_VERDICT_MALFORMED',
183
+ `the ${engine} engine returned ${JSON.stringify(raw)} — a verdict is exactly `
184
+ + `{verdict: ${VERDICTS.join('|')}, reason} and the lane never guesses`, { raw, engine });
185
+ }
186
+
187
+ // 4. The verdict becomes durable: the verification task's completion statement.
188
+ const verdictRef = `verdict:${raw.verdict}:${originalTask}`;
189
+ const done = await this.tools.oathe_done({
190
+ task_id: verificationTask,
191
+ proposition: `${raw.verdict}: ${raw.reason}`,
192
+ evidence_ref: verdictRef,
193
+ });
194
+
195
+ // 5. Settle the ORIGINAL claim — deterministic lane, verifier seat, FC010-clean.
196
+ const { SETTLE, laneFor } = await this.#runtime();
197
+ const tracePath = traces[0]?.path ?? `statement:${done.statement_id}`;
198
+ const lane = laneFor(this.verifierPrincipal);
199
+ const statementFor = (stmt) => ({
200
+ statement_ref: stmt.statement_id,
201
+ work_claim_id: stmt.work_claim_id,
202
+ evidence_refs: stmt.evidence_refs,
203
+ trace_ref: tracePath,
204
+ kind: 'completion',
205
+ statement_type: 'completion',
206
+ });
207
+ const clauseFor = (task, plan, stmt, extra = {}) => ({
208
+ org_id: this.orgId,
209
+ task_id: task,
210
+ clause_key: ACCEPTANCE_CLAUSE_KEY,
211
+ verification_plan: plan,
212
+ author_principal: stmt.claim_principal,
213
+ executor_principal: stmt.execution_actor,
214
+ seat_principal: null,
215
+ evidence_refs: [verdictRef],
216
+ trace_ref: tracePath,
217
+ privacy_class: 'org_internal',
218
+ transfer_scope: 'org_internal',
219
+ ...extra,
220
+ });
221
+ const outcome = await lane.verify({
222
+ agent_statement: statementFor(completion),
223
+ task_id: originalTask,
224
+ clause: clauseFor(originalTask, taskRows[0].verification_plan, completion,
225
+ { checker: RECORDED_VERDICT_CHECKER, oathe_recorded_verdict: raw.verdict }),
226
+ }, { settle: SETTLE.CLAIM });
227
+
228
+ if (outcome.verification?.verdict === 'blocked' || (!outcome.settled && raw.verdict === 'accepted')) {
229
+ throw new VerifierError('OATHE_SETTLEMENT_BLOCKED',
230
+ `the acceptance lane did not settle an ACCEPTED verdict: ${JSON.stringify(outcome.verification)}`,
231
+ { outcome });
232
+ }
233
+
234
+ // 6. R8: a rejection reopens the work, through the evaluator lane's own verb.
235
+ if (raw.verdict === 'rejected') {
236
+ await this.substrate.query('SELECT cell.reopen_rejected_task($1, $2)', [this.orgId, originalTask]);
237
+ }
238
+
239
+ // 7. The review itself settles under the OPERATOR seat (non-author of the verdict statement).
240
+ const verdictStatement = await this.#completionStatement(verificationTask);
241
+ const operatorLane = laneFor(this.operatorPrincipal);
242
+ const reviewOutcome = await operatorLane.verify({
243
+ agent_statement: statementFor(verdictStatement),
244
+ task_id: verificationTask,
245
+ clause: clauseFor(verificationTask, vtaskRows[0].verification_plan, verdictStatement,
246
+ { checker: 'verification-clause' }),
247
+ }, { settle: SETTLE.CLAIM });
248
+ if (!reviewOutcome.settled) {
249
+ throw new VerifierError('OATHE_REVIEW_UNSETTLED',
250
+ `the verification task's own settlement failed: ${JSON.stringify(reviewOutcome.verification)}`,
251
+ { reviewOutcome });
252
+ }
253
+
254
+ return {
255
+ task_id: originalTask,
256
+ verification_task: verificationTask,
257
+ engine,
258
+ verdict: raw.verdict,
259
+ reason: raw.reason,
260
+ settled: outcome.settled === true,
261
+ reopened: raw.verdict === 'rejected',
262
+ verdict_ref: verdictRef,
263
+ verification_claim: vclaim.work_claim_id,
264
+ traces: traces.map((t) => t.path),
265
+ };
266
+ }
267
+
268
+ /** Every open verification task in this workspace's view — `oathe verify --all` sweeps them. */
269
+ async pending() {
270
+ const { sections } = await this.tools.oathe_board({});
271
+ return [...sections.open, ...sections.mine]
272
+ .filter((r) => isVerificationTask(r.task_id))
273
+ .map((r) => r.task_id);
274
+ }
275
+
276
+ async close() {
277
+ if (this.pool) await this.pool.end();
278
+ }
279
+ }
280
+
281
+ /** The real engine runner: one headless run, strict JSON out. Refusals are typed and loud. */
282
+ export async function defaultEngineRunner({ engine, prompt, env = process.env, model = null }) {
283
+ const commands = {
284
+ claude: ['claude', ['-p', prompt, '--output-format', 'json', ...(model ? ['--model', model] : [])]],
285
+ codex: ['codex', ['exec', '--skip-git-repo-check', ...(model ? ['-m', model] : []), prompt]],
286
+ };
287
+ const command = commands[engine];
288
+ if (!command) {
289
+ throw new VerifierError('OATHE_ENGINE_UNKNOWN',
290
+ `no engine '${engine}' — known engines: ${Object.keys(commands).join(', ')}`, { engine });
291
+ }
292
+ const run = spawnSync(command[0], command[1], { encoding: 'utf8', env, maxBuffer: 32 * 1024 * 1024 });
293
+ if (run.error) {
294
+ throw new VerifierError('OATHE_ENGINE_MISSING',
295
+ `the '${engine}' CLI is not installed or not on PATH — verification needs a real engine `
296
+ + `(${String(run.error.message).slice(0, 120)})`, { engine });
297
+ }
298
+ if (run.status !== 0) {
299
+ throw new VerifierError('OATHE_ENGINE_FAILED',
300
+ `${engine} exited ${run.status}: ${String(run.stderr ?? '').slice(0, 300)}`, { engine, status: run.status });
301
+ }
302
+ let text = run.stdout;
303
+ if (engine === 'claude') {
304
+ try {
305
+ text = JSON.parse(run.stdout).result ?? '';
306
+ } catch {
307
+ throw new VerifierError('OATHE_ENGINE_OUTPUT_MALFORMED',
308
+ 'claude --output-format json did not return JSON', { engine });
309
+ }
310
+ }
311
+ const match = String(text).match(/\{[^{}]*"verdict"[^{}]*\}/g);
312
+ if (!match) {
313
+ throw new VerifierError('OATHE_VERDICT_MALFORMED',
314
+ `no JSON verdict found in ${engine} output: ${String(text).slice(-300)}`, { engine });
315
+ }
316
+ try {
317
+ return JSON.parse(match.at(-1));
318
+ } catch (e) {
319
+ throw new VerifierError('OATHE_VERDICT_MALFORMED',
320
+ `the ${engine} verdict JSON does not parse: ${e.message}`, { engine });
321
+ }
322
+ }
@@ -0,0 +1,47 @@
1
+ // oathe — workspace identity. Every claim minted through oathe records WHICH folder's board it
2
+ // belongs to (git-root realpath + origin-remote url when present; plain dir realpath otherwise),
3
+ // carried in the claim's contract_ref convention because adding DDL is out of scope for this
4
+ // package (the vendored cell DDL owns schema numbering — the additive workspace_ref column is the
5
+ // flagged post-episode upstream ask).
6
+
7
+ import crypto from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ /** Walk up from `dir` to the git root (the directory holding .git), or null. */
12
+ function gitRoot(dir) {
13
+ let current = dir;
14
+ for (;;) {
15
+ if (fs.existsSync(path.join(current, '.git'))) return current;
16
+ const parent = path.dirname(current);
17
+ if (parent === current) return null;
18
+ current = parent;
19
+ }
20
+ }
21
+
22
+ /** The url line of [remote "origin"] in .git/config, or null — read, not shelled. */
23
+ function originUrl(root) {
24
+ const configPath = path.join(root, '.git/config');
25
+ if (!fs.existsSync(configPath)) return null;
26
+ const lines = fs.readFileSync(configPath, 'utf8').split('\n');
27
+ let inOrigin = false;
28
+ for (const line of lines) {
29
+ const trimmed = line.trim();
30
+ if (trimmed.startsWith('[')) inOrigin = trimmed === '[remote "origin"]';
31
+ else if (inOrigin && trimmed.startsWith('url')) {
32
+ const eq = trimmed.indexOf('=');
33
+ if (eq !== -1) return trimmed.slice(eq + 1).trim();
34
+ }
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /** @returns {string} `ws-<12hex>` — stable for every path inside one workspace */
40
+ export function workspaceRef(cwd) {
41
+ const real = fs.realpathSync(cwd);
42
+ const root = gitRoot(real);
43
+ const identity = root === null
44
+ ? `dir:${real}`
45
+ : `git:${fs.realpathSync(root)}|origin:${originUrl(root) ?? ''}`;
46
+ return `ws-${crypto.createHash('sha256').update(identity).digest('hex').slice(0, 12)}`;
47
+ }
@@ -0,0 +1,312 @@
1
+ -- 001_core.sql — the cell work-spine core: task / work_claim / execution_attempt
2
+ -- and the claim-event ledger the terminals are read from.
3
+ --
4
+ -- Contract: docs/a1-cell-work-spine-contract.md §1-§2, AMENDED 2026-08-16 by
5
+ -- founder rulings R1 (ownership/attempt split), R2 (uniform assertion terminal +
6
+ -- mandatory verify_by), R3 (interrupted attempts carry outcome_status with a
7
+ -- clock), R5 (direct assignment), R7 (exclusive-only) and R8 (parent COMPLETE is
8
+ -- verification-gated, so nothing here blocks a parent's assertion).
9
+ --
10
+ -- Re-apply: idempotent (CREATE ... IF NOT EXISTS throughout).
11
+ -- Revert: DROP SCHEMA cell CASCADE;
12
+ --
13
+ -- Two standing rules for everything below:
14
+ --
15
+ -- 1. Enforcement lives HERE, not in a service. The estate's measured lesson
16
+ -- (STF-1 / migrations 0047 / 0073) is that a rule with a CLI gate and no
17
+ -- substrate trigger gets bypassed by direct publish — 23 historical
18
+ -- `verified` settles did exactly that. A rule this file does not enforce is
19
+ -- a rule whose coverage cannot be published (L9).
20
+ -- 2. Columns are NOT NULL unless the amended contract says the fact is absent.
21
+ -- Every nullable column below carries a comment naming the contract clause
22
+ -- that makes it absent, and a CHECK constraint that makes the absence
23
+ -- lawful only in that case. A nullable column with no such pairing is a
24
+ -- state the falsifiers cannot see (F2 legs a/b/c).
25
+ --
26
+ -- Constraint names are the failure vocabulary: the refusal text an operator or a
27
+ -- falsifier reads is the constraint name, so each one is written to name the
28
+ -- invariant it defends rather than the columns it happens to cover.
29
+
30
+ CREATE SCHEMA IF NOT EXISTS cell;
31
+
32
+ -- ---------------------------------------------------------------------------
33
+ -- task — work the company believes should be done (contract §1.1)
34
+ -- ---------------------------------------------------------------------------
35
+ CREATE TABLE IF NOT EXISTS cell.task (
36
+ org_id text NOT NULL,
37
+ task_id text NOT NULL,
38
+ department text NOT NULL,
39
+ origin text NOT NULL,
40
+ objective text NOT NULL,
41
+
42
+ -- The verification plan lives on the task (contract §1.1): settlement
43
+ -- predicate ownership is task-anchored. It is NOT NULL even when nothing is
44
+ -- known — an undeclared plan is recorded as plan_status 'unknown' and never
45
+ -- as an absent row, because "unknown" is a reportable epistemic status and
46
+ -- NULL is a hole a projection would have to guess about (L13).
47
+ verification_plan jsonb NOT NULL,
48
+
49
+ -- FOUNDER RULING R2: the deadline is mandatory, never optional. minutes for
50
+ -- business-consequential effects, longer explicitly for routine work. This
51
+ -- column is what makes "asserted_unverified past verify_by" a RED leg rather
52
+ -- than an opinion.
53
+ verify_by timestamptz NOT NULL,
54
+
55
+ -- FOUNDER RULING R7: exclusive is the only mode. Carried on the task because
56
+ -- the claim transaction reads the task's policy under lock before it writes.
57
+ claim_mode text NOT NULL,
58
+
59
+ -- FOUNDER RULING R5 / contract §2.3: to_principal is a real routing field.
60
+ -- NULL exactly and only for offer-based delegation, where the contract says
61
+ -- assignment is absent and the target principal CLAIMs instead. When it is
62
+ -- present the claim-or-refuse deadline is present with it — an assignment
63
+ -- with no deadline is the measured re-dispatch-forever defect.
64
+ to_principal text,
65
+ assignment_deadline timestamptz,
66
+
67
+ created_at timestamptz NOT NULL,
68
+
69
+ CONSTRAINT task_pkey PRIMARY KEY (org_id, task_id),
70
+
71
+ CONSTRAINT task_origin_is_a_declared_class
72
+ CHECK (origin IN ('enqueued', 'minted_at_claim', 'reopened')),
73
+
74
+ CONSTRAINT task_claim_mode_no_such_mode
75
+ CHECK (claim_mode = 'exclusive'),
76
+
77
+ -- The IS NOT NULL is load-bearing: a CHECK passes on NULL, so
78
+ -- `->> 'plan_status' IN (...)` alone would accept a plan with no status at
79
+ -- all — exactly the absent-plan hole this constraint exists to close.
80
+ CONSTRAINT task_verification_plan_declares_its_status
81
+ CHECK (jsonb_typeof(verification_plan) = 'object'
82
+ AND verification_plan ->> 'plan_status' IS NOT NULL
83
+ AND verification_plan ->> 'plan_status' IN ('declared', 'unknown')),
84
+
85
+ CONSTRAINT task_assignment_is_paired_with_its_deadline
86
+ CHECK ((to_principal IS NULL) = (assignment_deadline IS NULL))
87
+ );
88
+
89
+ COMMENT ON TABLE cell.task IS
90
+ 'Contract §1.1. Origin classes are first-class: claim-time minting is a '
91
+ 'shipped production origin, not an anomaly.';
92
+
93
+ -- ---------------------------------------------------------------------------
94
+ -- work_claim — one principal, one interval of RESPONSIBILITY (contract §1.2)
95
+ --
96
+ -- The R1 split, stated as a table: a work_claim is organizational, not runtime.
97
+ -- It survives Claude death, runtime death, session change, executor restart and
98
+ -- container restart; nothing in this table names a session, a runtime or a
99
+ -- heartbeat, because those live one level down in execution_attempt. A new claim
100
+ -- appears only when RESPONSIBILITY changes.
101
+ -- ---------------------------------------------------------------------------
102
+ CREATE TABLE IF NOT EXISTS cell.work_claim (
103
+ work_claim_id uuid NOT NULL,
104
+ org_id text NOT NULL,
105
+ task_id text NOT NULL,
106
+
107
+ -- contract §2.1: a delegated child claim is a full work_claim owned by a
108
+ -- DIFFERENT principal, linked here. NULL for a root claim — the absence of
109
+ -- a delegator, which is the majority case.
110
+ parent_work_claim_id uuid,
111
+
112
+ -- R-A35-23 (027_ownership_return.sql): the interval this one RESUMES.
113
+ -- SUCCESSION lineage — same work, same principal, a later interval — and
114
+ -- deliberately NOT the column above, which is DELEGATION lineage. NULL for
115
+ -- every interval that resumed nothing, which is the majority case. Stated
116
+ -- here as well as in 027's ALTER because CREATE TABLE IF NOT EXISTS does not
117
+ -- reach a database that already exists, so a fresh install and an ALTERed one
118
+ -- must be made to agree by hand.
119
+ predecessor_work_claim_id uuid,
120
+
121
+ principal_id text NOT NULL,
122
+ department text NOT NULL,
123
+
124
+ -- Claim terminals EXACTLY per contract §1.2 as amended by R1/R2:
125
+ -- completion assertion, yield-with-typed-basis, abort, takeover/reassignment,
126
+ -- organizational expiry. `orphaned` and `failed` are DELIBERATELY absent —
127
+ -- R1 moved them to execution_attempt, and accepting them here would re-merge
128
+ -- the two lifecycles this split exists to separate.
129
+ state text NOT NULL,
130
+
131
+ claim_mode text NOT NULL,
132
+ ownership_valid_until timestamptz NOT NULL,
133
+ contract_ref text NOT NULL,
134
+
135
+ -- "yield-with-typed-basis" (§1.2). Required on yield and abort; forbidden
136
+ -- while the claim is live or ended by assertion, where there is no basis to
137
+ -- state. Permitted on takeover/expiry, where the reason is useful but the
138
+ -- terminal is not the principal's own act.
139
+ terminal_basis text,
140
+
141
+ claimed_at timestamptz NOT NULL,
142
+
143
+ -- The ownership terminal stamp. NULL exactly while state = 'active'; this
144
+ -- column is what F2 leg (a) reads to call a claim past its
145
+ -- ownership_valid_until with no terminal RED.
146
+ ownership_ended_at timestamptz,
147
+
148
+ -- The two named terminals that carry their own stamp (contract §1.2/R2).
149
+ yielded_at timestamptz,
150
+ completed_at timestamptz,
151
+
152
+ -- contract §1.6: settlement is a separate fact from completion, and never
153
+ -- earlier than the end of responsibility.
154
+ settled_at timestamptz,
155
+
156
+ CONSTRAINT work_claim_pkey PRIMARY KEY (work_claim_id),
157
+
158
+ -- The org-consistent handle every child row references, so a child cannot
159
+ -- silently attach across an org boundary (PRD:1626).
160
+ CONSTRAINT work_claim_org_scoped_key UNIQUE (org_id, work_claim_id),
161
+
162
+ CONSTRAINT work_claim_task_fkey
163
+ FOREIGN KEY (org_id, task_id) REFERENCES cell.task (org_id, task_id),
164
+
165
+ CONSTRAINT work_claim_parent_fkey
166
+ FOREIGN KEY (org_id, parent_work_claim_id)
167
+ REFERENCES cell.work_claim (org_id, work_claim_id),
168
+
169
+ CONSTRAINT work_claim_predecessor_fkey
170
+ FOREIGN KEY (org_id, predecessor_work_claim_id)
171
+ REFERENCES cell.work_claim (org_id, work_claim_id),
172
+
173
+ CONSTRAINT work_claim_predecessor_is_not_itself
174
+ CHECK (predecessor_work_claim_id IS DISTINCT FROM work_claim_id),
175
+
176
+ CONSTRAINT work_claim_state_is_a_declared_claim_terminal
177
+ CHECK (state IN ('active', 'completion_asserted', 'yielded',
178
+ 'aborted', 'taken_over', 'expired')),
179
+
180
+ CONSTRAINT work_claim_claim_mode_no_such_mode
181
+ CHECK (claim_mode = 'exclusive'),
182
+
183
+ CONSTRAINT work_claim_active_claim_has_no_ownership_end
184
+ CHECK ((state = 'active') = (ownership_ended_at IS NULL)),
185
+
186
+ CONSTRAINT work_claim_yielded_at_is_the_yield_terminal
187
+ CHECK ((state = 'yielded') = (yielded_at IS NOT NULL)),
188
+
189
+ CONSTRAINT work_claim_completed_at_is_the_assertion_terminal
190
+ CHECK ((state = 'completion_asserted') = (completed_at IS NOT NULL)),
191
+
192
+ CONSTRAINT work_claim_yield_or_abort_carries_a_typed_basis
193
+ CHECK (state NOT IN ('yielded', 'aborted') OR terminal_basis IS NOT NULL),
194
+
195
+ CONSTRAINT work_claim_live_claim_has_no_typed_basis
196
+ CHECK (state NOT IN ('active', 'completion_asserted') OR terminal_basis IS NULL),
197
+
198
+ CONSTRAINT work_claim_settlement_follows_a_claim_terminal
199
+ CHECK (settled_at IS NULL
200
+ OR (state <> 'active' AND settled_at >= ownership_ended_at))
201
+ );
202
+
203
+ -- Unique active ownership (FOUNDER RULING R7), enforced beneath the claim
204
+ -- transaction rather than only inside it. The transaction is the path; this
205
+ -- index is the guarantee — it is what makes two live owners of one task
206
+ -- impossible for ANY writer, including one that never calls cell.claim_work.
207
+ -- PARTIAL by construction: terminal claims on the same task coexist without
208
+ -- limit, because claim history is durable (L12) and reclaim after a terminal is
209
+ -- a new, distinct episode.
210
+ CREATE UNIQUE INDEX IF NOT EXISTS work_claim_unique_active_ownership
211
+ ON cell.work_claim (org_id, task_id) WHERE state = 'active';
212
+
213
+ -- ---------------------------------------------------------------------------
214
+ -- execution_attempt — the disposable runtime binding beneath a claim (R1)
215
+ --
216
+ -- Everything the Mac used as a liveness proxy lives here and nowhere else. An
217
+ -- attempt dying is an attempt terminal; the claim above it does not move.
218
+ -- ---------------------------------------------------------------------------
219
+ CREATE TABLE IF NOT EXISTS cell.execution_attempt (
220
+ attempt_id uuid NOT NULL,
221
+ work_claim_id uuid NOT NULL,
222
+ org_id text NOT NULL,
223
+ runtime_id text NOT NULL,
224
+ session_id text NOT NULL,
225
+ executor_version text NOT NULL,
226
+ started_at timestamptz NOT NULL,
227
+
228
+ -- NULL exactly while the attempt is running; F2 leg (b) reads this to call
229
+ -- an attempt with no attempt terminal RED.
230
+ ended_at timestamptz,
231
+
232
+ -- Attempt terminals per contract §1.2: orphaned, failed, interrupted —
233
+ -- plus 'running' and the ordinary 'completed' end.
234
+ state text NOT NULL,
235
+
236
+ -- FOUNDER RULING R3: an INTERRUPTED attempt carries an outcome status, and
237
+ -- only an interrupted attempt does. `evidence_lost` was rejected as a
238
+ -- terminal because it mints an unobserved fact — the honest word for that
239
+ -- state is 'unknown', with a clock on it.
240
+ outcome_status text,
241
+
242
+ -- 'unknown' REQUIRES a deadline and a named resolver. Without them, unknown
243
+ -- is permanent by construction and there is no deadline for F2 leg (c) to be
244
+ -- red against. Resolution flows through the existing reconciler evaluator
245
+ -- lane — this pair names WHEN and WHO, not a new resolver species.
246
+ reconcile_by timestamptz,
247
+ resolver_principal text,
248
+
249
+ CONSTRAINT execution_attempt_pkey PRIMARY KEY (attempt_id),
250
+
251
+ CONSTRAINT execution_attempt_claim_fkey
252
+ FOREIGN KEY (org_id, work_claim_id)
253
+ REFERENCES cell.work_claim (org_id, work_claim_id),
254
+
255
+ CONSTRAINT execution_attempt_state_is_a_declared_runtime_state
256
+ CHECK (state IN ('running', 'completed', 'failed', 'orphaned', 'interrupted')),
257
+
258
+ CONSTRAINT execution_attempt_running_attempt_has_no_end
259
+ CHECK ((state = 'running') = (ended_at IS NULL)),
260
+
261
+ CONSTRAINT execution_attempt_outcome_status_is_a_declared_status
262
+ CHECK (outcome_status IS NULL
263
+ OR outcome_status IN ('known_success', 'known_failure', 'unknown')),
264
+
265
+ CONSTRAINT execution_attempt_outcome_status_is_the_interrupted_terminal
266
+ CHECK ((state = 'interrupted') = (outcome_status IS NOT NULL)),
267
+
268
+ -- IS NOT DISTINCT FROM, not '=': with a NULL outcome_status the '=' form
269
+ -- evaluates to NULL and a CHECK passes on NULL, which would leave a
270
+ -- reconciliation deadline lawful on an attempt that needs no reconciling.
271
+ CONSTRAINT execution_attempt_unknown_requires_reconcile_by
272
+ CHECK ((outcome_status IS NOT DISTINCT FROM 'unknown') = (reconcile_by IS NOT NULL)),
273
+
274
+ CONSTRAINT execution_attempt_unknown_requires_a_named_resolver
275
+ CHECK ((outcome_status IS NOT DISTINCT FROM 'unknown') = (resolver_principal IS NOT NULL))
276
+ );
277
+
278
+ CREATE INDEX IF NOT EXISTS execution_attempt_by_claim
279
+ ON cell.execution_attempt (org_id, work_claim_id, started_at);
280
+
281
+ -- ---------------------------------------------------------------------------
282
+ -- work_claim_event — terminals identified by MEANING, never by code path
283
+ --
284
+ -- MEASURED on the Mac: orphan events had three distinct producers, so "what
285
+ -- happened" could not be read off the event without knowing which code path
286
+ -- wrote it. The cell has exactly one producer per meaning; the topic vocabulary
287
+ -- is closed here, and the producer registry that enforces the other half of
288
+ -- that sentence is installed with the verb that owns each topic (002 registers
289
+ -- the claim producer).
290
+ -- ---------------------------------------------------------------------------
291
+ CREATE TABLE IF NOT EXISTS cell.work_claim_event (
292
+ event_id uuid NOT NULL,
293
+ org_id text NOT NULL,
294
+ work_claim_id uuid NOT NULL,
295
+ topic text NOT NULL,
296
+ ts timestamptz NOT NULL,
297
+ producer text NOT NULL,
298
+
299
+ CONSTRAINT work_claim_event_pkey PRIMARY KEY (event_id),
300
+
301
+ CONSTRAINT work_claim_event_claim_fkey
302
+ FOREIGN KEY (org_id, work_claim_id)
303
+ REFERENCES cell.work_claim (org_id, work_claim_id),
304
+
305
+ CONSTRAINT work_claim_event_claim_event_topic_is_a_declared_meaning
306
+ CHECK (topic IN ('work_claim.claimed', 'work_claim.completion_asserted',
307
+ 'work_claim.yielded', 'work_claim.aborted',
308
+ 'work_claim.taken_over', 'work_claim.expired'))
309
+ );
310
+
311
+ CREATE INDEX IF NOT EXISTS work_claim_event_by_claim
312
+ ON cell.work_claim_event (org_id, work_claim_id, ts);