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
78 changes: 74 additions & 4 deletions loopx/capabilities/native_chat/steward_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@

TARGET = "steward-portfolio-watch"
FOLLOWUP_TARGET_PREFIX = "steward-monitor-followup:"
ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS = 60
ADVANCEMENT_PRECOMMIT_RETRY_SUFFIX = ".precommit-retry"
_LOG = logging.getLogger(__name__)


Expand Down Expand Up @@ -69,6 +71,76 @@ def advancement_turn_id(todo: dict[str, Any]) -> str:
[todo["todo_id"], stamp], sort_keys=True).encode()).hexdigest()[:40]


def _is_precommit_retryable_advancement_turn(
turn: Mapping[str, Any],
*,
now: float | None = None,
) -> bool:
"""Allow one delayed retry only when zero kernel/Steward writes occurred."""
from .steward_turn import _iso_timestamp_seconds

if turn.get("status") != "completed":
return False
resp = turn.get("response")
if not isinstance(resp, Mapping):
return False
nl = resp.get("native_loopx")
if not isinstance(nl, Mapping):
return False
if nl.get("ok") is not False or nl.get("status") != "failed":
return False
if nl.get("result_kind") not in {"validation_failed", "host_failure"}:
return False
receipt = nl.get("receipt")
commit_eligibility = (receipt.get("commit_eligibility") if isinstance(receipt, Mapping) else None) or {}
effects = nl.get("effects") or {}
if not isinstance(commit_eligibility, Mapping) or not isinstance(effects, Mapping):
return False
if not (commit_eligibility.get("writeback") is False or effects.get("state_written") is False):
return False
if (effects.get("state_written") is True
or effects.get("quota_spent") is True
or effects.get("scheduler_acknowledged") is True):
return False
if (resp.get("steward_owner_report_queued")
or resp.get("context_handoff")
or resp.get("steward_user_action_receipts")):
return False
completed_ts = _iso_timestamp_seconds(turn.get("completed_at"))
if completed_ts is None:
return False
current_ts = time.time() if now is None else now
return current_ts - completed_ts >= ADVANCEMENT_PRECOMMIT_RETRY_COOLDOWN_SECONDS


def resolve_advancement_turn_id(
store: Any,
actor: Mapping[str, Any],
todo: dict[str, Any],
*,
now: float | None = None,
) -> str | None:
"""Resolve the active attempt id or at most one post-cooldown pre-commit retry."""
from .steward_turn import native_steward_client_id

base = advancement_turn_id(todo)
existing = store.turn_for_client(
actor["session_id"],
native_steward_client_id(actor, base),
)
if existing is None:
return base
if not _is_precommit_retryable_advancement_turn(existing, now=now):
return None
retry_token = base + ADVANCEMENT_PRECOMMIT_RETRY_SUFFIX
if store.turn_for_client(
actor["session_id"],
native_steward_client_id(actor, retry_token),
) is not None:
return None
return retry_token


def _github_repo_slug(task_repository: Any) -> str | None:
if not isinstance(task_repository, str):
return None
Expand Down Expand Up @@ -549,10 +621,8 @@ def pump_steward_monitors(controller: Any, *, cancelled=lambda: False) -> list[d
if dispatched:
continue
for adv in service.runnable_advancement_todos(actor):
from .steward_turn import native_steward_client_id
turn_id_token = advancement_turn_id(adv)
if controller.store.turn_for_client(actor["session_id"],
native_steward_client_id(actor, turn_id_token)) is not None:
turn_id_token = resolve_advancement_turn_id(controller.store, actor, adv)
if turn_id_token is None:
continue
accepted, created = StewardTurnHost(controller).submit(binding["binding_id"],
turn_instance_id=turn_id_token, todo_id=adv["todo_id"], work_kind="native_turn")
Expand Down
107 changes: 106 additions & 1 deletion loopx/capabilities/native_chat/steward_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,110 @@ def _normalize_report_kernel_candidate(candidate: Mapping[str, Any]) -> dict[str
return normalized


def _split_evidence_text_chunks(text: str, max_item_chars: int) -> list[str]:
"""Split a single normalized evidence string cleanly at natural boundaries."""
if len(text) <= max_item_chars:
return [text]
chunks: list[str] = []
rest = text
delimiters = ("; ", ". ", ";", "。", ", ", ",", " ")
while len(rest) > max_item_chars:
split_at = -1
matched_delim = ""
for delim in delimiters:
pos = rest.rfind(delim, 1, max_item_chars)
if pos > 0:
split_at = pos
matched_delim = delim
break
if split_at <= 0:
chunks.append(rest[:max_item_chars])
rest = rest[max_item_chars:].lstrip()
elif matched_delim in (";", "。", ","):
end = min(split_at + len(matched_delim), max_item_chars)
chunks.append(rest[:end].strip())
rest = rest[end:].lstrip()
else:
head = rest[:split_at].rstrip()
if matched_delim == ". " and len(head) + 1 <= max_item_chars:
head += "."
chunks.append(head)
rest = rest[split_at + len(matched_delim) :].lstrip()
if rest:
chunks.append(rest)
return [chunk for chunk in chunks if chunk]


def _append_bounded_ellipsis(text: str, limit: int) -> str:
if limit <= 0:
return ""
if limit <= 3:
return text[:limit]
if len(text) + 3 <= limit and not text.endswith("..."):
return text + "..."
trimmed = text[: max(1, limit - 3)].rstrip()
return (trimmed or text[: max(1, limit - 3)]) + "..."


def _split_bounded_evidence_items(
raw: Any,
*,
max_items: int = 8,
max_item_chars: int = 240,
max_total_chars: int = 1_200,
) -> Any:
"""Split over-long Steward evidence strings without masking invalid shapes."""
if not isinstance(raw, list) or not raw:
return raw
if not all(isinstance(item, str) and item.strip() for item in raw):
return raw
chunks: list[str] = []
for item in raw:
normalized = " ".join(item.split()).strip()
chunks.extend(_split_evidence_text_chunks(normalized, max_item_chars))
if len(chunks) > max_items:
merged: list[str] = []
for chunk in chunks:
if merged and len(merged[-1]) + 2 + len(chunk) <= max_item_chars:
merged[-1] = f"{merged[-1]}; {chunk}"
else:
merged.append(chunk)
chunks = merged
clipped = len(chunks) > max_items
if clipped:
chunks = chunks[:max_items]
bounded: list[str] = []
used = 0
for idx, chunk in enumerate(chunks):
remaining = max_total_chars - used
if remaining <= 0:
clipped = True
break
if len(chunk) > remaining or len(chunk) > max_item_chars:
cap = min(max_item_chars, remaining)
bounded.append(_append_bounded_ellipsis(chunk, cap))
used += len(bounded[-1])
clipped = True
break
bounded.append(chunk)
used += len(chunk)
if clipped and bounded and not bounded[-1].endswith("..."):
room = min(max_item_chars, len(bounded[-1]) + (max_total_chars - used))
bounded[-1] = _append_bounded_ellipsis(bounded[-1], room)
return bounded


def _normalize_steward_advancement_kernel_candidate(candidate: Mapping[str, Any]) -> dict[str, Any]:
"""Keep Steward advancement evidence within kernel per-item and total limits."""
normalized = dict(candidate)
if normalized.get("delivery_batch_scale") == "multi_surface_or_implementation":
normalized["delivery_batch_scale"] = "multi_surface"
for field in ("work_evidence", "validation_evidence"):
if field in normalized:
normalized[field] = _split_bounded_evidence_items(normalized[field])
return normalized


class StewardTurnHost:
def __init__(self, controller: Any) -> None:
self.controller = controller
Expand Down Expand Up @@ -1382,7 +1486,7 @@ def run(native_request: Mapping[str, Any], launch_scope: Any) -> dict[str, Any]:
"You may include optional top-level JSON fields alongside the normal kernel fields: "
"`context_handoff` (single object or array <=32 of {goal_id, agent_id, brief} with `schema_version='collaboration_brief_v0'` and `inputs=[]` when referencing URLs/PRs, restricted to `context_delegation.targets`), "
"`steward_owner_report` (optional non-empty Markdown string <=24000 chars or `{markdown}` delivered once directly to the bound Steward App and Feishu conversation; omit or set `null` when silent/no report should be sent), "
"and `steward_user_actions` (array <=16 of {dedupe_key, priority:'P0'|'P1'|'P2', text}; do NOT emit per-PR `steward_user_actions` when the monitor prompt asks for an aggregated report). Set `result_kind='validated_completion'` when triage/handoff/report/user-action preparation is complete.\n"
"and `steward_user_actions` (array <=16 of {dedupe_key, priority:'P0'|'P1'|'P2', text}; do NOT emit per-PR `steward_user_actions` when the monitor prompt asks for an aggregated report). Keep each `work_evidence` and `validation_evidence` item <=200 chars (1-8 items, <=1200 chars total per field). Set `result_kind='validated_completion'` when triage/handoff/report/user-action preparation is complete.\n"
"Steward monitor & dedupe context (data):\n" + json.dumps(followup_ctx, ensure_ascii=False)
)
if request.get("work_kind") == "scheduled_task":
Expand Down Expand Up @@ -1442,6 +1546,7 @@ def launch():
kernel_candidate.pop("context_handoff", None)
kernel_candidate.pop("steward_user_actions", None)
kernel_candidate.pop("steward_owner_report", None)
kernel_candidate = _normalize_steward_advancement_kernel_candidate(kernel_candidate)
if governance_work and kernel_candidate and kernel_candidate.get("result_kind") not in {"replan_required", "wait", "user_action_required", "iteration_failed"}:
kernel_candidate = {"result_kind": "wait", "classification": "report_replan_not_settled",
"next_action": "Retain the original report until its native semantic replan is settled."}
Expand Down
Loading
Loading