-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperator
More file actions
executable file
·7076 lines (6393 loc) · 261 KB
/
Copy pathoperator
File metadata and controls
executable file
·7076 lines (6393 loc) · 261 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
#!/usr/bin/env python3
"""
Operator Control Plane CLI (MVP) - Isolated Witness Edition
A local, file-backed control plane for coordinating multiple AI coding harnesses.
"""
from __future__ import annotations
import argparse
import datetime
import fcntl
import glob
import hashlib
import json
import os
import pwd
import re
import shutil
import socket
import sqlite3
import stat
import subprocess
import sys
import tempfile
from pathlib import Path
import yaml
import authority_client
import authority_projection
import crystal_parse
LEDGER_DB_NAME = "ledger.sqlite3"
LEDGER_HASH_FORMAT = "operator-ledger-event-v1"
LEDGER_SCHEMA_VERSION = 1
VALID_TASK_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
VALID_CLAIM_ID = re.compile(r"^claim-[0-9]{4,}$")
VALID_SHA256 = re.compile(r"^[0-9a-fA-F]{64}$")
TRUST_RECORD_DIRS = {
"tasks": "task",
"claims": "claim",
"evidence": "evidence",
"handoffs": "handoff",
"usage": "usage",
}
MUTATING_COMMANDS = {
"init",
"task-create",
"claim-add",
"evidence-attach",
"crystal-attach",
"crystal-import",
"crystal-bridge",
"usage-add",
"usage-import",
"usage-annotate",
"handoff-add",
"session-start",
"session-end",
}
EVIDENCE_TYPES = [
"run_log",
"manifest",
"database_query",
"test_output",
"git_commit",
"screenshot",
"transcript",
"paper_section",
"external_doc",
"session_crystal",
]
class LedgerWriteError(RuntimeError):
pass
class EvidenceFingerprintError(RuntimeError):
pass
class IdentityPolicyError(RuntimeError):
pass
class IdentityPolicyLoader(yaml.SafeLoader):
pass
def construct_unique_identity_mapping(loader, node, deep=False):
loader.flatten_mapping(node)
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
try:
duplicate = key in mapping
except TypeError as exc:
raise yaml.constructor.ConstructorError(
"while constructing identity mapping",
node.start_mark,
"found an unhashable mapping key",
key_node.start_mark,
) from exc
if duplicate:
raise yaml.constructor.ConstructorError(
"while constructing identity mapping",
node.start_mark,
f"found duplicate key {key!r}",
key_node.start_mark,
)
mapping[key] = loader.construct_object(value_node, deep=deep)
return mapping
IdentityPolicyLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_unique_identity_mapping,
)
def acquire_command_lock(command: str):
operator_dir = find_operator_dir()
if not operator_dir:
return None
lock_path = os.path.join(operator_dir, "ledger.lock")
is_mutating = command in MUTATING_COMMANDS
if not is_mutating and not os.path.exists(lock_path):
return None
handle = None
fd = None
try:
flags = os.O_RDONLY | (os.O_CREAT if is_mutating else 0)
fd = os.open(lock_path, flags, 0o666)
handle = os.fdopen(fd, "r")
fd = None
lock_mode = fcntl.LOCK_EX if is_mutating else fcntl.LOCK_SH
fcntl.flock(handle.fileno(), lock_mode)
return handle
except OSError as exc:
if fd is not None:
os.close(fd)
if handle is not None:
handle.close()
raise LedgerWriteError(f"Could not acquire ledger command lock: {exc}") from exc
def release_command_lock(handle) -> None:
if handle is None:
return
try:
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
finally:
handle.close()
def canonical_json(data: any) -> str:
return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=str)
def ledger_db_path(operator_dir: str) -> str:
return os.path.join(operator_dir, LEDGER_DB_NAME)
def connect_event_store(operator_dir: str, read_only: bool = False) -> sqlite3.Connection:
db_path = Path(ledger_db_path(operator_dir)).resolve()
if read_only:
conn = sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True)
else:
conn = sqlite3.connect(str(db_path), timeout=5.0)
conn.execute("PRAGMA busy_timeout = 5000")
conn.row_factory = sqlite3.Row
return conn
def initialize_event_store(operator_dir: str) -> None:
os.makedirs(operator_dir, exist_ok=True)
conn = None
try:
conn = connect_event_store(operator_dir)
schema_version = conn.execute("PRAGMA user_version").fetchone()[0]
if schema_version > LEDGER_SCHEMA_VERSION:
raise LedgerWriteError(
f"Durable ledger schema version {schema_version} is newer than this CLI supports "
f"(maximum {LEDGER_SCHEMA_VERSION})"
)
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA synchronous = FULL")
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS ledger_events (
event_id TEXT PRIMARY KEY,
record_type TEXT NOT NULL,
record_id TEXT NOT NULL,
version INTEGER NOT NULL CHECK (version > 0),
event_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
actor_uid INTEGER,
actor_name TEXT,
created_at TEXT NOT NULL,
source_command TEXT,
previous_event_hash TEXT,
event_hash TEXT NOT NULL,
UNIQUE(record_type, record_id, version)
);
CREATE INDEX IF NOT EXISTS idx_ledger_events_record
ON ledger_events(record_type, record_id, version);
CREATE TRIGGER IF NOT EXISTS ledger_events_no_update
BEFORE UPDATE ON ledger_events
BEGIN
SELECT RAISE(ABORT, 'ledger_events is append-only');
END;
CREATE TRIGGER IF NOT EXISTS ledger_events_no_delete
BEFORE DELETE ON ledger_events
BEGIN
SELECT RAISE(ABORT, 'ledger_events is append-only');
END;
"""
)
conn.execute(f"PRAGMA user_version = {LEDGER_SCHEMA_VERSION}")
conn.commit()
except LedgerWriteError:
raise
except sqlite3.Error as exc:
raise LedgerWriteError(f"Could not initialize durable ledger store: {exc}") from exc
finally:
if conn is not None:
conn.close()
def operator_dir_for_path(filepath: str) -> str | None:
path = Path(os.path.abspath(filepath))
for parent in [path.parent, *path.parents]:
if parent.name == ".operator":
return str(parent)
return None
def logical_record_id(record_type: str, record: dict) -> str:
id_fields = {
"task": "task_id",
"claim": "claim_id",
"evidence": "evidence_id",
"handoff": "handoff_id",
"usage": "usage_id",
}
field = id_fields[record_type]
record_id = record.get(field)
if not record_id:
raise LedgerWriteError(f"{record_type} record is missing required field '{field}'")
if record_type in {"evidence", "handoff"}:
task_id = record.get("task_id")
if not task_id:
raise LedgerWriteError(
f"{record_type} record '{record_id}' is missing required field 'task_id'"
)
return f"{task_id}/{record_id}"
return str(record_id)
def record_items_for_data(filepath: str, data: any) -> list[tuple[str, str, dict]]:
operator_dir = operator_dir_for_path(filepath)
if not operator_dir:
return []
try:
absolute_path = Path(os.path.abspath(filepath))
absolute_operator_dir = Path(os.path.abspath(operator_dir))
relative_parts = absolute_path.relative_to(absolute_operator_dir).parts
except ValueError:
return []
if not relative_parts or relative_parts[0] not in TRUST_RECORD_DIRS:
return []
record_type = TRUST_RECORD_DIRS[relative_parts[0]]
if record_type == "usage":
if len(relative_parts) != 2 or not relative_parts[1].endswith(".yaml"):
return []
if not isinstance(data, list):
raise LedgerWriteError(f"Usage ledger '{filepath}' must contain a YAML list")
records = data
else:
expected_depth = 3 if record_type in {"evidence", "handoff"} else 2
if len(relative_parts) != expected_depth or not relative_parts[-1].endswith(".yaml"):
return []
if not isinstance(data, dict):
raise LedgerWriteError(f"{record_type} ledger '{filepath}' must contain a YAML mapping")
records = [data]
items = []
seen_ids = set()
for record in records:
if not isinstance(record, dict):
raise LedgerWriteError(
f"{record_type} ledger '{filepath}' contains a non-mapping record"
)
record_id = logical_record_id(record_type, record)
if record_id in seen_ids:
raise LedgerWriteError(
f"{record_type} ledger '{filepath}' contains duplicate record ID '{record_id}'"
)
seen_ids.add(record_id)
items.append((record_type, record_id, record))
return items
def visible_record_files(operator_dir: str) -> list[str]:
patterns = [
os.path.join(operator_dir, "tasks", "*.yaml"),
os.path.join(operator_dir, "claims", "*.yaml"),
os.path.join(operator_dir, "evidence", "*", "evidence-*.yaml"),
os.path.join(operator_dir, "handoffs", "*", "handoff-*.yaml"),
os.path.join(operator_dir, "usage", "*.yaml"),
]
return sorted(path for pattern in patterns for path in glob.glob(pattern))
def load_visible_records(
operator_dir: str,
) -> tuple[dict[tuple[str, str], tuple[dict, str]], list[str]]:
records = {}
errors = []
for filepath in visible_record_files(operator_dir):
relative_path = os.path.relpath(filepath, operator_dir)
try:
with open(filepath, "r") as handle:
data = yaml.safe_load(handle)
items = record_items_for_data(filepath, data)
except Exception as exc:
errors.append(
f"[Error] Durable ledger cannot parse YAML projection {relative_path}: {exc}"
)
continue
for record_type, record_id, record in items:
key = (record_type, record_id)
if key in records:
errors.append(
f"[Error] Duplicate YAML projection for {record_type} {record_id}: "
f"{records[key][1]} and {relative_path}"
)
continue
records[key] = (record, relative_path)
return records, errors
def event_hash_for_fields(
record_type: str,
record_id: str,
version: int,
event_type: str,
payload_json: str,
actor_uid: int | None,
actor_name: str | None,
created_at: str,
source_command: str | None,
previous_event_hash: str | None,
) -> str:
hash_fields = {
"hash_format": LEDGER_HASH_FORMAT,
"record_type": record_type,
"record_id": record_id,
"version": version,
"event_type": event_type,
"payload_json": payload_json,
"actor_uid": actor_uid,
"actor_name": actor_name,
"created_at": created_at,
"source_command": source_command,
"previous_event_hash": previous_event_hash,
}
return hashlib.sha256(canonical_json(hash_fields).encode("utf-8")).hexdigest()
def event_type_for(record_type: str, version: int, source_command: str) -> str:
if source_command == "legacy-bootstrap":
return "baseline_imported"
if record_type == "usage" and source_command == "session-start":
return "session_started"
if record_type == "usage" and source_command == "session-end":
return "session_ended"
return "record_created" if version == 1 else "record_updated"
def append_record_events(
operator_dir: str,
items: list[tuple[str, str, dict]],
source_command: str,
) -> int:
if not items:
return 0
actor = get_executor_identity()
created_at = get_current_utc_iso()
inserted = 0
conn = connect_event_store(operator_dir)
try:
conn.execute("BEGIN IMMEDIATE")
for record_type, record_id, record in items:
payload_json = canonical_json(record)
previous = conn.execute(
"""
SELECT version, payload_json, event_hash
FROM ledger_events
WHERE record_type = ? AND record_id = ?
ORDER BY version DESC
LIMIT 1
""",
(record_type, record_id),
).fetchone()
if previous and previous["payload_json"] == payload_json:
continue
version = (previous["version"] + 1) if previous else 1
previous_hash = previous["event_hash"] if previous else None
event_type = event_type_for(record_type, version, source_command)
event_hash = event_hash_for_fields(
record_type,
record_id,
version,
event_type,
payload_json,
actor.get("uid"),
actor.get("user"),
created_at,
source_command,
previous_hash,
)
conn.execute(
"""
INSERT INTO ledger_events (
event_id, record_type, record_id, version, event_type, payload_json,
actor_uid, actor_name, created_at, source_command, previous_event_hash,
event_hash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
event_hash,
record_type,
record_id,
version,
event_type,
payload_json,
actor.get("uid"),
actor.get("user"),
created_at,
source_command,
previous_hash,
event_hash,
),
)
inserted += 1
conn.commit()
except Exception as exc:
conn.rollback()
raise LedgerWriteError(f"Could not append durable ledger event: {exc}") from exc
finally:
conn.close()
return inserted
def ensure_event_store(operator_dir: str) -> None:
initialize_event_store(operator_dir)
try:
conn = connect_event_store(operator_dir, read_only=True)
try:
event_count = conn.execute("SELECT COUNT(*) FROM ledger_events").fetchone()[0]
finally:
conn.close()
except sqlite3.Error as exc:
raise LedgerWriteError(f"Could not inspect durable ledger store: {exc}") from exc
if event_count:
return
records, errors = load_visible_records(operator_dir)
if errors:
raise LedgerWriteError(errors[0].removeprefix("[Error] "))
if records:
items = [
(record_type, record_id, payload)
for (record_type, record_id), (payload, _) in records.items()
]
append_record_events(operator_dir, items, "legacy-bootstrap")
def latest_event_payload(conn: sqlite3.Connection, record_type: str, record_id: str) -> str | None:
row = conn.execute(
"""
SELECT payload_json
FROM ledger_events
WHERE record_type = ? AND record_id = ?
ORDER BY version DESC
LIMIT 1
""",
(record_type, record_id),
).fetchone()
return row["payload_json"] if row else None
def assert_projection_current(
operator_dir: str,
filepath: str,
new_items: list[tuple[str, str, dict]],
) -> None:
new_keys = {(record_type, record_id) for record_type, record_id, _ in new_items}
old_items = []
if os.path.exists(filepath):
try:
with open(filepath, "r") as handle:
old_data = yaml.safe_load(handle)
old_items = record_items_for_data(filepath, old_data)
except Exception as exc:
raise LedgerWriteError(
f"YAML projection is not readable before write: {filepath}: {exc}"
) from exc
old_keys = {(record_type, record_id) for record_type, record_id, _ in old_items}
removed_keys = old_keys - new_keys
if removed_keys:
removed = ", ".join(f"{kind} {record_id}" for kind, record_id in sorted(removed_keys))
raise LedgerWriteError(
f"Refusing to remove append-only records from YAML projection: {removed}"
)
conn = connect_event_store(operator_dir, read_only=True)
try:
for record_type, record_id, record in old_items:
stored_payload = latest_event_payload(conn, record_type, record_id)
if stored_payload != canonical_json(record):
raise LedgerWriteError(
f"YAML projection for {record_type} {record_id} differs from the durable ledger; "
"run 'operator doctor' before writing"
)
for record_type, record_id, _ in new_items:
if (record_type, record_id) in old_keys:
continue
if latest_event_payload(conn, record_type, record_id) is not None:
raise LedgerWriteError(
f"Refusing to reuse durable record ID for {record_type} {record_id}"
)
finally:
conn.close()
def preflight_projection(operator_dir: str, filepath: str, data: any) -> None:
ensure_event_store(operator_dir)
items = record_items_for_data(filepath, data)
assert_projection_current(operator_dir, filepath, items)
def atomic_write_text(filepath: str, content: str) -> None:
parent = os.path.dirname(filepath)
os.makedirs(parent, exist_ok=True)
existing_stat = os.stat(filepath) if os.path.exists(filepath) else None
if existing_stat:
target_mode = stat.S_IMODE(existing_stat.st_mode)
else:
current_umask = os.umask(0)
os.umask(current_umask)
target_mode = 0o666 & ~current_umask
fd, temp_path = tempfile.mkstemp(prefix=f".{os.path.basename(filepath)}.", dir=parent)
try:
if existing_stat:
try:
os.fchown(fd, -1, existing_stat.st_gid)
except PermissionError:
pass
try:
os.fchown(fd, existing_stat.st_uid, -1)
except PermissionError:
pass
os.fchmod(fd, target_mode)
with os.fdopen(fd, "w") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, filepath)
directory_fd = os.open(parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
except Exception:
try:
os.unlink(temp_path)
except FileNotFoundError:
pass
raise
def audit_event_store(operator_dir: str) -> list[str]:
db_path = ledger_db_path(operator_dir)
if not os.path.exists(db_path):
return [
f"[Error] Durable ledger store is missing: {db_path}. Run 'operator init' to "
"baseline this YAML ledger."
]
visible_records, messages = load_visible_records(operator_dir)
latest_events = {}
chain_state = {}
try:
conn = connect_event_store(operator_dir, read_only=True)
try:
schema_version = conn.execute("PRAGMA user_version").fetchone()[0]
if schema_version != LEDGER_SCHEMA_VERSION:
messages.append(
f"[Error] Durable ledger schema version {schema_version} is unsupported; "
f"expected {LEDGER_SCHEMA_VERSION}"
)
return messages
rows = conn.execute(
"""
SELECT event_id, record_type, record_id, version, event_type, payload_json,
actor_uid, actor_name, created_at, source_command, previous_event_hash,
event_hash
FROM ledger_events
ORDER BY record_type, record_id, version
"""
).fetchall()
finally:
conn.close()
except sqlite3.Error as exc:
messages.append(f"[Error] Durable ledger store cannot be read: {exc}")
return messages
for row in rows:
key = (row["record_type"], row["record_id"])
previous = chain_state.get(key)
expected_version = previous[0] + 1 if previous else 1
expected_previous_hash = previous[1] if previous else None
if row["version"] != expected_version:
messages.append(
f"[Error] Durable ledger version gap for {key[0]} {key[1]}: "
f"expected {expected_version}, got {row['version']}"
)
if row["previous_event_hash"] != expected_previous_hash:
messages.append(
f"[Error] Durable ledger hash chain is broken for {key[0]} {key[1]} "
f"at version {row['version']}"
)
try:
decoded_payload = json.loads(row["payload_json"])
if canonical_json(decoded_payload) != row["payload_json"]:
messages.append(
f"[Error] Durable ledger payload is not canonical for {key[0]} {key[1]} "
f"version {row['version']}"
)
except (TypeError, json.JSONDecodeError):
messages.append(
f"[Error] Durable ledger payload is invalid JSON for {key[0]} {key[1]} "
f"version {row['version']}"
)
expected_hash = event_hash_for_fields(
row["record_type"],
row["record_id"],
row["version"],
row["event_type"],
row["payload_json"],
row["actor_uid"],
row["actor_name"],
row["created_at"],
row["source_command"],
row["previous_event_hash"],
)
if row["event_hash"] != expected_hash or row["event_id"] != row["event_hash"]:
messages.append(
f"[Error] Durable ledger event hash mismatch for {key[0]} {key[1]} "
f"version {row['version']}"
)
chain_state[key] = (row["version"], row["event_hash"])
latest_events[key] = row["payload_json"]
for key, (record, relative_path) in sorted(visible_records.items()):
stored_payload = latest_events.get(key)
if stored_payload is None:
messages.append(
f"[Error] Durable ledger has no event for YAML {key[0]} {key[1]} "
f"({relative_path})"
)
elif stored_payload != canonical_json(record):
messages.append(
f"[Error] Durable ledger mismatch for {key[0]} {key[1]}: "
f"YAML projection {relative_path} differs from latest event"
)
for key in sorted(set(latest_events) - set(visible_records)):
messages.append(f"[Error] Durable ledger latest {key[0]} {key[1]} has no YAML projection")
tasks = {
record_id: record
for (record_type, record_id), (record, _) in visible_records.items()
if record_type == "task"
}
for (record_type, record_id), (record, relative_path) in sorted(visible_records.items()):
if record_type == "task":
continue
task_id = record.get("task_id")
task = tasks.get(task_id)
if task is None:
messages.append(
f"[Error] YAML {record_type} {record_id} references missing task {task_id} "
f"({relative_path})"
)
continue
if record_type == "claim" and record_id not in (task.get("claims") or []):
messages.append(f"[Error] Claim {record_id} is not referenced by owning task {task_id}")
elif record_type == "evidence":
if record.get("path_or_url") not in (task.get("evidence") or []):
messages.append(
f"[Error] Evidence {record_id} is not referenced by owning task {task_id}"
)
claim_id = record.get("claim_id")
if claim_id:
claim_entry = visible_records.get(("claim", claim_id))
evidence_ref = f"evidence/{task_id}/{record.get('evidence_id')}.yaml"
if claim_entry is not None and claim_entry[0].get("task_id") != task_id:
messages.append(
f"[Error] Evidence {record_id} belongs to task {task_id} but claim "
f"{claim_id} belongs to task {claim_entry[0].get('task_id')}"
)
elif claim_entry is None or evidence_ref not in (
claim_entry[0].get("evidence_refs") or []
):
messages.append(
f"[Error] Evidence {record_id} is not referenced by claim {claim_id}"
)
elif record_type == "handoff":
handoff_ref = f"handoffs/{task_id}/{record.get('handoff_id')}.yaml"
if handoff_ref not in (task.get("handoffs") or []):
messages.append(
f"[Error] Handoff {record_id} is not referenced by owning task {task_id}"
)
return messages
def max_durable_sequence(
operator_dir: str, record_type: str, prefix: str, scope: str | None = None
) -> int:
if not os.path.exists(ledger_db_path(operator_dir)):
return 0
conn = connect_event_store(operator_dir, read_only=True)
try:
if scope is None:
rows = conn.execute(
"SELECT DISTINCT record_id FROM ledger_events WHERE record_type = ?",
(record_type,),
).fetchall()
else:
rows = conn.execute(
"""
SELECT DISTINCT record_id
FROM ledger_events
WHERE record_type = ? AND record_id LIKE ?
""",
(record_type, f"{scope}/%"),
).fetchall()
finally:
conn.close()
max_id = 0
pattern = re.compile(rf"^{re.escape(prefix)}(\d+)$")
for row in rows:
leaf_id = row["record_id"].rsplit("/", 1)[-1]
match = pattern.match(leaf_id)
if match:
max_id = max(max_id, int(match.group(1)))
return max_id
def durable_record_exists(operator_dir: str, record_type: str, record_id: str) -> bool:
if not os.path.exists(ledger_db_path(operator_dir)):
return False
conn = connect_event_store(operator_dir, read_only=True)
try:
row = conn.execute(
"SELECT 1 FROM ledger_events WHERE record_type = ? AND record_id = ? LIMIT 1",
(record_type, record_id),
).fetchone()
finally:
conn.close()
return row is not None
def find_operator_dir(start_dir: str | None = None) -> str | None:
"""Search upwards from start_dir for a directory named '.operator'."""
if start_dir is None:
start_dir = os.getcwd()
current = os.path.abspath(start_dir)
while True:
candidate = os.path.join(current, ".operator")
if os.path.isdir(candidate):
return candidate
parent = os.path.dirname(current)
if parent == current:
break
current = parent
return None
def resolve_operator_context() -> tuple[authority_client.Enrollment | None, str | None]:
enrollment = authority_client.resolve_enrollment()
if enrollment is None:
return None, find_operator_dir()
operator_dir = enrollment.repository_path / ".operator"
try:
metadata = operator_dir.lstat()
except FileNotFoundError:
return enrollment, None
if not stat.S_ISDIR(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
raise authority_client.EnrollmentError(
f"enrolled operator directory is not a real directory: {operator_dir}"
)
return enrollment, str(operator_dir)
def get_current_utc_iso() -> str:
"""Return the current time in UTC ISO format."""
return datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat()
def load_yaml(filepath: str) -> any:
"""Helper to load a YAML file safely."""
try:
with open(filepath, "r") as f:
return yaml.safe_load(f)
except Exception as e:
print(f"Error loading YAML {filepath}: {e}", file=sys.stderr)
return None
def save_yaml(data: any, filepath: str) -> bool:
"""Helper to save a python object to a YAML file."""
try:
rendered = yaml.safe_dump(data, default_flow_style=False, sort_keys=False)
items = record_items_for_data(filepath, data)
if items:
operator_dir = operator_dir_for_path(filepath)
ensure_event_store(operator_dir)
assert_projection_current(operator_dir, filepath, items)
source_command = sys.argv[1] if len(sys.argv) > 1 else "internal"
append_record_events(operator_dir, items, source_command)
atomic_write_text(filepath, rendered)
return True
except LedgerWriteError:
raise
except Exception as e:
raise LedgerWriteError(f"Error saving YAML {filepath}: {e}") from e
def get_machine_identity() -> str:
"""Short machine name for record provenance.
`OPERATOR_MACHINE` overrides detection (also the test hook); otherwise the
short hostname. The ledger itself stays single-machine — this field only
records WHERE a session/usage/evidence record was produced.
"""
override = os.environ.get("OPERATOR_MACHINE")
if override and override.strip():
return override.strip()
try:
host = socket.gethostname()
except Exception:
return "unknown"
short = host.split(".")[0].strip()
return short or "unknown"
def get_executor_identity() -> dict:
test_uid_env = os.environ.get("OPERATOR_TEST_UID")
test_sentinel_env = os.environ.get("OPERATOR_TEST_SENTINEL")
use_override = False
spoof_attempt = False
if test_uid_env:
if test_sentinel_env == "true" or test_sentinel_env == "1":
use_override = True
else:
spoof_attempt = True
if use_override:
uid = int(test_uid_env)
try:
user = pwd.getpwuid(uid).pw_name
except Exception:
user = f"uid-{uid}"
return {
"uid": uid,
"user": user,
"machine": get_machine_identity(),
"test_override_active": True,
}
else:
uid = os.getuid()
try:
user = pwd.getpwuid(uid).pw_name
except Exception:
user = f"uid-{uid}"
res = {"uid": uid, "user": user, "machine": get_machine_identity()}
if spoof_attempt:
res["test_override_unauthorized"] = True
return res
def load_identity_policy(operator_dir: str) -> dict:
identity_path = os.path.join(operator_dir, "identity.yaml")
if not os.path.exists(identity_path):
return {"mode": "single_user", "uids": {}}
try:
with open(identity_path, "r") as handle:
raw_policy = yaml.load(handle, Loader=IdentityPolicyLoader)
except (OSError, yaml.YAMLError) as exc:
raise IdentityPolicyError(f"could not read identity.yaml: {exc}") from exc
if raw_policy is None:
raw_policy = {}
if not isinstance(raw_policy, dict):
raise IdentityPolicyError("identity.yaml must contain a mapping")
mode = raw_policy.get("mode", "single_user")
if not isinstance(mode, str) or mode not in {"single_user", "enforced"}:
raise IdentityPolicyError("identity.yaml mode must be either 'single_user' or 'enforced'")
raw_uids = raw_policy.get("uids", {})
if raw_uids is None:
raw_uids = {}
if not isinstance(raw_uids, dict):
raise IdentityPolicyError("identity.yaml uids must contain a mapping")
identities = {}
for raw_uid, raw_identity in raw_uids.items():
if isinstance(raw_uid, bool):
raise IdentityPolicyError(f"identity UID key {raw_uid!r} is not a non-negative integer")
if isinstance(raw_uid, int):
uid = raw_uid
elif isinstance(raw_uid, str) and re.fullmatch(r"[0-9]+", raw_uid):
uid = int(raw_uid)
else:
raise IdentityPolicyError(f"identity UID key {raw_uid!r} is not a non-negative integer")
if uid < 0:
raise IdentityPolicyError(f"identity UID key {raw_uid!r} is not a non-negative integer")
if uid in identities:
raise IdentityPolicyError(f"identity UID {uid} is configured more than once")
legacy_scalar = isinstance(raw_identity, str)
if legacy_scalar:
name = raw_identity.strip()
roles = {"builder", "verifier"}
elif isinstance(raw_identity, dict):
name_value = raw_identity.get("name")
if not isinstance(name_value, str):
raise IdentityPolicyError(f"identity UID {uid} must have a string name")
name = name_value.strip()
raw_roles = raw_identity.get("roles")
if not isinstance(raw_roles, list) or any(
not isinstance(role, str) for role in raw_roles
):
raise IdentityPolicyError(f"identity UID {uid} roles must be a list of role names")
roles = set(raw_roles)
unknown_roles = roles - {"builder", "verifier"}
if unknown_roles:
rendered = ", ".join(sorted(unknown_roles))
raise IdentityPolicyError(f"identity UID {uid} has unknown role(s): {rendered}")
else:
raise IdentityPolicyError(
f"identity UID {uid} must map to a name or a name/roles mapping"
)
if not name:
raise IdentityPolicyError(f"identity UID {uid} must have a non-empty name")
identities[uid] = {
"name": name,
"roles": frozenset(roles),
"legacy_scalar": legacy_scalar,
}
return {"mode": mode, "uids": identities}
def identity_policy_for_write(operator_dir: str) -> dict | None:
try:
return load_identity_policy(operator_dir)
except IdentityPolicyError as exc:
print(f"Error: invalid identity policy: {exc}", file=sys.stderr)
return None
def require_executor_role(policy: dict, executor: dict, role: str, action: str) -> dict | None:
if policy["mode"] != "enforced":
return None
uid = executor.get("uid")
identity = policy["uids"].get(uid)
if identity is None:
print(
f"Error: refusing to {action}: executor uid {uid} is not a known identity",
file=sys.stderr,
)