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
105 changes: 91 additions & 14 deletions loopx/capabilities/native_chat/steward_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
import json
import logging
from pathlib import Path
import re
import subprocess
import time
from typing import Any
from typing import Any, Mapping

from ...agent_registry import load_goal_from_registry
from ...chat_store import _atomic_write_json
from ...control_plane.effect_runtime import effect_runtime_result
from ...control_plane.scheduler.monitor_todo import monitor_todo_is_due
from ...control_plane.todos.list_readback import list_goal_todos
from ...control_plane.runtime.time import now_utc
Expand Down Expand Up @@ -82,10 +84,64 @@ def _observe_github_repository_prs(repo_slug: str) -> dict[str, Any]:
return observe_github_repository_prs(repo_slug, runner=subprocess.run)


_MONITOR_TARGET_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$")


def steward_monitor_snapshot_path(runtime_root: Path, goal_id: str, todo_id: str) -> Path:
return Path(runtime_root).expanduser().resolve() / "steward-monitors" / goal_id / f"{todo_id}.latest.json"


def steward_monitor_scope_path(runtime_root: Path, goal_id: str, target_key: str) -> Path:
safe_goal = str(goal_id or "").strip()
safe_key = str(target_key or "").strip()
if not safe_goal or "/" in safe_goal or "\\" in safe_goal or ".." in safe_goal:
raise ValueError("invalid monitor scope goal_id")
if not _MONITOR_TARGET_KEY_RE.fullmatch(safe_key):
raise ValueError("invalid monitor scope target_key")
return Path(runtime_root).expanduser().resolve() / "steward-monitors" / safe_goal / "scopes" / f"{safe_key}.json"


def steward_monitor_delivery_dir(runtime_root: Path, goal_id: str) -> Path:
safe_goal = str(goal_id or "").strip()
if not safe_goal or "/" in safe_goal or "\\" in safe_goal or ".." in safe_goal:
raise ValueError("invalid monitor delivery goal_id")
return Path(runtime_root).expanduser().resolve() / "steward-monitors" / safe_goal / "deliveries"


def normalize_steward_monitor_scope(signal_scope: Mapping[str, Any] | None) -> dict[str, Any] | None:
if signal_scope is None:
return None
normalized = effect_runtime_result(
"collaboration.steward.monitor.signal_scope.normalize",
{"signal_scope": dict(signal_scope)},
).get("signal_scope")
return dict(normalized) if isinstance(normalized, Mapping) else None


def write_steward_monitor_scope(
runtime_root: Path, goal_id: str, target_key: str, signal_scope: Mapping[str, Any],
) -> dict[str, Any]:
normalized = normalize_steward_monitor_scope(signal_scope)
if normalized is None:
raise ValueError("signal_scope cannot be empty")
path = steward_monitor_scope_path(runtime_root, goal_id, target_key)
path.parent.mkdir(parents=True, exist_ok=True)
_atomic_write_json(path, normalized)
return normalized


def read_steward_monitor_scope(runtime_root: Path, goal_id: str, target_key: str) -> dict[str, Any] | None:
if not target_key or not _MONITOR_TARGET_KEY_RE.fullmatch(str(target_key)):
return None
path = steward_monitor_scope_path(runtime_root, goal_id, target_key)
if not path.is_file():
return None
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, Mapping):
raise ValueError("invalid persisted steward monitor scope")
return normalize_steward_monitor_scope(raw)


class StewardMonitor:
def __init__(self, controller: Any) -> None:
self.controller = controller
Expand Down Expand Up @@ -298,27 +354,47 @@ def configure(self, binding_id: str, *, operation: str, cadence_minutes: int = 3
"monitor": self.current(actor), "model_invoked": False}

def _collect_signal_monitor(self, actor: dict[str, Any], context: dict[str, Any], todo: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
portfolio = self.bindings._core("collaboration.steward.monitor.observation", {
"context": context, "goal_ids": self.bindings.steward_scope(self.controller.store.load_session(actor["session_id"])),
"actor_goal_id": actor["goal_id"], "previous_hash": None})
target_key = str(todo.get("target_key") or "")
signal_scope = read_steward_monitor_scope(
self.controller.coordination_runtime_root, actor["goal_id"], target_key,
)
include_portfolio = True if signal_scope is None else signal_scope.get("include_portfolio", True) is True
include_inbox = True if signal_scope is None else signal_scope.get("include_inbox", True) is True
portfolio = (
self.bindings._core("collaboration.steward.monitor.observation", {
"context": context, "goal_ids": self.bindings.steward_scope(self.controller.store.load_session(actor["session_id"])),
"actor_goal_id": actor["goal_id"], "previous_hash": None})
if include_portfolio else None
)
from ...control_plane.collaboration.inbox import pending as inbox_pending
try:
inbox_raw = inbox_pending(self.controller.coordination_runtime_root,
goal_id=actor["goal_id"], agent_id=actor["agent_id"])
inbox_items = [{"request_id": row["request_id"], "source_id": row.get("source_id")}
for row in inbox_raw if isinstance(row, dict) and row.get("request_id")]
except (OSError, ValueError):
if include_inbox:
try:
inbox_raw = inbox_pending(self.controller.coordination_runtime_root,
goal_id=actor["goal_id"], agent_id=actor["agent_id"])
inbox_items = [{"request_id": row["request_id"], "source_id": row.get("source_id")}
for row in inbox_raw if isinstance(row, dict) and row.get("request_id")]
except (OSError, ValueError):
inbox_items = []
else:
inbox_items = []
repo_slug = _github_repo_slug(todo.get("task_repository"))
repo_snapshot = _observe_github_repository_prs(repo_slug) if repo_slug else None
observation = self.bindings._core("collaboration.steward.monitor.signal_observation", {
observed_at = now_utc().isoformat()
signal_request: dict[str, Any] = {
"portfolio_observation": portfolio,
"inbox_items": inbox_items,
"repository_snapshot": repo_snapshot,
"previous_hash": todo.get("result_hash"),
})
}
if signal_scope is not None:
signal_request["signal_scope"] = signal_scope
signal_request["observed_at"] = observed_at
observation = self.bindings._core("collaboration.steward.monitor.signal_observation", signal_request)
if observation.get("observation_incomplete") is True:
raise RuntimeError("steward monitor external signal source temporarily unavailable")
persisted_repo_snapshot = repo_snapshot
if isinstance(repo_snapshot, Mapping) and "scoped_repository_items" in observation:
persisted_repo_snapshot = {**repo_snapshot, "items": list(observation["scoped_repository_items"])}
snapshot_path = steward_monitor_snapshot_path(
self.controller.coordination_runtime_root, actor["goal_id"], todo["todo_id"])
snapshot_path.parent.mkdir(parents=True, exist_ok=True)
Expand All @@ -329,10 +405,11 @@ def _collect_signal_monitor(self, actor: dict[str, Any], context: dict[str, Any]
"target_key": todo.get("target_key"),
"monitor_text": todo.get("text"),
"task_repository": todo.get("task_repository"),
**({"signal_scope": signal_scope} if signal_scope is not None else {}),
"result_hash": observation["result_hash"],
"material_change": observation["material_change"],
"observed_at": now_utc().isoformat(),
"repository_snapshot": repo_snapshot,
"observed_at": observed_at,
"repository_snapshot": persisted_repo_snapshot,
"inbox_items": inbox_items,
})
followup_key = f"{FOLLOWUP_TARGET_PREFIX}{todo['todo_id']}"
Expand Down
41 changes: 37 additions & 4 deletions loopx/capabilities/native_chat/steward_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -1130,7 +1130,7 @@ def _steward_followup_context(self, actor: Mapping[str, Any], session_id: str,
@staticmethod
def _normalize_steward_actions(candidate: Mapping[str, Any], context: Mapping[str, Any]) -> dict[str, Any]:
from ...control_plane.collaboration.inbox import normalize_handoff
state: dict[str, Any] = {"context_handoff": None, "user_actions": [], "validation_error": None}
state: dict[str, Any] = {"context_handoff": None, "user_actions": [], "owner_report": None, "validation_error": None}
allowed_targets = {
(row["goal_id"], row["agent_id"])
for row in ((context.get("context_delegation") or {}).get("targets") or [])
Expand Down Expand Up @@ -1171,6 +1171,17 @@ def _normalize_steward_actions(candidate: Mapping[str, Any], context: Mapping[st
seen_keys.add(key)
cleaned.append({"dedupe_key": key, "priority": prio, "text": text})
state["user_actions"] = cleaned
raw_report = candidate.get("steward_owner_report")
if raw_report is not None:
markdown = raw_report.get("markdown") if isinstance(raw_report, Mapping) else raw_report
if not isinstance(markdown, str):
state["validation_error"] = "steward_owner_report must be a markdown string or {markdown}"
return state
normalized_report = markdown.strip()
if not normalized_report or len(normalized_report) > 24000:
state["validation_error"] = "steward_owner_report markdown must be 1..24000 characters"
return state
state["owner_report"] = normalized_report
return state

def _apply_steward_user_actions(self, actor: Mapping[str, Any], actions: Sequence[Mapping[str, str]],
Expand Down Expand Up @@ -1269,7 +1280,7 @@ def execute(self, *, session_id: str, turn_id: str, adapter: Any,
managed_answer = ""
managed_lease, managed_lease_request = None, None
preparation_status = None
steward_actions_state: dict[str, Any] = {"context_handoff": None, "user_actions": [], "validation_error": None}
steward_actions_state: dict[str, Any] = {"context_handoff": None, "user_actions": [], "owner_report": None, "validation_error": None}

def report_lease_proof():
return self._task_lease_proof(request, report_lease)
Expand Down Expand Up @@ -1370,7 +1381,8 @@ def run(native_request: Mapping[str, Any], launch_scope: Any) -> dict[str, Any]:
"When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. "
"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`), "
"and `steward_user_actions` (array <=16 of {dedupe_key, priority:'P0'|'P1'|'P2', text}). Set `result_kind='validated_completion'` when triage/handoff/user-action preparation is complete.\n"
"`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"
"Steward monitor & dedupe context (data):\n" + json.dumps(followup_ctx, ensure_ascii=False)
)
if request.get("work_kind") == "scheduled_task":
Expand Down Expand Up @@ -1429,6 +1441,7 @@ def launch():
steward_actions_state.update(self._normalize_steward_actions(kernel_candidate, context))
kernel_candidate.pop("context_handoff", None)
kernel_candidate.pop("steward_user_actions", None)
kernel_candidate.pop("steward_owner_report", None)
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 Expand Up @@ -1587,13 +1600,33 @@ def steward_validator(_plan: Mapping[str, Any], candidate_result: Mapping[str, A
observed=observed, selection_recovery=selection_recovery)
user_action_receipts = self._apply_steward_user_actions(
actor, steward_actions_state["user_actions"], request["turn_instance_id"])
owner_report = (steward_actions_state["owner_report"]
if steward_advancement and result.get("status") == "committed" else None)
if owner_report:
from ...registry import atomic_write_json
from .steward_monitor import steward_monitor_delivery_dir
delivery_path = steward_monitor_delivery_dir(self.controller.coordination_runtime_root, actor["goal_id"]) / f"{turn_id}.json"
atomic_write_json(delivery_path, {
"schema_version": "steward_monitor_report_delivery_v0",
"goal_id": actor["goal_id"],
"agent_id": actor["agent_id"],
"session_id": actor["session_id"],
"turn_id": turn_id,
"turn_instance_id": request["turn_instance_id"],
"todo_id": (managed_lease_request or request).get("todo_id"),
"markdown": owner_report,
"created_at": datetime.now(timezone.utc).isoformat(),
"delivery_status": "pending",
"deliveries": {},
})
committed_handoff = (steward_actions_state["context_handoff"]
if steward_advancement and result.get("status") == "committed" else None)
return {"schema_version": "loopx_chat_agent_response_v0", "message":
"当前没有可执行且已配置独立验收的原生任务,尚未启动模型;请检查原任务的验收配置。" if managed_turn and managed_turn.validation_unavailable else
(managed_answer or "本轮任务已完成结果回写。") if result.get("status") == "committed" else
(owner_report or managed_answer or "本轮任务已完成结果回写。") if result.get("status") == "committed" else
"本轮等待后续执行条件。" if result.get("status") == "stopped" and result.get("result_kind") == "wait" else
"本轮任务尚未完成;执行状态已保留。",
"proposals": [], "gate": None, "native_loopx": result,
**({"context_handoff": committed_handoff} if committed_handoff else {}),
**({"steward_owner_report_queued": True} if owner_report else {}),
**({"steward_user_action_receipts": user_action_receipts} if user_action_receipts else {})}
8 changes: 8 additions & 0 deletions loopx/chat/monitor_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ def _run_monitor_update(
monitor_metadata=base_metadata,
)
result = update_goal_todo(**kwargs)
if not dry_run and parameters.get("signal_scope") is not None:
from ..capabilities.native_chat.steward_monitor import write_steward_monitor_scope
target_key = str(
parameters.get("target_key") or (result.get("todo") or {}).get("target_key") or ""
).strip()
if not target_key:
raise ValueError("signal_scope update requires target_key")
write_steward_monitor_scope(source.runtime_root, goal_id, target_key, parameters["signal_scope"])
return result

def _apply_monitor_update(
Expand Down
14 changes: 13 additions & 1 deletion loopx/chat_action_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,7 @@ def _normalize(
),
}
if action_kind == "monitor.create":
from .capabilities.native_chat.steward_monitor import normalize_steward_monitor_scope
values = self._allowed_parameters(
parameters,
allowed={
Expand All @@ -773,6 +774,7 @@ def _normalize(
"timezone",
"stop_condition",
"notification_rule",
"signal_scope",
},
)
goal_id = _opaque(values.get("goal_id"), field="goal_id")
Expand All @@ -785,6 +787,10 @@ def _normalize(
"cadence": _normalize_cadence(values.get("cadence")),
"timezone": _text(values.get("timezone"), field="timezone", limit=80),
}
if values.get("signal_scope") is not None:
if not isinstance(values["signal_scope"], Mapping):
raise ValueError("signal_scope must be an object")
result["signal_scope"] = normalize_steward_monitor_scope(values["signal_scope"])
if values.get("task_repository"):
raw_repo = _text(values["task_repository"], field="task_repository", limit=200)
if _REPO_PATTERN.fullmatch(raw_repo):
Expand All @@ -805,6 +811,7 @@ def _normalize(
)
return result
if action_kind == "monitor.update":
from .capabilities.native_chat.steward_monitor import normalize_steward_monitor_scope
values = self._allowed_parameters(
parameters,
allowed={
Expand All @@ -819,6 +826,7 @@ def _normalize(
"stop_condition",
"session_id",
"endpoint_id",
"signal_scope",
},
)
goal_id = _opaque(values.get("goal_id"), field="goal_id")
Expand All @@ -834,6 +842,10 @@ def _normalize(
"agent_id": _opaque(values.get("agent_id"), field="agent_id"),
"operation": operation,
}
if values.get("signal_scope") is not None:
if not isinstance(values["signal_scope"], Mapping):
raise ValueError("signal_scope must be an object")
result["signal_scope"] = normalize_steward_monitor_scope(values["signal_scope"])
if values.get("endpoint_id"):
endpoint_id = _opaque(values["endpoint_id"], field="endpoint_id")
result["endpoint_id"] = endpoint_id
Expand Down Expand Up @@ -863,7 +875,7 @@ def _normalize(
result["session_id"] = _opaque(values["session_id"], field="session_id")
if operation == "edit" and len(result) == 4:
raise ValueError(
"monitor edit requires target, target_key, cadence, or stop_condition"
"monitor edit requires target, target_key, cadence, stop_condition, or signal_scope"
)
return result
if action_kind == "pr.merge":
Expand Down
6 changes: 6 additions & 0 deletions loopx/chat_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,12 @@ def _apply_monitor_create(
}), receipt={})
return {"proposal": stale, "turn": None}
todo_id = _opaque(result.get("todo_id"), field="todo_id")
if parameters.get("signal_scope") is not None:
from .capabilities.native_chat.steward_monitor import write_steward_monitor_scope
target_key = str(parameters.get("target_key") or "").strip()
if not target_key:
raise ValueError("signal_scope requires target_key")
write_steward_monitor_scope(source.runtime_root, goal_id, target_key, parameters["signal_scope"])
receipt = {
"receipt_id": _digest(
{"proposal_id": proposal_id, "goal_id": goal_id, "todo_id": todo_id}
Expand Down
Loading
Loading