diff --git a/docs/reference/required-work-context.md b/docs/reference/required-work-context.md index d470e8dacd..4ac9a318fe 100644 --- a/docs/reference/required-work-context.md +++ b/docs/reference/required-work-context.md @@ -221,9 +221,17 @@ 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. +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. @@ -434,8 +442,15 @@ full/delta 字节比较计入这些 reader 命令元数据;既有进程内引 首读包含有界 `unfinished_delegations` 投影和 `read_complete` 标记。已准入的普通 工作 Turn 若有大型委派摘要、扫描完整,且必读列表中有同一条管家收件箱命令,首读保留 收发请求计数、扫描状态和必读命令。扫描完整但摘要达到展示上限时,首读同时保留精确的 -省略数量与核对指引。逐条请求通过必读命令及其现有分页游标交付。原摘要仍可从同一 -捕获取回。扫描不完整、扫描记录不可读或没有匹配必读命令时,首读保留完整摘要。 +省略数量与核对指引。逐条请求通过必读命令及其现有分页游标交付。`--attention-only` +下,需要原简报的收件仍在 `items`,最近一次结论已送达且有剩余工作的收件在 +`open_request_summaries`。只有摘要的页也继续跟随 `next_cursor`,收件读完后 +沿同一游标查阅未结外发委派。只含外发摘要的续页不送达或消费结果。 +`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 ac38d7bf00..7a4138a195 100644 --- a/loopx/capabilities/manager_context/README.md +++ b/loopx/capabilities/manager_context/README.md @@ -44,6 +44,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 diff --git a/loopx/capabilities/manager_context/__init__.py b/loopx/capabilities/manager_context/__init__.py index 3442c14bf1..8bfed0ca03 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 117519a81a..b8df03b909 100644 --- a/loopx/cli_commands/manager_inbox.py +++ b/loopx/cli_commands/manager_inbox.py @@ -236,6 +236,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" ) @@ -263,6 +265,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") @@ -465,7 +470,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_read.ts b/loopx/control_plane/collaboration/inbox_read.ts index df8a4db1a3..be7b15b0b9 100644 --- a/loopx/control_plane/collaboration/inbox_read.ts +++ b/loopx/control_plane/collaboration/inbox_read.ts @@ -26,6 +26,10 @@ 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; follow next_cursor to reach their summaries."; type InboxSource = Readonly<{root: string; goal: string; agent: string; scope: JsonObject; exact: boolean; recipient?: JsonObject}>; type ReturnDelivery = Readonly<{key: string; request: JsonObject; reply: JsonObject}>; @@ -202,7 +206,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; @@ -213,29 +241,50 @@ 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]); + const scope = scopeFor(cursorKind); + 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: scope, + _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 nextCursor = moreIncoming ? `1:${scope}:${page.at(-1)!.item.request_id}` + : outgoingScope === null ? null : (await outgoingSummaryPage(source, outgoingScope, "", 0)).next_cursor; + 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)} : {}), + has_more: nextCursor !== null, next_cursor: nextCursor, _cursor_scope: scope, + 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 { @@ -369,6 +418,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[] = []; @@ -379,28 +480,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(); } } @@ -546,6 +630,12 @@ export async function readCollaborationInbox(params: JsonObject): Promise { + 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({status: "delivered"})); + + 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); +}); diff --git a/tests/test_delegation_turn_context.py b/tests/test_delegation_turn_context.py index ab46e15a5d..86b670c2e8 100644 --- a/tests/test_delegation_turn_context.py +++ b/tests/test_delegation_turn_context.py @@ -133,6 +133,62 @@ 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")) + # One formerly delivered reply can no longer be verified. + unreadable, *_ = delivered + delivery_file = _root(root) / "replies" / unreadable / "conclusion.delivery.json" + assert delivery_file.is_file() + delivery_file.write_text("{invalid") + _, _, 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} + + 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 "--attention-only" not in view["unfinished_delegations"]["read_command"] + + 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 + + def test_invalid_receipt_and_invalid_entries_are_visible_as_unavailable(flow): root, registry, _store, create = flow _session, _turn, receipt = create() @@ -213,6 +269,7 @@ def test_unbound_cli_first_read_leaves_inbox_rows_to_its_required_read(tmp_path, 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) + assert "--attention-only" in command def invoke(argv): result = subprocess.run(argv, cwd=project, capture_output=True, timeout=40) assert result.returncode == 0, result.stderr @@ -424,7 +481,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", @@ -484,9 +542,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"]} @@ -500,7 +559,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":