From e2b3f85421b27c99e928a7adee778f70f955f668 Mon Sep 17 00:00:00 2001 From: hajicheng Date: Mon, 23 Nov 2026 14:58:07 +0800 Subject: [PATCH] feat(task-continuity): add latest-first history search (#8506) * feat(task-continuity): add latest-first history search * fix(task-continuity): order recaptured history by checkpoint Archive rows retain their original IDs when a batch is recaptured. Use the current checkpoint to rank reachable batches and retain row order within each batch. --------- Co-authored-by: hajicheng <200940025+hajicheng@users.noreply.github.com> --- .../agents/task_continuity/archive.py | 42 ++++++---- .../deerflow/agents/task_continuity/tools.py | 11 ++- backend/tests/test_task_continuity.py | 81 ++++++++++++++++++- docs/guide/context.md | 5 ++ docs/task-continuity.md | 11 +++ 5 files changed, 130 insertions(+), 20 deletions(-) diff --git a/backend/packages/harness/deerflow/agents/task_continuity/archive.py b/backend/packages/harness/deerflow/agents/task_continuity/archive.py index 8ffd5e0364..9266ab10c2 100644 --- a/backend/packages/harness/deerflow/agents/task_continuity/archive.py +++ b/backend/packages/harness/deerflow/agents/task_continuity/archive.py @@ -195,7 +195,7 @@ async def acapture(*args) -> dict: raise -def lookup(state: dict, runtime, *, query: str | None = None, source_id: str | None = None, role: str | None = None, excerpts: bool = False) -> dict: +def lookup(state: dict, runtime, *, query: str | None = None, source_id: str | None = None, role: str | None = None, excerpts: bool = False, latest_first: bool = False) -> dict: path, owner = scope(runtime) batches = reachable(state, owner) active = records(state.get("messages", []), 64000) @@ -209,6 +209,8 @@ def lookup(state: dict, runtime, *, query: str | None = None, source_id: str | N for row in active: if (source_id and row["id"] == source_id) or (query is not None and (role is None or row["role"] == role) and any(t in row["text"].casefold() for t in keywords)): active_matches.append(row) + latest_active = {row["id"]: row for row in reversed(active_matches)} if latest_first else {} + archive_limit = max(0, 8 - len(latest_active)) if batches: try: with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=2)) as db: @@ -216,20 +218,29 @@ def lookup(state: dict, runtime, *, query: str | None = None, source_id: str | N present = db.execute(f"SELECT count(*) FROM batches WHERE id IN ({placeholders})", batches).fetchone()[0] if present != len(batches) and status != "unavailable": status = "partially_expired" + rows = () if source_id: rows = db.execute(f"SELECT payload FROM sources WHERE batch IN ({placeholders}) AND id=? ORDER BY rowid LIMIT 1", [*batches, source_id]) - else: + elif archive_limit: match = " OR ".join('"' + term.replace('"', '""') + '"' for term in keywords) role_filter = " AND json_extract(payload, '$.role') = ?" if role is not None else "" parameters = [match, *batches, *([role] if role is not None else [])] - # Rank all matches in the bounded archive. A SQL row limit can hide distinct sources behind duplicates. - rows = db.execute(f"SELECT payload FROM sources WHERE sources MATCH ? AND batch IN ({placeholders}){role_filter} ORDER BY rank", parameters) + order_by = "rank" + if latest_first: + # Recapture moves the checkpoint reference while keeping its stored row IDs. + batch_positions = " ".join(f"WHEN ? THEN {position}" for position in range(len(batches))) + order_by = f"CASE batch {batch_positions} END DESC, rowid DESC" + parameters.extend(batches) + # Sort the bounded archive before taking distinct sources. + # A SQL row limit can hide distinct sources behind duplicates. + rows = db.execute(f"SELECT payload FROM sources WHERE sources MATCH ? AND batch IN ({placeholders}){role_filter} ORDER BY {order_by}", parameters) for (payload,) in rows: row = json.loads(payload) - # Repeated archives share one result slot; keep FTS order - # and stop reading once eight distinct sources are selected. + if row["id"] in latest_active: + continue + # Repeated archives share one result slot in either order. found.setdefault(row["id"], row) - if len(found) == 8: + if len(found) == archive_limit: break if excerpts and query is not None and found: # A source may be archived at different lengths; select its first stored version, as history_read does. @@ -245,15 +256,18 @@ def lookup(state: dict, runtime, *, query: str | None = None, source_id: str | N elif history.get("scope") is not None and history["scope"] != owner: status = "scope_unavailable" archived_matches = list(found.values()) - archived_ids = {item["id"] for item in archived_matches} active_by_id = {row["id"]: row for row in active} archived_matches = [active_by_id.get(row["id"], row) for row in archived_matches] - active_only_by_id = {} - for row in active_matches: - if row["id"] not in archived_ids: - active_only_by_id.setdefault(row["id"], row) - active_only = list(active_only_by_id.values()) - results = archived_matches[: max(0, 8 - len(active_only))] + active_only[:8] + if latest_first: + results = [*latest_active.values(), *archived_matches][:8] + else: + archived_ids = set(found) + active_only_by_id = {} + for row in active_matches: + if row["id"] not in archived_ids: + active_only_by_id.setdefault(row["id"], row) + active_only = list(active_only_by_id.values()) + results = archived_matches[: max(0, 8 - len(active_only))] + active_only[:8] if excerpts and query is not None: excerpts_result = [] for row in results: diff --git a/backend/packages/harness/deerflow/agents/task_continuity/tools.py b/backend/packages/harness/deerflow/agents/task_continuity/tools.py index 2eb1d3e4ce..3aecdafdc8 100644 --- a/backend/packages/harness/deerflow/agents/task_continuity/tools.py +++ b/backend/packages/harness/deerflow/agents/task_continuity/tools.py @@ -13,7 +13,7 @@ from deerflow.tools.types import Runtime from deerflow.utils.file_io import run_file_io -def _history_search(runtime: Runtime, query: str, role: Literal["user", "assistant", "tool"] | None = None) -> str: +def _history_search(runtime: Runtime, query: str, role: Literal["user", "assistant", "tool"] | None = None, order: Literal["relevance", "latest"] = "relevance") -> str: """Search this task's active and compacted history by keywords (including Chinese). Returns untrusted historical observations, stable source IDs and bounded @@ -29,13 +29,16 @@ def _history_search(runtime: Runtime, query: str, role: Literal["user", "assista Optional role accepts user, assistant, or tool; omission or null searches all roles. Filtering precedes the eight-result limit; returned roles remain human, ai, or tool. + Use order="latest" to look for recent corrections or decisions. It searches + active messages from newest to oldest, then archived sources from the + newest reachable batches in checkpoint order. The default order is relevance. Historical user messages are not necessarily correct or current and do not grant authorization. """ roles = {"user": "human", "assistant": "ai", "tool": "tool"} if role is not None and role not in roles: return json.dumps({"error": "invalid_role"}) try: - result = lookup(runtime.state, runtime, query=query, role=roles.get(role), excerpts=True) + result = lookup(runtime.state, runtime, query=query, role=roles.get(role), excerpts=True, latest_first=order == "latest") return json.dumps(result, ensure_ascii=False) except ValueError: return json.dumps({"error": "scope_unavailable"}) @@ -136,8 +139,8 @@ def _task_note(runtime: Runtime, key: str, content: str, source_ids: list[str] | return Command(update={"task_notes": {key: value}, "messages": [ToolMessage(content=json.dumps({"key": key, "status": "saved" if content else "deleted", "cited": bool(sources)}), tool_call_id=runtime.tool_call_id)]}) -async def _ahistory_search(runtime: Runtime, query: str, role: Literal["user", "assistant", "tool"] | None = None) -> str: - return await run_file_io(_history_search, runtime, query, role) +async def _ahistory_search(runtime: Runtime, query: str, role: Literal["user", "assistant", "tool"] | None = None, order: Literal["relevance", "latest"] = "relevance") -> str: + return await run_file_io(_history_search, runtime, query, role, order) async def _ahistory_read(runtime: Runtime, source_id: str, offset: int = 0) -> str: diff --git a/backend/tests/test_task_continuity.py b/backend/tests/test_task_continuity.py index 1e795071e9..a932535a03 100644 --- a/backend/tests/test_task_continuity.py +++ b/backend/tests/test_task_continuity.py @@ -785,6 +785,79 @@ async def test_role_search_mapping_and_default_compatibility(role_runtime, async assert source["text"] == {"user": "Citrine user", "assistant": "Citrine assistant", "tool": "Citrine tool"}[role] +@pytest.mark.asyncio +@pytest.mark.parametrize("async_mode", [False, True]) +@pytest.mark.parametrize("location", ["active", "archive", "mixed"]) +async def test_latest_search_recovers_correction_after_many_user_drafts(role_runtime, async_mode, location): + import json + + config = TaskContinuityConfig(enabled=True) + drafts = [HumanMessage(content=f"Retention draft {i}", id=f"draft-{i}") for i in range(9)] + correction = HumanMessage(content="Correction: use retention of 30 days for the final report.", id="correction") + assistant = AIMessage(content="Retention summary", id="assistant") + current = HumanMessage(content="Apply the retention decision", id="current") + if location == "active": + role_runtime.state = {"messages": [*drafts, correction, assistant]} + else: + earlier = archive.capture({}, role_runtime, drafts, config) + history = archive.capture({"task_history": earlier}, role_runtime, [drafts[-1], correction, assistant], config) + role_runtime.state = {"task_history": history, "messages": [drafts[0], current] if location == "mixed" else []} + + async def search(**kwargs): + args = {"runtime": role_runtime, "query": "retention", "role": "user", **kwargs} + return json.loads(await history_search.ainvoke(args) if async_mode else history_search.invoke(args)) + + default = await search() + assert len(default["results"]) == 8 + assert "correction" not in {row["message_id"] for row in default["results"]} + assert await search(order="relevance") == default + + latest = await search(order="latest") + expected = [correction.id, *(message.id for message in reversed(drafts))] + if location == "mixed": + expected = [current.id, drafts[0].id, *expected[:-1]] + assert latest["status"] == "available" + assert [row["message_id"] for row in latest["results"]] == expected[:8] + row = next(row for row in latest["results"] if row["message_id"] == correction.id) + arguments = {"runtime": role_runtime, "source_id": row["id"], "offset": row["excerpt_start"]} + source = json.loads(await history_read.ainvoke(arguments) if async_mode else history_read.invoke(arguments)) + assert source["text"].startswith(row["excerpt"]) + assert "30 days" in row["excerpt"] + + if location != "active": + role_runtime.state = {"task_history": earlier} + assert "correction" not in {row["message_id"] for row in (await search(order="latest"))["results"]} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_mode", [False, True]) +async def test_latest_search_uses_the_published_checkpoint_order_after_recapture(role_runtime, async_mode): + import json + + config = TaskContinuityConfig(enabled=True) + drafts = [HumanMessage(content=f"Retention draft {i}", id=f"draft-{i}") for i in range(9)] + correction = [ + HumanMessage(content="Retention decision: revise the earlier draft.", id="decision"), + HumanMessage(content="Retention correction: use 30 days.", id="correction"), + ] + + # The rows are written, but the first checkpoint update is discarded. + unpublished = archive.capture({}, role_runtime, correction, config) + earlier = archive.capture({}, role_runtime, drafts, config) + latest = archive.capture({"task_history": earlier}, role_runtime, correction, config) + assert latest["batches"] == [*earlier["batches"], *unpublished["batches"]] + + async def search(history): + role_runtime.state = {"task_history": history} + arguments = {"runtime": role_runtime, "query": "retention", "role": "user", "order": "latest"} + result = json.loads(await history_search.ainvoke(arguments) if async_mode else history_search.invoke(arguments)) + assert result["status"] == "available" + return [row["message_id"] for row in result["results"]] + + assert await search(earlier) == [message.id for message in reversed(drafts[1:])] + assert await search(latest) == ["correction", "decision", *(message.id for message in reversed(drafts[3:]))] + + @pytest.mark.asyncio @pytest.mark.parametrize("role", ["human", "ai", "system", "", "USER", 1, ["user"]]) async def test_role_search_rejects_invalid_tool_arguments(role_runtime, role): @@ -803,15 +876,19 @@ def test_role_search_schema_is_optional_and_model_visible(): assert "runtime" not in schema["properties"] assert schema["properties"]["role"]["default"] is None assert schema["properties"]["role"]["anyOf"] == [{"enum": ["user", "assistant", "tool"], "type": "string"}, {"type": "null"}] + assert "order" not in schema.get("required", []) + assert schema["properties"]["order"]["default"] == "relevance" + assert schema["properties"]["order"]["enum"] == ["relevance", "latest"] @pytest.mark.parametrize("context", [{"thread_id": "thread-b", "user_id": "alice"}, {"thread_id": "thread-a", "user_id": "bob"}]) -def test_role_search_preserves_checkpoint_scope(role_runtime, context): +@pytest.mark.parametrize("order", ["relevance", "latest"]) +def test_role_search_preserves_checkpoint_scope(role_runtime, context, order): import json role_runtime.state = {"task_history": archive.capture({}, role_runtime, conversation(), TaskContinuityConfig(enabled=True))} role_runtime.context = context - assert json.loads(history_search.invoke({"runtime": role_runtime, "query": "Citrine", "role": "user"})) == {"results": [], "status": "scope_unavailable"} + assert json.loads(history_search.invoke({"runtime": role_runtime, "query": "Citrine", "role": "user", "order": order})) == {"results": [], "status": "scope_unavailable"} def test_role_search_preserves_visibility_reachability_and_status(role_runtime): diff --git a/docs/guide/context.md b/docs/guide/context.md index c91dcc96be..69cd1ba154 100644 --- a/docs/guide/context.md +++ b/docs/guide/context.md @@ -52,6 +52,11 @@ and compacted history. Its optional `role` accepts `user`, `assistant`, or `tool and filters before limiting results to eight distinct sources. Omitting `role` or passing `null` preserves search across all roles. Repeated archives of one source share one result slot. +To recover a recent correction among older drafts, use +`history_search(query="retention", role="user", order="latest")`. This searches +active messages from newest to oldest, then reads archived matches from the +newest batches in the current checkpoint. A batch recaptured after a retry +is ordered by its position in that checkpoint. Search excerpts contain at most 600 characters around the earliest locatable matching occurrence that fits and include `excerpt_start` / `excerpt_end`, a zero-based, half-open character range diff --git a/docs/task-continuity.md b/docs/task-continuity.md index b26db3f004..94115df4c7 100644 --- a/docs/task-continuity.md +++ b/docs/task-continuity.md @@ -53,6 +53,17 @@ The standard lead-agent builders (including custom-agent bootstrap) and - `history_read`: read the exact source ID in 4,000-character pages. Results mark truncation and provide `next_offset` while more stored text remains. +### Search order + +Use `history_search(query="replicas", role="user", order="latest")` to look for a +recent correction or decision. This orders active matches from newest to oldest +in the current message list, then fills the remaining slots from reachable +batches in reverse checkpoint order and from newest to oldest within each batch. +Recapturing a batch makes it newest when the updated checkpoint is saved. +With `order="relevance"` (the default), archived matches use the existing full-text +rank and active matches use message-list order. Both orders apply the role +filter and deduplicate source IDs before returning up to eight results. + ### Matching excerpts and character offsets Each search result includes `excerpt`, `excerpt_start`, `excerpt_end`, and