Skip to content
Open
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
3 changes: 3 additions & 0 deletions docs/guides/personal-workspace-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,7 @@ URL 的 `todo` 参数支持刷新与返回恢复检查上下文。来源中已
「添加任务」就在当前工作区域:输入一次,检查后确认一次,创建结果通过刷新读回。
检查或应用失败时保留草稿,可从原有动作流程重新检查和确认;选择视图不会执行任务。
右侧「全部工作」可按状态筛选并搜索已载入的任务;完成记录沿用既有分页与虚拟化历史。
完成记录和 Goal 成果按完成时刻从新到旧排序,缺少可读时间的记录排在有时间的记录之后。
「活动」显示时间线中已结束的执行、已返回成果和已记录决定,覆盖范围取决于来源。

The Overview composes Direction, Needs you, Now and Results. Now groups work by its recorded owner,
Expand All @@ -513,6 +514,8 @@ retaining stale action authority. Add task uses one input and the existing previ
a failed preview or apply retains the draft. All work filters/searches listed tasks and reuses paginated,
virtualized completed history. Activity shows ended runs, returned results and recorded decisions from
the available timeline; it makes no complete-history claim.
Completed history and Goal results show the newest completion first. Records without a readable
completion time appear after dated records.

工作指标保持明确的覆盖范围:
工作指标只有在来源提供完成数、且未完成列表覆盖已知时显示“完成 / 总数”。
Expand Down
14 changes: 12 additions & 2 deletions loopx/chat/completed_todos.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
short-lived and server-local, never a second source of Todo authority.
"""
from collections import OrderedDict
from collections.abc import Mapping
from datetime import datetime
import json
from secrets import token_urlsafe
from threading import Lock
Expand All @@ -12,10 +14,18 @@

from ..paths import resolve_runtime_root
from ..capabilities.native_chat.project_context import coordination_runtime_root
from ..control_plane.runtime.time import chronology_key
from ..status_server import is_loopback_host
from ..presentation.report_reviews_api import ReportReviewsRequestMixin


def _completion_order(entry: tuple[int, Mapping[str, object]]) -> tuple[int, datetime, str, int]:
index, todo = entry
valid, timestamp, raw = chronology_key(todo.get("completed_at"))
# Equal instants use the source position even when their wire strings differ.
return valid, timestamp, "" if valid else raw, index


def _goal_result_candidates(*, runtime_root, goal_id):
"""Snapshot bounded metadata; exact acceptance is checked per requested page."""
from ..control_plane.coordination.local_authority import read_canonical_todos_if_promoted
Expand All @@ -26,7 +36,7 @@ def _goal_result_candidates(*, runtime_root, goal_id):
candidates = sorted(
((index, item) for index, item in enumerate(payload["todos"])
if item.get("role") == "agent" and item.get("status") == "done"),
key=lambda pair: (str(pair[1].get("completed_at") or ""), pair[0]),
key=_completion_order,
reverse=True,
)
return [
Expand Down Expand Up @@ -79,7 +89,7 @@ def _verify_goal_result_page(*, page, registry_path, runtime_root, goal_id):

def completed_todo_rows(payload, *, agent_id="", search=""):
"""Existing display projection shared by local and linked native reads."""
ordered = sorted(enumerate(payload["todos"]), key=lambda pair: (str(pair[1].get("completed_at") or ""), pair[0]), reverse=True)
ordered = sorted(enumerate(payload["todos"]), key=_completion_order, reverse=True)
return [
{
"todo_id": item["todo_id"],
Expand Down
63 changes: 63 additions & 0 deletions regression/ChatCompletionChronology.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Std

/-
Run with Lean 4.22.0 using
`lean -DwarningAsError=true regression/ChatCompletionChronology.lean`.

`instant` is the parsed UTC microsecond. The model uses the relative lexical
rank of unreadable timestamps. It mirrors the two Chat history sort keys in
`completed_todos.py`. The Python HTTP tests exercise parsing, live accepted
result verification and snapshot cursors on File and SQLite.
-/

namespace ChatCompletionChronology

structure Row where
instant : Option Int
rawRank : Nat
position : Nat

def beforeOrAt (left right : Row) : Bool :=
match left.instant, right.instant with
| some a, some b => decide (b < a ∨ (a = b ∧ right.position ≤ left.position))
| some _, none => true
| none, some _ => false
| none, none =>
decide (right.rawRank < left.rawRank ∨
(left.rawRank = right.rawRank ∧ right.position ≤ left.position))

def historyOrder (rows : List Row) : List Row :=
rows.mergeSort beforeOrAt

theorem history_is_ordered (rows : List Row) :
(historyOrder rows).Pairwise (fun a b => beforeOrAt a b = true) := by
apply List.sorted_mergeSort
· rintro ⟨a, ar, ap⟩ ⟨b, br, bp⟩ ⟨c, cr, cp⟩ hab hbc
cases a <;> cases b <;> cases c <;> simp [beforeOrAt] at * <;> omega
· rintro ⟨a, ar, ap⟩ ⟨b, br, bp⟩
cases a <;> cases b <;> simp [beforeOrAt, Bool.or_eq_true] <;> omega

theorem all_records_are_retained (rows : List Row) : (historyOrder rows).Perm rows :=
List.mergeSort_perm rows beforeOrAt

theorem equal_instants_use_source_position (instant : Int)
(leftRank rightRank leftPosition rightPosition : Nat) :
beforeOrAt ⟨some instant, leftRank, leftPosition⟩ ⟨some instant, rightRank, rightPosition⟩ =
decide (rightPosition ≤ leftPosition) := by
simp [beforeOrAt]

theorem snapshot_pages_preserve_the_order (rows : List Row) (size : Nat) :
(historyOrder rows).take size ++ (historyOrder rows).drop size = historyOrder rows :=
List.take_append_drop size (historyOrder rows)

theorem old_lexical_order_can_put_a_whole_second_first :
"2026-02-03T10:00:00Z" > "2026-02-03T10:00:00.000001Z" ∧
beforeOrAt ⟨some 1, 0, 0⟩ ⟨some 0, 1, 1⟩ = true := by decide

#print axioms history_is_ordered
#print axioms all_records_are_retained
#print axioms equal_instants_use_source_position
#print axioms snapshot_pages_preserve_the_order
#print axioms old_lexical_order_can_put_a_whole_second_first

end ChatCompletionChronology
156 changes: 155 additions & 1 deletion tests/test_chat_completed_todos.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@

import pytest

from loopx.chat.completed_todos import CompletedTodoPages, _verify_goal_result_page
from loopx.chat.completed_todos import (
CompletedTodoPages,
_verify_goal_result_page,
completed_todo_rows,
)
from loopx.chat_server import ChatHTTPServer, ChatRequestHandler
from loopx.control_plane.todos.contract import encode_metadata_value

Expand All @@ -19,6 +23,25 @@ def test_history_uses_the_same_readback_owner_through_the_compatibility_facade()
assert facade is readback


def test_completed_history_keeps_unknown_timestamp_fallbacks_after_dated_rows():
timestamps = [
("todo_missing", None),
("todo_opaque_a", "legacy-a"),
("todo_earliest", "0001-01-01T00:00:00Z"),
("todo_opaque_b", "legacy-b"),
]
rows = [
{"todo_id": todo_id, "completed_at": stamp, "done": True, "status": "done"}
for todo_id, stamp in timestamps
]

ordered = completed_todo_rows({"todos": rows})

assert [row["todo_id"] for row in ordered] == [
"todo_earliest", "todo_opaque_b", "todo_opaque_a", "todo_missing",
]


def test_snapshot_pagination_is_bounded_and_stable():
pages = CompletedTodoPages()
rows = [{"todo_id": f"todo_{index}"} for index in range(4087)]
Expand Down Expand Up @@ -180,6 +203,137 @@ def read(**kwargs):
assert [row["todo_id"] for row in verified["items"]] == ["todo_report_planned"]


@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_chat_history_routes_sort_mixed_timestamps_and_keep_frozen_pages(
tmp_path, monkeypatch, provider
):
from pathlib import Path
import subprocess
import sys
from urllib.parse import urlencode

from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted
from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection
from loopx.control_plane.goals.acceptance import configure_goal_acceptance, inspect_goal_acceptance
from loopx.control_plane.testing.canary_harness import write_fixture_registry
from loopx.control_plane.todos.mutation_api import complete_goal_todo
from tests.control_plane.canonical_authority_fixture import (
advance_canonical_fixture_authority, initialize_canonical_authority, isolate_sqlite_runtime,
)

isolate_sqlite_runtime(tmp_path, monkeypatch)
goal_id, agent_id = "history-goal", "agent-a"
project, runtime, registry = tmp_path / "project", tmp_path / "runtime", tmp_path / "registry.json"
project.mkdir()
state = project / "state.md"
state.write_text("# Synthetic history\n\n## Agent Todo\n\n## User Todo\n", encoding="utf-8")
write_fixture_registry(
project=project, runtime_root=runtime, registry_path=registry, goal_id=goal_id,
domain="acceptance", adapter_kind="generic_project_goal_v0", state_file=str(state),
registered_agents=[agent_id],
)
stamps = {
"todo_whole": "2026-02-03T10:00:00Z",
"todo_later": "2026-02-03T10:00:00.000001Z",
"todo_offset_tie": "2026-02-03T18:00:00+08:00",
}
todo_ids = [*stamps, "todo_new"]
todos = [
{"schema_version": "todo_item_v0", "todo_id": todo_id, "role": "agent",
"text": f"Synthetic result {index}", "status": "open", "done": False,
"task_class": "advancement_task", "action_kind": "implement", "index": index + 1,
"source_section": "Agent Todo", "archive_state": "active", "claimed_by": agent_id}
for index, todo_id in enumerate(todo_ids)
]

def projection(rows):
return build_todo_runtime_shadow_projection(goal_id=goal_id, todos=rows, handoff_mode="soft_claim")

initialize_canonical_authority(runtime, goal_id, projection(todos), state_path=state, provider=provider)
acceptance_route = dict(registry_path=registry, goal_id=goal_id, runtime_root=str(runtime))
configured = configure_goal_acceptance(
**acceptance_route,
expected_provider_revision=inspect_goal_acceptance(**acceptance_route)["provider_revision"],
document={
"scope": {"kind": "all_advancement"}, "objective": "Write accepted synthetic results",
"non_goals": [],
"criteria": [{"id": "result", "description": "The local result matches the fixture",
"validation_argv": [sys.executable, "-c",
"from pathlib import Path; assert Path('completion.md').read_text() == '# Synthetic result\\n'"],
"validation_timeout_seconds": 5}],
"bindings": [{"todo_id": todo_id, "criterion_ids": ["result"]} for todo_id in todo_ids],
}, execute=True,
)
assert configured["status"] == "applied", configured
result_file = project / "completion.md"
result_file.write_text("# Synthetic result\n", encoding="utf-8")

def complete(todo_id, stamp):
with monkeypatch.context() as clock:
clock.setattr("loopx.control_plane.todos.provider_terminal_lifecycle.now_local", lambda: stamp)
result = complete_goal_todo(
registry_path=registry, goal_id=goal_id, todo_id=todo_id, agent_id=agent_id,
runtime_root_arg=str(runtime), evidence="Validated synthetic result",
completion_result_file=result_file, completion_validation_workspace_path=project,
)
assert result["ok"], result

for todo_id, stamp in stamps.items():
complete(todo_id, stamp)

# Retain the real accepted artifacts and inject only historical timestamp encodings.
provider_module = Path(__file__).resolve().parents[1] / "loopx/control_plane/coordination/local_authority_provider.ts"
retained = json.loads(subprocess.check_output(
["node", "--no-warnings", "--experimental-strip-types", "--input-type=module", "-e",
"const [module, root, goal] = process.argv.slice(1);"
"const {openLocalAuthorityStore} = await import(module);"
"const loaded = await (await openLocalAuthorityStore(root, goal)).loadAuthority();"
"if (loaded.status !== 'loaded') throw new Error(loaded.status);"
"process.stdout.write(JSON.stringify(loaded.head));",
provider_module.as_uri(), str(runtime), goal_id],
text=True, timeout=30,
))
for row in retained["todos"]:
if row["todo_id"] in stamps:
row["completed_at"] = stamps[row["todo_id"]]
retained["todo_read_model"] = projection(retained["todos"])["todo_read_model"]
advance_canonical_fixture_authority(runtime, goal_id, retained, operation_id="fixture:mixed-completion-times")
before = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id)

server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler)
server.registry_path, server.runtime_root_override, server.verbose = registry, runtime, False
server.completed_todo_pages.page_size = 2
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
def read(route, cursor=""):
query = urlencode({"goal_id": goal_id, "cursor": cursor})
with urlopen(f"http://127.0.0.1:{server.server_port}/api/chat/{route}?{query}", timeout=20) as response:
return json.load(response)

first = {route: read(route) for route in ("completed-todos", "goal-results")}
after = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id)
assert after == before
complete("todo_new", "2026-02-03T11:00:00Z")
for route, page in first.items():
assert page["total"] == 3 and page["next_cursor"]
assert [row["todo_id"] for row in page["items"]] == ["todo_later", "todo_whole"], route
second = read(route, page["next_cursor"])
assert second["total"] == 3 and second["next_cursor"] is None
assert [row["todo_id"] for row in second["items"]] == ["todo_offset_tie"], route
for row in page["items"] + second["items"]:
assert row["completed_at"] == stamps[row["todo_id"]]
fresh = read(route)
assert fresh["total"] == 4
assert [row["todo_id"] for row in fresh["items"]] == ["todo_new", "todo_later"], route
if route == "goal-results":
assert page["unavailable_count"] == second["unavailable_count"] == fresh["unavailable_count"] == 0
finally:
server.shutdown()
server.server_close()
worker.join()


@pytest.mark.parametrize("count", [85, 4087])
@pytest.mark.parametrize("archived", [False, True])
def test_http_history_reads_full_retained_content_without_writes(tmp_path, count, archived):
Expand Down
Loading