This repository was archived by the owner on Oct 14, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathaligned_drift_watch.py
More file actions
executable file
·552 lines (492 loc) · 19.9 KB
/
Copy pathaligned_drift_watch.py
File metadata and controls
executable file
·552 lines (492 loc) · 19.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
#!/usr/bin/env python3
"""Watch ALIGNED drift on d6g8k5htny-coder/main; snapshot tip + markers.
Pressure context: ALIGNED can be reverted (happened via PR #32). Write is often
DENIED, but agents must stay ready to restore instantly (prefer Path B).
Exit codes:
0 — ALIGNED (q0 program or Option-B / renewal notice on default tip)
1 — MISALIGNED
2 — transport / API failure
Always prints one JSON object including preferred restore route (B vs A) for the
current tip. Always writes portable/ALIGNED_DRIFT_SNAPSHOT.json (tip SHA +
audit markers) unless --no-snapshot.
Batch 240 — MAIN_PUSH_TOKEN + auto Path B restore:
Discover MAIN_PUSH_TOKEN (env → well-known file drops; value never printed)
and inject into probe/restore children. When default tip is MISALIGNED and a
Path-B-capable write vector is WRITABLE, auto-run scripts/restore_main_face.sh
unless --no-restore. --restore-if-writable remains an explicit opt-in alias
(default auto when token present or write WRITABLE after probe).
Never flips lemma_closed / prizes / premises / research status.
Scientific effect: NONE.
"""
from __future__ import annotations
import argparse
import fcntl
import importlib.util
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
AUDIT = ROOT / "scripts" / "audit_main_alignment.py"
WATCH = ROOT / "scripts" / "watch_main_alignment.py"
PROBE = ROOT / "scripts" / "probe_main_write.py"
VECTORS = ROOT / "scripts" / "probe_main_write_vectors.py"
RESTORE = ROOT / "scripts" / "restore_main_face.sh"
WINDOW = ROOT / "scripts" / "check_autonomous_window.py"
PATH_C_STATUS = ROOT / "scripts" / "write_path_c_status.py"
WHEN_WRITABLE = ROOT / "scripts" / "when_writable_land.py"
SNAPSHOT = ROOT / "portable" / "ALIGNED_DRIFT_SNAPSHOT.json"
PATH_C_STATUS_OUT = ROOT / "portable" / "PATH_C_STATUS.json"
# Batch 256: serialize concurrent Path B restores (hourly watch + agent + lander).
RESTORE_LOCK = ROOT / "portable" / ".aligned_drift_restore.lock"
# Prefer Path B for restore when MISALIGNED; Path A is the alternate
# (PR #2 ready/merge or revert-of-revert). Path C is post-ALIGNED hardening.
ROUTE_WHEN_MISALIGNED = "Path_B"
ROUTE_ALTERNATE = "Path_A"
ROUTE_WHEN_ALIGNED = "Path_C_on_hardening"
def _load_token_helpers():
"""Reuse when_writable_land MAIN_PUSH_TOKEN discovery (never print values)."""
spec = importlib.util.spec_from_file_location("when_writable_land_tok", WHEN_WRITABLE)
if spec is None or spec.loader is None:
return None, None
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return getattr(mod, "resolve_main_push_token", None), getattr(
mod, "apply_token_to_env", None
)
def _resolve_token_env() -> tuple[dict[str, str], str | None]:
"""Return (child_env, token_source_label). Token value never logged."""
resolve, apply = _load_token_helpers()
base = dict(os.environ)
if not callable(resolve) or not callable(apply):
return base, None
token, source = resolve()
if not token:
return base, None
return apply(base, token), source
# Process-wide child env + source label (set once in main).
_CHILD_ENV: dict[str, str] = dict(os.environ)
_TOKEN_SOURCE: str | None = None
def _parse_json_stdout(text: str) -> dict:
text = (text or "").strip()
if not text:
return {}
try:
return json.loads(text)
except json.JSONDecodeError:
try:
start = text.index("{")
return json.loads(text[start:])
except (ValueError, json.JSONDecodeError):
return {"raw_stdout": text[-2000:]}
def _run_json(cmd: list[str], timeout: int = 120) -> tuple[int, dict, str]:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False,
timeout=timeout,
cwd=str(ROOT),
env=_CHILD_ENV,
)
return proc.returncode, _parse_json_stdout(proc.stdout), (proc.stderr or "").strip()
def _maybe_write_path_c_status(report: dict | None = None) -> None:
"""Best-effort refresh of portable/PATH_C_STATUS.json (Batch 195).
Keeps tip/base_tip/write_state/device_code fresh on each hourly watch run.
Never prints secrets; never flips lemma_closed / research status.
"""
if not PATH_C_STATUS.is_file():
return
try:
subprocess.run(
[sys.executable, str(PATH_C_STATUS), "--skip-write-probe"],
capture_output=True,
text=True,
timeout=120,
cwd=str(ROOT),
check=False,
)
except (OSError, subprocess.SubprocessError):
return
if report is not None and PATH_C_STATUS_OUT.is_file():
report["path_c_status_path"] = "portable/PATH_C_STATUS.json"
report["path_c_status_refreshed"] = True
def _preferred_restore_route(align_state: str) -> dict:
"""Prefer Path B over Path A for restore; Path C when already ALIGNED.
Batch 231: when Path C already landed on hardening, prefer tip-sync + drift
watch (no re-land, no research flip).
"""
path_c_landed = False
verify = ROOT / "portable" / "path-c-applied-bundle" / "VERIFY.json"
status = ROOT / "portable" / "PATH_C_STATUS.json"
for path in (verify, status):
if not path.is_file():
continue
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
continue
if data.get("path_c_landed") is True:
path_c_landed = True
break
if align_state == "ALIGNED" and path_c_landed:
return {
"prefer": "tip_sync_drift_watch",
"restore_if_drift": ROUTE_WHEN_MISALIGNED,
"alternate_restore": ROUTE_ALTERNATE,
"path_c_landed": True,
"action": "idle_path_c_done_then_drift_watch",
"note": (
"Path C DONE on hardening (PR #64 @ 93a4ecd). Prefer tip-sync + "
"aligned_drift_watch; do not re-apply Path C. If tip drifts, "
"restore via Path B first. Never flip lemma_closed."
),
}
if align_state == "ALIGNED":
return {
"prefer": ROUTE_WHEN_ALIGNED,
"restore_if_drift": ROUTE_WHEN_MISALIGNED,
"alternate_restore": ROUTE_ALTERNATE,
"action": "path_c_hardening_if_writable_else_dry_run",
"note": (
"Default tip ALIGNED. Prefer Path C on hardening when writable. "
"If tip drifts (e.g. another #32-style revert), restore via Path B "
"first; Path A remains alternate. Never flip lemma_closed."
),
}
if align_state == "MISALIGNED":
return {
"prefer": ROUTE_WHEN_MISALIGNED,
"alternate_restore": ROUTE_ALTERNATE,
"action": "path_b_if_writable_else_portable_prepare",
"note": (
"MISALIGNED — prefer Path B (Option-B README+AGENTS via "
"restore_main_face.sh). Path A (PR #2 / revert-of-revert) is "
"alternate. Never flip lemma_closed / research status."
),
}
return {
"prefer": "none",
"alternate_restore": ROUTE_ALTERNATE,
"action": "retry_transport",
"note": "Transport failure; cannot choose restore route until audit succeeds.",
}
def _window_payload() -> dict:
if not WINDOW.is_file():
return {
"state": "SCRIPT_MISSING",
"hard_stop": False,
"within_window": True,
"scientific_effect": "NONE",
}
_ec, payload, err = _run_json([sys.executable, str(WINDOW)], timeout=30)
if not payload:
return {
"state": "PARSE_ERROR",
"stderr": err[-500:],
"scientific_effect": "NONE",
}
payload.setdefault("scientific_effect", "NONE")
return payload
def _write_snapshot(report: dict, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
audit = report.get("audit") or {}
snap = {
"generated_at_utc": report.get("watched_at_utc"),
"scientific_effect": "NONE",
"goal_complete": False,
"lemma_closed": False,
"state": report.get("state"),
"default_tip_sha": audit.get("default_tip_sha") or report.get("default_tip_sha"),
"default_branch": audit.get("default_branch"),
"complexity_markers_present": audit.get("complexity_markers_present", []),
"q0_or_notice_markers_present": audit.get("q0_or_notice_markers_present", []),
"root_has_AGENTS_md": audit.get("root_has_AGENTS_md"),
"root_has_body": audit.get("root_has_body"),
"root_has_dot_github": audit.get("root_has_dot_github"),
"preferred_restore_route": report.get("preferred_restore_route"),
"write_state": (report.get("write") or {}).get("state"),
"path_b_ready": (report.get("write") or {}).get("path_b_ready"),
"threat_note": (
"ALIGNED can be reverted (PR #32 history). Keep Path B restore ready."
),
}
path.write_text(json.dumps(snap, indent=2, sort_keys=True) + "\n", encoding="utf-8")
try:
report["snapshot_path"] = str(path.relative_to(ROOT))
except ValueError:
report["snapshot_path"] = str(path)
report["snapshot"] = snap
def _maybe_restore(report: dict, batch: str, *, dry_run: bool = False) -> dict:
"""Run restore_main_face when MISALIGNED + Path-B-capable write.
Batch 240: child env carries MAIN_PUSH_TOKEN (discovered; never printed).
Batch 256: non-blocking flock so concurrent watchers do not race two Path B
lands; caller must promote post-restore audit into report["audit"] before
snapshot (otherwise state=ALIGNED while tip SHA stays pre-restore).
"""
detail: dict = {
"attempted": False,
"skipped_reason": None,
"exit": None,
"stdout_tail": None,
"stderr_tail": None,
"dry_run": dry_run,
"route": ROUTE_WHEN_MISALIGNED,
"token_source": _TOKEN_SOURCE,
"lock": "portable/.aligned_drift_restore.lock",
}
if report.get("state") != "MISALIGNED":
detail["skipped_reason"] = "not_misaligned"
return detail
write = report.get("write") or {}
if write.get("state") != "WRITABLE" and not write.get("path_b_ready"):
detail["skipped_reason"] = "not_writable"
return detail
if not RESTORE.is_file():
detail["skipped_reason"] = "restore_script_missing"
return detail
cmd = ["bash", str(RESTORE), "--batch", str(batch)]
if dry_run:
cmd = ["bash", str(RESTORE), "--dry-run", "--batch", str(batch)]
detail["skipped_reason"] = "dry_run"
detail["would_run"] = cmd
detail["attempted"] = False
return detail
RESTORE_LOCK.parent.mkdir(parents=True, exist_ok=True)
lock_fh = None
try:
lock_fh = open(RESTORE_LOCK, "a+", encoding="utf-8")
try:
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
detail["skipped_reason"] = "restore_lock_held"
return detail
lock_fh.seek(0)
lock_fh.truncate()
lock_fh.write(f"pid={os.getpid()} batch={batch}\n")
lock_fh.flush()
detail["attempted"] = True
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False,
timeout=300,
cwd=str(ROOT),
env=_CHILD_ENV,
)
detail["exit"] = proc.returncode
detail["stdout_tail"] = (proc.stdout or "")[-2000:]
detail["stderr_tail"] = (proc.stderr or "")[-2000:]
return detail
finally:
if lock_fh is not None:
try:
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_UN)
except OSError:
pass
try:
lock_fh.close()
except OSError:
pass
def _promote_post_restore_audit(report: dict, audit2: dict | None, audit_ec2: int) -> None:
"""Batch 256: keep snapshot tip/markers consistent with post-restore state.
Without this, restore can flip report['state'] to ALIGNED while report['audit']
(and therefore ALIGNED_DRIFT_SNAPSHOT.default_tip_sha + markers) still holds the
pre-restore MISALIGNED tip — a restore/snapshot race.
"""
if audit2:
report["post_restore_audit"] = audit2
report["audit"] = audit2
tip = audit2.get("default_tip_sha")
if tip:
report["default_tip_sha"] = tip
if audit_ec2 == 0:
report["state"] = "ALIGNED"
elif audit_ec2 == 1:
report["state"] = "MISALIGNED"
else:
report["state"] = "TRANSPORT_ERROR"
report["preferred_restore_route"] = _preferred_restore_route(report["state"])
def _should_auto_restore(
*,
restore_flag: bool,
no_restore: bool,
dry_run: bool,
write_state: str | None,
path_b_ready: bool | None,
token_source: str | None,
) -> bool:
"""Batch 240: auto Path B when MISALIGNED+WRITABLE unless --no-restore.
Explicit --restore-if-writable always enables (unless --no-restore).
Auto also enables when a MAIN_PUSH_TOKEN source is known or write is
already WRITABLE / path_b_ready after probe. --dry-run still decides.
"""
if no_restore:
return False
if restore_flag or dry_run:
return True
if token_source:
return True
if write_state == "WRITABLE" or path_b_ready:
return True
return False
def main() -> int:
global _CHILD_ENV, _TOKEN_SOURCE
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--no-snapshot",
action="store_true",
help="Skip writing portable/ALIGNED_DRIFT_SNAPSHOT.json",
)
parser.add_argument(
"--snapshot",
default=str(SNAPSHOT),
help="Snapshot output path (default: portable/ALIGNED_DRIFT_SNAPSHOT.json)",
)
parser.add_argument(
"--no-probe",
action="store_true",
help="Skip write probe / vectors (audit + route + snapshot only)",
)
parser.add_argument(
"--restore-if-writable",
action="store_true",
help=(
"If MISALIGNED and Path-B write works, run restore_main_face.sh "
"(Batch 240: also auto when MAIN_PUSH_TOKEN present / WRITABLE)"
),
)
parser.add_argument(
"--no-restore",
action="store_true",
help="Disable auto Path B restore even when MISALIGNED+WRITABLE (Batch 240)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Decide Path B restore only; never invoke real restore_main_face land",
)
parser.add_argument(
"--batch",
default=os.environ.get("RESTORE_BATCH", "72"),
help="Batch id passed to restore_main_face when restoring (default 72)",
)
parser.add_argument(
"--no-window",
action="store_true",
help="Skip autonomous window embed",
)
parser.add_argument(
"--no-path-c-status",
action="store_true",
help="Skip write_path_c_status.py refresh (Batch 195 default: refresh)",
)
args = parser.parse_args()
# Batch 240: discover MAIN_PUSH_TOKEN once; inject for all children.
_CHILD_ENV, _TOKEN_SOURCE = _resolve_token_env()
if _TOKEN_SOURCE and _CHILD_ENV.get("MAIN_PUSH_TOKEN"):
# Mirror into process env so nested helpers that read os.environ see it.
os.environ["MAIN_PUSH_TOKEN"] = _CHILD_ENV["MAIN_PUSH_TOKEN"]
if not (os.environ.get("GH_TOKEN") or "").strip():
os.environ["GH_TOKEN"] = _CHILD_ENV["MAIN_PUSH_TOKEN"]
if not (os.environ.get("GITHUB_TOKEN") or "").strip():
os.environ["GITHUB_TOKEN"] = _CHILD_ENV["MAIN_PUSH_TOKEN"]
watched_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
report: dict = {
"watched_at_utc": watched_at,
"scientific_effect": "NONE",
"goal_complete": False,
"lemma_closed": False,
"flipped_anything": False,
"token_source": _TOKEN_SOURCE,
"auto_path_b_restore": True,
}
audit_ec, audit, audit_err = _run_json([sys.executable, str(AUDIT)])
report["audit_exit"] = audit_ec
report["audit_stderr"] = audit_err
if audit:
report["audit"] = audit
report["default_tip_sha"] = audit.get("default_tip_sha")
if audit_ec == 0:
report["state"] = "ALIGNED"
elif audit_ec == 1:
report["state"] = "MISALIGNED"
else:
report["state"] = "TRANSPORT_ERROR"
report["preferred_restore_route"] = _preferred_restore_route(report["state"])
if not args.no_window:
report["autonomous_window"] = _window_payload()
else:
report["autonomous_window"] = None
write_info: dict = {
"probed": False,
"state": None,
"path_b_ready": None,
"probe_exit": None,
"vectors_exit": None,
}
if not args.no_probe:
write_info["probed"] = True
probe_ec, probe, _probe_err = _run_json([sys.executable, str(PROBE)])
write_info["probe_exit"] = probe_ec
write_info["probe"] = {
"state": probe.get("state"),
"create_http_status": probe.get("create_http_status"),
}
vec_ec, vectors, _vec_err = _run_json([sys.executable, str(VECTORS)], timeout=180)
write_info["vectors_exit"] = vec_ec
write_info["path_b_ready"] = bool(vectors.get("path_b_ready"))
write_info["path_b_writable_vectors"] = vectors.get("path_b_writable_vectors", [])
# Prefer vectors aggregate state; fall back to single-ref probe.
write_info["state"] = vectors.get("state") or probe.get("state")
report["write"] = write_info
# Instant-restore readiness signal (even when currently ALIGNED).
report["instant_restore_ready"] = {
"script": "scripts/restore_main_face.sh",
"preferred_when_misaligned": ROUTE_WHEN_MISALIGNED,
"alternate_when_misaligned": ROUTE_ALTERNATE,
"write_currently": write_info.get("state"),
"token_source": _TOKEN_SOURCE,
"auto_restore": not args.no_restore,
"note": (
"Batch 240: when write is WRITABLE (MAIN_PUSH_TOKEN env/file) and tip "
"is MISALIGNED, aligned_drift_watch auto Path B restores unless "
"--no-restore. Prefer restore_main_face.sh; never flip lemma_closed."
),
}
do_restore = _should_auto_restore(
restore_flag=args.restore_if_writable,
no_restore=args.no_restore,
dry_run=args.dry_run,
write_state=write_info.get("state"),
path_b_ready=write_info.get("path_b_ready"),
token_source=_TOKEN_SOURCE,
)
# With --no-probe and no token/flag, skip restore decision entirely (CI record-only).
if args.no_probe and not args.restore_if_writable and not args.dry_run and not _TOKEN_SOURCE:
do_restore = False
if do_restore:
report["restore"] = _maybe_restore(report, args.batch, dry_run=args.dry_run)
# Re-audit after restore attempt so exit code + snapshot reflect tip.
if report["restore"].get("attempted"):
audit_ec2, audit2, audit_err2 = _run_json([sys.executable, str(AUDIT)])
report["post_restore_audit_exit"] = audit_ec2
report["post_restore_audit_stderr"] = audit_err2
# Batch 256: promote audit2 into primary audit before snapshot write.
_promote_post_restore_audit(report, audit2, audit_ec2)
if not args.no_snapshot:
_write_snapshot(report, Path(args.snapshot))
# Batch 195: keep PATH_C_STATUS.json fresh on each watch run (hourly CI + local).
if not args.no_path_c_status:
_maybe_write_path_c_status(report)
print(json.dumps(report, indent=2, sort_keys=True))
if report["state"] == "ALIGNED":
return 0
if report["state"] == "MISALIGNED":
return 1
return 2
if __name__ == "__main__":
raise SystemExit(main())