-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path_runtime_execute.py
More file actions
1673 lines (1600 loc) · 72.9 KB
/
Copy path_runtime_execute.py
File metadata and controls
1673 lines (1600 loc) · 72.9 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
"""Execute-lifecycle mixin: ``SkillLoopExecuteMixin`` — the
``_SkillLoopRunner.execute()`` orchestrator and its lifecycle-phase helper
methods (config build, mission-context prep, bounded planning, loop
invocation, outcome-field extraction, stage-transition decision, outcome
assembly).
Split out of ``_runtime.py`` so that module stays under the maintainability
line-count target. Every name here is re-exported from ``_runtime.py`` (see
its module docstring and ``__all__``) so external imports are unaffected.
"""
from __future__ import annotations
import logging
import os
import shutil
import stat
import tempfile
import time
from pathlib import Path
from typing import Callable
from ..core.knobs import resolve_role_reasoning_effort
from ..core.ports import EventSink
from ..core.role_reply import strip_named_lines
from ..core.runner_errors import is_execution_host_startup_error
from ..engineer.runner import should_clear_thread_id_after_outcome
from ._env import env_flag as _env_flag
from ._runtime_backends import _Outcome
from ._runtime_helpers import (
_checkpoint_path_for,
_ExecuteState,
_project_state_dir_for,
_should_run_stage_transition,
)
log = logging.getLogger(__name__)
# The advisory Planner preview outlines; a preview that is still running after
# this long is exploring, which is the Engineer's job.
_PLANNER_PREVIEW_MAX_SECONDS = 180
def _engineer_model_for_task(default: str, vertical: str, task_text: str, project_root: Path | None) -> str:
"""The engineer model for this task, or the route model its vertical asked for.
A vertical's module may define ``model_route_for_task(text) -> str`` (the
research vertical routes figure work to ``figure``); the route's knob
``ARGUS_SKILL_<ROUTE>_MODEL`` then names the model and ``auto`` keeps the
engineer's. Anything failing here keeps the default: routing is a
convenience and must never stop a mission.
"""
if not vertical or not task_text:
return default
try:
from ..verticals._base import load_vertical
module = load_vertical(vertical, project_root=project_root)
route_for = getattr(module, "model_route_for_task", None)
route = str(route_for(task_text) or "").strip() if callable(route_for) else ""
if not route:
return default
from ..core.knobs import resolve_task_route_model
chosen = resolve_task_route_model(route, fallback=default)
except Exception: # noqa: BLE001 - see above
return default
if chosen != default:
log.info("engineer model for this task: %s (route %s)", chosen, route)
return chosen
def _decided_vertical(config: object, workdir: Path) -> str:
"""The Manager-classified vertical of this mission, or "" when undecided.
Role-prompt resolution falls back to research for an unclassified
workspace, so it cannot tell a research campaign from a task nobody has
classified yet; the mission's own classification can.
"""
active = str(getattr(config, "active_vertical", "") or "").strip().lower()
if active:
return active
from ..skills.vertical_select import resolve_vertical_if_decided
state_root = getattr(config, "vertical_state_root", None) or workdir
try:
return str(resolve_vertical_if_decided(Path(state_root)) or "").strip().lower()
except Exception: # noqa: BLE001 — undecided is the safe reading
return ""
def _execution_host_blocked_outcome(outcome: object) -> bool:
return (
getattr(outcome, "status", "") == "infra_blocked"
and getattr(outcome, "stop_kind", None) == "backend_unavailable"
and is_execution_host_startup_error(getattr(outcome, "reason", ""))
)
def _engineer_guidance(
state_root: Path | None,
workdir: Path,
manager: object | None = None,
*,
receiver=None,
delivery_messages: list[str] | None = None,
mission_id: str = "",
) -> list[str]:
"""Project the typed operator context after persisting fresh inbox input."""
if state_root is None:
return []
from ..core.file_lock import FileLockCancelled, bounded_file_lock_wait
from ..core.operator_context import (
OperatorContextUnavailable,
build_operator_context_block,
)
from ..core.run_gateway import current_run_interrupt_reason
from ._inbox_delivery import DurableInboxReceiver, operator_live_turn
owned_receiver = receiver is None
receiver = receiver or DurableInboxReceiver(state_root, consumer="engineer", project_root=workdir)
def cancelled() -> bool:
return bool(current_run_interrupt_reason())
try:
with bounded_file_lock_wait(timeout_seconds=float("inf"), cancelled=cancelled):
transient = receiver.receive(manager=manager, mission_id=mission_id, cancelled=cancelled)
if delivery_messages is not None:
delivery_messages.extend(transient)
block, _revision = build_operator_context_block(
"engineer", state_root, mission_id=mission_id, live_turn=operator_live_turn(transient),
)
except FileLockCancelled as exc:
if current_run_interrupt_reason():
return []
raise OperatorContextUnavailable("Current Engineer OperatorContext read was cancelled") from exc
except Exception as exc:
raise OperatorContextUnavailable("Current Engineer OperatorContext is unavailable") from exc
finally:
if owned_receiver:
# Standalone callers have no complete-prompt settlement hook.
receiver.release_pending()
return [block] if block else []
class SkillLoopExecuteMixin:
"""Mission-execution half of ``_SkillLoopRunner``."""
@staticmethod
def _is_link_or_reparse_point(path: Path) -> bool:
try:
if path.is_symlink():
return True
is_junction = getattr(path, "is_junction", None)
if callable(is_junction) and is_junction():
return True
attributes = getattr(os.lstat(path), "st_file_attributes", 0)
return bool(
attributes
& getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
)
except OSError:
return False
@classmethod
def _has_linked_ancestor(cls, path: Path) -> bool:
for parent in path.parents:
if parent == parent.parent:
break
if os.path.lexists(parent) and cls._is_link_or_reparse_point(parent):
return True
return False
@classmethod
def _is_unaliased_regular_file(cls, path: Path) -> bool:
try:
return (
not cls._is_link_or_reparse_point(path)
and not cls._has_linked_ancestor(path)
and path.is_file()
and os.stat(path).st_nlink == 1
)
except OSError:
return False
@classmethod
def _detach_packaged_skill_hardlink(cls, path: Path) -> None:
"""Give an installed Skill its own inode before establishing the guard.
uv legitimately hardlinks wheel resources from its cache. Replacing our
directory entry preserves those cached bytes and other environments;
in-place writes or weakening the execution-time alias check would not.
Symlinks, junctions and redirected ancestors remain disallowed.
"""
if cls._is_link_or_reparse_point(path) or cls._has_linked_ancestor(path):
return
before = path.stat()
if not stat.S_ISREG(before.st_mode) or before.st_nlink <= 1:
return
content = path.read_bytes()
fd, filename = tempfile.mkstemp(prefix=".argus-skill-", dir=path.parent)
temporary = Path(filename)
try:
with os.fdopen(fd, "wb") as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
temporary.chmod(stat.S_IMODE(before.st_mode))
if cls._is_link_or_reparse_point(path) or cls._has_linked_ancestor(path):
raise OSError(f"protected Skill path changed while preparing: {path}")
current = path.stat()
identity = lambda value: (value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns)
if identity(current) != identity(before) or path.read_bytes() != content:
# Another startup may already have detached exactly these bytes.
if cls._is_unaliased_regular_file(path) and path.read_bytes() == content:
return
raise OSError(f"protected Skill changed while preparing: {path}")
os.replace(temporary, path)
if not cls._is_unaliased_regular_file(path) or path.read_bytes() != content:
raise OSError(f"protected Skill private copy did not verify: {path}")
finally:
temporary.unlink(missing_ok=True)
@classmethod
def _remove_pipeline_state_replacement(cls, path: Path) -> None:
if path.is_symlink():
path.unlink()
return
is_junction = getattr(path, "is_junction", None)
if callable(is_junction) and is_junction():
path.rmdir()
return
if cls._is_link_or_reparse_point(path):
if path.is_dir():
path.rmdir()
else:
path.unlink()
return
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
@classmethod
def _snapshot_pipeline_state(
cls,
workdir: Path,
) -> tuple[Path, bool, bytes | None, str]:
from ..core.pipeline_state import pipeline_state_path
path = pipeline_state_path(workdir.expanduser().resolve(strict=False))
try:
if os.path.lexists(path.parent) and (
cls._is_link_or_reparse_point(path.parent)
or not path.parent.is_dir()
):
return path, True, None, "formal pipeline state parent is not a real directory"
if not os.path.lexists(path):
return path, False, None, ""
if not cls._is_unaliased_regular_file(path):
return path, True, None, "formal pipeline state is not a regular file"
return path, True, path.read_bytes(), ""
except OSError as exc:
return path, True, None, f"cannot snapshot formal pipeline state: {exc}"
@classmethod
def _restore_pipeline_state(
cls,
snapshot: tuple[Path, bool, bytes | None, str],
) -> tuple[bool, str, bool]:
path, existed, content, snapshot_error = snapshot
if snapshot_error:
return True, snapshot_error, False
try:
# A fresh mission may have neither a pipeline file nor its parent.
# Restoration must not create that parent and then accuse the
# mission of creating formal state that never existed.
if not existed and not os.path.lexists(path.parent):
return False, "", True
if cls._has_linked_ancestor(path.parent):
raise OSError(
f"formal pipeline state ancestor was replaced: {path.parent}"
)
parent_changed = False
if os.path.lexists(path.parent) and (
cls._is_link_or_reparse_point(path.parent)
or not path.parent.is_dir()
):
cls._remove_pipeline_state_replacement(path.parent)
path.parent.mkdir(parents=True, exist_ok=True)
parent_changed = True
elif not path.parent.exists():
path.parent.mkdir(parents=True, exist_ok=True)
parent_changed = True
current_exists = os.path.lexists(path)
if not existed:
if not current_exists and not parent_changed:
return False, "", True
if current_exists:
cls._remove_pipeline_state_replacement(path)
return (
True,
"Playground execution created formal pipeline state; removed it",
True,
)
if (
not parent_changed
and current_exists
and cls._is_unaliased_regular_file(path)
and path.read_bytes() == content
):
return False, "", True
if current_exists:
cls._remove_pipeline_state_replacement(path)
if cls._has_linked_ancestor(path.parent):
raise OSError(
f"formal pipeline state ancestor was replaced: {path.parent}"
)
path.write_bytes(content or b"")
if (
cls._is_link_or_reparse_point(path.parent)
or not path.parent.is_dir()
or not cls._is_unaliased_regular_file(path)
or path.read_bytes() != (content or b"")
):
raise OSError("restored formal pipeline state did not verify")
return (
True,
"Playground execution modified formal pipeline state; restored it",
True,
)
except OSError as exc:
return True, f"formal pipeline state isolation failed: {exc}", False
@staticmethod
def _canonical_playground_skill_paths() -> tuple[Path, Path]:
root = Path(__file__).resolve().parents[1]
return (
root
/ "domains"
/ "chemistry"
/ "skills"
/ "engineer"
/ "workflows"
/ "chemistry-playground.md",
root
/ "domains"
/ "chemistry"
/ "skills"
/ "reviewer"
/ "chemistry-playground-review.md",
)
@classmethod
def _snapshot_playground_skill_files(
cls,
) -> tuple[tuple[tuple[Path, bytes], ...], str]:
snapshots: list[tuple[Path, bytes]] = []
try:
canonical_paths = cls._canonical_playground_skill_paths()
protected_paths = list(canonical_paths)
for parent in dict.fromkeys(path.parent for path in canonical_paths):
for sibling in sorted(parent.iterdir()):
# Another mission may be detaching a cache hardlink now;
# its short-lived private copy is not a packaged Skill.
if sibling.name.startswith(".argus-skill-"):
continue
if sibling not in protected_paths and sibling.is_file():
protected_paths.append(sibling)
for path in protected_paths:
cls._detach_packaged_skill_hardlink(path)
if (
cls._is_link_or_reparse_point(path.parent)
or not path.parent.is_dir()
or not cls._is_unaliased_regular_file(path)
):
return (), f"protected Playground Skill is not a regular file: {path}"
snapshots.append((path, path.read_bytes()))
except OSError as exc:
return (), f"cannot snapshot protected Playground Skills: {exc}"
return tuple(snapshots), ""
@classmethod
def _restore_playground_skill_files(
cls,
snapshots: tuple[tuple[Path, bytes], ...],
snapshot_error: str,
) -> tuple[bool, str, bool]:
if snapshot_error:
return True, snapshot_error, False
changed_paths: list[str] = []
try:
canonical_paths = set(cls._canonical_playground_skill_paths())
recovery_parents = {
path.parent
for path in canonical_paths
if (
not path.parent.is_dir()
or cls._is_link_or_reparse_point(path.parent)
or not cls._is_unaliased_regular_file(path)
)
}
for path, content in snapshots:
if path not in canonical_paths and path.parent not in recovery_parents:
continue
if cls._has_linked_ancestor(path.parent):
raise OSError(
f"protected Skill ancestor was replaced: {path.parent}"
)
if os.path.lexists(path.parent) and (
cls._is_link_or_reparse_point(path.parent)
or not path.parent.is_dir()
):
cls._remove_pipeline_state_replacement(path.parent)
if not path.parent.is_dir():
if not path.parent.parent.is_dir():
raise OSError(
f"protected Skill ancestor is missing: {path.parent.parent}"
)
path.parent.mkdir(exist_ok=False)
changed_paths.append(str(path.parent))
if (
os.path.lexists(path)
and cls._is_unaliased_regular_file(path)
and path.read_bytes() == content
):
continue
if os.path.lexists(path):
cls._remove_pipeline_state_replacement(path)
path.write_bytes(content)
if (
not cls._is_unaliased_regular_file(path)
or path.read_bytes() != content
):
raise OSError(f"protected Skill restoration did not verify: {path}")
changed_paths.append(str(path))
except OSError as exc:
return True, f"protected Playground Skill isolation failed: {exc}", False
if not changed_paths:
return False, "", True
return (
True,
"Playground execution modified protected Skill files; restored: "
+ ", ".join(changed_paths),
True,
)
@classmethod
def _restore_playground_boundaries(
cls,
pipeline_snapshot: tuple[Path, bool, bytes | None, str],
skill_snapshots: tuple[tuple[Path, bytes], ...],
skill_snapshot_error: str,
) -> tuple[bool, str, bool]:
pipeline_changed, pipeline_reason, pipeline_ok = cls._restore_pipeline_state(
pipeline_snapshot
)
skills_changed, skills_reason, skills_ok = cls._restore_playground_skill_files(
skill_snapshots,
skill_snapshot_error,
)
reasons = [reason for reason in (pipeline_reason, skills_reason) if reason]
return (
pipeline_changed or skills_changed,
"; ".join(reasons),
pipeline_ok and skills_ok,
)
@staticmethod
def _playground_skills_from_snapshots(
snapshots: tuple[tuple[Path, bytes], ...],
) -> tuple[object | None, object | None, str]:
"""Return trusted source paths without parsing Skill Markdown."""
if len(snapshots) < 2:
return None, None, "protected Playground Skill snapshot is incomplete"
try:
snapshots[0][1].decode("utf-8")
snapshots[1][1].decode("utf-8")
except UnicodeError as exc:
return None, None, f"protected Playground Skill is not UTF-8: {exc}"
return snapshots[0][0], snapshots[1][0], ""
def execute(
self,
*,
objective: str,
original_objective: str = "",
review_objective: str = "",
sink: EventSink,
preload_injects: list[str] | None = None, # noqa: ARG002 — protocol parity
prelude_context: str = "",
prelude_context_provider: Callable[[], str] | None = None,
planner_context: str = "",
planner_context_provider: Callable[[], str] | None = None,
seed_thread_id: str | None = None,
scope: str = "",
preplanned: bool = False,
mission_id: str | None = None,
usage_mission_id: str | None = None,
context_packet_path: str = "",
max_rounds_override: int | None = None,
workflow_mode_override: str = "",
require_independent_review: bool = True,
skip_stage_transition: bool = False,
stage_closing: bool = False,
holds_stage_authority: bool = True,
working_dir_override: str = "",
maintenance_mission: bool = False,
allow_skill_changes: bool = False,
vertical_override: str = "",
) -> _Outcome:
from ._runtime_interrupt import execution_interrupt_scope
with execution_interrupt_scope(
stop_event=getattr(self, "_execution_stop_event", None),
state_root=getattr(self, "_manager_session_root", None),
mission_id=str(mission_id or getattr(self, "_active_mission_id", "") or ""),
enable_abort=bool(getattr(self, "_enable_mission_abort_signal", False)),
):
# Chat fast-path (operator-front-door-only; gated by _allow_chat_fast_path).
# The classifier + reply logic lives in ``_maybe_chat_outcome``; here we
# only gate it so the 7×24 daemon (``_allow_chat_fast_path=False``) does
# not classify arbitrary autonomous work — agent-produced backlog work
# must not be second-guessed.
chat_outcome = self._execute_chat_fast_path(
objective=objective,
sink=sink,
seed_thread_id=seed_thread_id,
mission_id=mission_id,
usage_mission_id=usage_mission_id,
)
if chat_outcome is not None:
return chat_outcome
ex_state = _ExecuteState()
ex_state.prelude_context_provider = prelude_context_provider
# This is an explicitly shared projection. Engineer prelude_context may
# contain role-exclusive runtime instructions and must never be reused.
ex_state.planner_context = planner_context
ex_state.planner_context_provider = planner_context_provider
self._build_execute_config(
ex_state,
working_dir_override=working_dir_override,
maintenance_mission=maintenance_mission,
vertical_override=vertical_override,
require_independent_review=require_independent_review,
max_rounds_override=max_rounds_override,
context_packet_path=context_packet_path,
mission_id=mission_id,
objective=objective,
workflow_mode_override=workflow_mode_override,
)
self._build_execute_skill_store_and_loop(ex_state, sink=sink)
self._prepare_execute_mission_context(
ex_state,
objective=objective,
review_objective=review_objective,
prelude_context=prelude_context,
seed_thread_id=seed_thread_id,
scope=scope,
)
self._invoke_execute_loop(
ex_state,
sink=sink,
objective=objective,
original_objective=original_objective,
preplanned=preplanned,
mission_id=mission_id,
usage_mission_id=usage_mission_id,
)
self._extract_execute_outcome_fields(ex_state)
self._maybe_decide_stage_transition(
ex_state,
sink=sink,
mission_id=mission_id,
usage_mission_id=usage_mission_id,
maintenance_mission=maintenance_mission,
skip_stage_transition=skip_stage_transition,
preplanned=preplanned,
stage_closing=stage_closing,
holds_stage_authority=holds_stage_authority,
)
return self._build_execute_outcome(ex_state)
def _execute_chat_fast_path(
self,
*,
objective: str,
sink: EventSink,
seed_thread_id: str | None,
mission_id: str | None,
usage_mission_id: str | None,
) -> "_Outcome | None":
"""Classify and answer an operator-front-door chat message, if the
classifier decides this objective is chat rather than mission work.
Returns ``None`` when the caller should proceed with a real mission
(the 7×24 daemon never reaches the classifier: it always gets ``None``).
"""
if not self._allow_chat_fast_path:
return None
self._set_usage_context(usage_mission_id or mission_id)
try:
return self._maybe_chat_outcome(
objective=objective,
sink=sink,
seed_thread_id=seed_thread_id,
)
finally:
self._set_usage_context(None)
def _build_execute_config(
self,
ex_state: "_ExecuteState",
*,
working_dir_override: str,
maintenance_mission: bool,
vertical_override: str,
require_independent_review: bool,
max_rounds_override: int | None,
context_packet_path: str,
mission_id: str | None,
workflow_mode_override: str,
objective: str = "",
) -> None:
"""Resolve the workdir/vertical-derived flags and build the
``SkillLoopConfig`` for this mission.
"""
args = self._args
# Lazy proxy: ``_independent_review_required_for_project_root``,
# ``_workflow_mode_for_project_root``, and
# ``_paper_mission_for_project_root`` (used below) live in
# ``_runtime_supervisor`` but are re-exported on — and monkeypatched
# directly against — the ``_runtime`` facade module by tests (e.g.
# tests/life/test_chat_fast_path.py). Resolving them here at call
# time keeps that monkeypatch effective even though this method
# lives in a sibling module.
from ._runtime import (
_independent_review_required_for_project_root,
_paper_mission_for_project_root,
_workflow_mode_for_project_root,
)
workdir = (
Path(working_dir_override).expanduser().resolve()
if working_dir_override
else Path(args.workdir).expanduser()
if args.workdir
else Path.cwd()
)
# Execution happens in the operator workspace, but vertical contracts
# live in session state. A working-dir override must not make a freshly
# authored project-local vertical disappear before Engineer starts.
_proot = (
workdir
if maintenance_mission
else Path(getattr(self, "_artifact_root", None) or workdir)
)
active_vertical = str(vertical_override or "").strip()
active_contract = None
if active_vertical:
from ..skills.vertical_select import require_vertical
from ..verticals._base import load_vertical_contract
active_vertical = require_vertical(active_vertical, _proot)
active_contract = load_vertical_contract(
active_vertical,
project_root=_proot,
)
effective_require_independent_review = bool(
require_independent_review
or _env_flag("ARGUS_SKILL_REQUIRE_INDEPENDENT_REVIEW", False)
or (
active_contract.requires_independent_review
if active_contract is not None
else _independent_review_required_for_project_root(_proot)
)
)
if not effective_require_independent_review:
# Bug #42: 14 consecutive missions closed on the Engineer's own
# say-so and the only trace of it was a reason string inside each
# review record. Dropping the Reviewer is a policy decision; say so
# once, out loud, with the inputs that produced it. The framework
# path is the one that mattered — the daemon had rolled back to a
# source root whose math vertical predated the review requirement.
from ..skills.stage_machine import framework_source_root
waiver_reason = (
"framework maintenance mission"
if maintenance_mission
else "explicit mission configuration with no stricter vertical policy"
)
log.warning(
"independent review waived: %s; "
"project_root=%s vertical=%s framework=%s",
waiver_reason,
_proot,
active_vertical or "<persisted>",
framework_source_root(),
)
# 7×24 product: default to dangerous_yolo (no bwrap sandbox).
# The operator runs the daemon on their own box and explicitly
# consents to autonomous execution; the sandbox only fights us
# (`bwrap: Can't create file at /.codex: Permission denied`).
# Operators can opt back into sandbox via ARGUS_SKILL_SAFE_MODE=1.
safe_mode = _env_flag("ARGUS_SKILL_SAFE_MODE", False)
config_kwargs = {
"engineer_model": _engineer_model_for_task(args.engineer_model, active_vertical, objective, _proot),
"reviewer_model": args.reviewer_model,
"require_independent_review": effective_require_independent_review,
"engineer_initial_reasoning_effort": os.environ.get(
"ARGUS_SKILL_ENGINEER_INITIAL_REASONING_EFFORT", "high"
),
"engineer_reasoning_effort": getattr(args, "engineer_reasoning_effort", "xhigh"),
"reviewer_reasoning_effort": getattr(
args,
"reviewer_reasoning_effort",
"xhigh",
),
"max_rounds": (
max(1, int(max_rounds_override))
if max_rounds_override is not None
else args.max_rounds
),
"require_post_task_learning": bool(
getattr(self, "_role_memory_maintenance_enabled", True)
),
"wiki_enabled": _env_flag("ARGUS_SKILL_WIKI", default=True),
"auto_init_wiki": _env_flag(
"ARGUS_SKILL_AUTO_INIT_WIKI",
default=True,
),
"dangerous_yolo": not safe_mode,
"full_auto": safe_mode,
"sandbox_mode": (
"workspace-write" if maintenance_mission and safe_mode else None
),
"isolate_workdir": bool(maintenance_mission and safe_mode),
"skip_git_repo_check": True,
# Filled from the resolved vertical below. Fail-safe default: an
# undecided task is bounded/non-paper.
"paper_mission": False,
"active_vertical": active_vertical,
"vertical_state_root": _proot,
# Shared Markdown checkpoint in internal project state. Engineer
# and Reviewer receive its absolute path and edit it in sequence;
# output workdirs contain deliverables only.
"checkpoint_path": _checkpoint_path_for(
args,
Path(args.workdir).expanduser() if args.workdir else Path.cwd(),
),
"context_packet_path": str(context_packet_path or ""),
"session_id": mission_id,
# Process-correctness audit: the reviewer runs in the project
# work-tree and only sees the engineer's final summary. Give it the
# ABSOLUTE path to this project's engineer execution log
# (``<life_dir>/events.jsonl``) so it can grep HOW the result was
# produced. This runtime log remains outside the worktree.
}
maintenance_checkpoint_dir: Path | None = None
if context_packet_path:
config_kwargs["checkpoint_path"] = (
Path(context_packet_path).expanduser().resolve().parent / "CHECKPOINT.md"
)
if maintenance_mission:
maintenance_checkpoint_dir = workdir / ".argus-self-maintenance-runtime"
maintenance_checkpoint_dir.mkdir(parents=True, exist_ok=True)
config_kwargs["checkpoint_path"] = maintenance_checkpoint_dir / "CHECKPOINT.md"
_project_state_dir = _project_state_dir_for(
args, Path(args.workdir).expanduser() if args.workdir else Path.cwd()
)
config_kwargs["engineer_log_path"] = (
str(_project_state_dir / "events.jsonl") if _project_state_dir is not None else ""
)
from ..manager.directive import active_operator_question_policy
explicit_operator_root = str(getattr(args, "operator_context_dir", "") or "").strip()
operator_policy_root = (
Path(explicit_operator_root).expanduser() if explicit_operator_root else _project_state_dir
)
config_kwargs["operator_questions_allowed"] = (
active_operator_question_policy(operator_policy_root) != "forbid"
)
config_kwargs["operator_question_policy_root"] = operator_policy_root
# Campaign lifetime metadata forwarded from the daemon namespace so the
# Manager stage hook receives open_ended=True for daemon-created open-ended
# campaigns, preventing final_stage_completion_decision from overwriting a
# structured Manager rollback verdict with a bounded completion.
config_kwargs["open_ended"] = bool(getattr(args, "open_ended", False))
config_kwargs["continuous_objective"] = str(getattr(args, "continuous_objective", "") or "")
resolved_workflow_mode = (
workflow_mode_override.strip().lower()
or _workflow_mode_for_project_root(_proot)
or (active_contract.workflow_mode if active_contract is not None else "")
)
config_kwargs["workflow_mode"] = resolved_workflow_mode
if resolved_workflow_mode == "direct":
from ..core.knobs import resolve_role_reasoning_effort
config_kwargs["reviewer_reasoning_effort"] = (
resolve_role_reasoning_effort(
"ARGUS_SKILL_REVIEWER_REASONING_EFFORT",
default="high",
)
)
# A paper contract is enabled only by a non-direct vertical that explicitly
# declares PAPER_MISSION. Certification strength is a separate contract.
# An explicit False may opt out; True cannot turn a non-paper vertical
# into a paper.
_paper_override = getattr(args, "paper_mission", None)
_paper_allowed = True if _paper_override is None else bool(_paper_override)
config_kwargs["paper_mission"] = bool(
not maintenance_mission
and resolved_workflow_mode != "direct"
and _paper_allowed
and (
active_contract.paper_mission
if active_contract is not None
else _paper_mission_for_project_root(_proot)
)
)
try:
from inspect import signature
sig = signature(self._SkillLoopConfig)
if not any(param.kind == param.VAR_KEYWORD for param in sig.parameters.values()):
config_kwargs = {
key: value for key, value in config_kwargs.items() if key in sig.parameters
}
except (TypeError, ValueError):
pass
ex_state.workdir = workdir
ex_state.effective_require_independent_review = effective_require_independent_review
ex_state.config = self._SkillLoopConfig(**config_kwargs)
ex_state.maintenance_checkpoint_dir = maintenance_checkpoint_dir
def _build_execute_skill_store_and_loop(
self,
ex_state: "_ExecuteState",
*,
sink: EventSink,
) -> None:
"""Refresh the Manager skill store, wire the per-round operator inbox
drain, and construct this mission's ``SkillLoop``.
"""
args = self._args
workdir = ex_state.workdir
config = ex_state.config
self._refresh_manager_skill_store(args, workdir=workdir)
# The per-project runtime state dir holds inbox.jsonl + events.jsonl.
operator_state_dir = _project_state_dir_for(args, workdir)
# Both built-in consumers share durable claims. Canonical acceptance is
# idempotent; ephemeral messages settle only after full prompt assembly.
inbox_life_dir = operator_state_dir
from ._inbox_delivery import EngineerInboxGuidance
extra_guidance_provider = (
EngineerInboxGuidance(
inbox_life_dir, workdir, lambda: getattr(self, "manager", None),
mission_id=str(getattr(config, "session_id", "") or ""),
) if inbox_life_dir is not None else None
)
engineer_backend = getattr(self, "engineer_backend", None) or self._backend
global_skills_dir = Path(args.skills_dir)
skill_store = None
project_state_dir = str(getattr(args, "project_state_dir", "") or "").strip()
if project_state_dir:
from ..skills.layered import (
LayeredSkillStore,
shared_skill_scope_dir,
)
from ..skills.vertical_select import resolve_skill_scope
active_skill_scope = config.active_vertical or resolve_skill_scope(workdir)
vertical_dir = shared_skill_scope_dir(
global_skills_dir,
active_skill_scope,
)
if vertical_dir is not None and active_skill_scope:
from ..skills.builtins import seed_context_skills
seed_context_skills(
vertical_dir,
active_skill_scope,
overwrite=False,
)
explicit_project_skills = str(
os.environ.get("ARGUS_SKILL_PROJECT_SKILLS_DIR", "") or ""
).strip()
project_skills_dir = (
Path(explicit_project_skills)
if explicit_project_skills
else Path(project_state_dir) / "skills"
)
skill_store = LayeredSkillStore(
project_dir=project_skills_dir,
global_dir=global_skills_dir,
vertical_dir=vertical_dir,
native_project_dir=workdir / ".agents" / "skills",
execution_project_root=workdir,
)
ex_state.loop = self._SkillLoop(
skills_dir=global_skills_dir,
engineer_runner=engineer_backend,
reviewer_runner=getattr(self, "reviewer_backend", None) or self._backend,
config=config,
skill_store=skill_store,
on_event=sink.handle_event,
extra_guidance_provider=extra_guidance_provider,
prelude_context_provider=getattr(ex_state, "prelude_context_provider", None),
)
def _prepare_execute_mission_context(
self,
ex_state: "_ExecuteState",
*,
objective: str,
review_objective: str,
prelude_context: str,
seed_thread_id: str | None,
scope: str,
) -> None:
"""Build the full task text (objective + prelude), pick the seed
thread id to chain off of, and normalize the structural scope tag.
"""
full_task = objective
if prelude_context and getattr(ex_state, "prelude_context_provider", None) is None:
full_task = f"{prelude_context}\n---\n## Live objective\n{objective}"
# Use the seed for the first execute() of this runner; subsequent
# execute() calls (LifeSupervisor may run several missions in one
# supervisor.run()) chain off the previous mission's last thread_id.
seed = self._next_seed_thread_id if seed_thread_id is None else seed_thread_id
# Scope is threaded structurally from the planner via the backlog
# item's tags (LifeSupervisor passes _planner_scope_from_item(item)).
# We no longer re-parse it out of the objective prose — the harness
# should consume the structured field, not sniff the rendered text.
mission_scope = (scope or "").strip().lower()
ex_state.full_task = full_task
ex_state.review_objective = review_objective or objective
ex_state.seed = seed
ex_state.mission_scope = mission_scope
def _run_bounded_planning(
self,
ex_state: "_ExecuteState",
*,
sink: EventSink,
objective: str,
original_objective: str,
preplanned: bool,
mission_id: str | None,
) -> None:
"""Draft the advisory Planner execution plan for bounded (non-direct,
non-preplanned) work and fold it into ``ex_state.full_task``.
User-authored bounded work now follows the full team chain:
Manager → Planner → Engineer → Reviewer. Planner-authored backlog
items set ``preplanned=True`` and skip this call, avoiding a second
redundant planning pass. The plan is advisory context, not a gate:
if drafting fails, Engineer still receives the immutable objective.
"""
args = self._args
workdir = ex_state.workdir
config = ex_state.config
if preplanned or getattr(config, "workflow_mode", "staged") == "direct":
return
try:
from ..core.planner_verdict import (
PlannerVerdictStatus,
build_planner_verdict_event,
)
from ..manager.plan_mode import draft_plan
from ..roles.prompts import resolve_role_prompt
from ..roles.prompts.planner import preview_request
from ._runtime_planning_context import bounded_planner_request
preview_prompt = resolve_role_prompt(preview_request(workdir))
if _decided_vertical(config, workdir) == "research":
# The research Planner's own cycle plans the campaign minutes
# later with the stage playbook, and the idea stage forms its
# portfolio without reading this outline. On the stable web
# trial (2026-09-16) this preview ran at every attempt with
# repository tools and no turn cap; on an empty workspace it
# wandered the host for nineteen turns (361k input tokens)
# before the provider cut it off, and its output was unused.
sink.handle_event(
{
"type": "life.planner.preview_skipped",
"agent_layer": "planner",
"vertical": "research",
"text": (
"Planner preview skipped: the research Planner cycle "
"owns the campaign plan"
),
}
)
return
planner_role_banner = preview_prompt.role_banner