-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathaboyeur.py
More file actions
4021 lines (3720 loc) · 158 KB
/
Copy pathaboyeur.py
File metadata and controls
4021 lines (3720 loc) · 158 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
"""Bounded cross-model orchestration for `brigade run`."""
from __future__ import annotations
import copy
import inspect
import json
import os
import re
import signal
import sys
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from functools import partial, wraps
from json import JSONDecoder
from pathlib import Path
from typing import Any, Callable, Iterator, Mapping
from uuid import uuid4
from . import agents
from . import codex_appserver
from . import context_eval
from . import evidence_brief as evidence_brief_mod
from . import graphtrail_delta
from . import localio
from . import proc, receipt_schema, runguard
from . import run_control
from . import run_checkpoint
from . import run_events
from . import run_journal
from . import run_lifecycle
from . import run_projector
from . import run_shadow
from .result_integrity import validate_final_output
from .run_receipts import (
agent_result_from_worker as _agent_result_from_worker,
agent_result_payload as _agent_result_payload,
assignment_payload as _assignment_payload,
worker_payload as _worker_payload,
write_agent_logs as _write_agent_logs,
write_worker_logs as _write_worker_logs,
)
from .run_transport import Assignment, WorkerResult
from .roster import Agent, Roster, is_cli_allowed, read_only_capability_error, timeout_for, workers
from .route_catalog import RouteBrief, route_brief, uncovered_stages, unknown_covers
from .route_policy import (
RoutePolicyDecision,
direct_worker_skill_ids,
planner_skill_policy_section,
validate_plan_skill_bindings,
worker_skill_policy_constraint,
)
CODE_GRAPH_HEADING = "## Code graph context (GraphTrail, read-only)"
CODE_GRAPH_LIMIT = 4000
DRIFT_IMPACT_HEADING = "## Upstream drift impact (Upstream Drift + GraphTrail, read-only)"
DRIFT_IMPACT_LIMIT = 4000
BRIEF_BUDGET_BYTES = 6000
NOOP_DETAIL = "no-op"
# Journal authority is the default for every new run (issue #568 slice 11).
# Enrollment stays durable and per-run: existing runs are classified only from
# their stored run.json fields, so legacy snapshot-only runs are never migrated
# by a later Brigade release or environment change.
_AUTHORITY_REQUEST_FIELD = "run_journal_authority_requested"
# A plan-mode seat has no write tool, so any file it tries to create fails, and a
# failed write is what invites harness hooks to hijack the seat's final message
# (#518). Say the quiet part in the prompt: the plan lives in the reply, nowhere else.
NO_PLAN_FILE_RULE = (
"- Do not write, create, or edit any file, including a plan, design, or context file. "
"This seat runs with every write tool hidden: the write fails, and the failure can "
"replace your plan with tool or hook commentary. The plan belongs in this reply only."
)
# The corrective turn is the last chance before the run dies on an unparsable
# plan, so it restates the output contract instead of only naming the parse error.
PLAN_JSON_ONLY_RULE = (
"Reply with the JSON plan object and nothing else: no prose, no preamble, no explanation, "
"no tool-failure or hook commentary, nothing before or after the object. "
'If no worker is useful, reply with exactly {"assignments": []}.'
)
@dataclass(frozen=True)
class CodeGraphBrief:
attached: bool
text: str = ""
bytes: int = 0
@dataclass(frozen=True)
class DriftImpactBrief:
attached: bool
text: str = ""
bytes: int = 0
pending_count: int = 0
EvidenceBrief = evidence_brief_mod.EvidenceBrief
@dataclass(frozen=True)
class BriefSet:
code_graph: CodeGraphBrief
drift_impact: DriftImpactBrief
evidence: EvidenceBrief
budget_bytes: int
attached: tuple[dict[str, object], ...]
def _brief_bytes(text: str) -> int:
return len(text.encode())
def _truncate_brief_text(text: str, limit: int, label: str) -> str:
if _brief_bytes(text) <= limit:
return text
note = f"\n\n[{label} brief truncated to fit the run brief budget.]\n"
room = max(0, limit - _brief_bytes(note))
clipped = text.encode()[:room].decode(errors="ignore")
boundary = clipped.rfind("\n")
if boundary > 0:
clipped = clipped[:boundary]
else:
clipped = clipped.rstrip()
return clipped.rstrip() + note
def _brief_order(task: str) -> tuple[str, ...]:
lowered = task.lower()
if any(word in lowered for word in ("release", "changelog", "publish", "version")):
return ("drift_impact", "code_graph", "evidence")
if any(word in lowered for word in ("doc", "readme", "handoff", "memory", "evidence")):
return ("drift_impact", "code_graph", "evidence")
return ("code_graph", "drift_impact", "evidence")
def arbitrate_briefs(
task: str,
*,
code_graph: CodeGraphBrief,
drift_impact: DriftImpactBrief,
evidence: EvidenceBrief | None = None,
budget_bytes: int = BRIEF_BUDGET_BYTES,
) -> BriefSet:
evidence = evidence or EvidenceBrief(attached=False)
briefs: dict[str, CodeGraphBrief | DriftImpactBrief | EvidenceBrief] = {
"code_graph": code_graph,
"drift_impact": drift_impact,
"evidence": evidence,
}
kept_code_graph = CodeGraphBrief(attached=False)
kept_drift = DriftImpactBrief(attached=False)
kept_evidence = EvidenceBrief(attached=False)
used = 0
attached: list[dict[str, object]] = []
for name in _brief_order(task):
brief = briefs[name]
if not brief.attached or not brief.text:
continue
remaining = budget_bytes - used
if remaining <= 0:
continue
text = brief.text
truncated = False
if _brief_bytes(text) > remaining:
if remaining < 500:
continue
text = _truncate_brief_text(text, remaining, name.replace("_", " "))
truncated = True
size = _brief_bytes(text)
used += size
attached.append({"name": name, "bytes": size, "truncated": truncated})
if name == "code_graph":
kept_code_graph = CodeGraphBrief(attached=True, text=text, bytes=size)
elif name == "drift_impact":
kept_drift = DriftImpactBrief(
attached=True,
text=text,
bytes=size,
pending_count=getattr(brief, "pending_count", 0),
)
else:
kept_evidence = EvidenceBrief(attached=True, text=text, bytes=size)
return BriefSet(
code_graph=kept_code_graph,
drift_impact=kept_drift,
evidence=kept_evidence,
budget_bytes=budget_bytes,
attached=tuple(attached),
)
def _prepend_brief(prompt: str, *, heading: str, text: str) -> str:
if not text:
return prompt
if heading in prompt:
return prompt
return f"{text}\n{prompt}"
def _prepend_optional_briefs(
prompt: str,
*,
code_graph: CodeGraphBrief | None = None,
drift_impact: DriftImpactBrief | None = None,
evidence: EvidenceBrief | None = None,
) -> str:
if code_graph is not None and code_graph.attached and code_graph.text:
prompt = _prepend_brief(prompt, heading=CODE_GRAPH_HEADING, text=code_graph.text)
if drift_impact is not None and drift_impact.attached and drift_impact.text:
prompt = _prepend_brief(prompt, heading=DRIFT_IMPACT_HEADING, text=drift_impact.text)
if evidence is not None and evidence.attached and evidence.text:
prompt = _prepend_brief(prompt, heading=evidence_brief_mod.HEADING, text=evidence.text)
return prompt
def _prepend_code_graph(prompt: str, code_graph: CodeGraphBrief | None) -> str:
if CODE_GRAPH_HEADING in prompt:
return prompt
return _prepend_optional_briefs(prompt, code_graph=code_graph)
def _truncate_on_line_boundary(text: str, limit: int = CODE_GRAPH_LIMIT) -> str:
if len(text) <= limit:
return text
note = f"\n\n[GraphTrail context truncated to {limit} chars.]\n"
room = max(0, limit - len(note))
clipped = text[:room]
boundary = clipped.rfind("\n")
if boundary > 0:
clipped = clipped[:boundary]
else:
clipped = clipped.rstrip()
return clipped.rstrip() + note
def _graphtrail_bin() -> str | None:
from . import context_cmd
return context_cmd._graphtrail_bin()
def code_graph_brief(cwd: Path | None, task: str) -> CodeGraphBrief:
if cwd is None:
return CodeGraphBrief(attached=False)
db_path = cwd / ".graphtrail" / "graphtrail.db"
if not db_path.is_file():
return CodeGraphBrief(attached=False)
binary = _graphtrail_bin()
if binary is None:
return CodeGraphBrief(attached=False)
result = proc.run(
[binary, "--db", str(db_path), "context", task, "--markdown", "--limit", "8"],
timeout=10.0,
cwd=cwd,
)
if result.code != 0:
return CodeGraphBrief(attached=False)
body = result.stdout.strip()
if not body:
return CodeGraphBrief(attached=False)
text = _truncate_on_line_boundary(f"{CODE_GRAPH_HEADING}\n\n{body}\n")
return CodeGraphBrief(attached=True, text=text, bytes=len(text.encode()))
def _upstream_drift_state_path() -> Path:
return Path(os.environ.get("UPSTREAM_DRIFT_STATE_PATH", Path.home() / ".config/upstream-drift/state.json"))
def _upstream_drift_reports_dir() -> Path:
return Path(os.environ.get("UPSTREAM_DRIFT_REPORTS_DIR", Path.home() / "repos/upstream-drift/reports"))
def _read_json_dict(path: Path) -> dict[str, object] | None:
try:
value = json.loads(path.read_text())
except (OSError, json.JSONDecodeError):
return None
return value if isinstance(value, dict) else None
def _latest_drift_report(reports_dir: Path, watch: str) -> str:
if not _safe_watch_name(watch):
return ""
root = reports_dir / watch
if not root.is_dir():
return ""
reports = sorted(root.glob("*.md"), key=lambda path: path.stat().st_mtime, reverse=True)
if not reports:
return ""
try:
return reports[0].read_text()
except OSError:
return ""
def _safe_watch_name(value: str) -> bool:
return bool(re.fullmatch(r"[A-Za-z0-9._-]+", value))
def _drift_symbol_candidates(watch: str, report: str) -> list[str]:
candidates: list[str] = []
for value in [watch, *re.findall(r"`([A-Za-z_][A-Za-z0-9_.:-]{2,80})`", report)]:
for part in re.split(r"[^A-Za-z0-9_.:]+", value):
cleaned = part.strip("._:")
if len(cleaned) < 3:
continue
if cleaned not in candidates:
candidates.append(cleaned)
if len(candidates) >= 4:
return candidates
return candidates
def _drift_report_excerpt(report: str, limit: int = 700) -> str:
lines = []
for line in report.splitlines():
stripped = line.strip()
if not stripped or stripped == "---" or stripped.startswith(("watch:", "date:")):
continue
lines.append(stripped)
if len(" ".join(lines)) >= limit:
break
text = "\n".join(lines)
return _truncate_on_line_boundary(text, limit)
def _pending_drift_entries() -> list[dict[str, object]]:
state = _read_json_dict(_upstream_drift_state_path())
if state is None:
return []
entries: list[dict[str, object]] = []
for name, raw in sorted(state.items()):
if not isinstance(name, str) or not _safe_watch_name(name) or not isinstance(raw, dict):
continue
failures = raw.get("consecutiveFailures")
if not isinstance(failures, int) or failures < 3:
continue
entries.append(
{
"name": name,
"consecutive_failures": failures,
"last_run_at": raw.get("lastRunAt") if isinstance(raw.get("lastRunAt"), str) else None,
}
)
return entries
def drift_impact_brief(cwd: Path | None) -> DriftImpactBrief:
if cwd is None:
return DriftImpactBrief(attached=False)
db_path = cwd / ".graphtrail" / "graphtrail.db"
binary = _graphtrail_bin()
if not db_path.is_file() or binary is None:
return DriftImpactBrief(attached=False)
pending = _pending_drift_entries()
if not pending:
return DriftImpactBrief(attached=False)
reports_dir = _upstream_drift_reports_dir()
sections = [DRIFT_IMPACT_HEADING, ""]
for entry in pending[:3]:
watch = str(entry["name"])
report = _latest_drift_report(reports_dir, watch)
sections.append(
f"### {watch}\n"
f"- consecutive failures: {entry['consecutive_failures']}\n"
f"- last run: {entry.get('last_run_at') or 'unknown'}"
)
excerpt = _drift_report_excerpt(report)
if excerpt:
sections.append("Drift report excerpt:\n" + excerpt)
for candidate in _drift_symbol_candidates(watch, report):
result = proc.run(
[binary, "--db", str(db_path), "impact", candidate, "--depth", "2"],
timeout=5.0,
cwd=cwd,
)
body = result.stdout.strip()
if result.code == 0 and body:
sections.append(f"GraphTrail impact for `{candidate}`:\n{body}")
break
text = _truncate_on_line_boundary("\n\n".join(sections).strip() + "\n", DRIFT_IMPACT_LIMIT)
return DriftImpactBrief(
attached=True,
text=text,
bytes=len(text.encode()),
pending_count=len(pending),
)
def build_plan_prompt(
task: str,
roster: Roster,
corrective_note: str | None = None,
read_only: bool = False,
code_graph: CodeGraphBrief | None = None,
drift_impact: DriftImpactBrief | None = None,
evidence: EvidenceBrief | None = None,
route: RouteBrief | None = None,
no_file_writes: bool = False,
skill_policy: RoutePolicyDecision | None = None,
) -> str:
worker_lines = "\n".join(
f"- {agent.name}: cli={agent.cli}; "
+ (f"read_only_capable={str(agent.read_only_capable).lower()}; " if read_only else "")
+ f"role={agent.role}"
for agent in workers(roster)
)
if not worker_lines:
worker_lines = "- no workers configured"
note = f"\nCorrection needed: {corrective_note}\n" if corrective_note else ""
policy = f"\n\n{_read_only_rules()}\n" if read_only else ""
capability_rule = "- Assign only workers with read_only_capable=true.\n" if read_only else ""
no_write_rule = f"\n{NO_PLAN_FILE_RULE}" if no_file_writes else ""
route_section = ""
route_rule = ""
if route is not None and route.attached and route.text:
route_section = f"\n{route.text}"
route_rule = (
'\n- Tag each assignment with "covers": ["<stage>", ...] naming the route '
"stages it satisfies; every required route stage must be covered."
)
skill_section = ""
skill_text = planner_skill_policy_section(skill_policy)
if skill_text:
skill_section = f"\n{skill_text}"
prompt = (
"You are the Brigade aboyeur. Split the user's task across the available workers.\n"
"Return exactly one JSON object, with no prose outside JSON:\n"
'{"assignments":[{"stage":1,"worker":"<worker-name>","task":"<specific sub-task>",'
'"covers":["<route-stage>"],"selected_skill_ids":["<artifact-id>"]}]}\n'
f"{note}\n"
f"User task:\n{task}\n\n"
f"Available workers, excluding you:\n{worker_lines}\n"
f"{route_section}"
f"{skill_section}\n"
f"Rules:\n- Use at most {roster.max_workers} assignments per stage.\n"
"- Stage must be a positive integer starting at stage 1.\n"
"- Assignments in the same stage run in parallel; later stages receive earlier-stage worker results.\n"
"- Omit stage only for backwards-compatible stage 1 assignments.\n"
"- Assign only listed workers.\n"
f"{capability_rule}"
"- Use zero assignments only if no worker is useful."
f"{route_rule}"
f"{no_write_rule}"
f"{policy}"
)
return _prepend_optional_briefs(prompt, code_graph=code_graph, drift_impact=drift_impact, evidence=evidence)
def _extract_json(text: str) -> object:
stripped = text.strip()
fenced = _extract_fenced_json(stripped)
if fenced is not None:
return json.loads(fenced)
return _loads_first_json_object(stripped)
def _extract_fenced_json(text: str) -> str | None:
lines = text.splitlines()
start = None
for index, line in enumerate(lines):
if line.strip().startswith("```"):
start = index + 1
break
if start is None:
return None
for end in range(start, len(lines)):
if lines[end].strip().startswith("```"):
return "\n".join(lines[start:end]).strip()
return None
def _loads_first_json_object(text: str) -> object:
decoder = JSONDecoder()
for index, char in enumerate(text):
if char != "{":
continue
try:
value, _ = decoder.raw_decode(text[index:])
except json.JSONDecodeError:
continue
return value
return json.loads(text)
def make_run_dir(base: Path, now: datetime | None = None) -> Path:
stamp = (now or datetime.now(timezone.utc)).strftime("%Y%m%d-%H%M%S")
return base / f"{stamp}-{uuid4().hex[:8]}"
def _resolve_authority_state(run_dir: Path) -> str:
"""Return one of 'legacy', 'authority-requested', 'authoritative'.
'legacy' only when no durable authority request is present
(run_journal_authority_requested is not true on run.json). 'authority-
requested' only when the durable authority request is true and NONE of the
four projection metadata fields is present on run.json (projector_version,
journal_present, journal_last_sequence, journal_last_event_digest). Once
ANY of the four projection metadata fields is present, the run is past the
not-yet-authoritative fallback: incomplete fields, a stale or wrong
projector version, a bounded read failure, a chain failure, a cursor
failure, or a digest failure all raise a bounded LifecycleJournalError and
never downgrade. 'authoritative' only when run.json carries all four
journal-metadata fields with projector_version == run_projector.
PROJECTOR_VERSION and its saved journal_last_sequence /
journal_last_event_digest verifies against the event at that sequence in a
bounded, chain-valid journal prefix. A bound failure or chain error on a
run with NO projection metadata fields returns 'authority-requested' (the
not-yet-authoritative fallback); it never authorizes projection.
"""
run_json = run_dir / "run.json"
try:
raw = run_json.read_bytes()
except FileNotFoundError:
return "legacy"
try:
meta = json.loads(raw)
except (ValueError, UnicodeDecodeError):
meta = None
if not isinstance(meta, dict) or meta.get(_AUTHORITY_REQUEST_FIELD) is not True:
return "legacy"
metadata_fields = (
"projector_version",
"journal_present",
"journal_last_sequence",
"journal_last_event_digest",
)
present = [name for name in metadata_fields if name in meta]
if not present:
return "authority-requested"
# Past the not-yet-authoritative fallback: no downgrade is allowed.
missing = [name for name in metadata_fields if name not in meta]
if missing:
raise run_lifecycle.LifecycleJournalError(
run_events._bound(f"authority run missing projection metadata: {sorted(missing)}")
)
if meta.get("projector_version") != run_projector.PROJECTOR_VERSION:
raise run_lifecycle.LifecycleJournalError(run_events._bound("authority run projector version is not current"))
# Finding 1: once any projection metadata exists, journal_present must be
# exactly True. A false or wrong-typed value is invalid authoritative
# metadata and must fail closed before the checkpoint/lifecycle append.
if meta.get("journal_present") is not True:
raise run_lifecycle.LifecycleJournalError(run_events._bound("authority run journal_present is not true"))
saved_seq = meta.get("journal_last_sequence")
saved_digest = meta.get("journal_last_event_digest")
if isinstance(saved_seq, bool) or not isinstance(saved_seq, int) or saved_seq < 1:
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authority run saved journal_last_sequence is invalid")
)
if not isinstance(saved_digest, str):
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authority run saved journal_last_event_digest is invalid")
)
journal_path = run_lifecycle._journal_path(run_dir)
try:
report = run_journal.read_journal_bounded(journal_path)
except (OSError, run_journal.RunJournalError) as exc:
raise run_lifecycle._bound_journal_failure(exc) from exc
if report.partial_tail is not None or report.chain_errors:
raise run_lifecycle.LifecycleJournalError(run_events._bound("authority run journal is not chain-valid"))
events = report.events
# Finding 2: the bounded verified prefix must reject ANY event whose run_id
# differs from run_dir.name, not only the event at the saved cursor. A
# chain-valid journal that mixes in a foreign-run-id event is not
# exclusively this run's and must fail closed.
for event in events:
if event.run_id != run_dir.name:
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authority run journal contains an event with a foreign run_id")
)
if saved_seq > len(events):
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authority run saved sequence is beyond the journal tail")
)
event = events[saved_seq - 1]
if event.event_digest != saved_digest:
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authority run saved cursor does not verify against the journal")
)
return "authoritative"
_PROJECTION_METADATA_FIELDS = (
"projector_version",
"journal_present",
"journal_last_sequence",
"journal_last_event_digest",
)
def _payload_requests_authority(payload: dict[str, object]) -> bool:
"""Cheap payload classification: does the incoming run.json payload carry
any authority signal that requires filesystem authority resolution?
Returns True when the payload carries the durable authority request field
with ANY value (present, including an explicit ``False`` which is a forged
downgrade attempt) OR any of the four projection metadata fields
(projector_version, journal_present, journal_last_sequence,
journal_last_event_digest). Only legacy and lifecycle-only writes (the
authority request field ABSENT and all four projection metadata fields
ABSENT) return False so ``_write_json`` can skip the existing-run.json
authority read entirely. No-downgrade is preserved: any incoming durable
authority request (true or false) or projected metadata still resolves
and validates authority through ``_resolve_authority_state``.
"""
if _AUTHORITY_REQUEST_FIELD in payload:
return True
return any(field in payload for field in _PROJECTION_METADATA_FIELDS)
def _genuine_journal_ahead(run_dir: Path) -> bool:
"""Return True only for one verified checkpoint/event pair ahead.
``check_projection_readiness`` reports ``REASON_JOURNAL_AHEAD`` whenever
the artifact's ``last_compared_sequence``/``last_compared_event_digest``
does not match the journal tail, which conflates a real committed
checkpoint/event pair whose shadow step has not run yet with a forged,
stale, or multi-pair cursor. Catch-up is safe only when the artifact cursor
verifies against an actual event in a clean journal and the tail is exactly
one structurally covered pair ahead.
"""
artifact_path = run_shadow.shadow_artifact_path(run_dir)
try:
data = json.loads(artifact_path.read_text())
except (OSError, ValueError):
return False
if not isinstance(data, dict):
return False
baseline = run_shadow._verify_stale_baseline(
run_dir,
run_dir.name,
data.get("last_compared_sequence"),
data.get("last_compared_event_digest"),
)
if baseline is None:
return False
try:
journal_report = run_journal.read_journal_bounded(run_lifecycle._journal_path(run_dir))
except (OSError, run_journal.RunJournalError):
return False
if journal_report.partial_tail is not None or journal_report.chain_errors:
return False
if not journal_report.events:
return False
tail_seq = journal_report.events[-1].sequence
return run_shadow._checkpoint_status_write_gap(run_dir, prior_seq=baseline[0], tail_seq=tail_seq)
def _authoritative_prior_decision(run_dir: Path, prior_snapshot: dict[str, object]) -> str:
"""Resolve the prior authority gate for an authoritative run.
A ready prior returns immediately. A prior that is not ready may catch up
exactly one verified checkpoint/event pair by recording parity against the
persisted pre-write snapshot and then requiring readiness to become fully
green. Forged cursors, multi-pair gaps, mismatches, errors, and a catch-up
that does not restore readiness all raise before a new pair is appended.
"""
report = run_shadow.check_projection_readiness(run_dir)
if report.ready:
return "ready"
if report.reasons == (run_shadow.REASON_JOURNAL_AHEAD,) and _genuine_journal_ahead(run_dir):
run_shadow.record_shadow_comparison(run_dir, prior_snapshot)
caught_up = run_shadow.check_projection_readiness(run_dir)
if caught_up.ready:
artifact_path = run_shadow.shadow_artifact_path(run_dir)
try:
artifact = json.loads(artifact_path.read_text())
except (OSError, ValueError) as exc:
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative run prior catch-up evidence is unreadable")
) from exc
mismatches = artifact.get("mismatches") if isinstance(artifact, dict) else None
errors = artifact.get("errors") if isinstance(artifact, dict) else None
if (
not isinstance(artifact, dict)
or artifact.get("last_outcome") != run_shadow.OUTCOME_MATCH
or isinstance(mismatches, bool)
or not isinstance(mismatches, int)
or mismatches != 0
or isinstance(errors, bool)
or not isinstance(errors, int)
or errors != 0
or artifact.get("last_error_category") is not None
):
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative run prior catch-up evidence is not a clean match")
)
return "ready"
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative run prior catch-up not ready: " + ",".join(sorted(caught_up.reasons)))
)
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative run prior gate not ready: " + ",".join(sorted(report.reasons)))
)
def _project_authority_candidate(path: Path, run_dir: Path, candidate: dict[str, object]) -> None:
"""Re-read the bounded journal, verify a clean chain, project the
candidate, and atomically replace run.json with the projected bytes."""
try:
journal_report = run_journal.read_journal_bounded(run_lifecycle._journal_path(run_dir))
except (OSError, run_journal.RunJournalError) as exc:
raise run_lifecycle._bound_journal_failure(exc) from exc
if journal_report.partial_tail is not None or journal_report.chain_errors:
raise run_lifecycle.LifecycleJournalError(run_events._bound("authority write journal is not chain-valid"))
try:
projection = run_projector.project_run_snapshot(candidate, journal_report.events, journal_present=True)
except run_projector.ProjectionError as exc:
raise run_lifecycle.LifecycleJournalError(run_events._bound(exc.diagnostic)) from exc
localio.write_text_atomic(path, projection.to_bytes().decode("utf-8"))
def _write_json_inner(path: Path, payload: object) -> None:
# run.json is polled by `brigade runs watch/steer/interrupt` while the run
# rewrites it, so the write must be atomic or a concurrent reader can
# observe a truncated file.
if path.name == "run.json" and isinstance(payload, dict):
status = payload.get("status")
if isinstance(status, str) and status:
transition_status = status
approval_reference = payload.get("approval_reference")
if status == "running" and isinstance(approval_reference, Mapping):
decision_state = approval_reference.get("decision_state")
if decision_state == "pending":
# Keep the compatibility snapshot on a status understood
# by the previous reader while journaling the intentional
# pause.
transition_status = "paused"
elif decision_state in {"approved", "rejected", "held", "consumed"}:
# Approval facts own these state changes. Treat their
# compatibility snapshot refreshes as neutral so a
# same-status write cannot leave a checkpoint promising a
# run.resumed event that record_lifecycle_transition
# correctly suppresses.
transition_status = "approval-state-refresh"
run_dir = path.parent
workspace = runguard.resolve_run_lock_workspace(payload, run_dir)
# Cheap payload classification BEFORE the filesystem authority
# resolution. Legacy and lifecycle-only status writes (the durable
# authority request field ABSENT and all four projection metadata
# fields ABSENT in the incoming payload) never read/parse the
# existing run.json only to resolve authority, so an unreadable
# legacy run.json cannot make a status write fail. No-downgrade is
# preserved: an incoming durable authority request of ANY value
# (including an explicit False, which is a forged downgrade
# attempt) or any projection metadata field still resolves and
# validates authority through _resolve_authority_state.
if _payload_requests_authority(payload):
authority_state = _resolve_authority_state(run_dir)
else:
authority_state = "legacy"
# Construct the canonical legacy candidate and the projection base
# exactly once. The base strips the four journal-derived metadata
# fields; the same object is the base-stripped checkpoint body
# whenever the resolved state is authority-requested or
# authoritative.
candidate = copy.deepcopy(payload)
for derived in (
"projector_version",
"journal_present",
"journal_last_sequence",
"journal_last_event_digest",
):
candidate.pop(derived, None)
encoded_candidate = json.dumps(candidate, indent=2, sort_keys=True) + "\n"
base_bytes = encoded_candidate.encode("utf-8")
body_kind = (
run_checkpoint._BODY_KIND_BASE_STRIPPED
if authority_state in {"authority-requested", "authoritative"}
else None
)
# Prior authority gate (authoritative only): fail closed BEFORE
# the checkpoint/lifecycle append when the prior committed state
# is not ready and not exactly one recoverable checkpoint/event
# pair ahead. The catch-up uses the persisted pre-write snapshot,
# never the incoming next status. Legacy and authority-requested
# runs skip this gate.
if authority_state == "authoritative":
try:
prior_snapshot = json.loads(path.read_bytes())
except (OSError, ValueError, UnicodeDecodeError) as exc:
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative prior snapshot is unreadable")
) from exc
if not isinstance(prior_snapshot, dict):
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative prior snapshot is not an object")
)
_authoritative_prior_decision(run_dir, prior_snapshot)
# Exact order: activate the journal, publish the recovery
# checkpoint, append the lifecycle status transition, record the
# shadow parity, consult the post-parity readiness veto, then
# atomically replace run.json. A CheckpointError from
# write_checkpoint fails BEFORE the lifecycle append and BEFORE
# run.json replacement. The prior gate above raises BEFORE any
# append for an authoritative run with a real prior defect.
run_lifecycle.prepare_lifecycle_journal(
run_dir,
workspace=workspace,
incoming_snapshot=payload,
)
run_checkpoint.write_checkpoint(
run_dir,
base_bytes,
workspace=workspace,
paired_event_type=run_lifecycle.STATUS_EVENT_TYPE.get(transition_status),
body_kind=body_kind,
)
run_lifecycle.record_lifecycle_transition(
run_dir,
status=transition_status,
# The receipt payload identifies the lock workspace
# (lock_workspace or cwd); the run directory layout does not.
workspace=workspace,
incoming_snapshot=payload,
)
run_shadow.record_shadow_comparison(run_dir, payload)
if authority_state == "legacy":
# Legacy runs skip the veto and write the legacy body (slice 5).
localio.write_text_atomic(path, encoded_candidate)
return
readiness = run_shadow.check_projection_readiness(run_dir)
if authority_state == "authority-requested":
# Authority-requested projection uses the POST-parity readiness
# report (a ready first comparison projects that same write),
# never the pre-parity decision. A not-ready gate falls back to
# the legacy body until a ready first comparison catches up.
if readiness.ready:
_project_authority_candidate(path, run_dir, candidate)
else:
localio.write_text_atomic(path, encoded_candidate)
return
# Authoritative writes require both the prior gate and this
# post-parity gate to be fully ready. No comparison-gap override
# survives: the only recoverable lag was consumed before append.
if readiness.ready:
_project_authority_candidate(path, run_dir, candidate)
return
raise run_lifecycle.LifecycleJournalError(
run_events._bound("authoritative run gate not ready: " + ",".join(sorted(readiness.reasons)))
)
localio.write_text_atomic(path, json.dumps(payload, indent=2, sort_keys=True) + "\n")
if path.name == "run.json" and isinstance(payload, dict):
run_shadow.record_shadow_comparison(path.parent, payload)
def _write_json(path: Path, payload: object) -> None:
"""Write JSON, serializing every run.json checkpoint/event transaction."""
if (
path.name == "run.json"
and isinstance(payload, dict)
and isinstance(payload.get("status"), str)
and payload["status"]
):
with run_lifecycle.checkpoint_event_pair():
_write_json_inner(path, payload)
return
_write_json_inner(path, payload)
def _revision_contains(revisions_dir: Path, projection: bytes) -> bool:
"""Return whether a preserved sidecar revision matches ``projection``."""
if not revisions_dir.is_dir():
return False
for revision_path in revisions_dir.glob("*.json"):
try:
if revision_path.read_bytes() == projection:
return True
except OSError:
continue
return False
def _supports_directory_fsync() -> bool:
return os.name == "posix"
def _fsync_directory(path: Path) -> None:
"""Persist directory entries where the platform supports directory fsync."""
if not _supports_directory_fsync():
return
directory_fd = os.open(path, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
def _ensure_directory_durable(path: Path) -> None:
"""Create missing directory levels and persist each new parent entry."""
missing: list[Path] = []
current = path
while not current.exists():
missing.append(current)
current = current.parent
for directory in reversed(missing):
try:
directory.mkdir()
except FileExistsError:
if not directory.is_dir():
raise
else:
_fsync_directory(directory.parent)
def _write_new_revision(revisions_dir: Path, encoded: bytes) -> None:
"""Exclusively create the next immutable sidecar revision."""
_ensure_directory_durable(revisions_dir)
sequence = max(
(int(path.stem) for path in revisions_dir.glob("*.json") if path.stem.isascii() and path.stem.isdecimal()),
default=0,
)
while True:
sequence += 1
revision_path = revisions_dir / f"{sequence:06d}.json"
writer_acquired = False
try:
fd = os.open(revision_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
writer_acquired = True
with os.fdopen(fd, "wb") as handle:
handle.write(encoded)
handle.flush()
os.fsync(handle.fileno())
_fsync_directory(revisions_dir)
except FileExistsError:
continue
except BaseException:
if writer_acquired:
revision_path.unlink(missing_ok=True)
raise
return
def write_sidecar_revision(run_dir: Path, filename: str, payload: object) -> None:
"""Append an immutable sidecar revision, then update its compatibility file."""
projection_path = run_dir / filename
revisions_dir = run_dir / "revisions" / Path(filename).stem
if projection_path.exists():
legacy_projection = projection_path.read_bytes()
json.loads(legacy_projection)
if not _revision_contains(revisions_dir, legacy_projection):
_write_new_revision(revisions_dir, legacy_projection)
_write_new_revision(revisions_dir, (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8"))
_write_json(projection_path, payload)
def _utc_iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _slug(text: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return slug[:48] or "brigade-run"
def _safe_document_content(text: str) -> str:
# The ingester treats `##` as handoff section boundaries, so keep routed
# document content at ### or below.
return re.sub(r"(?m)^##(?!#)", "###", text).strip()
def _one_line(text: str) -> str:
return re.sub(r"\s+", " ", text).strip()
def write_run_handoff(
inbox: Path,
*,
task: str,
cwd: Path | None,
output_dir: Path | None,
assignments: list[Assignment],
worker_results: list[WorkerResult],
final_text: str,
read_only: bool = False,
now: datetime | None = None,
) -> Path:
timestamp = (now or datetime.now(timezone.utc)).strftime("%Y-%m-%d-%H%M")
safe_task = _one_line(task)
path = inbox / f"{timestamp}-brigade-run-{_slug(safe_task)}.md"
worker_summary = (
"\n".join(
f"- {result.worker}: {'ok' if result.ok else 'failed'}"
+ (f" ({_one_line(result.detail)})" if result.detail else "")
for result in worker_results
)
or "- no workers dispatched"
)
assignment_summary = (