maxxab-agent-runner 0.1.0rc7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- automation/__init__.py +1 -0
- automation/__main__.py +4 -0
- automation/accounting.py +107 -0
- automation/callbacks.py +24 -0
- automation/cli.py +266 -0
- automation/config.py +193 -0
- automation/contracts.py +100 -0
- automation/control.py +860 -0
- automation/control_bootstrap.py +526 -0
- automation/control_docker_credentials.py +394 -0
- automation/control_docker_http.py +239 -0
- automation/control_docker_io.py +378 -0
- automation/control_docker_stream.py +57 -0
- automation/control_guardian_protocol.py +62 -0
- automation/control_runtime_assets.py +254 -0
- automation/control_runtime_bootstrap.py +336 -0
- automation/control_runtime_channel.py +240 -0
- automation/control_runtime_clock.py +266 -0
- automation/control_runtime_configuration.py +80 -0
- automation/control_runtime_consumer.py +89 -0
- automation/control_runtime_containment.py +363 -0
- automation/control_runtime_dispatch.py +173 -0
- automation/control_runtime_docker_recipe.py +262 -0
- automation/control_runtime_elf.py +154 -0
- automation/control_runtime_execution_root.py +385 -0
- automation/control_runtime_frozen.py +914 -0
- automation/control_runtime_handoff.py +105 -0
- automation/control_runtime_launch_data.py +188 -0
- automation/control_runtime_lifetime.py +56 -0
- automation/control_runtime_linux.py +90 -0
- automation/control_runtime_manager.py +263 -0
- automation/control_runtime_observer.py +222 -0
- automation/control_runtime_operational.py +62 -0
- automation/control_runtime_original.py +183 -0
- automation/control_runtime_payload.py +180 -0
- automation/control_runtime_prefork.py +143 -0
- automation/control_runtime_proc.py +478 -0
- automation/control_runtime_proc_view.py +351 -0
- automation/control_runtime_project_layout.py +241 -0
- automation/control_runtime_provisioner.py +357 -0
- automation/control_runtime_readiness.py +252 -0
- automation/control_runtime_receiver.py +909 -0
- automation/control_runtime_root_entry.py +331 -0
- automation/control_runtime_seal.py +356 -0
- automation/control_runtime_source_pins.py +101 -0
- automation/control_runtime_state.py +100 -0
- automation/control_runtime_systemd.py +82 -0
- automation/control_runtime_verity.py +219 -0
- automation/control_startup.py +91 -0
- automation/control_store.py +2778 -0
- automation/control_supervisor.py +431 -0
- automation/control_transport.py +703 -0
- automation/control_workspace.py +255 -0
- automation/fresh_github.py +288 -0
- automation/fresh_work.py +400 -0
- automation/github.py +165 -0
- automation/github_transport.py +269 -0
- automation/hold_journal.py +182 -0
- automation/lifecycle.py +156 -0
- automation/live_contracts.py +750 -0
- automation/live_io.py +576 -0
- automation/live_preview.py +155 -0
- automation/managed_config.py +265 -0
- automation/managed_observation.py +203 -0
- automation/native/libmd/COPYING +177 -0
- automation/native/libmd/config.h +1 -0
- automation/native/libmd/local-link.h +68 -0
- automation/native/libmd/sha2.c +990 -0
- automation/native/libmd/sha2.h +130 -0
- automation/native/runtime_guardian.c +290 -0
- automation/native/runtime_stage0_admission.c +296 -0
- automation/native/runtime_stage0_admission.h +49 -0
- automation/native/runtime_stage0_bootstrap.c +232 -0
- automation/native/runtime_stage0_bootstrap.h +26 -0
- automation/native/runtime_stage0_clock.c +811 -0
- automation/native/runtime_stage0_clock.h +130 -0
- automation/native/runtime_stage0_launch.c +490 -0
- automation/native/runtime_stage0_launch.h +77 -0
- automation/native/runtime_stage0_persistence.c +321 -0
- automation/native/runtime_stage0_persistence.h +50 -0
- automation/native/runtime_stage0_preparer.c +4178 -0
- automation/native/runtime_stage0_preparer.h +110 -0
- automation/native/runtime_stage0_project_view.c +444 -0
- automation/native/runtime_stage0_project_view.h +31 -0
- automation/native/runtime_stage0_qualification_main.c +22 -0
- automation/native/runtime_stage0_records.c +478 -0
- automation/native/runtime_stage0_records.h +101 -0
- automation/native/runtime_stage0_validate_main.c +13 -0
- automation/operation_journal.py +214 -0
- automation/selection.py +175 -0
- automation/sqlite_support.py +40 -0
- automation/supervised_inputs.py +193 -0
- automation/supervised_observer.py +147 -0
- automation/supervised_run.py +287 -0
- automation/supervised_state.py +542 -0
- automation/usage_journal.py +110 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/METADATA +97 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/RECORD +106 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/WHEEL +4 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/entry_points.txt +2 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/licenses/LICENSE +21 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/licenses/NOTICE.md +19 -0
- maxxab_agent_runner-0.1.0rc7.dist-info/licenses/automation/native/libmd/COPYING +177 -0
- tools/__init__.py +1 -0
- tools/runner_container_preflight.py +624 -0
- tools/runner_idle_notifications.py +33 -0
automation/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Standard-library automation diagnostics and supervised-run components."""
|
automation/__main__.py
ADDED
automation/accounting.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Pure synthetic observation projection, never billing or execution authority.
|
|
2
|
+
|
|
3
|
+
There is no SDK event adapter, persistent state or coverage verifier here.
|
|
4
|
+
Input order is receipt order, not established provider ordering.
|
|
5
|
+
"""
|
|
6
|
+
import unicodedata
|
|
7
|
+
|
|
8
|
+
from .contracts import digest, fields, string, version
|
|
9
|
+
|
|
10
|
+
MAX_COUNTER = (1 << 63) - 1
|
|
11
|
+
EVENT_FIELDS = ('schema_version', 'source', 'session_id', 'turn_id', 'event_id',
|
|
12
|
+
'mode', 'scope', 'metric', 'unit', 'value', 'evidence_ref', 'evidence_sha256')
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _record(value, required):
|
|
16
|
+
if type(value) is not dict or any(type(key) is not str for key in value):
|
|
17
|
+
raise ValueError('expected a normalized object with string keys')
|
|
18
|
+
fields(value, required)
|
|
19
|
+
version(value['schema_version'])
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _text(value, maximum):
|
|
23
|
+
value = string(value)
|
|
24
|
+
if len(value) > maximum or any(unicodedata.category(ch) in ('Cc', 'Cs') for ch in value):
|
|
25
|
+
raise ValueError('expected bounded control-free Unicode text')
|
|
26
|
+
return value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _identity(value):
|
|
30
|
+
return _text(value['source'], 128), _text(value['session_id'], 128)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def summarize_cumulative_usage(events: list[dict], expected_streams: list[dict]) -> dict:
|
|
34
|
+
"""Summarize supplied observations; complete totals deliberately stay unknown.
|
|
35
|
+
|
|
36
|
+
Namespace and session attribution are caller-declared normalization inputs,
|
|
37
|
+
not proof of identity, non-overlap, coverage, authorization or actual charge.
|
|
38
|
+
"""
|
|
39
|
+
if type(events) is not list or len(events) > 10000:
|
|
40
|
+
raise ValueError('expected at most 10000 normalized events')
|
|
41
|
+
if type(expected_streams) is not list or len(expected_streams) > 1000:
|
|
42
|
+
raise ValueError('expected at most 1000 normalized streams')
|
|
43
|
+
streams = {}
|
|
44
|
+
sources = set()
|
|
45
|
+
for item in expected_streams:
|
|
46
|
+
_record(item, ('schema_version', 'source', 'session_id'))
|
|
47
|
+
key = _identity(item)
|
|
48
|
+
if key in streams:
|
|
49
|
+
raise ValueError('duplicate expected stream')
|
|
50
|
+
sources.add(key[0])
|
|
51
|
+
streams[key] = {'observed_tokens': None, 'unique_event_count': 0, 'reasons': set()}
|
|
52
|
+
if len(sources) > 1:
|
|
53
|
+
raise ValueError('version 1 supports one declared source namespace per report')
|
|
54
|
+
|
|
55
|
+
seen = {}
|
|
56
|
+
for item in events:
|
|
57
|
+
_record(item, EVENT_FIELDS)
|
|
58
|
+
key = _identity(item)
|
|
59
|
+
if key not in streams:
|
|
60
|
+
raise ValueError('event belongs to an undeclared stream')
|
|
61
|
+
identity = (*key, _text(item['turn_id'], 128), _text(item['event_id'], 128))
|
|
62
|
+
if (item['mode'], item['scope'], item['metric'], item['unit']) != (
|
|
63
|
+
'cumulative', 'session', 'total_tokens', 'tokens'):
|
|
64
|
+
raise ValueError('unsupported accounting mode, scope, metric or unit')
|
|
65
|
+
value = item['value']
|
|
66
|
+
if value is not None and (type(value) is not int or not 0 <= value <= MAX_COUNTER):
|
|
67
|
+
raise ValueError('counter must be a nonnegative bounded integer or null')
|
|
68
|
+
reference = _text(item['evidence_ref'], 1024)
|
|
69
|
+
evidence_hash = digest(item['evidence_sha256'])
|
|
70
|
+
# All other validated fields are fixed enums or part of the identity.
|
|
71
|
+
payload = value, reference, evidence_hash
|
|
72
|
+
new_identity = identity not in seen
|
|
73
|
+
state = streams[key]
|
|
74
|
+
if not new_identity:
|
|
75
|
+
if seen[identity] == payload:
|
|
76
|
+
continue
|
|
77
|
+
state['reasons'].add('conflicting_event_identity')
|
|
78
|
+
else:
|
|
79
|
+
seen[identity] = payload
|
|
80
|
+
state['unique_event_count'] += 1
|
|
81
|
+
if value is None:
|
|
82
|
+
state['reasons'].add('unknown_observation')
|
|
83
|
+
continue
|
|
84
|
+
previous = state['observed_tokens']
|
|
85
|
+
if previous is not None and new_identity and value < previous:
|
|
86
|
+
state['reasons'].add('cumulative_regression_or_reordering')
|
|
87
|
+
state['observed_tokens'] = value if previous is None else max(previous, value)
|
|
88
|
+
|
|
89
|
+
rows, reasons, known = [], {'coverage_unverified'}, []
|
|
90
|
+
if not streams:
|
|
91
|
+
reasons.add('no_expected_streams')
|
|
92
|
+
for (source, session), state in streams.items():
|
|
93
|
+
if state['unique_event_count'] == 0:
|
|
94
|
+
state['reasons'].add('missing_observations')
|
|
95
|
+
if state['observed_tokens'] is not None:
|
|
96
|
+
known.append(state['observed_tokens'])
|
|
97
|
+
reasons.update(state['reasons'])
|
|
98
|
+
rows.append({'source': source, 'session_id': session,
|
|
99
|
+
'observed_tokens': state['observed_tokens'],
|
|
100
|
+
'unique_event_count': state['unique_event_count'],
|
|
101
|
+
'reasons': sorted(state['reasons'])})
|
|
102
|
+
observed = sum(known) if known else None
|
|
103
|
+
if observed is not None and observed > MAX_COUNTER:
|
|
104
|
+
raise ValueError('aggregate observed counter exceeds limit')
|
|
105
|
+
return {'schema_version': 1, 'mode': 'source_projection', 'execution_enabled': False,
|
|
106
|
+
'streams': rows, 'observed_tokens': observed, 'total_tokens': None,
|
|
107
|
+
'complete': False, 'reasons': sorted(reasons)}
|
automation/callbacks.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Pure refusal callback for a disabled runner, not an operational SDK adapter.
|
|
2
|
+
|
|
3
|
+
Nothing constructs or configures an SDK client here. A future authorized adapter
|
|
4
|
+
must inject this handler explicitly instead of the SDK's default acceptance.
|
|
5
|
+
The pinned SDK bypasses callbacks for non-string wire methods and normalizes
|
|
6
|
+
non-dict params to None: direct helper checks are not wire validation. Callback
|
|
7
|
+
errors/cancel responses never prove that processes or allocations were released.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class UnsupportedServerRequest(ValueError):
|
|
12
|
+
"""The disabled runner has no supported response for this direct request."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def reject_server_request(method: str, params: dict | None) -> dict:
|
|
16
|
+
"""Return only fixed refusals; never inspect payloads or call into a runtime."""
|
|
17
|
+
if type(method) is not str or (params is not None and type(params) is not dict):
|
|
18
|
+
raise UnsupportedServerRequest('Unsupported server request while runner execution is disabled.')
|
|
19
|
+
if method in ('item/commandExecution/requestApproval', 'item/fileChange/requestApproval'):
|
|
20
|
+
return {'decision': 'cancel'}
|
|
21
|
+
if method == 'item/tool/call':
|
|
22
|
+
return {'success': False, 'contentItems': [
|
|
23
|
+
{'type': 'inputText', 'text': 'Runner execution is disabled.'}]}
|
|
24
|
+
raise UnsupportedServerRequest('Unsupported server request while runner execution is disabled.')
|
automation/cli.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Advisory diagnostics and explicitly requested foreground supervision."""
|
|
2
|
+
import argparse
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import socket
|
|
8
|
+
import stat
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from .config import load_context
|
|
13
|
+
from .contracts import load_json
|
|
14
|
+
from .selection import preview
|
|
15
|
+
from .live_contracts import LiveCode, LiveOutcome, Receipt, public_error
|
|
16
|
+
from .live_preview import production_preview, deliver
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _supervised_run(captured):
|
|
20
|
+
# Keep the advisory CLI importable without platform-specific runtime modules.
|
|
21
|
+
from .supervised_run import _run_cli
|
|
22
|
+
return _run_cli(captured)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _notify_supervised(report):
|
|
26
|
+
if report.get("mode") == "supervised" and report.get("status") in ("completed", "failed"):
|
|
27
|
+
from .supervised_run import report_delivered
|
|
28
|
+
report_delivered(report.get("attempt_id"), report["status"])
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _terminal():
|
|
32
|
+
return bool(sys.stdin.isatty() and sys.stdout.isatty())
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _approve(summary):
|
|
36
|
+
if not _terminal():
|
|
37
|
+
return False
|
|
38
|
+
print(summary)
|
|
39
|
+
try:
|
|
40
|
+
return input("Type APPROVE to continue: ") == "APPROVE"
|
|
41
|
+
except EOFError:
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _supervised(args):
|
|
46
|
+
if not _terminal():
|
|
47
|
+
raise ValueError("a foreground terminal is required")
|
|
48
|
+
from . import supervised_inputs, supervised_state
|
|
49
|
+
|
|
50
|
+
project = args.project.resolve(strict=True)
|
|
51
|
+
if args.command in ("supervised-init", "supervised-run"):
|
|
52
|
+
summary = json.dumps({"mode": "checkout-inspection", "checkout": str(project),
|
|
53
|
+
"risk": "Git checkout inspection may run repository-configured filters "
|
|
54
|
+
"with your account's access. Approve only a trusted checkout."},
|
|
55
|
+
ensure_ascii=True, indent=2, sort_keys=True)
|
|
56
|
+
if not _approve(summary):
|
|
57
|
+
return {"mode": "checkout-inspection", "status": "declined"}, 2
|
|
58
|
+
context = load_context(project, args.enrollment, host_id=socket.gethostname())
|
|
59
|
+
if args.command == "supervised-status":
|
|
60
|
+
state = supervised_state.open_project(context, project=project)
|
|
61
|
+
try:
|
|
62
|
+
return {"mode": "supervised-status", **state.inspect()}, 0
|
|
63
|
+
finally:
|
|
64
|
+
state.close()
|
|
65
|
+
if args.command == "supervised-init":
|
|
66
|
+
snapshot = supervised_inputs.checkout(context, project)
|
|
67
|
+
location = supervised_state.state_location(context, project=project)
|
|
68
|
+
summary = json.dumps({"mode": "supervised-init", "repository": context.config.repository,
|
|
69
|
+
"checkout": str(project), "base_revision": context.base_revision,
|
|
70
|
+
"remote": snapshot[1], "state_location": str(location),
|
|
71
|
+
"risk": "This opts in one trusted project. Project commands and Codex may "
|
|
72
|
+
"access credentials, network and host files."},
|
|
73
|
+
ensure_ascii=True, indent=2, sort_keys=True)
|
|
74
|
+
if not _approve(summary):
|
|
75
|
+
return {"mode": "supervised-init", "status": "declined"}, 2
|
|
76
|
+
current = load_context(project, args.enrollment, host_id=socket.gethostname())
|
|
77
|
+
if current != context or supervised_inputs.checkout(current, project) != snapshot:
|
|
78
|
+
raise ValueError("project inputs changed during approval")
|
|
79
|
+
supervised_state.initialize(context, project=project)
|
|
80
|
+
return {"mode": "supervised-init", "status": "initialized", "state_location": str(location)}, 0
|
|
81
|
+
if args.command == "supervised-reconcile":
|
|
82
|
+
state = supervised_state.open_project(context, project=project)
|
|
83
|
+
try:
|
|
84
|
+
pending = state.describe_pending(args.attempt)
|
|
85
|
+
summary = json.dumps({"mode": "supervised-reconcile", "pending": pending, "note": args.note,
|
|
86
|
+
"risk": "Confirm only after manually inspecting the original checkout, "
|
|
87
|
+
"processes and possible external effects. This records your "
|
|
88
|
+
"decision; it does not perform cleanup or prove absence."},
|
|
89
|
+
ensure_ascii=True, indent=2, sort_keys=True)
|
|
90
|
+
if not _approve(summary):
|
|
91
|
+
return {"mode": "supervised-reconcile", "status": "declined"}, 2
|
|
92
|
+
if load_context(project, args.enrollment, host_id=socket.gethostname()) != context:
|
|
93
|
+
raise ValueError("enrollment changed during approval")
|
|
94
|
+
state.reconcile(args.attempt, args.note)
|
|
95
|
+
return {"mode": "supervised-reconcile", "status": "recorded", "attempt_id": args.attempt}, 0
|
|
96
|
+
finally:
|
|
97
|
+
state.close()
|
|
98
|
+
captured = supervised_inputs.capture(project, args.enrollment, args.task, args.checks,
|
|
99
|
+
host=socket.gethostname())
|
|
100
|
+
result = _supervised_run(captured)
|
|
101
|
+
report = asdict(result)
|
|
102
|
+
report.update({"mode": "supervised", "review_required": True,
|
|
103
|
+
"codex_model": captured.codex_model,
|
|
104
|
+
"codex_reasoning_effort": captured.codex_reasoning_effort,
|
|
105
|
+
"codex_settings_note": "Requested settings; null uses CLI defaults. "
|
|
106
|
+
"Verify effective settings in CLI output.",
|
|
107
|
+
"cost": "Unavailable — not reported to the runner",
|
|
108
|
+
"recovery": "Clearance is attempted after normal foreground exit; "
|
|
109
|
+
"check supervised-status. Abrupt loss requires reconciliation."})
|
|
110
|
+
return report, 0 if result.status == "completed" else 3 if result.status == "unknown" else 2
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _live(args):
|
|
114
|
+
try:
|
|
115
|
+
context = load_context(args.project, args.enrollment, host_id=socket.gethostname())
|
|
116
|
+
except BaseException:
|
|
117
|
+
code = LiveCode.LIVE_CONTEXT_INVALID
|
|
118
|
+
outcome = LiveOutcome(public_error(code), False, code,
|
|
119
|
+
Receipt('unknown', None, None, None, None, 'failed', 'confirmed'))
|
|
120
|
+
else:
|
|
121
|
+
try:
|
|
122
|
+
outcome = production_preview(context)
|
|
123
|
+
except BaseException:
|
|
124
|
+
code = LiveCode.LIVE_INTERNAL_ERROR
|
|
125
|
+
outcome = LiveOutcome(public_error(code), False, code,
|
|
126
|
+
Receipt('unknown', None, None, None, None, 'failed', 'confirmed'))
|
|
127
|
+
return deliver(outcome, stdout=sys.stdout, stderr=sys.stderr)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _snapshot(path):
|
|
131
|
+
# Opening a FIFO or device must not hang or turn diagnostics into I/O.
|
|
132
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
133
|
+
with os.fdopen(fd, "rb") as stream:
|
|
134
|
+
before = os.fstat(stream.fileno())
|
|
135
|
+
if not stat.S_ISREG(before.st_mode):
|
|
136
|
+
raise ValueError("snapshot must be a regular file")
|
|
137
|
+
raw = stream.read(16777217)
|
|
138
|
+
after = os.fstat(stream.fileno())
|
|
139
|
+
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
140
|
+
raise ValueError("snapshot changed during read")
|
|
141
|
+
return load_json(raw, max_bytes=16777216)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _supervised_cli(args):
|
|
145
|
+
delivery_started = False
|
|
146
|
+
try:
|
|
147
|
+
report, code = _supervised(args)
|
|
148
|
+
rendered = json.dumps(report, indent=2, sort_keys=True) + "\n"
|
|
149
|
+
if sys.stdout.write(rendered) != len(rendered):
|
|
150
|
+
raise OSError("incomplete terminal report")
|
|
151
|
+
sys.stdout.flush()
|
|
152
|
+
delivery_started = True
|
|
153
|
+
_notify_supervised(report)
|
|
154
|
+
return code
|
|
155
|
+
except (ValueError, OSError, subprocess.TimeoutExpired, RecursionError, KeyboardInterrupt) as error:
|
|
156
|
+
print(json.dumps({"mode": "supervised", "status": "error",
|
|
157
|
+
"error": str(error)[:512] or type(error).__name__}, sort_keys=True),
|
|
158
|
+
file=sys.stderr)
|
|
159
|
+
return 3 if delivery_started else 2
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def main(argv=None):
|
|
163
|
+
parser = argparse.ArgumentParser(
|
|
164
|
+
prog="agent-runner",
|
|
165
|
+
description="Fresh GitHub issue review, owner-approved stateless work and advisory diagnostics.")
|
|
166
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
167
|
+
for name in ("doctor", "preview"):
|
|
168
|
+
command = commands.add_parser(name)
|
|
169
|
+
command.add_argument("--project", type=Path, required=True)
|
|
170
|
+
command.add_argument("--enrollment", type=Path, required=True,
|
|
171
|
+
help="Existing private operator enrollment outside the project")
|
|
172
|
+
if name == "preview":
|
|
173
|
+
source = command.add_mutually_exclusive_group(required=True)
|
|
174
|
+
source.add_argument("--snapshot", type=Path,
|
|
175
|
+
help="Existing normalized JSON snapshot; never executed")
|
|
176
|
+
source.add_argument("--live", action="store_true",
|
|
177
|
+
help="Unavailable: live authorization and qualification remain pending")
|
|
178
|
+
for name in ("supervised-init", "supervised-run", "supervised-reconcile", "supervised-status"):
|
|
179
|
+
command = commands.add_parser(name)
|
|
180
|
+
command.add_argument("--project", type=Path, required=True)
|
|
181
|
+
command.add_argument("--enrollment", type=Path, required=True)
|
|
182
|
+
if name == "supervised-run":
|
|
183
|
+
command.add_argument("--task", type=Path, required=True)
|
|
184
|
+
command.add_argument("--checks", type=Path, required=True)
|
|
185
|
+
if name == "supervised-reconcile":
|
|
186
|
+
command.add_argument("--attempt", required=True)
|
|
187
|
+
command.add_argument("--note", required=True)
|
|
188
|
+
for name in ("issues", "work"):
|
|
189
|
+
help_text = ("List current GitHub issues" if name == "issues"
|
|
190
|
+
else "Run one stateless task from chat or with terminal supervision")
|
|
191
|
+
command = commands.add_parser(name, help=help_text, description=help_text)
|
|
192
|
+
command.add_argument("--project", type=Path, required=True)
|
|
193
|
+
command.add_argument("--github-env-file", type=Path,
|
|
194
|
+
help="Owner-supplied environment file containing GH_TOKEN for GitHub reads")
|
|
195
|
+
if name == "work":
|
|
196
|
+
mode = command.add_mutually_exclusive_group(required=True)
|
|
197
|
+
mode.add_argument("--checks", type=Path, help="Use terminal supervision and an operator checks file")
|
|
198
|
+
mode.add_argument("--from-chat", action="store_true", help="Start the owner-requested chat workflow")
|
|
199
|
+
selection = command.add_mutually_exclusive_group()
|
|
200
|
+
selection.add_argument("--issue", type=int, help="Use the issue named by the owner in chat")
|
|
201
|
+
selection.add_argument("--priority", action="store_true", help="Use the priority order requested in chat")
|
|
202
|
+
command.add_argument("--chat-model", help="Effective model identifier of the invoking chat")
|
|
203
|
+
command.add_argument("--model", help="Different model explicitly requested by the owner in chat")
|
|
204
|
+
command.add_argument("--related-path", action="append", default=[],
|
|
205
|
+
help="Explicit source path for review")
|
|
206
|
+
else:
|
|
207
|
+
command.add_argument("--from-chat", action="store_true", help="List issues for an owner request in chat")
|
|
208
|
+
args = parser.parse_args(argv)
|
|
209
|
+
if args.command == "work":
|
|
210
|
+
if args.from_chat != (args.issue is not None or args.priority):
|
|
211
|
+
parser.error("--from-chat requires an explicit --issue or --priority choice")
|
|
212
|
+
has_model = args.chat_model is not None or args.model is not None
|
|
213
|
+
if args.from_chat and not has_model:
|
|
214
|
+
parser.error("--from-chat requires --chat-model or --model")
|
|
215
|
+
if has_model and not args.from_chat:
|
|
216
|
+
parser.error("--chat-model and --model require --from-chat")
|
|
217
|
+
if args.command in ("supervised-init", "supervised-run"):
|
|
218
|
+
print(json.dumps({"status": "retired", "error":
|
|
219
|
+
"Stateful init/run commands are retired. Use issues/work for fresh stateless work; "
|
|
220
|
+
"preserve existing records and use legacy status/reconcile only for explicit recovery."}), file=sys.stderr)
|
|
221
|
+
return 2
|
|
222
|
+
if args.command in ("issues", "work"):
|
|
223
|
+
report = None
|
|
224
|
+
try:
|
|
225
|
+
from .fresh_work import work
|
|
226
|
+
report, code = work(args)
|
|
227
|
+
rendered = json.dumps(report, ensure_ascii=True, indent=2, sort_keys=True) + "\n"
|
|
228
|
+
if sys.stdout.write(rendered) != len(rendered):
|
|
229
|
+
raise OSError("incomplete terminal report")
|
|
230
|
+
sys.stdout.flush()
|
|
231
|
+
return code
|
|
232
|
+
except (ValueError, OSError, subprocess.TimeoutExpired, RecursionError, KeyboardInterrupt) as error:
|
|
233
|
+
uncertain = report is not None and report.get("started", False)
|
|
234
|
+
print(json.dumps({"mode": "stateless", "status": "unknown" if uncertain else "error",
|
|
235
|
+
"error": str(error)[:512] or type(error).__name__,
|
|
236
|
+
"recovery": "Inspect any interrupted effects before another invocation; no saved replay guard."},
|
|
237
|
+
ensure_ascii=True), file=sys.stderr)
|
|
238
|
+
return 3 if uncertain else 2
|
|
239
|
+
if args.command in ("supervised-status", "supervised-reconcile"):
|
|
240
|
+
return _supervised_cli(args)
|
|
241
|
+
if args.command == 'preview' and args.live:
|
|
242
|
+
return _live(args)
|
|
243
|
+
try:
|
|
244
|
+
context = load_context(args.project, args.enrollment, host_id=socket.gethostname())
|
|
245
|
+
if args.command == "preview":
|
|
246
|
+
result = preview(context, _snapshot(args.snapshot))
|
|
247
|
+
else:
|
|
248
|
+
result = {"schema_version": 1, "mode": "advisory",
|
|
249
|
+
"repository": context.config.repository,
|
|
250
|
+
"base_revision": context.base_revision,
|
|
251
|
+
"config_sha256": context.config_sha256,
|
|
252
|
+
"configuration_valid": True, "execution_enabled": False,
|
|
253
|
+
"runtime": {"status": "unavailable",
|
|
254
|
+
"reason": "admission_isolation_lifecycle_gates_unproven"},
|
|
255
|
+
"checks_executed": [], "network_enabled": False}
|
|
256
|
+
print(json.dumps(result, indent=2, sort_keys=True))
|
|
257
|
+
return 0
|
|
258
|
+
except (ValueError, OSError, subprocess.TimeoutExpired, RecursionError) as error:
|
|
259
|
+
print(json.dumps({"schema_version": 1, "execution_enabled": False,
|
|
260
|
+
"error": str(error)[:512] or type(error).__name__}, sort_keys=True),
|
|
261
|
+
file=sys.stderr)
|
|
262
|
+
return 2
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
if __name__ == "__main__":
|
|
266
|
+
sys.exit(main())
|
automation/config.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Read private operator enrollment and immutable approved-base configuration.
|
|
2
|
+
|
|
3
|
+
This boundary is not proof of human authorship. It supplies advisory preview
|
|
4
|
+
only. There is no enrollment writer or execution authorization here.
|
|
5
|
+
"""
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
import hashlib
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path, PurePosixPath
|
|
11
|
+
import re
|
|
12
|
+
import stat
|
|
13
|
+
import subprocess
|
|
14
|
+
from .contracts import digest, fields, integer, load_json, repository, string, strings, utc, version
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Approval:
|
|
19
|
+
issue: int
|
|
20
|
+
scope_sha256: str
|
|
21
|
+
approved_by: str
|
|
22
|
+
acceptance_ids: tuple[str, ...]
|
|
23
|
+
expires_at: datetime
|
|
24
|
+
decisions_resolved: bool
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class AcceptedDependency:
|
|
29
|
+
issue: int
|
|
30
|
+
scope_sha256: str
|
|
31
|
+
result_sha256: str
|
|
32
|
+
accepted_by: str
|
|
33
|
+
closed_at: datetime
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Config:
|
|
38
|
+
repository: str
|
|
39
|
+
target_branch: str
|
|
40
|
+
runner_host: str
|
|
41
|
+
approvers: tuple[str, ...]
|
|
42
|
+
documents: tuple[str, ...]
|
|
43
|
+
required_checks: tuple[str, ...]
|
|
44
|
+
labels: tuple[str, ...]
|
|
45
|
+
priorities: tuple[str, ...]
|
|
46
|
+
max_candidates: int
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Context:
|
|
51
|
+
config: Config
|
|
52
|
+
base_revision: str
|
|
53
|
+
config_sha256: str
|
|
54
|
+
approvals: tuple[Approval, ...]
|
|
55
|
+
accepted_dependencies: tuple[AcceptedDependency, ...]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _private_enrollment(path, project):
|
|
59
|
+
path = Path(path).absolute()
|
|
60
|
+
if any(part.is_symlink() for part in (path, *path.parents)):
|
|
61
|
+
raise ValueError("enrollment path must not contain a symlink")
|
|
62
|
+
path = path.resolve(strict=True)
|
|
63
|
+
if path.is_relative_to(project):
|
|
64
|
+
raise ValueError("enrollment must be outside the candidate project")
|
|
65
|
+
if os.name != "posix":
|
|
66
|
+
raise ValueError("private enrollment permissions are unverified on this platform")
|
|
67
|
+
parent = path.parent.stat()
|
|
68
|
+
if parent.st_uid != os.getuid() or parent.st_mode & 0o077:
|
|
69
|
+
raise ValueError("enrollment parent must be private and operator-owned")
|
|
70
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
71
|
+
with os.fdopen(fd, "rb") as stream:
|
|
72
|
+
info = os.fstat(stream.fileno())
|
|
73
|
+
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
|
74
|
+
raise ValueError("enrollment must be a private operator-owned regular file")
|
|
75
|
+
raw = stream.read(131073)
|
|
76
|
+
after = os.fstat(stream.fileno())
|
|
77
|
+
if (info.st_mtime_ns, info.st_size) != (after.st_mtime_ns, after.st_size):
|
|
78
|
+
raise ValueError("enrollment changed during read")
|
|
79
|
+
return load_json(raw)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _git(project, *arguments):
|
|
83
|
+
env = {"PATH": os.defpath, "LC_ALL": "C", "GIT_CONFIG_GLOBAL": "/dev/null",
|
|
84
|
+
"GIT_CONFIG_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1",
|
|
85
|
+
# Old Git may ignore NO_LAZY_FETCH. An empty transport allowlist
|
|
86
|
+
# also prevents partial-clone object reads invoking remote helpers.
|
|
87
|
+
"GIT_NO_LAZY_FETCH": "1", "GIT_ALLOW_PROTOCOL": "",
|
|
88
|
+
"GIT_PROTOCOL_FROM_USER": "0"}
|
|
89
|
+
result = subprocess.run(["git", "-C", str(project), "-c", "core.fsmonitor=false",
|
|
90
|
+
"-c", "core.hooksPath=/dev/null", *arguments],
|
|
91
|
+
env=env, capture_output=True, timeout=10, check=False)
|
|
92
|
+
if result.returncode:
|
|
93
|
+
raise ValueError("approved Git base or document is unavailable")
|
|
94
|
+
return result.stdout
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _blob(project, revision, path):
|
|
98
|
+
normalized = PurePosixPath(path)
|
|
99
|
+
if (normalized.is_absolute() or ".." in normalized.parts or
|
|
100
|
+
str(normalized) != path or "\\" in path or path.startswith("-")):
|
|
101
|
+
raise ValueError("unsafe document path")
|
|
102
|
+
record = _git(project, "ls-tree", "-z", revision, "--", path)
|
|
103
|
+
parts = record.rstrip(b"\0").split(b"\t", 1)
|
|
104
|
+
if (len(parts) != 2 or parts[1].decode("utf-8") != path or
|
|
105
|
+
parts[0].split()[0] not in (b"100644", b"100755")):
|
|
106
|
+
raise ValueError("required document is missing or not a regular file")
|
|
107
|
+
size = int(_git(project, "cat-file", "-s", f"{revision}:{path}"))
|
|
108
|
+
if not 0 < size <= 131072:
|
|
109
|
+
raise ValueError("approved document exceeds size limit or is empty")
|
|
110
|
+
return _git(project, "cat-file", "blob", f"{revision}:{path}")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _configuration(project, revision, host_id, repo=None, expected=None):
|
|
114
|
+
raw = _blob(project, revision, ".agent-runner/automation.json")
|
|
115
|
+
if expected is not None and hashlib.sha256(raw).hexdigest() != expected:
|
|
116
|
+
raise ValueError("approved configuration digest changed")
|
|
117
|
+
data = load_json(raw)
|
|
118
|
+
fields(data, ("schema_version", "repository", "target_branch", "runner_host",
|
|
119
|
+
"approvers", "documents", "required_checks", "selection"))
|
|
120
|
+
version(data["schema_version"])
|
|
121
|
+
if repo is not None and repository(data["repository"]) != repo:
|
|
122
|
+
raise ValueError("configuration repository does not match enrollment")
|
|
123
|
+
if string(data["runner_host"]) != host_id:
|
|
124
|
+
raise ValueError("configuration host does not match enrollment")
|
|
125
|
+
selection = fields(data["selection"], ("labels", "priorities", "max_candidates"))
|
|
126
|
+
repo = repository(data["repository"])
|
|
127
|
+
config = Config(repo, string(data["target_branch"]), host_id,
|
|
128
|
+
strings(data["approvers"]), strings(data["documents"]),
|
|
129
|
+
strings(data["required_checks"]), strings(selection["labels"], allow_empty=True),
|
|
130
|
+
strings(selection["priorities"], allow_empty=True),
|
|
131
|
+
integer(selection["max_candidates"], 100))
|
|
132
|
+
for document in config.documents:
|
|
133
|
+
_blob(project, revision, document)
|
|
134
|
+
return config, hashlib.sha256(raw).hexdigest()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def load_context(project, enrollment_path, *, host_id):
|
|
138
|
+
project = Path(project).resolve(strict=True)
|
|
139
|
+
root = Path(os.fsdecode(_git(project, "rev-parse", "--show-toplevel")).rstrip("\n"))
|
|
140
|
+
if not root.is_absolute() or root.resolve(strict=True) != project:
|
|
141
|
+
raise ValueError("project must be the actual Git worktree root")
|
|
142
|
+
source = _private_enrollment(enrollment_path, project)
|
|
143
|
+
fields(source, ("schema_version", "repository", "base_revision", "config_sha256",
|
|
144
|
+
"runner_host", "approvals", "accepted_dependencies"))
|
|
145
|
+
version(source["schema_version"])
|
|
146
|
+
repo = repository(source["repository"])
|
|
147
|
+
revision = source["base_revision"]
|
|
148
|
+
if not isinstance(revision, str) or not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", revision):
|
|
149
|
+
raise ValueError("base_revision must be a full immutable object ID")
|
|
150
|
+
expected = digest(source["config_sha256"])
|
|
151
|
+
if string(source["runner_host"]) != host_id:
|
|
152
|
+
raise ValueError("enrollment host does not match this host")
|
|
153
|
+
if _git(project, "cat-file", "-t", revision).strip() != b"commit":
|
|
154
|
+
raise ValueError("approved base must be a commit")
|
|
155
|
+
config, _ = _configuration(project, revision, host_id, repo, expected)
|
|
156
|
+
approvals, accepted = [], []
|
|
157
|
+
for key in ("approvals", "accepted_dependencies"):
|
|
158
|
+
if not isinstance(source[key], list) or len(source[key]) > 10000:
|
|
159
|
+
raise ValueError(f"invalid {key} list")
|
|
160
|
+
seen = set()
|
|
161
|
+
for item in source[key]:
|
|
162
|
+
if key == "approvals":
|
|
163
|
+
fields(item, ("issue", "scope_sha256", "approved_by", "acceptance_ids",
|
|
164
|
+
"expires_at", "decisions_resolved"))
|
|
165
|
+
if type(item["decisions_resolved"]) is not bool:
|
|
166
|
+
raise ValueError("decisions_resolved must be boolean")
|
|
167
|
+
number = integer(item["issue"], 2147483647)
|
|
168
|
+
actor = string(item["approved_by"])
|
|
169
|
+
approvals.append(Approval(number, digest(item["scope_sha256"]), actor,
|
|
170
|
+
strings(item["acceptance_ids"]), utc(item["expires_at"]),
|
|
171
|
+
item["decisions_resolved"]))
|
|
172
|
+
else:
|
|
173
|
+
fields(item, ("issue", "scope_sha256", "result_sha256", "accepted_by", "closed_at"))
|
|
174
|
+
number = integer(item["issue"], 2147483647)
|
|
175
|
+
actor = string(item["accepted_by"])
|
|
176
|
+
accepted.append(AcceptedDependency(number, digest(item["scope_sha256"]),
|
|
177
|
+
digest(item["result_sha256"]), actor,
|
|
178
|
+
utc(item["closed_at"])))
|
|
179
|
+
if actor not in config.approvers or number in seen:
|
|
180
|
+
raise ValueError(f"untrusted approver or duplicate issue in {key}")
|
|
181
|
+
seen.add(number)
|
|
182
|
+
return Context(config, revision, expected, tuple(approvals), tuple(accepted))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def load_current_context(project, *, host_id):
|
|
186
|
+
"""Read this invocation's HEAD/configuration, with no historical grants."""
|
|
187
|
+
project = Path(project).resolve(strict=True)
|
|
188
|
+
root = Path(os.fsdecode(_git(project, "rev-parse", "--show-toplevel")).rstrip("\n"))
|
|
189
|
+
if not root.is_absolute() or root.resolve(strict=True) != project:
|
|
190
|
+
raise ValueError("project must be the actual Git worktree root")
|
|
191
|
+
revision = _git(project, "rev-parse", "HEAD").decode("ascii").strip()
|
|
192
|
+
config, config_sha256 = _configuration(project, revision, host_id)
|
|
193
|
+
return Context(config, revision, config_sha256, (), ())
|