From a2cd8c957323566e4298b717063e1d7c89dcb5e5 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:31:37 +0800 Subject: [PATCH 1/2] perf(status): reuse the source row for indexed Todo handoffs Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../control_plane/todos/context_projection.ts | 32 ++++++++++++++--- loopx/control_plane/todos/handoff_note.py | 17 ++++++---- loopx/control_plane/todos/read_codec.ts | 16 ++++++--- loopx/control_plane/todos/todo_index.py | 34 ++++++++----------- .../test_handoff_context_projection.py | 11 ++++++ .../todo_context_projection.test.ts | 22 ++++++++++++ 6 files changed, 98 insertions(+), 34 deletions(-) diff --git a/loopx/control_plane/todos/context_projection.ts b/loopx/control_plane/todos/context_projection.ts index 812a93a5e9..2f08e0d4d3 100644 --- a/loopx/control_plane/todos/context_projection.ts +++ b/loopx/control_plane/todos/context_projection.ts @@ -13,6 +13,20 @@ import {compactThinTodoRead, compactTodoReadSummary, compactThinTodoReadSummary} import {TODO_DECISION_SCOPE_OUTCOME_SCHEMA_VERSION} from "./user_completion_types.ts"; import {removedTodoContinuationPolicy} from "./legacy_continuation_policy_migration.ts"; +// Index rows retain the compact Todo and replace only these presentation labels. +function indexedHandoffSource(source: JsonObject, value: unknown): JsonObject { + const labels = requireJsonObject(value, "handoff index labels"); + const keys = ["schema_version", "goal_id", "role", "source", "text", "title"]; + if (Object.keys(labels).length !== keys.length || keys.some(key => typeof labels[key] !== "string")) { + throw new EffectRuntimeRequestError("invalid handoff index labels"); + } + requireJsonObject(source.record, "handoff index source record"); + const original = decodeTodoReadSource(source); + const indexed = {...original, ...labels}; + copyTodoPythonValues(original, indexed, labels); + return handoffSource(indexed); +} + // A read lens over canonical records, shared by global and Goal conversations. // These are existing Todo facts, not dependency evaluation or execution grants. const CONTEXT_FIELDS = [ @@ -63,12 +77,22 @@ export function projectTodoContextPage(input: JsonObject): JsonObject { return compactTodoReadSummary(requireJsonObject(input.summary_payload, "Todo summary payload"), String(input.role), input.limit == null ? null : Number(input.limit)); } if (input.handoff_sources !== undefined) { - if (Object.keys(input).some(key => key !== "handoff_sources" && key !== "handoff_followups")) { + if (Object.keys(input).some(key => !["handoff_sources", "handoff_followups", "handoff_index_labels"].includes(key))) { throw new EffectRuntimeRequestError("handoff context cannot be combined with list/detail/page inputs"); } - return {handoff_context: projectTodoHandoffContext( - Array.isArray(input.handoff_sources) ? input.handoff_sources.map(row => handoffReadSource(requireJsonObject(row, "handoff source"))) : input.handoff_sources, - Array.isArray(input.handoff_followups) ? input.handoff_followups.map(row => row === null ? null : handoffReadSource(requireJsonObject(row, "handoff followup"))) : input.handoff_followups)}; + if (!Array.isArray(input.handoff_sources)) throw new EffectRuntimeRequestError("handoff sources must be an array"); + const sources = input.handoff_sources.map(row => requireJsonObject(row, "handoff source")); + let followups = input.handoff_followups; + if (input.handoff_index_labels !== undefined) { + const labels = input.handoff_index_labels; + if (followups !== undefined || !Array.isArray(labels) || labels.length !== sources.length) { + throw new EffectRuntimeRequestError("handoff index labels require one entry per source and no full followups"); + } + followups = labels.map((entry, index) => entry === null ? null : indexedHandoffSource(sources[index]!, entry)); + } else if (Array.isArray(followups)) { + followups = followups.map(row => row === null ? null : handoffReadSource(requireJsonObject(row, "handoff followup"))); + } + return {handoff_context: projectTodoHandoffContext(sources.map(handoffReadSource), followups)}; } if (input.list_payload !== undefined) return projectTodoListPayload(input); if (input.detail_payload !== undefined) return projectTodoDetailPayload(input); diff --git a/loopx/control_plane/todos/handoff_note.py b/loopx/control_plane/todos/handoff_note.py index f8711ac97b..299fb84d0c 100644 --- a/loopx/control_plane/todos/handoff_note.py +++ b/loopx/control_plane/todos/handoff_note.py @@ -54,10 +54,15 @@ def validate_handoff_context(value: Any, count: int) -> list[dict[str, Any]]: def project_handoff_context(sources: list[dict[str, Any]], *, - followups: list[dict[str, Any] | None] | None = None) -> list[dict[str, Any]]: + followups: list[dict[str, Any] | None] | None = None, + index_labels: list[dict[str, Any] | None] | None = None) -> list[dict[str, Any]]: from ..effect_runtime import MAX_REQUEST_BYTES, EffectRuntimeRejected, effect_runtime_result - if followups is not None and len(followups) != len(sources): + if index_labels is not None and followups is not None: + raise ValueError("handoff index labels and full followups are mutually exclusive") + field = "handoff_index_labels" if index_labels is not None else "handoff_followups" + second_stage = index_labels if index_labels is not None else followups + if second_stage is not None and len(second_stage) != len(sources): raise ValueError("handoff followup cardinality mismatch") results: list[dict[str, Any]] = [] # This lens is row-independent: byte-bounded transport batches preserve @@ -65,12 +70,12 @@ def project_handoff_context(sources: list[dict[str, Any]], *, start, size = 0, 0 for index in range(len(sources) + 1): row_size = 0 if index == len(sources) else len(json.dumps(sources[index], separators=(",", ":")).encode()) + 2 - if followups is not None and index < len(sources): - row_size += len(json.dumps(followups[index], separators=(",", ":")).encode()) + 2 + if second_stage is not None and index < len(sources): + row_size += len(json.dumps(second_stage[index], separators=(",", ":")).encode()) + 2 if index > start and (index == len(sources) or size + row_size > MAX_REQUEST_BYTES - 4096): try: result = effect_runtime_result("todo.context.page", {"handoff_sources": sources[start:index], - **({"handoff_followups": followups[start:index]} if followups is not None else {})}) + **({field: second_stage[start:index]} if second_stage is not None else {})}) except EffectRuntimeRejected as error: raise ValueError(str(error)) from error results.extend(validate_handoff_context(result.get("handoff_context") if isinstance(result, dict) else None, index - start)) @@ -81,7 +86,7 @@ def project_handoff_context(sources: list[dict[str, Any]], *, # typed credential exclusion or add a Python fallback decision. try: result = effect_runtime_result("todo.context.page", {"handoff_sources": sources[index:index + 1], - **({"handoff_followups": followups[index:index + 1]} if followups is not None else {})}, + **({field: second_stage[index:index + 1]} if second_stage is not None else {})}, large_local_snapshot=True) except EffectRuntimeRejected as error: raise ValueError(str(error)) from error diff --git a/loopx/control_plane/todos/read_codec.ts b/loopx/control_plane/todos/read_codec.ts index 7f6110b729..73b402f785 100644 --- a/loopx/control_plane/todos/read_codec.ts +++ b/loopx/control_plane/todos/read_codec.ts @@ -182,15 +182,21 @@ export function pythonFieldInteger(row: JsonObject, key: string, fallback = 9999 function fieldRepr(row: JsonObject | unknown[], key: string | number): string { return pythonValues.get(row)?.get(String(key))?.[1] as string ?? repr((row as JsonObject)[key]); } -export function copyTodoPythonValues(source: JsonObject, target: JsonObject): void { +export function copyTodoPythonValues(source: JsonObject, target: JsonObject, replaced?: JsonObject): void { const fields = pythonValues.get(source); - if (fields) pythonValues.set(target, new Map([...fields].filter(([key]) => target[key] === source[key]))); + if (fields) pythonValues.set(target, new Map([...fields].filter(([key]) => target[key] === source[key] && !(replaced && Object.hasOwn(replaced, key))))); } export function handoffReadSource(value: JsonObject): JsonObject { if (value.record === undefined) return value; // retained already-encoded transport callers return {...handoffSource(decodeTodoReadSource(value)), goal_id: value.goal_id ?? "", source: value.source ?? ""}; } +function legacyHandoffId(item: JsonObject): string { + const fields = ["goal_id", "role", "index", truthy(item.text) ? "text" : "title"]; + const tuple = "(" + fields.map(key => fieldRepr(item, key)).join(", ") + ")"; + return "handoff_" + createHash("sha1").update(tuple).digest("hex").slice(0, 12); +} + export function handoffSource(item: JsonObject): JsonObject { const refs = (value: unknown): JsonObject => ({...(truthy(value) ? {truthy: true} : {}), ...(Array.isArray(value) && value.length ? {values: value.map((_, i) => pythonFieldText(value, i))} : {})}); @@ -204,15 +210,15 @@ export function handoffSource(item: JsonObject): JsonObject { } const fields = ["continuation_hint", "suggested_next_action", "note", "reason", "summary", "intent", "blocked_on", "evidence", "title", "text", "task_class", "goal_id", "source", "latest_event_kind"]; const action = compactPythonWhitespace(scalarText(item.action_kind)).toLowerCase(); - const legacy = "(" + ["goal_id", "role", "index", truthy(item.text) ? "text" : "title"].map(key => fieldRepr(item, key)).join(", ") + ")"; + const todoId = id(item.todo_id); return {...nested, nested_metadata: nestedMetadata, texts: Object.fromEntries(fields.filter(key => truthy(item[key])).map(key => [key, pythonFieldText(item, key)])), - metadata: {todo_id: id(item.todo_id), claimed_by: readAgent(item.claimed_by), excluded_agents: readExcludedAgents(item.excluded_agents), + metadata: {todo_id: todoId, claimed_by: readAgent(item.claimed_by), excluded_agents: readExcludedAgents(item.excluded_agents), successor_todo_ids: ids(item.successor_todo_ids), unblocks_todo_id: id(item.unblocks_todo_id), superseded_by: id(item.superseded_by), action_kind: /^[a-z][a-z0-9_-]{0,63}$/.test(action) ? action : null, resume_when: readResume(item.resume_when), required_decision_scopes: readScopes(item.required_decision_scopes), decision_scope: readScope(item.decision_scope)}, evidence_refs: refs(item.evidence_refs), has_evidence: truthy(item.evidence), has_note: truthy(item.note), - goal_id: "", source: "", legacy_id: id(item.todo_id) ? null : "handoff_" + createHash("sha1").update(legacy).digest("hex").slice(0, 12)}; + goal_id: "", source: "", legacy_id: todoId ? null : legacyHandoffId(item)}; } /** Provider records are already decoded. This changes presentation, never authority. */ diff --git a/loopx/control_plane/todos/todo_index.py b/loopx/control_plane/todos/todo_index.py index 0c0f99dffd..c5f499e02b 100644 --- a/loopx/control_plane/todos/todo_index.py +++ b/loopx/control_plane/todos/todo_index.py @@ -56,7 +56,7 @@ def _todo_index_key(goal_id: str, todo: dict[str, Any]) -> tuple[str, str]: return goal_id, f"synthetic:{todo.get('role') or ''}:{todo.get('index') or ''}:{todo.get('text') or ''}" -def _indexed_status_todo( +def _status_index_labels( *, goal_id: str, role: str, @@ -67,18 +67,14 @@ def _indexed_status_todo( text = public_safe_compact_text(todo.get("title") or todo.get("text"), limit=320) if not text: return None - item = dict(todo) - item.update( - { - "schema_version": TODO_INDEX_ITEM_SCHEMA_VERSION, - "goal_id": goal_id, - "role": role, - "source": source, - "text": text, - "title": public_safe_compact_text(todo.get("title"), limit=320) or text, - } - ) - return item + return { + "schema_version": TODO_INDEX_ITEM_SCHEMA_VERSION, + "goal_id": goal_id, + "role": role, + "source": source, + "text": text, + "title": public_safe_compact_text(todo.get("title"), limit=320) or text, + } def _rollout_event_todo_status(event: Mapping[str, Any]) -> str: @@ -174,14 +170,14 @@ def build_todo_index( status_sources.extend((goal_id, role, todo) for todo in todos.get("items") or [] if isinstance(todo, dict)) compacts = [_compact_todo_item_record(todo) for _, _, todo in status_sources] - status_rows, context_sources, followups = [], [], [] + status_rows, context_sources, index_labels = [], [], [] for (goal_id, role, _), compact in zip(status_sources, compacts, strict=True): - row = _indexed_status_todo(goal_id=goal_id, role=role, todo=compact, + labels = _status_index_labels(goal_id=goal_id, role=role, todo=compact, source="attention_queue", public_safe_compact_text=public_safe_compact_text) - if row is not None: - status_rows.append(row) + if labels is not None: + status_rows.append({**compact, **labels}) context_sources.append(todo_read_source(compact)) - followups.append(todo_read_source(row)) + index_labels.append(labels) current_count = len(status_rows) rollout_event_count = 0 @@ -218,7 +214,7 @@ def build_todo_index( event_rows.append(event_item) contexts = project_handoff_context([ *context_sources, *(todo_read_source(row) for row in event_rows)], - followups=[*followups, *([None] * len(event_rows))]) + index_labels=[*index_labels, *([None] * len(event_rows))]) for row, context in zip([*status_rows, *event_rows], contexts, strict=True): if context["note"]: row["handoff_note"] = context["note"] diff --git a/tests/control_plane/test_handoff_context_projection.py b/tests/control_plane/test_handoff_context_projection.py index e9b9003bd1..22d8a84c08 100644 --- a/tests/control_plane/test_handoff_context_projection.py +++ b/tests/control_plane/test_handoff_context_projection.py @@ -109,6 +109,17 @@ def cli(*args, succeeds=True): assert indexed["handoff_note"]["handoff_id"] == "handoff_" + original.removeprefix("todo_") again = cli("todo", "list", "--goal-id", "goal-a", "--todo-id", original) assert again["todo"] == record and again["authority_read"]["provider_revision"] == revision + update = ["todo", "update", "--goal-id", "goal-a", "--todo-id", original, "--agent-id", "agent-a", + "--note", "Recheck the updated requirement", "--update-operation-id", "handoff-revised", + "--update-expected-provider-revision"] + assert cli(*update, first["authority_read"]["provider_revision"], succeeds=False)["ok"] is False + cli(*update, revision) + cli(*update, revision) # Lost reply to an accepted update. + revised = cli("todo", "list", "--goal-id", "goal-a", "--todo-id", original) + record, revision = revised["todo"], revised["authority_read"]["provider_revision"] + indexed = next(row for row in cli("status", "--goal-id", "goal-a")["todo_index"]["items"] if row["todo_id"] == original) + assert indexed["handoff_note"]["summary"] == record["note"] == "Recheck the updated requirement" + assert indexed["handoff_note"]["successor_todo_ids"] == [successor] display = state.read_bytes() backend = runtime / "authority" / f"{provider}-v0" offline = backend.with_name(backend.name + "-offline") diff --git a/tests/control_plane_ts/todo_context_projection.test.ts b/tests/control_plane_ts/todo_context_projection.test.ts index 2fbaea8444..68c99818aa 100644 --- a/tests/control_plane_ts/todo_context_projection.test.ts +++ b/tests/control_plane_ts/todo_context_projection.test.ts @@ -179,6 +179,28 @@ test("handoff context is an exclusive read lens with aligned stages", () => { assert.deepEqual(Object.keys(result), ["handoff_context"]); }); +test("index labels preserve the complete two-stage handoff and source scalar facts", () => { + const record = {goal_id: "original", role: "agent", index: 1, text: "Original", + note: 1, successor_todo_ids: ["todo_next"], handoff: {to_agent: "receiver"}}; + const labels = {goal_id: "listed", role: "user", source: "attention_queue", + schema_version: "todo_index_item_v0", text: "Original", title: "Indexed title"}; + const original = {record, python_values: [ + [["index"], "1.0", "1.0", "1"], [["note"], "1.0", "1.0", "1"], + [["text"], "Original", "'raw source text'", null], + ]}; + const event = {record: {todo_id: "todo_event", text: "Event"}}; + const sources = [original, event]; + const full = {record: {...record, ...labels}, python_values: original.python_values.slice(0, 2)}; + const reference = projectTodoContextPage({handoff_sources: sources, handoff_followups: [full, null]}); + assert.deepEqual(projectTodoContextPage({handoff_sources: sources, handoff_index_labels: [labels, null]}), reference); + assert.equal(record.text, "Original"); + for (const invalid of [[], [labels, {}], [{...labels, note: "replacement"}, null], [{...labels, role: 1}, null]]) { + assert.throws(() => projectTodoContextPage({handoff_sources: sources, handoff_index_labels: invalid})); + } + assert.throws(() => projectTodoContextPage({handoff_sources: sources, handoff_followups: [full, null], + handoff_index_labels: [labels, null]})); +}); + // Captured before the cutover; independent rule cases below constrain its meaning. import displayFixture from "./fixtures/todo_summary_display.json" with {type: "json"}; import {projectTodoSummaryDisplay} from "../../loopx/control_plane/todos/context_projection.ts"; From 3d4b1245f93892e8879c96d61ec9d5888773ad1e Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:33:03 +0800 Subject: [PATCH 2/2] test(todos): assert compact summaries retain scopes on the source Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- tests/control_plane/test_handoff_context_projection.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/control_plane/test_handoff_context_projection.py b/tests/control_plane/test_handoff_context_projection.py index 22d8a84c08..4bd33b5e7f 100644 --- a/tests/control_plane/test_handoff_context_projection.py +++ b/tests/control_plane/test_handoff_context_projection.py @@ -209,7 +209,8 @@ def test_python_sequence_and_scalar_facts_cross_the_retained_facade(): result = compact_todo_summary_items([row], strip_text=True)[0] assert result["text"] == "('Check', True)" assert result["continuation_hint"] == "1.0" - assert result["required_write_scopes"] == ["True", "1.0", "docs/**"] + assert "required_write_scopes" not in result + assert row["required_write_scopes"] == (True, 1.0, "docs/**", "../bad") assert result["excluded_agents"] == ["agent-b"] assert result["decision_scope"]["scope_key"] == "1.0" assert result["handoff_note"]["successor_todo_ids"] == ["todo_next"]