diff --git a/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.md b/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.md index 762de909ec..fdb5bd04a0 100644 --- a/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.md +++ b/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.md @@ -39,3 +39,12 @@ Integration base: `d29ec8bf2a105aac24629bcbf3dfb7c97aea51fe`. Source candidate: Candidate `ff4e94459` integrates latest base `ce4cfc1ce`. Its four changed production files remain byte-identical to `c137daecc`. Upstream now returns capture navigation; the existing product reader verifies and opens the complete current projection. Actual File/SQLite entrypoint readbacks on this base preserve complete work context and event identity; logical Effect calls are 74→73 in these newer observations. Six historical direct-stdout assertions fail on both latest main and candidate because they still expect an inline `should_run` field. Both selected runs have 2 pass /6 fail, with the same identities and failure boundary. Those failures remain evidence. Earlier installed/cost measurements retain their stated revision; latest-main full cost and Host qualification remain held. + +### Complete Turn CLI Vision audit + +The Complete Turn writer replaces an exact duplicate CLI audit view with a typed +reference to the root in the same capture. The existing capture reader restores +the CLI audit through the interaction view before address selection and pinned +first-read rendering. The TypeScript selector still validates addresses. File and +SQLite tests exercise the generated first read, child selects and field discovery +against the same saved capture. The original capture hash remains unchanged. diff --git a/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.zh-CN.md b/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.zh-CN.md index c1eeda5117..7ea2a4e548 100644 --- a/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.zh-CN.md +++ b/docs/architecture/rfcs/ledger/typescript-control-plane-migration-v0/2026-11-04-selected-context-source-read.zh-CN.md @@ -39,3 +39,10 @@ 候选 `ff4e94459` 集成最新基线 `ce4cfc1ce`,四个改动生产文件与 `c137daecc` 字节一致。上游现在返回 capture 导航引用;原有产品读取器校验后打开完整当前观察。在该基线上,实际 File/SQLite 入口的完整工作上下文与事件身份保持一致;业务 Effect 调用在这组较新观察中为74→73。 六项旧断言仍直接读取 stdout 顶层 `should_run`,因此最新 main 和候选均为2通过/6失败,失败身份与边界相同。失败继续保留。此前安装包和成本测量保留各自版本;不声称最新主干的完整成本或 Host 资格已通过。 + +### Complete Turn 的 CLI Vision 审核 + +Complete Turn 写入端将完全重复的 CLI 审核视图替换为指向同一捕获内根审核的类型化引用。 +现有捕获读取器复用交互契约的 CLI 视图,在地址选择和绑定首读渲染前还原该审核。 +TypeScript 选择器继续校验地址。File 和 SQLite 测试对同一份保存的捕获验证生成的首读、 +子字段选择和字段发现,原捕获摘要保持不变。 diff --git a/docs/reference/protocols/quota-cli-hot-path-compaction-v0.md b/docs/reference/protocols/quota-cli-hot-path-compaction-v0.md index 8030a685e8..e846595780 100644 --- a/docs/reference/protocols/quota-cli-hot-path-compaction-v0.md +++ b/docs/reference/protocols/quota-cli-hot-path-compaction-v0.md @@ -127,6 +127,25 @@ projection. Candidate lists and peer action lists retain counts and point to `--include-detail vision`; `--include-detail all` restores every supported detail section. +Complete Turn output may also share the narrower +`interaction_contract.cli_channel.vision_continuation_audit` when its entire +value equals the CLI view of the root audit. The wire reference uses +`projection_ref: "$.vision_continuation_audit"` and +`projection_view: "cli_channel"`. A different channel obligation stays inline. +The native first read and digest-pinned `quota context-read --select` and +`--list` resolve the CLI view at its original address, including nested +obligations such as `required_before_closeout`. An explicit empty pointer +returns the signed source object. The capture and its digest bind subsequent +reads and their native section observations. + +Complete Turn 也可以共享与根审核的 CLI 视图完全相同的 +`interaction_contract.cli_channel.vision_continuation_audit`。传输引用包含 +`projection_ref: "$.vision_continuation_audit"` 和 +`projection_view: "cli_channel"`。通道义务有差异时保留原文。 +原生首读和绑定捕获摘要的 `quota context-read --select`、`--list` 都在原地址 +还原 CLI 视图,支持读取 `required_before_closeout` 等子字段。显式选择空指针会返回 +带签名的源对象。后续读取及其原生区段观察均以原捕获及其摘要为准。 + When a bounded next-action label still carries the complete Task again in `agent_lane_next_action.title`, the default view may replace that exact duplicate with `title_ref`. The reference resolves to `text` or `title` in the single diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 20dd18d001..68f669644e 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -997,7 +997,7 @@ export function composeCompleteTurnDecision(value: unknown): JsonObject { source = referenceReplanAuthoring(source, sourceIdentity); source = referenceExploreGuidance(source); source = referenceCurrentTaskTitle(source); - source = referenceVisionContinuation(source, sourceIdentity); + source = referenceVisionContinuation(source, sourceIdentity, true); source = referenceQuotaSummaryLanes(source, sourceIdentity); return sealCompleteTurnDecision(source, request.scheduler_execution_args, sourceIdentity); } diff --git a/loopx/control_plane/quota/turn_envelope_references.ts b/loopx/control_plane/quota/turn_envelope_references.ts index 6198416b4b..9849d9c4c1 100644 --- a/loopx/control_plane/quota/turn_envelope_references.ts +++ b/loopx/control_plane/quota/turn_envelope_references.ts @@ -305,12 +305,28 @@ export function referenceExploreGuidance(payload: JsonObject): JsonObject { work_context: {...context, sources}}}}; } -/** Keep the complete vision audit once. These existing projection references - * share identical facts only; a channel-specific obligation is never a summary - * of the root. The old display adapter delegates here before adding metadata. */ +const VISION_AUDIT_PATH = "$.vision_continuation_audit"; +const CLI_VISION_AUDIT_REFERENCE = { + projection_ref: VISION_AUDIT_PATH, projection_view: "cli_channel", required: true, +}; + +/** The writer checks the entire view against the root fields before sharing + * them. The capture reader uses the existing interaction owner to present it. */ +function cliVisionAuditView(owner: JsonObject): JsonObject | undefined { + if (owner.schema_version !== "vision_continuation_audit_v0" || owner.required !== true) return undefined; + const view = pickOwn(owner, ["required", "required_before_closeout", "recommended_action"]); + const judge = object(owner.vision_gap_judge); + if (Object.keys(judge).length) view.vision_gap_judge = pickOwn(judge, [ + "done", "decision", "reason", "agent_judge_instruction", "evidence_read_instruction", + "registry_read_instruction", "done_only_when", "continue_when", "otherwise", + ]); + return view; +} + +/** Exact copies use the complete root as their projection. */ function visionAuditReference(audit: JsonObject): JsonObject { const reference: JsonObject = { - projection_ref: "$.vision_continuation_audit", + projection_ref: VISION_AUDIT_PATH, ...pickOwn(audit, ["schema_version", "required", "decision"]), }; if (typeof audit.vision_gap_judge === "object" && audit.vision_gap_judge !== null && @@ -342,12 +358,15 @@ function mapNestedVisionAudits(payload: JsonObject, export function requireVisionAuditReferences(payload: JsonObject): void { const owner = object(payload.vision_continuation_audit); - const chained = Object.hasOwn(owner, "projection_ref") || Object.hasOwn(object(owner.vision_gap_judge), "projection_ref"); - if (chained) throw new EffectRuntimeRequestError("Vision audit reference requires a complete inline root owner"); - mapNestedVisionAudits(payload, audit => { - if (Object.hasOwn(audit, "projection_ref") || Object.hasOwn(object(audit.vision_gap_judge), "projection_ref")) { + const hasReference = (audit: JsonObject) => Object.hasOwn(audit, "projection_ref") || + Object.hasOwn(audit, "projection_view") || Object.hasOwn(object(audit.vision_gap_judge), "projection_ref"); + if (hasReference(owner)) throw new EffectRuntimeRequestError("Vision audit reference requires a complete inline root owner"); + mapNestedVisionAudits(payload, (audit, path) => { + if (hasReference(audit)) { + const expected = audit.projection_view === "cli_channel" && path[1] === "cli_channel" && cliVisionAuditView(owner) + ? CLI_VISION_AUDIT_REFERENCE : visionAuditReference(owner); if (!Object.keys(owner).length || - JSON.stringify(canonicalValue(audit)) !== JSON.stringify(canonicalValue(visionAuditReference(owner)))) { + JSON.stringify(canonicalValue(audit)) !== JSON.stringify(canonicalValue(expected))) { throw new EffectRuntimeRequestError("Vision audit reference must match its complete inline root owner without conflicting facts"); } } @@ -356,16 +375,27 @@ export function requireVisionAuditReferences(payload: JsonObject): void { } export function referenceVisionContinuation(payload: JsonObject, - identity = contextSourceIdentity(payload)): JsonObject { + identity = contextSourceIdentity(payload), shareCliView = false): JsonObject { requireVisionAuditReferences(payload); const owner = object(payload.vision_continuation_audit); if (!Object.keys(owner).length) return payload; const encoded = JSON.stringify(canonicalValue(owner)), reference = visionAuditReference(owner); - // A short audit is cheaper inline. Do not create a reference merely to count sharing. - if (Buffer.byteLength(encoded, "utf8") <= Buffer.byteLength(JSON.stringify(reference), "utf8")) return payload; + const smallerThanRoot = Buffer.byteLength(JSON.stringify(reference)) < Buffer.byteLength(encoded); + const cliView = shareCliView ? cliVisionAuditView(owner) : undefined; + // A short audit is cheaper inline. + if (!smallerThanRoot && !cliView) return payload; const source = identity(owner, ["vision_continuation_audit"]); - return mapNestedVisionAudits(payload, (audit, path) => - identity(audit, path) === source ? structuredClone(reference) : audit); + const cliIdentity = cliView && identity(cliView, ["vision_continuation_audit"]); + const cliReferenceBytes = Buffer.byteLength(JSON.stringify(CLI_VISION_AUDIT_REFERENCE)); + return mapNestedVisionAudits(payload, (audit, path) => { + const candidate = identity(audit, path); + if (smallerThanRoot && candidate === source) return structuredClone(reference); + if (path[1] === "cli_channel" && candidate === cliIdentity && + cliReferenceBytes < Buffer.byteLength(JSON.stringify(audit))) { + return {...CLI_VISION_AUDIT_REFERENCE}; + } + return audit; + }); } /** The verified current Task is the only owner of a shared lane title. Keep diff --git a/loopx/control_plane/turn_driver/decision_capture.py b/loopx/control_plane/turn_driver/decision_capture.py index 137c9c53e7..eca7d27416 100644 --- a/loopx/control_plane/turn_driver/decision_capture.py +++ b/loopx/control_plane/turn_driver/decision_capture.py @@ -13,7 +13,7 @@ from dataclasses import dataclass from pathlib import Path -from ..quota.turn_envelope import bind_turn_decision_capture +from ..quota.turn_envelope import COMPLETE_TURN_DECISION_VERSION, bind_turn_decision_capture from ..quota.error_codes import QuotaCommandValidationError from ..content_digest import BARE_SHA256_PATTERN from .native_context_profile import ( @@ -731,12 +731,14 @@ def _context_selection_bytes(payload: dict[str, Any], selections: list[dict[str, """Render TS-verified addresses from the original, digest-checked values.""" if text_append is not None and (list_fields or not isinstance(text_append, dict)): raise ValueError("observed text append requires a selected value") + presentation = context_vision_audit_view(payload) views: list[dict[str, Any]] = [] presented: list[str] = [] append_rendered = False for item in selections: - selected: Any = payload path, pointer = item["path"], item["pointer"] + # The empty pointer still returns the signed Complete Turn source. + selected: Any = presentation if path else payload for key in path: if type(key) is str and isinstance(selected, dict) and key in selected: selected = selected[key] @@ -754,7 +756,7 @@ def _context_selection_bytes(payload: dict[str, Any], selections: list[dict[str, presented.append(pointer) append_rendered = True elif list_fields: - views.append({"pointer": pointer, "fields": context_index_fields(payload, item["children"])}) + views.append({"pointer": pointer, "fields": context_index_fields(presentation, item["children"])}) elif opening_context_instruction is not None and pointer == "/context_details/instruction": presented.append(pointer) views.append({"pointer": pointer, "value": opening_context_instruction, @@ -830,6 +832,35 @@ class ContextSelectionDigestChanged(ValueError): """The rendered selection no longer matches its recorded digest.""" +def context_vision_audit_view(payload: dict[str, Any]) -> dict[str, Any]: + # Before planning explicit addresses or replaying a pinned native read, + # restore the exact named view from the same capture. Its bytes and digest + # remain the authority, and unrelated historical references stay literal. + if payload.get("schema_version") != COMPLETE_TURN_DECISION_VERSION: + return payload + interaction = payload.get("interaction_contract") + if not isinstance(interaction, dict): + return payload + cli = interaction.get("cli_channel") + if not isinstance(cli, dict): + return payload + audit = cli.get("vision_continuation_audit") + if not (isinstance(audit, dict) and audit.get("projection_view") == "cli_channel"): + return payload + owner = payload.get("vision_continuation_audit") + if (audit != {"projection_ref": "$.vision_continuation_audit", "projection_view": "cli_channel", "required": True} + or audit["required"] is not True + or not isinstance(owner, dict) or owner.get("schema_version") != "vision_continuation_audit_v0" + or owner.get("required") is not True or "projection_ref" in owner or "projection_view" in owner + or (isinstance(judge := owner.get("vision_gap_judge"), dict) and "projection_ref" in judge)): + raise ValueError("CLI Vision audit view requires a complete inline owner in the same capture") + from ..work_items.interaction_contract import cli_vision_audit_view + + return {**payload, "interaction_contract": {**interaction, "cli_channel": { + **cli, "vision_continuation_audit": cli_vision_audit_view(owner), + }}} + + def context_selection_view(payload: dict[str, Any], *, select: list[str] | None, initial_read: bool, list_fields: bool, list_depth: int | None, expected_sha256: str | None, preserve_selection_order: bool = False, @@ -848,8 +879,9 @@ def context_selection_view(payload: dict[str, Any], *, select: list[str] | None, else: from ..quota.turn_envelope import _turn_envelope_result - context = payload if initial_read else context_selection_transport( - payload, select, list_fields=list_fields, list_depth=list_depth) + view = context_vision_audit_view(payload) + context = view if initial_read else context_selection_transport( + view, select, list_fields=list_fields, list_depth=list_depth) selection = {"initial_read": True} if initial_read else {"select": select} depth = {"list_depth": list_depth} if list_depth is not None else {} order = {"preserve_selection_order": True} if preserve_selection_order else {} diff --git a/loopx/control_plane/turn_driver/native_context_selection.py b/loopx/control_plane/turn_driver/native_context_selection.py index 728129493b..118e905a53 100644 --- a/loopx/control_plane/turn_driver/native_context_selection.py +++ b/loopx/control_plane/turn_driver/native_context_selection.py @@ -9,8 +9,9 @@ from pathlib import Path from typing import Any -from .decision_capture import (read_context_capture_file, read_context_read_reference, - context_selection_view) +from .decision_capture import ( + context_selection_view, context_vision_audit_view, read_context_capture_file, read_context_read_reference, +) def _terminal_range_seen(state: dict[str, Any], digest: str, total: int) -> bool: @@ -142,7 +143,8 @@ def verified_context_selection( # Native hook processes need not inherit the shell's CODEX_THREAD_ID. if observation_current(observation, physical, source_digest, hook_session=state.get("session_id")): inherited = observation["fields"] - sections = _turn_envelope_result("context_read_sections", context=source, select=literal_pointers, + sections = _turn_envelope_result("context_read_sections", + context=context_vision_audit_view(source), select=literal_pointers, consumed_pointers=inherited, **({"observed_text_append": text_append} if inherited and text_append is not None else {}))["sections"] return {**page, "schema_version": "context_capture_page_v1", "sha256": view_digest, diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 320a4b3cad..69521a40ae 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -1618,15 +1618,8 @@ def _attach_interaction_post_writeback_actions( cli_channel["post_writeback_actions"] = actions -def _attach_interaction_vision_continuation_audit( - agent_channel: dict[str, object], - cli_channel: dict[str, object], - payload: Mapping[str, object], -) -> None: - vision_continuation_audit = _as_mapping(payload.get("vision_continuation_audit")) - if not vision_continuation_audit.get("required"): - return - agent_channel["vision_continuation_audit"] = vision_continuation_audit +def cli_vision_audit_view(vision_continuation_audit: Mapping[str, object]) -> dict[str, object]: + """Return the CLI-owned view of the complete Vision audit.""" cli_audit: dict[str, object] = { "required": True, "required_before_closeout": vision_continuation_audit.get("required_before_closeout") or [], @@ -1646,7 +1639,19 @@ def _attach_interaction_vision_continuation_audit( "continue_when": vision_gap_judge.get("continue_when") or [], "otherwise": vision_gap_judge.get("otherwise"), } - cli_channel["vision_continuation_audit"] = cli_audit + return cli_audit + + +def _attach_interaction_vision_continuation_audit( + agent_channel: dict[str, object], + cli_channel: dict[str, object], + payload: Mapping[str, object], +) -> None: + vision_continuation_audit = _as_mapping(payload.get("vision_continuation_audit")) + if not vision_continuation_audit.get("required"): + return + agent_channel["vision_continuation_audit"] = vision_continuation_audit + cli_channel["vision_continuation_audit"] = cli_vision_audit_view(vision_continuation_audit) def _attach_interaction_vision_wait_state( diff --git a/tests/control_plane/test_cli_output_budget.py b/tests/control_plane/test_cli_output_budget.py index 37cad32ed2..f59b624355 100644 --- a/tests/control_plane/test_cli_output_budget.py +++ b/tests/control_plane/test_cli_output_budget.py @@ -9,11 +9,13 @@ import tempfile from dataclasses import dataclass, replace from datetime import datetime, timezone +from hashlib import sha256 from pathlib import Path import pytest from loopx.cli import main as cli_main +from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision from loopx.control_plane.scheduler.execution_context import SchedulerRuntimeProfile from loopx.control_plane.testing.canary_harness import import_fixture_authority from loopx.control_plane.testing.cli_output_budget import ( @@ -1177,6 +1179,72 @@ def test_unmigrated_malformed_todo_state_stays_bounded_and_refuses_ordinary_read assert state_file.read_bytes() == before +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_complete_turn_shares_vision_audit_with_exact_native_and_stateless_reads( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + from loopx.control_plane.turn_driver.decision_capture import read_context_read_reference + from loopx.control_plane.turn_driver.native_context_selection import verified_context_selection + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + from tests.control_plane.codex_checkpoint_fixture import selected_context_values + + with _stable_budget_fixture_root(tmp_path / "complete-vision-audit") as stable_root: + isolate_sqlite_runtime(stable_root, monkeypatch) + project, runtime, registry, _ = _write_fixture(stable_root, SCENARIOS[1], include_agent_vision=True) + import_fixture_authority(registry, GOAL_ID, provider=provider) + monkeypatch.chdir(project) + common = ["--format", "json", "--registry", str(registry), "--runtime-root", str(runtime)] + guard = common + ["quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_IDS[0]] + fixed_route = ["--cli-bin", "/fixture/bin/loopx"] + code, text = _invoke_cli(fixed_route + guard + ["--complete-turn", "--context-delivery", "off"]) + assert code == 0, text + assert len(text) <= CLI_OUTPUT_MODE_VARIANT_BY_ID["quota_should_run_vision_detail"].max_chars["json"] + payload = json.loads(text) + assert_complete_turn_decision(payload) + root_audit = payload["vision_continuation_audit"] + cli_audit = payload["interaction_contract"]["cli_channel"]["vision_continuation_audit"] + assert cli_audit == {"projection_ref": "$.vision_continuation_audit", + "projection_view": "cli_channel", "required": True} + assert root_audit["required_before_closeout"] and root_audit["vision_gap_judge"]["registry_read_instruction"] + + captures = stable_root / "decisions" + captures.mkdir(mode=0o700) + code, text = _invoke_cli(guard + ["--codex-app", "--context-delivery", "on", + "--turn-instance-id", "fixture-vision-audit", "--decision-output-root", str(captures)]) + assert code == 0, text + navigation = json.loads(text) + _, reference = read_context_read_reference(navigation["recovery"]["reference_file"]) + capture = Path(reference["path"]) + original = capture.read_bytes() + assert sha256(original).hexdigest() == reference["sha256"] + assert json.loads(original)["interaction_contract"]["cli_channel"]["vision_continuation_audit"] == cli_audit + section = "/interaction_contract/cli_channel/vision_continuation_audit" + child = section + "/required_before_closeout" + judge = section + "/vision_gap_judge/registry_read_instruction" + initial, _, _ = read_pinned_cli_body(navigation["first_read_command"]) + first = selected_context_values(initial) + assert first[child] == root_audit["required_before_closeout"] + assert first[judge] == root_audit["vision_gap_judge"]["registry_read_instruction"] + + select = common + ["quota", "context-read", "--capture-file", str(capture), + "--capture-sha256", reference["sha256"]] + code, text = _invoke_cli(select + ["--select", child, "--select", judge]) + assert code == 0, text + page = json.loads(text) + values = selected_context_values(page["content"]) + assert values[child] == first[child] and values[judge] == first[judge] + observation = verified_context_selection({"source_recovery": reference}, page) + assert observation is not None and observation["source_sha256"] == reference["sha256"] + assert set(observation["selected_pointers"]) == {child, judge} + code, text = _invoke_cli(select + ["--select", section, "--list", "--list-depth", "2"]) + assert code == 0, text + fields = json.loads(json.loads(text)["content"])["selections"][0]["fields"] + assert {child, judge} <= {field["pointer"] for field in fields} + whole, _, _ = read_pinned_cli_body(navigation["recovery"]["command"] + " --select ''") + assert json.loads(whole)["selections"] == [{"pointer": "", "value": json.loads(original)}] + assert capture.read_bytes() == original + + def test_quota_cli_keeps_complete_vision_rules_with_reachable_duplicate_refs( tmp_path: Path, ) -> None: diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts index a3a21c16be..dd7aa32270 100644 --- a/tests/control_plane_ts/turn_envelope.test.ts +++ b/tests/control_plane_ts/turn_envelope.test.ts @@ -25,6 +25,8 @@ import {projectQuotaDiagnostics, referenceQuotaSummaryLanes, resolveQuotaSummary from "../../loopx/control_plane/quota/diagnostic_projection.ts"; import { controllerRequest } from "../../loopx/control_plane/turn_driver/loop_controller.ts"; import {turnScopedCliSettlementPlan} from "../../loopx/control_plane/quota/settlement_plan.ts"; +import {referenceVisionContinuation, requireVisionAuditReferences} + from "../../loopx/control_plane/quota/turn_envelope_references.ts"; test("normal-work initial navigation stays scoped while other reads keep discovery", () => { const source = payload(); @@ -925,6 +927,31 @@ test("vision closeout obligations survive projection and signature mutation", () assert.deepEqual(source, before); }); +test("only an exact complete CLI Vision view shares its required audit", () => { + const clauses = ["Read and verify the registered original Vision source.".repeat(12)]; + const view = {required: true, required_before_closeout: clauses, recommended_action: "Continue."}; + const root = {schema_version: "vision_continuation_audit_v0", ...view, acceptance_gaps: ["open"]}; + const source = (audit: JsonObject) => ({vision_continuation_audit: root, interaction_contract: { + agent_channel: {vision_continuation_audit: root}, cli_channel: {vision_continuation_audit: audit}, + }}); + const getCli = (result: JsonObject) => + ((result.interaction_contract as JsonObject).cli_channel as JsonObject).vision_continuation_audit; + const exact = source(view); + const shared = referenceVisionContinuation(exact, undefined, true); + const reference = {projection_ref: "$.vision_continuation_audit", projection_view: "cli_channel", required: true}; + assert.deepEqual(getCli(shared), reference); + assert.deepEqual(shared.vision_continuation_audit, root); + assert.deepEqual(referenceVisionContinuation(shared, undefined, true), shared); + assert.deepEqual(getCli(referenceVisionContinuation(exact)), view); + for (const changed of [{...view, required_before_closeout: ["Shorter."]}, + {...view, new_channel_obligation: "Read the omitted evidence."}]) { + assert.deepEqual(getCli(referenceVisionContinuation(source(changed), undefined, true)), changed); + } + assert.throws(() => requireVisionAuditReferences(source({...reference, required: false})), /complete inline root owner/); + assert.throws(() => requireVisionAuditReferences({...shared, vision_continuation_audit: reference}), + /complete inline root owner/); +}); + test("absent vision audit retains the existing envelope shape", () => { const source = payload(); const envelope = buildTurnEnvelope({payload: source,