diff --git a/docs/reference/required-work-context.md b/docs/reference/required-work-context.md index 8f896959e4..339fbebb7b 100644 --- a/docs/reference/required-work-context.md +++ b/docs/reference/required-work-context.md @@ -229,9 +229,20 @@ applies during explicit Todo selection when work and quota spending are still disabled. A complete scan can still hit the summary's display limit. The initial view then also keeps the exact omitted count and reconciliation guidance. The required read and its existing cursor deliver the scoped request -rows. The captured summary remains available at its original address. An -incomplete scan, unavailable scan records or an unmatched read keeps the whole -summary inline. +rows. With `--attention-only`, each incoming page keeps full `items` for +requests still needing their briefs and `open_request_summaries` for requests +whose latest delivered conclusion leaves remaining work. Follow `next_cursor` +even on summary-only pages. The same cursor continues to open sent requests +after the incoming rows. Pages with only sent summaries do not deliver or +consume results. A nonzero `unavailable_count` calls for receipt recovery. +For peer returns, folding a brief requires a delivery receipt that binds its +request ID and exact result key. An older receipt without that binding keeps +the full brief visible until an authorized read supplies the specific result. +Use `--request-id` without `--attention-only` to read a complete incoming +brief. Inspect a sent Goal request with `manager-inbox status` using the +summary's receiver `agent_id` and exact `request_id` in the same Goal. +The captured summary remains available at its original address. An incomplete +scan, unavailable scan records or an unmatched read keeps the whole summary inline. Adoption and queued returns are intermediate states. Read the full current request before assessing, executing or returning it. Use the existing scoped request and consumption routes for those actions. @@ -444,8 +455,17 @@ full/delta 字节比较计入这些 reader 命令元数据;既有进程内引 首读包含有界 `unfinished_delegations` 投影和 `read_complete` 标记。已准入的普通 工作 Turn 若有大型委派摘要、扫描完整,且必读列表中有同一条管家收件箱命令,首读保留 收发请求计数、扫描状态和必读命令。扫描完整但摘要达到展示上限时,首读同时保留精确的 -省略数量与核对指引。逐条请求通过必读命令及其现有分页游标交付。原摘要仍可从同一 -捕获取回。扫描不完整、扫描记录不可读或没有匹配必读命令时,首读保留完整摘要。 +省略数量与核对指引。逐条请求通过必读命令及其现有分页游标交付。`--attention-only` +下,需要原简报的收件仍在 `items`,最近一次结论已送达且有剩余工作的收件在 +`open_request_summaries`。只有摘要的页也继续跟随 `next_cursor`,收件读完后 +沿同一游标查阅未结外发委派。只含外发摘要的续页不送达或消费结果。 +`Peer` 回传只有在送达回执绑定请求 ID 和确切结果键时才折叠简报。缺少绑定的旧回执 +继续保留完整简报,直到有权限的读取实际交付该条结果。 +`unavailable_count` 大于零时须恢复对应回执。收件全文用不带 +`--attention-only` 的 `--request-id` 精读。Goal 外发委派可在同一 Goal 下用 +摘要中的接收方 `agent_id` 和精确 `request_id` 查阅 `manager-inbox status`。 +原摘要仍可从同一捕获取回。 +扫描不完整、扫描记录不可读或没有匹配必读命令时,首读保留完整摘要。 采纳和回传入队是中间状态,评估、执行或回传前须读当前请求全文,并沿已有范围约束和 消费入口办理。 diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md index faa35db564..beeee14a32 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -43,6 +43,13 @@ and governed-delegation tool descriptions. Keep reader, language, corrections and result destination with the original work; do not maintain a second copy in a private manager configuration or an installed skill. The heartbeat hook's required Inbox read uses the same CLI entrypoint. +It requests `read --attention-only`. An unfinished incoming request with a +verified delivered partial answer for its current revision stays on the compact +agenda, with its remaining work and the unfiltered read command. Requests +without that proof, including queued or unreadable returns, still supply the +full brief before work. Read a request's full current brief with `--request-id` +before resuming it or returning an answer. Peer returns, native child results +and operation handoffs use their usual readers. The rule calls for a useful outcome first, explained terms and comparisons with units and direction. Full evidence, negative results, unknown costs and remaining @@ -745,9 +752,10 @@ and are not paginated by this cursor. `status --offset/--limit` remains separate Large Markdown Inbox responses open with a reference to a private capture. The generated native context configuration declares `LOOPX_CONTEXT_PAGE_OUTPUT_BYTES=64000` for tools that can retain that size. -The Inbox uses that profile for both capture reader commands and keeps the -opening within 12,000 bytes. Without that declaration the reader also stays -within 12,000 bytes. Follow the capture's byte cursors and verify coverage before +The Inbox uses that profile for both capture reader commands. The Markdown +response and capture opening stay within 5,000 serialized bytes. Without the +declaration, both reader commands use the same 5,000-byte limit. Follow the +capture's byte cursors and verify coverage before using the Inbox cursor. If a reader output is truncated, reduce both page limits and recover the affected range of the same capture. diff --git a/loopx/capabilities/manager_context/__init__.py b/loopx/capabilities/manager_context/__init__.py index df56ea27a8..2b6a5c3a3d 100644 --- a/loopx/capabilities/manager_context/__init__.py +++ b/loopx/capabilities/manager_context/__init__.py @@ -292,6 +292,7 @@ def produce(): str(runtime_root), "manager-inbox", "read", + "--attention-only", *(["--format", "markdown"] if model_read else []), "--goal-id", goal_id, diff --git a/loopx/cli_commands/manager_inbox.py b/loopx/cli_commands/manager_inbox.py index adaa910411..4d744b3155 100644 --- a/loopx/cli_commands/manager_inbox.py +++ b/loopx/cli_commands/manager_inbox.py @@ -111,12 +111,12 @@ def _render_read_markdown(result: dict) -> str: def _read_markdown(result: dict, *, runtime_root: Path) -> tuple[str, bool]: """Deliver the already-recorded scoped read without repeating its effects.""" from ..control_plane.turn_driver.native_context_profile import ( - NATIVE_CONTEXT_FIRST_READ_FALLBACK_BYTES, NATIVE_CONTEXT_OUTPUT_ENV, + NATIVE_INBOX_MARKDOWN_OUTPUT_BYTES, native_context_page_budget, ) - limit = NATIVE_CONTEXT_FIRST_READ_FALLBACK_BYTES + limit = NATIVE_INBOX_MARKDOWN_OUTPUT_BYTES view = _share_item_guidance(result) body = _render_read_markdown(view) size = len((body + os.linesep).encode("utf-8")) @@ -151,7 +151,8 @@ def _read_markdown(result: dict, *, runtime_root: Path) -> tuple[str, bool]: "Follow next_command through eof in UTF-8 byte-offset order. Compare each reported digest with " "this opening's SHA-256. Check each " "page's content length against its offsets, and complete coverage through total_bytes. " - "If output is missing or truncated, reread that range of the same capture with a smaller page. " + "If output is missing or truncated, reread that range of the same capture with smaller " + "--page-bytes and --max-page-output-bytes. " + CONTEXT_CAPTURE_CODE_MODE_GUIDANCE + "Apply any shared_item_guidance to the items on this page. After the page is complete, " "follow its next_cursor, operation_handoff_next_cursor, or native_child_results.next_cursor with the original Inbox command. " @@ -245,6 +246,8 @@ def register_manager_inbox(subparsers, add_format): parser.add_argument("--sender-id", help="For configuring a new delivery source: its independently verified sender.") parser.add_argument("--execute", action="store_true") parser.add_argument("--request-id", help="For read: inspect this exact current or concluded request instead of the pending inbox.") + parser.add_argument("--attention-only", action="store_true", + help="For read: page through incoming briefs, summaries of partial conclusions and open sent requests.") parser.add_argument( "--phase", choices=("decision", "conclusion"), default="conclusion" ) @@ -273,6 +276,9 @@ def handle_manager_inbox(args, registry_path, runtime_root): try: remainder = getattr(args, "remaining_work", None) resume = getattr(args, "resume_when", None) + attention_only = getattr(args, "attention_only", False) + if attention_only and (args.manager_inbox_action != "read" or getattr(args, "request_id", None) is not None): + raise ValueError("--attention-only requires read without --request-id") if remainder is not None or resume is not None: if args.manager_inbox_action != "report" or remainder is None or resume is None: raise ValueError("--remaining-work and --resume-when require report and each other") @@ -478,7 +484,7 @@ def handle_manager_inbox(args, registry_path, runtime_root): # Only the invocation-bound host reader can record Turn delivery. result = read_inbox(runtime_root, registry_path, args.goal_id, args.agent_id, workspace=Path.cwd(), cursor=cursor, operation_cursor=operation_cursor, - request_id=request_id) + request_id=request_id, attention_only=attention_only) result["instruction"] += " " + collaboration_answer_instruction() if request_id is None: result["followthrough"] += ( diff --git a/loopx/control_plane/collaboration/inbox.py b/loopx/control_plane/collaboration/inbox.py index 4acd4ad2f2..df3b6f84ed 100644 --- a/loopx/control_plane/collaboration/inbox.py +++ b/loopx/control_plane/collaboration/inbox.py @@ -223,7 +223,10 @@ def pending( def _pending_result(root, snapshot, scope, operation_cursor): result = snapshot["result"] - if "request_id" in result or snapshot.get("completed") or snapshot.get("native_child_continuation"): + # A completed request page has no read effects left, but an explicitly + # requested operation page still has its own independent cursor. + if ("request_id" in result or snapshot.get("native_child_continuation") + or (snapshot.get("completed") and operation_cursor is None)): return result from .operation_handoff import pending_operation_handoffs diff --git a/loopx/control_plane/collaboration/inbox_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index 22329287f0..d2b6326c89 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -13,7 +13,7 @@ import {jsonObject, requireJsonObject, requireNonEmptyString, requireStringLiter import {decideCollaborationLifecycle} from "./goal_instance_lifecycle.ts"; import {inspectCollaborationInboxReceipts, projectReceiverFollowthrough} from "./inbox_receipts.ts"; import {recordControlledRequestRead} from "./request_control.ts"; -import {planCollaborationResult} from "./result_publication.ts"; +import {planCollaborationResult, returnMessageId} from "./result_publication.ts"; import {CONVERSATION_ENTRY_SCHEMA, normalizeOriginalConversationRecipient, verifyOriginalConversationReturnRoute} from "./semantic_request.ts"; import {projectDelegationTurnContext, projectDelegationTurnItem, projectDelegationTurnItems} from "./turn_context.ts"; import {isNativeChildResultCursor, nativeChildResultInbox} from "../capabilities/native_child_result_inbox.ts"; @@ -26,6 +26,11 @@ const DELIVERY_STATUSES: ReadonlySet = new Set(deliveryContract.delivery const DELIVERY_ERRORS: ReadonlySet = new Set(deliveryContract.delivery_errors); const RESULT_KEY = /^(?:decision|conclusion)(?:-[0-9]{8})?$/; const TURN_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; +const INBOX_PAGE_SIZE = 20; +const ATTENTION_GUIDANCE = " Reconcile open_request_summaries together with items on every page, including pages with no full briefs. " + + "For an incoming summary, use the unfiltered read command with --request-id for the full current brief before working on or returning it. " + + "Use the existing scoped request status for sent requests and follow next_cursor to reach their summaries. " + + "An unavailable_count above zero requires receipt recovery."; type InboxSource = Readonly<{root: string; goal: string; agent: string; scope: JsonObject; exact: boolean; recipient?: JsonObject}>; type ReturnDelivery = Readonly<{key: string; request: JsonObject; reply: JsonObject}>; type PeerReturnPage = Readonly<{scope: string; afterOperation: string; afterResult: string}>; @@ -203,7 +208,31 @@ function inboxItem(row: JsonObject, state: JsonObject): JsonObject { else if (view) item.next_action = view.receiver_instruction; return item; } +function deliveredRemainderSummary(source: InboxSource, row: JsonObject, state: JsonObject): JsonObject | null { + if (state.kind !== "awaiting_conclusion" || !state.remaining_work) return null; + const control = jsonObject(state.request_control_view); + if (control?.active_reservation != null || jsonObject(jsonObject(state.readback)?.read)?.status === "unavailable") { + return null; + } + const links = linksReceipt(source.root, row); + if (links.unavailable) return null; + try { + const results = agendaResults(source.root, row); + const latest = results.filter(result => result.request_revision === (control?.revision ?? 1)).at(-1); + return latest?.status === "delivered" + ? projectDelegationTurnItem(delegationObservation("incoming", row, state, links, results)) + : null; + } catch (error) { + if (!recordFailure(error)) throw error; + return null; + } +} + async function pendingPage(source: InboxSource, params: JsonObject): Promise { + const attentionOnly = params.attention_only === true; + if (attentionOnly && (source.recipient || params.request_id != null)) { + fail("attention-only Inbox reads require a Goal inbox without an exact request selector"); + } if (params.request_id != null) { if (params.cursor != null || params.operation_cursor != null) fail("an exact request read cannot use inbox cursors"); let row: JsonObject; @@ -214,29 +243,55 @@ async function pendingPage(source: InboxSource, params: JsonObject): Promise digest(source.exact ? [kind, params.runtime_root, target(source)] + : [kind, params.runtime_root, source.goal, source.agent]); + // Operation handoffs retain their existing Goal/Agent cursor scope in both views. + const operationCursorScope = scopeFor("pending_requests_v1"); + const scope = attentionOnly ? scopeFor("pending_attention_v2") : operationCursorScope; + const outgoingScope = attentionOnly ? scopeFor("pending_outgoing_v1") : null; let after = ""; if (params.cursor != null) { - if (typeof params.cursor !== "string" || !/^1:[a-f0-9]{64}:[a-f0-9]{64}$/.test(params.cursor)) fail("invalid pending request cursor"); + if (typeof params.cursor !== "string" || !/^1:[a-f0-9]{64}:(?:[a-f0-9]{64}|start)$/.test(params.cursor)) { + fail("invalid pending request cursor"); + } const [, suppliedScope, suppliedAfter] = params.cursor.split(":"); - if (suppliedScope !== scope) fail("pending request cursor scope mismatch"); + if (outgoingScope === suppliedScope) { + const outgoing = await outgoingSummaryPage(source, outgoingScope, suppliedAfter === "start" ? "" : suppliedAfter, INBOX_PAGE_SIZE); + return {ok: true, items: [], open_request_summaries: outgoing.items, has_more: outgoing.next_cursor !== null, + next_cursor: outgoing.next_cursor, unavailable_count: outgoing.unavailable_count, + _cursor_scope: operationCursorScope, + _outgoing_continuation: true, + instruction: "Review these sent request summaries against the current work. Follow next_cursor when supplied. " + + "An unavailable_count above zero requires receipt recovery. This page records no request reads, result delivery or consumption."}; + } + if (suppliedScope !== scope || suppliedAfter === "start") fail("pending request cursor scope mismatch"); after = suppliedAfter; } - const folder = join(source.root, "entries", digest(target(source))), items: JsonObject[] = []; + const folder = join(source.root, "entries", digest(target(source))); + const entries: {item: JsonObject; summary: boolean}[] = []; for (const [index, name] of names(folder).entries()) { if (index > 0 && index % 128 === 0) await yieldToRuntime(); if (!name.endsWith(".json") || !BARE_SHA256_PATTERN.test(name.slice(0, -5)) || name.slice(0, -5) <= after) continue; const row = pendingEntry(source, join(folder, name)), state = receiptState(source.root, row); if (state.kind === "settled" && !(source.recipient && params.include_settled === true) || !lifecycle(source, "inbox_observe", row)) continue; - items.push(inboxItem(row, state)); - if (items.length === 21) break; + const summary = attentionOnly ? deliveredRemainderSummary(source, row, state) : null; + entries.push({item: summary ?? inboxItem(row, state), summary: summary !== null}); + if (entries.length > INBOX_PAGE_SIZE) break; } - return {ok: true, items: items.slice(0, 20), has_more: items.length > 20, - next_cursor: items.length > 20 ? `1:${scope}:${items[19].request_id}` : null, _cursor_scope: scope, - instruction: TRIAGE + " Follow next_cursor to read later pending requests. Restart without a cursor " + - "to discover new requests before it. The end of a page sequence is not work completion."}; + const page = entries.slice(0, INBOX_PAGE_SIZE); + const moreIncoming = entries.length > page.length; + const outgoing = !moreIncoming && outgoingScope !== null + ? await outgoingSummaryPage(source, outgoingScope, "", 0) : null; + const nextCursor = moreIncoming ? `1:${scope}:${page.at(-1)!.item.request_id}` : outgoing?.next_cursor ?? null; + return {ok: true, items: page.filter(entry => !entry.summary).map(entry => entry.item), + ...(attentionOnly ? {open_request_summaries: page.filter(entry => entry.summary).map(entry => entry.item)} : {}), + ...(outgoing && nextCursor === null && outgoing.unavailable_count > 0 + ? {unavailable_count: outgoing.unavailable_count} : {}), + has_more: nextCursor !== null, next_cursor: nextCursor, _cursor_scope: operationCursorScope, + instruction: TRIAGE + (attentionOnly ? ATTENTION_GUIDANCE : "") + + " Follow next_cursor to read later pending requests. Restart without a cursor to discover new " + + "requests before it. The end of a page sequence is not work completion."}; } function inspectResult(root: string, row: JsonObject, key: string, reply: JsonObject, observations?: JsonObject[]): JsonObject | null { @@ -340,6 +395,20 @@ async function collectReturns(source: InboxSource, page: PeerReturnPage | null = return {view: {items: items.slice(0, 20), has_more: hasMore, ...(hasMore && nextCursor ? {next_cursor: nextCursor} : {})}, deliveries}; } +function peerDeliveryScope(row: JsonObject): JsonObject { + return {status: "delivered", + ...(row.recipient !== undefined ? {requester: row.requester, recipient: row.recipient} + : Object.hasOwn(row, "goal_ref") ? {goal_ref: row.goal_ref} : {})}; +} + +function partialDeliveryMatches(row: JsonObject, key: string, state: JsonObject): boolean { + if (row.source_kind === "peer" && state.kind === "requester_cli_read") { + return Object.entries({...peerDeliveryScope(row), request_id: row.request_id, result_key: key}) + .every(([field, value]) => equal(state[field], value)); + } + return state.message_id === returnMessageId(requestId(row.request_id), key); +} + function replyStatuses(root: string, row: JsonObject): JsonObject[] { const folder = join(root, "replies", requestId(row.request_id)); return resultKeys(folder).map(key => { @@ -362,6 +431,10 @@ function replyStatuses(root: string, row: JsonObject): JsonObject[] { || error !== null && (typeof error !== "string" || !DELIVERY_ERRORS.has(error))) { status = "explicit_unverified"; error = "delivery_state_unreadable"; } + if (status === "delivered" && phase === "conclusion" && reply.remaining_work != null + && !partialDeliveryMatches(row, key, state)) { + fail("partial delegation result delivery scope mismatch"); + } return {...identity, status, created_at: reply.created_at ?? null, delivered_at: typeof state.delivered_at === "string" && [...state.delivered_at].length <= 80 ? state.delivered_at : null, error, ...(state.verification === "reconciled_after_restart" ? {verification: state.verification} : {})}; @@ -391,6 +464,58 @@ function linksReceipt(root: string, row: JsonObject): {value: JsonObject; unavai && validRefs("todo_ids", isCanonicalTodoId) && validRefs("evidence_ids", ref => ENVELOPED_SHA256_PATTERN.test(ref)); return {value: valid ? value : {}, unavailable: !valid}; } +function delegationObservation(direction: "incoming" | "outgoing", row: JsonObject, state: JsonObject, + links: ReturnType, results: JsonObject[], evidenceUnavailable = links.unavailable): JsonObject { + const view = jsonObject(state.request_control_view); + const receipt: JsonObject = {kind: state.kind, recorded_decision: state.recorded_decision}; + if (state.remaining_work) receipt.remaining_work = state.remaining_work; + if (view) receipt.request_control_view = {control_state: view.control_state, active_reservation: view.active_reservation, + revision: view.revision, revision_digest: view.revision_digest, brief: {purpose: (view.brief as JsonObject).purpose}}; + return {direction, request: {...Object.fromEntries(["request_id", "agent_id", "source_kind", "source_agent_id", "goal_ref", "recipient"] + .filter(key => Object.hasOwn(row, key)).map(key => [key, row[key]])), + purpose: (jsonObject(row.brief)?.purpose || [...(row.message as string ?? "")].slice(0, 2000).join(""))}, + receipt, todo_ids: links.value.todo_ids ?? [], evidence_unavailable: evidenceUnavailable, results}; +} + +function agendaEntry(source: InboxSource, direction: "incoming" | "outgoing", path: string): JsonObject | null { + const row = direction === "incoming" ? pendingEntry(source, path) : outgoingEntry(source, readRecord(path)); + if (row.schema_version === CONVERSATION_ENTRY_SCHEMA) { + verifyOriginalConversationReturnRoute({entry: row, + route: readRecord(join(source.root, "roundtrips", String(row.request_id) + ".json"))}); + return row; + } + return lifecycle(source, "inbox_observe", row) ? row : null; +} + +function observeDelegation(source: InboxSource, direction: "incoming" | "outgoing", row: JsonObject): JsonObject { + const state = receiptState(source.root, row), links = linksReceipt(source.root, row); + let results: JsonObject[] = [], evidenceUnavailable = links.unavailable; + try { results = agendaResults(source.root, row); } + catch (error) { if (!recordFailure(error)) throw error; evidenceUnavailable = true; } + return delegationObservation(direction, row, state, links, results, evidenceUnavailable); +} + +async function outgoingSummaryPage(source: InboxSource, scope: string, after: string, limit: number) { + const folder = join(source.root, "peer-operations", digest(target(source))), items: JsonObject[] = []; + let unavailableCount = 0, cursorAfter = after; + for (const [index, name] of names(folder).entries()) { + if (index > 0 && index % 128 === 0) await yieldToRuntime(); + const key = name.slice(0, -5); + if (!name.endsWith(".json") || !BARE_SHA256_PATTERN.test(key) || key <= after) continue; + let row: JsonObject | null; + try { row = agendaEntry(source, "outgoing", join(folder, name)); } + catch (error) { if (!recordFailure(error)) throw error; unavailableCount++; continue; } + const item = row ? projectDelegationTurnItem(observeDelegation(source, "outgoing", row)) : null; + if (!item) continue; + if (items.length === limit) { + return {items, unavailable_count: unavailableCount, next_cursor: `1:${scope}:${cursorAfter || "start"}`}; + } + items.push(item); + cursorAfter = key; + } + return {items, unavailable_count: unavailableCount, next_cursor: null}; +} + async function turnContext(source: InboxSource, params: JsonObject): Promise { let complete = true, unavailable = 0; const batches: JsonObject[] = [], observations: JsonObject[] = []; @@ -401,28 +526,11 @@ async function turnContext(source: InboxSource, params: JsonObject): Promise 0 && index % 128 === 0) await yieldToRuntime(); - let row: JsonObject; - try { - if (direction === "incoming") row = pendingEntry(source, join(folder, name)); - else row = outgoingEntry(source, readRecord(join(folder, name))); - if (row.schema_version === CONVERSATION_ENTRY_SCHEMA) { - verifyOriginalConversationReturnRoute({entry: row, - route: readRecord(join(source.root, "roundtrips", String(row.request_id) + ".json"))}); - } else if (!lifecycle(source, "inbox_observe", row)) continue; - } catch (error) { if (!recordFailure(error)) throw error; unavailable++; continue; } - const state = receiptState(source.root, row), links = linksReceipt(source.root, row); - let results: JsonObject[] = [], evidenceUnavailable = links.unavailable; - try { results = agendaResults(source.root, row); } - catch (error) { if (!recordFailure(error)) throw error; evidenceUnavailable = true; } - const view = jsonObject(state.request_control_view); - const receipt: JsonObject = {kind: state.kind, recorded_decision: state.recorded_decision}; - if (state.remaining_work) receipt.remaining_work = state.remaining_work; - if (view) receipt.request_control_view = {control_state: view.control_state, active_reservation: view.active_reservation, - revision: view.revision, revision_digest: view.revision_digest, brief: {purpose: (view.brief as JsonObject).purpose}}; - observations.push({direction, request: {...Object.fromEntries(["request_id", "agent_id", "source_kind", "source_agent_id", "goal_ref", "recipient"] - .filter(key => Object.hasOwn(row, key)).map(key => [key, row[key]])), - purpose: (jsonObject(row.brief)?.purpose || [...(row.message as string ?? "")].slice(0, 2000).join(""))}, - receipt, todo_ids: links.value.todo_ids ?? [], evidence_unavailable: evidenceUnavailable, results}); + let row: JsonObject | null; + try { row = agendaEntry(source, direction, join(folder, name)); } + catch (error) { if (!recordFailure(error)) throw error; unavailable++; continue; } + if (!row) continue; + observations.push(observeDelegation(source, direction, row)); if (observations.length === 128) flush(); } } @@ -484,14 +592,18 @@ async function recordReads(source: InboxSource, params: JsonObject): Promise !equal(prior[field], value))) { + const scope = peerDeliveryScope(stored); + const identity = {...scope, request_id: id, result_key: key}; + const bound = prior !== null && Object.hasOwn(prior, "request_id"); + const expected = bound ? identity + : {...scope, ...(Object.hasOwn(reply, "result_key") || Object.hasOwn(prior ?? {}, "result_key") + ? {result_key: key} : {})}; + if (prior && Object.entries(expected).some(([field, value]) => !equal(prior[field], value))) { fail("peer return delivery receipt scope mismatch"); } - const priorTurn = jsonObject(prior?.model_turn); + // An older receipt may come from another request in the same scope. + // Bind it on a fresh delivery of this result without inheriting its Turn. + const priorTurn = bound ? jsonObject(prior?.model_turn) : null; const sameTurn = turn !== null && priorTurn?.turn_instance_id === turn; const priorToken = sameTurn ? priorTurn?.read_token : undefined; if (priorToken !== undefined && (typeof priorToken !== "string" || !BARE_SHA256_PATTERN.test(priorToken))) { @@ -500,9 +612,9 @@ async function recordReads(source: InboxSource, params: JsonObject): Promise [name, readFileSync(join(folder, name)).toString("hex")]); } +function deliveredMessage(requestId: string, key: string): JsonObject { + return {status: "delivered", + message_id: "handoff." + createHash("sha256").update(`["${requestId}", "${key}"]`).digest("hex")}; +} + for (const profile of ["legacy", "exact"] as const) { test(`${profile}: Turn observation retains full counts without writing or exposing long source`, async t => { const f = fixture(t, profile); @@ -237,7 +243,8 @@ test("peer-return transport reads remain pending until a concrete model Turn rec const replies = join(f.base, "replies", row.request_id); mkdirSync(replies, {recursive: true}); writeFileSync(join(replies, "conclusion.json"), JSON.stringify({...identity, phase: "conclusion", - decision: "adopt", text: "Checked result", created_at: "2026-10-19T00:00:00Z"})); + decision: "adopt", text: "Checked result", created_at: "2026-10-19T00:00:00Z", + remaining_work: {summary: "Read the final package", resume_when: "The package becomes available"}})); const delivery = join(replies, "conclusion.delivery.json"); await assert.rejects(f.call("receiver_read", {turn_instance_id: "bad/turn"}), /work Turn identity is invalid/); @@ -246,6 +253,9 @@ test("peer-return transport reads remain pending until a concrete model Turn rec const transport = JSON.parse(readFileSync(delivery, "utf8")); assert.equal(transport.kind, "requester_cli_read"); assert.equal(transport.model_turn, undefined); + const receiverView = (await f.call("pending", {attention_only: true, agent_id: "reviewer"})).result as JsonObject; + assert.deepEqual(receiverView.items, []); + assert.equal((receiverView.open_request_summaries as JsonObject[])[0].request_id, row.request_id); await f.call("receiver_read", {turn_instance_id: "turn-a"}); const supplied = readFileSync(delivery); assert.deepEqual(JSON.parse(supplied.toString()).model_turn, @@ -282,11 +292,16 @@ for (const profile of ["legacy", "exact"] as const) { writeFileSync(join(replies, key(n) + ".json"), JSON.stringify({...identity, phase: "conclusion", decision: "adopt", text: "Recorded evidence " + n + "😀".repeat(2000), remaining_work, ...(n ? {result_key: key(n), previous_result_key: key(n - 1), update_id: "evidence-" + n} : {})})); - writeFileSync(join(replies, key(n) + ".delivery.json"), JSON.stringify({status: "delivered"})); + writeFileSync(join(replies, key(n) + ".delivery.json"), JSON.stringify(deliveredMessage(row.request_id, key(n)))); } const original = sourceBytes(replies); const pending = (await f.call("pending")).result as JsonObject; assert.deepEqual((pending.items as JsonObject[])[0].remaining_work, remaining_work); + const attention = (await f.call("receiver_read", {attention_only: true})).result as JsonObject; + assert.deepEqual(attention.items, []); + assert.equal(attention.has_more, false); + assert.equal((attention.open_request_summaries as JsonObject[])[0].request_id, row.request_id); + assert.equal(readdirSync(f.base).includes("reads"), false); const agenda = (await f.call("turn_context")).unfinished_delegations as JsonObject; assert.equal(agenda.incoming_count, 1); assert.equal((agenda.items as JsonObject[])[0].step, "review_request_work"); @@ -296,7 +311,7 @@ for (const profile of ["legacy", "exact"] as const) { const corrupt = JSON.parse(bytes); corrupt.previous_result_key = "conclusion"; writeFileSync(damaged, JSON.stringify(corrupt)); - const failed = (await f.call("pending")).result as JsonObject; + const failed = (await f.call("pending", {attention_only: true})).result as JsonObject; assert.equal((failed.items as JsonObject[])[0].inbox_state, "receipt_unavailable"); const unavailable = (await f.call("turn_context")).unfinished_delegations as JsonObject; assert.equal((unavailable.items as JsonObject[])[0].step, "recover_evidence"); @@ -309,5 +324,123 @@ for (const profile of ["legacy", "exact"] as const) { assert.equal((queued.items as JsonObject[])[0].step, "await_return_delivery"); writeFileSync(join(replies, key(4) + ".delivery.json"), JSON.stringify({status: "delivered"})); assert.deepEqual(((await f.call("turn_context")).unfinished_delegations as JsonObject).items, []); + for (let n = 2; n <= 22; n++) f.publish(n); + const first = (await f.call("pending", {attention_only: true})).result as JsonObject; + assert.equal(first.has_more, true); + await assert.rejects(f.call("pending", {cursor: first.next_cursor}), /pending request cursor scope mismatch/); + const last = (await f.call("pending", {attention_only: true, cursor: first.next_cursor})).result as JsonObject; + assert.equal(last.has_more, false); + assert.equal((last.items as JsonObject[])[0].request_id, f.row(22).request_id); }); } + +test("attention pagination retains a delivered remainder outside the compact agenda", async t => { + const f = fixture(t); + for (let n = 1; n <= 20; n++) f.publish(n); + const row = f.publish(21); + const identity = {goal_id: row.goal_id, goal_ref: ref, agent_id: row.agent_id, + request_id: row.request_id, source_id: row.source_id}; + const replies = join(f.base, "replies", row.request_id); + for (const folder of [replies, join(f.base, "decisions"), join(f.base, "roundtrips")]) mkdirSync(folder, {recursive: true}); + writeFileSync(join(f.base, "decisions", row.request_id + ".json"), JSON.stringify({...identity, decision: "adopt"})); + writeFileSync(join(f.base, "roundtrips", row.request_id + ".json"), JSON.stringify(identity)); + const remaining_work = {summary: "Validate the package", resume_when: "The build is ready"}; + writeFileSync(join(replies, "conclusion.json"), JSON.stringify({...identity, phase: "conclusion", + decision: "adopt", text: "Source verification passed.", remaining_work})); + writeFileSync(join(replies, "conclusion.delivery.json"), JSON.stringify(deliveredMessage(row.request_id, "conclusion"))); + + const first = await f.call("receiver_read", {attention_only: true}); + const firstPage = first.result as JsonObject, context = first.context as JsonObject; + assert.equal((firstPage.items as JsonObject[]).length, 20); + assert.equal(((context.unfinished_delegations as JsonObject).items as JsonObject[]) + .some(item => item.request_id === row.request_id), false); + assert.deepEqual(firstPage.open_request_summaries, []); + assert.equal(firstPage.has_more, true); + + const last = (await f.call("receiver_read", {attention_only: true, cursor: firstPage.next_cursor})).result as JsonObject; + assert.deepEqual(last.items, []); + assert.equal(last.has_more, false); + assert.equal(last.next_cursor, null); + const [summary] = last.open_request_summaries as JsonObject[]; + assert.equal(summary.request_id, row.request_id); + assert.equal(summary.request_revision, 1); + assert.equal(summary.step, "review_request_work"); + assert.deepEqual(summary.remaining_work, remaining_work); + assert.equal(JSON.stringify(summary).includes("PRIVATE_LONG_SOURCE"), false); + assert.equal(readdirSync(join(f.base, "reads")).includes(row.request_id + ".json"), false); + const exact = (await f.call("receiver_read", {request_id: row.request_id})).result as JsonObject; + assert.equal((exact.items as JsonObject[])[0].message, row.message); +}); + +test("the attention cursor reaches all open sent requests without redelivering a peer result", async t => { + const f = fixture(t), operations = join(f.base, "peer-operations", targets.exact); + const receiver = join(f.base, "entries", "5ab0deb53efce4b1d0cf830afb67ce662e0e9aff3127e2424a4ce768212b5586"); + for (const folder of [operations, receiver, join(f.base, "decisions"), join(f.base, "roundtrips")]) { + mkdirSync(folder, {recursive: true}); + } + for (let n = 1; n <= 20; n++) f.publish(n); + const sent = Array.from({length: 22}, (_, n) => f.row(101 + n, { + agent_id: "reviewer", source_kind: "peer", source_agent_id: "worker", + brief: {schema_version: "collaboration_brief_v0", purpose: "Independent review", + context: "PRIVATE_LONG_SOURCE", constraints: [], inputs: [], acceptance: ["Return findings"], return_requirement: "Reply"}, + })); + for (const row of sent) { + writeFileSync(join(receiver, row.request_id + ".json"), JSON.stringify(row)); + writeFileSync(join(operations, row.request_id + ".json"), JSON.stringify(row)); + } + const {request_id, goal_id, agent_id, source_id} = sent[0]; + const identity = {request_id, goal_id, agent_id, source_id, goal_ref: ref}; + writeFileSync(join(f.base, "roundtrips", request_id + ".json"), JSON.stringify(identity)); + writeFileSync(join(f.base, "decisions", request_id + ".json"), JSON.stringify({...identity, decision: "adopt"})); + const replies = join(f.base, "replies", request_id); + mkdirSync(replies, {recursive: true}); + writeFileSync(join(replies, "conclusion.json"), JSON.stringify({...identity, phase: "conclusion", + decision: "adopt", text: "Checked result", created_at: "2026-10-19T00:00:00Z"})); + + const open = (await f.call("receiver_read", {attention_only: true, turn_instance_id: "turn-original"})).result as JsonObject; + assert.equal((open.items as JsonObject[]).length, 20); + assert.deepEqual(open.open_request_summaries, []); + assert.ok(open.peer_returns); + const originalReceipt = sourceBytes(replies); + await assert.rejects(f.call("pending", {cursor: open.next_cursor}), /pending request cursor scope mismatch/); + await assert.rejects(f.call("pending", {attention_only: true, cursor: open.next_cursor, agent_id: "other"}), + /pending request cursor scope mismatch/); + + const next = await f.call("receiver_read", {attention_only: true, cursor: open.next_cursor, turn_instance_id: "turn-other"}); + assert.equal(next.outgoing_continuation, true); + const second = next.result as JsonObject; + assert.equal(second.unavailable_count, 0); + assert.equal((second.open_request_summaries as JsonObject[]).length, 20); + assert.equal((second.open_request_summaries as JsonObject[])[0].step, "consume_peer_result"); + assert.deepEqual(second.items, []); + assert.equal(second.peer_returns, undefined); + writeFileSync(join(operations, "f".repeat(64) + ".json"), "{malformed"); + const last = (await f.call("receiver_read", {attention_only: true, cursor: second.next_cursor})).result as JsonObject; + assert.equal(last.has_more, false); + assert.equal(last.next_cursor, null); + assert.equal(last.unavailable_count, 1); + assert.equal(last.peer_returns, undefined); + const summaries = [...second.open_request_summaries as JsonObject[], ...last.open_request_summaries as JsonObject[]]; + assert.deepEqual(summaries.map(row => row.request_id), sent.map(row => row.request_id)); + assert.ok(summaries.every(row => row.direction === "outgoing" && row.request_revision === 1)); + assert.doesNotMatch(JSON.stringify(summaries), /PRIVATE_LONG_SOURCE|Checked result/); + assert.deepEqual(sourceBytes(replies), originalReceipt); +}); + +test("terminal attention page reports unreadable sent requests even without a continuation", async t => { + const f = fixture(t); + const operations = join(f.base, "peer-operations", targets.exact); + mkdirSync(operations, {recursive: true}); + const request = f.row(101, {agent_id: "reviewer", source_kind: "peer", source_agent_id: "worker"}); + writeFileSync(join(operations, request.request_id + ".json"), JSON.stringify(request)); + const before = sourceBytes(operations); + + const ordinary = (await f.call("pending")).result as JsonObject; + assert.equal(ordinary.unavailable_count, undefined); + const attention = (await f.call("pending", {attention_only: true})).result as JsonObject; + assert.deepEqual(attention.items, []); + assert.deepEqual(attention.open_request_summaries, []); + assert.equal(attention.next_cursor, null); + assert.equal(attention.unavailable_count, 1); + assert.deepEqual(sourceBytes(operations), before); +}); diff --git a/tests/test_chat_operation_actions.py b/tests/test_chat_operation_actions.py index b35478125c..454e819505 100644 --- a/tests/test_chat_operation_actions.py +++ b/tests/test_chat_operation_actions.py @@ -1211,8 +1211,9 @@ def interleaved_binding(registry_path, parameters, runtime_root): def test_inbox_uses_shared_recovery_priority_and_explicit_overflow( tmp_path: Path, ) -> None: - import subprocess - import sys + from loopx.capabilities.manager_context import acknowledge + from loopx.capabilities.manager_context.roundtrip import report + from loopx.control_plane.collaboration.peers import request as request_peer service, store = _service(tmp_path) operation_ids = set() @@ -1244,32 +1245,17 @@ def test_inbox_uses_shared_recovery_priority_and_explicit_overflow( cursor = inbox["operation_handoff_next_cursor"] assert cursor == inbox["operation_handoff_overflow"]["next_cursor"] before = store.path.read_bytes() - process = subprocess.run( - [ - sys.executable, - "-m", - "loopx.cli", - "--format", - "json", - "--registry", - str(service.registry_path), - "--runtime-root", - str(store.root.parent.parent), - "manager-inbox", - "read", - "--goal-id", - GOAL_ID, - "--agent-id", - EXECUTION_ACTOR["agent_id"], - "--operation-cursor", - cursor, - ], - text=True, - capture_output=True, - check=True, - timeout=30, - ) - rest = json.loads(process.stdout) + def read_inbox(*options): + process = subprocess.run( + [sys.executable, "-m", "loopx.cli", "--format", "json", + "--registry", str(service.registry_path), "--runtime-root", str(store.root.parent.parent), + "manager-inbox", "read", "--goal-id", GOAL_ID, "--agent-id", EXECUTION_ACTOR["agent_id"], + *options], + text=True, capture_output=True, check=True, timeout=30, + ) + return json.loads(process.stdout) + + rest = read_inbox("--operation-cursor", cursor) assert len(rest["operation_handoffs"]) == 2 assert rest["operation_handoff_next_cursor"] is None assert rest["operation_handoff_pending_count"] == 22 @@ -1295,6 +1281,39 @@ def test_inbox_uses_shared_recovery_priority_and_explicit_overflow( store.root.parent.parent, GOAL_ID, "other-agent", operation_cursor=cursor ) + root = store.root.parent.parent + registry = json.loads(service.registry_path.read_text()) + registry["goals"][0]["coordination"]["registered_agents"].append("fixture-reviewer") + service.registry_path.write_text(json.dumps(registry)) + peer = request_peer(root, service.registry_path, GOAL_ID, EXECUTION_ACTOR["agent_id"], + "fixture-reviewer", "review-fixture", {"schema_version": "collaboration_brief_v0", + "purpose": "Confirm the test boundary", "context": "Isolated review fixture", + "constraints": [], "inputs": [], "acceptance": ["Report the observations"], + "return_requirement": "Reply to the requester"}) + peer_id = peer["request_id"] + acknowledge(root, GOAL_ID, "fixture-reviewer", peer_id, "adopt", "Fixture inspection") + report(root, GOAL_ID, "fixture-reviewer", peer_id, "conclusion", "The isolated check passed.") + first = read_inbox("--attention-only") + assert [row["request_id"] for row in first["peer_returns"]["items"]] == [peer_id] + request_cursor = first["next_cursor"] + operation_cursor = first["operation_handoff_next_cursor"] + assert request_cursor and operation_cursor + # The overflow instruction resumes operation paging without --attention-only. + assert operation_cursor == cursor + resumed = read_inbox("--operation-cursor", operation_cursor) + outgoing = read_inbox("--attention-only", "--cursor", request_cursor) + operation = read_inbox("--attention-only", "--operation-cursor", operation_cursor) + combined = read_inbox("--attention-only", "--cursor", request_cursor, "--operation-cursor", operation_cursor) + assert combined["open_request_summaries"] == outgoing["open_request_summaries"] + assert [row["request_id"] for row in combined["open_request_summaries"]] == [peer_id] + assert "operation_handoffs" not in outgoing + assert len(operation["operation_handoffs"]) == 2 + assert resumed["operation_handoffs"] == operation["operation_handoffs"] + assert combined["operation_handoffs"] == operation["operation_handoffs"] + assert combined["operation_handoff_next_cursor"] is None and combined["operation_handoff_pending_count"] == 22 + assert combined["items"] == [] and "peer_returns" not in combined + assert store.path.read_bytes() == before + def test_operation_preview_arms_one_canonical_gate_and_local_apply_cannot_claim( tmp_path: Path, diff --git a/tests/test_delegation_turn_context.py b/tests/test_delegation_turn_context.py index 047e30a0bd..4cdcc30fd8 100644 --- a/tests/test_delegation_turn_context.py +++ b/tests/test_delegation_turn_context.py @@ -133,6 +133,136 @@ def test_peer_return_deferral_survives_until_a_later_turn(flow): assert agenda(root, registry)["return_attention"]["count"] == 0 +@pytest.mark.skipif(os.name != "posix", reason="exercise the rendered POSIX host command") +def test_before_work_reader_preserves_delivered_partial_work_without_repeating_the_brief(flow): + root, registry, store, create = flow + remainder = {"summary": "Run the remaining validation", "resume_when": "The isolated build is ready"} + delivered = {} + for index in range(4): + brief = { + "schema_version": "collaboration_brief_v0", "purpose": f"Verify artifact {index}", + "context": ("Detailed original acceptance evidence. " * 130).strip(), + "constraints": [], "inputs": [], "acceptance": ["Return the checked artifact."], + "return_requirement": "Report to the original conversation.", + } + _, _, receipt = create(brief=brief) + rid = receipt["request_id"] + acknowledge(root, "research", "worker", rid, "adopt", "Continue validation") + report(root, "research", "worker", rid, "conclusion", "The first check passed.", + remaining_work=remainder) + delivered[rid] = brief + drain(root, registry, store, lambda *_: pytest.fail("local return does not use an external sender")) + # Preserve the original brief when the delivery is unreadable or points to another request. + unreadable, mismatched, matching, *_ = delivered + delivery_file = _root(root) / "replies" / unreadable / "conclusion.delivery.json" + assert delivery_file.is_file() + delivery_file.write_text("{invalid") + wrong_delivery = _root(root) / "replies" / mismatched / "conclusion.delivery.json" + original_delivery = wrong_delivery.read_bytes() + other_delivery = _root(root) / "replies" / matching / "conclusion.delivery.json" + wrong_message = json.loads(other_delivery.read_bytes())["message_id"] + assert wrong_message != json.loads(original_delivery)["message_id"] + wrong_delivery.write_text(json.dumps({**json.loads(original_delivery), "message_id": wrong_message})) + _, _, queued = create() + queued_id = queued["request_id"] + acknowledge(root, "research", "worker", queued_id, "adopt", "Continue validation") + report(root, "research", "worker", queued_id, "conclusion", "The first check passed.", + remaining_work=remainder) + _, _, fresh = create() + expected = {fresh["request_id"], queued_id, unreadable, mismatched} + + for _ in range(2): + dispatch = dispatch_turn_start_hooks([turn_start_hook(root, registry, "research", "worker")]) + route, = dispatch["required_reads"] + command = shlex.split(route["command"]) + assert "--attention-only" in command + native = subprocess.run(command, cwd=root, capture_output=True, timeout=60) + assert native.returncode == 0, native.stderr + view = json.loads(native.stdout) + assert {row["request_id"] for row in view["items"]} == expected + compact = {row["request_id"]: row for row in view["unfinished_delegations"]["items"]} + assert set(compact) == set(delivered) | expected + assert all(compact[rid]["remaining_work"] == remainder for rid in delivered) + assert compact[mismatched]["step"] == "recover_evidence" + mismatched_item = next(row for row in view["items"] if row["request_id"] == mismatched) + assert mismatched_item["brief"] == delivered[mismatched] + assert "--attention-only" not in view["unfinished_delegations"]["read_command"] + + assert json.loads(wrong_delivery.read_bytes())["message_id"] == wrong_message + wrong_delivery.write_bytes(original_delivery) + restored = subprocess.run(command, cwd=root, capture_output=True, check=True, timeout=60) + restored_view = json.loads(restored.stdout) + assert {row["request_id"] for row in restored_view["items"]} == expected - {mismatched} + assert matching in {row["request_id"] for row in restored_view["open_request_summaries"]} + assert mismatched in {row["request_id"] for row in restored_view["open_request_summaries"]} + + entire = subprocess.run([arg for arg in command if arg != "--attention-only"], + cwd=root, capture_output=True, timeout=60) + assert entire.returncode == 0, entire.stderr + assert {row["request_id"] for row in json.loads(entire.stdout)["items"]} == set(delivered) | expected + assert len(native.stdout) < len(entire.stdout) + for rid, brief in delivered.items(): + exact = read_inbox(root, registry, "research", "worker", request_id=rid) + assert exact["items"][0]["brief"] == brief + + +@pytest.mark.skipif(os.name != "posix", reason="exercise the rendered POSIX host command") +def test_before_work_reader_requires_exact_peer_delivery(flow): + root, registry, _store, _create = flow + configured = json.loads(registry.read_text()) + configured["goals"][0]["coordination"]["registered_agents"].append("reviewer") + registry.write_text(json.dumps(configured)) + + def partial(name): + brief = {"schema_version": "collaboration_brief_v0", "purpose": name, + "context": f"Original brief for {name}", "constraints": [], "inputs": [], + "acceptance": ["Check the final package"], "return_requirement": "Return the result"} + rid = request(root, registry, "research", "worker", "reviewer", name, brief)["request_id"] + acknowledge(root, "research", "reviewer", rid, "adopt", "Review") + report(root, "research", "reviewer", rid, "conclusion", "The first check passed.", + remaining_work={"summary": "Check the final package", "resume_when": "The package is ready"}) + return rid, brief, _root(root) / "replies" / rid / "conclusion.delivery.json" + + first, _, first_delivery = partial("first-review") + read_inbox(root, registry, "research", "worker", turn_instance_id="turn-first") + first_receipt = json.loads(first_delivery.read_bytes()) + assert first_receipt["kind"] == "requester_cli_read" + second, second_brief, second_delivery = partial("second-review") + assert not second_delivery.exists() + + hook = dispatch_turn_start_hooks([turn_start_hook(root, registry, "research", "reviewer")]) + command = shlex.split(hook["required_reads"][0]["command"]) + assert "--attention-only" in command + legacy = {key: value for key, value in first_receipt.items() + if key not in {"request_id", "result_key"}} + wrong_result = {**first_receipt, "request_id": second, "result_key": "conclusion-00000001"} + for receipt in (legacy, first_receipt, wrong_result): + second_delivery.write_text(json.dumps(receipt)) + before = second_delivery.read_bytes() + view = json.loads(subprocess.run(command, cwd=root, capture_output=True, check=True, timeout=60).stdout) + assert [row["brief"] for row in view["items"]] == [second_brief] + assert [row["request_id"] for row in view["open_request_summaries"]] == [first] + compact = {row["request_id"]: row for row in view["unfinished_delegations"]["items"]} + assert compact[second]["step"] == "recover_evidence" + assert second_delivery.read_bytes() == before + + assert first_receipt["request_id"] == first + assert first_receipt["result_key"] == "conclusion" + with pytest.raises(ValueError, match="peer return delivery receipt scope mismatch"): + read_inbox(root, registry, "research", "worker", turn_instance_id="turn-recovery") + assert json.loads(second_delivery.read_bytes()) == wrong_result + + second_delivery.write_text(json.dumps(legacy)) + read_inbox(root, registry, "research", "worker", turn_instance_id="turn-recovery") + restored = json.loads(second_delivery.read_bytes()) + assert restored["request_id"] == second + assert restored["result_key"] == "conclusion" + assert restored["model_turn"]["turn_instance_id"] == "turn-recovery" + view = json.loads(subprocess.run(command, cwd=root, capture_output=True, check=True, timeout=60).stdout) + assert view["items"] == [] + assert {row["request_id"] for row in view["open_request_summaries"]} == {first, second} + + def test_invalid_receipt_and_invalid_entries_are_visible_as_unavailable(flow): root, registry, _store, create = flow _session, _turn, receipt = create() @@ -158,7 +288,7 @@ def test_separate_agent_has_no_access_to_another_receivers_agenda(flow): @pytest.mark.skipif(os.name != "posix", reason="native context delivery requires POSIX") @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("reader_output_bytes", [12_000, 64_000]) +@pytest.mark.parametrize("reader_output_bytes", [5_000, 64_000]) def test_unbound_cli_first_read_leaves_inbox_rows_to_its_required_read( tmp_path, monkeypatch, provider, reader_output_bytes, ): @@ -220,7 +350,9 @@ def test_unbound_cli_first_read_leaves_inbox_rows_to_its_required_read( read, = (row for row in first["/interaction_contract/agent_channel/required_reads"] if row.get("kind") == "operator_inbox") command = shlex.split(read["command"]) assert command[0] == str(console) - def invoke(argv, output_limit=12_000): + assert "--attention-only" in command + + def invoke(argv, output_limit=5_000): result = subprocess.run(argv, cwd=project, capture_output=True, timeout=40) assert result.returncode == 0, result.stderr assert 0 < len(result.stdout) <= output_limit @@ -271,7 +403,7 @@ def read_receipts(): if logical_pages == 1: reference_path.unlink() failed = subprocess.run(shlex.split(page["command"]), cwd=project, capture_output=True, timeout=40) - assert failed.returncode == 1 and len(failed.stdout) <= 12_000 + assert failed.returncode == 1 and len(failed.stdout) <= 5_000 assert "content" not in json.loads(failed.stdout) recovered = json.loads(invoke(direct, reader_output_bytes)) assert recovered["offset"] == 0 and recovered["sha256"] == pinned @@ -287,7 +419,7 @@ def read_receipts(): if cursor is None: break assert seen == request_ids and logical_pages == 2 and captured_pages > 1 - assert (largest_reader_output > 12_000) is (reader_output_bytes > 12_000) + assert (largest_reader_output > 5_000) is (reader_output_bytes > 5_000) _, saved = read_selection(view["recovery"]["command"] + " --select " + shlex.quote(address)) assert saved[address] == channel["work_context"]["sources"][index]["content"]["unfinished_delegations"] assert path.read_bytes() == original @@ -309,7 +441,7 @@ def test_large_inbox_does_not_fall_back_to_unbounded_output(flow): invocation = [sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry), "--runtime-root", str(root), "manager-inbox", "read", "--format", "markdown", "--goal-id", "research", "--agent-id", "worker"] result = subprocess.run(invocation, cwd=root, capture_output=True, timeout=40) - assert result.returncode == 1 and len(result.stdout) <= 12_000 + assert result.returncode == 1 and len(result.stdout) <= 5_000 output = result.stdout.decode() failure = json.loads(output.split("\n```json\n", 1)[1].removesuffix("\n```\n")) assert not failure["ok"] and not failure["read_complete"] @@ -346,7 +478,7 @@ def test_large_inbox_reader_commands_run_verbatim_in_powershell(flow, directory) opening = subprocess.run([*powershell, "-Command", required_read["command"]], cwd=root, env=environment, capture_output=True, timeout=60) assert opening.returncode == 0, opening.stderr - assert 0 < len(opening.stdout) <= 12_000 + assert 0 < len(opening.stdout) <= 5_000 markdown = opening.stdout.decode().replace("\r\n", "\n") view = json.loads(markdown.split("\n```json\n", 1)[1].removesuffix("\n```\n")) before = {p.relative_to(root): p.read_bytes() for p in _root(root).rglob("*.json")} @@ -357,7 +489,7 @@ def test_large_inbox_reader_commands_run_verbatim_in_powershell(flow, directory) output = subprocess.run([*powershell, "-Command", command], cwd=root, env=environment, capture_output=True, timeout=60) assert output.returncode == 0, output.stderr - assert 0 < len(output.stdout) <= 12_000 + assert 0 < len(output.stdout) <= 5_000 page = json.loads(output.stdout) assert page["ok"] and page["offset"] == len(original) and page["sha256"] == view["sha256"] original.extend(page["content"].encode()) @@ -439,7 +571,8 @@ def run(*arguments): }) acknowledge(root, "research", "reviewer", peer["request_id"], "adopt", "Review the artifact", registry=registry) report(root, "research", "reviewer", peer["request_id"], "conclusion", "The artifact retains an explicit limit.", registry=registry) - code, inbox = run(*prefix, "manager-inbox", "read", "--goal-id", "research", "--agent-id", "worker") + code, inbox = run(*prefix, "manager-inbox", "read", "--goal-id", "research", "--agent-id", "worker", + "--attention-only") assert code == 0 and inbox["ok"] assert inbox["peer_returns"]["items"][0]["request_id"] == peer["request_id"] code, tracking = run(*prefix, "manager-inbox", "status", "--goal-id", "research", "--agent-id", "worker", @@ -499,9 +632,10 @@ def run(*arguments): else: assert packet["schema_version"] == "loopx_turn_envelope_v1" channel = packet["interaction_contract"]["agent_channel"] - source = next(row for row in channel["work_context"]["sources"] if row.get("hook_id") == "manager.context_inbox") + work_context = channel["work_context"] + source = next(row for row in work_context["sources"] if row.get("hook_id") == "manager.context_inbox") content, required_reads = source["content"], channel["required_reads"] - assert channel["work_context"]["complete"] is True + assert work_context["complete"] is True assert content["read_complete"] is False rows = {row["request_id"]: row for row in content["unfinished_delegations"]["items"]} assert set(rows) == {receipt["request_id"], queued["request_id"], peer["request_id"]} @@ -515,7 +649,8 @@ def run(*arguments): manager_argv = shlex.split(manager_read["command"]) assert "manager-inbox" in manager_argv and "read" in manager_argv assert "--turn-instance-id" not in manager_argv - assert "markdown" in manager_argv + assert "--attention-only" in manager_argv + assert manager_argv[manager_argv.index("--format") + 1] == "markdown" assert "Continue the linked work" not in json.dumps(content) assert os.environ["LOOPX_CONTEXT_DELIVERY"] == parent_context if delivery == "native_files":