Repository navigation
Expand file tree
/
Copy pathcodex_app_apply_rrule.py
More file actions
656 lines (597 loc) · 21 KB
/
Copy pathcodex_app_apply_rrule.py
File metadata and controls
656 lines (597 loc) · 21 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
#!/usr/bin/env python3
"""Apply a LoopX scheduler-hint RRULE to the Codex App automation store.
Fallback host bridge for hosts where the Codex App does not expose
``automation_update``. The script:
1. replays the original registry, runtime and Turn through ``loopx quota
should-run`` and consumes ``scheduler_hint.app_automation``;
2. when ``stateful_backoff.apply_needed=true`` and ``recommended_rrule`` is
present, creates the automation TOML and ``automations`` row when they are
missing, backs up the Codex App automation SQLite database, and updates
both stores to the recommended RRULE;
3. runs the bound ``ack_hint.cli_args`` so LoopX persists the reset token and
progression index.
The script is public-safe: it carries no credentials and all host paths can be
overridden for tests or alternate installations.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sqlite3
import subprocess
import sys
import time
import tomllib
from pathlib import Path
from typing import Any
from loopx.control_plane.quota.turn_envelope import COMPLETE_TURN_DECISION_VERSION
from loopx.paths import codex_automation_database, global_registry_path, select_default_runtime_root
from loopx.turn_identity import normalize_turn_instance_id
_FAILURE_OUTPUT_LIMIT = 2_000
def _now_ms() -> int:
return int(time.time() * 1000)
def _bounded_failure_output(value: str) -> str:
output = value.strip()
if len(output) <= _FAILURE_OUTPUT_LIMIT:
return output
half = (_FAILURE_OUTPUT_LIMIT - len(" ... ")) // 2
return f"{output[:half]} ... {output[-half:]}"
def _subprocess_failure_detail(completed: subprocess.CompletedProcess[str]) -> str:
details = []
for label, value in (
("stdout", completed.stdout),
("stderr", completed.stderr),
):
if value is None:
# A decoder failure in CPython's reader thread leaves the stream
# unset instead of raising here, so the decode must not be reported
# as the CLI having printed nothing.
details.append(f"{label}=<not decoded as UTF-8>")
continue
bounded = _bounded_failure_output(value)
if bounded:
details.append(f"{label}={bounded}")
return "; ".join(details) or "no diagnostic output"
def _scheduler_hint_turn_instance_id(parent_turn_instance_id: str) -> str:
"""Reuse the host Turn so the fallback query replays its quota receipt."""
try:
normalized = normalize_turn_instance_id(parent_turn_instance_id)
except ValueError as exc:
raise SystemExit(str(exc)) from exc
if not normalized:
raise SystemExit("--turn-instance-id must not be empty")
return normalized
def _codex_home() -> Path:
"""Resolve the active Codex App home without changing LoopX registry roots."""
configured = os.environ.get("CODEX_HOME", "").strip()
return Path(configured).expanduser() if configured else Path.home() / ".codex"
def _load_registry_goal(registry: Path, goal_id: str) -> dict[str, Any]:
try:
payload = json.loads(registry.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
goals = payload.get("goals") if isinstance(payload, dict) else None
if not isinstance(goals, list):
return {}
for goal in goals:
if isinstance(goal, dict) and str(goal.get("id") or "") == goal_id:
return goal
return {}
def _loopx_json_route(loopx: str, registry: Path, runtime_root: Path | None) -> list[str]:
command = [loopx, "--format", "json", "--registry", str(registry)]
if runtime_root is not None:
command.extend(["--runtime-root", str(runtime_root)])
return command
def _heartbeat_task_body(
*,
loopx: str,
registry: Path,
goal_id: str,
agent_id: str,
runtime_root: Path | None = None,
) -> str:
command = _loopx_json_route(loopx, registry, runtime_root) + [
"heartbeat-prompt",
"--thin",
"--goal-id",
goal_id,
"--agent-id",
agent_id,
"--codex-app",
]
completed = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
encoding="utf-8",
)
if completed.returncode != 0:
raise SystemExit(
f"loopx heartbeat-prompt failed ({completed.returncode}): "
f"{_subprocess_failure_detail(completed)}"
)
if completed.stdout is None:
raise SystemExit(
f"loopx heartbeat-prompt output could not be decoded as UTF-8: "
f"{_subprocess_failure_detail(completed)}"
)
try:
payload = json.loads(completed.stdout)
except json.JSONDecodeError as exc:
raise SystemExit(f"loopx heartbeat-prompt returned invalid JSON: {exc}") from exc
body = payload.get("task_body") if isinstance(payload, dict) else None
if not isinstance(body, str) or not body.strip():
raise SystemExit("loopx heartbeat-prompt returned no task_body")
return body
def _toml_string(value: str) -> str:
"""Encode a string in the JSON-compatible subset of TOML basic strings."""
return json.dumps(value, ensure_ascii=False)
def _write_automation_toml(
path: Path,
*,
automation_id: str,
name: str,
prompt: str,
rrule: str,
thread_id: str,
) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
text = (
"version = 1\n"
f"id = {_toml_string(automation_id)}\n"
'kind = "heartbeat"\n'
f"name = {_toml_string(name)}\n"
f"prompt = {_toml_string(prompt)}\n"
'status = "ACTIVE"\n'
f"rrule = {_toml_string(rrule)}\n"
f"target_thread_id = {_toml_string(thread_id)}\n"
f"created_at = {_now_ms()}\n"
f"updated_at = {_now_ms()}\n"
)
path.write_text(text, encoding="utf-8")
def _read_automation_prompt(path: Path) -> str | None:
try:
automation = tomllib.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, tomllib.TOMLDecodeError) as exc:
raise SystemExit(f"automation TOML is unreadable or invalid: {path}") from exc
prompt = automation.get("prompt")
return prompt if isinstance(prompt, str) and prompt.strip() else None
def _sqlite_row_exists(db_path: Path, automation_id: str) -> bool:
if not db_path.exists():
return False
connection = sqlite3.connect(str(db_path))
try:
try:
row = connection.execute(
"SELECT 1 FROM automations WHERE id=?", (automation_id,)
).fetchone()
except sqlite3.OperationalError:
return False
finally:
connection.close()
return row is not None
def _ensure_sqlite_row(
db_path: Path,
*,
automation_id: str,
name: str,
prompt: str,
rrule: str,
cwd: str,
backup_path: Path | None,
) -> None:
if backup_path is not None and db_path.exists():
connection = sqlite3.connect(str(db_path))
try:
connection.execute("PRAGMA busy_timeout=5000")
connection.backup(sqlite3.connect(str(backup_path)))
finally:
connection.close()
now = _now_ms()
connection = sqlite3.connect(str(db_path))
try:
connection.execute("PRAGMA busy_timeout=5000")
connection.execute(
"""
CREATE TABLE IF NOT EXISTS automations (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
prompt TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'ACTIVE',
next_run_at INTEGER,
last_run_at INTEGER,
cwds TEXT NOT NULL DEFAULT '[]',
rrule TEXT NOT NULL DEFAULT 'FREQ=HOURLY;INTERVAL=24;BYMINUTE=0',
model TEXT,
reasoning_effort TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
target_type TEXT,
project_id TEXT
)
"""
)
connection.execute(
"""
INSERT INTO automations (
id, name, prompt, status, next_run_at, last_run_at,
cwds, rrule, model, reasoning_effort, created_at,
updated_at, target_type, project_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name,
prompt=excluded.prompt,
status=excluded.status,
next_run_at=excluded.next_run_at,
last_run_at=excluded.last_run_at,
cwds=excluded.cwds,
rrule=excluded.rrule,
updated_at=excluded.updated_at
""",
(
automation_id,
name,
prompt,
"ACTIVE",
now + 30_000,
now,
json.dumps([cwd]) if cwd else "[]",
rrule,
"",
"",
now,
now,
"",
"",
),
)
connection.commit()
finally:
connection.close()
def _resolve_bound_thread_id(
goal: dict[str, Any],
*,
goal_id: str,
agent_id: str,
automation_id: str,
) -> str:
"""Resolve the one bound host thread this automation must target.
The installed manifest carries its target thread, and host-side readback
resolves a goal's threads through the goal's ``thread_agent_bindings``.
Installing with an unresolved thread therefore writes an automation that no
readback can observe, so an unbound or ambiguous binding is refused here
instead of being persisted as an empty value.
"""
bindings = (goal.get("coordination") or {}).get("thread_agent_bindings")
matches: list[str] = []
for binding in bindings if isinstance(bindings, list) else []:
if not isinstance(binding, dict):
continue
if str(binding.get("agent_id") or "") != agent_id:
continue
thread_id = str(binding.get("thread_id") or "").strip()
if thread_id:
matches.append(thread_id)
if len(matches) != 1:
# The recovery command must be runnable as printed: ``bind-agent-thread``
# is registered at the root, and without ``--execute`` it only previews
# the binding it is asked to write.
raise SystemExit(
f"{automation_id}: expected exactly one bound host thread for agent "
f"{agent_id!r}, found {len(matches)}; bind one with "
f"`loopx bind-agent-thread --goal-id {goal_id} --agent-id {agent_id} "
"--host-surface codex-app --thread-id <host-thread-id> --execute`, or "
"remove an extra binding with "
f"`loopx unbind-agent-thread --goal-id {goal_id} --agent-id {agent_id} "
"--host-surface codex-app --thread-id <host-thread-id> --execute`, "
"before installing the Codex App automation"
)
return matches[0]
def _ensure_automation(
*,
loopx: str,
registry: Path,
automations_root: Path,
db_path: Path,
automation_id: str,
goal_id: str,
agent_id: str,
rrule: str,
backup_path: Path | None,
runtime_root: Path | None = None,
) -> bool:
toml_path = automations_root / automation_id / "automation.toml"
if toml_path.exists() and _sqlite_row_exists(db_path, automation_id):
return False
goal = _load_registry_goal(registry, goal_id)
thread_id = _resolve_bound_thread_id(
goal,
goal_id=goal_id,
agent_id=agent_id,
automation_id=automation_id,
)
cwd = str(goal.get("repo") or "")
name = f"{goal_id} LoopX"
if toml_path.exists():
prompt = _read_automation_prompt(toml_path) or _heartbeat_task_body(
loopx=loopx,
registry=registry,
goal_id=goal_id,
agent_id=agent_id,
runtime_root=runtime_root,
)
else:
prompt = _heartbeat_task_body(
loopx=loopx,
registry=registry,
goal_id=goal_id,
agent_id=agent_id,
runtime_root=runtime_root,
)
_write_automation_toml(
toml_path,
automation_id=automation_id,
name=name,
prompt=prompt,
rrule=rrule,
thread_id=thread_id,
)
_ensure_sqlite_row(
db_path,
automation_id=automation_id,
name=name,
prompt=prompt,
rrule=rrule,
cwd=cwd,
backup_path=backup_path,
)
return True
def _load_scheduler_hint(
*,
loopx: str,
registry: Path,
goal_id: str,
agent_id: str,
parent_turn_instance_id: str,
capabilities: list[str],
runtime_root: Path | None = None,
) -> tuple[dict[str, Any], dict[str, Any]]:
turn_instance_id = _scheduler_hint_turn_instance_id(parent_turn_instance_id)
command = _loopx_json_route(loopx, registry, runtime_root) + [
"quota",
"should-run",
"--goal-id",
goal_id,
"--agent-id",
agent_id,
"--codex-app",
"--turn-instance-id",
turn_instance_id,
]
for capability in capabilities:
command.extend(["--available-capability", capability])
completed = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
encoding="utf-8",
env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"},
)
if completed.returncode != 0:
raise SystemExit(
f"loopx should-run failed ({completed.returncode}): "
f"{_subprocess_failure_detail(completed)}"
)
if completed.stdout is None:
raise SystemExit(
f"loopx should-run output could not be decoded as UTF-8: "
f"{_subprocess_failure_detail(completed)}"
)
try:
payload = json.loads(completed.stdout)
except json.JSONDecodeError as exc:
raise SystemExit(f"loopx should-run returned invalid JSON: {exc}") from exc
hint = payload.get("scheduler_hint") if isinstance(payload, dict) else None
if not isinstance(hint, dict):
return {}, {}
app = hint.get("app_automation")
if "app_automation" not in hint and payload.get("schema_version") != COMPLETE_TURN_DECISION_VERSION:
app = hint.get("codex_app")
if not isinstance(app, dict):
return {}, {}
stateful = app.get("stateful_backoff", {})
if not isinstance(stateful, dict):
stateful = {}
return app, stateful
def _update_toml(toml_path: Path, rrule: str) -> None:
text = toml_path.read_text(encoding="utf-8")
pattern = re.compile(r'^rrule\s*=\s*".*?"', re.MULTILINE)
if not pattern.search(text):
raise SystemExit(f"automation TOML has no rrule field: {toml_path}")
replacement = f"rrule = {_toml_string(rrule)}"
toml_path.write_text(
pattern.sub(lambda _: replacement, text),
encoding="utf-8",
)
def _update_sqlite(
db_path: Path,
*,
automation_id: str,
rrule: str,
backup_path: Path | None,
) -> None:
if backup_path is not None:
if not db_path.exists():
raise SystemExit(f"automation SQLite does not exist: {db_path}")
connection = sqlite3.connect(str(db_path))
try:
connection.execute("PRAGMA busy_timeout=5000")
connection.backup(sqlite3.connect(str(backup_path)))
finally:
connection.close()
connection = sqlite3.connect(str(db_path))
try:
connection.execute("PRAGMA busy_timeout=5000")
cursor = connection.execute(
"UPDATE automations SET rrule=?, updated_at=? WHERE id=?",
(rrule, _now_ms(), automation_id),
)
connection.commit()
if cursor.rowcount != 1:
raise SystemExit(
f"automation row not found or not updated in {db_path}: "
f"{automation_id}"
)
finally:
connection.close()
def _run_ack(loopx: str, ack_args: list[str]) -> None:
completed = subprocess.run(
[loopx, *ack_args],
check=False,
capture_output=True,
text=True,
encoding="utf-8",
)
if completed.returncode != 0:
raise SystemExit(
f"loopx scheduler ACK failed ({completed.returncode}): "
f"{_subprocess_failure_detail(completed)}"
)
def _parse_args(argv: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Apply the LoopX scheduler-hint RRULE to the Codex App automation "
"store (TOML + SQLite) and run the bound ACK."
)
)
parser.add_argument("--goal-id", default="loopx-meta")
parser.add_argument(
"--agent-id",
required=True,
help="Registered LoopX Agent that owns this scheduler mutation.",
)
parser.add_argument(
"--registry",
type=Path,
help="Global registry; defaults to the selected LoopX local state route.",
)
parser.add_argument(
"--runtime-root",
type=Path,
help="Original runtime root of the parent Turn. Defaults to the registry route.",
)
parser.add_argument("--automation-id", default="loopx")
parser.add_argument(
"--automations-root",
type=Path,
default=_codex_home() / "automations",
)
parser.add_argument(
"--db-path",
type=Path,
default=codex_automation_database(_codex_home()),
)
parser.add_argument("--loopx", default="loopx")
parser.add_argument(
"--capability",
action="append",
default=[],
)
parser.add_argument(
"--turn-instance-id",
default=f"apply-rrule-{_now_ms()}",
help=(
"outer host turn identity; the bridge reuses it when replaying the "
"scheduler hint"
),
)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(argv)
if args.registry is None:
args.registry = global_registry_path(args.runtime_root or select_default_runtime_root())
return args
def main(argv: list[str] | None = None) -> int:
args = _parse_args(sys.argv[1:] if argv is None else argv)
app, stateful = _load_scheduler_hint(
loopx=args.loopx,
registry=args.registry,
goal_id=args.goal_id,
agent_id=args.agent_id,
parent_turn_instance_id=args.turn_instance_id,
capabilities=args.capability,
runtime_root=args.runtime_root,
)
apply_needed = stateful.get("apply_needed") is True
rrule = app.get("recommended_rrule") or stateful.get("current_rrule")
ack_hint = app.get("ack_hint", {})
ack_args = ack_hint.get("cli_args") if isinstance(ack_hint, dict) else None
toml_path = args.automations_root / args.automation_id / "automation.toml"
toml_missing = not toml_path.exists()
sqlite_missing = not _sqlite_row_exists(args.db_path, args.automation_id)
if not apply_needed:
print(
f"no apply needed (apply_needed=false); rrule={rrule or 'unknown'}; "
f"ack_needed={stateful.get('ack_needed') is True}"
)
if (
stateful.get("ack_needed") is True
and isinstance(ack_args, list)
and not args.dry_run
):
_run_ack(args.loopx, ack_args)
return 0
if not rrule:
raise SystemExit(
"apply_needed=true but no recommended_rrule/current_rrule was projected"
)
if not isinstance(ack_args, list):
raise SystemExit("apply_needed=true but no ack_hint.cli_args was projected")
backup_path = (
Path(str(args.db_path) + f".bak-{time.strftime('%Y%m%dT%H%M%S')}")
if not args.dry_run
else None
)
print(f"apply rrule={rrule}")
print(f"toml={toml_path}")
print(f"db={args.db_path}")
print(f"backup={backup_path or 'none (dry-run)'}")
print(f"ack_args={ack_args}")
if args.dry_run:
if toml_missing or sqlite_missing:
print(
"dry-run: would create missing automation "
f"{args.automation_id} (toml={not toml_missing}, "
f"sqlite={not sqlite_missing})"
)
print("dry-run: no writes performed")
return 0
created = False
if toml_missing or sqlite_missing:
created = _ensure_automation(
loopx=args.loopx,
registry=args.registry,
automations_root=args.automations_root,
db_path=args.db_path,
automation_id=args.automation_id,
goal_id=args.goal_id,
agent_id=args.agent_id,
rrule=rrule,
backup_path=backup_path,
runtime_root=args.runtime_root,
)
print(f"created missing automation: {args.automation_id}")
_update_toml(toml_path, rrule)
_update_sqlite(
args.db_path,
automation_id=args.automation_id,
rrule=rrule,
backup_path=None if created else backup_path,
)
_run_ack(args.loopx, ack_args)
print(f"applied {rrule} and ACKed")
return 0
if __name__ == "__main__":
raise SystemExit(main())