Skip to content

Commit cc0ed3e

Browse files
authored
feat: discover repeatable Tasks in their original managed Session (#7669)
1 parent 3b4641c commit cc0ed3e

5 files changed

Lines changed: 167 additions & 8 deletions

File tree

‎docs/product/periodic-reports.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,6 +1020,29 @@ renderer preset; it does not invoke the progress-report source or editorial
10201020
format. Task descriptions, scripts and validation argv cannot be supplied in
10211021
this configuration.
10221022

1023+
Callers can discover eligible references on demand with
1024+
`GET /api/chat/sessions/<original-session-id>/native-turn?calendar_task_sources=true`.
1025+
The `calendar_task_sources` view reads the original Goal's canonical completed
1026+
history, including archived Tasks, and applies the same original Agent and
1027+
independent argv-declaration checks used when configuring execution. It returns
1028+
Task references, display titles, validation digests and archive state, without
1029+
installing commands or copying validators into the configuration. Open work,
1030+
other Agents' work, report generation and generated calendar periods are not
1031+
offered as repeating sources. A missing, changed or unreadable declaration
1032+
fails this read visibly; it is not represented as an empty valid list.
1033+
Ordinary inspection omits this optional catalog. Repeated discovery does not
1034+
configure a subscription, wake an Agent, create a Task, invoke a model, spend
1035+
quota or send a message. Configuration and every due execution still recheck
1036+
the original source; a displayed reference grants no launch authority.
1037+
1038+
调用方可在原会话的 `native-turn` 读取中显式加入
1039+
`calendar_task_sources=true`,发现同一 Agent 可重复执行的已完成 Task,包含已归档项。
1040+
此只读视图复用原生已完成历史和执行入口的验收声明检查;返回原引用、显示标题、
1041+
验收摘要和归档状态,不传入新命令。未完成任务、其它 Agent 的任务、报告生成和
1042+
已生成的日历窗口不会成为候选。声明缺失、变化或不可读时明确失败,不伪装为空列表。
1043+
普通状态读取不加载此目录;重复发现不会启用计划、唤醒 Agent、创建 Task、调用模型、
1044+
扣额或发消息。保存配置和每次到期执行仍重新核验原来源。
1045+
10231046
At the first due boundary, the original idle Chat pump freezes the source
10241047
Task's declaration into the existing cadence attempt. It creates one finite
10251048
native Task for that window, inheriting the source Task's scope, repository,

‎loopx/capabilities/native_chat/session_calendar_tasks.py‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,17 +84,53 @@ def source_task(self, actor, task):
8484
row = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"],
8585
runtime_root_arg=str(self.root), todo_id=task["source_todo_id"], role="agent",
8686
status="done", read_scope="completed_history").get("todo")
87-
if (not row or row.get("status") != "done" or row.get("claimed_by") != actor["agent_id"]
88-
or row.get("task_class") != "advancement_task" or row.get("completion_validation_required") is not True
89-
or row.get("action_kind") == "generate_periodic_report"
90-
or re.fullmatch(r"cadence_[a-f0-9]{64}", row.get("target_key") or "")
91-
or actor["agent_id"] in row.get("excluded_agents", [])):
87+
return row, self._source_validation(actor, row)
88+
89+
@staticmethod
90+
def _source_candidate(actor, row):
91+
return bool(row and row.get("status") == "done" and row.get("claimed_by") == actor["agent_id"]
92+
and row.get("task_class") == "advancement_task" and row.get("completion_validation_required") is True
93+
and row.get("action_kind") != "generate_periodic_report"
94+
and not re.fullmatch(r"cadence_[a-f0-9]{64}", row.get("target_key") or "")
95+
and actor["agent_id"] not in row.get("excluded_agents", []))
96+
97+
def _source_validation(self, actor, row):
98+
if not self._source_candidate(actor, row):
9299
raise ValueError("select this Agent's existing completed Task with independent argv validation")
93100
declaration = read_completion_validation_declaration(runtime_root=self.root,
94101
goal_id=actor["goal_id"], todo_id=row["todo_id"], expected_digest=row["completion_validation_sha256"])
95102
if not declaration or not declaration.get("validation_command_argv"):
96103
raise ValueError("the existing source task has no independent argv validation")
97-
return row, declaration
104+
return declaration
105+
106+
def source_options(self, session_id):
107+
"""Discover references through the same source admission, without enrolling work.
108+
109+
Completed-history reads include active and archived native Tasks. The
110+
canonical owner drains its snapshot pages before projecting this view;
111+
no hot-list limit or private second index determines membership here.
112+
"""
113+
from ...control_plane.todos.list_readback import list_goal_todos
114+
try:
115+
actor = self.selected(session_id)["actor"]
116+
snapshot = list_goal_todos(registry_path=self.controller.registry_path, goal_id=actor["goal_id"],
117+
runtime_root_arg=str(self.root), role="agent", status="done", read_scope="completed_history", limit=None)
118+
sources = []
119+
for row in snapshot["todos"]:
120+
if not self._source_candidate(actor, row):
121+
continue
122+
# An unreadable or changed declaration must fail the read instead
123+
# of turning a source-coverage failure into an empty valid catalog.
124+
validation = self._source_validation(actor, row)
125+
sources.append({"source_todo_id": row["todo_id"], "title": row.get("title") or row["text"],
126+
"completion_validation_sha256": row["completion_validation_sha256"],
127+
"validation_label": validation.get("validation_label"),
128+
"archived": row.get("archive_state") == "archive"})
129+
return {"schema_version": "managed_session_task_sources_v0", "session_id": session_id,
130+
"goal_id": actor["goal_id"], "agent_id": actor["agent_id"], "read_only": True,
131+
"sources": sources, "authority_read": snapshot["authority_read"]}
132+
except OSError as exc:
133+
raise RuntimeError("Original managed Task sources are temporarily unreadable") from exc
98134

99135
def admission(self, request):
100136
actor = request["actor"]

‎loopx/capabilities/native_chat/steward_managed_mode.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None,
290290
"queued_turn_count": len(self.store.queued_turns(actor["session_id"]))})
291291

292292
def inspect(self, session_id: str, *, agent_id: str | None = None,
293-
operation_id: str | None = None) -> dict[str, Any]:
293+
operation_id: str | None = None, include_calendar_task_sources: bool = False) -> dict[str, Any]:
294294
session = self.store.load_session(session_id)
295295
if not session:
296296
raise KeyError("chat session was not found")
@@ -315,6 +315,11 @@ def inspect(self, session_id: str, *, agent_id: str | None = None,
315315
task = SessionCalendarTasks(self.controller).health(session_id)
316316
if task.get("configured"):
317317
result["scheduled_task"] = task
318+
if include_calendar_task_sources:
319+
if agent_id is not None and agent_id != session.get("managed_agent_id"):
320+
raise ValueError("select the original registered Agent for calendar Task sources")
321+
from .session_calendar_tasks import SessionCalendarTasks
322+
result["calendar_task_sources"] = SessionCalendarTasks(self.controller).source_options(session_id)
318323
return result
319324

320325
def submit(self, session_id: str, *, agent_id: str, operation_id: str,

‎loopx/chat_server.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -960,8 +960,15 @@ def _managed_native_turn(self, session_id: str, *, execute: bool = False) -> Non
960960
turn, created = service.submit(session_id, **body)
961961
return self._send_json({"ok": True, "session_id": session_id, "turn": turn, "created": created}, status=202)
962962
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
963+
sources = query.get("calendar_task_sources", ["false"])
964+
if sources not in (["true"], ["false"]):
965+
raise ValueError("calendar_task_sources must be one true or false value")
966+
include_sources = sources == ["true"]
967+
if include_sources and (set(query) - {"calendar_task_sources", "agent_id", "operation_id"}
968+
or any(len(values) != 1 for values in query.values())):
969+
raise ValueError("select one original managed Session and Agent for Task sources")
963970
self._send_json(service.inspect(session_id, agent_id=query.get("agent_id", [None])[0],
964-
operation_id=query.get("operation_id", [None])[0]))
971+
operation_id=query.get("operation_id", [None])[0], include_calendar_task_sources=include_sources))
965972
except KeyError:
966973
self._send_error("chat session was not found", status=404)
967974
except (TypeError, ValueError, RuntimeError) as exc:

‎tests/test_managed_session_calendar_tasks.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,94 @@ def now(cls, tz=None):
140140
return point
141141

142142

143+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
144+
def test_original_session_discovers_repeatable_tasks_without_enrolling_or_replaying(steward, tmp_path, monkeypatch, provider):
145+
from loopx.capabilities.native_chat.steward_managed_mode import ManagedSessionTurn
146+
from loopx.capabilities.native_chat.steward_monitor import StewardMonitor
147+
session, actor, unrelated, capture, _, config = setup_task(steward, tmp_path, monkeypatch, provider)
148+
store, runtime, bot, *_ = steward
149+
sid = session["session_id"]
150+
fixed_clock(monkeypatch)
151+
calls, history, writes = capture.read_bytes(), store.messages(sid), list(bot.writes)
152+
before = load_goal_from_registry(runtime.registry_path, actor["goal_id"])
153+
with settings_server(steward) as request:
154+
url = f"/api/chat/sessions/{sid}/native-turn"
155+
status, plain = request(url, None, method="GET")
156+
assert status == 200 and "calendar_task_sources" not in plain
157+
status, view = request(url + "?calendar_task_sources=true", None, method="GET")
158+
assert status == 200, view
159+
options = view["calendar_task_sources"]
160+
assert options["session_id"] == sid and options["goal_id"] == actor["goal_id"]
161+
assert options["agent_id"] == actor["agent_id"] and options["read_only"]
162+
assert options["authority_read"]["source_authority"] == ("file_v0" if provider == "file" else "sqlite_v0")
163+
assert [row["source_todo_id"] for row in options["sources"]] == [config["task"]["source_todo_id"]]
164+
chosen = options["sources"][0]
165+
assert chosen["title"] and len(chosen["completion_validation_sha256"]) == 64
166+
assert not chosen["archived"] and "validation_command_argv" not in json.dumps(options)
167+
for selector in ("yes", "true&calendar_task_sources=false", f"true&agent_id={actor['agent_id']}-other",
168+
f"true&agent_id={actor['agent_id']}&agent_id=other", "true&goal_id=other"):
169+
status, rejected = request(url + "?calendar_task_sources=" + selector, None, method="GET")
170+
assert status == 409 and rejected["ok"] is False
171+
# Discovery is opt-in and has not changed the original Goal, Task,
172+
# model calls, original messages, or private provider delivery.
173+
assert load_goal_from_registry(runtime.registry_path, actor["goal_id"]) == before
174+
assert capture.read_bytes() == calls and store.messages(sid) == history and bot.writes == writes
175+
assert read_cadence_journal(runtime_root=runtime.coordination_runtime_root, goal_id=actor["goal_id"]) is None
176+
apply_configuration(request, actor["goal_id"], {**config, "task": {"source_todo_id": chosen["source_todo_id"]}})
177+
completed = finish(runtime, pump_steward_monitors(runtime)[0])
178+
assert completed["response"]["native_loopx"]["status"] == "committed"
179+
# A completed generated period cannot become another repeating source.
180+
assert [row["source_todo_id"] for row in ManagedSessionTurn(runtime).inspect(
181+
sid, include_calendar_task_sources=True)["calendar_task_sources"]["sources"]] == [chosen["source_todo_id"]]
182+
cli(runtime, "todo", "archive-completed", "--goal-id", actor["goal_id"], "--role", "agent",
183+
"--max-active-done", "0", "--execute")
184+
calls = capture.read_bytes()
185+
status, archived = request(url + "?calendar_task_sources=true", None, method="GET")
186+
assert status == 200, archived
187+
assert archived["calendar_task_sources"]["sources"] == [{**chosen, "archived": True}]
188+
assert archived["scheduled_task"]["completion_verified"] and capture.read_bytes() == calls
189+
assert next(row for row in StewardMonitor(runtime).todos(actor) if row["todo_id"] == unrelated)["status"] == "open"
190+
191+
192+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
193+
@pytest.mark.parametrize("fault", ["malformed", "directory"])
194+
def test_calendar_task_discovery_retains_unreadable_validator_and_recovers_without_work(steward, tmp_path, monkeypatch, provider, fault):
195+
from loopx.control_plane.todos.completion_validation_store import completion_validation_declaration_path
196+
session, actor, _, capture, _, config = setup_task(steward, tmp_path, monkeypatch, provider)
197+
store, runtime, bot, *_ = steward
198+
service = SessionCalendarTasks(runtime)
199+
options = service.source_options(session["session_id"])
200+
source = options["sources"][0]
201+
path = completion_validation_declaration_path(runtime_root=runtime.coordination_runtime_root,
202+
goal_id=actor["goal_id"], todo_id=source["source_todo_id"]).parent / "blobs" / (source["completion_validation_sha256"] + ".json")
203+
original = path.read_bytes()
204+
calls, history, writes = capture.read_bytes(), store.messages(session["session_id"]), list(bot.writes)
205+
path.unlink()
206+
if fault == "directory":
207+
path.mkdir()
208+
else:
209+
path.write_text("{}")
210+
try:
211+
with settings_server(steward) as request:
212+
url = f"/api/chat/sessions/{session['session_id']}/native-turn?calendar_task_sources=true"
213+
status, failed = request(url, None, method="GET")
214+
assert status == 409 and failed["error_code"] == "managed_turn_unavailable", failed
215+
assert "calendar_task_sources" not in failed
216+
with pytest.raises(OSError if fault == "directory" else ValueError):
217+
service.source_task(actor, config["task"])
218+
if path.is_dir():
219+
path.rmdir()
220+
path.write_bytes(original)
221+
status, recovered = request(url, None, method="GET")
222+
assert status == 200 and recovered["calendar_task_sources"]["sources"] == options["sources"]
223+
finally:
224+
if path.is_dir():
225+
path.rmdir()
226+
path.write_bytes(original)
227+
assert capture.read_bytes() == calls and store.messages(session["session_id"]) == history and bot.writes == writes
228+
assert read_cadence_journal(runtime_root=runtime.coordination_runtime_root, goal_id=actor["goal_id"]) is None
229+
230+
143231
@pytest.mark.parametrize("provider", ["file", "sqlite"])
144232
def test_calendar_preserves_canonical_decision_scopes_through_original_return(steward, tmp_path, monkeypatch, provider):
145233
from loopx.control_plane.todos.contract import normalize_todo_required_decision_scopes

0 commit comments

Comments
 (0)