diff --git a/loopx/cli_commands/quota_presentation.py b/loopx/cli_commands/quota_presentation.py index 2d2d95abea..0492b66f5d 100644 --- a/loopx/cli_commands/quota_presentation.py +++ b/loopx/cli_commands/quota_presentation.py @@ -16,13 +16,47 @@ def compose_quota_work_contract(payload: dict[str, object], args: argparse.Names """Compose Complete Turn sources before capture and display.""" if args.quota_command != "should-run" or not isinstance(payload.get("interaction_contract"), Mapping): return payload + from ..command_invocation import current_loopx_cli_argv from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError from ..control_plane.quota.error_codes import QuotaDecisionTransportError from ..control_plane.quota.turn_envelope import compose_turn_decision + from .quota_request import quota_detail_sections_from_args + detail_sections = quota_detail_sections_from_args(args) + capture_reference_file = ( + str(capture_directory / "decision.reader.json") + if capture_directory is not None + else None + ) + + def _anchor_existing_path(value: object) -> str | None: + if not isinstance(value, str) or not value.strip(): + return None + candidate = Path(value).expanduser() + if candidate.is_absolute() or not candidate.exists(): + return None + return str(candidate.resolve()) + + cli_registry = _anchor_existing_path(payload.get("registry")) + cli_runtime_root = _anchor_existing_path(payload.get("runtime_root")) try: - return compose_turn_decision(payload, scheduler_execution_context=scheduler_context, - composed_settlement=True) + return compose_turn_decision( + payload, + scheduler_execution_context=scheduler_context, + composed_settlement=True, + include_vision_detail=( + "vision" in detail_sections + or getattr(args, "context_delivery", None) == "off" + ), + include_goal_acceptance_detail=( + "goal_acceptance" in detail_sections + or getattr(args, "context_delivery", None) == "off" + ), + cli_argv=current_loopx_cli_argv(), + capture_reference_file=capture_reference_file, + cli_registry=cli_registry, + cli_runtime_root=cli_runtime_root, + ) except (EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc: from .quota_capture import capture_decision from .quota_failure_report import quota_decision_transport_diagnostic diff --git a/loopx/cli_commands/quota_registration.py b/loopx/cli_commands/quota_registration.py index 4824de9580..a4dd4927d6 100644 --- a/loopx/cli_commands/quota_registration.py +++ b/loopx/cli_commands/quota_registration.py @@ -103,9 +103,9 @@ def register_quota_command( help=( "Include one command-specific cold-path detail section. Status/plan default " "to bounded Todo summaries; use agent-todos or user-todos for full lists. For `quota " - "should-run`: scheduler, agent-todos, user-todos, goal-boundary, or " - "vision. For `quota monitor-poll`: decisions. Repeat for multiple " - "sections or use `all`." + "should-run`: scheduler, agent-todos, user-todos, goal-boundary, " + "goal_acceptance (expands current live Goal acceptance at invocation time, not historical capture replay; use quota context-read on the original capture for admission-time readback), or vision. " + "For `quota monitor-poll`: decisions. Repeat for multiple sections or use `all`." ), ) quota_parser.add_argument( diff --git a/loopx/cli_commands/quota_request.py b/loopx/cli_commands/quota_request.py index 57003515fa..40c2895da6 100644 --- a/loopx/cli_commands/quota_request.py +++ b/loopx/cli_commands/quota_request.py @@ -10,6 +10,7 @@ "agent-todos", "user-todos", "goal-boundary", + "goal_acceptance", "vision", ) QUOTA_MONITOR_POLL_DETAIL_SECTIONS = ("decisions",) diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index 8924164c2e..27286b396d 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -14,6 +14,7 @@ import {quotaSummaryReferences, contextSourceIdentity, contextProjectionChanges, type ProjectionSourceValues} from "./diagnostic_projection.ts"; import {encodeContextDelivery, fileNavigationPaths} from "./context_delivery.ts"; import {capturedContextSelection} from "./context_selection.ts"; +import {SCOPED_OUTCOME_PROJECTION_MODE} from "./turn_envelope_scoping.ts"; import {createHash} from "node:crypto"; @@ -588,6 +589,19 @@ export function progressiveContextPlan(request: JsonObject, row.reason.replace(FULL_OUTCOME_READ_GUIDANCE, PROGRESSIVE_OUTCOME_READ_GUIDANCE)}); }); } + const deferredDetails = jsonObject(at(payload, ["deferred_settlement_details"])); + if (deferredDetails !== null) { + const hasGoalAcceptance = Object.hasOwn(deferredDetails, "goal_acceptance"); + const hasOptionalAttachments = Object.hasOwn(deferredDetails, "optional_attachments"); + deferred.push({ + path: ["deferred_settlement_details"], + read_instruction: hasGoalAcceptance + ? (hasOptionalAttachments + ? "Admission-time goal_acceptance outcomes and optional settlement attachment details stay in the original capture; use outcome_requirements.capture_read_command for immutable baseline readback, or cold_read_command / optional_attachments[].cold_read_command for live inspection." + : "Admission-time goal_acceptance outcomes stay in the original capture; use outcome_requirements.capture_read_command for immutable baseline readback, or cold_read_command for live inspection.") + : "Complete optional settlement attachment details stay in the original capture; use optional_attachments[].cold_read_command when needed.", + }); + } for (const scope of scopes) { deferred.push({path: scope.path, read_instruction: scope.instruction}); if (scope.marker_path) instructions.push({path: scope.marker_path, value: pointer(scope.path)}); @@ -1248,7 +1262,18 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly && suggested.every(id => typeof id === "string" && outcomes.filter(value => object(value)?.id === id).length === 1); const expanded = new Set(expand ? suggested as string[] : []); - const outcomesPath = [...source, "content", "goal_acceptance_contract", "outcome_requirements", "outcomes"]; + const requirementsPath = [...source, "content", "goal_acceptance_contract", "outcome_requirements"]; + if (requirements?.projection_mode === SCOPED_OUTCOME_PROJECTION_MODE) { + for (const field of [ + "schema_version", "revision", "outcome_revision", "current_lifetime", + "projection_mode", "full_outcome_count", "inline_outcome_count", + "compacted_outcome_count", "full_outcomes_sha256", + "capture_read_command", "cold_read_command", "cold_read_instruction", + ]) { + if (Object.hasOwn(requirements, field)) include(...requirementsPath, field); + } + } + const outcomesPath = [...requirementsPath, "outcomes"]; const canDeferSuggested = openingBudget !== undefined && readyIdentity !== undefined && expanded.size > 0 && inlineSupportingDetails && details?.outcome_support_from_id === true && details.path === supportingSource?.path && details.sha256 === supportingSource?.sha256 @@ -1268,6 +1293,11 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly const suggested = typeof outcomeId === "string" && expanded.has(outcomeId); if (suggested && !deferSuggested) { include(...outcome); return; } include(...outcome, "id"); + if (row?.summary_only === true) { + for (const key of ["owner_agent_id", "basis_digest", "revision", "todo_count", "summary_only", "capture_read_command", "read_modes", "cold_read_command"]) { + if (Object.hasOwn(row, key)) include(...outcome, key); + } + } if (suggested) { include(...outcome, "objective"); include(...outcome, "revision"); diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index 55260bf5fb..dd061dcd1e 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -339,6 +339,12 @@ def compose_turn_decision( Mapping[str, Any] | SchedulerExecutionContextResolution | None ) = None, composed_settlement: bool = False, + include_vision_detail: bool = False, + include_goal_acceptance_detail: bool = False, + cli_argv: tuple[str, ...] | list[str] | None = None, + capture_reference_file: str | None = None, + cli_registry: str | None = None, + cli_runtime_root: str | None = None, ) -> dict[str, Any]: """Transport complete source facts to the existing typed composition owner.""" resolution = resolve_scheduler_execution_context(scheduler_execution_context) @@ -346,7 +352,13 @@ def compose_turn_decision( source = dict(payload) result = _turn_envelope_result("compose_complete", payload=source, scheduler_execution_args=args, source_edits=True, - **({"composed_settlement": composed_settlement} if composed_settlement is not False else {})) + **({"composed_settlement": composed_settlement} if composed_settlement is not False else {}), + **({"include_vision_detail": True} if include_vision_detail else {}), + **({"include_goal_acceptance_detail": True} if include_goal_acceptance_detail else {}), + **({"cli_argv": list(cli_argv)} if cli_argv is not None else {}), + **({"capture_reference_file": capture_reference_file} if capture_reference_file is not None else {}), + **({"cli_registry": cli_registry} if cli_registry is not None else {}), + **({"cli_runtime_root": cli_runtime_root} if cli_runtime_root is not None else {})) return _apply_context_projection_changes(source, result) diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 661624ed90..9e31ec2309 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -20,6 +20,7 @@ import { referenceQuotaSummaryLanes, resolveQuotaSummaryLanes, } from "./diagnostic_projection.ts"; import { completeCliSettlementChannel } from "./settlement_plan.ts"; +import { compactRoutineSettlementPlan, scopeTurnGoalAcceptance } from "./turn_envelope_scoping.ts"; import { interpretQuotaShouldRunPacket, assertSupportedQuotaPacket, settlementIdentityFromPlan, settlementIdentityPayload, type JsonObject, @@ -1026,9 +1027,33 @@ export function composeCompleteTurnDecision(value: unknown): JsonObject { const payload = requireJsonObject(request.payload, "complete Turn decision source"); const composedSettlement = request.composed_settlement === undefined ? false : requireBoolean(request.composed_settlement, "composed_settlement"); + const includeGoalAcceptanceDetail = request.include_goal_acceptance_detail === undefined ? false + : requireBoolean(request.include_goal_acceptance_detail, "include_goal_acceptance_detail"); + const includeVisionDetail = request.include_vision_detail === undefined ? false + : requireBoolean(request.include_vision_detail, "include_vision_detail"); if (typeof request.scheduler_execution_args !== "string") { throw new EffectRuntimeRequestError("Turn scheduler execution binding must be a string"); } + const cliArgv = request.cli_argv === undefined ? ["loopx"] : executableCliArgs(request.cli_argv); + if (request.cli_argv !== undefined && cliArgv.length === 0) { + throw new EffectRuntimeRequestError("Turn envelope cli_argv must be a non-empty list of strings"); + } + const captureReferenceFile = request.capture_reference_file; + if (captureReferenceFile !== undefined && !isNonEmptyFilePath(captureReferenceFile)) { + throw new EffectRuntimeRequestError("Turn envelope capture_reference_file must be a non-empty file path"); + } + if (request.cli_registry !== undefined && !isNonEmptyFilePath(request.cli_registry)) { + throw new EffectRuntimeRequestError("Turn envelope cli_registry must be a non-empty file path"); + } + if (request.cli_runtime_root !== undefined && !isNonEmptyFilePath(request.cli_runtime_root)) { + throw new EffectRuntimeRequestError("Turn envelope cli_runtime_root must be a non-empty file path"); + } + const coldReadOptions = { + cliArgv, + captureReferenceFile, + registry: request.cli_registry ?? payload.registry, + runtimeRoot: request.cli_runtime_root ?? payload.runtime_root, + }; if (payload.schema_version === COMPLETE_TURN_DECISION_VERSION) { const prior = requireCompleteTurnDecision(payload, request.source_number_tokens); if (object(prior.contract_binding).scheduler_execution_args !== request.scheduler_execution_args) { @@ -1083,7 +1108,13 @@ export function composeCompleteTurnDecision(value: unknown): JsonObject { })}}}}; } } + if (!includeVisionDetail) { + source = compactRoutineSettlementPlan(source, coldReadOptions); + } source = referenceGoalAcceptance(source, sourceIdentity); + if (!includeGoalAcceptanceDetail) { + source = scopeTurnGoalAcceptance(source, coldReadOptions); + } source = referenceReplanAuthoring(source, sourceIdentity); source = referenceExploreGuidance(source); source = referenceCurrentTaskTitle(source); diff --git a/loopx/control_plane/quota/turn_envelope_references.ts b/loopx/control_plane/quota/turn_envelope_references.ts index 8c6150081b..2ee690981e 100644 --- a/loopx/control_plane/quota/turn_envelope_references.ts +++ b/loopx/control_plane/quota/turn_envelope_references.ts @@ -322,11 +322,23 @@ function indexCapturedAcceptanceOutcomes(payload: JsonObject, indexOutcome: (val } } +function summaryOutcomeIndexRow(ref: string, outcome: JsonObject): JsonObject | null { + if (outcome.summary_only !== true) return null; + return { + outcome_ref: ref, + id: outcome.id, + ...pickOwn(outcome, ["owner_agent_id", "basis_digest", "revision", "todo_count", "capture_read_command", "read_modes", "cold_read_command"]), + summary_only: true, + }; +} + /** Expose existing facts, not another acceptance verdict. Missing values stay * absent; an Agent's `met` review is not a current independent check. */ function capturedOutcomeIndex(outcomes: ReadonlyMap, precision?: ReplanReadPrecision): JsonObject[] { return [...outcomes].map(([ref, outcome]) => { + const compactRow = summaryOutcomeIndexRow(ref, outcome); + if (compactRow) return compactRow; const states = new Map(); if (Array.isArray(outcome.requirements)) for (const value of outcome.requirements) { const requirement = requireJsonObject(value, "captured outcome requirement"); @@ -674,10 +686,14 @@ export function replanGoalContext(payload: JsonObject, reads: JsonObject | null, } const acceptanceIndex = outcomes.size ? { read_action_template: `${reads!.acceptance} --outcome-ref {outcome_ref}`, - outcomes: complete ? capturedOutcomeIndex(outcomes, precision) : [...outcomes].map(([ref, outcome]) => retain({outcome_ref: ref, id: outcome.id, - objective: outcome.objective, revision: outcome.revision, - requirement_count: Array.isArray(outcome.requirements) ? outcome.requirements.length : null}, - outcome, ["id", "objective", "revision"])), + outcomes: complete ? capturedOutcomeIndex(outcomes, precision) : [...outcomes].map(([ref, outcome]) => { + const compactRow = summaryOutcomeIndexRow(ref, outcome); + if (compactRow) return compactRow; + return retain({outcome_ref: ref, id: outcome.id, + objective: outcome.objective, revision: outcome.revision, + requirement_count: Array.isArray(outcome.requirements) ? outcome.requirements.length : null}, + outcome, ["id", "objective", "revision"]); + }), } : null; return {core, horizon, outcomes, acceptanceIndex, ambiguous}; } diff --git a/loopx/control_plane/quota/turn_envelope_scoping.ts b/loopx/control_plane/quota/turn_envelope_scoping.ts new file mode 100644 index 0000000000..6be276f5f1 --- /dev/null +++ b/loopx/control_plane/quota/turn_envelope_scoping.ts @@ -0,0 +1,627 @@ +/** Scoped per-Turn goal acceptance and lean routine settlement projections. + * + * On captured routine execution Turns (`captureReferenceFile` provided), keeps + * full acceptance bodies only for Turn-relevant outcomes (Todo linkage, + * active/unmet owned outcomes, open gaps, or ambiguous/fail-closed linkage), + * preserves the complete admission-time `goal_acceptance` contract inside + * `deferred_settlement_details.goal_acceptance` for immutable `capture_read_command` + * recovery, and represents remaining historical or other-agent outcomes as + * compact index entries with separate immutable `capture_read_command` and live + * `cold_read_command` (`loopx goal-acceptance inspect`) pointers. Without a + * capture reference file (or with explicit `--context-delivery off` / detail + * flags), preserves all inline acceptance outcomes verbatim. + * + * Routine `durable_writeback` steps keep the canonical complete `vision_authoring` + * contract intact in the decision (trimmed only in progressive first-read opening + * groups) while compacting non-triggered optional explore attachment prose into + * explicit `cold_read_command` hints (`explore turn-context`) and preserving + * complete optional attachments inside `deferred_settlement_details` for captured turns. + */ +import {isDeepStrictEqual} from "node:util"; +import {exploreResultWritebackAffordance} from "../capabilities/explore_context_delivery.ts"; +import type {JsonObject} from "../effect_program.ts"; +import {OUTCOME_CONTEXT_NAVIGATION_SCHEMA} from "../goals/outcome_requirements.ts"; +import {jsonObject} from "../runtime_decode.ts"; +import {EffectiveAction} from "./effective_action.generated.ts"; +import {canonicalHash, shellQuote} from "./turn_envelope_codec.ts"; + +const object = (value: unknown): JsonObject => jsonObject(value) ?? {}; + +export const SCOPED_OUTCOME_THRESHOLD = 6; +export const SCOPED_OUTCOME_PROJECTION_MODE = "turn_scoped_v0"; + +const UNVERIFIED_OR_FAILING_STATUSES = new Set(["failed", "stale", "unverified"]); +const EXPLORE_STATIC_GRAPH_KEYS = [ + ["result_attachment_template", "attachment_template"], + ["path_delta_attachment_template", "path_delta_attachment_template"], + ["linked_question_attachment_template", "linked_question_attachment_template"], + ["optional_question_evolution_example", "optional_question_evolution_example"], + ["optional_measurement_example", "optional_measurement_example"], + ["optional_execution_observation_example", "optional_execution_observation_example"], +] as const; + +function nonEmptyString(value: unknown): string | null { + return typeof value === "string" && value.length > 0 ? value : null; +} + +function stringList(value: unknown): string[] { + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === "string" && item.length > 0) + : []; +} + +export type ColdReadSourceOptions = { + cliArgv?: readonly string[]; + captureReferenceFile?: string; + registry?: unknown; + runtimeRoot?: unknown; +}; + +export type CompactSettlementOptions = ColdReadSourceOptions; +export type ScopeGoalAcceptanceOptions = ColdReadSourceOptions; + +function goalAcceptanceColdReadCommand(options: { + cliArgv: readonly string[]; + registry: unknown; + runtimeRoot: unknown; + goalId: string; +}): string { + const prefix = cliPrefix(options.cliArgv, options.registry, options.runtimeRoot); + return `${prefix} goal-acceptance inspect --goal-id ${shellQuote(options.goalId)}`; +} + +function goalAcceptanceCaptureReadCommand(options: { + cliArgv: readonly string[]; + captureReferenceFile: string; + selectPointer: string; +}): string { + const argv = options.cliArgv.length > 0 ? options.cliArgv : ["loopx"]; + return [ + ...argv.map(shellQuote), + "--format", "json", + "quota", "context-read", + "--reference-file", shellQuote(options.captureReferenceFile), + "--select", shellQuote(options.selectPointer), + ].join(" "); +} + +function cliPrefix( + cliArgv: readonly string[], + registry: unknown, + runtimeRoot: unknown, +): string { + const argv = cliArgv.length > 0 ? cliArgv : ["loopx"]; + const parts = argv.map(shellQuote); + const registryText = nonEmptyString(registry); + const runtimeRootText = nonEmptyString(runtimeRoot); + if (registryText) parts.push("--registry", shellQuote(registryText)); + if (runtimeRootText) parts.push("--runtime-root", shellQuote(runtimeRootText)); + parts.push("--format", "json"); + return parts.join(" "); +} + +function exploreColdReadCommand(options: { + cliArgv: readonly string[]; + registry: unknown; + runtimeRoot: unknown; + goalId: string; + agentId: string; + todoId: string | null; +}): string { + const prefix = cliPrefix(options.cliArgv, options.registry, options.runtimeRoot); + const parts = [ + prefix, + "explore", + "turn-context", + "--goal-id", shellQuote(options.goalId), + "--agent-id", shellQuote(options.agentId), + ...(options.todoId ? ["--todo-id", shellQuote(options.todoId)] : []), + ]; + return parts.join(" "); +} + +function isRoutineNormalRun(payload: JsonObject): boolean { + if (payload.effective_action !== EffectiveAction.NORMAL_RUN || payload.normal_delivery_allowed !== true) return false; + if (payload.replan_action_packet != null || payload.autonomous_replan_obligation != null) return false; + if (object(payload.vision_continuation_audit).required === true) return false; + if (object(payload.goal_frontier_projection).replan_required === true) return false; + if (payload.selected_todo_is_goal_completion === true) return false; + if (object(payload.vision_checkpoint).required === true) return false; + const todo = object(payload.selected_todo); + if (todo.task_class === "goal_completion") return false; + return true; +} + +function allRequirementsSatisfied(requirements: unknown[]): boolean { + if (requirements.length === 0) return false; + return requirements.every(value => { + const req = jsonObject(value); + if (!req || req.planning_satisfied !== true) return false; + if (typeof req.status === "string" && UNVERIFIED_OR_FAILING_STATUSES.has(req.status)) return false; + const review = jsonObject(req.agent_review); + if (review && (review.conclusion === "unmet" || review.conclusion === "uncertain")) return false; + return true; + }); +} + +interface InlineOutcomeOwner { + kind: "work_context" | "planning_horizon" | "agent_todo_summary"; + sourceIndex?: number; + contract: JsonObject; + requirements: JsonObject; + sourceContent?: JsonObject; +} + +function findSingleInlineOutcomeOwner(payload: JsonObject): InlineOutcomeOwner | null { + const owners: InlineOutcomeOwner[] = []; + const register = (owner: InlineOutcomeOwner | null): void => { + if (owner) owners.push(owner); + }; + const extract = ( + contractValue: unknown, + build: (contract: JsonObject, requirements: JsonObject) => InlineOutcomeOwner, + ): InlineOutcomeOwner | null => { + const contract = jsonObject(contractValue); + if (!contract || Object.hasOwn(contract, "outcome_requirements_ref")) return null; + const requirements = jsonObject(contract.outcome_requirements); + return requirements ? build(contract, requirements) : null; + }; + + const sources = object(object(object(payload.interaction_contract).agent_channel).work_context).sources; + if (Array.isArray(sources)) { + sources.forEach((value, index) => { + const source = object(value); + const content = object(source.content); + if (source.source !== "goal_acceptance") return; + register(extract(content.goal_acceptance_contract, (contract, requirements) => ({ + kind: "work_context", sourceIndex: index, contract, requirements, sourceContent: content, + }))); + }); + } + const horizonCore = object(object(payload.planning_horizon).core_goal); + if (!Object.hasOwn(horizonCore, "acceptance_contract_ref")) { + register(extract(horizonCore.acceptance_contract, (contract, requirements) => ({ + kind: "planning_horizon", contract, requirements, + }))); + } + const summary = object(payload.agent_todo_summary); + if (!Object.hasOwn(summary, "goal_acceptance_contract_ref")) { + register(extract(summary.goal_acceptance_contract, (contract, requirements) => ({ + kind: "agent_todo_summary", contract, requirements, + }))); + } + const replanCore = object(object(object(payload.autonomous_replan_obligation).replan_context).core_goal); + if (!Object.hasOwn(replanCore, "acceptance_contract_ref") && + Object.hasOwn(replanCore, "acceptance_contract") && + jsonObject(object(replanCore.acceptance_contract).outcome_requirements)) { + return null; + } + return owners.length === 1 ? owners[0] : null; +} + +function collectAcceptanceGaps( + payload: JsonObject, + requirements: JsonObject, + agentId: string, +): {globalAmbiguity: boolean; gapOutcomeIds: Set} { + const gapOutcomeIds = new Set(); + let globalAmbiguity = false; + const lists = [ + requirements.acceptance_gaps, + object(payload.goal_frontier_projection).acceptance_gaps, + ]; + for (const list of lists) { + if (list === undefined || list === null) continue; + if (!Array.isArray(list)) return {globalAmbiguity: true, gapOutcomeIds}; + for (const rawGap of list) { + const gap = jsonObject(rawGap); + if (!gap) return {globalAmbiguity: true, gapOutcomeIds}; + const outcomeId = nonEmptyString(gap.outcome_id); + const gapAgentId = nonEmptyString(gap.agent_id); + if (outcomeId !== null) { + gapOutcomeIds.add(outcomeId); + } else if (gapAgentId === null || gapAgentId === agentId) { + globalAmbiguity = true; + } + } + } + return {globalAmbiguity, gapOutcomeIds}; +} + +export function compactOutcomeIndexEntry( + outcome: JsonObject, + goalId: string, + options: ScopeGoalAcceptanceOptions & {outcomeIndex?: number} = {}, +): JsonObject { + const todoIds = Array.isArray(outcome.todo_ids) ? outcome.todo_ids : []; + const cliArgv = options.cliArgv ?? ["loopx"]; + const captureReferenceFile = nonEmptyString(options.captureReferenceFile); + const captureReadCommand = captureReferenceFile && options.outcomeIndex !== undefined && options.outcomeIndex >= 0 + ? goalAcceptanceCaptureReadCommand({ + cliArgv, + captureReferenceFile, + selectPointer: `/deferred_settlement_details/goal_acceptance/outcome_requirements/outcomes/${options.outcomeIndex}`, + }) + : null; + return { + id: outcome.id, + owner_agent_id: outcome.owner_agent_id ?? null, + basis_digest: outcome.basis_digest ?? null, + revision: outcome.revision ?? null, + todo_count: todoIds.length, + summary_only: true, + ...(captureReadCommand ? { + capture_read_command: captureReadCommand, + read_modes: "capture_read_command=immutable admission baseline; cold_read_command=live workspace inspect", + } : {}), + cold_read_command: goalAcceptanceColdReadCommand({ + cliArgv, + registry: options.registry, + runtimeRoot: options.runtimeRoot, + goalId, + }), + }; +} + +function replaceInlineOutcomeRequirements( + payload: JsonObject, + owner: InlineOutcomeOwner, + scopedRequirements: JsonObject, +): JsonObject { + if (owner.kind === "work_context") { + const interaction = object(payload.interaction_contract); + const agent = object(interaction.agent_channel); + const workContext = object(agent.work_context); + const sources = Array.isArray(workContext.sources) ? workContext.sources : []; + const targetIndex = owner.sourceIndex!; + return { + ...payload, + interaction_contract: { + ...interaction, + agent_channel: { + ...agent, + work_context: { + ...workContext, + sources: sources.map((entry, idx) => { + if (idx !== targetIndex) return entry; + const row = object(entry); + const content = object(row.content); + return { + ...row, + content: { + ...content, + goal_acceptance_contract: { + ...owner.contract, + outcome_requirements: scopedRequirements, + }, + }, + }; + }), + }, + }, + }, + }; + } + if (owner.kind === "planning_horizon") { + const horizon = object(payload.planning_horizon); + const core = object(horizon.core_goal); + return { + ...payload, + planning_horizon: { + ...horizon, + core_goal: { + ...core, + acceptance_contract: { + ...owner.contract, + outcome_requirements: scopedRequirements, + }, + }, + }, + }; + } + const summary = object(payload.agent_todo_summary); + return { + ...payload, + agent_todo_summary: { + ...summary, + goal_acceptance_contract: { + ...owner.contract, + outcome_requirements: scopedRequirements, + }, + }, + }; +} + +export function scopeTurnGoalAcceptance( + payload: JsonObject, + options: ScopeGoalAcceptanceOptions = {}, +): JsonObject { + if (!isRoutineNormalRun(payload)) return payload; + const captureReferenceFile = nonEmptyString(options.captureReferenceFile); + if (!captureReferenceFile) return payload; + const goalId = nonEmptyString(payload.goal_id); + const agentId = nonEmptyString(object(payload.agent_identity).agent_id ?? payload.agent_id); + const selectedTodo = jsonObject(payload.selected_todo); + const todoId = nonEmptyString(selectedTodo?.todo_id); + if (!goalId || !agentId || !selectedTodo || !todoId) return payload; + + const owner = findSingleInlineOutcomeOwner(payload); + if (!owner) return payload; + const {contract, requirements, sourceContent} = owner; + if (requirements.projection_mode === SCOPED_OUTCOME_PROJECTION_MODE) return payload; + if (requirements.current_lifetime !== true) return payload; + const outcomes = requirements.outcomes; + if (!Array.isArray(outcomes) || outcomes.length <= SCOPED_OUTCOME_THRESHOLD) return payload; + + const contractScope = jsonObject(contract.scope); + if (contractScope?.kind === "all_advancement") return payload; + if (Array.isArray(contract.criteria) && contract.criteria.length > 0) return payload; + + if (sourceContent) { + if (sourceContent.read_complete === false || sourceContent.legacy_fallback_used === true) return payload; + if (sourceContent.status !== undefined && sourceContent.status !== "loaded") return payload; + } + + const outcomeContext = jsonObject(sourceContent?.outcome_context); + let suggestedComplete: Set | null = null; + if (outcomeContext !== null) { + if (outcomeContext.schema_version !== OUTCOME_CONTEXT_NAVIGATION_SCHEMA) return payload; + const limitations = stringList(outcomeContext.limitations); + if (limitations.includes("goal_wide") || limitations.includes("lifetime") || limitations.includes("missing_relation")) { + return payload; + } + if (outcomeContext.coverage_complete === false) { + if (limitations.length === 0 || !limitations.every(item => item === "unbound_work")) return payload; + } else if (outcomeContext.coverage_complete === true) { + if (!Array.isArray(outcomeContext.suggested_outcome_ids)) return payload; + suggestedComplete = new Set(stringList(outcomeContext.suggested_outcome_ids)); + } else { + return payload; + } + } + + const gaps = collectAcceptanceGaps(payload, requirements, agentId); + if (gaps.globalAmbiguity) return payload; + + const relevantTodoIds = new Set([ + todoId, + ...stringList(selectedTodo.dependency_todo_ids), + ...stringList(selectedTodo.successor_todo_ids), + ...(nonEmptyString(selectedTodo.unblocks_todo_id) ? [nonEmptyString(selectedTodo.unblocks_todo_id)!] : []), + ]); + + const cliArgv = options.cliArgv ?? ["loopx"]; + const registry = options.registry ?? payload.registry; + const runtimeRoot = options.runtimeRoot ?? payload.runtime_root; + const coldReadOptions: ScopeGoalAcceptanceOptions = { + cliArgv, + registry, + runtimeRoot, + captureReferenceFile, + }; + const coldReadCommand = goalAcceptanceColdReadCommand({ + cliArgv, + registry, + runtimeRoot, + goalId, + }); + const captureReadCommand = goalAcceptanceCaptureReadCommand({ + cliArgv, + captureReferenceFile, + selectPointer: "/deferred_settlement_details/goal_acceptance", + }); + + let compactedCount = 0; + const scopedOutcomes: unknown[] = []; + for (const [outcomeIndex, rawOutcome] of outcomes.entries()) { + const outcome = jsonObject(rawOutcome); + if (!outcome) return payload; + const outcomeId = nonEmptyString(outcome.id); + const todoIds = outcome.todo_ids; + const reqs = outcome.requirements; + const ownerAgentId = nonEmptyString(outcome.owner_agent_id); + const declOwnerId = nonEmptyString(outcome.declaration_owner_agent_id); + + const ambiguous = !outcomeId + || !Array.isArray(todoIds) + || todoIds.some(item => nonEmptyString(item) === null) + || !Array.isArray(reqs) + || (ownerAgentId === null && todoIds.length === 0); + + const linkedToTodo = Array.isArray(todoIds) && todoIds.some(item => typeof item === "string" && relevantTodoIds.has(item)); + const linkedToGap = outcomeId !== null && gaps.gapOutcomeIds.has(outcomeId); + const suggested = outcomeId !== null && suggestedComplete !== null && suggestedComplete.has(outcomeId); + const ownedRelevant = (ownerAgentId === agentId || declOwnerId === agentId) + && (Array.isArray(todoIds) && todoIds.length === 0 + || !Array.isArray(reqs) + || !allRequirementsSatisfied(reqs) + || suggestedComplete === null); + + if (ambiguous || linkedToTodo || linkedToGap || suggested || ownedRelevant) { + scopedOutcomes.push(rawOutcome); + } else { + compactedCount += 1; + scopedOutcomes.push(compactOutcomeIndexEntry(outcome, goalId, {...coldReadOptions, outcomeIndex})); + } + } + + if (compactedCount === 0) return payload; + + const fullDigest = canonicalHash(outcomes); + const scopedRequirements: JsonObject = { + ...requirements, + projection_mode: SCOPED_OUTCOME_PROJECTION_MODE, + full_outcome_count: outcomes.length, + inline_outcome_count: outcomes.length - compactedCount, + compacted_outcome_count: compactedCount, + outcome_revision: requirements.revision ?? null, + full_outcomes_sha256: fullDigest, + capture_read_command: captureReadCommand, + cold_read_command: coldReadCommand, + cold_read_instruction: + "capture_read_command reads immutable admission-time goal_acceptance from this Turn capture (verify outcome_revision and full_outcomes_sha256); cold_read_command and --include-detail goal_acceptance query current live workspace state rather than replaying historical Turn state.", + outcomes: scopedOutcomes, + }; + const scopedPayload = replaceInlineOutcomeRequirements(payload, owner, scopedRequirements); + return { + ...scopedPayload, + deferred_settlement_details: { + ...object(scopedPayload.deferred_settlement_details), + goal_acceptance: owner.contract, + }, + }; +} + +function compactExploreGraphBoilerplate( + sources: unknown[], + affordance: JsonObject, + coldReadCommand: string, +): {sources: unknown[]; changed: boolean} { + let changed = false; + const next = sources.map(value => { + const item = jsonObject(value); + if (!item || item.source !== "turn_start_capability_hook" + || item.hook_id !== "explore.turn_context" || item.capability_id !== "explore") { + return value; + } + const content = jsonObject(item.content); + const graph = jsonObject(content?.graph); + if (!content || !graph || graph.result_writeback_guidance !== affordance.guidance) { + return value; + } + const nextGraph: JsonObject = {...graph}; + delete nextGraph.result_writeback_guidance; + for (const [graphKey, affordanceKey] of EXPLORE_STATIC_GRAPH_KEYS) { + if (Object.hasOwn(nextGraph, graphKey) && isDeepStrictEqual(nextGraph[graphKey], affordance[affordanceKey])) { + delete nextGraph[graphKey]; + } + } + nextGraph.result_writeback_guidance_summary_only = true; + nextGraph.result_writeback_guidance_cold_read_command = coldReadCommand; + changed = true; + return {...item, content: {...content, graph: nextGraph}}; + }); + return {sources: next, changed}; +} + +export function compactRoutineSettlementPlan( + payload: JsonObject, + options: CompactSettlementOptions = {}, +): JsonObject { + if (!isRoutineNormalRun(payload)) return payload; + const captureReferenceFile = nonEmptyString(options.captureReferenceFile); + if (!captureReferenceFile) return payload; + const frontier = object(payload.goal_frontier_projection); + if (Array.isArray(frontier.acceptance_gaps) && frontier.acceptance_gaps.length > 0) return payload; + + const interaction = jsonObject(payload.interaction_contract); + const cli = jsonObject(interaction?.cli_channel); + const plan = jsonObject(cli?.settlement_plan); + if (!interaction || !cli || !plan || !Array.isArray(plan.ordered_steps)) return payload; + + const identity = object(plan.identity); + const isTodoBound = identity.binding_kind === "todo" + || (identity.binding_kind === undefined && nonEmptyString(identity.todo_id) !== null && identity.replan_obligation_id == null); + if (!isTodoBound) return payload; + const goalId = nonEmptyString(payload.goal_id ?? identity.goal_id); + const agentId = nonEmptyString(object(payload.agent_identity).agent_id ?? payload.agent_id ?? identity.agent_id); + const todoId = nonEmptyString(object(payload.selected_todo).todo_id ?? identity.todo_id); + if (!goalId || !agentId) return payload; + + const requiredCaps = new Set(stringList(object(payload.selected_todo).required_capabilities)); + const exploreEnabled = requiredCaps.has("explore"); + const knownExplore = exploreResultWritebackAffordance(); + const cliArgv = options.cliArgv ?? ["loopx"]; + const exploreColdRead = exploreColdReadCommand({ + cliArgv, + registry: options.registry ?? payload.registry, + runtimeRoot: options.runtimeRoot ?? payload.runtime_root, + goalId, + agentId, + todoId, + }); + let deferredOptionalAttachments: unknown[] | null = null; + + let planChanged = false; + let compactedExploreAttachment = false; + const nextSteps = plan.ordered_steps.map(rawStep => { + const step = jsonObject(rawStep); + if (!step || step.kind !== "durable_writeback") return rawStep; + + let stepUpdated = false; + let nextStep: JsonObject = {...step}; + + if (!exploreEnabled && Array.isArray(step.optional_attachments)) { + let attachmentsChanged = false; + const nextAttachments = step.optional_attachments.map(rawAtt => { + const att = jsonObject(rawAtt); + if (!att || att.required !== false || att.capability_id !== "explore") return rawAtt; + if (!isDeepStrictEqual(att, knownExplore)) return rawAtt; + attachmentsChanged = true; + compactedExploreAttachment = true; + return { + capability_id: att.capability_id, + option: att.option, + inline_option: att.inline_option, + inline_field: att.inline_field, + attachment_schema: att.attachment_schema, + required: false, + summary_only: true, + cold_read_command: exploreColdRead, + }; + }); + if (attachmentsChanged) { + deferredOptionalAttachments = step.optional_attachments; + nextStep.optional_attachments = nextAttachments; + stepUpdated = true; + } + } + + if (stepUpdated) { + planChanged = true; + return nextStep; + } + return rawStep; + }); + + if (!planChanged) return payload; + + let nextInteraction: JsonObject = { + ...interaction, + cli_channel: { + ...cli, + settlement_plan: { + ...plan, + ordered_steps: nextSteps, + }, + }, + }; + + if (compactedExploreAttachment) { + const agent = jsonObject(interaction.agent_channel); + const workContext = jsonObject(agent?.work_context); + if (agent && workContext && Array.isArray(workContext.sources)) { + const updated = compactExploreGraphBoilerplate(workContext.sources, knownExplore, exploreColdRead); + if (updated.changed) { + nextInteraction = { + ...nextInteraction, + agent_channel: { + ...agent, + work_context: { + ...workContext, + sources: updated.sources, + }, + }, + }; + } + } + } + + return { + ...payload, + interaction_contract: nextInteraction, + ...(deferredOptionalAttachments !== null + ? {deferred_settlement_details: {optional_attachments: deferredOptionalAttachments}} + : {}), + }; +} diff --git a/tests/control_plane/test_context_first_read.py b/tests/control_plane/test_context_first_read.py index 21a4f3b767..2f09aaa89c 100644 --- a/tests/control_plane/test_context_first_read.py +++ b/tests/control_plane/test_context_first_read.py @@ -2591,9 +2591,9 @@ def exhausted(*_args): if key != "write_scope": assert warm_facts[f"/goal_boundary/{key}"] == value assert warm_facts["/interaction_contract/cli_channel/settlement_plan/identity/turn_instance_id"] == "scope-warm" - restored_selection = {key: value for key, value in restored_facts.items() - if key != "/goal_boundary" and not key.startswith(scope_path)} observed = warm[0].get("previously_delivered_fields", []) + restored_selection = {key: value for key, value in restored_facts.items() + if not key.startswith(scope_path) and not any(pointer.startswith(key + "/") for pointer in observed)} assert restored_selection == { **warm_facts, **{key: value for key, value in restored_selection.items() @@ -2822,8 +2822,9 @@ def appended_turn(turn, prefix, suffix): assert facts[source_pointer + "/authority_read"] == current_authority if complete: assert pointer in warm[0].get("previously_delivered_fields", []) and pointer not in facts - restored_note = {key: value for key, value in restored.items() if key != pointer} observed = warm[0].get("previously_delivered_fields", []) + restored_note = {key: value for key, value in restored.items() + if key != pointer and not any(address.startswith(key + "/") for address in observed)} assert restored_note == { **facts, **{key: value for key, value in restored_note.items() diff --git a/tests/control_plane/test_refresh_settle_turn.py b/tests/control_plane/test_refresh_settle_turn.py index cbd326505f..c780d65524 100644 --- a/tests/control_plane/test_refresh_settle_turn.py +++ b/tests/control_plane/test_refresh_settle_turn.py @@ -932,6 +932,13 @@ def test_execution_evidence_uses_explicit_finding_binding_in_settlement(tmp_path assert rc == 0 and detail["eof"], detail plan = json.loads(detail["content"])["selections"][0]["value"] writeback = next(step for step in plan["ordered_steps"] if step["kind"] == "durable_writeback") + assert writeback["optional_attachments"][0]["summary_only"] is True + assert "explore turn-context" in writeback["optional_attachments"][0]["cold_read_command"] + rc, detail_entry = _run_cli(registry, runtime, "quota", "should-run", "--codex-app", + *binding, "--context-delivery", "off", "--include-detail", "vision", cwd=project) + assert rc == 0, detail_entry + detail_writeback = next(step for step in detail_entry["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"] + if step["kind"] == "durable_writeback") refs = ["result:probe", "source:" + "e" * 64] revision = "dataset:" + "d" * 64 @@ -978,7 +985,7 @@ def test_execution_evidence_uses_explicit_finding_binding_in_settlement(tmp_path assert settled["settlement_identity"] == plan["identity"] assert settled["quota_spend"]["ok"] and "settlement_owed" not in settled - example = writeback["optional_attachments"][0]["optional_execution_observation_example"] + example = detail_writeback["optional_attachments"][0]["optional_execution_observation_example"] assert example["execution_observation"]["schema_version"] == compact["schema_version"] assert compact["schema_version"] not in json.dumps(entry) assert settled["explore_result"]["execution_observation"] == observation diff --git a/tests/control_plane/test_scoped_turn_envelope_cli.py b/tests/control_plane/test_scoped_turn_envelope_cli.py new file mode 100644 index 0000000000..3cc3b45521 --- /dev/null +++ b/tests/control_plane/test_scoped_turn_envelope_cli.py @@ -0,0 +1,929 @@ +"""End-to-end File + SQLite verification for scoped outcomes & lean settlement plans.""" +from __future__ import annotations + +import copy +import json +from pathlib import Path +import shlex +import subprocess +import sys + +import pytest + +from canonical_authority_fixture import initialize_canonical_authority +from loopx.configure_goal import configure_goal +from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection +from loopx.control_plane.testing.canary_harness import write_fixture_registry +from loopx.control_plane.todos.machine_section_projection import render_canonical_todo_sections +from loopx.control_plane.turn_driver.codex_context import codex_context_hook +from loopx.control_plane.turn_driver.decision_capture import read_context_read_reference + + +def _seed_mature_goal( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + *, + provider: str, + outcome_count: int = 33, + goal_id: str = "mature-scoped-goal", + objective_prefix: str = "Historical outcome", + explore_graph_enabled: bool = False, +) -> dict[str, object]: + monkeypatch.delenv("CODEX_THREAD_ID", raising=False) + project = tmp_path / "project" + runtime = tmp_path / "runtime" + registry = project / ".loopx" / "registry.json" + state = project / "ACTIVE_GOAL_STATE.md" + project.mkdir(parents=True) + registry.parent.mkdir(parents=True) + + agent_id = "worker" + todos = [ + { + "schema_version": "todo_item_v0", + "todo_id": "todo_current", + "role": "agent", + "text": "Validate and settle the active scoped slice.", + "status": "open", + "done": False, + "task_class": "advancement_task", + "action_kind": "implement", + "index": 1, + "source_section": "Agent Todo", + "archive_state": "active", + "claimed_by": agent_id, + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_next", + "role": "agent", + "text": "Follow-up pending open deliverable.", + "status": "open", + "done": False, + "task_class": "advancement_task", + "action_kind": "implement", + "index": 2, + "source_section": "Agent Todo", + "archive_state": "active", + "claimed_by": "peer-0", + }, + ] + for i in range(outcome_count - 1): + todos.append({ + "schema_version": "todo_item_v0", + "todo_id": f"todo_hist_{i}", + "role": "agent", + "text": f"Historical archived task {i}.", + "status": "done", + "done": True, + "task_class": "advancement_task", + "action_kind": "implement", + "index": i + 3, + "source_section": "Completed Work Archive", + "archive_state": "archive", + "claimed_by": f"peer-{i % 4}", + }) + + body = ( + "---\nstatus: active\n---\n# Goal\n## Objective\n" + "Ship public-safe scoped context projections.\n" + "## Agent Todo\n\n## User Todo\n\n## Completed Work Archive\n" + ) + state.write_text(render_canonical_todo_sections(body, todos, provider_revision="fixture-src").markdown) + write_fixture_registry( + project=project, + runtime_root=runtime, + registry_path=registry, + goal_id=goal_id, + domain="software", + adapter_kind="generic_project_goal_v0", + state_file=str(state), + registered_agents=[agent_id, "peer-0", "peer-1", "peer-2", "peer-3"], + quota_allowed_slots=4, + ) + configure_goal(registry_path=registry, goal_id=goal_id, execute=True, explore_mode="planning") + if explore_graph_enabled: + cfg = json.loads(registry.read_text()) + cfg["goals"][0]["explore_graph"] = {"enabled": True} + registry.write_text(json.dumps(cfg)) + initialize_canonical_authority( + runtime, + goal_id, + build_todo_runtime_shadow_projection(goal_id=goal_id, todos=todos, handoff_mode="hard_lease"), + state_path=state, + provider=provider, + ) + + patches = [{ + "outcome_id": "outcome-current", + "owner_agent_id": agent_id, + "objective": "Deliver current feature slice with verified parity.", + "todo_ids": ["todo_current"], + "storage_format": "records", + "requirements": [ + {"id": f"req-{r}", "description": (f"Current requirement {r}. " + ("Verify parity. " * 20)).strip()} + for r in range(4) + ], + "source": {"ref": "spec:current", "summary": ("Current spec provenance " * 20).strip()}, + }] + for i in range(outcome_count - 1): + patches.append({ + "outcome_id": f"outcome-hist-{i}", + "owner_agent_id": f"peer-{i % 4}", + "objective": f"{objective_prefix} {i}.", + "todo_ids": [f"todo_hist_{i}"], + "storage_format": "records", + "requirements": [ + {"id": f"hreq-{r}", "description": (f"Hist req {i}-{r}. " + ("Detail check. " * 22)).strip()} + for r in range(8) + ], + "source": {"ref": f"hist:{i}", "summary": ("Historical provenance " * 15).strip()}, + "review": [ + {"id": f"hreq-{r}", "conclusion": "met", "note": ("Verified acceptance criteria. " * 8).strip(), + "evidence_refs": [f"ev:{i}-{r}"]} + for r in range(8) + ], + }) + + ts_seed = """ +import {openLocalAuthorityStore} from "./loopx/control_plane/coordination/local_authority_provider.ts"; +import {refineGoalOutcome, serializeGoalOutcomes} from "./loopx/control_plane/goals/outcome_requirements.ts"; +let input = ''; for await (const c of process.stdin) input += c; +const {root, goal, patches} = JSON.parse(input); +const store = await openLocalAuthorityStore(root, goal); +const prior = await store.loadAuthority(); +if (prior.status !== 'loaded') throw new Error('missing authority'); +let head = prior.head; +for (const p of patches) { + const {review, ...decl} = p; + let next = refineGoalOutcome(head, goal, null, p.owner_agent_id, decl); + head = {...head, goal_outcomes: serializeGoalOutcomes(next)}; + if (review) { + next = refineGoalOutcome(head, goal, null, p.owner_agent_id, {outcome_id: p.outcome_id, review, storage_format: "records"}); + head = {...head, goal_outcomes: serializeGoalOutcomes(next)}; + } +} +const res = await store.commitAuthority({operation_id: 'seed-mature', expected_provider_revision: prior.provider_revision, events: [], receipts: [], next_projection: head}); +if (res.status !== 'applied') throw new Error(JSON.stringify(res)); +""" + repo_root = Path(__file__).resolve().parents[2] + subprocess.run( + ["node", "--no-warnings", "--experimental-sqlite", "--experimental-strip-types", "--input-type=module", "-e", ts_seed], + cwd=repo_root, + input=json.dumps({"root": str(runtime), "goal": goal_id, "patches": patches}), + text=True, + check=True, + ) + + def cli(*args: str, check: bool = True) -> tuple[int, dict]: + proc = subprocess.run( + [sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", *args], + cwd=project, + capture_output=True, + text=True, + ) + data = json.loads(proc.stdout) if proc.stdout.strip() else {"raw": proc.stderr} + if check: + assert proc.returncode == 0, (proc.stdout, proc.stderr) + return proc.returncode, data + + return {"project": project, "runtime": runtime, "registry": registry, "goal_id": goal_id, "agent_id": agent_id, "cli": cli} + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_mature_goal_scoped_envelope_inspect_detail_replan_and_settle_parity(tmp_path, monkeypatch, provider): + env = _seed_mature_goal(tmp_path, monkeypatch, provider=provider) + cli = env["cli"] + goal_id = env["goal_id"] + agent_id = env["agent_id"] + + # 1. Claim todo_current under hard_lease (soft claim + task-lease acquire/inspect). + _, claim = cli("todo", "claim", "--goal-id", goal_id, "--todo-id", "todo_current", "--agent-id", agent_id, "--claimed-by", agent_id) + assert claim["ok"], claim + _, inspected_lease = cli("task-lease", "inspect", "--goal-id", goal_id, "--todo-id", "todo_current") + lease = inspected_lease.get("lease") + if not lease: + _, acquired = cli("task-lease", "acquire", "--goal-id", goal_id, "--todo-id", "todo_current", + "--agent-id", agent_id, "--lease-owner", agent_id, "--execute") + lease = acquired["lease"] + + native = tmp_path / "native" + native.mkdir(mode=0o700) + captures = tmp_path / "captures" + captures.mkdir(mode=0o700) + monkeypatch.setenv("CODEX_THREAD_ID", f"scoped-{provider}") + codex_context_hook(str(native), {"hook_event_name": "SessionStart", "session_id": f"scoped-{provider}", "cwd": str(env["project"]), "source": "startup"}) + + # 2. Routine Turn produces lean decision.json + required-context.json. + _, view = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", + "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-routine", "--codex-context-dir", str(native), + "--decision-output-root", str(captures), + ) + decision_path = next(captures.rglob("decision.json")) + decision = json.loads(decision_path.read_text()) + _, req_ref = read_context_read_reference(view["recovery"]["reference_file"]) + required_ctx = json.loads(Path(req_ref["path"]).read_bytes()) + + # required-context.json omits deferred_settlement_details and stays lean; decision.json preserves admission-time goal_acceptance. + assert Path(req_ref["path"]).stat().st_size < decision_path.stat().st_size * 0.38 + assert "deferred_settlement_details" not in required_ctx + deferred_ga = decision["deferred_settlement_details"]["goal_acceptance"]["outcome_requirements"] + assert len(deferred_ga["outcomes"]) == 33 + assert all("requirements" in row and "sources" in row for row in deferred_ga["outcomes"]) + wc_ga = next(s["content"]["goal_acceptance_contract"] + for s in decision["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance") + reqs = wc_ga["outcome_requirements"] + assert reqs["projection_mode"] == "turn_scoped_v0" + assert reqs["full_outcome_count"] == 33 + assert reqs["inline_outcome_count"] == 1 + assert reqs["compacted_outcome_count"] == 32 + assert isinstance(reqs["full_outcomes_sha256"], str) and reqs["full_outcomes_sha256"].startswith("sha256:") + assert reqs["outcome_revision"] == reqs["revision"] + assert "--reference-file" in reqs["capture_read_command"] + assert "--select /deferred_settlement_details/goal_acceptance" in reqs["capture_read_command"] + assert "--include-detail goal_acceptance" in reqs["cold_read_instruction"] + assert str(env["registry"]) in reqs["cold_read_command"] + assert str(env["runtime"]) in reqs["cold_read_command"] + assert f"goal-acceptance inspect --goal-id {goal_id}" in reqs["cold_read_command"] + assert len(reqs["outcomes"]) == 33 + assert reqs["outcomes"][0]["id"] == "outcome-current" and "requirements" in reqs["outcomes"][0] + assert all( + row["summary_only"] is True + and row["cold_read_command"] == reqs["cold_read_command"] + and f"/deferred_settlement_details/goal_acceptance/outcome_requirements/outcomes/{idx}" in row["capture_read_command"] + for idx, row in enumerate(reqs["outcomes"][1:], start=1) + ) + assert len(required_ctx.get("context_details", {}).get("unread_context_index", {}).get("pointers", [])) < 20 + + step1 = decision["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1] + assert len(step1["vision_authoring"]) == 11 + assert "minimal_example" in step1["vision_authoring"] + assert step1["optional_attachments"][0]["summary_only"] is True + assert step1["optional_attachments"][0]["required"] is False + assert "--settle-turn" in step1["command_template"] + + # 3. Full cold-read via goal-acceptance inspect still returns all 33 full outcomes verbatim. + _, inspected = cli("goal-acceptance", "inspect", "--goal-id", goal_id) + full_outcomes = inspected["goal_acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(full_outcomes) == 33 + assert all("requirements" in row and "sources" in row for row in full_outcomes) + + # 4. --include-detail vision on the same Turn delivers full optional_attachments alongside complete vision_authoring. + _, detail = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", "--include-detail", "vision", + "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-routine", + ) + detail_step1 = detail["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1] + assert detail_step1["vision_authoring"] == step1["vision_authoring"] + assert len(detail_step1["vision_authoring"]) == 11 + assert "guidance" in detail_step1["optional_attachments"][0] + + # 4b. Captured Turn retains complete 11-field vision_authoring at its canonical step pointer + # and preserves full optional_attachments in deferred_settlement_details inside decision.json + # while omitting deferred_settlement_details from required-context.json; initial first-read + # keeps vision_authoring concise while immutable capture readback and explore cold-read succeed + # verbatim on File & SQLite. + deferred = decision["deferred_settlement_details"] + assert deferred["optional_attachments"] == detail_step1["optional_attachments"] + assert "deferred_settlement_details" not in required_ctx + + first_read = subprocess.run( + shlex.split(view["first_read_command"]), + cwd=env["project"], + capture_output=True, + text=True, + ) + assert first_read.returncode == 0, first_read.stderr + first_page = json.loads(first_read.stdout) + assert first_page["ok"] is True + assert "minimal_example" not in first_page["content"] + + ga_index = next( + i for i, s in enumerate(decision["interaction_contract"]["agent_channel"]["work_context"]["sources"]) + if s.get("source") == "goal_acceptance" + ) + recovery_read_cmd = ( + view["recovery"]["command"] + + " --select /interaction_contract/cli_channel/settlement_plan/ordered_steps/1/vision_authoring" + + " --select /interaction_contract/cli_channel/settlement_plan/identity" + + f" --select /interaction_contract/agent_channel/work_context/sources/{ga_index}/content/goal_acceptance_contract" + ) + captured_cold_read = subprocess.run( + shlex.split(recovery_read_cmd), + cwd=env["project"], + capture_output=True, + text=True, + ) + assert captured_cold_read.returncode == 0, captured_cold_read.stdout + captured_cold_read.stderr + read_page = json.loads(captured_cold_read.stdout) + assert read_page["ok"] is True and read_page["eof"] is True + selected = json.loads(read_page["content"]) + by_pointer = {row["pointer"]: row["value"] for row in selected["selections"]} + assert by_pointer["/interaction_contract/cli_channel/settlement_plan/ordered_steps/1/vision_authoring"] == detail_step1["vision_authoring"] + assert by_pointer["/interaction_contract/cli_channel/settlement_plan/identity"]["effect_id"] == decision["interaction_contract"]["cli_channel"]["settlement_plan"]["identity"]["effect_id"] + acceptance_ptrs = [ptr for ptr in by_pointer if ptr.endswith(("goal_acceptance_contract", "acceptance_contract"))] + assert acceptance_ptrs == [f"/interaction_contract/agent_channel/work_context/sources/{ga_index}/content/goal_acceptance_contract"] + assert by_pointer[acceptance_ptrs[0]]["outcome_requirements"]["outcomes"][0]["id"] == "outcome-current" + + # Full decision capture reader (.reader.json) delivers deferred_settlement_details, + # 11-field vision_authoring, settlement identity, and scoped goal_acceptance verbatim. + decision_reader_cmd = [ + sys.executable, "-m", "loopx.entrypoint", "--format", "json", "quota", "context-read", + "--reference-file", str(decision_path.with_suffix(".reader.json")), + "--select", "/interaction_contract/cli_channel/settlement_plan/ordered_steps/1/vision_authoring", + "--select", "/deferred_settlement_details/optional_attachments", + "--select", "/interaction_contract/cli_channel/settlement_plan/identity", + "--select", f"/interaction_contract/agent_channel/work_context/sources/{ga_index}/content/goal_acceptance_contract", + "--page-bytes", "64000", "--max-page-output-bytes", "64000", + ] + decision_read = subprocess.run(decision_reader_cmd, cwd=env["project"], capture_output=True, text=True) + assert decision_read.returncode == 0, decision_read.stdout + decision_read.stderr + decision_selected = { + row["pointer"]: row["value"] + for row in json.loads(json.loads(decision_read.stdout)["content"])["selections"] + } + assert decision_selected["/interaction_contract/cli_channel/settlement_plan/ordered_steps/1/vision_authoring"] == detail_step1["vision_authoring"] + assert decision_selected["/deferred_settlement_details/optional_attachments"] == detail_step1["optional_attachments"] + assert decision_selected["/interaction_contract/cli_channel/settlement_plan/identity"]["effect_id"] == decision["interaction_contract"]["cli_channel"]["settlement_plan"]["identity"]["effect_id"] + assert decision_selected[f"/interaction_contract/agent_channel/work_context/sources/{ga_index}/content/goal_acceptance_contract"] == wc_ga + + # Explore cold_read_command inherits registry & runtime-root and executes verbatim. + explore_cold_read = subprocess.run( + shlex.split(step1["optional_attachments"][0]["cold_read_command"]), + cwd=env["project"], + capture_output=True, + text=True, + ) + assert explore_cold_read.returncode == 0, explore_cold_read.stderr + explore_payload = json.loads(explore_cold_read.stdout) + assert explore_payload["ok"] is True + + # Uncaptured --context-delivery off omits deferred_settlement_details and preserves both + # all 33 full inline goal_acceptance outcomes and all 14 Explore attachment fields alongside + # complete 11-field vision_authoring for disabled-delivery parity. + _, uncaptured = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", + "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-routine", + ) + assert "deferred_settlement_details" not in uncaptured + uncaptured_ga = next( + s["content"]["goal_acceptance_contract"] + for s in uncaptured["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + uncaptured_ga_reqs = uncaptured_ga["outcome_requirements"] + assert "projection_mode" not in uncaptured_ga_reqs + assert "capture_read_command" not in uncaptured_ga_reqs + assert len(uncaptured_ga_reqs["outcomes"]) == 33 + assert all( + "requirements" in row and "sources" in row and "summary_only" not in row + for row in uncaptured_ga_reqs["outcomes"] + ) + uncaptured_step1 = uncaptured["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1] + assert uncaptured_step1["vision_authoring"] == detail_step1["vision_authoring"] + assert uncaptured_step1["optional_attachments"] == detail_step1["optional_attachments"] + assert "summary_only" not in uncaptured_step1["optional_attachments"][0] + assert "guidance" in uncaptured_step1["optional_attachments"][0] + + # 4c. --include-detail goal_acceptance returns all 33 full inline outcomes cleanly, + # and unsupported or invalid --include-detail choices fail cleanly. + _, ga_detail = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", "--include-detail", "goal_acceptance", + "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-routine", + ) + ga_full = next( + s["content"]["goal_acceptance_contract"] + for s in ga_detail["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + ga_full_reqs = ga_full["outcome_requirements"] + assert "projection_mode" not in ga_full_reqs + assert Path(req_ref["path"]).stat().st_size < len(json.dumps(ga_detail).encode("utf-8")) * 0.45 + assert len(ga_full_reqs["outcomes"]) == 33 + assert all("requirements" in row and "sources" in row and "summary_only" not in row for row in ga_full_reqs["outcomes"]) + + bad_detail_rc, _ = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", "--include-detail", "bogus", + "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-routine", check=False, + ) + assert bad_detail_rc == 2 + plan_detail_rc, plan_detail_err = cli( + "quota", "plan", "--include-detail", "goal_acceptance", + "--goal-id", goal_id, "--agent-id", agent_id, check=False, + ) + assert plan_detail_rc == 1 + assert plan_detail_err["error_code"] == "QUOTA_VALIDATION_FAILED" + assert "goal_acceptance" in json.dumps(plan_detail_err) + + # 5. End-to-end execution parity: refresh-state + spend-slot settles cleanly on File & SQLite. + _, settled = cli( + "refresh-state", "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-routine", "--classification", "implemented", + "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", + "--delivery-boundary", "in_flight_continuation", "--delivery-workspace-path", str(env["project"]), + "--task-lease-idempotency-key", lease["idempotency_key"], + "--task-lease-expected-version", str(lease["version"]), + "--settle-turn", "--settlement-receipt", "--no-global-sync", "--suppress-external-sinks", + ) + assert settled["ok"] and settled["settlement_progress"]["state"] == "settled", settled + + # 6. Tampered scoped capture is rejected fail-closed. + tampered_path = tmp_path / "tampered-decision.json" + tampered = copy.deepcopy(decision) + tampered["contract_binding"]["content_hash"] = "sha256:" + ("0" * 64) + tampered_path.write_text(json.dumps(tampered)) + from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision + with pytest.raises(Exception): + assert_complete_turn_decision(tampered) + + +def _claim_current_todo(env: dict[str, object]) -> None: + cli = env["cli"] + goal_id = env["goal_id"] + agent_id = env["agent_id"] + _, claim = cli( + "todo", "claim", "--goal-id", goal_id, "--todo-id", "todo_current", + "--agent-id", agent_id, "--claimed-by", agent_id, + ) + assert claim["ok"], claim + _, inspected_lease = cli("task-lease", "inspect", "--goal-id", goal_id, "--todo-id", "todo_current") + if not inspected_lease.get("lease"): + _, acquired = cli( + "task-lease", "acquire", "--goal-id", goal_id, "--todo-id", "todo_current", + "--agent-id", agent_id, "--lease-owner", agent_id, "--execute", + ) + assert acquired.get("lease"), acquired + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_scoped_acceptance_cold_read_binds_original_workspace_across_sibling_cwd( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + ws_a = _seed_mature_goal( + tmp_path / "ws_a", + monkeypatch, + provider=provider, + outcome_count=9, + goal_id="shared-goal", + objective_prefix="Workspace A outcome", + ) + ws_b = _seed_mature_goal( + tmp_path / "ws_b", + monkeypatch, + provider=provider, + outcome_count=7, + goal_id="shared-goal", + objective_prefix="Workspace B outcome", + ) + _claim_current_todo(ws_a) + + # Sanity check: Workspace B directly holds 7 outcomes under the same goal_id. + _, ws_b_direct = ws_b["cli"]("goal-acceptance", "inspect", "--goal-id", "shared-goal") + ws_b_outcomes = ws_b_direct["goal_acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(ws_b_outcomes) == 7 + assert ws_b_outcomes[1]["objective"].startswith("Workspace B outcome") + + native = tmp_path / "native_a" + native.mkdir(mode=0o700) + captures = tmp_path / "captures_a" + captures.mkdir(mode=0o700) + monkeypatch.setenv("CODEX_THREAD_ID", f"cross-ws-{provider}") + codex_context_hook( + str(native), + {"hook_event_name": "SessionStart", "session_id": f"cross-ws-{provider}", "cwd": str(ws_a["project"]), "source": "startup"}, + ) + + _, view = ws_a["cli"]( + "quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", + "--goal-id", "shared-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-ws-a", "--codex-context-dir", str(native), + "--decision-output-root", str(captures), + ) + decision_path = next(captures.rglob("decision.json")) + decision = json.loads(decision_path.read_text()) + _, req_ref = read_context_read_reference(view["recovery"]["reference_file"]) + required_ctx = json.loads(Path(req_ref["path"]).read_bytes()) + + wc_ga = next( + s["content"]["goal_acceptance_contract"] + for s in decision["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + reqs = wc_ga["outcome_requirements"] + assert reqs["full_outcome_count"] == 9 + assert reqs["compacted_outcome_count"] == 8 + assert isinstance(reqs["full_outcomes_sha256"], str) and reqs["full_outcomes_sha256"].startswith("sha256:") + assert reqs["outcome_revision"] == reqs["revision"] + assert "--include-detail goal_acceptance" in reqs["cold_read_instruction"] + + summary_cmd = reqs["cold_read_command"] + compact_rows = [row for row in reqs["outcomes"] if row.get("summary_only") is True] + assert len(compact_rows) == 8 + row_cmd = compact_rows[0]["cold_read_command"] + assert row_cmd == summary_cmd + + # Progressive first read carries the exact same bound summary command, metadata, and row commands. + req_ga = next( + s["content"]["goal_acceptance_contract"] + for s in required_ctx["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + req_reqs = req_ga["outcome_requirements"] + assert req_reqs["cold_read_command"] == summary_cmd + assert req_reqs["full_outcomes_sha256"] == reqs["full_outcomes_sha256"] + assert req_reqs["outcome_revision"] == reqs["outcome_revision"] + assert req_reqs["cold_read_instruction"] == reqs["cold_read_instruction"] + assert req_reqs["outcomes"][1]["cold_read_command"] == summary_cmd + + # Run BOTH emitted cold_read_commands verbatim from Workspace B without adding flags. + for cmd in (summary_cmd, row_cmd): + proc = subprocess.run( + shlex.split(cmd), + cwd=ws_b["project"], + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr + inspected = json.loads(proc.stdout) + outcomes = inspected["goal_acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(outcomes) == 9 + assert all(row["objective"].startswith("Workspace A outcome") for row in outcomes[1:]) + + # Default relative `.loopx/registry.json` invocation in Workspace A also binds absolutely across cwd. + ws_a_rel = _seed_mature_goal( + tmp_path / "ws_a_rel", + monkeypatch, + provider=provider, + outcome_count=9, + goal_id="shared-goal", + objective_prefix="Workspace A rel outcome", + ) + _claim_current_todo(ws_a_rel) + rel_native = tmp_path / "native_rel" + rel_native.mkdir(mode=0o700) + rel_captures = tmp_path / "captures_rel" + rel_captures.mkdir(mode=0o700) + monkeypatch.setenv("CODEX_THREAD_ID", f"cross-ws-rel-{provider}") + codex_context_hook( + str(rel_native), + {"hook_event_name": "SessionStart", "session_id": f"cross-ws-rel-{provider}", "cwd": str(ws_a_rel["project"]), "source": "startup"}, + ) + rel_proc = subprocess.run( + [ + sys.executable, "-m", "loopx.cli", + "--runtime-root", str(ws_a_rel["runtime"]), + "--format", "json", + "quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", + "--goal-id", "shared-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-ws-a-rel", "--codex-context-dir", str(rel_native), + "--decision-output-root", str(rel_captures), + ], + cwd=ws_a_rel["project"], + capture_output=True, + text=True, + ) + assert rel_proc.returncode == 0, rel_proc.stdout + rel_proc.stderr + rel_view = json.loads(rel_proc.stdout) + _, rel_req_ref = read_context_read_reference(rel_view["recovery"]["reference_file"]) + rel_req_ctx = json.loads(Path(rel_req_ref["path"]).read_bytes()) + rel_reqs = next( + s["content"]["goal_acceptance_contract"] + for s in rel_req_ctx["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + )["outcome_requirements"] + rel_cold_proc = subprocess.run( + shlex.split(rel_reqs["cold_read_command"]), + cwd=ws_b["project"], + capture_output=True, + text=True, + ) + assert rel_cold_proc.returncode == 0, rel_cold_proc.stdout + rel_cold_proc.stderr + rel_outcomes = json.loads(rel_cold_proc.stdout)["goal_acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(rel_outcomes) == 9 + assert all(row["objective"].startswith("Workspace A rel outcome") for row in rel_outcomes[1:]) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_captured_turn_recovers_admission_time_outcomes_after_goal_advances( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + env = _seed_mature_goal( + tmp_path, + monkeypatch, + provider=provider, + outcome_count=9, + goal_id="drift-goal", + objective_prefix="Admitted outcome", + ) + cli = env["cli"] + _claim_current_todo(env) + + _, before_inspect = cli("goal-acceptance", "inspect", "--goal-id", "drift-goal") + admitted_rev = before_inspect["goal_acceptance_contract"]["outcome_requirements"]["revision"] + provider_rev = before_inspect["provider_revision"] + orig_hist0 = before_inspect["goal_acceptance_contract"]["outcome_requirements"]["outcomes"][1] + assert orig_hist0["id"] == "outcome-hist-0" + orig_req_ids = [req["id"] for req in orig_hist0["requirements"]] + assert len(orig_req_ids) == 8 + + native = tmp_path / "native" + native.mkdir(mode=0o700) + captures = tmp_path / "captures" + captures.mkdir(mode=0o700) + monkeypatch.setenv("CODEX_THREAD_ID", f"drift-{provider}") + codex_context_hook( + str(native), + {"hook_event_name": "SessionStart", "session_id": f"drift-{provider}", "cwd": str(env["project"]), "source": "startup"}, + ) + + # 1. Admit Turn 1 with capture + progressive delivery. + _, view = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", + "--goal-id", "drift-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-drift", "--codex-context-dir", str(native), + "--decision-output-root", str(captures), + ) + decision_path = next(captures.rglob("decision.json")) + decision = json.loads(decision_path.read_text()) + _, req_ref = read_context_read_reference(view["recovery"]["reference_file"]) + required_ctx = json.loads(Path(req_ref["path"]).read_bytes()) + + assert "deferred_settlement_details" not in required_ctx + assert Path(req_ref["path"]).stat().st_size < decision_path.stat().st_size * 0.6 + req_reqs = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in required_ctx["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert req_reqs["projection_mode"] == "turn_scoped_v0" + assert req_reqs["outcome_revision"] == admitted_rev + row1 = req_reqs["outcomes"][1] + assert row1["id"] == "outcome-hist-0" and row1["summary_only"] is True + assert "capture_read_command" in req_reqs and "capture_read_command" in row1 + assert "cold_read_command" in req_reqs and "cold_read_command" in row1 + + # 2. Advance live Goal acceptance after Turn 1 admission by adding a new requirement. + refine_doc = tmp_path / "advance-outcome.json" + refine_doc.write_text(json.dumps({ + "outcome_id": "outcome-hist-0", + "owner_agent_id": "peer-0", + "objective": orig_hist0["objective"], + "todo_ids": orig_hist0["todo_ids"], + "storage_format": "records", + "source": {"ref": "spec:post-admission", "summary": "Post-admission requirement provenance."}, + "requirements": [ + {"id": req["id"], "description": req["description"]} + for req in orig_hist0["requirements"] + ] + [ + {"id": "hreq-post-admission", "description": "Post-admission requirement added after Turn 1."}, + ], + })) + _, refined = cli( + "goal-acceptance", "refine", + "--goal-id", "drift-goal", + "--agent-id", "peer-0", + "--document", str(refine_doc), + "--operation-id", "op-advance-after-turn1", + "--expected-provider-revision", provider_rev, + "--execute", + ) + assert refined["ok"] is True + live_reqs = refined["goal_acceptance_contract"]["outcome_requirements"] + assert live_reqs["revision"] == admitted_rev + 1 + + # 3. Immutable capture readback (both summary and compacted row capture_read_command) + # recovers the exact admission-time outcomes/requirements (NO post-admission requirement). + summary_capture_proc = subprocess.run( + shlex.split(req_reqs["capture_read_command"]), + cwd=env["project"], + capture_output=True, + text=True, + ) + assert summary_capture_proc.returncode == 0, summary_capture_proc.stdout + summary_capture_proc.stderr + summary_page = json.loads(summary_capture_proc.stdout) + assert summary_page["ok"] is True and summary_page["eof"] is True + captured_ga = json.loads(summary_page["content"])["selections"][0]["value"] + captured_reqs = captured_ga["outcome_requirements"] + assert captured_reqs["revision"] == admitted_rev + assert len(captured_reqs["outcomes"]) == 9 + assert [r["id"] for r in captured_reqs["outcomes"][1]["requirements"]] == orig_req_ids + assert all(r["id"] != "hreq-post-admission" for r in captured_reqs["outcomes"][1]["requirements"]) + + row_capture_proc = subprocess.run( + shlex.split(row1["capture_read_command"]), + cwd=env["project"], + capture_output=True, + text=True, + ) + assert row_capture_proc.returncode == 0, row_capture_proc.stdout + row_capture_proc.stderr + row_page = json.loads(row_capture_proc.stdout) + assert row_page["ok"] is True and row_page["eof"] is True + captured_row = json.loads(row_page["content"])["selections"][0]["value"] + assert captured_row["id"] == "outcome-hist-0" + assert [r["id"] for r in captured_row["requirements"]] == orig_req_ids + + # 4. Live cold_read_command and --include-detail goal_acceptance inspect current live revision. + live_proc = subprocess.run( + shlex.split(req_reqs["cold_read_command"]), + cwd=env["project"], + capture_output=True, + text=True, + ) + assert live_proc.returncode == 0, live_proc.stdout + live_proc.stderr + live_inspect_reqs = json.loads(live_proc.stdout)["goal_acceptance_contract"]["outcome_requirements"] + assert live_inspect_reqs["revision"] == admitted_rev + 1 + assert "hreq-post-admission" in [r["id"] for r in live_inspect_reqs["outcomes"][1]["requirements"]] + + _, live_detail = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", + "--include-detail", "goal_acceptance", + "--goal-id", "drift-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-drift", + ) + detail_reqs = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in live_detail["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert detail_reqs["revision"] == admitted_rev + 1 + assert "hreq-post-admission" in [r["id"] for r in detail_reqs["outcomes"][1]["requirements"]] + assert decision["deferred_settlement_details"]["goal_acceptance"]["outcome_requirements"]["revision"] == admitted_rev + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_disabled_context_delivery_preserves_full_inline_outcomes_without_capture( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + env = _seed_mature_goal( + tmp_path, + monkeypatch, + provider=provider, + outcome_count=9, + goal_id="disabled-delivery-goal", + objective_prefix="Disabled delivery outcome", + explore_graph_enabled=True, + ) + cli = env["cli"] + _claim_current_todo(env) + + _, before_inspect = cli("goal-acceptance", "inspect", "--goal-id", "disabled-delivery-goal") + admitted_rev = before_inspect["goal_acceptance_contract"]["outcome_requirements"]["revision"] + provider_rev = before_inspect["provider_revision"] + orig_hist0 = before_inspect["goal_acceptance_contract"]["outcome_requirements"]["outcomes"][1] + assert orig_hist0["id"] == "outcome-hist-0" + orig_req_ids = [req["id"] for req in orig_hist0["requirements"]] + assert len(orig_req_ids) == 8 + + # 1. Explicit `--context-delivery off` with NO capture location must keep all 9 full outcomes, + # all 8 historical requirements, all 14 Explore attachment fields, and Explore graph guidance ref inline. + _, off_nocapture = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", + "--goal-id", "disabled-delivery-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-off-nocapture", + ) + assert "deferred_settlement_details" not in off_nocapture + off_reqs = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in off_nocapture["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert "projection_mode" not in off_reqs + assert off_reqs["revision"] == admitted_rev + assert len(off_reqs["outcomes"]) == 9 + assert all("summary_only" not in row and "requirements" in row for row in off_reqs["outcomes"]) + assert [r["id"] for r in off_reqs["outcomes"][1]["requirements"]] == orig_req_ids + + off_step1 = off_nocapture["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1] + off_att = off_step1["optional_attachments"][0] + assert len(off_att) == 14 + assert "summary_only" not in off_att and "cold_read_command" not in off_att + for key in ("guidance", "attachment_template", "path_delta_attachment_template"): + assert key in off_att + off_graph = next( + s["content"]["graph"] + for s in off_nocapture["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("kind") == "explore_turn_context" + ) + assert "result_writeback_guidance_summary_only" not in off_graph + assert "result_writeback_guidance_ref" in off_graph + + # Uncaptured compose_turn_decision (without capture_reference_file) also refuses to compact outcomes or attachments. + from loopx.control_plane.quota.turn_envelope import compose_turn_decision + + stripped_input = { + key: copy.deepcopy(val) + for key, val in off_nocapture.items() + if key not in {"schema_version", "contract_binding", "deferred_settlement_details"} + } + composed_no_capture = compose_turn_decision( + stripped_input, + scheduler_execution_context=None, + composed_settlement=True, + include_goal_acceptance_detail=False, + include_vision_detail=False, + capture_reference_file=None, + ) + assert "deferred_settlement_details" not in composed_no_capture + nocap_reqs = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in composed_no_capture["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert "projection_mode" not in nocap_reqs + assert len(nocap_reqs["outcomes"]) == 9 + assert [r["id"] for r in nocap_reqs["outcomes"][1]["requirements"]] == orig_req_ids + nocap_att = composed_no_capture["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1]["optional_attachments"][0] + assert nocap_att == off_att and len(nocap_att) == 14 + + # 2. Advance live Goal acceptance (`admitted_rev -> admitted_rev + 1`), run `--context-delivery off` + # with `--decision-output-dir` while Explore is enabled, then disable Explore in registry. + refine_doc = tmp_path / "advance-disabled-delivery.json" + refine_doc.write_text(json.dumps({ + "outcome_id": "outcome-hist-0", + "owner_agent_id": "peer-0", + "objective": orig_hist0["objective"], + "todo_ids": orig_hist0["todo_ids"], + "storage_format": "records", + "source": {"ref": "spec:post-off-admission", "summary": "Post-admission requirement provenance."}, + "requirements": [ + {"id": req["id"], "description": req["description"]} + for req in orig_hist0["requirements"] + ] + [ + {"id": "hreq-post-off-admission", "description": "Added after off admission."}, + ], + })) + _, refined = cli( + "goal-acceptance", "refine", + "--goal-id", "disabled-delivery-goal", + "--agent-id", "peer-0", + "--document", str(refine_doc), + "--operation-id", "op-advance-after-off", + "--expected-provider-revision", provider_rev, + "--execute", + ) + assert refined["ok"] is True + + off_capture_dir = tmp_path / "off-capture-dir" + _, off_with_dir = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", + "--decision-output-dir", str(off_capture_dir), + "--goal-id", "disabled-delivery-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-off-nocapture", + ) + off_dir_decision = json.loads((off_capture_dir / "decision.json").read_text()) + + configure_goal(registry_path=env["registry"], goal_id="disabled-delivery-goal", execute=True, explore_mode="off") + explore_rc, explore_disabled = cli( + "explore", "turn-context", "--goal-id", "disabled-delivery-goal", "--agent-id", "worker", "--todo-id", "todo_current", + check=False, + ) + assert explore_rc == 0 + assert explore_disabled["graph_enabled"] is False + assert "result_writeback_guidance" not in (explore_disabled.get("graph") or {}) + + # Original response and `--context-delivery off --decision-output-dir` both preserve all 14 Explore + # attachment fields and full inline outcomes even after Explore is disabled and Goal advances; + # same-Turn `--include-detail goal_acceptance` reads live rev + 1. + assert len(off_att) == 14 and "guidance" in off_att + for payload in (off_with_dir, off_dir_decision): + assert "deferred_settlement_details" not in payload + dir_reqs = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in payload["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert "projection_mode" not in dir_reqs + assert dir_reqs["revision"] == admitted_rev + 1 + assert len(dir_reqs["outcomes"]) == 9 + assert all("summary_only" not in row and "requirements" in row for row in dir_reqs["outcomes"]) + assert "hreq-post-off-admission" in [r["id"] for r in dir_reqs["outcomes"][1]["requirements"]] + dir_att = payload["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"][1]["optional_attachments"][0] + assert dir_att == off_att and len(dir_att) == 14 + + _, detail_after = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "off", + "--include-detail", "goal_acceptance", + "--goal-id", "disabled-delivery-goal", "--agent-id", "worker", "--todo-id", "todo_current", + "--turn-instance-id", "turn-off-nocapture", + ) + detail_after_reqs = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in detail_after["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert detail_after_reqs["revision"] == admitted_rev + 1 + assert "hreq-post-off-admission" in [r["id"] for r in detail_after_reqs["outcomes"][1]["requirements"]] + assert [r["id"] for r in off_reqs["outcomes"][1]["requirements"]] == orig_req_ids diff --git a/tests/control_plane_ts/turn_envelope_scoping.test.ts b/tests/control_plane_ts/turn_envelope_scoping.test.ts new file mode 100644 index 0000000000..c1203685fc --- /dev/null +++ b/tests/control_plane_ts/turn_envelope_scoping.test.ts @@ -0,0 +1,779 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import {exploreResultWritebackAffordance} from "../../loopx/control_plane/capabilities/explore_context_delivery.ts"; +import {type JsonObject} from "../../loopx/control_plane/effect_program.ts"; +import {visionAuthoringContract} from "../../loopx/control_plane/goals/vision_checkpoint.ts"; +import {progressiveContextPlan} from "../../loopx/control_plane/quota/progressive_context.ts"; +import {evaluateTurnEnvelope} from "../../loopx/control_plane/quota/turn_envelope.ts"; +import {canonicalHash} from "../../loopx/control_plane/quota/turn_envelope_codec.ts"; +import {replanGoalContext} from "../../loopx/control_plane/quota/turn_envelope_references.ts"; +import { + SCOPED_OUTCOME_PROJECTION_MODE, + compactRoutineSettlementPlan, + scopeTurnGoalAcceptance, +} from "../../loopx/control_plane/quota/turn_envelope_scoping.ts"; + +function routineWritebackStep(agentId = "a1", todoId = "todo-current"): JsonObject { + return { + kind: "durable_writeback", + owner: "agent", + precondition: "Persist evidence after independent checks.", + idempotency_key_ref: "$.identity.effect_id", + expected_receipt: "durable_writeback_receipt", + command_template: `loopx refresh-state --goal-id g1 --agent-id ${agentId} --todo-id ${todoId} --settle-turn --settlement-receipt`, + semantic_closeout_command_template: `loopx refresh-state --goal-id g1 --agent-id ${agentId} --todo-id ${todoId} --agent-vision-json --settle-turn --settlement-receipt`, + vision_authoring: visionAuthoringContract(false), + optional_attachments: [exploreResultWritebackAffordance()], + }; +} + +function outcomeRow(index: number, overrides: JsonObject = {}): JsonObject { + return { + id: `out-${index}`, + owner_agent_id: `peer-${index % 4}`, + objective: `Verify historical deliverable ${index} cleanly.`, + revision: 2, + todo_ids: [`todo-hist-${index}`], + sources: [{ref: `docs/evidence-${index}.md`, summary: `Historical evidence summary ${index} ` + "x".repeat(900)}], + requirements: [ + { + id: `req-${index}-a`, + description: `Independent acceptance requirement for ${index} ` + "y".repeat(220), + status: "verified", + planning_satisfied: true, + agent_review: { + id: `req-${index}-a`, + conclusion: "met", + basis_current: true, + independently_verified: false, + note: `Detailed agent verification note ${index} ` + "z".repeat(450), + evidence_refs: [`evidence:item-${index}`], + }, + }, + ], + basis_digest: "sha256:" + String(index % 10).repeat(64), + work: "complete", + ...overrides, + }; +} + +function baseNormalPayload(count = 33, agentId = "a1", todoId = "todo-current"): JsonObject { + const outcomes: JsonObject[] = [ + outcomeRow(0, { + id: "out-current", + owner_agent_id: agentId, + todo_ids: [todoId], + requirements: [{ + id: "req-current", + description: "Current deliverable must pass strict parity verification " + "p".repeat(200), + status: "unverified", + planning_satisfied: false, + }], + }), + ]; + for (let i = 1; i < count; i++) outcomes.push(outcomeRow(i)); + + const affordance = exploreResultWritebackAffordance(); + const requirements = { + schema_version: "loopx_goal_outcomes_v0", + revision: 33, + current_lifetime: true, + outcomes, + }; + const contract = (goalObjective: JsonObject): JsonObject => ({ + checks: ["pytest"], + goal_objective: goalObjective, + outcome_requirements: structuredClone(requirements), + }); + + return { + ok: true, + goal_id: "g1", + agent_id: agentId, + decision: "run", + should_run: true, + normal_delivery_allowed: true, + effective_action: "normal_run", + state: "eligible", + reason: "admitted selected todo", + action_required: false, + open_count: 1, + recommended_action: "Deliver scoped verification slice.", + agent_identity: {agent_id: agentId, role: "worker"}, + selected_todo: { + todo_id: todoId, + text: "Deliver scoped verification slice.", + status: "open", + claimed_by: agentId, + task_repository: "repo", + }, + work_lane_contract: { + schema_version: "work_lane_contract_v0", + must_attempt_work: true, + }, + heartbeat_receipt: { + schema_version: "heartbeat_receipt_v0", + status: "committed", + closeout_required: true, + turn_instance_id: "turn-1", + settlement_identity: { + schema_version: "quota_settlement_identity_v0", + effect_id: `g1:${agentId}:${todoId}:turn-1`, + goal_id: "g1", + agent_id: agentId, + todo_id: todoId, + turn_instance_id: "turn-1", + }, + }, + goal_frontier_projection: { + schema_version: "goal_frontier_projection_v0", + replan_required: false, + acceptance_gaps: [], + }, + interaction_contract: { + schema_version: "loopx_interaction_contract_v0", + mode: "bounded_delivery", + agent_channel: { + must_attempt: true, + delivery_allowed: true, + quiet_noop_allowed: false, + primary_action: "Deliver scoped verification slice.", + required_reads: [{source: "goal_acceptance", reason: "Read all Goal acceptance criteria."}], + work_context: { + complete: true, + selected_todo_ref: "selected_todo", + selected_todo_text_verified: true, + instruction: "Read full task requirements.", + sources: [ + { + source: "turn_start_capability_hook", + hook_id: "explore.turn_context", + capability_id: "explore", + kind: "explore_turn_context", + content: { + graph: { + counts: {node_count: 1, finding_count: 0}, + writeback_results: [], + result_attachment_template: affordance.attachment_template, + path_delta_attachment_template: affordance.path_delta_attachment_template, + result_writeback_guidance: affordance.guidance, + guidance: "Use explore when branching.", + }, + }, + }, + { + source: "goal_acceptance", + content: { + ok: true, + status: "loaded", + decision_read_from_provider: true, + legacy_fallback_used: false, + read_complete: true, + provider_revision: "sqlite:abc:33", + goal_acceptance_contract: contract({schema_version: "goal_objective_revision_v0", objective: "Deliver X"}), + outcome_context: { + schema_version: "outcome_context_navigation_v1", + goal_id: "g1", + agent_id: agentId, + todo_id: todoId, + outcome_revision: 33, + coverage_complete: true, + limitations: [], + suggested_outcome_ids: ["out-current"], + provider_revision: "sqlite:abc:33", + }, + }, + }, + ], + }, + }, + user_channel: {action_required: false, notify: "DONT_NOTIFY"}, + cli_channel: { + execution_preparation: {state: "ready", todo_id: todoId}, + spend_allowed_now: false, + spend_after_validation: true, + spend_policy: "spend once after validated writeback", + next_cli_actions: [`loopx refresh-state --goal-id g1 --agent-id ${agentId} --todo-id ${todoId} --settle-turn --settlement-receipt`], + settlement_plan: { + schema_version: "quota_settlement_plan_v2", + identity: { + schema_version: "quota_settlement_identity_v0", + effect_id: `g1:${agentId}:${todoId}:turn-1`, + goal_id: "g1", + agent_id: agentId, + todo_id: todoId, + turn_instance_id: "turn-1", + binding_kind: "todo", + }, + ordered_steps: [{kind: "validation", owner: "agent"}, routineWritebackStep(agentId, todoId), {kind: "quota_spend", owner: "runtime"}], + }, + }, + }, + planning_horizon: { + core_goal: { + goal_id: "g1", + objective: "Deliver X", + acceptance_contract: contract({schema_version: "goal_objective_revision_v0", objective: "Deliver X", adoptions: []}), + }, + }, + agent_todo_summary: { + schema_version: "todo_summary_v0", + open_count: 1, + all_open_count: 1, + open: [], + goal_acceptance_contract: contract({schema_version: "goal_objective_revision_v0", objective: "Deliver X", agent_adoption: {adopted: false}}), + }, + }; +} + +test("scoped per-Turn goal_acceptance shrinks 33+ outcomes while retaining relevant, gap, and ambiguous rows", () => { + const source = baseNormalPayload(33); + const ambiguousRow: JsonObject = { + id: "out-12", + objective: "Ambiguous unowned unbound outcome", + revision: 1, + todo_ids: [], + sources: [{ref: "unknown", summary: "Ambiguous origin."}], + requirements: [{id: "amb", description: "Preserve ambiguous outcome in full.", status: "unverified", planning_satisfied: false}], + }; + const carriers: JsonObject[] = [ + ((((source.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject, + (source.planning_horizon as JsonObject).core_goal as JsonObject, + source.agent_todo_summary as JsonObject, + ]; + for (const holder of carriers) { + const contract = (holder.goal_acceptance_contract ?? holder.acceptance_contract) as JsonObject; + ((contract.outcome_requirements as JsonObject).outcomes as JsonObject[])[12] = structuredClone(ambiguousRow); + } + const fullOutcomes = carriers[0].goal_acceptance_contract as JsonObject; + const origOutcomes = (fullOutcomes.outcome_requirements as JsonObject).outcomes as JsonObject[]; + // Inject: (1) open gap referencing out-5, (2) dependency todo matching out-8, + // (3) ambiguous outcome missing owner and todos at out-12. + (source.selected_todo as JsonObject).dependency_todo_ids = ["todo-hist-8"]; + (source.goal_frontier_projection as JsonObject).acceptance_gaps = [ + {kind: "outcome_gap", outcome_id: "out-5", agent_id: "peer-1"}, + ]; + const expectedDigest = canonicalHash(origOutcomes); + + const composed = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + capture_reference_file: "state/captures/decision.reader.json", + }); + const wcSources = (((composed.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[]; + const gaContract = (wcSources[1].content as JsonObject).goal_acceptance_contract as JsonObject; + assert.deepEqual(gaContract.goal_objective, {schema_version: "goal_objective_revision_v0", objective: "Deliver X"}); + assert.deepEqual(gaContract.checks, ["pytest"]); + + const reqs = gaContract.outcome_requirements as JsonObject; + assert.equal(reqs.projection_mode, SCOPED_OUTCOME_PROJECTION_MODE); + assert.equal(reqs.full_outcome_count, 33); + assert.equal(reqs.inline_outcome_count, 4); + assert.equal(reqs.compacted_outcome_count, 29); + assert.equal(reqs.outcome_revision, 33); + assert.equal(reqs.full_outcomes_sha256, expectedDigest); + assert.equal( + reqs.capture_read_command, + "loopx --format json quota context-read --reference-file state/captures/decision.reader.json --select /deferred_settlement_details/goal_acceptance", + ); + assert.equal(reqs.cold_read_command, "loopx --format json goal-acceptance inspect --goal-id g1"); + assert.match(String(reqs.cold_read_instruction), /capture_read_command reads immutable admission-time goal_acceptance/); + assert.match(String(reqs.cold_read_instruction), /--include-detail goal_acceptance/); + assert.deepEqual((composed.deferred_settlement_details as JsonObject).goal_acceptance, fullOutcomes); + + const outcomes = reqs.outcomes as JsonObject[]; + assert.equal(outcomes.length, 33); + for (const id of ["out-current", "out-5", "out-8", "out-12"]) { + const row = outcomes.find(o => o.id === id)!; + assert.equal(row.summary_only, undefined); + assert.ok(Array.isArray(row.requirements), `${id} must stay full`); + } + const compactRow = outcomes.find(o => o.id === "out-1")!; + assert.equal(compactRow.summary_only, true); + assert.equal(compactRow.owner_agent_id, "peer-1"); + assert.equal(compactRow.revision, 2); + assert.equal(compactRow.todo_count, 1); + assert.equal(compactRow.basis_digest, "sha256:" + "1".repeat(64)); + assert.equal(compactRow.cold_read_command, "loopx --format json goal-acceptance inspect --goal-id g1"); + assert.equal(compactRow.requirements, undefined); + assert.equal(compactRow.sources, undefined); + assert.equal(compactRow.work, undefined); + + // Ref deduplication still holds across planning_horizon and agent_todo_summary. + const expectedRef = "$.interaction_contract.agent_channel.work_context.sources[1].content.goal_acceptance_contract.outcome_requirements"; + assert.equal((((composed.planning_horizon as JsonObject).core_goal as JsonObject).acceptance_contract as JsonObject).outcome_requirements_ref, expectedRef); + assert.equal(((composed.agent_todo_summary as JsonObject).goal_acceptance_contract as JsonObject).outcome_requirements_ref, expectedRef); + + // Envelope + host view + progressive unread_context_index stay valid and vastly smaller. + assert.deepEqual(evaluateTurnEnvelope({operation: "complete_consumer", payload: composed}), {ok: true}); + const envelope = evaluateTurnEnvelope({operation: "build", payload: composed, scheduler_execution_args: ""}); + assert.equal((envelope.action_signature as JsonObject).matches, true); + + const planFull = progressiveContextPlan({payload: source, surface: "quota_packet"}); + const fullComposed = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + include_goal_acceptance_detail: true, + include_vision_detail: true, + }); + const progBaseline = evaluateTurnEnvelope({ + operation: "progressive_context_delivery", + surface: "complete_turn", + context: fullComposed, + native_projection: {path: "source.json", sha256: "a".repeat(64)}, + }); + const progScoped = evaluateTurnEnvelope({ + operation: "progressive_context_delivery", + surface: "complete_turn", + context: composed, + native_projection: {path: "source.json", sha256: "a".repeat(64)}, + }); + assert.ok((planFull.deferred as unknown[]).length > 30); + const fullWcBytes = Buffer.byteLength(JSON.stringify(((((fullComposed.interaction_contract as JsonObject).agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1])); + const scopedWcBytes = Buffer.byteLength(JSON.stringify(wcSources[1])); + // Including capture_read_command + read_modes on all 29 summary_only rows brings wcSources[1] + // from ~20% to ~33% of fullWcBytes (>65% savings) while keeping admission readback addressable. + assert.ok(scopedWcBytes < fullWcBytes * 0.38); + // First-read progressive delivery strips deferred_settlement_details while keeping captured decision complete. + assert.ok(Buffer.byteLength(JSON.stringify(progScoped)) < Buffer.byteLength(JSON.stringify(progBaseline)) * 0.30); +}); + +test("small Goals, uncaptured runs, replan turns, audit required, closeout, detail flags, and fail-closed gates preserve full outcomes", () => { + const captureOpts = {captureReferenceFile: "state/captures/decision.reader.json"}; + + // Small Goal <= 6 outcomes stays verbatim even when captured. + const small = baseNormalPayload(4); + assert.equal(scopeTurnGoalAcceptance(small, captureOpts), small); + + // Uncaptured call without captureReferenceFile always returns payload unchanged (100% inline outcomes). + const uncaptured33 = baseNormalPayload(33); + assert.equal(scopeTurnGoalAcceptance(uncaptured33), uncaptured33); + assert.equal(scopeTurnGoalAcceptance(uncaptured33, {}), uncaptured33); + + const uncapturedComposed = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: uncaptured33, + scheduler_execution_args: "", + }); + const uncapturedGa = (((((uncapturedComposed.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject; + const uncapturedReqs = uncapturedGa.outcome_requirements as JsonObject; + assert.equal(uncapturedReqs.projection_mode, undefined); + assert.equal((uncapturedReqs.outcomes as JsonObject[]).length, 33); + assert.equal((uncapturedReqs.outcomes as JsonObject[]).every(o => o.summary_only === undefined), true); + assert.equal(uncapturedComposed.deferred_settlement_details, undefined); + + // Replan, vision audit, closeout, legacy lifetime, goal-wide criteria, missing relation, global gap, detail flag. + for (const [name, mutate] of [ + ["non_normal_run", (p: JsonObject) => { p.effective_action = "autonomous_replan_required"; }], + ["replan_action_packet", (p: JsonObject) => { p.replan_action_packet = {obligation_id: "rep-1"}; }], + ["vision_audit_required", (p: JsonObject) => { p.vision_continuation_audit = {required: true}; }], + ["closeout_flag", (p: JsonObject) => { p.selected_todo_is_goal_completion = true; }], + ["legacy_lifetime", (p: JsonObject) => { + const c = (((((p.interaction_contract as JsonObject).agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject).goal_acceptance_contract as JsonObject; + (c.outcome_requirements as JsonObject).current_lifetime = false; + }], + ["goal_wide_criteria", (p: JsonObject) => { + const c = (((((p.interaction_contract as JsonObject).agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject).goal_acceptance_contract as JsonObject; + c.criteria = [{id: "global"}]; + }], + ["missing_relation", (p: JsonObject) => { + const oc = (((((p.interaction_contract as JsonObject).agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject).outcome_context as JsonObject; + oc.coverage_complete = false; + oc.limitations = ["missing_relation"]; + }], + ["unlinked_agent_gap", (p: JsonObject) => { + (p.goal_frontier_projection as JsonObject).acceptance_gaps = [{kind: "vision_gap", agent_id: "a1"}]; + }], + ["divergent_carriers", (p: JsonObject) => { + const s = (((((p.interaction_contract as JsonObject).agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject).goal_acceptance_contract as JsonObject; + ((s.outcome_requirements as JsonObject).outcomes as JsonObject[])[10].objective = "Diverged carrier objective"; + }], + ] as const) { + const candidate = baseNormalPayload(33); + mutate(candidate); + const out = scopeTurnGoalAcceptance(candidate, captureOpts); + assert.equal(out, candidate, `${name} must preserve full outcomes`); + } + + // Explicitly requesting include_goal_acceptance_detail keeps all 33 outcomes verbatim even with captureReferenceFile. + const source = baseNormalPayload(33); + const full = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + capture_reference_file: "state/captures/decision.reader.json", + include_goal_acceptance_detail: true, + }); + const wcReqs = (((((full.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject; + const outcomeReq = wcReqs.outcome_requirements as JsonObject; + assert.equal(outcomeReq.projection_mode, undefined); + assert.equal((outcomeReq.outcomes as JsonObject[]).every(o => o.summary_only === undefined), true); + assert.equal((full.deferred_settlement_details as JsonObject).goal_acceptance, undefined); +}); + +test("lean routine settlement_plan compacts static prose and preserves commands, identity, and triggered turns", () => { + const captureOpts = {captureReferenceFile: "state/captures/decision.reader.json"}; + const source = baseNormalPayload(4); + + // Uncaptured compactRoutineSettlementPlan without captureReferenceFile preserves full attachments and graph prose. + assert.equal(compactRoutineSettlementPlan(source), source); + assert.equal(compactRoutineSettlementPlan(source, {}), source); + + const composed = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + capture_reference_file: captureOpts.captureReferenceFile, + }); + const cli = (composed.interaction_contract as JsonObject).cli_channel as JsonObject; + const plan = cli.settlement_plan as JsonObject; + const step1 = (plan.ordered_steps as JsonObject[])[1]; + + // Routine step keeps command templates, precondition, identity ref, and expected receipt intact. + assert.match(String(step1.command_template), /--settle-turn/); + assert.match(String(step1.semantic_closeout_command_template), /--agent-vision-json/); + assert.equal(step1.precondition, "Persist evidence after independent checks."); + assert.equal(step1.idempotency_key_ref, "$.identity.effect_id"); + assert.equal(step1.expected_receipt, "durable_writeback_receipt"); + + const va = step1.vision_authoring as JsonObject; + assert.deepEqual(va, visionAuthoringContract(false)); + assert.equal(Object.keys(va).length, 11); + + const att = (step1.optional_attachments as JsonObject[])[0]; + assert.equal(att.capability_id, "explore"); + assert.equal(att.required, false); + assert.equal(att.summary_only, true); + assert.equal(att.option, "--explore-result-json "); + assert.match(String(att.cold_read_command), /explore turn-context/); + assert.equal(att.guidance, undefined); + assert.ok(Buffer.byteLength(JSON.stringify(att)) < 420); + + // Explore work_context graph drops matching static boilerplate without leaving a dangling ref. + const exploreGraph = (((((composed.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[0].content as JsonObject).graph as JsonObject; + assert.equal(exploreGraph.result_writeback_guidance, undefined); + assert.equal(exploreGraph.result_writeback_guidance_ref, undefined); + assert.equal(exploreGraph.result_writeback_guidance_summary_only, true); + assert.match(String(exploreGraph.result_writeback_guidance_cold_read_command), /explore turn-context/); + + // Consumer and envelope remain valid. + assert.deepEqual(evaluateTurnEnvelope({operation: "complete_consumer", payload: composed}), {ok: true}); + const env = evaluateTurnEnvelope({operation: "build", payload: composed, scheduler_execution_args: ""}); + assert.equal((env.action_signature as JsonObject).matches, true); + + // Triggered cases preserve full attachment prose verbatim alongside complete vision_authoring. + for (const [name, mutate] of [ + ["vision_continuation_audit", (p: JsonObject) => { p.vision_continuation_audit = {required: true}; }], + ["vision_checkpoint_required", (p: JsonObject) => { p.vision_checkpoint = {required: true}; }], + ["explore_required_cap", (p: JsonObject) => { (p.selected_todo as JsonObject).required_capabilities = ["explore"]; }], + ["required_attachment", (p: JsonObject) => { + const steps = (((p.interaction_contract as JsonObject).cli_channel as JsonObject).settlement_plan as JsonObject).ordered_steps as JsonObject[]; + ((steps[1].optional_attachments as JsonObject[])[0] as JsonObject).required = true; + }], + ] as const) { + const triggered = baseNormalPayload(4); + mutate(triggered); + const out = compactRoutineSettlementPlan(triggered, captureOpts); + const outStep1 = ((((out.interaction_contract as JsonObject).cli_channel as JsonObject).settlement_plan as JsonObject).ordered_steps as JsonObject[])[1]; + assert.deepEqual(outStep1.vision_authoring, visionAuthoringContract(false), `${name} keeps full authoring`); + assert.ok(typeof ((outStep1.optional_attachments as JsonObject[])[0]).guidance === "string", `${name} keeps attachment`); + } + + // Tampered scoped capture is rejected fail-closed by complete_consumer. + const tampered = structuredClone(composed); + (tampered.contract_binding as JsonObject).content_hash = "sha256:" + "0".repeat(64); + assert.throws(() => evaluateTurnEnvelope({operation: "complete_consumer", payload: tampered})); +}); + +test("compactRoutineSettlementPlan preserves immutable deferred attachment details and binds explore cold-reads", () => { + const source = baseNormalPayload(4); + source.registry = "state/registry.json"; + source.runtime_root = "state/runtime"; + source.goal_ref = {goal_id: "g1", goal_instance_id: "gi-1"}; + + // Captured mode keeps full 11-field vision_authoring at its canonical step location and stores + // full optional_attachments in decision.json under deferred_settlement_details, dropping them + // from progressive delivery while binding explore cold-reads to registry & runtime-root. + const captured = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: " --codex-app", + cli_argv: ["loopx"], + capture_reference_file: "state/captures/decision.reader.json", + }); + const capturedCli = (captured.interaction_contract as JsonObject).cli_channel as JsonObject; + const capturedStep1 = ((capturedCli.settlement_plan as JsonObject).ordered_steps as JsonObject[])[1]; + assert.deepEqual(capturedStep1.vision_authoring, visionAuthoringContract(false)); + assert.equal(Object.keys(capturedStep1.vision_authoring as JsonObject).length, 11); + const capturedAtt = (capturedStep1.optional_attachments as JsonObject[])[0]; + assert.equal( + capturedAtt.cold_read_command, + "loopx --registry state/registry.json --runtime-root state/runtime --format json explore turn-context --goal-id g1 --agent-id a1 --todo-id todo-current", + ); + const deferred = captured.deferred_settlement_details as JsonObject; + assert.deepEqual(deferred.optional_attachments, [exploreResultWritebackAffordance()]); + assert.deepEqual(evaluateTurnEnvelope({operation: "complete_consumer", payload: captured}), {ok: true}); + const capturedEnv = evaluateTurnEnvelope({operation: "build", payload: captured, scheduler_execution_args: " --codex-app"}); + assert.equal((capturedEnv.action_signature as JsonObject).matches, true); + + const stripped = structuredClone(captured); + delete stripped.schema_version; + delete stripped.contract_binding; + const plan = progressiveContextPlan({payload: stripped, surface: "quota_packet"}); + assert.ok((plan.deferred as JsonObject[]).some( + entry => JSON.stringify(entry.path) === JSON.stringify(["deferred_settlement_details"]), + )); + + const deliveryInput = { + operation: "progressive_context_delivery", + surface: "complete_turn", + context: captured, + native_projection: {path: "state/captures/decision.json", sha256: "a".repeat(64)}, + }; + const at = (root: unknown, path: (string | number)[]) => path.reduce( + (row, key) => (row as Record)[key], + root, + ); + const delivered = structuredClone(deliveryInput); + for (const change of evaluateTurnEnvelope(deliveryInput).changes as JsonObject[]) { + const path = change.path as (string | number)[]; + const parent = at(delivered, path.slice(0, -1)) as Record; + const key = path.at(-1)!; + if (change.remove) delete parent[key]; + else parent[key] = structuredClone(change.from ? at(deliveryInput, change.from as (string | number)[]) : change.value); + } + assert.equal((delivered.context as JsonObject).deferred_settlement_details, undefined); + + // Uncaptured mode omits deferred_settlement_details and preserves all 14 Explore attachment fields + // and explore graph guidance verbatim alongside complete 11-field vision_authoring. + const uncaptured = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: " --codex-app", + cli_argv: ["loopx"], + }); + assert.equal(uncaptured.deferred_settlement_details, undefined); + const uncapturedCli = (uncaptured.interaction_contract as JsonObject).cli_channel as JsonObject; + const uncapturedStep1 = ((uncapturedCli.settlement_plan as JsonObject).ordered_steps as JsonObject[])[1]; + assert.deepEqual(uncapturedStep1.vision_authoring, visionAuthoringContract(false)); + assert.deepEqual(uncapturedStep1.optional_attachments, [exploreResultWritebackAffordance()]); + const uncapturedGraph = (((((uncaptured.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[0].content as JsonObject).graph as JsonObject; + assert.equal(uncapturedGraph.result_writeback_guidance_summary_only, undefined); + assert.match(String(uncapturedGraph.result_writeback_guidance_ref), /optional_attachments/); +}); + +test("scoped goal_acceptance cold_read_command binds original cli_argv, registry, and runtime_root across summary, rows, and first read", () => { + const source = baseNormalPayload(9); + source.registry = "state/ws a/registry.json"; + source.runtime_root = "state/ws a/runtime"; + const rawOutcomes = (((((((source.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject).outcomes as JsonObject[]; + const expectedOutcomesSha = canonicalHash(rawOutcomes); + + const composed = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + cli_argv: ["/opt/custom loopx", "--cli-bin", "/opt/custom loopx"], + capture_reference_file: "state/captures/decision.reader.json", + }); + const expectedCmd = + "'/opt/custom loopx' --cli-bin '/opt/custom loopx' --registry 'state/ws a/registry.json' --runtime-root 'state/ws a/runtime' --format json goal-acceptance inspect --goal-id g1"; + const expectedCaptureCmd = + "'/opt/custom loopx' --cli-bin '/opt/custom loopx' --format json quota context-read --reference-file state/captures/decision.reader.json --select /deferred_settlement_details/goal_acceptance"; + const wcReqs = ((((((composed.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject; + assert.equal(wcReqs.projection_mode, SCOPED_OUTCOME_PROJECTION_MODE); + assert.equal(wcReqs.full_outcome_count, 9); + assert.equal(wcReqs.outcome_revision, 33); + assert.equal(wcReqs.full_outcomes_sha256, expectedOutcomesSha); + assert.equal(wcReqs.capture_read_command, expectedCaptureCmd); + assert.equal(wcReqs.cold_read_command, expectedCmd); + assert.match(String(wcReqs.cold_read_instruction), /capture_read_command reads immutable admission-time goal_acceptance/); + assert.match(String(wcReqs.cold_read_instruction), /cold_read_command and --include-detail goal_acceptance query current live workspace state/); + + const compactRows = (wcReqs.outcomes as JsonObject[]).filter(row => row.summary_only === true); + assert.equal(compactRows.length, 8); + assert.ok(compactRows.every(row => row.cold_read_command === expectedCmd)); + + // Progressive first-read retains summary metadata, full_outcomes_sha256, outcome_revision, and bound commands. + const deliveryInput = { + operation: "progressive_context_delivery", + surface: "complete_turn", + context: composed, + native_projection: {path: "state/captures/decision.json", sha256: "a".repeat(64)}, + }; + const at = (root: unknown, path: (string | number)[]) => path.reduce( + (row, key) => (row as Record)[key], + root, + ); + const delivered = structuredClone(deliveryInput); + for (const change of evaluateTurnEnvelope(deliveryInput).changes as JsonObject[]) { + const path = change.path as (string | number)[]; + const parent = at(delivered, path.slice(0, -1)) as Record; + const key = path.at(-1)!; + if (change.remove) delete parent[key]; + else parent[key] = structuredClone(change.from ? at(deliveryInput, change.from as (string | number)[]) : change.value); + } + const deliveredReqs = (((((((delivered.context as JsonObject).interaction_contract as JsonObject) + .agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject; + assert.equal(deliveredReqs.cold_read_command, expectedCmd); + assert.equal(deliveredReqs.full_outcomes_sha256, expectedOutcomesSha); + assert.equal(deliveredReqs.outcome_revision, 33); + assert.equal(deliveredReqs.cold_read_instruction, wcReqs.cold_read_instruction); + const deliveredCompact = (deliveredReqs.outcomes as JsonObject[]).filter(row => row.summary_only === true); + assert.equal(deliveredCompact.length, 8); + assert.ok(deliveredCompact.every(row => row.cold_read_command === expectedCmd)); + + // summaryOutcomeIndexRow via replanGoalContext preserves source-bound cold_read_command on summary_only rows. + const gaContract = (((((composed.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject).goal_acceptance_contract as JsonObject; + const indexed = replanGoalContext({ + ...composed, + autonomous_replan_obligation: {replan_context: {core_goal: {acceptance_contract: gaContract}}}, + }, {acceptance: "loopx quota replan-view --decision-file d.json"}); + const indexRows = ((indexed.acceptanceIndex as JsonObject).outcomes as JsonObject[]).filter(r => r.summary_only === true); + assert.equal(indexRows.length, 8); + assert.ok(indexRows.every(row => row.cold_read_command === expectedCmd)); + + // cli_registry / cli_runtime_root overrides bind cold reads without altering payload.registry/runtime_root. + const anchored = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + cli_argv: ["loopx"], + capture_reference_file: "state/captures/decision.reader.json", + cli_registry: "/workspace/ws a/.loopx/registry.json", + cli_runtime_root: "/workspace/ws a/runtime", + }); + const anchoredReqs = ((((((anchored.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject; + assert.equal( + anchoredReqs.cold_read_command, + "loopx --registry '/workspace/ws a/.loopx/registry.json' --runtime-root '/workspace/ws a/runtime' --format json goal-acceptance inspect --goal-id g1", + ); + assert.equal(anchored.registry, "state/ws a/registry.json"); + assert.equal(anchored.runtime_root, "state/ws a/runtime"); +}); + +test("captured scoped goal_acceptance preserves full admission outcomes in deferred_settlement_details and separates capture_read_command from live cold_read_command", () => { + const source = baseNormalPayload(9); + source.registry = "state/ws a/registry.json"; + source.runtime_root = "state/ws a/runtime"; + const originalContract = structuredClone( + ((((source.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject, + ).goal_acceptance_contract as JsonObject; + const originalReqs = originalContract.outcome_requirements as JsonObject; + const expectedOutcomesSha = canonicalHash(originalReqs.outcomes); + + const captured = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + cli_argv: ["/opt/custom loopx", "--cli-bin", "/opt/custom loopx"], + capture_reference_file: "state/captures/decision.reader.json", + }); + + // 1. Captured decision preserves BOTH optional_attachments and unmodified admission-time goal_acceptance. + const deferred = captured.deferred_settlement_details as JsonObject; + assert.deepEqual(deferred.optional_attachments, [exploreResultWritebackAffordance()]); + assert.deepEqual(deferred.goal_acceptance, originalContract); + + // 2. Summary & summary_only rows distinguish immutable capture_read_command from live cold_read_command. + const wcReqs = ((((((captured.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject; + const expectedSummaryCaptureCmd = + "'/opt/custom loopx' --cli-bin '/opt/custom loopx' --format json quota context-read --reference-file state/captures/decision.reader.json --select /deferred_settlement_details/goal_acceptance"; + const expectedLiveCmd = + "'/opt/custom loopx' --cli-bin '/opt/custom loopx' --registry 'state/ws a/registry.json' --runtime-root 'state/ws a/runtime' --format json goal-acceptance inspect --goal-id g1"; + assert.equal(wcReqs.capture_read_command, expectedSummaryCaptureCmd); + assert.equal(wcReqs.cold_read_command, expectedLiveCmd); + assert.equal(wcReqs.full_outcomes_sha256, expectedOutcomesSha); + assert.equal(wcReqs.outcome_revision, 33); + assert.match(String(wcReqs.cold_read_instruction), /capture_read_command reads immutable admission-time goal_acceptance/); + assert.match(String(wcReqs.cold_read_instruction), /cold_read_command and --include-detail goal_acceptance query current live workspace state/); + + const compactRows = (wcReqs.outcomes as JsonObject[]).filter(row => row.summary_only === true); + assert.equal(compactRows.length, 8); + compactRows.forEach((row, idx) => { + const outcomeIndex = idx + 1; + assert.equal( + row.capture_read_command, + `'/opt/custom loopx' --cli-bin '/opt/custom loopx' --format json quota context-read --reference-file state/captures/decision.reader.json --select /deferred_settlement_details/goal_acceptance/outcome_requirements/outcomes/${outcomeIndex}`, + ); + assert.equal(row.cold_read_command, expectedLiveCmd); + assert.match(String(row.read_modes), /capture_read_command=immutable admission baseline/); + assert.match(String(row.read_modes), /cold_read_command=live workspace inspect/); + }); + + // 3. Consumer validation, build, progressive_context_delivery, and replanGoalContext keep deferred_settlement_details pruned in first read. + assert.deepEqual(evaluateTurnEnvelope({operation: "complete_consumer", payload: captured}), {ok: true}); + const env = evaluateTurnEnvelope({operation: "build", payload: captured, scheduler_execution_args: ""}); + assert.equal((env.action_signature as JsonObject).matches, true); + + const stripped = structuredClone(captured); + delete stripped.schema_version; + delete stripped.contract_binding; + const plan = progressiveContextPlan({payload: stripped, surface: "quota_packet"}); + const deferredEntry = (plan.deferred as JsonObject[]).find( + entry => JSON.stringify(entry.path) === JSON.stringify(["deferred_settlement_details"]), + )!; + assert.match(String(deferredEntry.read_instruction), /capture_read_command/); + + const deliveryInput = { + operation: "progressive_context_delivery", + surface: "complete_turn", + context: captured, + native_projection: {path: "state/captures/decision.json", sha256: "a".repeat(64)}, + }; + const at = (root: unknown, path: (string | number)[]) => path.reduce( + (row, key) => (row as Record)[key], + root, + ); + const delivered = structuredClone(deliveryInput); + for (const change of evaluateTurnEnvelope(deliveryInput).changes as JsonObject[]) { + const path = change.path as (string | number)[]; + const parent = at(delivered, path.slice(0, -1)) as Record; + const key = path.at(-1)!; + if (change.remove) delete parent[key]; + else parent[key] = structuredClone(change.from ? at(deliveryInput, change.from as (string | number)[]) : change.value); + } + assert.equal((delivered.context as JsonObject).deferred_settlement_details, undefined); + const deliveredReqs = (((((((delivered.context as JsonObject).interaction_contract as JsonObject) + .agent_channel as JsonObject).work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject; + assert.equal(deliveredReqs.capture_read_command, expectedSummaryCaptureCmd); + assert.equal(deliveredReqs.cold_read_command, expectedLiveCmd); + assert.equal(deliveredReqs.cold_read_instruction, wcReqs.cold_read_instruction); + const deliveredCompact = (deliveredReqs.outcomes as JsonObject[]).filter(row => row.summary_only === true); + assert.equal(deliveredCompact.length, 8); + assert.equal(deliveredCompact[0].capture_read_command, compactRows[0].capture_read_command); + assert.equal(deliveredCompact[0].read_modes, compactRows[0].read_modes); + + const gaContract = (((((captured.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[1].content as JsonObject).goal_acceptance_contract as JsonObject; + const indexed = replanGoalContext({ + ...captured, + autonomous_replan_obligation: {replan_context: {core_goal: {acceptance_contract: gaContract}}}, + }, {acceptance: "loopx quota replan-view --decision-file d.json"}); + const indexRows = ((indexed.acceptanceIndex as JsonObject).outcomes as JsonObject[]).filter(r => r.summary_only === true); + assert.equal(indexRows.length, 8); + assert.equal(indexRows[0].capture_read_command, compactRows[0].capture_read_command); + assert.equal(indexRows[0].read_modes, compactRows[0].read_modes); +});