Repository navigation
Expand file tree
/
Copy pathtodo_claim.ts
More file actions
763 lines (733 loc) · 34 KB
/
Copy pathtodo_claim.ts
File metadata and controls
763 lines (733 loc) · 34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
import {prepareClaimExecution, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {retiredHandoffModeRejection, HANDOFF_MODE_RETIRED_REASON,
EXECUTION_HANDOFF_MODES, type ExecutionHandoffMode} from "./handoff_mode_policy.ts";
import {AUTHORITY_SOURCE_CHANGED, uncheckedAuthoritySource, type AuthoritySourceCheck} from "./authority_source.ts";
import {currentLeaseAcquisitionProof} from "./lease_acquisition_proof.ts";
import {canonicalTaskLease, canonicalTaskLeaseAcquireFacts} from "./task_lease_state.ts";
import {evaluateTaskLeaseAcquireDecision, materializeTaskLeaseAcquire} from "../work_items/task_lease_acquire_decision.ts";
import type { JsonObject } from "../effect_program.ts";
import type { AuthorityStore, AuthorityStoreCommit } from "./authority_store.ts";
import {
AuthorityStoreProtocolError,
canonicalAuthorityObject,
canonicalAuthoritySha256,
requireAuthorityBoolean,
requireAuthorityDate,
requireAuthorityStoreId,
} from "./authority_store_codec.ts";
import {validateContinuationNote, computeContinuationTodoFacts} from "./continuation_note.ts";
import {CoordinationCommandReceipt} from "./command_receipt.ts";
import {acceptanceWorkGuard} from "../goals/acceptance_contract.ts";
import {goalObjectiveWorkGuard} from "../goals/goal_objective.ts";
import {todoExecutionDependencyRejection} from "./todo_execution_dependency.ts";
import {normalizeRegisteredTodoAgents, normalizeTodoAgent} from "./todo_agents.ts";
import {
prepareCoordinationProjectionCommit,
indexCoordinationProjection,
validateCoordinationTodoReadModel,
type CoordinationProjectionMutation,
} from "./coordination_projection.ts";
import {
leaseInteger,
leaseIsActive,
normalizeAgent,
normalizeIdempotencyKey,
normalizeTtl,
} from "../work_items/task_lease_acquire.ts";
import {coordinationTodoWriteScopes} from "./todo_write_scopes.ts";
export const COORDINATION_TODO_CLAIM_RESULT_SCHEMA =
"loopx_coordination_todo_claim_result_v0";
export const COORDINATION_TODO_CLAIM_RECEIPT_SCHEMA =
"loopx_coordination_todo_claim_receipt_v0";
export const COORDINATION_TODO_CLAIM_DECISION_SCHEMA =
"loopx_coordination_todo_claim_decision_v0";
export interface CoordinationTodoClaimTransferGrant {
readonly schema_version: "todo_transfer_grant_v0";
readonly source_agent_id: string;
readonly target_agent_id: string;
readonly todo_id: string;
readonly expected_revision: string;
readonly continuation_note_facts: string;
}
export interface CoordinationTodoClaimInput {
readonly goal_id: string;
readonly todo_id: string;
readonly claimed_by: string;
readonly actor_agent_id: string | null;
readonly expected_role: string | null;
readonly registered_agents: readonly string[];
readonly operation_id: string;
readonly expected_provider_revision?: string;
readonly transfer_grant?: CoordinationTodoClaimTransferGrant;
/** Optional causal binding materialized atomically with an actual runnable claim. */
readonly replan_obligation_id?: string;
readonly lease_request?: CoordinationTodoClaimLeaseRequest | null;
readonly manage_execution?: boolean;
/** Admission constraint on every attempt and replay, not a new business intent. */
readonly required_handoff_mode?: ExecutionHandoffMode;
readonly dry_run: boolean;
readonly now: Date;
}
export interface CoordinationTodoClaimLeaseRequest {
readonly idempotency_key: string;
readonly expected_version: number | null;
readonly ttl_seconds: number;
}
export type CoordinationTodoClaimResult = JsonObject & {
readonly schema_version: typeof COORDINATION_TODO_CLAIM_RESULT_SCHEMA;
};
export interface CoordinationTodoClaimAcceptedDecision extends JsonObject {
readonly schema_version: typeof COORDINATION_TODO_CLAIM_DECISION_SCHEMA;
readonly status: "accepted";
readonly owner: string;
readonly actor: string | null;
readonly mode: "single_agent_compatibility" | "registered_peer_actor";
readonly mutation_authority: JsonObject;
}
export interface CoordinationTodoClaimRejectedDecision extends JsonObject {
readonly schema_version: typeof COORDINATION_TODO_CLAIM_DECISION_SCHEMA;
readonly status: "rejected";
readonly reason_code: string;
readonly reason: string;
}
export type CoordinationTodoClaimDecision =
| CoordinationTodoClaimAcceptedDecision
| CoordinationTodoClaimRejectedDecision;
type ClaimRejection = CoordinationTodoClaimRejectedDecision | null;
function normalizeExcludedAgents(value: unknown): string[] {
if (value === undefined || value === null) return [];
if (!Array.isArray(value)) {
throw new AuthorityStoreProtocolError("todo.excluded_agents must be an array");
}
const normalized = value.map((agent, index) =>
normalizeTodoAgent(agent, `todo.excluded_agents[${index}]`)
);
if (new Set(normalized).size !== normalized.length) {
throw new AuthorityStoreProtocolError(
"todo.excluded_agents must contain unique public-safe agent ids",
);
}
return normalized;
}
type CoordinationTodoClaimFailureKind =
| "decision_rejection"
| "protocol_failure";
function failure(
code: string,
reason: string,
detail: JsonObject = {},
kind: CoordinationTodoClaimFailureKind = "protocol_failure",
): CoordinationTodoClaimResult {
return {
...detail,
schema_version: COORDINATION_TODO_CLAIM_RESULT_SCHEMA,
status: "failed",
failure_kind: kind,
reason_code: code,
reason,
};
}
function decisionFailure(
code: string,
reason: string,
detail: JsonObject = {},
): CoordinationTodoClaimRejectedDecision {
return {
...detail,
schema_version: COORDINATION_TODO_CLAIM_DECISION_SCHEMA,
status: "rejected",
reason_code: code,
reason,
};
}
function rejectInvalidClaimActor(
input: CoordinationTodoClaimInput,
): ClaimRejection {
const { registered_agents: registered, claimed_by: owner, actor_agent_id: actor } = input;
if (!registered.includes(owner)) {
return decisionFailure(
"actor_not_registered",
"claimed_by is not registered for this goal",
{ claimed_by: owner },
);
}
if (actor !== null && !registered.includes(actor)) {
return decisionFailure(
"actor_not_registered",
"actor_agent_id is not registered for this goal",
{ actor_agent_id: actor },
);
}
if (registered.length > 1 && actor === null) {
return decisionFailure(
"actor_required",
"multi-agent Todo claim requires actor_agent_id",
);
}
return actor !== null && actor !== owner
? decisionFailure(
"claim_actor_mismatch",
"Todo claim requires claimed_by to match actor_agent_id",
{ actor_agent_id: actor, claimed_by: owner },
)
: null;
}
function rejectIneligibleTodo(
todo: JsonObject,
input: CoordinationTodoClaimInput,
): ClaimRejection {
if (todo.role !== "agent") {
return decisionFailure("todo_not_agent", "claimed_by is only valid for agent Todos");
}
if (input.expected_role !== null && input.expected_role !== todo.role) {
return decisionFailure(
"todo_role_mismatch",
"Todo does not have the requested role",
{ requested_role: input.expected_role, todo_role: todo.role },
);
}
if (todo.status !== "open") {
return decisionFailure(
"todo_not_open",
"todo claim requires status=open",
{ todo_status: todo.status },
);
}
if (todo.archive_state !== "active") {
return decisionFailure("todo_archived", "Todo claim requires an active Todo");
}
return typeof todo.removed_continuation_policy === "string" &&
todo.removed_continuation_policy.length > 0
? decisionFailure(
"removed_continuation_policy",
"Todo uses a removed continuation policy and must be repaired before claiming",
)
: null;
}
export function evaluateCoordinationTodoClaimDecision(
todo: JsonObject,
input: CoordinationTodoClaimInput,
activeLeaseOwner?: string | null,
expiredLeaseOwner?: string | null,
): CoordinationTodoClaimDecision {
const registered = input.registered_agents;
const owner = input.claimed_by;
const actor = input.actor_agent_id;
const rejection = rejectInvalidClaimActor(input) ?? rejectIneligibleTodo(todo, input);
if (rejection !== null) return rejection;
const excluded = normalizeExcludedAgents(todo.excluded_agents);
if (excluded.includes(owner)) {
return decisionFailure(
"actor_excluded",
"claiming agent is excluded from this Todo",
{ actor_agent_id: owner },
);
}
const existing = typeof todo.claimed_by === "string" && todo.claimed_by.length > 0
? normalizeTodoAgent(todo.claimed_by, "todo.claimed_by")
: null;
// A managed hard-lease claim can replace the matching expired holder.
// This fact is derived from canonical state, never a caller bypass flag.
// Other cross-agent transfer requires an explicit handoff transfer grant.
// The grant binds source owner, target owner, todo id, revision, and
// current continuation-note facts; it can only be produced by the handoff
// flow. Without expiry or a valid grant, foreign-owner claims are rejected.
// The final claim authority reuses the shared validateContinuationNote so
// the prepared-note invariant is enforced in one place: an arbitrary JSON
// note with matching hash is rejected because it lacks the typed marker,
// bounded fields, and current todo_facts.
if (existing !== null && existing !== owner) {
const grant = input.transfer_grant;
let grantValid = false;
if (grant != null) {
// Validate the continuation note using the shared predicate. This
// enforces the typed loopx-explicit-continuation invariant: marker,
// bounded fields, source session, and current todo_facts. An invalid
// note yields empty noteFacts, which cannot match a real grant.
const noteValidation = validateContinuationNote(todo.note, computeContinuationTodoFacts(todo));
grantValid = noteValidation.valid
&& grant.schema_version === "todo_transfer_grant_v0"
&& grant.source_agent_id === existing
&& grant.target_agent_id === owner
&& grant.todo_id === todo.todo_id
&& grant.expected_revision === input.expected_provider_revision
&& grant.continuation_note_facts === noteValidation.noteFacts
&& registered.includes(existing)
&& registered.includes(owner);
}
const leasedByOther = activeLeaseOwner !== undefined && activeLeaseOwner !== null && activeLeaseOwner === existing;
if (leasedByOther || !(grantValid || expiredLeaseOwner === existing)) {
return decisionFailure(
"claim_owner_mismatch",
"Todo is already claimed by another agent",
{ claim_owner: existing },
);
}
}
const mode = registered.length <= 1 ? "single_agent_compatibility" : "registered_peer_actor";
return {
schema_version: COORDINATION_TODO_CLAIM_DECISION_SCHEMA,
status: "accepted",
owner,
actor,
mode,
mutation_authority: {
schema_version: "todo_mutation_authority_v0",
command: "claim",
mode,
actor_agent_id: actor,
todo_id: todo.todo_id,
registered_agent_count: registered.length,
...(mode === "registered_peer_actor" ? { claim_owner: existing } : {}),
},
};
}
function normalizeLeaseRequest(value: unknown): CoordinationTodoClaimLeaseRequest | null {
if (value === undefined || value === null) return null;
const request = canonicalAuthorityObject(value, "lease_request");
const expectedVersion = request.expected_version;
if (expectedVersion !== null && expectedVersion !== undefined &&
(!Number.isSafeInteger(expectedVersion) || Number(expectedVersion) < 0)) {
throw new AuthorityStoreProtocolError(
"lease_request.expected_version must be a non-negative safe integer or null",
);
}
return {
idempotency_key: normalizeIdempotencyKey(request.idempotency_key),
expected_version: expectedVersion === undefined ? null : expectedVersion as number | null,
ttl_seconds: normalizeTtl(request.ttl_seconds),
};
}
function activeLeaseForOwner(
lease: JsonObject | undefined,
owner: string,
now: Date,
): boolean {
if (lease === undefined || lease.status !== "active" ||
typeof lease.owner !== "string" || typeof lease.expires_at !== "string") return false;
let leaseOwner: string;
try {
leaseOwner = normalizeTodoAgent(lease.owner, "lease.owner");
} catch {
return false;
}
if (leaseOwner !== owner) return false;
const expiresAt = new Date(lease.expires_at);
return !Number.isNaN(expiresAt.valueOf()) && expiresAt.valueOf() > now.valueOf();
}
/**
* Claim one Todo against the canonical provider head.
*
* The transaction is store-neutral: file, NoKV, and PostgreSQL adapters share
* the same semantic decision, complete-record replacement, CAS, and receipt.
* No caller-supplied projection is accepted.
*/
export async function executeCoordinationTodoClaim(
store: AuthorityStore,
rawInput: CoordinationTodoClaimInput,
authoritySourcesCurrent: AuthoritySourceCheck = uncheckedAuthoritySource,
observeWorkspace?: ClaimWorkspaceObserver,
): Promise<CoordinationTodoClaimResult> {
// Retry only a conclusive provider CAS rejection. Each attempt rereads the
// original receipt and the complete head, then rechecks source authorization,
// claim ownership, acceptance and lease/write-scope exclusion. Pinned revisions
// (including handoff grants) must return to their caller for a fresh observation.
for (let attempt = 0; ; attempt++) {
const result = await executeClaimAttempt(store, rawInput, authoritySourcesCurrent, observeWorkspace);
if (attempt >= 2 || rawInput.expected_provider_revision !== undefined ||
rawInput.transfer_grant !== undefined || result.status !== "conflict" ||
result.conflict_kind !== "provider_revision_mismatch") return result;
}
}
async function executeClaimAttempt(
store: AuthorityStore,
rawInput: CoordinationTodoClaimInput,
authoritySourcesCurrent: AuthoritySourceCheck,
observeWorkspace?: ClaimWorkspaceObserver,
): Promise<CoordinationTodoClaimResult> {
let input: CoordinationTodoClaimInput;
try {
input = {
...rawInput,
goal_id: requireAuthorityStoreId(rawInput.goal_id, "goal id"),
todo_id: requireAuthorityStoreId(rawInput.todo_id, "todo id"),
operation_id: requireAuthorityStoreId(rawInput.operation_id, "operation id"),
claimed_by: normalizeTodoAgent(rawInput.claimed_by, "claimed_by"),
actor_agent_id: rawInput.actor_agent_id === null
? null : normalizeTodoAgent(rawInput.actor_agent_id, "actor_agent_id"),
registered_agents: normalizeRegisteredTodoAgents(rawInput.registered_agents),
lease_request: normalizeLeaseRequest(rawInput.lease_request),
};
if (input.manage_execution !== undefined) requireAuthorityBoolean(input.manage_execution, "manage_execution");
if (input.required_handoff_mode !== undefined && !EXECUTION_HANDOFF_MODES.includes(input.required_handoff_mode)) {
throw new AuthorityStoreProtocolError("required_handoff_mode must be a current execution mode");
}
if (input.manage_execution && (input.lease_request != null || input.actor_agent_id !== input.claimed_by)) {
throw new AuthorityStoreProtocolError("Managed execution requires the claiming actor and no explicit lease request");
}
requireAuthorityBoolean(input.dry_run, "dry_run");
requireAuthorityDate(input.now, "now");
} catch (error) {
return failure(
"invalid_coordination_todo_claim",
error instanceof Error ? error.message : "invalid Todo claim",
);
}
if (input.replan_obligation_id !== undefined &&
(typeof input.replan_obligation_id !== "string" || !/^replan-[a-f0-9]{16}$/.test(input.replan_obligation_id) ||
input.actor_agent_id !== input.claimed_by)) {
return failure("invalid_replan_successor_claim", "A replan successor claim requires an exact obligation and the claiming Agent");
}
const leaseRequest = input.lease_request ?? null;
// Intent identity excludes observation time and current authorization facts.
// A receipt proves historical acceptance, never a renewed/current lease.
const requestIdentity = {
goal_id: input.goal_id,
todo_id: input.todo_id,
claimed_by: input.claimed_by,
actor_agent_id: input.actor_agent_id,
expected_role: input.expected_role,
...(input.expected_provider_revision === undefined ? {} :
{expected_provider_revision: input.expected_provider_revision}),
...(input.transfer_grant === undefined ? {} : {transfer_grant: input.transfer_grant}),
dry_run: input.dry_run,
...(leaseRequest === null ? {} : {lease_request: leaseRequest}),
...(input.manage_execution ? {manage_execution: true} : {}),
...(input.replan_obligation_id === undefined ? {} : {replan_obligation_id: input.replan_obligation_id}),
};
const requestSha = canonicalAuthoritySha256(requestIdentity);
const receipt = new CoordinationCommandReceipt({result_schema: COORDINATION_TODO_CLAIM_RESULT_SCHEMA,
identity: {schema_version: COORDINATION_TODO_CLAIM_RECEIPT_SCHEMA,
operation_id: input.operation_id, goal_id: input.goal_id, request_sha256: requestSha},
failure: (code, reason) => failure(code === "invalid_coordination_command_receipt"
? "invalid_coordination_todo_claim_receipt" : code, reason),
decode(original) {
const result = canonicalAuthorityObject(original.result, "original claim result");
if (result.todo_id !== input.todo_id || result.claimed_by !== input.claimed_by ||
(result.changed !== undefined && typeof result.changed !== "boolean") ||
(result.changed !== false && typeof result.updated_at !== "string") ||
typeof result.handoff_mode !== "string" ||
(input.required_handoff_mode !== undefined && result.handoff_mode !== input.required_handoff_mode) ||
result.mutation_authority === null || typeof result.mutation_authority !== "object") {
throw new AuthorityStoreProtocolError("original claim result is invalid");
}
if (input.manage_execution && (result.execution_managed !== true || result.claim_operation_id !== input.operation_id)) {
throw new AuthorityStoreProtocolError("managed claim receipt lost its execution reference");
}
if (input.replan_obligation_id !== undefined && result.replan_obligation_id !== input.replan_obligation_id) {
throw new AuthorityStoreProtocolError("claim replan binding differs from its original receipt");
}
if (leaseRequest !== null || result.execution_managed === true && result.handoff_mode === "hard_lease") {
const lease = canonicalAuthorityObject(result.lease, "original claim lease");
if (lease.todo_id !== input.todo_id || lease.owner !== input.claimed_by ||
leaseRequest !== null && lease.idempotency_key !== leaseRequest.idempotency_key) {
throw new AuthorityStoreProtocolError("original claim lease identity is invalid");
}
}
// Pre-change claim receipts may omit changed; those encoded a real mutation.
return {fields: {...result, original_receipt: original}, changed: result.changed !== false};
}});
const currentProof = async (result: CoordinationTodoClaimResult): Promise<CoordinationTodoClaimResult> => {
if (!await authoritySourcesCurrent()) return failure(AUTHORITY_SOURCE_CHANGED.code, AUTHORITY_SOURCE_CHANGED.reason,
{original_receipt: result.original_receipt}, "decision_rejection");
if (leaseRequest !== null || result.execution_managed === true && result.handoff_mode === "hard_lease") {
try {
const key = leaseRequest?.idempotency_key ?? String(canonicalAuthorityObject(result.lease, "managed claim lease").idempotency_key);
result = await currentLeaseAcquisitionProof(store, {...input, owner: input.claimed_by,
idempotency_key: key, required_handoff_mode: "hard_lease"}, result,
(code, reason, detail = {}) => failure(code, reason, detail, "decision_rejection"));
} catch (error) {
return failure("invalid_coordination_task_lease", error instanceof Error ? error.message : "invalid canonical task lease",
{original_receipt: result.original_receipt});
}
} else if (["replayed", "recovered"].includes(String(result.status))) {
// A plain historical claim has no lease proof to grant, but an enabled
// acceptance contract still governs adoption of that work.
const current = await store.loadAuthority();
if (current.status === "loaded") {
const guard = acceptanceWorkGuard(current.head, input.goal_id, input.todo_id);
if (guard !== null && !guard.allowed) return failure(String(guard.reason_code),
`${String(guard.reason)} Inspect Goal acceptance and ask the owner to configure or rebind this Todo.`,
{goal_acceptance_guard: guard}, "decision_rejection");
}
}
if (!await authoritySourcesCurrent()) return failure(AUTHORITY_SOURCE_CHANGED.code, AUTHORITY_SOURCE_CHANGED.reason,
{original_receipt: result.original_receipt}, "decision_rejection");
return result;
};
const recoverProof = async (result: CoordinationTodoClaimResult): Promise<CoordinationTodoClaimResult> => {
if (input.manage_execution && result.reason_code === "coordination_operation_identity_mismatch") {
const original = await store.readReceipt(input.operation_id);
const legacyIntent = {...requestIdentity};
delete legacyIntent.manage_execution;
if (original.status === "found" && original.receipts.length === 1 &&
original.receipts[0]?.schema_version === COORDINATION_TODO_CLAIM_RECEIPT_SCHEMA &&
original.receipts[0]?.goal_id === input.goal_id &&
original.receipts[0]?.request_sha256 === canonicalAuthoritySha256(legacyIntent)) {
// Preserve pre-upgrade assignment recovery. It remains historical, not
// a new managed execution; fresh work needs a new ordinary claim.
return executeClaimAttempt(store, {...input, manage_execution: false}, authoritySourcesCurrent);
}
}
return currentProof(result);
};
const existing = await receipt.read(store);
if (existing !== null) return recoverProof(existing);
if (!await authoritySourcesCurrent()) return failure(AUTHORITY_SOURCE_CHANGED.code, AUTHORITY_SOURCE_CHANGED.reason, {}, "decision_rejection");
const observation = await receipt.observe(store);
if (observation.kind === "receipt") return recoverProof(observation.result);
const head = observation.authority;
if (head.status !== "loaded") {
return {
schema_version: COORDINATION_TODO_CLAIM_RESULT_SCHEMA,
...head,
} as CoordinationTodoClaimResult;
}
if (input.expected_provider_revision !== undefined &&
input.expected_provider_revision !== head.provider_revision) {
return failure("provider_revision_mismatch", "Current revision changed; inspect again before continuing");
}
let projection: ReturnType<typeof indexCoordinationProjection>;
try {
projection = indexCoordinationProjection(head.head, input.goal_id);
validateCoordinationTodoReadModel(head.head, input.goal_id);
} catch (error) {
return failure(
"invalid_coordination_projection",
error instanceof Error ? error.message : "invalid coordination projection",
);
}
const todo = projection.todos.get(input.todo_id);
if (todo === undefined) {
return failure(
"todo_not_found",
"Todo is missing from the canonical provider head",
{ todo_id: input.todo_id },
"decision_rejection",
);
}
if (input.replan_obligation_id !== undefined &&
(todo.role !== "agent" || todo.status !== "open" || todo.task_class !== "advancement_task" ||
typeof todo.action_kind !== "string" || !todo.action_kind.trim() ||
!(typeof todo.target_key === "string" && todo.target_key.trim()) ||
(todo.replan_obligation_id !== undefined && todo.replan_obligation_id !== input.replan_obligation_id))) {
return failure("invalid_replan_successor_claim", "A successor must be open advancement work with a concrete action/target and unchanged causal identity");
}
const activeLeaseOwner = projection.leases.get(input.todo_id);
let authority: ReturnType<typeof evaluateCoordinationTodoClaimDecision>;
try {
const activeLeaseActive = activeLeaseOwner !== undefined && leaseIsActive(activeLeaseOwner, input.now);
const activeLeaseHolder = activeLeaseActive && activeLeaseOwner !== undefined && typeof activeLeaseOwner.owner === "string"
? normalizeTodoAgent(activeLeaseOwner.owner, "lease.owner")
: null;
let expiredLeaseHolder: string | null = null;
if (head.head.handoff_mode === "hard_lease" && input.manage_execution === true && activeLeaseOwner) {
const retained = canonicalTaskLease(activeLeaseOwner, input.goal_id, input.todo_id);
if (retained.status === "active" && !leaseIsActive(retained, input.now)) {
expiredLeaseHolder = normalizeTodoAgent(retained.owner, "lease.owner");
}
}
authority = evaluateCoordinationTodoClaimDecision(todo, input, activeLeaseHolder, expiredLeaseHolder);
} catch (error) {
return failure(
"invalid_coordination_todo_claim",
error instanceof Error ? error.message : "invalid Todo claim",
);
}
if (authority.status !== "accepted" || typeof authority.owner !== "string") {
return failure(
typeof authority.reason_code === "string" ? authority.reason_code : "invalid_coordination_todo_claim",
typeof authority.reason === "string" ? authority.reason : "Todo claim was rejected",
authority,
"decision_rejection",
);
}
const handoffMode = typeof head.head.handoff_mode === "string"
? head.head.handoff_mode
: "legacy";
if (!["legacy", "soft_claim", "hard_lease"].includes(handoffMode)) {
return failure("invalid_handoff_mode", "canonical projection has an invalid handoff mode");
}
const retired = retiredHandoffModeRejection(handoffMode);
if (retired !== null) return failure(retired, HANDOFF_MODE_RETIRED_REASON,
{todo_id: input.todo_id, handoff_mode: handoffMode}, "decision_rejection");
if (input.required_handoff_mode !== undefined && handoffMode !== input.required_handoff_mode) {
return failure("claim_handoff_mode_mismatch", "Current handoff mode does not satisfy the claim's admission constraint",
{todo_id: input.todo_id, handoff_mode: handoffMode, required_handoff_mode: input.required_handoff_mode}, "decision_rejection");
}
if (leaseRequest !== null && handoffMode !== "hard_lease") {
return failure(
"claim_lease_requires_hard_lease",
"atomic Todo claim and lease acquire requires handoff_mode=hard_lease",
{ todo_id: input.todo_id, handoff_mode: handoffMode },
"decision_rejection",
);
}
let lease: JsonObject | null = null;
let leaseChanged = false;
let leaseIdempotent = false;
let overlapAdvisories: JsonObject[] = [];
try {
const currentLease = projection.leases.get(input.todo_id);
if (handoffMode === "hard_lease" && input.manage_execution === true) {
const prepared = await prepareClaimExecution(head.head, input, observeWorkspace);
lease = prepared.lease;
leaseChanged = prepared.changed;
leaseIdempotent = !leaseChanged;
overlapAdvisories = prepared.overlapAdvisories ?? [];
} else if (handoffMode === "hard_lease" && leaseRequest !== null) {
// Validate required scopes before planning; a caller cannot omit a required conflict.
const writeScopes = coordinationTodoWriteScopes(todo);
const facts = canonicalTaskLeaseAcquireFacts(projection, input.goal_id, input.todo_id, input.registered_agents, input.now);
const decision = evaluateTaskLeaseAcquireDecision({handoff_mode: handoffMode,
registered_agents: [...input.registered_agents], ...facts,
command: {owner: authority.owner, idempotency_key: leaseRequest.idempotency_key,
ttl_seconds: leaseRequest.ttl_seconds, write_scopes: writeScopes,
expected_version: leaseRequest.expected_version}});
if (decision.outcome === "no_change") {
if (currentLease === undefined) {
throw new AuthorityStoreProtocolError(
"lease acquire replay is missing its canonical lease",
);
}
lease = currentLease;
leaseIdempotent = true;
} else if (decision.outcome === "apply") {
if (decision.next_lease === null) {
throw new AuthorityStoreProtocolError("lease acquire apply is missing next_lease");
}
lease = materializeTaskLeaseAcquire(input, {owner: authority.owner,
idempotency_key: leaseRequest.idempotency_key, ttl_seconds: leaseRequest.ttl_seconds,
write_scopes: writeScopes, expected_version: leaseRequest.expected_version}, decision, input.now);
leaseChanged = true;
} else {
return failure(
decision.code,
`canonical task lease acquire rejected the Todo claim: ${decision.code}`,
{
todo_id: input.todo_id,
actor_agent_id: authority.owner,
lease_decision: decision,
},
"decision_rejection",
);
}
} else if (handoffMode === "hard_lease" &&
!activeLeaseForOwner(currentLease, authority.owner, input.now)) {
const existingVersion = currentLease !== undefined
? (leaseInteger(currentLease, "version") ?? 0)
: null;
const expectedVersionGuidance = existingVersion !== null
? `; specify --task-lease-expected-version ${existingVersion} to match the existing canonical lease version`
: "; provide --task-lease-expected-version if a canonical lease already exists";
return failure(
"handoff_mode_requires_lease",
`hard_lease Todo claim requires an active canonical lease held by the claiming agent; ` +
`retry with \`loopx todo claim --task-lease-idempotency-key <key>\`${expectedVersionGuidance}`,
{
todo_id: input.todo_id,
actor_agent_id: authority.owner,
handoff_mode: handoffMode,
recovery: {
command: "loopx todo claim",
requires_flags: ["--task-lease-idempotency-key"],
optional_flags: ["--task-lease-expected-version"],
expected_version: existingVersion,
expected_version_required: existingVersion !== null,
},
},
"decision_rejection",
);
}
} catch (error) {
return failure(
"invalid_coordination_task_lease",
error instanceof Error ? error.message : "invalid canonical task lease",
{todo_id: input.todo_id},
);
}
const objective = goalObjectiveWorkGuard(head.head, authority.owner);
if (objective !== null) return failure(String(objective.reason_code), String(objective.reason),
{goal_objective_guard: objective}, "decision_rejection");
const acceptance = acceptanceWorkGuard(head.head, input.goal_id, input.todo_id);
if (acceptance !== null && !acceptance.allowed) {
return failure(String(acceptance.reason_code), `${String(acceptance.reason)} Inspect Goal acceptance and ask the owner to configure or rebind this Todo.`,
{goal_acceptance_guard: acceptance}, "decision_rejection");
}
if (leaseRequest !== null || input.manage_execution) {
const dependency = todoExecutionDependencyRejection(projection.todos, input.todo_id, input.now);
if (dependency !== null) return failure(dependency.code, dependency.reason,
{resume_condition: dependency.condition}, "decision_rejection");
}
const mutationAuthority = canonicalAuthorityObject(
authority.mutation_authority,
"Todo claim mutation authority",
);
const updatedAt = input.now.toISOString().replace(/\.\d{3}Z$/u, "Z");
const todoChanged = todo.claimed_by !== authority.owner ||
(input.replan_obligation_id !== undefined && todo.replan_obligation_id !== input.replan_obligation_id);
const changed = todoChanged || leaseChanged;
const result = {
todo_id: input.todo_id,
claimed_by: authority.owner,
...(input.replan_obligation_id === undefined ? {} : {replan_obligation_id: input.replan_obligation_id}),
changed,
handoff_mode: handoffMode,
...(changed ? {updated_at: updatedAt} : {}),
mutation_authority: mutationAuthority,
...(overlapAdvisories.length ? {integration_overlap_advisories: overlapAdvisories} : {}),
...(input.manage_execution ? {execution_managed: true, claim_operation_id: input.operation_id} : {}),
...(leaseRequest === null && !(input.manage_execution && handoffMode === "hard_lease") ? {} : {
todo_changed: todoChanged,
lease_changed: leaseChanged,
lease_idempotent: leaseIdempotent,
lease,
}),
};
if (!await authoritySourcesCurrent()) return failure(AUTHORITY_SOURCE_CHANGED.code, AUTHORITY_SOURCE_CHANGED.reason, {}, "decision_rejection");
if (input.dry_run) {
return {
...result,
schema_version: COORDINATION_TODO_CLAIM_RESULT_SCHEMA,
status: changed ? "planned" : "no_change",
dry_run: true,
provider_revision: head.provider_revision,
cursor: head.cursor,
};
}
// A successful no-op still consumes its operation identity. Commit only its
// receipt under the observed head's CAS; never fabricate a Todo mutation.
const mutations: CoordinationProjectionMutation[] = [
...(leaseChanged && lease !== null
? [{kind: "lease_upsert" as const, lease}]
: []),
...(todoChanged
? [{ kind: "todo_upsert" as const, todo: {...todo,
claimed_by: authority.owner, updated_at: updatedAt,
...(input.replan_obligation_id === undefined ? {} : {replan_obligation_id: input.replan_obligation_id})} }]
: []),
];
const commit: AuthorityStoreCommit = mutations.length > 0 ? prepareCoordinationProjectionCommit({
goal_id: input.goal_id,
operation_id: input.operation_id,
expected_provider_revision: head.provider_revision,
projection: head.head,
mutations,
}) : {
operation_id: input.operation_id,
expected_provider_revision: head.provider_revision,
next_projection: head.head,
events: [],
receipts: [],
};
// Reuse the validated reduction and event, but persist claim intent/result:
// a full replacement's digest depends on state and cannot identify a retry.
commit.receipts = [{
schema_version: COORDINATION_TODO_CLAIM_RECEIPT_SCHEMA,
operation_id: input.operation_id,
goal_id: input.goal_id,
request_sha256: requestSha,
result,
}];
return currentProof(await receipt.commit(store, commit));
}