@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,320 @@
1
+ -- 010_parent_child_verification.sql — R8: the parent's VERIFICATION is child-gated.
2
+ --
3
+ -- Contract: docs/a1-cell-work-spine-contract.md §2.2, FOUNDER RULING R8
4
+ -- (2026-08-16). Requires 001_core.sql, 003_verification.sql and
5
+ -- 008_effect_receipt.sql (the mid-effect hold reads unresolved receipts).
6
+ --
7
+ -- Re-apply: idempotent (CREATE ... IF NOT EXISTS / OR REPLACE).
8
+ -- Revert: DROP SCHEMA cell CASCADE; (this file installs nothing outside it)
9
+ --
10
+ -- THE RULING, AND THE LINE IT DRAWS
11
+ --
12
+ -- "The parent's completion assertion is NEVER structurally blocked — an
13
+ -- assertion is an agent_statement, and blocking statements is the abolished
14
+ -- modal pattern — but the parent's VERIFICATION requires its delegated
15
+ -- children settled by default: the parent's acceptance checker refuses while
16
+ -- a child's verification is missing, and an early-asserting parent sits
17
+ -- `asserted_unverified` under its own verify_by clock, visibly."
18
+ --
19
+ -- Nothing in this file touches the statement path. That is deliberate and it is
20
+ -- half the ruling: the measured cost of blocking an assertion is the 8h04m
21
+ -- modal-block incident, and the cost of NOT gating the verification is that
22
+ -- delegation launders an unverified result into a verified one — the parent says
23
+ -- "done", somebody verifies the parent, and the work actually delegated was
24
+ -- never checked by anyone.
25
+ --
26
+ -- THE WIND-DOWN IS NOT A CASCADE
27
+ --
28
+ -- Child claims are owned by their own principals (R1). Parent YIELD leaves
29
+ -- children untouched, because the reopened parent's next claimant resumes
30
+ -- waiting on the same edges. Parent ABORT records a typed retraction ADDRESSED
31
+ -- TO the child's principal, who winds down via decline or yield with the
32
+ -- retraction as the typed basis. This file therefore records the retraction and
33
+ -- moves nothing: a substrate that ended the child's claim here would be the
34
+ -- hard-kill cascade the ruling refuses, wearing a typed name.
35
+ --
36
+ -- Declared failure vocabulary added by this file (SQLSTATE class FC):
37
+ -- FC050 PARENT_VERIFICATION_CHILD_UNVERIFIED a parent verified while a
38
+ -- delegated child is unverified
39
+ -- FC051 RETRACTION_WITHOUT_PARENT_ABORT a retraction with no abort behind it
40
+ -- FC052 CHILD_RETRACTION_MID_EFFECT a child told to stand down while
41
+ -- holding an unresolved receipt
42
+ -- FC053 RETRACTION_NOT_MY_CHILD a retraction addressed to somebody
43
+ -- else's delegate
44
+ -- FC054 PARENT_CLAIM_UNKNOWN the acceptance checker was asked
45
+ -- about a claim that does not exist
46
+
47
+ -- ---------------------------------------------------------------------------
48
+ -- v_parent_child_verification — one row per delegated child, with its verdict
49
+ --
50
+ -- The parent's TASK travels with the parent's claim, because delegation edges
51
+ -- outlive the claim episode that created them. A child is linked to the specific
52
+ -- parent CLAIM it was delegated under (§2.1), but R8 says parent YIELD leaves
53
+ -- children untouched "because the reopened parent's next claimant resumes
54
+ -- waiting on the same edges" — so the lineage the gate walks is the parent
55
+ -- TASK's, and every claim episode of that task sees the same children.
56
+ -- ---------------------------------------------------------------------------
57
+ CREATE OR REPLACE VIEW cell.v_parent_child_verification AS
58
+ SELECT
59
+ parent.org_id,
60
+ parent.work_claim_id AS parent_work_claim_id,
61
+ child.work_claim_id AS child_work_claim_id,
62
+ child.principal_id AS child_principal,
63
+ child.task_id AS child_task_id,
64
+ c.completion AS child_completion,
65
+ (c.completion = 'complete') AS child_verified,
66
+ -- Appended rather than placed beside parent_work_claim_id where it reads
67
+ -- best: CREATE OR REPLACE VIEW may only ADD columns at the end, and this
68
+ -- file's declared re-apply contract is idempotence over an installed cell.
69
+ parent.task_id AS parent_task_id
70
+ FROM cell.work_claim parent
71
+ JOIN cell.work_claim child
72
+ ON child.org_id = parent.org_id
73
+ AND child.parent_work_claim_id = parent.work_claim_id
74
+ JOIN cell.v_task_completion c
75
+ ON c.org_id = child.org_id AND c.task_id = child.task_id;
76
+
77
+ COMMENT ON VIEW cell.v_parent_child_verification IS
78
+ 'Contract §2.2 / R8. MEASURED: zero historical events carry '
79
+ 'parent_work_claim_id — this is forward contract, not history reconstruction.';
80
+
81
+ -- ------------------------------------------ the check the acceptance path consults
82
+ --
83
+ -- A verb in its own right, not a rule reachable only by attempting a write: §2.2
84
+ -- says "the parent's acceptance checker refuses while a child's verification is
85
+ -- missing", and the checker has to be able to ASK.
86
+ --
87
+ -- Returns the number of delegated children, all of them verified. Zero children
88
+ -- returns 0 and raises nothing — the gate must not become a tax on undelegated
89
+ -- work. A claim id that names no claim RAISES: "0 children, all verified" is a
90
+ -- clean bill of health, and issuing one about work the company has no record of
91
+ -- is an error that looks like success.
92
+ --
93
+ -- The lineage walked is the parent TASK's, not the single claim episode's. R8:
94
+ -- "parent YIELD leaves children untouched, because the reopened parent's next
95
+ -- claimant resumes waiting on the SAME EDGES." Children stay linked to the claim
96
+ -- episode they were delegated under and nothing re-links them, so a gate keyed to
97
+ -- the asserting claim's own id forgets every delegated child the instant the
98
+ -- parent yields — and the next claimant verifies straight through.
99
+ CREATE OR REPLACE FUNCTION cell.assert_children_verified(
100
+ p_org_id text,
101
+ p_work_claim_id uuid
102
+ )
103
+ RETURNS integer
104
+ LANGUAGE plpgsql
105
+ STABLE
106
+ AS $children$
107
+ DECLARE
108
+ v_parent_task text;
109
+ v_unverified text;
110
+ v_total integer;
111
+ BEGIN
112
+ SELECT task_id INTO v_parent_task
113
+ FROM cell.work_claim
114
+ WHERE org_id = p_org_id AND work_claim_id = p_work_claim_id;
115
+
116
+ IF NOT FOUND THEN
117
+ RAISE EXCEPTION
118
+ 'PARENT_CLAIM_UNKNOWN:%/% — no claim by that identity exists in this '
119
+ 'org, so it has no task, no delegation lineage, and nothing this '
120
+ 'checker could truthfully report about. Answering 0 here would be an '
121
+ 'acceptance checker issuing a clean bill of health about work the '
122
+ 'company has no record of.',
123
+ p_org_id, p_work_claim_id
124
+ USING ERRCODE = 'FC054';
125
+ END IF;
126
+
127
+ SELECT string_agg(v.child_work_claim_id::text || ' (' || v.child_principal ||
128
+ ', ' || v.child_completion || ')', ', '
129
+ ORDER BY v.child_work_claim_id)
130
+ INTO v_unverified
131
+ FROM cell.v_parent_child_verification v
132
+ WHERE v.org_id = p_org_id
133
+ AND v.parent_task_id = v_parent_task
134
+ AND NOT v.child_verified;
135
+
136
+ IF v_unverified IS NOT NULL THEN
137
+ RAISE EXCEPTION
138
+ 'PARENT_VERIFICATION_CHILD_UNVERIFIED:% — these delegated children are '
139
+ 'not verified: %. FOUNDER RULING R8: the parent''s ASSERTION is never '
140
+ 'blocked, but its VERIFICATION requires its delegated children settled. '
141
+ 'Verifying the parent here would launder an unverified result into a '
142
+ 'verified one — the delegated work would be the only part nobody checked.',
143
+ p_work_claim_id, v_unverified
144
+ USING ERRCODE = 'FC050';
145
+ END IF;
146
+
147
+ SELECT count(*)::integer INTO v_total
148
+ FROM cell.v_parent_child_verification v
149
+ WHERE v.org_id = p_org_id AND v.parent_task_id = v_parent_task;
150
+
151
+ RETURN v_total;
152
+ END;
153
+ $children$;
154
+
155
+ -- The same check, on the write path. A rule the acceptance checker consults but
156
+ -- the substrate does not enforce is a rule with a bypass (the §4.3 lesson,
157
+ -- applied one level up).
158
+ --
159
+ -- EVERY `verified` verdict is gated, whatever type of statement it hangs on. The
160
+ -- gate deliberately does NOT narrow to `statement_type = 'completion'`:
161
+ -- v_task_completion (003_verification.sql) counts any `verified` row naming a
162
+ -- declared plan clause and never looks at the type of the statement underneath
163
+ -- it, so a completion-only gate is walked around by attaching the same verdict to
164
+ -- a `result` statement under the same claim. The parent then projects `complete`
165
+ -- with its delegated child unverified — the exact laundering R8 prohibits, and it
166
+ -- releases the R4 task-type dependency edges gated on that parent.
167
+ --
168
+ -- A `rejected` or `indeterminate` verdict stays ungated: those are information
169
+ -- the cell wants recorded, and gating them would mean the only verdict a
170
+ -- delegating parent could ever receive is silence.
171
+ CREATE OR REPLACE FUNCTION cell.enforce_parent_verification_is_child_gated()
172
+ RETURNS trigger
173
+ LANGUAGE plpgsql
174
+ AS $child_gate$
175
+ DECLARE
176
+ v_work_claim_id uuid;
177
+ BEGIN
178
+ IF NEW.result <> 'verified' THEN
179
+ RETURN NEW;
180
+ END IF;
181
+
182
+ SELECT work_claim_id INTO v_work_claim_id
183
+ FROM cell.agent_statement
184
+ WHERE statement_id = NEW.statement_id;
185
+
186
+ IF NOT FOUND THEN
187
+ -- Not a tolerated absence: verification_statement_fkey is the authority
188
+ -- on whether the named statement exists, and it refuses this row at the
189
+ -- end of the statement with the FK's own message. Raising a second,
190
+ -- competing refusal here would report a delegation problem for what is a
191
+ -- dangling reference.
192
+ RETURN NEW;
193
+ END IF;
194
+
195
+ PERFORM cell.assert_children_verified(NEW.org_id, v_work_claim_id);
196
+ RETURN NEW;
197
+ END;
198
+ $child_gate$;
199
+
200
+ CREATE OR REPLACE TRIGGER verification_is_child_gated
201
+ BEFORE INSERT OR UPDATE ON cell.verification
202
+ FOR EACH ROW EXECUTE FUNCTION cell.enforce_parent_verification_is_child_gated();
203
+
204
+ -- ---------------------------------------------------------------------------
205
+ -- child_retraction — the typed retraction a parent ABORT sends to its children
206
+ --
207
+ -- What this table is NOT: an instruction the substrate carries out. It records
208
+ -- that the parent withdrew, addressed to the child's principal, who winds down
209
+ -- via decline or yield with this retraction as the typed basis (§1.2's
210
+ -- yield-with-typed-basis). Nothing here moves the child's claim.
211
+ -- ---------------------------------------------------------------------------
212
+ CREATE TABLE IF NOT EXISTS cell.child_retraction (
213
+ retraction_id uuid NOT NULL,
214
+ org_id text NOT NULL,
215
+ parent_work_claim_id uuid NOT NULL,
216
+ child_work_claim_id uuid NOT NULL,
217
+ basis text NOT NULL,
218
+
219
+ -- L13: the retraction carries its own evidence, exactly as §4.4's dependency
220
+ -- retraction does. "The parent withdrew" is a claim about the world and the
221
+ -- child's principal is entitled to the reference.
222
+ evidence_refs jsonb NOT NULL,
223
+
224
+ ts timestamptz NOT NULL,
225
+
226
+ CONSTRAINT child_retraction_pkey PRIMARY KEY (retraction_id),
227
+
228
+ CONSTRAINT child_retraction_parent_fkey
229
+ FOREIGN KEY (org_id, parent_work_claim_id)
230
+ REFERENCES cell.work_claim (org_id, work_claim_id),
231
+
232
+ CONSTRAINT child_retraction_child_fkey
233
+ FOREIGN KEY (org_id, child_work_claim_id)
234
+ REFERENCES cell.work_claim (org_id, work_claim_id),
235
+
236
+ CONSTRAINT child_retraction_basis_is_a_declared_basis
237
+ CHECK (basis IN ('parent_aborted', 'parent_withdrawn')),
238
+
239
+ CONSTRAINT child_retraction_carries_addressable_evidence
240
+ CHECK (jsonb_typeof(evidence_refs) = 'array'
241
+ AND jsonb_array_length(evidence_refs) > 0),
242
+
243
+ CONSTRAINT child_retraction_is_not_addressed_to_the_parent_itself
244
+ CHECK (child_work_claim_id <> parent_work_claim_id)
245
+ );
246
+
247
+ CREATE INDEX IF NOT EXISTS child_retraction_by_child
248
+ ON cell.child_retraction (org_id, child_work_claim_id, ts);
249
+
250
+ CREATE OR REPLACE FUNCTION cell.enforce_child_retraction_preconditions()
251
+ RETURNS trigger
252
+ LANGUAGE plpgsql
253
+ AS $retraction$
254
+ DECLARE
255
+ v_parent_state text;
256
+ v_child_parent uuid;
257
+ v_receipt text;
258
+ BEGIN
259
+ SELECT state INTO v_parent_state
260
+ FROM cell.work_claim
261
+ WHERE org_id = NEW.org_id AND work_claim_id = NEW.parent_work_claim_id;
262
+
263
+ IF v_parent_state IS DISTINCT FROM 'aborted' THEN
264
+ RAISE EXCEPTION
265
+ 'RETRACTION_WITHOUT_PARENT_ABORT:% — the parent claim is ''%'', not '
266
+ '''aborted''. R8: parent YIELD leaves children UNTOUCHED, because the '
267
+ 'reopened parent''s next claimant resumes waiting on the same edges. '
268
+ 'Only abort or withdrawal sends a retraction; recording one for a yield '
269
+ 'tells a principal to stand down from work that is about to resume.',
270
+ NEW.parent_work_claim_id, coalesce(v_parent_state, '<no such claim>')
271
+ USING ERRCODE = 'FC051';
272
+ END IF;
273
+
274
+ SELECT parent_work_claim_id INTO v_child_parent
275
+ FROM cell.work_claim
276
+ WHERE org_id = NEW.org_id AND work_claim_id = NEW.child_work_claim_id;
277
+
278
+ IF v_child_parent IS DISTINCT FROM NEW.parent_work_claim_id THEN
279
+ RAISE EXCEPTION
280
+ 'RETRACTION_NOT_MY_CHILD:% — this claim''s parent is %, not %. A '
281
+ 'retraction addressed to somebody else''s delegate is an instruction to '
282
+ 'stand down from work this parent never delegated.',
283
+ NEW.child_work_claim_id, coalesce(v_child_parent::text, '<none>'),
284
+ NEW.parent_work_claim_id
285
+ USING ERRCODE = 'FC053';
286
+ END IF;
287
+
288
+ -- R3/R6 discipline, applied identically: a mid-effect child resolves its
289
+ -- receipts first. Telling a principal to stand down mid-effect is how an
290
+ -- irreversible effect ends up with nobody left to reconcile it.
291
+ SELECT receipt_key INTO v_receipt
292
+ FROM cell.effect_receipt
293
+ WHERE org_id = NEW.org_id
294
+ AND work_claim_id = NEW.child_work_claim_id
295
+ AND outcome = 'claimed'
296
+ ORDER BY claimed_at
297
+ LIMIT 1;
298
+
299
+ IF FOUND THEN
300
+ RAISE EXCEPTION
301
+ 'CHILD_RETRACTION_MID_EFFECT:% — this child holds an unresolved effect '
302
+ 'receipt (%). R8 with R3/R6: a mid-effect child resolves its receipts '
303
+ 'first. Standing it down now leaves an irreversible effect claimed and '
304
+ 'nobody responsible for reconciling it.',
305
+ NEW.child_work_claim_id, v_receipt
306
+ USING ERRCODE = 'FC052';
307
+ END IF;
308
+
309
+ RETURN NEW;
310
+ END;
311
+ $retraction$;
312
+
313
+ CREATE OR REPLACE TRIGGER child_retraction_meets_its_preconditions
314
+ BEFORE INSERT OR UPDATE ON cell.child_retraction
315
+ FOR EACH ROW EXECUTE FUNCTION cell.enforce_child_retraction_preconditions();
316
+
317
+ COMMENT ON TABLE cell.child_retraction IS
318
+ 'R8: parent ABORT sends a TYPED RETRACTION to its children — never a '
319
+ 'hard-kill cascade. This table records the withdrawal; the child''s own '
320
+ 'principal winds down with it as the typed basis.';
@@ -0,0 +1,288 @@
1
+ -- 011_confirm.sql — the confirm token: the operator verification case 4 waits on.
2
+ --
3
+ -- Contract: docs/a1-cell-work-spine-contract.md §1.4 source 3 (the consume is a
4
+ -- verification, state_version-bound; a REJECT consume is a verification with
5
+ -- result='rejected'; a NULL-verdict consume projects `indeterminate`, never
6
+ -- approve) and §5 case 4 (restart neither re-mints the ask nor double-consumes;
7
+ -- the claim resumes against the already-recorded verification).
8
+ -- Requires 001_core.sql (the task this ask hangs off).
9
+ --
10
+ -- Re-apply: idempotent (CREATE ... IF NOT EXISTS / OR REPLACE).
11
+ -- Revert: DROP SCHEMA cell CASCADE; (this file installs nothing outside it)
12
+ --
13
+ -- WHAT THIS FILE IS AND IS NOT
14
+ --
15
+ -- It is the minimal confirm-token-shaped substrate the `C4-*` bake-off legs
16
+ -- assert over: one canonical ask, one state-version-bound consume, one derived
17
+ -- projection. It is deliberately NOT the operator surface — nothing here renders
18
+ -- a prompt, routes a page, or decides who may answer. Those live above it, and
19
+ -- the point of putting the token here is that a restart, a redeploy or a killed
20
+ -- executor changes none of it.
21
+ --
22
+ -- The verification record itself is 003_verification.sql's
23
+ -- `source='confirm_token_consume'` row. This file holds the ASK and the CONSUME;
24
+ -- the evaluator lane writes the verification against them. Keeping the two apart
25
+ -- is what makes "recv is a wake-up, confirm_tokens is truth" expressible: a
26
+ -- waiter that woke up learns nothing until it re-reads this table.
27
+ --
28
+ -- FOUR MEASURED LESSONS, MADE STRUCTURAL
29
+ --
30
+ -- 1. ONE TOKEN PER CANONICAL ASK, FOREVER. `UNIQUE (org_id, ask_key)` carries no
31
+ -- predicate. A partial index on `state = 'issued'` would open a window in
32
+ -- which re-asking one question is lawful, and a restart landing in that window
33
+ -- leaves an operator staring at two prompts for one decision — after which the
34
+ -- second consume approves something already approved once.
35
+ --
36
+ -- 2. THE STATED WAIT COVERS THE TOKEN'S OWN LIFE. `wait_timeout_s` is mandatory
37
+ -- and is checked against the TTL. That is `CONFIRM_WAIT_ABANDONED` made
38
+ -- structural: the measured trap is an executor whose `recv` gives up after a
39
+ -- default 60 seconds nobody wrote down, while the ask it was waiting on
40
+ -- remains answerable for an hour. A waiter that abandons a live decision has
41
+ -- not timed out; it has dropped the decision on the floor.
42
+ --
43
+ -- 3. EXPIRY IS DERIVED AT AN EXPLICIT INSTANT, NEVER STORED. There is no
44
+ -- `expired` state. A stored expiry needs a reaper, and between reaper runs the
45
+ -- column reads as authoritative while being wrong — the same defect shape as
46
+ -- the Mac's transcript-mtime liveness proxy. `cell.expired_confirm_tokens(at)`
47
+ -- is the shape `cell.unverified_past_verify_by` already uses.
48
+ --
49
+ -- 4. A NULL VERDICT PROJECTS `indeterminate`. MEASURED: 217 NULL-verdict rows in
50
+ -- the estate. `verdict` is nullable for exactly that case — the contract's
51
+ -- §1.4 clause 3 names it — and the projection is a VIEW so that no reader gets
52
+ -- to decide for itself what a missing verdict meant. Deciding it locally is
53
+ -- how a non-decision becomes an approval (L13).
54
+ --
55
+ -- Declared failure vocabulary added by this file (SQLSTATE class FC):
56
+ -- FC060 CONFIRM_TOKEN_NO_SUCH_TOKEN a consume against an ask never minted
57
+ -- FC061 CONFIRM_TOKEN_ALREADY_CONSUMED the double consume / the race loser
58
+ -- FC062 CONFIRM_TOKEN_EXPIRED a consume past the ask's own life
59
+ -- FC063 CONFIRM_STATE_VERSION_STALE the 0073 analog: an approval bound to
60
+ -- a state that has since moved
61
+ -- FC064 CONFIRM_CONSUME_REFUSED the CAS admitted nothing and none of
62
+ -- the named reasons applied
63
+
64
+ -- ---------------------------------------------------------------------------
65
+ -- confirm_token — one canonical ask, one answer
66
+ -- ---------------------------------------------------------------------------
67
+ CREATE TABLE IF NOT EXISTS cell.confirm_token (
68
+ token_id uuid NOT NULL,
69
+ org_id text NOT NULL,
70
+ task_id text NOT NULL,
71
+
72
+ -- The canonical ask. Everything that makes this question THIS question:
73
+ -- restart, redeploy and re-entry all derive the same key, which is why
74
+ -- re-minting is a uniqueness violation rather than a policy check.
75
+ ask_key text NOT NULL,
76
+
77
+ state text NOT NULL,
78
+
79
+ -- §1.4 clause 3 / the 0073 lesson: an approval is an approval OF something.
80
+ -- The consume must name the same version, or it approved a different world.
81
+ state_version bigint NOT NULL,
82
+
83
+ -- The wait this ask binds its waiter to, stated in the substrate. Mandatory
84
+ -- because the alternative is the executor's own undeclared default, and the
85
+ -- bake-off exists to stop measuring those.
86
+ wait_timeout_s numeric NOT NULL,
87
+
88
+ issued_at timestamptz NOT NULL,
89
+ expires_at timestamptz NOT NULL,
90
+
91
+ -- NULL exactly while the token is unconsumed.
92
+ consumed_at timestamptz,
93
+ consumed_by text,
94
+
95
+ -- NULL on an unconsumed token, and NULL on a consumed one is the MEASURED
96
+ -- null-verdict shape the contract names (§1.4 clause 3): an operator closed
97
+ -- the ask without recording a verdict. It projects `indeterminate`.
98
+ verdict text,
99
+
100
+ CONSTRAINT confirm_token_pkey PRIMARY KEY (token_id),
101
+
102
+ CONSTRAINT confirm_token_task_fkey
103
+ FOREIGN KEY (org_id, task_id) REFERENCES cell.task (org_id, task_id),
104
+
105
+ -- Lesson 1, as an index rather than as a habit.
106
+ CONSTRAINT confirm_token_one_token_per_canonical_ask UNIQUE (org_id, ask_key),
107
+
108
+ CONSTRAINT confirm_token_state_is_a_declared_state
109
+ CHECK (state IN ('issued', 'consumed')),
110
+
111
+ CONSTRAINT confirm_token_verdict_is_a_declared_verdict
112
+ CHECK (verdict IS NULL OR verdict IN ('approve', 'reject')),
113
+
114
+ CONSTRAINT confirm_token_consumed_token_names_its_operator_and_instant
115
+ CHECK ((state = 'consumed')
116
+ = (consumed_at IS NOT NULL AND consumed_by IS NOT NULL)),
117
+
118
+ CONSTRAINT confirm_token_only_a_consumed_token_carries_a_verdict
119
+ CHECK (state = 'consumed' OR verdict IS NULL),
120
+
121
+ CONSTRAINT confirm_token_expires_after_it_is_issued
122
+ CHECK (expires_at > issued_at),
123
+
124
+ CONSTRAINT confirm_token_stated_wait_is_positive
125
+ CHECK (wait_timeout_s > 0),
126
+
127
+ -- Lesson 2. The waiter may wait longer than the ask lives — that is how it
128
+ -- observes the expiry and escalates. It may never wait less.
129
+ CONSTRAINT confirm_token_stated_wait_covers_the_token_ttl
130
+ CHECK (wait_timeout_s >= EXTRACT(EPOCH FROM (expires_at - issued_at)))
131
+ );
132
+
133
+ COMMENT ON TABLE cell.confirm_token IS
134
+ 'Contract §1.4 clause 3. recv is a wake-up; this table is truth — a waiter '
135
+ 'that woke up has learned nothing until it re-reads the row.';
136
+
137
+ CREATE INDEX IF NOT EXISTS confirm_token_by_task
138
+ ON cell.confirm_token (org_id, task_id, state);
139
+
140
+ -- ---------------------------------------------------------------------------
141
+ -- cell.consume_confirm_token — the CAS that admits exactly one operator
142
+ --
143
+ -- The admission test IS the UPDATE's WHERE clause: the transition out of
144
+ -- `issued` happens once, under the row lock Postgres already takes, and every
145
+ -- other caller re-evaluates the predicate against the committed row and matches
146
+ -- nothing. Diagnosis happens only AFTER the CAS has declined, so the refusal
147
+ -- names what was actually true rather than what was true when we looked first.
148
+ -- ---------------------------------------------------------------------------
149
+ CREATE OR REPLACE FUNCTION cell.consume_confirm_token(
150
+ p_org_id text,
151
+ p_token_id uuid,
152
+ p_consumed_by text,
153
+ p_state_version bigint,
154
+ p_verdict text,
155
+ p_at timestamptz
156
+ )
157
+ RETURNS void
158
+ LANGUAGE plpgsql
159
+ AS $consume$
160
+ DECLARE
161
+ v_token cell.confirm_token%ROWTYPE;
162
+ v_updated integer;
163
+ BEGIN
164
+ UPDATE cell.confirm_token
165
+ SET state = 'consumed',
166
+ consumed_at = p_at,
167
+ consumed_by = p_consumed_by,
168
+ verdict = p_verdict
169
+ WHERE org_id = p_org_id
170
+ AND token_id = p_token_id
171
+ AND state = 'issued'
172
+ AND state_version = p_state_version
173
+ AND p_at < expires_at;
174
+
175
+ GET DIAGNOSTICS v_updated = ROW_COUNT;
176
+ IF v_updated = 1 THEN
177
+ RETURN;
178
+ END IF;
179
+
180
+ SELECT * INTO v_token
181
+ FROM cell.confirm_token
182
+ WHERE org_id = p_org_id AND token_id = p_token_id;
183
+
184
+ IF NOT FOUND THEN
185
+ RAISE EXCEPTION
186
+ 'CONFIRM_TOKEN_NO_SUCH_TOKEN:%/% — there is no ask with this id in '
187
+ 'this org. A consume against a token nobody minted is an approval '
188
+ 'with no question behind it.',
189
+ p_org_id, p_token_id
190
+ USING ERRCODE = 'FC060';
191
+
192
+ ELSIF v_token.state = 'consumed' THEN
193
+ RAISE EXCEPTION
194
+ 'CONFIRM_TOKEN_ALREADY_CONSUMED:% — % answered this ask at %. One '
195
+ 'canonical ask has one answer: a restart resumes against the '
196
+ 'recorded consume (§5 case 4), it never consumes again.',
197
+ p_token_id, v_token.consumed_by, v_token.consumed_at
198
+ USING ERRCODE = 'FC061';
199
+
200
+ ELSIF p_at >= v_token.expires_at THEN
201
+ RAISE EXCEPTION
202
+ 'CONFIRM_TOKEN_EXPIRED:% — the ask expired at % and the consume is '
203
+ 'stamped %. The honest outcome is a typed yield and an escalation to '
204
+ 'the assigner; an approve minted here would be an approval nobody '
205
+ 'gave.',
206
+ p_token_id, v_token.expires_at, p_at
207
+ USING ERRCODE = 'FC062';
208
+
209
+ ELSIF v_token.state_version <> p_state_version THEN
210
+ RAISE EXCEPTION
211
+ 'CONFIRM_STATE_VERSION_STALE:% — the ask was minted against state '
212
+ 'version %, the consume names %. An approval is an approval OF '
213
+ 'something (the 0073 lesson); binding it to a version that has since '
214
+ 'moved approves a different world than the operator saw.',
215
+ p_token_id, v_token.state_version, p_state_version
216
+ USING ERRCODE = 'FC063';
217
+
218
+ ELSE
219
+ -- Unreachable by construction, and loud rather than silent for exactly
220
+ -- that reason: if the CAS declines for a reason this function cannot
221
+ -- name, the predicate and the diagnosis have drifted apart, and a
222
+ -- silent RETURN would report a consume that never happened.
223
+ RAISE EXCEPTION
224
+ 'CONFIRM_CONSUME_REFUSED:% — the CAS admitted no row and none of the '
225
+ 'declared reasons (no such token, already consumed, expired, stale '
226
+ 'version) applies. The admission predicate and this diagnosis have '
227
+ 'drifted apart.',
228
+ p_token_id
229
+ USING ERRCODE = 'FC064';
230
+ END IF;
231
+ END;
232
+ $consume$;
233
+
234
+ -- ---------------------------------------------------------------------------
235
+ -- cell.v_confirm_verdict — what a token PROJECTS, decided in one place
236
+ --
237
+ -- `indeterminate` is the answer for a consumed token with no verdict, and it is
238
+ -- computed here so that no reader can reach its own conclusion about what a
239
+ -- missing verdict meant. 217 rows in the estate are exactly this shape.
240
+ -- ---------------------------------------------------------------------------
241
+ CREATE OR REPLACE VIEW cell.v_confirm_verdict AS
242
+ SELECT
243
+ t.token_id,
244
+ t.org_id,
245
+ t.task_id,
246
+ t.ask_key,
247
+ t.state,
248
+ t.state_version,
249
+ t.consumed_by,
250
+ t.consumed_at,
251
+ CASE
252
+ WHEN t.state <> 'consumed' THEN 'unconsumed'
253
+ WHEN t.verdict = 'approve' THEN 'verified'
254
+ WHEN t.verdict = 'reject' THEN 'rejected'
255
+ ELSE 'indeterminate'
256
+ END AS projects
257
+ FROM cell.confirm_token t;
258
+
259
+ COMMENT ON VIEW cell.v_confirm_verdict IS
260
+ 'Contract §1.4 clause 3: a NULL-verdict consume projects indeterminate, '
261
+ 'never approve (MEASURED: 217 rows; L13).';
262
+
263
+ -- ---------------------------------------------------------------------------
264
+ -- cell.expired_confirm_tokens — expiry, read at an instant the caller states
265
+ --
266
+ -- No stored `expired` state and no reaper. A consumed token is never reported:
267
+ -- it was answered, and paging an operator about a decision they already made is
268
+ -- how an alert lane loses its readers.
269
+ -- ---------------------------------------------------------------------------
270
+ CREATE OR REPLACE FUNCTION cell.expired_confirm_tokens(p_at timestamptz)
271
+ RETURNS TABLE (
272
+ token_id uuid,
273
+ org_id text,
274
+ task_id text,
275
+ ask_key text,
276
+ issued_at timestamptz,
277
+ expires_at timestamptz,
278
+ overdue_by interval
279
+ )
280
+ LANGUAGE sql
281
+ STABLE
282
+ AS $expired$
283
+ SELECT t.token_id, t.org_id, t.task_id, t.ask_key, t.issued_at,
284
+ t.expires_at, p_at - t.expires_at
285
+ FROM cell.confirm_token t
286
+ WHERE t.state = 'issued'
287
+ AND p_at >= t.expires_at;
288
+ $expired$;