@oathe/oathe 0.0.1 → 0.2.0

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 (70) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +7 -0
  3. package/README.md +99 -12
  4. package/assets/oathe-hero.svg +92 -0
  5. package/bin/oathe.mjs +376 -0
  6. package/docs/PRIVACY.md +45 -0
  7. package/package.json +32 -23
  8. package/plugin/.claude-plugin/plugin.json +10 -0
  9. package/plugin/.mcp.json +13 -0
  10. package/plugin/hooks/frame-note.mjs +24 -0
  11. package/plugin/hooks/heartbeat.mjs +49 -0
  12. package/plugin/hooks/hooks.json +39 -0
  13. package/plugin/hooks/lib.mjs +83 -0
  14. package/plugin/hooks/render-board.mjs +11 -0
  15. package/plugin/skills/oathe-work/SKILL.md +33 -0
  16. package/src/atif.mjs +633 -0
  17. package/src/blocks.mjs +192 -0
  18. package/src/board-render.mjs +106 -0
  19. package/src/config.mjs +169 -0
  20. package/src/context.mjs +35 -0
  21. package/src/doctor.mjs +108 -0
  22. package/src/harness.mjs +271 -0
  23. package/src/init.mjs +92 -0
  24. package/src/launch-env.mjs +25 -0
  25. package/src/launch.mjs +259 -0
  26. package/src/manifest.mjs +89 -0
  27. package/src/mcp/oathe-tools.mjs +517 -0
  28. package/src/paths.mjs +49 -0
  29. package/src/plans.mjs +50 -0
  30. package/src/runtime/discharge.mjs +57 -0
  31. package/src/runtime/provider.mjs +154 -0
  32. package/src/runtime/simple-cage.mjs +67 -0
  33. package/src/runtime/sql-acceptance-lane.mjs +89 -0
  34. package/src/session-host.mjs +81 -0
  35. package/src/substrate.mjs +337 -0
  36. package/src/successor.mjs +31 -0
  37. package/src/traces.mjs +242 -0
  38. package/src/uninstall.mjs +45 -0
  39. package/src/verifier.mjs +322 -0
  40. package/src/workspace.mjs +47 -0
  41. package/vendor/ddl/001_core.sql +312 -0
  42. package/vendor/ddl/002_claim.sql +438 -0
  43. package/vendor/ddl/003_verification.sql +480 -0
  44. package/vendor/ddl/004_delegation.sql +397 -0
  45. package/vendor/ddl/005_escalation.sql +303 -0
  46. package/vendor/ddl/006_dependency.sql +384 -0
  47. package/vendor/ddl/007_assignment.sql +502 -0
  48. package/vendor/ddl/008_effect_receipt.sql +290 -0
  49. package/vendor/ddl/009_verified_edge.sql +452 -0
  50. package/vendor/ddl/010_parent_child_verification.sql +320 -0
  51. package/vendor/ddl/011_confirm.sql +288 -0
  52. package/vendor/ddl/012_evaluator_lane.sql +444 -0
  53. package/vendor/ddl/013_claim_terminal.sql +279 -0
  54. package/vendor/ddl/014_claim_settlement.sql +327 -0
  55. package/vendor/ddl/015_claim_yield.sql +213 -0
  56. package/vendor/ddl/016_reopened_reclaim.sql +285 -0
  57. package/vendor/ddl/017_claim_yield_causes.sql +357 -0
  58. package/vendor/ddl/018_receiptless_unknown.sql +249 -0
  59. package/vendor/ddl/019_verification_contract_freeze.sql +335 -0
  60. package/vendor/ddl/020_context_compilation.sql +105 -0
  61. package/vendor/ddl/021_execution_attempt_closure.sql +95 -0
  62. package/vendor/ddl/022_verification_clause.sql +106 -0
  63. package/vendor/ddl/023_executor_role.sql +66 -0
  64. package/vendor/ddl/024_executor_role_hardening.sql +439 -0
  65. package/vendor/ddl/025_running_attempt_uniqueness.sql +102 -0
  66. package/vendor/ddl/026_acceptance_authority.sql +230 -0
  67. package/vendor/ddl/027_ownership_return.sql +836 -0
  68. package/vendor/ddl/028_attempt_bind_ownership.sql +173 -0
  69. package/vendor/ddl/manifest.json +183 -0
  70. package/index.js +0 -33
@@ -0,0 +1,438 @@
1
+ -- 002_claim.sql — the claim transaction, and the two halves of one-producer-per-
2
+ -- meaning: the guard on the claim-meaning EVENT, and the guard on the terminal
3
+ -- ROW whose meaning no verb produces.
4
+ --
5
+ -- Contract: docs/a1-cell-work-spine-contract.md §1.2, FOUNDER RULING R7
6
+ -- ("enforced inside the claim transaction: lock task policy -> insert claim row
7
+ -- -> emit claim event, atomically; any other value is a validation error
8
+ -- NO_SUCH_MODE"). Requires 001_core.sql.
9
+ --
10
+ -- Re-apply: idempotent (CREATE OR REPLACE FUNCTION / TRIGGER, ON CONFLICT seed).
11
+ -- Revert: DROP SCHEMA cell CASCADE; (this file installs nothing outside it)
12
+ --
13
+ -- WHY THIS IS A DATABASE FUNCTION AND NOT APPLICATION CODE
14
+ --
15
+ -- Unique active ownership must hold for every writer, not only for writers that
16
+ -- remembered to call the library. MEASURED on the Mac: `realClaimTask` had three
17
+ -- bypasses, and 23 `verified` settles reached the bus by direct publish past a
18
+ -- CLI-only gate. A claim path expressed as a Postgres function plus a partial
19
+ -- unique index has no "past" — the lock, the check, the row and the event are
20
+ -- one transaction on the server, and a caller that skips the function still
21
+ -- meets the index (001_core.sql).
22
+ --
23
+ -- WHY THE LOCK IS ON THE TASK ROW
24
+ --
25
+ -- Read-committed visibility is not enough on its own: two claimants can each
26
+ -- observe "no active claim" in their own snapshot. SELECT ... FOR UPDATE on the
27
+ -- task's policy row serializes the claimants against each other, so the second
28
+ -- one re-reads AFTER the first has committed and refuses with a typed error
29
+ -- rather than colliding on the index with an untyped 23505. The index remains as
30
+ -- the guarantee; the lock is what makes the refusal legible.
31
+
32
+ -- ---------------------------------------------------------------------------
33
+ -- Declared failure vocabulary (SQLSTATE class FC — outside every class Postgres
34
+ -- assigns). The message prefix and the SQLSTATE carry the SAME invariant name,
35
+ -- so a caller can key on either and an operator reading the log sees the rule.
36
+ -- FC001 CLAIM_UNKNOWN_TASK claim against work the company has no record of
37
+ -- FC002 NO_SUCH_MODE any claim_mode but 'exclusive' (R7)
38
+ -- FC003 WORK_ALREADY_CLAIMED a live owner already holds this task
39
+ -- FC004 CLAIM_EVENT_FOREIGN_PRODUCER a claim-meaning event from a foreign writer
40
+ -- FC005 CLAIM_EVENT_UNREGISTERED_MEANING a claim-meaning event on a topic no
41
+ -- verb has been registered to produce
42
+ -- FC006 CLAIM_TERMINAL_HAS_NO_DECLARED_WRITER a claim moved into a terminal
43
+ -- state that no verb in the cell writes
44
+ -- ---------------------------------------------------------------------------
45
+ --
46
+ -- The two codes above ARE ONE RULE IN TWO HALVES, and they share this file's block
47
+ -- for that reason rather than opening one of their own. Checkpoint annex eff9796
48
+ -- §E.2, absorbed at design §8 addition 2, measured the hole as a single
49
+ -- sentence: for `work_claim.aborted`, `.taken_over` and `.expired` a session
50
+ -- could forge BOTH the meaning event AND the terminal row, so 015's argument
51
+ -- that a forged terminal "can still reach the ROW but can never reach the
52
+ -- MEANING" was true of two terminals out of five. Closing one half would have
53
+ -- left the sentence false and the other half open.
54
+ --
55
+ -- The alternative considered and rejected: a fresh file with its own block, the
56
+ -- way 028 takes one for the attempt-bind guard. 028's subject is a DIFFERENT
57
+ -- table with DIFFERENT writers; this one's subject is the same claim vocabulary
58
+ -- this file already owns, and splitting it would put the two halves of one rule
59
+ -- in two migrations for a reviewer to reassemble.
60
+ --
61
+ -- RETIREMENT CONDITION for both: a verb that writes any of the three terminals,
62
+ -- registered in cell.claim_event_producer as that meaning's producer. DELETION
63
+ -- OWNER: whoever lands it, in the same change. PHASE: W4's FC-D/FC-E grid, which
64
+ -- is where FOUNDER CHECKPOINT FC-E sits.
65
+
66
+ -- --------------------------------------------------------- producer registry
67
+ --
68
+ -- contract §1.2: terminals are identified by event MEANING (topic), never by
69
+ -- producing code path — MEASURED, the Mac's orphan events had three distinct
70
+ -- producers. The cell has exactly one producer per meaning, and this table is
71
+ -- where that sentence is checkable rather than asserted.
72
+ --
73
+ -- L8 (dated bridge), RETIRED 2026-08-25 — see the guard below. Only the meanings
74
+ -- whose verb has landed are registered: `work_claim.claimed` here,
75
+ -- `work_claim.completion_asserted` by 013 and `work_claim.yielded` by 017. The
76
+ -- bridge used to be the GUARD's, which answered a registry miss with `RETURN NEW`
77
+ -- while the remaining terminal verbs were pending. That is closed: an
78
+ -- unregistered meaning is now refused (FC005), so the three verbless terminals
79
+ -- are unwritable as MEANINGS by anybody until W4's FC-E grid says what writes
80
+ -- them. Retirement condition for the registry itself is unchanged: the
81
+ -- claim-terminal verbs of contract §1.2 all present in this table.
82
+ CREATE TABLE IF NOT EXISTS cell.claim_event_producer (
83
+ topic text NOT NULL,
84
+ producer text NOT NULL,
85
+
86
+ CONSTRAINT claim_event_producer_pkey PRIMARY KEY (topic),
87
+
88
+ CONSTRAINT claim_event_producer_topic_is_a_declared_meaning
89
+ CHECK (topic IN ('work_claim.claimed', 'work_claim.completion_asserted',
90
+ 'work_claim.yielded', 'work_claim.aborted',
91
+ 'work_claim.taken_over', 'work_claim.expired'))
92
+ );
93
+
94
+ INSERT INTO cell.claim_event_producer (topic, producer)
95
+ VALUES ('work_claim.claimed', 'cell.claim_work')
96
+ ON CONFLICT (topic) DO UPDATE SET producer = EXCLUDED.producer;
97
+
98
+ -- ------------------------------------------------------ the writer signal
99
+ --
100
+ -- "Which verb is writing this row" — the signal every governed-writer guard in
101
+ -- the cell reads, here once because two answers to that question is two answers
102
+ -- to the question the whole guard family exists to have one answer to.
103
+ --
104
+ -- It is the PL/pgSQL CALL STACK, and it used to be a transaction-local setting
105
+ -- (`cell.event_producer`, `cell.registrar`, `cell.settling_evaluator`). That was
106
+ -- forgeable: a setting is transaction-local, not privileged, so ANY session could
107
+ -- type `set_config('cell.settling_evaluator', '<the registered evaluator>', true)`
108
+ -- before a direct UPDATE and satisfy the guard that exists to refuse exactly that
109
+ -- write. MEASURED in review: the verified edge settled and a second
110
+ -- `work_claim.claimed` event landed, both past guards whose comments claimed the
111
+ -- writer was checked. The three settings are DELETED in the same change (L5).
112
+ --
113
+ -- The stack is not forgeable by typing: a caller cannot put a frame on it that is
114
+ -- not there. Fabricating one would mean CREATEing a function of that
115
+ -- schema-qualified name, which needs CREATE on schema `cell` — owner authority,
116
+ -- and an owner already has every authority these guards are about.
117
+ --
118
+ -- `strpos` rather than LIKE deliberately: every verb name in the cell contains
119
+ -- underscores, and `_` is a LIKE wildcard — a LIKE-based check would accept
120
+ -- `cell.settleXverified_edge`.
121
+ CREATE OR REPLACE FUNCTION cell.written_by(p_verb text)
122
+ RETURNS boolean
123
+ LANGUAGE plpgsql
124
+ STABLE
125
+ AS $written_by$
126
+ DECLARE
127
+ v_stack text;
128
+ BEGIN
129
+ GET DIAGNOSTICS v_stack = PG_CONTEXT;
130
+ RETURN strpos(v_stack, 'PL/pgSQL function ' || p_verb || '(') > 0;
131
+ END;
132
+ $written_by$;
133
+
134
+ COMMENT ON FUNCTION cell.written_by IS
135
+ 'The cell''s one writer signal: is the named governed verb on this trigger''s '
136
+ 'PL/pgSQL call stack. Replaces three transaction-local settings that any '
137
+ 'session could set, and therefore forge.';
138
+
139
+ -- The guard. A direct INSERT — from psql, from a script, from any service that
140
+ -- learned the table name — cannot present itself as the registered producer,
141
+ -- because the registered producer's frame is either on the call stack or it is
142
+ -- not. Matching the `producer` column alone would be forgeable by typing the
143
+ -- right string; so, as it turned out, was matching a settable GUC.
144
+ CREATE OR REPLACE FUNCTION cell.enforce_one_producer_per_meaning()
145
+ RETURNS trigger
146
+ LANGUAGE plpgsql
147
+ AS $enforce$
148
+ DECLARE
149
+ v_registered text;
150
+ v_running text;
151
+ BEGIN
152
+ SELECT producer INTO v_registered
153
+ FROM cell.claim_event_producer
154
+ WHERE topic = NEW.topic;
155
+
156
+ IF NOT FOUND THEN
157
+ -- REGISTER-OR-REFUSE (F4, 2026-08-25). This used to `RETURN NEW`: a
158
+ -- meaning whose verb had not landed was bounded by 001's topic
159
+ -- vocabulary and nothing else. MEASURED consequence (design §8, addition
160
+ -- 2): `work_claim.aborted`, `.taken_over` and `.expired` have NO
161
+ -- registered producer, so a session could forge BOTH the terminal row
162
+ -- and its meaning event, and 015's argument that a forged terminal "can
163
+ -- reach the ROW but can never reach the MEANING" was true of two
164
+ -- terminals out of five.
165
+ --
166
+ -- The guard must DECIDE rather than defer: an unregistered topic is
167
+ -- exactly the case where nobody can say what the event means, and a
168
+ -- trigger that waved it through was the widest hole in the terminal
169
+ -- vocabulary. The three verbless terminals get their meanings back the
170
+ -- day a verb registers as their producer — which is FC-E's question and
171
+ -- W4's grid, not this file's.
172
+ --
173
+ -- ENUMERATED EXEMPTIONS AT LANDING: none. No declared meaning in
174
+ -- 001_core.sql's vocabulary legitimately has no producer, so the
175
+ -- exemption list is empty and says so; an unenumerated miss is a refusal.
176
+ --
177
+ -- The refusal names the REGISTRY as what is missing, which is true of
178
+ -- every topic 001's vocabulary declares. A topic outside that vocabulary
179
+ -- meets this refusal first — a BEFORE trigger runs ahead of a CHECK — and
180
+ -- work_claim_event_claim_event_topic_is_a_declared_meaning is still the
181
+ -- layer beneath it, unchanged and still the guarantee for any writer that
182
+ -- could reach the table around this trigger. The same rule is asserted at
183
+ -- its own home in tests/test_core_schema.py: a producer cannot be
184
+ -- registered for a meaning the vocabulary does not declare.
185
+ RAISE EXCEPTION
186
+ 'CLAIM_EVENT_UNREGISTERED_MEANING:% — no verb is registered to '
187
+ 'produce the meaning ''%''. Terminals are identified by MEANING and '
188
+ 'the cell has exactly one producer per meaning (contract §1.2); an '
189
+ 'event nobody is registered to write is an event no reader can '
190
+ 'attribute, and accepting it is how a forged terminal reaches the '
191
+ 'ledger. Register the producing verb in cell.claim_event_producer in '
192
+ 'the migration that introduces it.',
193
+ NEW.topic, NEW.topic
194
+ USING ERRCODE = 'FC005';
195
+ END IF;
196
+
197
+ IF cell.written_by(v_registered) THEN
198
+ v_running := v_registered;
199
+ ELSE
200
+ v_running := NULL;
201
+ END IF;
202
+
203
+ IF v_running IS DISTINCT FROM v_registered
204
+ OR NEW.producer IS DISTINCT FROM v_registered THEN
205
+ RAISE EXCEPTION
206
+ 'CLAIM_EVENT_FOREIGN_PRODUCER:%:% — the meaning ''%'' has exactly one '
207
+ 'registered producer (%), and this row was not written by it. '
208
+ 'Terminals are identified by meaning, never by code path: a second '
209
+ 'writer of this topic makes the event unreadable without knowing who '
210
+ 'wrote it.',
211
+ NEW.topic, coalesce(v_running, '<no producer in this transaction>'),
212
+ NEW.topic, v_registered
213
+ USING ERRCODE = 'FC004';
214
+ END IF;
215
+
216
+ RETURN NEW;
217
+ END;
218
+ $enforce$;
219
+
220
+ CREATE OR REPLACE TRIGGER work_claim_event_one_producer_per_meaning
221
+ BEFORE INSERT ON cell.work_claim_event
222
+ FOR EACH ROW EXECUTE FUNCTION cell.enforce_one_producer_per_meaning();
223
+
224
+ -- --------------------------------------------- the ROW half of the same rule
225
+ --
226
+ -- Contract §1.2 declares six claim states. Three of them — `aborted`,
227
+ -- `taken_over`, `expired` — are written by NO VERB (FOUNDER CHECKPOINT FC-E),
228
+ -- and until one exists there is no lawful road into them. This guard is that
229
+ -- sentence made true: the transition is refused for EVERY writer, with no
230
+ -- `cell.written_by` exemption, because naming a verb here would be naming one
231
+ -- that does not exist.
232
+ --
233
+ -- BEFORE UPDATE, and only the TRANSITION, which is the same two scopes 013's
234
+ -- completion guard (:83-88) and 014's settlement guard (:83-88) carry and for
235
+ -- the same stated reason: `cell.claim_work` always mints `active`, so every
236
+ -- terminal a LIVE cell reaches is reached by UPDATE, while an INSERT of an
237
+ -- already-terminal row is a SCENE declaring history rather than a writer
238
+ -- performing one. A row that ALREADY holds one of the three may still be written
239
+ -- for reasons that are not about its terminal.
240
+ --
241
+ -- MEASURED consequence, recorded rather than discovered later: this makes
242
+ -- 010_parent_child_verification.sql's child-retraction lane unenterable, because
243
+ -- its precondition (`010:259-272`) is a parent at `aborted`. That lane was
244
+ -- ALREADY dead — annex §E.2 measured every insert raising FC051 today, for the
245
+ -- same reason one level down — so this does not close a road; it makes the
246
+ -- closed road say so at the first step instead of the second.
247
+ CREATE OR REPLACE FUNCTION cell.enforce_verbless_terminal_has_no_writer()
248
+ RETURNS trigger
249
+ LANGUAGE plpgsql
250
+ AS $verbless_terminal$
251
+ BEGIN
252
+ IF NEW.state IS NOT DISTINCT FROM OLD.state
253
+ OR NEW.state NOT IN ('aborted', 'taken_over', 'expired') THEN
254
+ RETURN NEW;
255
+ END IF;
256
+
257
+ RAISE EXCEPTION
258
+ 'CLAIM_TERMINAL_HAS_NO_DECLARED_WRITER:%:% — no verb in the cell writes '
259
+ 'the ''%'' terminal, so there is no lawful road into it and this write '
260
+ 'has no author to be accountable to. Contract §1.2 declares six claim '
261
+ 'states and the cell has one producer per meaning; three of the six have '
262
+ 'no producer at all, which is FOUNDER CHECKPOINT FC-E and W4''s to rule '
263
+ 'on. Until a verb lands and registers as that meaning''s producer, a '
264
+ 'session that could write this row would be relieving a principal of '
265
+ 'work for a reason the company does not hold — and, because the meaning '
266
+ 'event is refused too (FC005), would leave a terminal no reader can '
267
+ 'attribute.',
268
+ NEW.work_claim_id, NEW.state, NEW.state
269
+ USING ERRCODE = 'FC006';
270
+ END;
271
+ $verbless_terminal$;
272
+
273
+ CREATE OR REPLACE TRIGGER work_claim_verbless_terminal_has_no_writer
274
+ BEFORE UPDATE ON cell.work_claim
275
+ FOR EACH ROW EXECUTE FUNCTION cell.enforce_verbless_terminal_has_no_writer();
276
+
277
+ -- ------------------------------------------------------- the claim transaction
278
+ --
279
+ -- Every argument is required. There is no default in this signature and there
280
+ -- will not be one: a default claim_mode, a default ownership window or a
281
+ -- server-generated identifier would each be a policy decision made in the
282
+ -- substrate, invisible at the call site, and unreachable by the config object
283
+ -- that is supposed to hold every such decision.
284
+ --
285
+ -- `p_predecessor_work_claim_id` (R-A35-23, added by 027_ownership_return.sql) is
286
+ -- SUCCESSION lineage — the interval this claim RESUMES — and it has no default
287
+ -- for the same reason nothing else here does. The eleven-argument form is
288
+ -- DROPped by 027 in the same change (L5) rather than left beside this one: an
289
+ -- overload would be two claim paths, and a caller that kept the old shape would
290
+ -- write successor claims carrying no provenance at all.
291
+ --
292
+ -- Nothing in this signature carries a comment BETWEEN its parameters, and that
293
+ -- is load-bearing rather than tidy: the runtime's ONE-CLOCK standing leg derives
294
+ -- each verb's instant POSITIONS by parsing this list, and a comment inside it
295
+ -- shifts every position after it (MEASURED, this change).
296
+ CREATE OR REPLACE FUNCTION cell.claim_work(
297
+ p_org_id text,
298
+ p_task_id text,
299
+ p_work_claim_id uuid,
300
+ p_parent_work_claim_id uuid,
301
+ p_predecessor_work_claim_id uuid,
302
+ p_principal_id text,
303
+ p_department text,
304
+ p_claim_mode text,
305
+ p_ownership_valid_until timestamptz,
306
+ p_contract_ref text,
307
+ p_claimed_at timestamptz,
308
+ p_event_id uuid
309
+ )
310
+ RETURNS uuid
311
+ LANGUAGE plpgsql
312
+ AS $claim_work$
313
+ DECLARE
314
+ v_task_claim_mode text;
315
+ v_holder text;
316
+ v_holder_claim uuid;
317
+ v_constraint text;
318
+ BEGIN
319
+ -- 1. lock the task's policy row. Claimants of the same task serialize here.
320
+ SELECT claim_mode INTO v_task_claim_mode
321
+ FROM cell.task
322
+ WHERE org_id = p_org_id AND task_id = p_task_id
323
+ FOR UPDATE;
324
+
325
+ IF NOT FOUND THEN
326
+ RAISE EXCEPTION
327
+ 'CLAIM_UNKNOWN_TASK:%/% — no task by that identity exists in this org, '
328
+ 'so there is nothing to take responsibility for. A claim never mints '
329
+ 'the work it claims.',
330
+ p_org_id, p_task_id
331
+ USING ERRCODE = 'FC001';
332
+ END IF;
333
+
334
+ -- 2. mode. FOUNDER RULING R7: exclusive is the only mode there is. Both the
335
+ -- caller's declared mode and the task's recorded policy are checked, so a
336
+ -- task carrying some other policy cannot be claimed by asking politely.
337
+ IF p_claim_mode IS DISTINCT FROM 'exclusive'
338
+ OR v_task_claim_mode IS DISTINCT FROM 'exclusive' THEN
339
+ RAISE EXCEPTION
340
+ 'NO_SUCH_MODE:% — claim_mode ''exclusive'' is the only mode the cell '
341
+ 'has (task policy is ''%''). max_active_claims was deferred for want '
342
+ 'of any measured workload demanding it; a second mode is a founder '
343
+ 'ruling, not a parameter.',
344
+ coalesce(p_claim_mode, '<null>'), coalesce(v_task_claim_mode, '<null>')
345
+ USING ERRCODE = 'FC002';
346
+ END IF;
347
+
348
+ -- 3. unique active ownership. Re-read under the lock: the winner of a race
349
+ -- has committed by the time a loser reaches this statement.
350
+ SELECT principal_id, work_claim_id INTO v_holder, v_holder_claim
351
+ FROM cell.work_claim
352
+ WHERE org_id = p_org_id AND task_id = p_task_id AND state = 'active';
353
+
354
+ IF FOUND THEN
355
+ RAISE EXCEPTION
356
+ 'WORK_ALREADY_CLAIMED:%/% — principal % holds an active claim (%) on '
357
+ 'this work. Responsibility passes by a claim terminal — yield, abort, '
358
+ 'takeover, reassignment or organizational expiry — never by a second '
359
+ 'claimant arriving.',
360
+ p_org_id, p_task_id, v_holder, v_holder_claim
361
+ USING ERRCODE = 'FC003';
362
+ END IF;
363
+
364
+ -- 4. the claim row: an interval of RESPONSIBILITY. No session, no runtime,
365
+ -- no heartbeat — those belong to the execution attempts beneath it (R1).
366
+ --
367
+ -- The handler is not a fallback, it is the SAME refusal reached by the
368
+ -- other road. Step 3's re-read uses the TRANSACTION's snapshot, so at
369
+ -- REPEATABLE READ or SERIALIZABLE — where the snapshot predates the
370
+ -- winner's commit — the task row is locked but unmodified, no
371
+ -- serialization failure fires, and the loser sees no active claim. It
372
+ -- then collides with the partial unique index instead: uniqueness still
373
+ -- holds, but the caller gets an untyped 23505 rather than the declared
374
+ -- FC003, and a caller keying on the rule sees a broken substrate. An
375
+ -- executor's own transaction machinery may run this claim at an elevated
376
+ -- isolation level, so the typed refusal is made to hold there too rather
377
+ -- than at READ COMMITTED alone. (At SERIALIZABLE the conflict arrives as
378
+ -- a 40001 serialization failure instead, which is retryable and is NOT a
379
+ -- refusal — the Python face gives it its own type.)
380
+ --
381
+ -- ONLY the unique-active-ownership index is translated. Any other
382
+ -- unique_violation — a reused work_claim_id, say — is a different fact
383
+ -- and is re-raised untouched.
384
+ BEGIN
385
+ INSERT INTO cell.work_claim (
386
+ work_claim_id, org_id, task_id, parent_work_claim_id,
387
+ predecessor_work_claim_id, principal_id,
388
+ department, state, claim_mode, ownership_valid_until, contract_ref,
389
+ terminal_basis, claimed_at, ownership_ended_at, yielded_at, completed_at,
390
+ settled_at
391
+ ) VALUES (
392
+ p_work_claim_id, p_org_id, p_task_id, p_parent_work_claim_id,
393
+ p_predecessor_work_claim_id, p_principal_id,
394
+ p_department, 'active', p_claim_mode, p_ownership_valid_until, p_contract_ref,
395
+ NULL, p_claimed_at, NULL, NULL, NULL,
396
+ NULL
397
+ );
398
+ EXCEPTION WHEN unique_violation THEN
399
+ GET STACKED DIAGNOSTICS v_constraint = CONSTRAINT_NAME;
400
+ IF v_constraint IS DISTINCT FROM 'work_claim_unique_active_ownership' THEN
401
+ RAISE;
402
+ END IF;
403
+
404
+ SELECT principal_id, work_claim_id INTO v_holder, v_holder_claim
405
+ FROM cell.work_claim
406
+ WHERE org_id = p_org_id AND task_id = p_task_id AND state = 'active';
407
+
408
+ RAISE EXCEPTION
409
+ 'WORK_ALREADY_CLAIMED:%/% — principal % holds an active claim (%) on '
410
+ 'this work. Responsibility passes by a claim terminal — yield, abort, '
411
+ 'takeover, reassignment or organizational expiry — never by a second '
412
+ 'claimant arriving. (Reached through the unique-ownership index rather '
413
+ 'than the re-read: this transaction''s snapshot predates the winner''s '
414
+ 'commit, which is what an isolation level above READ COMMITTED means.)',
415
+ p_org_id, p_task_id, coalesce(v_holder, '<committed after this snapshot>'),
416
+ coalesce(v_holder_claim::text, '<committed after this snapshot>')
417
+ USING ERRCODE = 'FC003';
418
+ END;
419
+
420
+ -- 5. the claim event, in the SAME transaction. A claim visible as an event
421
+ -- but not as a row (or the reverse) is the split-brain this shape exists
422
+ -- to make impossible. Nothing is set to authorize this write: THIS frame,
423
+ -- on the call stack, is the authorization, and it stops existing when the
424
+ -- function returns — so nothing later in the transaction inherits the
425
+ -- authority to write the meaning, without anybody having to remember to
426
+ -- clear a setting.
427
+ INSERT INTO cell.work_claim_event (event_id, org_id, work_claim_id, topic, ts, producer)
428
+ VALUES (p_event_id, p_org_id, p_work_claim_id, 'work_claim.claimed', p_claimed_at,
429
+ 'cell.claim_work');
430
+
431
+ RETURN p_work_claim_id;
432
+ END;
433
+ $claim_work$;
434
+
435
+ COMMENT ON FUNCTION cell.claim_work IS
436
+ 'The one path by which a principal takes responsibility for work. Locks the '
437
+ 'task policy row, refuses any mode but exclusive (R7) and any second live '
438
+ 'owner, then writes the claim row and its claim-meaning event atomically.';