Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 69 additions & 15 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3878,6 +3878,59 @@ def _reddog_queue_stage_rejection_reasons(stage_callable: Any) -> tuple[str, ...
return tuple(str(value) for value in values if str(value or "").strip())


def _reddog_record_queue_control_result(repo_root: Path, result: Mapping[str, Any]) -> Dict[str, Any]:
"""Record and expose one resident queue control-loop result."""

recorded = dict(result)
try:
from modules.communication.moltbot_bridge.src.reddog_resident_queue_binding_profile import (
resident_queue_runtime_file_path,
resident_queue_runtime_flag_enabled,
)

if resident_queue_runtime_flag_enabled(
os.environ,
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPT_PERSISTENCE",
):
receipt_path = resident_queue_runtime_file_path(
os.environ,
repo_root,
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPTS_PATH",
)
if receipt_path:
from modules.communication.moltbot_bridge.src.reddog_resident_control_loop_receipt_store import (
append_resident_control_loop_receipt,
)

receipt = append_resident_control_loop_receipt(
path=receipt_path,
result=recorded,
repo_root=repo_root,
created_at=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
)
recorded["receipt_id"] = receipt.receipt_id
recorded["receipt_path"] = str(receipt_path)
except Exception as exc:
recorded["accepted"] = False
recorded["status"] = "CONTROL_LOOP_RECEIPT_PERSISTENCE_REJECT"
recorded["receipt_id"] = ""
recorded["receipt_path"] = ""
recorded["rejection_reasons"] = tuple(
dict.fromkeys(
[
*(
str(reason)
for reason in recorded.get("rejection_reasons", ())
if str(reason or "").strip()
),
f"receipt_persistence:{type(exc).__name__}",
]
)
)
run_reddog_resident_queue_control_loop_preflight.last_result = recorded
return recorded


def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
"""
Drive the resident queue through bounded serial/claim rounds.
Expand All @@ -3904,7 +3957,7 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
)
if not requested:
if not run_reddog_resident_queue_serial_loop_preflight(repo_root):
run_reddog_resident_queue_control_loop_preflight.last_result = {
_reddog_record_queue_control_result(repo_root, {
"accepted": False,
"status": "SERIAL_LOOP_REJECT",
"rounds": 0,
Expand All @@ -3917,13 +3970,13 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
"rejection_reasons": _reddog_queue_stage_rejection_reasons(
run_reddog_resident_queue_serial_loop_preflight
),
}
})
return False
claim_ok = run_reddog_openclaw_signed_worker_claim_loop_preflight(repo_root)
claim_receipts = _reddog_queue_stage_receipt_ids(
run_reddog_openclaw_signed_worker_claim_loop_preflight
)
run_reddog_resident_queue_control_loop_preflight.last_result = {
recorded = _reddog_record_queue_control_result(repo_root, {
"accepted": bool(claim_ok)
and not _reddog_queue_stage_rejected(
run_reddog_openclaw_signed_worker_claim_loop_preflight
Expand All @@ -3942,8 +3995,8 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
"rejection_reasons": _reddog_queue_stage_rejection_reasons(
run_reddog_openclaw_signed_worker_claim_loop_preflight
),
}
return claim_ok
})
return bool(recorded.get("accepted")) and claim_ok

enforced = os.getenv("REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_ENFORCED", "0") != "0"
raw_rounds = os.getenv("REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_MAX_ROUNDS", "8").strip()
Expand All @@ -3953,15 +4006,15 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
max_rounds = 0
if max_rounds < 1:
print("[REDDOG-QUEUE-CONTROL] preflight=FAIL error=invalid_max_rounds")
run_reddog_resident_queue_control_loop_preflight.last_result = {
_reddog_record_queue_control_result(repo_root, {
"accepted": False,
"status": "INVALID_MAX_ROUNDS",
"rounds": 0,
"serial_progress": 0,
"claim_progress": 0,
"receipt_ids": (),
"rejection_reasons": ("invalid_max_rounds",),
}
})
return not enforced

completed_rounds = 0
Expand All @@ -3979,7 +4032,7 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
if not serial_ok or _reddog_queue_stage_rejected(
run_reddog_resident_queue_serial_loop_preflight
):
run_reddog_resident_queue_control_loop_preflight.last_result = {
_reddog_record_queue_control_result(repo_root, {
"accepted": False,
"status": "SERIAL_LOOP_REJECT",
"rounds": completed_rounds,
Expand All @@ -3989,7 +4042,7 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
"rejection_reasons": _reddog_queue_stage_rejection_reasons(
run_reddog_resident_queue_serial_loop_preflight
),
}
})
print(
f"[REDDOG-QUEUE-CONTROL] preflight=FAIL round={round_index} "
"stage=serial_loop"
Expand All @@ -4009,7 +4062,7 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
if not claim_ok or _reddog_queue_stage_rejected(
run_reddog_openclaw_signed_worker_claim_loop_preflight
):
run_reddog_resident_queue_control_loop_preflight.last_result = {
_reddog_record_queue_control_result(repo_root, {
"accepted": False,
"status": "CLAIM_LOOP_REJECT",
"rounds": completed_rounds,
Expand All @@ -4019,7 +4072,7 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
"rejection_reasons": _reddog_queue_stage_rejection_reasons(
run_reddog_openclaw_signed_worker_claim_loop_preflight
),
}
})
print(
f"[REDDOG-QUEUE-CONTROL] preflight=FAIL round={round_index} "
"stage=openclaw_claim_loop"
Expand All @@ -4031,23 +4084,24 @@ def run_reddog_resident_queue_control_loop_preflight(repo_root: Path) -> bool:
break

receipt_ids_tuple = tuple(dict.fromkeys(receipt_ids))
run_reddog_resident_queue_control_loop_preflight.last_result = {
recorded = _reddog_record_queue_control_result(repo_root, {
"accepted": True,
"status": "PASS",
"rounds": completed_rounds,
"serial_progress": serial_progress_total,
"claim_progress": claim_progress_total,
"receipt_ids": receipt_ids_tuple,
"rejection_reasons": (),
}
})
receipts = ",".join(receipt_ids_tuple) or "(none)"
control_receipt = str(recorded.get("receipt_id") or "(none)")
print(
f"[REDDOG-QUEUE-CONTROL] preflight=PASS rounds={completed_rounds} "
f"max_rounds={max_rounds} stopped_reason={stopped_reason} "
f"serial_progress={serial_progress_total} claim_progress={claim_progress_total} "
f"receipts={receipts}"
f"receipts={receipts} control_receipt={control_receipt}"
)
return True
return bool(recorded.get("accepted"))


def run_reddog_openclaw_signed_worker_claim_loop_preflight(repo_root: Path) -> bool:
Expand Down
17 changes: 17 additions & 0 deletions modules/communication/moltbot_bridge/ModLog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# ModLog - moltbot_bridge

## 2026-07-17: REDDOG_RESIDENT_CONTROL_LOOP_RECEIPT_PERSISTENCE_PHASE1

**Author**: 0102 (Codex) | Commander: 012 | WSP: 00, 15, 22, 97

- Added an append-only resident control-loop receipt store for compact JSONL
summaries of completed control-loop runs.
- Added profile-derived `REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPT_PERSISTENCE`
and `REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPTS_PATH` wiring so resident
profiles can persist control receipts under the outside-repo runtime root.
- Wired `main.py` to persist accepted control-loop summaries and fail closed if
configured receipt persistence rejects.
- Added regressions proving persisted control receipts bind the signed-worker
task receipt IDs surfaced by the OpenClaw claim loop.
- HoloIndex query-only check did not surface the new control-loop receipt store;
recorded as HOLOINDEX_REDDOG_RESIDENT_CONTROL_LOOP_RECEIPT_PERSISTENCE_INDEX_GAP.
No runtime reindex performed.

## 2026-07-17: REDDOG_RESIDENT_CONTROL_LOOP_RECEIPT_SUMMARY_PHASE1

**Author**: 0102 (Codex) | Commander: 012 | WSP: 00, 15, 22, 97
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
"""Append-only receipts for the resident RedDog control loop.

Slice: REDDOG_RESIDENT_CONTROL_LOOP_RECEIPT_PERSISTENCE_PHASE1

This module records compact control-loop summaries after the already-governed
resident queue serial loop and OpenClaw signed-worker claim loop run. It does
not invoke workers, mutate source, issue authority, reindex HoloIndex, or
settle rewards.
"""

from __future__ import annotations

import hashlib
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Mapping


CONTROL_LOOP_RECEIPT_SCHEMA_VERSION = "reddog_resident_control_loop_receipt.v1"


@dataclass(frozen=True)
class ResidentControlLoopReceipt:
schema_version: str
receipt_id: str
accepted: bool
status: str
rounds: int
serial_progress: int
claim_progress: int
receipt_ids: tuple[str, ...]
rejection_reasons: tuple[str, ...]
created_at: str
repo_root_digest: str
no_authority_issued: bool = True
no_worker_spawn_performed: bool = True
no_shell_command_executed: bool = True
no_holoindex_reindex_performed: bool = True
no_merge_performed: bool = True
no_reward_settlement_performed: bool = True

def to_dict(self) -> dict[str, Any]:
payload = asdict(self)
payload["receipt_ids"] = list(self.receipt_ids)
payload["rejection_reasons"] = list(self.rejection_reasons)
return payload


def build_resident_control_loop_receipt(
*,
result: Mapping[str, Any],
repo_root: Path | str,
created_at: str,
) -> ResidentControlLoopReceipt:
"""Build a deterministic receipt for an already-produced control result."""

payload = {
"schema_version": CONTROL_LOOP_RECEIPT_SCHEMA_VERSION,
"accepted": bool(result.get("accepted")),
"status": str(result.get("status") or ""),
"rounds": _int(result.get("rounds")),
"serial_progress": _int(result.get("serial_progress")),
"claim_progress": _int(result.get("claim_progress")),
"receipt_ids": _string_tuple(result.get("receipt_ids")),
"rejection_reasons": _string_tuple(result.get("rejection_reasons")),
"created_at": str(created_at or ""),
"repo_root_digest": _digest(str(Path(repo_root).resolve())),
"no_authority_issued": True,
"no_worker_spawn_performed": True,
"no_shell_command_executed": True,
"no_holoindex_reindex_performed": True,
"no_merge_performed": True,
"no_reward_settlement_performed": True,
}
payload["receipt_id"] = "reddog_resident_control_loop_" + _digest(payload)[:16]
return ResidentControlLoopReceipt(**payload)


def append_resident_control_loop_receipt(
*,
path: Path | str,
result: Mapping[str, Any],
repo_root: Path | str,
created_at: str,
) -> ResidentControlLoopReceipt:
"""Append one control-loop receipt as JSONL and return it."""

receipt = build_resident_control_loop_receipt(
result=result,
repo_root=repo_root,
created_at=created_at,
)
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("a", encoding="utf-8", newline="\n") as handle:
handle.write(json.dumps(receipt.to_dict(), sort_keys=True, separators=(",", ":")))
handle.write("\n")
return receipt


def _string_tuple(value: Any) -> tuple[str, ...]:
if not isinstance(value, (list, tuple)):
return ()
return tuple(str(item) for item in value if str(item or "").strip())


def _int(value: Any) -> int:
try:
return max(int(value or 0), 0)
except (TypeError, ValueError):
return 0


def _digest(payload: Any) -> str:
raw = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=str)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()


__all__ = [
"CONTROL_LOOP_RECEIPT_SCHEMA_VERSION",
"ResidentControlLoopReceipt",
"append_resident_control_loop_receipt",
"build_resident_control_loop_receipt",
]
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
"REDDOG_SIGNED_WORKER_QUEUE_LOOP_RUNNER",
"REDDOG_RESIDENT_QUEUE_SERIAL_LOOP",
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP",
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPT_PERSISTENCE",
}
)

Expand Down Expand Up @@ -129,6 +130,9 @@
"REDDOG_SIGNER_SOCKET_PATH": "reddog_signer.sock",
"REDDOG_RESIDENT_QUEUE_CHAIN_RESULTS_PATH": "resident_queue_chain_results.json",
"REDDOG_RESIDENT_QUEUE_AUTHORITY_PROFILE_PATH": "authority_profile.json",
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPTS_PATH": (
"resident_queue_control_loop_receipts.jsonl"
),
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,20 @@ def _serve_signer() -> None:
"receipt_ids"
][0]
).startswith("signed_worker_task_execution_")
assert "control_receipt=reddog_resident_control_loop_" in captured
control_receipt_path = Path(
resident_queue_runtime_file_path(
profile_env,
repo,
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPTS_PATH",
)
)
control_receipt = json.loads(control_receipt_path.read_text(encoding="utf-8").splitlines()[-1])
assert (
control_receipt["receipt_id"]
== main.run_reddog_resident_queue_control_loop_preflight.last_result["receipt_id"]
)
assert control_receipt["receipt_ids"][0].startswith("signed_worker_task_execution_")
assert "REDDOG_WORK_ORDERS_PATH" not in os.environ

pending = [
Expand Down Expand Up @@ -1441,6 +1455,20 @@ def _serve_signer_cli() -> None:
"receipt_ids"
][0]
).startswith("signed_worker_task_execution_")
assert "control_receipt=reddog_resident_control_loop_" in captured
control_receipt_path = Path(
resident_queue_runtime_file_path(
profile_env,
repo,
"REDDOG_RESIDENT_QUEUE_CONTROL_LOOP_RECEIPTS_PATH",
)
)
control_receipt = json.loads(control_receipt_path.read_text(encoding="utf-8").splitlines()[-1])
assert (
control_receipt["receipt_id"]
== main.run_reddog_resident_queue_control_loop_preflight.last_result["receipt_id"]
)
assert control_receipt["receipt_ids"][0].startswith("signed_worker_task_execution_")
assert calls
stored = json.loads(chain.read_text(encoding="utf-8"))
assert stored["stage_results"]["worker_dispatch_runtime"]["accepted"] is True
Expand Down
Loading