Repository navigation
Expand file tree
/
Copy pathgoals.py
More file actions
1825 lines (1758 loc) · 112 KB
/
Copy pathgoals.py
File metadata and controls
1825 lines (1758 loc) · 112 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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import hashlib
import json
import os
import re
import sqlite3
import stat
import threading
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from uuid import UUID, uuid4
from .autonomy import AutonomyDisposition, AutonomyPolicyEngine, AutonomyRequest
from .autonomy_catalog import TRUSTED_OPERATION_CONTRACTS, validate_operation_plan
from .autonomy_profiles import AutonomyProfileVerifier, load_signed_autonomy_profile_record
from .impact_assessments import impact_assessment_digest as _impact_assessment_digest
MAX_GOAL_BYTES = 64 * 1024
TASK_STATES = frozenset({
"pending_policy", "auto_eligible", "approval_required", "denied",
"queued", "leased", "running", "verification", "completed",
"failed", "cancelled", "blocked",
})
_TRANSITIONS = {
"pending_policy": {"auto_eligible", "approval_required", "denied", "blocked", "cancelled"},
"auto_eligible": {"approval_required", "denied", "queued", "blocked", "cancelled"},
"approval_required": {"queued", "denied", "blocked", "cancelled"},
"queued": {"leased", "cancelled", "blocked"},
"leased": {"queued", "running", "cancelled", "blocked"},
"running": {"verification", "failed", "blocked"},
"verification": {"completed", "failed", "blocked"},
"blocked": {"pending_policy", "approval_required", "cancelled"},
"denied": set(), "completed": set(), "failed": set(), "cancelled": set(),
}
_NON_EXECUTABLE_STATES = frozenset({"auto_eligible", "approval_required", "queued", "leased", "running", "verification"})
def _canonical(value: Any) -> bytes:
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False).encode("utf-8")
def _unique_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
value: dict[str, Any] = {}
for key, item in pairs:
if key in value:
raise ValueError(f"duplicate plan JSON key: {key}")
value[key] = item
return value
def _now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
@dataclass(frozen=True)
class GoalReceipt:
goal_id: str
tenant_id: str
status: str
created: bool
def as_dict(self) -> dict[str, Any]:
return {"goal_id": self.goal_id, "tenant_id": self.tenant_id, "status": self.status, "created": self.created}
class DurableGoalStore:
"""Local SQLite journal for typed, governed goals; it is not an executor.
Goals are operator-submitted outcomes. Codex/planners must convert them into
typed, target-scoped tasks; free text is never interpreted as a shell command.
The store records policy decisions and workflow transitions. Queueing,
lease start, and permit consumption require injected verifiers; none of
these transitions invokes an infrastructure adapter.
"""
def __init__(self, path: str | Path) -> None:
self.path = Path(path).expanduser().absolute()
if not self.path.parent.is_dir():
raise ValueError("goal database parent directory must already exist")
if self.path.is_symlink():
raise PermissionError("goal database may not be a symlink")
self._lock = threading.RLock()
self._db = sqlite3.connect(self.path, timeout=10, isolation_level=None, check_same_thread=False)
os.chmod(self.path, 0o600)
self._db.row_factory = sqlite3.Row
self._db.execute("PRAGMA foreign_keys=ON")
self._db.execute("PRAGMA journal_mode=DELETE")
self._db.execute("PRAGMA synchronous=FULL")
self._db.executescript("""
CREATE TABLE IF NOT EXISTS goals (
goal_id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
requested_by TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
request_digest TEXT NOT NULL,
objective TEXT NOT NULL,
guardrails_json TEXT NOT NULL,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE (tenant_id, requested_by, idempotency_key)
);
CREATE TABLE IF NOT EXISTS tasks (
task_id TEXT PRIMARY KEY,
goal_id TEXT NOT NULL REFERENCES goals(goal_id),
tenant_id TEXT NOT NULL,
operation_id TEXT NOT NULL,
target_ids_json TEXT NOT NULL,
environment TEXT NOT NULL,
plan_json TEXT NOT NULL DEFAULT '{}',
plan_digest TEXT NOT NULL,
policy_digest TEXT NOT NULL,
status TEXT NOT NULL,
decision_json TEXT NOT NULL,
approval_ref TEXT,
lease_owner TEXT,
lease_until TEXT,
lease_token TEXT,
lease_stage TEXT,
lease_generation INTEGER NOT NULL DEFAULT 0,
execution_deadline TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS goal_events (
event_no INTEGER PRIMARY KEY AUTOINCREMENT,
sequence INTEGER NOT NULL,
event_id TEXT NOT NULL UNIQUE,
tenant_id TEXT NOT NULL,
goal_id TEXT NOT NULL REFERENCES goals(goal_id),
task_id TEXT,
event_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
previous_hash TEXT,
event_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
UNIQUE (tenant_id, goal_id, sequence)
);
CREATE INDEX IF NOT EXISTS tasks_queue_idx ON tasks(status, created_at);
CREATE INDEX IF NOT EXISTS events_goal_idx ON goal_events(tenant_id, goal_id, sequence);
CREATE TABLE IF NOT EXISTS consumed_approvals (
approval_id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
consumed_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS runner_attestations (
receipt_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
tenant_id TEXT NOT NULL,
target_id TEXT NOT NULL,
lease_generation INTEGER NOT NULL,
envelope_json TEXT NOT NULL,
attestation_sha256 TEXT NOT NULL,
recorded_at TEXT NOT NULL,
UNIQUE (task_id, lease_generation, target_id)
);
CREATE TABLE IF NOT EXISTS postcondition_attestations (
verification_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
tenant_id TEXT NOT NULL,
target_id TEXT NOT NULL,
lease_generation INTEGER NOT NULL,
envelope_json TEXT NOT NULL,
attestation_sha256 TEXT NOT NULL,
expected_state_sha256 TEXT NOT NULL,
observed_state_sha256 TEXT NOT NULL,
verified INTEGER NOT NULL CHECK (verified IN (0,1)),
recorded_at TEXT NOT NULL,
UNIQUE (task_id,lease_generation)
);
CREATE TABLE IF NOT EXISTS execution_grants (
grant_id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(task_id),
tenant_id TEXT NOT NULL,
lease_generation INTEGER NOT NULL,
envelope_json TEXT NOT NULL,
grant_sha256 TEXT NOT NULL,
expires_at TEXT NOT NULL,
issued_at TEXT NOT NULL,
consumed_at TEXT,
consumed_by TEXT,
UNIQUE (task_id, lease_generation)
);
CREATE TABLE IF NOT EXISTS circuit_breakers (
tenant_id TEXT NOT NULL,
target_id TEXT NOT NULL,
operation_id TEXT NOT NULL,
environment TEXT NOT NULL,
state TEXT NOT NULL CHECK (state IN ('open','closed')),
goal_id TEXT NOT NULL REFERENCES goals(goal_id),
task_id TEXT NOT NULL REFERENCES tasks(task_id),
last_receipt_id TEXT NOT NULL,
reason TEXT NOT NULL,
opened_at TEXT NOT NULL,
reset_approval_id TEXT,
reset_evidence_sha256 TEXT,
reset_at TEXT,
PRIMARY KEY (tenant_id,target_id,operation_id)
);
""")
task_columns = {row["name"] for row in self._db.execute("PRAGMA table_info(tasks)")}
for column in ("lease_token", "lease_stage"):
if column not in task_columns:
self._db.execute(f"ALTER TABLE tasks ADD COLUMN {column} TEXT")
if "lease_generation" not in task_columns:
self._db.execute("ALTER TABLE tasks ADD COLUMN lease_generation INTEGER NOT NULL DEFAULT 0")
if "execution_deadline" not in task_columns:
self._db.execute("ALTER TABLE tasks ADD COLUMN execution_deadline TEXT")
if "plan_json" not in task_columns:
self._db.execute("ALTER TABLE tasks ADD COLUMN plan_json TEXT NOT NULL DEFAULT '{}'")
grant_columns = {row["name"] for row in self._db.execute("PRAGMA table_info(execution_grants)")}
for column in ("consumed_at", "consumed_by"):
if column not in grant_columns:
self._db.execute(f"ALTER TABLE execution_grants ADD COLUMN {column} TEXT")
info = self.path.stat()
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) & 0o077:
self._db.close()
raise PermissionError("goal database must be a regular owner-only file")
def close(self) -> None:
with self._lock:
self._db.close()
def submit_goal(
self,
*,
tenant_id: str,
requested_by: str,
idempotency_key: str,
objective: str,
guardrails: dict[str, Any],
) -> GoalReceipt:
for label, value in (("tenant_id", tenant_id), ("requested_by", requested_by), ("idempotency_key", idempotency_key)):
if not isinstance(value, str) or not value.strip() or len(value) > 256:
raise ValueError(f"{label} must be a non-empty string of at most 256 characters")
if not isinstance(objective, str) or not objective.strip() or len(objective.encode("utf-8")) > MAX_GOAL_BYTES:
raise ValueError("objective must be non-empty and at most 64 KiB")
if not isinstance(guardrails, dict) or len(_canonical(guardrails)) > MAX_GOAL_BYTES:
raise ValueError("guardrails must be a JSON object of at most 64 KiB")
guardrails_json = _canonical(guardrails).decode()
with self._transaction():
request_digest = hashlib.sha256(_canonical({"objective": objective, "guardrails": guardrails})).hexdigest()
row = self._db.execute(
"SELECT goal_id,status,request_digest FROM goals WHERE tenant_id=? AND requested_by=? AND idempotency_key=?",
(tenant_id, requested_by, idempotency_key),
).fetchone()
if row:
if row["request_digest"] != request_digest:
raise ValueError("idempotency key was already used with a different goal payload")
return GoalReceipt(row["goal_id"], tenant_id, row["status"], False)
goal_id, stamp = str(uuid4()), _now()
self._db.execute(
"INSERT INTO goals VALUES (?,?,?,?,?,?,?,?,?)",
(goal_id, tenant_id, requested_by, idempotency_key, request_digest, objective, guardrails_json, "submitted", stamp),
)
self._append_event(tenant_id, goal_id, None, "goal.submitted", {"requested_by": requested_by, "objective_sha256": hashlib.sha256(objective.encode()).hexdigest(), "guardrails": guardrails})
return GoalReceipt(goal_id, tenant_id, "submitted", True)
def add_task(
self,
*,
goal_id: str,
tenant_id: str,
operation_id: str,
target_ids: tuple[str, ...],
environment: str,
plan: dict[str, Any],
policy_digest: str = "",
) -> dict[str, Any]:
if (not isinstance(operation_id, str) or not operation_id.strip() or len(operation_id) > 128
or operation_id in {"*", "shell.exec", "command.run"}):
raise ValueError("task requires a specific registered operation; generic command execution is forbidden")
if (not isinstance(target_ids, (tuple, list)) or not target_ids or len(target_ids) > 20
or any(not isinstance(target, str) or not target.strip() or len(target) > 256 for target in target_ids)
or len(set(target_ids)) != len(target_ids)):
raise ValueError("task requires unique exact target IDs")
if environment not in {"lab", "development", "staging", "production", "regulated"}:
raise ValueError("environment is not recognized")
plan_json, plan_digest = self._validate_plan(
plan, operation_id=operation_id, target_ids=target_ids, environment=environment,
)
if policy_digest and (not isinstance(policy_digest, str) or len(policy_digest) != 64 or any(c not in "0123456789abcdef" for c in policy_digest)):
raise ValueError("policy_digest must be a lowercase SHA-256 digest")
with self._transaction():
goal = self._db.execute("SELECT status FROM goals WHERE goal_id=? AND tenant_id=?", (goal_id, tenant_id)).fetchone()
if not goal:
raise KeyError("goal not found in tenant scope")
if goal["status"] not in {"submitted", "planning"}:
raise PermissionError("goal is not accepting planned tasks")
task_id, stamp = str(uuid4()), _now()
targets_json = _canonical(list(target_ids)).decode()
self._db.execute(
"INSERT INTO tasks (task_id,goal_id,tenant_id,operation_id,target_ids_json,environment,plan_json,plan_digest,policy_digest,status,decision_json,approval_ref,lease_owner,lease_until,lease_token,lease_stage,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(task_id, goal_id, tenant_id, operation_id, targets_json, environment, plan_json, plan_digest, policy_digest,
"pending_policy", "{}", None, None, None, None, None, stamp, stamp),
)
self._db.execute("UPDATE goals SET status='planning' WHERE goal_id=?", (goal_id,))
self._append_event(tenant_id, goal_id, task_id, "task.created", {
"operation_id": operation_id, "target_ids": list(target_ids), "environment": environment,
"plan": json.loads(plan_json), "plan_sha256": plan_digest,
})
return self.get_task(task_id=task_id, tenant_id=tenant_id)
@staticmethod
def _validate_plan(plan: dict[str, Any], *, operation_id: str, target_ids: tuple[str, ...],
environment: str) -> tuple[str, str]:
required = {
"schema_version", "operation_id", "target_ids", "environment", "preconditions",
"desired_state", "rollback", "max_runtime_seconds",
}
if not isinstance(plan, dict) or set(plan) != required:
raise ValueError("plan fields must exactly match a2z-task-plan-v1")
if plan["schema_version"] != "a2z-task-plan-v1" or plan["operation_id"] != operation_id:
raise ValueError("plan version or operation_id does not match the task")
if plan["target_ids"] != list(target_ids) or plan["environment"] != environment:
raise ValueError("plan targets or environment do not exactly match the task")
for field in ("preconditions", "desired_state", "rollback"):
if not isinstance(plan[field], dict) or not plan[field]:
raise ValueError(f"plan {field} must be a non-empty object")
DurableGoalStore._validate_plan_values(plan)
runtime = plan["max_runtime_seconds"]
if isinstance(runtime, bool) or not isinstance(runtime, int) or not 1 <= runtime <= 1800:
raise ValueError("plan max_runtime_seconds must be between 1 and 1800")
try:
canonical_plan = _canonical(plan)
except (TypeError, ValueError) as exc:
raise ValueError("plan must contain only JSON-compatible values") from exc
if len(canonical_plan) > MAX_GOAL_BYTES:
raise ValueError("plan artifact exceeds 64 KiB")
plan_json = canonical_plan.decode("utf-8")
return plan_json, hashlib.sha256(canonical_plan).hexdigest()
@staticmethod
def _validate_plan_values(value: Any) -> None:
sensitive_keys = {
"password", "passwd", "secret", "secrets", "credential", "credentials",
"private_key", "privatekey", "access_token", "refresh_token", "client_secret",
"token", "api_key", "access_key", "session_key", "key_material", "authorization",
}
if isinstance(value, dict):
for key, child in value.items():
if not isinstance(key, str):
raise ValueError("plan object keys must be strings")
normalized = key.lower().replace("-", "_")
compact = normalized.replace("_", "")
compact_sensitive = {item.replace("_", "") for item in sensitive_keys}
if (normalized in sensitive_keys or compact in compact_sensitive
or normalized.endswith(("_secret", "_password", "_credential", "_private_key", "_token"))):
raise PermissionError("plan artifacts must not contain secret or credential fields")
DurableGoalStore._validate_plan_values(child)
elif isinstance(value, list):
for child in value:
DurableGoalStore._validate_plan_values(child)
def claim_policy_task(self, *, task_id: str, tenant_id: str, worker_id: str, lease_seconds: int = 60) -> dict[str, Any]:
if not worker_id.strip() or len(worker_id) > 128:
raise ValueError("worker_id must be a non-empty bounded identifier")
if isinstance(lease_seconds, bool) or not 1 <= lease_seconds <= 600:
raise ValueError("policy lease must be between 1 and 600 seconds")
with self._transaction():
task = self._db.execute(
"SELECT status,lease_stage,lease_until FROM tasks WHERE task_id=? AND tenant_id=?",
(task_id, tenant_id),
).fetchone()
if not task:
raise KeyError("task not found in tenant scope")
if task["status"] != "pending_policy":
raise PermissionError("only a pending-policy task can be leased for policy evaluation")
now = datetime.now(timezone.utc)
if task["lease_until"] and task["lease_until"] > now.isoformat(timespec="seconds").replace("+00:00", "Z"):
raise PermissionError("task already has an active worker lease")
expires = now.timestamp() + lease_seconds
until = datetime.fromtimestamp(expires, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
token = str(uuid4())
self._db.execute(
"UPDATE tasks SET lease_owner=?,lease_until=?,lease_token=?,lease_stage='policy_evaluation',updated_at=? WHERE task_id=?",
(worker_id, until, token, _now(), task_id),
)
task_goal = self._db.execute("SELECT goal_id FROM tasks WHERE task_id=?", (task_id,)).fetchone()
self._append_event(tenant_id, task_goal["goal_id"], task_id, "task.policy_lease_claimed", {"worker_id": worker_id, "lease_until": until})
return self.get_task(task_id=task_id, tenant_id=tenant_id) | {"lease_token": token}
def record_decision(self, *, task_id: str, tenant_id: str, lease_token: str, disposition: str,
reasons: tuple[str, ...], policy_digest: str,
impact_assessment_digest: str = "",
impact_assessment_record: dict[str, Any] | None = None,
autonomy_profile_record: dict[str, Any] | None = None,
autonomy_profile_verifier: Any | None = None) -> dict[str, Any]:
if disposition not in {"auto_eligible", "approval_required", "denied"}:
raise ValueError("decision must come from the governed policy decision point")
if disposition == "auto_eligible" and (len(policy_digest) != 64 or any(c not in "0123456789abcdef" for c in policy_digest)):
raise PermissionError("auto-eligible decisions require a signed policy digest")
if impact_assessment_digest and (len(impact_assessment_digest) != 64 or any(c not in "0123456789abcdef" for c in impact_assessment_digest)):
raise ValueError("impact assessment digest must be a lowercase SHA-256 digest")
if impact_assessment_record is not None:
if (_impact_assessment_digest(impact_assessment_record) != impact_assessment_digest
or len(_canonical(impact_assessment_record)) > MAX_GOAL_BYTES):
raise ValueError("impact assessment evidence does not match its verified digest or size limit")
elif impact_assessment_digest:
raise ValueError("impact assessment digest requires the signed assessment evidence")
if disposition == "auto_eligible":
if autonomy_profile_record is None or autonomy_profile_verifier is None:
raise PermissionError("auto-eligible decisions require the signed autonomy profile and trusted verifier")
if (not isinstance(autonomy_profile_record, dict)
or set(autonomy_profile_record) != {"profile", "signature"}
or not isinstance(autonomy_profile_record.get("profile"), dict)):
raise ValueError("signed autonomy profile record is malformed")
verified_profile_digest = autonomy_profile_verifier.verify(autonomy_profile_record)
if (verified_profile_digest != policy_digest
or autonomy_profile_record["profile"].get("tenant_id") != tenant_id
or autonomy_profile_record["profile"].get("enabled") is not True):
raise PermissionError("signed autonomy profile does not match the tenant, enabled state, or decision digest")
elif autonomy_profile_record is not None:
raise ValueError("autonomy profile evidence is retained only for auto-eligible decisions")
decision = {"disposition": disposition, "reasons": list(reasons), "policy_digest": policy_digest,
"impact_assessment_digest": impact_assessment_digest or None,
"impact_assessment": impact_assessment_record,
"autonomy_profile": autonomy_profile_record,
"execution_permitted": False}
with self._transaction():
task = self._db.execute("SELECT goal_id,status,lease_token,lease_stage,lease_until FROM tasks WHERE task_id=? AND tenant_id=?", (task_id, tenant_id)).fetchone()
if not task:
raise KeyError("task not found in tenant scope")
if task["status"] != "pending_policy":
raise PermissionError("policy decision can only be recorded for a pending task")
now_text = _now()
if task["lease_stage"] != "policy_evaluation" or task["lease_token"] != lease_token or not task["lease_until"] or task["lease_until"] <= now_text:
raise PermissionError("a current policy-evaluation lease is required")
self._db.execute("UPDATE tasks SET status=?,decision_json=?,policy_digest=?,lease_owner=NULL,lease_until=NULL,lease_token=NULL,lease_stage=NULL,updated_at=? WHERE task_id=?", (disposition, _canonical(decision).decode(), policy_digest, now_text, task_id))
self._append_event(tenant_id, task["goal_id"], task_id, "task.policy_decided", decision)
return self.get_task(task_id=task_id, tenant_id=tenant_id)
def queue_task(self, *, task_id: str, tenant_id: str, signed_approval: dict[str, Any], approval_verifier: Any) -> dict[str, Any]:
"""Queue one non-production task only after a single-use signed approval verifies."""
if not isinstance(signed_approval, dict) or len(_canonical(signed_approval)) > MAX_GOAL_BYTES:
raise ValueError("signed approval must be a JSON object of at most 64 KiB")
with self._lock:
task = self._db.execute(
"SELECT goal_id,tenant_id,operation_id,target_ids_json,environment,plan_json,plan_digest,status,decision_json FROM tasks WHERE task_id=? AND tenant_id=?",
(task_id, tenant_id),
).fetchone()
if not task:
raise KeyError("task not found in tenant scope")
if task["status"] != "approval_required" or task["environment"] in {"production", "regulated"}:
raise PermissionError("only a non-production task awaiting operator approval can be queued")
targets = json.loads(task["target_ids_json"])
self._assert_stored_plan(task, targets)
if len(targets) != 1:
raise PermissionError("signed approval currently requires exactly one task target")
plan_digest = task["plan_digest"]
if not isinstance(plan_digest, str) or len(plan_digest) != 64 or any(c not in "0123456789abcdef" for c in plan_digest):
raise PermissionError("task must have a SHA-256 plan digest before approval")
expected_scope = {
"tenant_id": tenant_id,
"target": targets[0],
"action": task["operation_id"],
"environment": task["environment"],
"capabilities": ["task.execute", f"plan.sha256:{plan_digest}"],
"plan_id": task_id,
}
if approval_verifier is None:
raise PermissionError("trusted signed-approval verifier is unavailable")
approval = approval_verifier.verify(signed_approval, expected_scope=expected_scope)
if approval.get("request_id") != task["goal_id"]:
raise PermissionError("signed approval request_id does not match the task's goal")
approval_id = approval["approval_id"]
approval_digest = hashlib.sha256(_canonical(signed_approval)).hexdigest()
decision = json.loads(task["decision_json"])
decision["approval"] = {
"approval_id": approval_id,
"approver_id": approval["approver_id"],
"signed_record_sha256": approval_digest,
"signed_record": signed_approval,
}
decision["authorization_mode"] = "operator_approval"
decision["execution_permitted"] = False
with self._transaction():
current = self._db.execute(
"SELECT goal_id,operation_id,target_ids_json,environment,plan_json,plan_digest,status FROM tasks WHERE task_id=? AND tenant_id=?",
(task_id, tenant_id),
).fetchone()
if (not current or current["status"] != "approval_required" or current["goal_id"] != task["goal_id"]
or current["operation_id"] != task["operation_id"] or current["target_ids_json"] != task["target_ids_json"]
or current["environment"] != task["environment"] or current["plan_json"] != task["plan_json"]
or current["plan_digest"] != plan_digest):
raise PermissionError("task changed while signed approval was being verified")
try:
self._db.execute(
"INSERT INTO consumed_approvals (approval_id,tenant_id,task_id,consumed_at) VALUES (?,?,?,?)",
(approval_id, tenant_id, task_id, _now()),
)
except sqlite3.IntegrityError as exc:
raise PermissionError("signed approval was already consumed") from exc
stamp = _now()
self._db.execute(
"UPDATE tasks SET status='queued',approval_ref=?,decision_json=?,updated_at=? WHERE task_id=? AND tenant_id=?",
(approval_id, _canonical(decision).decode(), stamp, task_id, tenant_id),
)
self._append_event(tenant_id, task["goal_id"], task_id, "task.approved_and_queued", {
"approval_id": approval_id, "approver_id": approval["approver_id"],
"authorization_mode": "operator_approval", "authorization_id": approval_id,
"signed_record_sha256": approval_digest, "signed_record": signed_approval,
"execution_permitted": False,
})
return self.get_task(task_id=task_id, tenant_id=tenant_id)
def queue_autonomous_task(self, *, task_id: str, tenant_id: str,
autonomy_profile_verifier: AutonomyProfileVerifier,
impact_verifier: Any) -> dict[str, Any]:
"""Queue routine work only after revalidating signed policy and estimate."""
if autonomy_profile_verifier is None or impact_verifier is None:
raise PermissionError("trusted autonomy-profile and impact-assessment verifiers are required")
with self._transaction():
task = self._db.execute(
"SELECT t.*,g.guardrails_json FROM tasks t JOIN goals g ON g.goal_id=t.goal_id "
"WHERE t.task_id=? AND t.tenant_id=?",
(task_id, tenant_id),
).fetchone()
if not task:
raise KeyError("task not found in tenant scope")
if task["status"] != "auto_eligible" or task["environment"] in {"production", "regulated"}:
raise PermissionError("only a current auto-eligible non-production task can be queued by policy")
active = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? "
"AND status IN ('queued','leased','running','verification')",
(tenant_id, task_id),
).fetchone()["count"]
profile, assessment = self._revalidate_autonomous_task(
task, autonomy_profile_verifier=autonomy_profile_verifier,
impact_verifier=impact_verifier, active_concurrency=active,
)
decision = json.loads(task["decision_json"])
queued_at = _now()
decision["authorization_mode"] = "standing_policy"
decision["autonomous_queue"] = {
"authorization_id": str(uuid4()),
"queued_at": queued_at,
"policy_digest": profile.policy_digest,
"impact_assessment_digest": assessment.assessment_digest,
"execution_permitted": False,
}
current = self._db.execute(
"SELECT status,decision_json,plan_digest FROM tasks WHERE task_id=? AND tenant_id=?",
(task_id, tenant_id),
).fetchone()
if (not current or current["status"] != "auto_eligible"
or current["decision_json"] != task["decision_json"]
or current["plan_digest"] != task["plan_digest"]):
raise PermissionError("autonomous task changed during policy revalidation")
self._db.execute(
"UPDATE tasks SET status='queued',decision_json=?,updated_at=? WHERE task_id=? AND tenant_id=?",
(_canonical(decision).decode(), queued_at, task_id, tenant_id),
)
self._append_event(tenant_id, task["goal_id"], task_id, "task.autonomous_policy_queued", {
"authorization_id": decision["autonomous_queue"]["authorization_id"],
"policy_digest": profile.policy_digest,
"impact_assessment_digest": assessment.assessment_digest,
"authorization_mode": "standing_policy",
"execution_permitted": False,
})
return self.get_task(task_id=task_id, tenant_id=tenant_id)
def _revalidate_autonomous_task(self, task: Any, *, autonomy_profile_verifier: Any,
impact_verifier: Any, active_concurrency: int):
decision = json.loads(task["decision_json"])
if decision.get("disposition") != "auto_eligible":
raise PermissionError("stored task does not have an auto-eligible policy decision")
profile_record = decision.get("autonomy_profile")
profile = load_signed_autonomy_profile_record(
profile_record, verifier=autonomy_profile_verifier,
)
if profile.tenant_id != task["tenant_id"] or profile.policy_digest != task["policy_digest"]:
raise PermissionError("retained signed autonomy profile no longer matches task scope or digest")
if not profile.enabled:
raise PermissionError("standing autonomy profile is disabled")
targets = json.loads(task["target_ids_json"])
self._assert_stored_plan(task, targets)
if len(targets) != 1:
raise PermissionError("routine autonomy currently requires exactly one target")
goals = self._db.execute(
"SELECT guardrails_json FROM goals WHERE goal_id=? AND tenant_id=?",
(task["goal_id"], task["tenant_id"]),
).fetchone()
if not goals:
raise PermissionError("task goal governance envelope is unavailable")
guardrails = json.loads(goals["guardrails_json"])
if (guardrails.get("autonomy_enabled") is not True
or task["environment"] not in guardrails.get("allowed_environments", [])
or not set(targets).issubset(set(guardrails.get("allowed_targets", [])))):
raise PermissionError("task is outside its immutable goal governance envelope")
assessment_record = decision.get("impact_assessment")
if not isinstance(assessment_record, dict):
raise PermissionError("autonomous dispatch requires the retained signed impact assessment")
assessment = impact_verifier.verify(assessment_record, expected={
"tenant_id": task["tenant_id"], "task_id": task["task_id"],
"operation_id": task["operation_id"], "target_ids": tuple(targets),
"environment": task["environment"], "plan_digest": task["plan_digest"],
})
if (assessment.assessment_digest != decision.get("impact_assessment_digest")
or assessment.assessment_digest != _impact_assessment_digest(assessment_record)):
raise PermissionError("retained impact assessment digest no longer matches task decision")
contract = TRUSTED_OPERATION_CONTRACTS.get(task["operation_id"])
plan = json.loads(task["plan_json"], object_pairs_hook=_unique_pairs)
plan_reasons = validate_operation_plan(task["operation_id"], plan)
if plan_reasons:
raise PermissionError("task plan failed code-owned validation: " + ",".join(plan_reasons))
reevaluated = AutonomyPolicyEngine().evaluate(
profile,
AutonomyRequest(
tenant_id=task["tenant_id"], action_id=task["operation_id"],
target_ids=tuple(targets), environment=task["environment"],
plan_digest=task["plan_digest"], task_id=task["task_id"],
active_concurrency=active_concurrency,
max_runtime_seconds=plan["max_runtime_seconds"],
impact_assessment=assessment,
),
contract,
)
if reevaluated.disposition is not AutonomyDisposition.AUTO_ELIGIBLE:
raise PermissionError(
"autonomous policy no longer permits queueing: " + ",".join(reevaluated.reason_codes)
)
return profile, assessment
def _execution_authorization(self, task: Any, *, approval_verifier: Any,
autonomy_profile_verifier: Any, impact_verifier: Any,
active_concurrency: int) -> dict[str, Any]:
"""Re-derive an exact operator or standing-policy authorization."""
decision = json.loads(task["decision_json"])
mode = decision.get("authorization_mode", "operator_approval")
if mode == "standing_policy":
queued = decision.get("autonomous_queue")
if (not isinstance(queued, dict) or not isinstance(queued.get("authorization_id"), str)
or autonomy_profile_verifier is None or impact_verifier is None):
raise PermissionError("standing-policy authorization record or trusted verifiers are unavailable")
try:
UUID(queued["authorization_id"])
except ValueError as exc:
raise PermissionError("standing-policy authorization_id is invalid") from exc
profile, assessment = self._revalidate_autonomous_task(
task, autonomy_profile_verifier=autonomy_profile_verifier,
impact_verifier=impact_verifier, active_concurrency=active_concurrency,
)
if (queued.get("policy_digest") != profile.policy_digest
or queued.get("impact_assessment_digest") != assessment.assessment_digest):
raise PermissionError("standing-policy authorization digests no longer match retained evidence")
return {
"authorization_mode": "standing_policy",
"authorization_id": queued["authorization_id"],
"approval_id": None,
"policy_digest": profile.policy_digest,
"impact_assessment_digest": assessment.assessment_digest,
}
if mode != "operator_approval":
raise PermissionError("task authorization mode is unsupported")
approval_data = decision.get("approval")
signed_record = approval_data.get("signed_record") if isinstance(approval_data, dict) else None
if not isinstance(signed_record, dict) or not task["approval_ref"]:
raise PermissionError("queued task has no retained signed approval record")
if approval_verifier is None:
raise PermissionError("trusted signed-approval verifier is unavailable")
targets = json.loads(task["target_ids_json"])
if len(targets) != 1:
raise PermissionError("execution authorization requires exactly one target")
approval = approval_verifier.verify(signed_record, expected_scope={
"tenant_id": task["tenant_id"], "target": targets[0],
"action": task["operation_id"], "environment": task["environment"],
"capabilities": ["task.execute", f"plan.sha256:{task['plan_digest']}"],
"plan_id": task["task_id"],
})
if (approval.get("approval_id") != task["approval_ref"]
or approval.get("request_id") != task["goal_id"]):
raise PermissionError("retained approval no longer matches queued task")
return {
"authorization_mode": "operator_approval",
"authorization_id": task["approval_ref"],
"approval_id": task["approval_ref"],
"policy_digest": None,
"impact_assessment_digest": None,
}
def claim_execution_lease(self, *, task_id: str, tenant_id: str, worker_id: str,
approval_verifier: Any = None, autonomy_profile_verifier: Any = None,
impact_verifier: Any = None, lease_seconds: int = 60) -> dict[str, Any]:
if not isinstance(worker_id, str) or not worker_id.strip() or len(worker_id) > 128:
raise ValueError("worker_id must be a non-empty bounded identifier")
if isinstance(lease_seconds, bool) or not 1 <= lease_seconds <= 600:
raise ValueError("execution lease must be between 1 and 600 seconds")
with self._lock:
task = self._db.execute(
"SELECT * FROM tasks WHERE task_id=? AND tenant_id=?", (task_id, tenant_id),
).fetchone()
if not task:
raise KeyError("task not found in tenant scope")
if task["status"] != "queued" or task["environment"] in {"production", "regulated"}:
raise PermissionError("only an authorized, queued non-production task can be leased")
targets = json.loads(task["target_ids_json"])
self._assert_stored_plan(task, targets)
active_queued = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? "
"AND status IN ('queued','leased','running','verification')",
(tenant_id, task_id),
).fetchone()["count"]
authorization = self._execution_authorization(
task, approval_verifier=approval_verifier,
autonomy_profile_verifier=autonomy_profile_verifier,
impact_verifier=impact_verifier, active_concurrency=active_queued,
)
with self._transaction():
current = self._db.execute(
"SELECT * FROM tasks WHERE task_id=? AND tenant_id=?", (task_id, tenant_id),
).fetchone()
if (not current or current["status"] != "queued" or current["approval_ref"] != task["approval_ref"]
or current["plan_digest"] != task["plan_digest"] or current["decision_json"] != task["decision_json"]):
raise PermissionError("queued task changed while its authorization was revalidated")
active = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? AND status IN ('leased','running','verification') AND lease_stage='execution'",
(tenant_id, task_id),
).fetchone()["count"]
if active:
raise PermissionError("tenant execution concurrency limit is one active task")
rechecked_queued = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? "
"AND status IN ('queued','leased','running','verification')",
(tenant_id, task_id),
).fetchone()["count"]
current_authorization = self._execution_authorization(
current, approval_verifier=approval_verifier,
autonomy_profile_verifier=autonomy_profile_verifier,
impact_verifier=impact_verifier, active_concurrency=rechecked_queued,
)
if current_authorization != authorization:
raise PermissionError("authorization changed during execution-lease claim")
generation = current["lease_generation"] + 1
now = datetime.now(timezone.utc)
until = datetime.fromtimestamp(now.timestamp() + lease_seconds, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
deadline = datetime.fromtimestamp(now.timestamp() + 1800, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
token = str(uuid4())
self._db.execute(
"UPDATE tasks SET status='leased',lease_owner=?,lease_until=?,lease_token=?,lease_stage='execution',lease_generation=?,execution_deadline=?,updated_at=? WHERE task_id=? AND tenant_id=?",
(worker_id, until, token, generation, deadline, _now(), task_id, tenant_id),
)
self._append_event(tenant_id, task["goal_id"], task_id, "task.execution_lease_claimed", {
"worker_id": worker_id, "lease_generation": generation, "lease_until": until,
"execution_deadline": deadline, **authorization, "execution_permitted": False,
})
return self.get_task(task_id=task_id, tenant_id=tenant_id) | {
"lease_token": token, "lease_generation": generation,
}
def issue_execution_grant(self, *, task_id: str, tenant_id: str, lease_token: str,
approval_verifier: Any = None, autonomy_profile_verifier: Any = None,
impact_verifier: Any = None, grant_signer: Any = None,
grant_verifier: Any = None, execution_control: Any = None) -> dict[str, Any]:
"""Issue a runner capability from a live revalidated authorization and lease."""
if (grant_signer is None or grant_verifier is None
or execution_control is None):
raise PermissionError("grant signer, grant verifier, and root kill switch are required")
with self._transaction():
task = self._current_execution_lease(task_id, tenant_id, lease_token, {"leased"})
control_digest = execution_control.assert_enabled()
if (not isinstance(control_digest, str) or len(control_digest) != 64
or any(character not in "0123456789abcdef" for character in control_digest)):
raise PermissionError("execution-control verifier returned an invalid digest")
target_ids = json.loads(task["target_ids_json"])
if len(target_ids) != 1:
raise PermissionError("execution grant issuance requires exactly one authorized target")
breaker = self._db.execute(
"SELECT state,reason FROM circuit_breakers WHERE tenant_id=? AND target_id=? AND operation_id=?",
(tenant_id, target_ids[0], task["operation_id"]),
).fetchone()
if breaker and breaker["state"] == "open":
raise PermissionError(f"execution circuit breaker is open: {breaker['reason']}")
self._assert_stored_plan(task, target_ids)
active_queued = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? "
"AND status IN ('queued','leased','running','verification')",
(tenant_id, task_id),
).fetchone()["count"]
authorization = self._execution_authorization(
task, approval_verifier=approval_verifier,
autonomy_profile_verifier=autonomy_profile_verifier,
impact_verifier=impact_verifier, active_concurrency=active_queued,
)
token_digest = hashlib.sha256(lease_token.encode("utf-8")).hexdigest()
claims = {
"task_id": task_id,
"tenant_id": tenant_id,
"target_id": target_ids[0],
"operation_id": task["operation_id"],
"environment": task["environment"],
"plan_digest": task["plan_digest"],
**authorization,
"lease_generation": task["lease_generation"],
"runner_id": task["lease_owner"],
"lease_token_sha256": token_digest,
}
prior = self._db.execute(
"SELECT grant_id,envelope_json,grant_sha256,expires_at,consumed_at FROM execution_grants WHERE task_id=? AND lease_generation=?",
(task_id, task["lease_generation"]),
).fetchone()
if prior:
if prior["consumed_at"] is not None:
raise PermissionError("execution grant has already been consumed")
envelope = json.loads(prior["envelope_json"])
grant, digest = grant_verifier.verify(envelope, expected_claims=claims)
if (grant.get("grant_id") != prior["grant_id"] or digest != prior["grant_sha256"]
or grant.get("expires_at") != prior["expires_at"]):
raise PermissionError("stored execution grant integrity verification failed")
return {
"grant": envelope, "grant_sha256": digest, "expires_at": grant["expires_at"],
"execution_control_sha256": control_digest, "execution_permitted": False,
}
now = datetime.now(timezone.utc)
hard_deadline = datetime.fromisoformat(task["execution_deadline"].replace("Z", "+00:00"))
lease_deadline = datetime.fromisoformat(task["lease_until"].replace("Z", "+00:00"))
stored_plan = json.loads(task["plan_json"])
requested_runtime = min(int(stored_plan["max_runtime_seconds"]), 300)
expires = min(
datetime.fromtimestamp(now.timestamp() + requested_runtime, timezone.utc),
hard_deadline, lease_deadline,
)
if expires <= now:
raise PermissionError("execution lease expires before a grant can be issued")
grant_body = {
"schema_version": "a2z-execution-grant-v2",
"grant_id": str(uuid4()),
**claims,
"issued_at": now.isoformat(timespec="seconds").replace("+00:00", "Z"),
"expires_at": expires.isoformat(timespec="seconds").replace("+00:00", "Z"),
"max_runtime_seconds": requested_runtime,
}
envelope = grant_signer.sign(grant_body)
verified_grant, digest = grant_verifier.verify(envelope, expected_claims=claims)
if verified_grant != grant_body:
raise PermissionError("signed execution grant differs from the authorized lease")
self._db.execute(
"INSERT INTO execution_grants (grant_id,task_id,tenant_id,lease_generation,envelope_json,grant_sha256,expires_at,issued_at) VALUES (?,?,?,?,?,?,?,?)",
(grant_body["grant_id"], task_id, tenant_id, task["lease_generation"],
_canonical(envelope).decode(), digest, grant_body["expires_at"], grant_body["issued_at"]),
)
self._append_event(tenant_id, task["goal_id"], task_id, "task.execution_grant_issued", {
"grant_id": grant_body["grant_id"], "grant_sha256": digest,
"target_id": target_ids[0], "operation_id": task["operation_id"],
"lease_generation": task["lease_generation"], "runner_id": task["lease_owner"],
**authorization, "expires_at": grant_body["expires_at"],
"execution_control_sha256": control_digest, "execution_permitted": False,
})
return {
"grant": envelope, "grant_sha256": digest, "expires_at": grant_body["expires_at"],
"execution_control_sha256": control_digest, "execution_permitted": False,
}
def _assert_stored_plan(self, task: Any, target_ids: list[str]) -> None:
try:
plan = json.loads(task["plan_json"], object_pairs_hook=_unique_pairs)
plan_json, digest = self._validate_plan(
plan, operation_id=task["operation_id"], target_ids=tuple(target_ids),
environment=task["environment"],
)
except (KeyError, TypeError, ValueError) as exc:
raise PermissionError("stored task plan is invalid or does not match task scope") from exc
if plan_json != task["plan_json"] or digest != task["plan_digest"]:
raise PermissionError("stored task plan digest verification failed")
def start_leased_task(self, *, task_id: str, tenant_id: str, lease_token: str,
authenticated_runner_id: str, approval_verifier: Any = None,
autonomy_profile_verifier: Any = None, impact_verifier: Any = None,
expected_grant_digest: str | None = None,
grant_verifier: Any, execution_control: Any) -> dict[str, Any]:
"""Atomically consume a verified one-shot permit and start the journal state.
This does not dispatch the task. Callers must derive authenticated_runner_id
from the runner's workload identity, never from the task request body.
"""
if grant_verifier is None or execution_control is None:
raise PermissionError("grant verifier and root kill switch are required")
if (not isinstance(authenticated_runner_id, str) or not authenticated_runner_id.strip()
or len(authenticated_runner_id) > 256 or authenticated_runner_id == "*"):
raise PermissionError("authenticated runner identity must be specific")
with self._transaction():
task = self._current_execution_lease(task_id, tenant_id, lease_token, {"leased"})
if task["lease_owner"] != authenticated_runner_id:
raise PermissionError("authenticated runner does not own the active lease")
control_digest = execution_control.assert_enabled()
if (not isinstance(control_digest, str) or len(control_digest) != 64
or any(character not in "0123456789abcdef" for character in control_digest)):
raise PermissionError("execution-control verifier returned an invalid digest")
if task["operation_id"] not in TRUSTED_OPERATION_CONTRACTS:
raise PermissionError("operation is not present in the code-owned runner catalog")
target_ids = json.loads(task["target_ids_json"])
self._assert_stored_plan(task, target_ids)
plan = json.loads(task["plan_json"], object_pairs_hook=_unique_pairs)
plan_reasons = validate_operation_plan(task["operation_id"], plan)
if plan_reasons:
raise PermissionError("task plan failed code-owned validation: " + ",".join(plan_reasons))
if len(target_ids) != 1:
raise PermissionError("execution permit consumption requires one exact target")
breaker = self._db.execute(
"SELECT state,reason FROM circuit_breakers WHERE tenant_id=? AND target_id=? AND operation_id=?",
(tenant_id, target_ids[0], task["operation_id"]),
).fetchone()
if breaker and breaker["state"] == "open":
raise PermissionError(f"execution circuit breaker is open: {breaker['reason']}")
active_queued = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? "
"AND status IN ('queued','leased','running','verification')",
(tenant_id, task_id),
).fetchone()["count"]
authorization = self._execution_authorization(
task, approval_verifier=approval_verifier,
autonomy_profile_verifier=autonomy_profile_verifier,
impact_verifier=impact_verifier, active_concurrency=active_queued,
)
grant_row = self._db.execute(
"SELECT grant_id,envelope_json,grant_sha256,expires_at,consumed_at,consumed_by "
"FROM execution_grants WHERE task_id=? AND tenant_id=? AND lease_generation=?",
(task_id, tenant_id, task["lease_generation"]),
).fetchone()
if not grant_row:
raise PermissionError("active lease has no signed execution grant")
if grant_row["consumed_at"] is not None:
raise PermissionError("execution grant has already been consumed")
claims = {
"task_id": task_id, "tenant_id": tenant_id, "target_id": target_ids[0],
"operation_id": task["operation_id"], "environment": task["environment"],
"plan_digest": task["plan_digest"], **authorization,
"lease_generation": task["lease_generation"], "runner_id": authenticated_runner_id,
"lease_token_sha256": hashlib.sha256(lease_token.encode("utf-8")).hexdigest(),
}
envelope = json.loads(grant_row["envelope_json"])
grant, grant_digest = grant_verifier.verify(envelope, expected_claims=claims)
if (grant.get("grant_id") != grant_row["grant_id"]
or grant_digest != grant_row["grant_sha256"]
or grant.get("expires_at") != grant_row["expires_at"]):
raise PermissionError("stored execution grant integrity verification failed")
if (expected_grant_digest is not None
and (not isinstance(expected_grant_digest, str)
or not re.fullmatch(r"[0-9a-f]{64}", expected_grant_digest)
or expected_grant_digest != grant_digest)):
raise PermissionError("requested one-shot permit digest does not match the active grant")
lease_until = datetime.fromisoformat(task["lease_until"].replace("Z", "+00:00"))
grant_until = datetime.fromisoformat(grant["expires_at"].replace("Z", "+00:00"))
if grant_until > lease_until or grant["max_runtime_seconds"] > plan["max_runtime_seconds"]:
raise PermissionError("execution grant exceeds lease or task plan bounds")
stamp = _now()
consumed = self._db.execute(
"UPDATE execution_grants SET consumed_at=?,consumed_by=? "
"WHERE grant_id=? AND consumed_at IS NULL",
(stamp, authenticated_runner_id, grant_row["grant_id"]),
)
if consumed.rowcount != 1:
raise PermissionError("execution grant was concurrently consumed")
self._db.execute("UPDATE tasks SET status='running',updated_at=? WHERE task_id=?", (stamp, task_id))
self._append_event(tenant_id, task["goal_id"], task_id, "task.execution_started", {
"lease_generation": task["lease_generation"], "runner_id": authenticated_runner_id,
"grant_id": grant_row["grant_id"], "grant_sha256": grant_digest,
"authorization_mode": authorization["authorization_mode"],
"authorization_id": authorization["authorization_id"],
"execution_control_sha256": control_digest, "permit_consumed": True,
"execution_permitted": False,
})
return self.get_task(task_id=task_id, tenant_id=tenant_id) | {
"permit_consumed": True, "grant_digest": grant_digest,
"execution_permitted": False,
}
def get_current_execution_lease(self, *, task_id: str, tenant_id: str, runner_id: str,
approval_verifier: Any = None,
autonomy_profile_verifier: Any = None,
impact_verifier: Any = None) -> dict[str, Any]:
"""Return fresh runner-scoped lease claims for an authenticated worker adapter.
The caller must establish runner_id and tenant_id from a mutually
authenticated workload identity before calling this method. This method
itself is not a network authentication mechanism.
"""
with self._lock:
task = self._db.execute(
"SELECT * FROM tasks WHERE task_id=? AND tenant_id=?", (task_id, tenant_id),
).fetchone()
if not task:
raise KeyError("task not found in tenant scope")
if (task["status"] != "leased" or task["lease_stage"] != "execution"
or task["lease_owner"] != runner_id or not task["lease_token"]
or not task["lease_until"] or task["lease_until"] <= _now()):
raise PermissionError("runner has no current unexpired execution lease for this task")
target_ids = json.loads(task["target_ids_json"])
if len(target_ids) != 1:
raise PermissionError("runner lease requires exactly one target")
active_queued = self._db.execute(
"SELECT COUNT(*) AS count FROM tasks WHERE tenant_id=? AND task_id<>? "