diff --git a/loopx/cli_commands/quota_capture.py b/loopx/cli_commands/quota_capture.py index b26980e05a..53891304b3 100644 --- a/loopx/cli_commands/quota_capture.py +++ b/loopx/cli_commands/quota_capture.py @@ -322,11 +322,12 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa root=getattr(args, "codex_context_root", None), create=True) except NativeContextSessionUnavailable: directory = None # Current full input, no fabricated native journal. + detail_sections = quota_detail_sections_from_args(args) decision_ref = ( _saved_decision_reference(capture_directory, expected_sha256=capture_id) if progressive_enabled and (directory is not None or not bool(getattr(args, "begin_turn", False))) - and "vision" not in quota_detail_sections_from_args(args) + and "vision" not in detail_sections else None ) prepared = prepare_codex_context(payload, directory=directory, @@ -335,7 +336,9 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa capture_id=capture_id, continuity_generation=getattr(args, "_context_delivery_generation", None), progressive_enabled=progressive_enabled, captured_decision=decision_ref, - max_page_output_bytes=getattr(args, "max_page_output_bytes", None)) + max_page_output_bytes=getattr(args, "max_page_output_bytes", None), + include_goal_acceptance_detail="goal_acceptance" in detail_sections, + include_agent_todos_detail="agent-todos" in detail_sections) recovery = prepared.delivery.get("recovery") view = native_context_capture_view(prepared.delivery, capture_directory, context_directory=directory, progressive_enabled=progressive_enabled, initial_read_plan=prepared.initial_read_plan, @@ -376,8 +379,9 @@ def progressive_context_capture_view(payload: dict[str, Any], args: argparse.Nam # Only a fresh stateless source can supply this route. Saved and explicitly # captured decisions keep the reader chosen by their existing callers. + detail_sections = quota_detail_sections_from_args(args) stage_from_projection = (directory is None and captured_decision is None - and "vision" not in quota_detail_sections_from_args(args)) + and "vision" not in detail_sections) if directory is None: root = Path(_private_transport_root(runtime_root)) try: @@ -393,7 +397,9 @@ def progressive_context_capture_view(payload: dict[str, Any], args: argparse.Nam transport = _capture_selection_transport_template(payload, args, capture_root=directory.parent) required, reference = capture_progressive_context(payload, directory=directory, surface=surface, selection_command_args_template=transport, captured_decision=captured_decision, - replan_reader_argv=reader_argv if stage_from_projection else None) + replan_reader_argv=reader_argv if stage_from_projection else None, + include_goal_acceptance_detail="goal_acceptance" in detail_sections, + include_agent_todos_detail="agent-todos" in detail_sections) view = native_context_capture_view(required, directory, captured_recovery=reference, metadata={"context_delivery": native_context_activation(args), **({"capture_sha256": args.capture_sha256} if getattr(args, "capture_sha256", None) else {})}, diff --git a/loopx/cli_commands/quota_result_delivery.py b/loopx/cli_commands/quota_result_delivery.py index c66dcf55ea..145ac4bebb 100644 --- a/loopx/cli_commands/quota_result_delivery.py +++ b/loopx/cli_commands/quota_result_delivery.py @@ -531,6 +531,8 @@ def _publish_quota_result( goal_id=decision_identity[0], agent_id=decision_identity[1], surface=quota_context_surface(captured_payload), + include_goal_acceptance_detail="goal_acceptance" in detail_sections, + include_agent_todos_detail="agent-todos" in detail_sections, ) if ( not deferred_context diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index 27286b396d..460883e15e 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -14,7 +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 {SCOPED_OUTCOME_PROJECTION_MODE, SCOPED_OUTCOME_THRESHOLD} from "./turn_envelope_scoping.ts"; import {createHash} from "node:crypto"; @@ -32,6 +32,8 @@ const MAX_INLINE_WORK_OPENING_BYTES = 7000; const SETTLEMENT_PLAN_PATH = ["interaction_contract", "cli_channel", "settlement_plan"]; const REPLAN_CONTEXT_PATH = ["autonomous_replan_obligation", "replan_context"]; const COMPLETE_REQUIREMENTS_CLAUSE = "This view retains complete requirements and current review/check states. "; +const PROGRESSIVE_COMPLETE_REQUIREMENTS_CLAUSE = + "Read the complete acceptance basis, cumulative outcome requirements, work links and current review/check states. "; const pointer = (path: Path): string => path.length ? "/" + path.map(key => String(key).replaceAll("~", "~0").replaceAll("/", "~1")).join("/") : ""; const at = (root: unknown, path: Path): unknown => path.reduce((row, key) => @@ -517,7 +519,13 @@ function inlineReadSections(request: JsonObject, required: JsonObject, exactBody /** Return paths instead of round-tripping the caller's JSON numeric values * through JS. The IO adapter performs only these typed-owner-selected edits. */ export function progressiveContextPlan(request: JsonObject, - scopes: readonly PreparationScopeDetail[] = []): JsonObject { + scopes: readonly PreparationScopeDetail[] = [], + extraReferences: readonly JsonObject[] = []): JsonObject { + const includeGoalAcceptanceDetail = request.include_goal_acceptance_detail === undefined ? false + : requireBoolean(request.include_goal_acceptance_detail, "include_goal_acceptance_detail"); + if (request.include_agent_todos_detail !== undefined) { + requireBoolean(request.include_agent_todos_detail, "include_agent_todos_detail"); + } const payload = requireJsonObject(request.payload, "captured context"); const deferred: JsonObject[] = [], instructions: JsonObject[] = []; const unchanged = {deferred, instructions}; @@ -526,12 +534,25 @@ export function progressiveContextPlan(request: JsonObject, if (request.surface !== "quota_packet" || payload.ok !== true || payload.schema_version !== undefined || payload.contract_binding !== undefined || payload.context_details !== undefined || payload.context_reference_instruction !== undefined) return unchanged; - const references = quotaSummaryReferences(payload); - const carriers: Path[] = [ - ["planning_horizon", "core_goal", "acceptance_contract"], - ["autonomous_replan_obligation", "replan_context", "core_goal", "acceptance_contract"], - ["agent_todo_summary", "goal_acceptance_contract"], + const references = [...quotaSummaryReferences(payload), ...extraReferences]; + const carriers: {path: Path; suggestedIds?: Set}[] = [ + {path: ["planning_horizon", "core_goal", "acceptance_contract"]}, + {path: ["agent_todo_summary", "goal_acceptance_contract"]}, + {path: ["autonomous_replan_obligation", "replan_context", "core_goal", "acceptance_contract"]}, ]; + const selectedTodo = jsonObject(payload.selected_todo); + const relevantTodoIds = new Set( + [selectedTodo?.todo_id, selectedTodo?.unblocks_todo_id, + ...(Array.isArray(selectedTodo?.dependency_todo_ids) ? selectedTodo.dependency_todo_ids : []), + ...(Array.isArray(selectedTodo?.successor_todo_ids) ? selectedTodo.successor_todo_ids : [])] + .filter((id): id is string => typeof id === "string" && id.length > 0), + ); + const gapOutcomeIds = new Set( + (Array.isArray(jsonObject(payload.goal_frontier_projection)?.acceptance_gaps) + ? jsonObject(payload.goal_frontier_projection)!.acceptance_gaps as unknown[] : []) + .map(gap => jsonObject(gap)?.outcome_id) + .filter((id): id is string => typeof id === "string" && id.length > 0), + ); const agent = ["interaction_contract", "agent_channel"]; const sourcePath = [...agent, "work_context", "sources"]; const sources = at(payload, sourcePath); @@ -539,12 +560,24 @@ export function progressiveContextPlan(request: JsonObject, const source = jsonObject(value), content = jsonObject(source?.content); if (source?.source === "goal_acceptance" && content?.ok !== false && content?.read_complete !== false && (content?.status === undefined || content.status === "loaded") - && (source.reason === undefined || typeof source.reason === "string" && source.reason.includes(FULL_OUTCOME_READ_GUIDANCE))) - carriers.push([...sourcePath, i, "content", "goal_acceptance_contract"]); + && (source.reason === undefined || typeof source.reason === "string" && source.reason.includes(FULL_OUTCOME_READ_GUIDANCE))) { + const outcomeCtx = jsonObject(content?.outcome_context); + const suggested = Array.isArray(outcomeCtx?.suggested_outcome_ids) + ? new Set(outcomeCtx.suggested_outcome_ids.filter((id): id is string => typeof id === "string" && id.length > 0)) + : undefined; + carriers.push({path: [...sourcePath, i, "content", "goal_acceptance_contract"], suggestedIds: suggested}); + } }); - for (const carrier of carriers) { + let deferredHistoricalRequirements = false; + for (const {path: carrier, suggestedIds} of carriers) { const path = [...carrier, "outcome_requirements"], declaration = jsonObject(at(payload, path)); if (declaration?.schema_version !== GOAL_OUTCOMES_SCHEMA || !Array.isArray(declaration.outcomes)) continue; + const isReplanObligationCarrier = carrier[0] === "autonomous_replan_obligation" + && payload.effective_action === EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED; + const deferLargeHistoricalOutcomes = !includeGoalAcceptanceDetail + && !isReplanObligationCarrier + && declaration.outcomes.length > SCOPED_OUTCOME_THRESHOLD + && declaration.projection_mode !== SCOPED_OUTCOME_PROJECTION_MODE; declaration.outcomes.forEach((value, i) => { const row = jsonObject(value); if (!row || !known(row, ["id", "owner_agent_id", "declaration_owner_agent_id", "objective", "revision", "requirements", "todo_ids", "sources", "basis_digest", "work"]) @@ -571,11 +604,28 @@ export function progressiveContextPlan(request: JsonObject, } const parent = [...path, "outcomes", i]; const index_key = "supporting_material_pointer"; + const isActiveOutcome = suggestedIds?.has(row.id) === true + || gapOutcomeIds.has(row.id) + || (Array.isArray(row.todo_ids) && row.todo_ids.some(id => typeof id === "string" && relevantTodoIds.has(id))); + if (deferLargeHistoricalOutcomes && !isActiveOutcome) { + if (row.sources.length) deferred.push({path: [...parent, "sources"], parent, index_key}); + if (row.requirements.length) { + deferred.push({path: [...parent, "requirements"], parent, index_key}); + deferredHistoricalRequirements = true; + } + return; + } if (row.sources.length) deferred.push({path: [...parent, "sources"], parent, index_key}); for (const j of reviews) for (const field of ["note", "evidence_refs"]) deferred.push({path: [...parent, "requirements", j, "agent_review", field], parent, index_key}); }); } + const progressiveOutcomeGuidance = deferredHistoricalRequirements + ? PROGRESSIVE_OUTCOME_READ_GUIDANCE.replace( + PROGRESSIVE_COMPLETE_REQUIREMENTS_CLAUSE, + "Read the complete acceptance basis, work links and current review/check states. Active/suggested outcomes retain complete requirements here; historical non-selected outcome requirements remain in context_details (read via supporting_material_pointer before dependent work). ", + ) + : PROGRESSIVE_OUTCOME_READ_GUIDANCE; // Replace only the exact source-owned obligation. Other merged obligations, // objective adoption, unknown provider prose and pending reads remain intact. for (const listPath of deferred.length ? [sourcePath, [...agent, "required_reads"]] : []) { @@ -586,7 +636,7 @@ export function progressiveContextPlan(request: JsonObject, if (row?.source === "goal_acceptance" && typeof row.reason === "string" && row.reason.includes(FULL_OUTCOME_READ_GUIDANCE)) instructions.push({path: [...listPath, i, "reason"], value: - row.reason.replace(FULL_OUTCOME_READ_GUIDANCE, PROGRESSIVE_OUTCOME_READ_GUIDANCE)}); + row.reason.replace(FULL_OUTCOME_READ_GUIDANCE, progressiveOutcomeGuidance)}); }); } const deferredDetails = jsonObject(at(payload, ["deferred_settlement_details"])); @@ -617,7 +667,12 @@ export function progressiveContextPlan(request: JsonObject, const pathStartsWith = (path: Path, start: Path) => start.every((key, i) => path[i] === key); function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSourceValues, - plan = progressiveContextPlan({payload: request.context, surface: request.surface})): + plan = progressiveContextPlan({ + payload: request.context, + surface: request.surface, + ...(request.include_goal_acceptance_detail === undefined ? {} : {include_goal_acceptance_detail: request.include_goal_acceptance_detail}), + ...(request.include_agent_todos_detail === undefined ? {} : {include_agent_todos_detail: request.include_agent_todos_detail}), + })): {context: JsonObject; tokens: [Path, string][]; projected: boolean} { const original = requireJsonObject(request.context, "current projection"); const staged = jsonObject(plan.staged_context); @@ -687,6 +742,12 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour }); const sourcePath: Path = ["interaction_contract", "agent_channel", "work_context", "sources"]; const sources = at(context, sourcePath); + const hasDeferredOutcomeRequirements = deferred.some( + edit => Array.isArray(edit.path) && edit.path.at(-1) === "requirements", + ); + const requirementsClause = hasDeferredOutcomeRequirements + ? "Active/suggested outcomes retain complete requirements and current review/check states here; historical non-selected outcome requirements are supporting material in this same capture (append /requirements alongside supporting_material_pointer or use unread_context_index.pointers). " + : COMPLETE_REQUIREMENTS_CLAUSE; required.context_details = {path: details.path, sha256: details.sha256, ...(typeof details.command_template === "string" ? {command_template: details.command_template} : {}), source_path: details.path, @@ -702,7 +763,7 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour }) : [], }, instruction: deferred.map(edit => typeof edit.read_instruction === "string" ? edit.read_instruction : "").join("") - + COMPLETE_REQUIREMENTS_CLAUSE + + requirementsClause + "Source history, review reasoning and evidence references are supporting material. " + "Read them from this same immutable capture when a decision, verification or review depends on them. " + "Use the outcome's supporting_material_pointer when shown, or remove /id from its selected JSON pointer. " @@ -1274,6 +1335,11 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly } } const outcomesPath = [...requirementsPath, "outcomes"]; + const hasContainerOutcomeReadCommands = requirements?.projection_mode === SCOPED_OUTCOME_PROJECTION_MODE + && typeof requirements.capture_read_command === "string" + && typeof requirements.cold_read_command === "string" + && typeof requirements.cold_read_instruction === "string" + && Array.isArray(outcomes) && outcomes.length > SCOPED_OUTCOME_THRESHOLD; const canDeferSuggested = openingBudget !== undefined && readyIdentity !== undefined && expanded.size > 0 && inlineSupportingDetails && details?.outcome_support_from_id === true && details.path === supportingSource?.path && details.sha256 === supportingSource?.sha256 @@ -1292,6 +1358,7 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly const row = object(_outcome), outcomeId = row?.id; const suggested = typeof outcomeId === "string" && expanded.has(outcomeId); if (suggested && !deferSuggested) { include(...outcome); return; } + if (row?.summary_only === true && hasContainerOutcomeReadCommands) 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"]) { diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index 1294052695..77a7a58e6a 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -463,6 +463,8 @@ def prepare_context_delivery( surface: str = "work_context", native_projection: Mapping[str, Any] | None = None, consumed_pointers: Mapping[str, str] | None = None, observe_first_read: bool = False, include_initial_read_plan: bool = False, + include_goal_acceptance_detail: bool = False, + include_agent_todos_detail: bool = False, ) -> dict[str, Any]: """Prepare under the Host's explicit continuity basis, not a model assertion. @@ -479,6 +481,10 @@ def prepare_context_delivery( source["native_projection"] = dict(native_projection) if include_initial_read_plan: source["include_initial_read_plan"] = True + if include_goal_acceptance_detail: + source["include_goal_acceptance_detail"] = True + if include_agent_todos_detail: + source["include_agent_todos_detail"] = True if consumed_pointers is not None: source["consumed_pointers"] = dict(consumed_pointers) if consumed_pointers and observe_first_read: @@ -494,9 +500,15 @@ def prepare_context_delivery( def prepare_progressive_context(context: Mapping[str, Any], *, source_reference: Mapping[str, Any], - surface: str = "quota_packet") -> dict[str, Any]: + surface: str = "quota_packet", + include_goal_acceptance_detail: bool = False, + include_agent_todos_detail: bool = False) -> dict[str, Any]: """Stateless IO adapter to the same typed presentation owner; no Delta identity.""" - source = dict(context=dict(context), native_projection=dict(source_reference), surface=surface) + source: dict[str, Any] = dict( + context=dict(context), native_projection=dict(source_reference), surface=surface, + **({"include_goal_acceptance_detail": True} if include_goal_acceptance_detail else {}), + **({"include_agent_todos_detail": True} if include_agent_todos_detail else {}), + ) return _apply_context_projection_changes(source, _turn_envelope_result("progressive_context_delivery", **source, source_edits=True)) diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 3ed18242a2..ef365fe6f2 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1,3 +1,4 @@ +import {isDeepStrictEqual} from "node:util"; import { EXECUTION_PREPARATION_SCHEMA_VERSION } from "../work_items/execution_preparation.ts"; import { leaseEpoch } from "../work_items/task_lease_record.ts"; import { capturedContextSelection } from "./context_selection.ts"; @@ -952,17 +953,57 @@ function checkedContextPresentationSource(request: JsonObject): JsonObject { return context; } +function legacyRecommendationFallbackReferences(payload: JsonObject): JsonObject[] { + const rootFallback = jsonObject(payload.blocked_priority_fallback); + const recFallback = jsonObject(object(payload.heartbeat_recommendation).blocked_priority_fallback); + if (!rootFallback || !recFallback || !isDeepStrictEqual(rootFallback, recFallback)) return []; + return [{ + path: ["heartbeat_recommendation", "blocked_priority_fallback"], + from: ["blocked_priority_fallback"], + value: {context_ref: "/blocked_priority_fallback"}, + }]; +} + +function presentationDetailFlags(request: JsonObject): { + includeGoalAcceptanceDetail: boolean; + includeAgentTodosDetail: boolean; +} { + return { + includeGoalAcceptanceDetail: request.include_goal_acceptance_detail === undefined ? false + : requireBoolean(request.include_goal_acceptance_detail, "include_goal_acceptance_detail"), + includeAgentTodosDetail: request.include_agent_todos_detail === undefined ? false + : requireBoolean(request.include_agent_todos_detail, "include_agent_todos_detail"), + }; +} + +function buildContextPresentationPlan( + payload: JsonObject, + surface: unknown, + flags: {includeGoalAcceptanceDetail: boolean; includeAgentTodosDetail: boolean}, +): JsonObject { + return progressiveContextPlan( + { + payload, + surface, + ...(flags.includeGoalAcceptanceDetail ? {include_goal_acceptance_detail: true} : {}), + ...(flags.includeAgentTodosDetail ? {include_agent_todos_detail: true} : {}), + }, + progressivePreparationScopes(payload), + flags.includeAgentTodosDetail ? [] : legacyRecommendationFallbackReferences(payload), + ); +} + /** The unsigned root is used for path selection; edits and recovery still * address the unchanged, signed original capture. */ function checkedContextPresentationPlan(request: JsonObject): JsonObject { + const flags = presentationDetailFlags(request); const context = checkedContextPresentationSource(request); if (request.surface !== "complete_turn") - return nativeReplanPresentation(request) ?? contextPresentationPlan(request); + return nativeReplanPresentation(request) ?? contextPresentationPlan(request, flags); const source = {...context}; delete source.schema_version; delete source.contract_binding; - return nativeReplanPresentation(request) ?? - progressiveContextPlan({payload: source, surface: "quota_packet"}, progressivePreparationScopes(source)); + return nativeReplanPresentation(request) ?? buildContextPresentationPlan(source, "quota_packet", flags); } function completeWorkIdentity(decision: JsonObject): JsonObject { @@ -1522,9 +1563,12 @@ function progressivePreparationScopes(payload: JsonObject): PreparationScopeDeta return scopes; } -function contextPresentationPlan(request: JsonObject): JsonObject { +function contextPresentationPlan( + request: JsonObject, + flags = presentationDetailFlags(request), +): JsonObject { const context = requireJsonObject(request.context, "current projection"); - return progressiveContextPlan({payload: context, surface: request.surface}, progressivePreparationScopes(context)); + return buildContextPresentationPlan(context, request.surface, flags); } const resolveViewWriteback = ( @@ -1750,6 +1794,7 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { return prepareProgressiveContext(request, checkedContextPresentationPlan(request)); if (operation === "context_delivery") { if (request.native_projection === undefined) { + presentationDetailFlags(request); if (request.surface === "complete_turn") checkedContextPresentationSource(request); return prepareContextDelivery(request, LEGACY_QUOTA_CONTEXT_FIELDS); } diff --git a/loopx/control_plane/quota/turn_envelope_scoping.ts b/loopx/control_plane/quota/turn_envelope_scoping.ts index 6be276f5f1..336cb7b4e2 100644 --- a/loopx/control_plane/quota/turn_envelope_scoping.ts +++ b/loopx/control_plane/quota/turn_envelope_scoping.ts @@ -120,8 +120,7 @@ function exploreColdReadCommand(options: { return parts.join(" "); } -function isRoutineNormalRun(payload: JsonObject): boolean { - if (payload.effective_action !== EffectiveAction.NORMAL_RUN || payload.normal_delivery_allowed !== true) return false; +function isNonReplanTurn(payload: JsonObject): boolean { 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; @@ -132,6 +131,19 @@ function isRoutineNormalRun(payload: JsonObject): boolean { return true; } +function isRoutineNormalRun(payload: JsonObject): boolean { + if (payload.effective_action !== EffectiveAction.NORMAL_RUN || payload.normal_delivery_allowed !== true) return false; + return isNonReplanTurn(payload); +} + +function isScopableGoalAcceptanceTurn(payload: JsonObject): boolean { + const action = payload.effective_action; + if (action !== EffectiveAction.NORMAL_RUN && action !== EffectiveAction.UNSETTLED_HOST_TURN_RECOVERY) { + return false; + } + return isNonReplanTurn(payload); +} + function allRequirementsSatisfied(requirements: unknown[]): boolean { if (requirements.length === 0) return false; return requirements.every(value => { @@ -336,17 +348,22 @@ export function scopeTurnGoalAcceptance( payload: JsonObject, options: ScopeGoalAcceptanceOptions = {}, ): JsonObject { - if (!isRoutineNormalRun(payload)) return payload; + if (!isScopableGoalAcceptanceTurn(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 receiptIdentity = jsonObject(object(payload.heartbeat_receipt).settlement_identity); + const todoId = nonEmptyString(selectedTodo?.todo_id) + ?? (payload.effective_action === EffectiveAction.UNSETTLED_HOST_TURN_RECOVERY + ? nonEmptyString(receiptIdentity?.todo_id) + : null); + if (!goalId || !agentId) return payload; const owner = findSingleInlineOutcomeOwner(payload); if (!owner) return payload; + if (owner.kind === "work_context" && (!selectedTodo || !todoId)) return payload; const {contract, requirements, sourceContent} = owner; if (requirements.projection_mode === SCOPED_OUTCOME_PROJECTION_MODE) return payload; if (requirements.current_lifetime !== true) return payload; @@ -383,11 +400,12 @@ export function scopeTurnGoalAcceptance( const gaps = collectAcceptanceGaps(payload, requirements, agentId); if (gaps.globalAmbiguity) return payload; + const unblocksTodoId = nonEmptyString(selectedTodo?.unblocks_todo_id); 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)!] : []), + ...(todoId ? [todoId] : []), + ...stringList(selectedTodo?.dependency_todo_ids), + ...stringList(selectedTodo?.successor_todo_ids), + ...(unblocksTodoId ? [unblocksTodoId] : []), ]); const cliArgv = options.cliArgv ?? ["loopx"]; diff --git a/loopx/control_plane/turn_driver/codex_context.py b/loopx/control_plane/turn_driver/codex_context.py index 3d1be0df1a..a2a50a877d 100644 --- a/loopx/control_plane/turn_driver/codex_context.py +++ b/loopx/control_plane/turn_driver/codex_context.py @@ -999,6 +999,8 @@ def prepare_codex_context(payload: dict[str, Any], *, directory: str | None, cap hook_session: str | None = None, saved_capture: bool = False, publication_guard: Callable[[], AbstractContextManager[None]] = nullcontext, + include_goal_acceptance_detail: bool = False, + include_agent_todos_detail: bool = False, ) -> NativeContextPreparation: """Commit current recovery before optional projection or candidate updates. @@ -1024,6 +1026,8 @@ def prepare_codex_context(payload: dict[str, Any], *, directory: str | None, cap surface=surface, selection_command_args_template=selection_command_args_template, captured_decision=captured_decision, + include_goal_acceptance_detail=include_goal_acceptance_detail, + include_agent_todos_detail=include_agent_todos_detail, )[0]) try: with _locked(directory) as root: @@ -1101,7 +1105,9 @@ def publish_recovery(reference: dict[str, Any]) -> None: if include_initial_read_plan and progressive else {}), "command_template": recovery["command"] + " --select ''", } if presentation else None, consumed_pointers=state.get("consumed_pointers"), - observe_first_read=progressive) + observe_first_read=progressive, + include_goal_acceptance_detail=include_goal_acceptance_detail, + include_agent_todos_detail=include_agent_todos_detail) except (EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc: if check_saved_source and isinstance(exc, EffectRuntimeRejected): raise QuotaDecisionTransportError(str(exc)) from exc diff --git a/loopx/control_plane/turn_driver/decision_capture.py b/loopx/control_plane/turn_driver/decision_capture.py index 96dff8973a..046e4c42bf 100644 --- a/loopx/control_plane/turn_driver/decision_capture.py +++ b/loopx/control_plane/turn_driver/decision_capture.py @@ -545,7 +545,9 @@ def capture_progressive_context(payload: dict[str, Any], *, directory: Path, surface: str = "quota_packet", selection_command_args_template: str | None = None, captured_decision: dict[str, str] | None = None, - replan_reader_argv: list[str] | None = None) -> tuple[dict[str, Any], dict[str, Any]]: + replan_reader_argv: list[str] | None = None, + include_goal_acceptance_detail: bool = False, + include_agent_todos_detail: bool = False) -> tuple[dict[str, Any], dict[str, Any]]: """Publish the complete current source before optional stateless presentation. The typed owner applies the shrink guard. This neither creates a native @@ -563,7 +565,8 @@ def capture_progressive_context(payload: dict[str, Any], *, directory: Path, **({"replan_reader_argv": replan_reader_argv} if replan_reader_argv is not None else {}), "source_path": source["path"], "command_template": source["command"] + " --select ''", - }) + }, include_goal_acceptance_detail=include_goal_acceptance_detail, + include_agent_todos_detail=include_agent_todos_detail) if not transaction["projected"]: return payload, source required = transaction["context"] @@ -574,6 +577,8 @@ def project_captured_context( payload: dict[str, Any], *, directory: Path | None, request: dict[str, Any] | None, goal_id: str, agent_id: str, surface: str, capture_id: str, captured_recovery: dict[str, Any] | None = None, + include_goal_acceptance_detail: bool = False, + include_agent_todos_detail: bool = False, ) -> dict[str, Any]: """Adapt an admitted capture to the shared TS presentation owner. @@ -614,7 +619,9 @@ def project_captured_context( continuity = None delivery = prepare_context_delivery(payload, scope=scope, capture_id=capture_id, surface=surface, - baseline=request.get("baseline"), retained=retained, continuity=continuity) + baseline=request.get("baseline"), retained=retained, continuity=continuity, + include_goal_acceptance_detail=include_goal_acceptance_detail, + include_agent_todos_detail=include_agent_todos_detail) delivery["recovery"] = recovery return delivery except (OSError, ValueError, TypeError, EffectRuntimeRemoteError, EffectRuntimeStartupError): diff --git a/tests/control_plane/test_scoped_turn_envelope_cli.py b/tests/control_plane/test_scoped_turn_envelope_cli.py index 3cc3b45521..09fe383b0e 100644 --- a/tests/control_plane/test_scoped_turn_envelope_cli.py +++ b/tests/control_plane/test_scoped_turn_envelope_cli.py @@ -2,6 +2,7 @@ from __future__ import annotations import copy +import hashlib import json from pathlib import Path import shlex @@ -28,6 +29,7 @@ def _seed_mature_goal( goal_id: str = "mature-scoped-goal", objective_prefix: str = "Historical outcome", explore_graph_enabled: bool = False, + leading_todos: list[dict[str, object]] | None = None, ) -> dict[str, object]: monkeypatch.delenv("CODEX_THREAD_ID", raising=False) project = tmp_path / "project" @@ -38,7 +40,10 @@ def _seed_mature_goal( registry.parent.mkdir(parents=True) agent_id = "worker" + prefix_todos = copy.deepcopy(leading_todos) if leading_todos else [] + offset = len(prefix_todos) todos = [ + *prefix_todos, { "schema_version": "todo_item_v0", "todo_id": "todo_current", @@ -48,7 +53,7 @@ def _seed_mature_goal( "done": False, "task_class": "advancement_task", "action_kind": "implement", - "index": 1, + "index": 1 + offset, "source_section": "Agent Todo", "archive_state": "active", "claimed_by": agent_id, @@ -62,7 +67,7 @@ def _seed_mature_goal( "done": False, "task_class": "advancement_task", "action_kind": "implement", - "index": 2, + "index": 2 + offset, "source_section": "Agent Todo", "archive_state": "active", "claimed_by": "peer-0", @@ -78,7 +83,7 @@ def _seed_mature_goal( "done": True, "task_class": "advancement_task", "action_kind": "implement", - "index": i + 3, + "index": i + 3 + offset, "source_section": "Completed Work Archive", "archive_state": "archive", "claimed_by": f"peer-{i % 4}", @@ -927,3 +932,414 @@ def test_disabled_context_delivery_preserves_full_inline_outcomes_without_captur 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 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_unscoped_prereqs_recovery_and_first_read_keep_file_and_sqlite_lean_with_readback( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + env = _seed_mature_goal(tmp_path, monkeypatch, provider=provider, outcome_count=15) + cli = env["cli"] + goal_id = env["goal_id"] + agent_id = env["agent_id"] + + # 1. Pre-claim should-run without --codex-app keeps planning_horizon lean via progressive context + # capture while preserving verbatim historical requirement recovery from context_details. + _, pre_view = cli("quota", "should-run", "--goal-id", goal_id, "--agent-id", agent_id) + pre_required = ( + json.loads(Path(read_context_read_reference(pre_view["recovery"]["reference_file"])[1]["path"]).read_bytes()) + if "recovery" in pre_view + else pre_view + ) + ph_outcomes = pre_required["planning_horizon"]["core_goal"]["acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(ph_outcomes) == 15 + by_id = {row["id"]: row for row in ph_outcomes} + assert "requirements" in by_id["outcome-current"] + assert "requirements" not in by_id["outcome-hist-5"] + assert "sources" not in by_id["outcome-hist-5"] + hist_ptr = by_id["outcome-hist-5"]["supporting_material_pointer"] + unread_ptrs = set(pre_required["context_details"]["unread_context_index"]["pointers"]) + assert f"{hist_ptr}/requirements" in unread_ptrs + pre_read_cmd = pre_required["context_details"]["command_template"].replace( + "''", shlex.quote(f"{hist_ptr}/requirements"), + ) + pre_read = subprocess.run( + shlex.split(pre_read_cmd), + cwd=env["project"], capture_output=True, text=True, + ) + assert pre_read.returncode == 0, pre_read.stderr + pre_selected = json.loads(json.loads(pre_read.stdout)["content"])["selections"] + assert len(pre_selected) == 1 and len(pre_selected[0]["value"]) == 8 + + # 2. Claim todo_current: first_read_command skips redundant summary_only row pointers when container + # capture_read_command + cold_read_command exist, while decision.json and required-context.json keep them. + _claim_current_todo(env) + native_claimed = tmp_path / "native_claimed" + native_claimed.mkdir(mode=0o700) + captures_claimed = tmp_path / "captures_claimed" + captures_claimed.mkdir(mode=0o700) + captures_claimed_resolved = captures_claimed.resolve() + monkeypatch.setenv("CODEX_THREAD_ID", f"claimed-{provider}") + codex_context_hook( + str(native_claimed), + {"hook_event_name": "SessionStart", "session_id": f"claimed-{provider}", "cwd": str(env["project"]), "source": "startup"}, + ) + _, claimed_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-claimed-1", + "--codex-context-dir", str(native_claimed), "--decision-output-root", str(captures_claimed_resolved), + ) + claimed_required = json.loads(Path(read_context_read_reference(claimed_view["recovery"]["reference_file"])[1]["path"]).read_bytes()) + assert claimed_required["effective_action"] == "normal_run" + first_chunks: list[str] = [] + page_count = 0 + next_offset: int | None = None + while True: + page_cmd = shlex.split(claimed_view["first_read_command"]) + if next_offset is not None: + page_cmd.extend(["--offset", str(next_offset)]) + first_read = subprocess.run(page_cmd, cwd=env["project"], capture_output=True, text=True) + assert first_read.returncode == 0, first_read.stderr + page = json.loads(first_read.stdout) + first_chunks.append(page["content"]) + page_count += 1 + if page["eof"]: + break + next_offset = page["next_offset"] + assert page_count <= 4 + first_content = json.loads("".join(first_chunks)) + first_ptrs = [row["pointer"] for row in first_content["selections"]] + ga_idx, ga_src = next( + (idx, src) + for idx, src in enumerate(claimed_required["interaction_contract"]["agent_channel"]["work_context"]["sources"]) + if src.get("source") == "goal_acceptance" + ) + req_prefix = f"/interaction_contract/agent_channel/work_context/sources/{ga_idx}/content/goal_acceptance_contract/outcome_requirements" + assert f"{req_prefix}/capture_read_command" in first_ptrs + assert f"{req_prefix}/cold_read_command" in first_ptrs + assert f"{req_prefix}/outcomes/0" in first_ptrs + assert not any(p.startswith(f"{req_prefix}/outcomes/1") or p.startswith(f"{req_prefix}/outcomes/14") for p in first_ptrs) + assert ga_src["content"]["goal_acceptance_contract"]["outcome_requirements"]["outcomes"][1]["capture_read_command"] + + # 3. Unsettled recovery (no --todo-id and --todo-id + --include-detail agent-todos) scopes acceptance + # while preserving full deferred admission outcomes. + native_rec1 = tmp_path / "native_rec1" + native_rec1.mkdir(mode=0o700) + captures_rec1 = tmp_path / "captures_rec1" + captures_rec1.mkdir(mode=0o700) + captures_rec1_resolved = captures_rec1.resolve() + monkeypatch.setenv("CODEX_THREAD_ID", f"rec1-{provider}") + codex_context_hook( + str(native_rec1), + {"hook_event_name": "SessionStart", "session_id": f"rec1-{provider}", "cwd": str(env["project"]), "source": "startup"}, + ) + _, rec_view = cli( + "quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", + "--goal-id", goal_id, "--agent-id", agent_id, + "--turn-instance-id", "turn-rec-1", + "--codex-context-dir", str(native_rec1), "--decision-output-root", str(captures_rec1_resolved), + ) + rec_decision = json.loads(next(captures_rec1_resolved.rglob("decision.json")).read_text()) + assert rec_decision["effective_action"] == "unsettled_host_turn_recovery" + rec_ph_reqs = rec_decision["planning_horizon"]["core_goal"]["acceptance_contract"]["outcome_requirements"] + assert rec_ph_reqs["projection_mode"] == "turn_scoped_v0" + assert rec_ph_reqs["full_outcome_count"] == 15 + assert rec_ph_reqs["inline_outcome_count"] == 1 + assert rec_ph_reqs["compacted_outcome_count"] == 14 + assert rec_ph_reqs["outcomes"][0]["id"] == "outcome-current" + assert len(rec_decision["deferred_settlement_details"]["goal_acceptance"]["outcome_requirements"]["outcomes"]) == 15 + rec_required = ( + json.loads(Path(read_context_read_reference(rec_view["recovery"]["reference_file"])[1]["path"]).read_bytes()) + if "recovery" in rec_view + else rec_view + ) + assert rec_required.get("blocked_priority_fallback") is None or ( + rec_required.get("heartbeat_recommendation", {}).get("blocked_priority_fallback") + == {"context_ref": "/blocked_priority_fallback"} + ) + + native_rec2 = tmp_path / "native_rec2" + native_rec2.mkdir(mode=0o700) + captures_rec2 = tmp_path / "captures_rec2" + captures_rec2.mkdir(mode=0o700) + captures_rec2_resolved = captures_rec2.resolve() + monkeypatch.setenv("CODEX_THREAD_ID", f"rec2-{provider}") + codex_context_hook( + str(native_rec2), + {"hook_event_name": "SessionStart", "session_id": f"rec2-{provider}", "cwd": str(env["project"]), "source": "startup"}, + ) + _, rec_detail_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-rec-2", "--include-detail", "agent-todos", + "--codex-context-dir", str(native_rec2), "--decision-output-root", str(captures_rec2_resolved), + ) + rec_detail_decision = json.loads(next(captures_rec2_resolved.rglob("decision.json")).read_text()) + assert rec_detail_decision["effective_action"] == "unsettled_host_turn_recovery" + rec_summary_reqs = rec_detail_decision["agent_todo_summary"]["goal_acceptance_contract"]["outcome_requirements"] + assert rec_summary_reqs["projection_mode"] == "turn_scoped_v0" + assert rec_summary_reqs["full_outcome_count"] == 15 + assert rec_summary_reqs["inline_outcome_count"] == 1 + assert rec_summary_reqs["compacted_outcome_count"] == 14 + assert len(rec_detail_decision["deferred_settlement_details"]["goal_acceptance"]["outcome_requirements"]["outcomes"]) == 15 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_explicit_goal_acceptance_detail_retains_historical_requirements_directly( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + env = _seed_mature_goal( + tmp_path, monkeypatch, provider=provider, outcome_count=9, goal_id=f"explicit-ga-{provider}", + ) + cli = env["cli"] + goal_id = str(env["goal_id"]) + agent_id = str(env["agent_id"]) + + # 1a. Pre-claim plain entry defers historical requirements in planning_horizon (recoverable via context-read); + # explicit --include-detail goal_acceptance and --include-detail all return all 8 directly. + _, ordinary_plain = cli("quota", "should-run", "--goal-id", goal_id, "--agent-id", agent_id) + ordinary_plain_req = ( + json.loads(Path(read_context_read_reference(ordinary_plain["recovery"]["reference_file"])[1]["path"]).read_bytes()) + if "recovery" in ordinary_plain + else ordinary_plain + ) + plain_hist = [ + row + for row in ordinary_plain_req["planning_horizon"]["core_goal"]["acceptance_contract"]["outcome_requirements"]["outcomes"] + if row["id"].startswith("outcome-hist-") + ] + assert len(plain_hist) == 8 + assert all("requirements" not in row and row.get("supporting_material_pointer") for row in plain_hist) + plain_cmd = ordinary_plain_req["context_details"]["command_template"].replace( + "''", shlex.quote(f"{plain_hist[0]['supporting_material_pointer']}/requirements"), + ) + plain_recovered = json.loads( + json.loads(subprocess.run(shlex.split(plain_cmd), cwd=env["project"], capture_output=True, text=True, check=True).stdout)["content"] + ) + assert len(plain_recovered["selections"][0]["value"]) == 8 + + for detail in ("goal_acceptance", "all"): + _, detail_plain = cli("quota", "should-run", "--goal-id", goal_id, "--agent-id", agent_id, "--include-detail", detail) + detail_plain_req = ( + json.loads(Path(read_context_read_reference(detail_plain["recovery"]["reference_file"])[1]["path"]).read_bytes()) + if "recovery" in detail_plain + else detail_plain + ) + plain_detail_hist = [ + row + for row in detail_plain_req["planning_horizon"]["core_goal"]["acceptance_contract"]["outcome_requirements"]["outcomes"] + if row["id"].startswith("outcome-hist-") + ] + assert len(plain_detail_hist) == 8 + assert all(isinstance(row.get("requirements"), list) and len(row["requirements"]) == 8 for row in plain_detail_hist) + + # 1b. Claimed Codex App entry compacts ordinary goal_acceptance (recoverable from capture) while + # explicit --include-detail goal_acceptance and --include-detail all keep all 8 inline directly. + _claim_current_todo(env) + + def _run_case(name: str, extra_args: tuple[str, ...]) -> tuple[dict, dict]: + native = tmp_path / f"native_{name}" + captures = tmp_path / f"captures_{name}" + native.mkdir(mode=0o700) + captures.mkdir(mode=0o700) + caps_resolved = captures.resolve() + monkeypatch.setenv("CODEX_THREAD_ID", f"{name}-{provider}") + codex_context_hook( + str(native), + {"hook_event_name": "SessionStart", "session_id": f"{name}-{provider}", "cwd": str(env["project"]), "source": "startup"}, + ) + _, 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", f"turn-{name}", + "--codex-context-dir", str(native), "--decision-output-root", str(caps_resolved), + *extra_args, + ) + _, req_ref = read_context_read_reference(view["recovery"]["reference_file"]) + return view, json.loads(Path(req_ref["path"]).read_bytes()) + + _, ordinary_req = _run_case("ordinary", ()) + ordinary_wc_ga = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in ordinary_req["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + assert ordinary_wc_ga["projection_mode"] == "turn_scoped_v0" + assert len(ordinary_wc_ga["outcomes"]) == 9 + assert "requirements" in ordinary_wc_ga["outcomes"][0] + hist_ordinary = [row for row in ordinary_wc_ga["outcomes"] if row["id"].startswith("outcome-hist-")] + assert len(hist_ordinary) == 8 + assert all(row.get("summary_only") is True and "requirements" not in row for row in hist_ordinary) + recovered = json.loads( + json.loads( + subprocess.run( + shlex.split(hist_ordinary[0]["capture_read_command"].replace( + "outcome_requirements/outcomes/1", + "outcome_requirements/outcomes/1/requirements", + )), + cwd=env["project"], capture_output=True, text=True, check=True, + ).stdout + )["content"] + ) + assert len(recovered["selections"][0]["value"]) == 8 + + for detail in ("goal_acceptance", "all"): + detail_root = tmp_path / f"case_{detail}" + detail_root.mkdir() + detail_env = _seed_mature_goal( + detail_root, monkeypatch, provider=provider, outcome_count=9, goal_id=f"explicit-ga-{detail}-{provider}", + ) + _claim_current_todo(detail_env) + d_native = detail_root / "native" + d_captures = detail_root / "captures" + d_native.mkdir(mode=0o700) + d_captures.mkdir(mode=0o700) + monkeypatch.setenv("CODEX_THREAD_ID", f"{detail}-{provider}") + codex_context_hook( + str(d_native), + {"hook_event_name": "SessionStart", "session_id": f"{detail}-{provider}", "cwd": str(detail_env["project"]), "source": "startup"}, + ) + _, detail_view = detail_env["cli"]( + "quota", "should-run", "--codex-app", "--context-delivery", "on", "--delta-delivery", "auto", + "--goal-id", str(detail_env["goal_id"]), "--agent-id", str(detail_env["agent_id"]), "--todo-id", "todo_current", + "--turn-instance-id", f"turn-{detail}", + "--codex-context-dir", str(d_native), "--decision-output-root", str(d_captures.resolve()), + "--include-detail", detail, + ) + _, d_ref = read_context_read_reference(detail_view["recovery"]["reference_file"]) + detail_req = json.loads(Path(d_ref["path"]).read_bytes()) + assert detail_req["effective_action"] == "normal_run" + wc_ga = next( + s["content"]["goal_acceptance_contract"]["outcome_requirements"] + for s in detail_req["interaction_contract"]["agent_channel"]["work_context"]["sources"] + if s.get("source") == "goal_acceptance" + ) + hist_rows = [row for row in wc_ga["outcomes"] if row["id"].startswith("outcome-hist-")] + assert len(hist_rows) == 8 + assert all(isinstance(row.get("requirements"), list) and len(row["requirements"]) == 8 for row in hist_rows) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_explicit_agent_todos_detail_preserves_full_blocked_priority_fallback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + blocked_leading = [{ + "schema_version": "todo_item_v0", + "todo_id": "todo_primary_blocked", + "role": "agent", + "text": "Wait for external dependency clearance before core implementation.", + "status": "blocked", + "done": False, + "task_class": "advancement_task", + "action_kind": "implement", + "index": 1, + "source_section": "Agent Todo", + "archive_state": "active", + "claimed_by": "worker", + }] + env = _seed_mature_goal( + tmp_path, monkeypatch, provider=provider, outcome_count=9, + goal_id=f"fallback-detail-{provider}", leading_todos=blocked_leading, + ) + _claim_current_todo(env) + cli = env["cli"] + goal_id = str(env["goal_id"]) + agent_id = str(env["agent_id"]) + + def _run_case( + case_name: str, + *, + context_delivery: str, + include_detail: str | None = None, + with_native_dir: bool = True, + ) -> tuple[dict, dict, Path, dict, dict | None]: + case_root = tmp_path / f"case_{case_name}" + captures = case_root / "captures" + captures.mkdir(parents=True, mode=0o700) + args = [ + "quota", "should-run", "--codex-app", + "--context-delivery", context_delivery, + "--goal-id", goal_id, "--agent-id", agent_id, "--todo-id", "todo_current", + "--turn-instance-id", "turn-fallback", + "--decision-output-root", str(captures.resolve()), + ] + if context_delivery == "on": + args.extend(["--delta-delivery", "auto"]) + if with_native_dir: + native = case_root / "native" + native.mkdir(mode=0o700) + monkeypatch.setenv("CODEX_THREAD_ID", f"{case_name}-{provider}") + codex_context_hook( + str(native), + {"hook_event_name": "SessionStart", "session_id": f"{case_name}-{provider}", + "cwd": str(env["project"]), "source": "startup"}, + ) + args.extend(["--codex-context-dir", str(native)]) + else: + monkeypatch.delenv("CODEX_THREAD_ID", raising=False) + if include_detail is not None: + args.extend(["--include-detail", include_detail]) + + _, view = cli(*args) + decision_path = next(captures.rglob("decision.json")) + decision = json.loads(decision_path.read_text()) + if "recovery" in view: + delivered = json.loads(Path(read_context_read_reference(view["recovery"]["reference_file"])[1]["path"]).read_bytes()) + else: + delivered = view + required_path = next(captures.rglob("required-context.json"), None) + return view, delivered, decision_path, decision, (json.loads(required_path.read_text()) if required_path else None) + + cases: list[tuple[str, str, str | None, bool]] = [ + ("ordinary_on_native", "on", None, True), + ("ordinary_on_stateless", "on", None, False), + ("agent_todos_on_native", "on", "agent-todos", True), + ("agent_todos_on_stateless", "on", "agent-todos", False), + ("all_on_native", "on", "all", True), + ("all_on_stateless", "on", "all", False), + ("ordinary_off", "off", None, True), + ("agent_todos_off", "off", "agent-todos", True), + ("all_off", "off", "all", True), + ] + + expected_fallback: dict | None = None + for case_name, delivery_mode, detail, use_native in cases: + view, delivered, decision_path, decision, required_copy = _run_case( + case_name, context_delivery=delivery_mode, include_detail=detail, with_native_dir=use_native, + ) + assert decision["effective_action"] == "normal_run" + assert delivered["effective_action"] == "normal_run" + root_fallback = decision["blocked_priority_fallback"] + assert root_fallback["kind"] == "blocked_priority_fallback" + assert [row["todo_id"] for row in root_fallback["blocked_items"]] == ["todo_primary_blocked"] + assert root_fallback["selected_executable"]["todo_id"] == "todo_current" + assert decision["heartbeat_recommendation"]["blocked_priority_fallback"] == root_fallback + if expected_fallback is None: + expected_fallback = root_fallback + else: + assert root_fallback == expected_fallback + + # Verify digest-bound selection read on saved decision.json returns both complete fallback objects. + decision_sha = hashlib.sha256(decision_path.read_bytes()).hexdigest() + _, read_back = cli( + "quota", "context-read", + "--capture-file", str(decision_path), + "--capture-sha256", decision_sha, + "--select", "/blocked_priority_fallback", + "--select", "/heartbeat_recommendation/blocked_priority_fallback", + ) + selections = json.loads(read_back["content"])["selections"] + assert [row["value"] for row in selections] == [expected_fallback, expected_fallback] + + for target in [delivered, *([required_copy] if required_copy is not None else [])]: + assert target["blocked_priority_fallback"] == expected_fallback + rec = target["heartbeat_recommendation"] + if detail in {"agent-todos", "all"} or delivery_mode == "off": + assert rec["blocked_priority_fallback"] == expected_fallback + assert "blocked_priority_fallback_ref" not in rec + else: + assert rec["blocked_priority_fallback"] == {"context_ref": "/blocked_priority_fallback"} + assert "blocked_priority_fallback_ref" not in rec diff --git a/tests/control_plane_ts/progressive_context.test.ts b/tests/control_plane_ts/progressive_context.test.ts index 3fd2f25969..52cb55198a 100644 --- a/tests/control_plane_ts/progressive_context.test.ts +++ b/tests/control_plane_ts/progressive_context.test.ts @@ -3,6 +3,7 @@ import test from "node:test"; import {visionAuthoringContract} from "../../loopx/control_plane/goals/vision_checkpoint.ts"; import {contextReadSectionDigests, initialContextReadPointers, prepareProgressiveContextDelivery, progressiveContextPlan} from "../../loopx/control_plane/quota/progressive_context.ts"; +import {evaluateTurnEnvelope} from "../../loopx/control_plane/quota/turn_envelope.ts"; import {FULL_OUTCOME_READ_GUIDANCE, PROGRESSIVE_OUTCOME_READ_GUIDANCE} from "../../loopx/control_plane/work_items/interaction_contract.ts"; const outcome = {id: "o", objective: "Keep all requirements.", revision: 1, owner_agent_id: "a", todo_ids: ["t"], @@ -338,3 +339,341 @@ test("bounded ready opening discloses omitted suggested outcome parents before d assert.equal(largerPlan.deferred_suggested_outcomes, undefined); assert.equal(largerPlan.opening_context_instruction, undefined); }); + +test("progressiveContextPlan defers large unscoped historical requirements and deduplicates blocked_priority_fallback", () => { + const makeOutcome = (id: string, todoId: string) => ({ + id, objective: `Deliver ${id}.`, revision: 2, owner_agent_id: "a1", todo_ids: [todoId], + sources: [{ref: `${id}:doc`, summary: "Supporting evidence summary. ".repeat(25)}], + requirements: [{ + id: `${id}-req`, description: `Acceptance criterion for ${id}. `.repeat(20), status: "unverified", planning_satisfied: false, + agent_review: { + id: `${id}-req`, conclusion: "met", note: "Detailed agent review note. ".repeat(15), evidence_refs: [`ev:${id}`], + basis_current: true, independently_verified: false, + }, + }], + }); + const outcomes = [ + makeOutcome("o-cur", "todo-cur"), + makeOutcome("o-gap", "todo-gap"), + makeOutcome("o-sug", "todo-sug"), + ...Array.from({length: 5}, (_, idx) => makeOutcome(`o-hist-${idx}`, `todo-hist-${idx}`)), + ]; + const fallback = {reason: "blocked by open prerequisite", priority_todo_id: "todo-cur", guidance: "Inspect dependency first. ".repeat(20)}; + const payload = { + ok: true, goal_id: "goal-unscoped", agent_id: "a1", + selected_todo: {todo_id: "todo-cur"}, + goal_frontier_projection: {acceptance_gaps: [{outcome_id: "o-gap"}]}, + blocked_priority_fallback: fallback, + heartbeat_recommendation: {action: "retry", blocked_priority_fallback: structuredClone(fallback)}, + planning_horizon: {core_goal: {acceptance_contract: {outcome_requirements: { + schema_version: "loopx_goal_outcomes_v0", outcomes: structuredClone(outcomes), + }}}}, + interaction_contract: { + schema_version: "loopx_interaction_contract_v0", + agent_channel: { + required_reads: [{source: "goal_acceptance", reason: "Check acceptance. " + FULL_OUTCOME_READ_GUIDANCE}], + work_context: {sources: [{ + source: "goal_acceptance", + reason: "Adopt goal objective. " + FULL_OUTCOME_READ_GUIDANCE, + content: { + status: "loaded", ok: true, read_complete: true, + outcome_context: {suggested_outcome_ids: ["o-sug"]}, + goal_acceptance_contract: {outcome_requirements: { + schema_version: "loopx_goal_outcomes_v0", outcomes: structuredClone(outcomes), + }}, + }, + }]}, + }, + }, + }; + + const plan = progressiveContextPlan({payload, surface: "quota_packet"}) as { + deferred: {path: (string | number)[]; parent: (string | number)[]; index_key: string}[]; + instructions: {path: (string | number)[]; value: unknown}[]; + references?: {path: (string | number)[]; from: (string | number)[]; value: unknown}[]; + }; + + const wcDeferredPaths = plan.deferred + .filter(item => item.path[0] === "interaction_contract") + .map(item => item.path.slice(-2).join("/")); + assert.ok(wcDeferredPaths.includes("3/requirements"), "historical non-active outcomes defer requirements"); + assert.ok(wcDeferredPaths.includes("7/requirements")); + assert.ok(!wcDeferredPaths.includes("0/requirements"), "selected_todo outcome keeps requirements inline"); + assert.ok(!wcDeferredPaths.includes("1/requirements"), "gap outcome keeps requirements inline"); + assert.ok(!wcDeferredPaths.includes("2/requirements"), "suggested outcome keeps requirements inline"); + const phDeferredPaths = plan.deferred + .filter(item => item.path[0] === "planning_horizon") + .map(item => item.path.slice(-2).join("/")); + assert.ok(!phDeferredPaths.includes("0/requirements")); + assert.ok(!phDeferredPaths.includes("1/requirements")); + assert.ok(phDeferredPaths.includes("2/requirements") && phDeferredPaths.includes("7/requirements")); + + const reasonUpdate = plan.instructions.find(inst => inst.path.at(-1) === "reason"); + assert.ok(typeof reasonUpdate?.value === "string"); + assert.ok(!reasonUpdate.value.includes("cumulative outcome requirements")); + assert.ok(reasonUpdate.value.includes("Active/suggested outcomes retain complete requirements here")); + assert.ok(reasonUpdate.value.includes("historical non-selected outcome requirements remain in context_details")); + + // Autonomous replan obligation carriers retain full requirements inline for all outcomes. + const replanPlan = progressiveContextPlan({ + payload: { + ok: true, + effective_action: "autonomous_replan_required", + autonomous_replan_obligation: {replan_context: {core_goal: {acceptance_contract: { + outcome_requirements: {schema_version: "loopx_goal_outcomes_v0", outcomes: structuredClone(outcomes)}, + }}}}, + }, + surface: "quota_packet", + }) as {deferred: {path: (string | number)[]}[]}; + assert.equal(replanPlan.deferred.some(item => item.path.at(-1) === "requirements"), false); + + // Full evaluateTurnEnvelope context_delivery applies blocked_priority_fallback context_ref when equal, + // leaves unequal fallbacks intact, and moves historical requirements cleanly. + const {changes} = evaluateTurnEnvelope({ + operation: "context_delivery", + scope: {goal_id: "goal-unscoped", agent_id: "a1", session_id: "s1", context_epoch: "e1"}, + capture_id: "cap-unscoped", + surface: "quota_packet", + context: payload, + native_projection: { + path: "projection.json", sha256: "b".repeat(64), + command_template: "loopx --format json quota context-read --capture-file projection.json --capture-sha256 " + "b".repeat(64) + " --select ''", + }, + }) as {changes: {path: (string | number)[]; from?: (string | number)[]; value?: unknown; remove?: true}[]}; + assert.ok(changes.some(edit => edit.path.join("/") === "context/heartbeat_recommendation/blocked_priority_fallback" + && (edit.value as {context_ref?: string} | undefined)?.context_ref === "/blocked_priority_fallback")); + assert.ok(changes.some(edit => + edit.path.join("/") === "context/planning_horizon/core_goal/acceptance_contract/outcome_requirements/outcomes/3/requirements" + && edit.remove === true)); + + const {changes: unequalChanges} = evaluateTurnEnvelope({ + operation: "context_delivery", + scope: {goal_id: "goal-unscoped", agent_id: "a1", session_id: "s1", context_epoch: "e1"}, + capture_id: "cap-unscoped", + surface: "quota_packet", + context: { + ...payload, + heartbeat_recommendation: {action: "retry", blocked_priority_fallback: {...fallback, priority_todo_id: "other"}}, + }, + native_projection: { + path: "projection.json", sha256: "b".repeat(64), + command_template: "loopx --format json quota context-read --capture-file projection.json --capture-sha256 " + "b".repeat(64) + " --select ''", + }, + }) as {changes: {path: (string | number)[]}[]}; + assert.equal(unequalChanges.some(edit => + edit.path.join("/") === "context/heartbeat_recommendation/blocked_priority_fallback"), false); + + // Explicit include_goal_acceptance_detail keeps historical requirements inline directly. + const explicitPlan = progressiveContextPlan({payload, surface: "quota_packet", include_goal_acceptance_detail: true}) as { + deferred: {path: (string | number)[]}[]; + }; + assert.equal(explicitPlan.deferred.some(item => item.path.at(-1) === "requirements"), false); + const {changes: explicitChanges} = evaluateTurnEnvelope({ + operation: "context_delivery", + scope: {goal_id: "goal-unscoped", agent_id: "a1", session_id: "s1", context_epoch: "e1"}, + capture_id: "cap-unscoped", + surface: "quota_packet", + context: payload, + include_goal_acceptance_detail: true, + native_projection: { + path: "projection.json", sha256: "b".repeat(64), + command_template: "loopx --format json quota context-read --capture-file projection.json --capture-sha256 " + "b".repeat(64) + " --select ''", + }, + }) as {changes: {path: (string | number)[]; remove?: true}[]}; + assert.equal(explicitChanges.some(edit => edit.path[0] === "context" && edit.path.at(-1) === "requirements" && edit.remove === true), false); +}); + +test("explicit include_agent_todos_detail preserves full fallback mirror across delivery surfaces", () => { + const fallback = { + schema_version: "blocked_priority_fallback_v0", + kind: "blocked_priority_fallback", + notify_user: true, + reason: "Higher-priority work is blocked while fallback continues. ".repeat(12), + blocked_items: [{todo_id: "todo-blocked", status: "blocked"}], + selected_executable: {todo_id: "todo-fallback", text: "Continue executable fallback."}, + }; + const makeOutcome = (id: string) => ({ + id, + objective: `Deliver ${id}.`, + revision: 2, + owner_agent_id: "a1", + todo_ids: ["todo-other"], + sources: [{ref: `${id}:doc`, summary: "Supporting evidence summary. ".repeat(25)}], + requirements: [{ + id: `${id}-req`, + description: `Acceptance criterion for ${id}. `.repeat(20), + status: "unverified", + planning_satisfied: false, + }], + }); + const payload = { + ok: true, + goal_id: "goal-fallback", + selected_todo: {todo_id: "todo-fallback"}, + blocked_priority_fallback: fallback, + heartbeat_recommendation: {action: "retry", blocked_priority_fallback: structuredClone(fallback)}, + planning_horizon: { + core_goal: { + acceptance_contract: { + outcome_requirements: { + schema_version: "loopx_goal_outcomes_v0", + outcomes: Array.from({length: 7}, (_, i) => makeOutcome(`o-${i}`)), + }, + }, + }, + }, + }; + const nativeProjection = { + path: "projection.json", + sha256: "f".repeat(64), + command_template: "loopx --format json quota context-read --capture-file projection.json --capture-sha256 " + "f".repeat(64) + " --select ''", + }; + const baseDelivery = { + operation: "context_delivery", + scope: {goal_id: "goal-fallback", agent_id: "a1", session_id: "s1", context_epoch: "e1"}, + capture_id: "cap-fallback", + surface: "quota_packet", + context: payload, + native_projection: nativeProjection, + }; + + // Ordinary context delivery continues deduplicating confirmed-equal fallback mirrors. + const ordinary = evaluateTurnEnvelope(baseDelivery) as { + changes: {path: (string | number)[]; value?: unknown}[]; + }; + assert.ok(ordinary.changes.some(edit => edit.path.join("/") === "context/heartbeat_recommendation/blocked_priority_fallback" + && (edit.value as {context_ref?: string} | undefined)?.context_ref === "/blocked_priority_fallback")); + + // Explicit include_agent_todos_detail retains the complete fallback mirror even when other fields project. + for (const request of [ + {...baseDelivery, include_agent_todos_detail: true}, + { + operation: "progressive_context_delivery", + surface: "quota_packet", + context: payload, + native_projection: nativeProjection, + include_agent_todos_detail: true, + }, + ]) { + const explicit = evaluateTurnEnvelope(request) as { + changes: {path: (string | number)[]; value?: unknown}[]; + }; + assert.ok(explicit.changes.some(edit => edit.path.join("/") === "projected" && edit.value === true)); + assert.equal(explicit.changes.some(edit => + edit.path.join("/") === "context/heartbeat_recommendation/blocked_priority_fallback"), false); + } + + assert.throws( + () => evaluateTurnEnvelope({...baseDelivery, include_agent_todos_detail: "yes"}), + /include_agent_todos_detail/, + ); + assert.throws( + () => progressiveContextPlan({payload, surface: "quota_packet", include_agent_todos_detail: 1}), + /include_agent_todos_detail/, + ); +}); + +test("initial read omits redundant summary_only outcome rows when container read commands exist", () => { + const identity = {schema_version: "quota_settlement_identity_v0", effect_id: "eff-1", + goal_id: "goal-scoped", agent_id: "agent-1", todo_id: "todo-1", turn_instance_id: "turn-1"}; + const summaryRow = (idx: number) => ({ + id: `out-${idx}`, + owner_agent_id: "peer-1", + basis_digest: "sha256:" + "c".repeat(64), + revision: 2, + todo_count: 1, + summary_only: true, + capture_read_command: `loopx quota context-read --select /deferred_settlement_details/goal_acceptance/outcome_requirements/outcomes/${idx}`, + cold_read_command: "loopx goal-acceptance inspect --goal-id goal-scoped", + read_modes: "capture_read_command=immutable admission baseline; cold_read_command=live workspace inspect", + }); + const scopedContext = { + ok: true, goal_id: "goal-scoped", agent_id: "agent-1", agent_identity: {agent_id: "agent-1"}, + should_run: true, effective_action: "normal_run", normal_delivery_allowed: true, + selected_todo: {todo_id: "todo-1"}, heartbeat_receipt: {settlement_identity: identity}, + interaction_contract: { + schema_version: "loopx_interaction_contract_v0", + agent_channel: {delivery_allowed: true, work_context: {sources: [{ + source: "goal_acceptance", + reason: FULL_OUTCOME_READ_GUIDANCE, + content: { + status: "loaded", ok: true, read_complete: true, decision_read_from_provider: true, + legacy_fallback_used: false, provider_revision: "rev-scoped", + goal_acceptance_contract: {outcome_requirements: { + schema_version: "loopx_goal_outcomes_v0", current_lifetime: true, revision: 9, outcome_revision: 9, + projection_mode: "turn_scoped_v0", full_outcome_count: 9, inline_outcome_count: 1, compacted_outcome_count: 8, + full_outcomes_sha256: "sha256:" + "d".repeat(64), + capture_read_command: "loopx quota context-read --select /deferred_settlement_details/goal_acceptance", + cold_read_command: "loopx goal-acceptance inspect --goal-id goal-scoped", + cold_read_instruction: "Use --include-detail goal_acceptance or cold_read_command.", + outcomes: [ + { + id: "out-0", objective: "Active objective.", revision: 9, owner_agent_id: "agent-1", todo_ids: ["todo-1"], + sources: [{ref: "spec:0", summary: "Active provenance"}], + requirements: [{id: "req-0", description: "Active requirement.", status: "unverified", planning_satisfied: false}], + }, + ...Array.from({length: 8}, (_, i) => summaryRow(i + 1)), + ], + }}, + outcome_context: { + schema_version: "outcome_context_navigation_v1", goal_id: "goal-scoped", agent_id: "agent-1", + todo_id: "todo-1", outcome_revision: 9, provider_revision: "rev-scoped", + coverage_complete: true, suggested_outcome_ids: ["out-0"], + }, + }, + }]}}, + cli_channel: { + execution_preparation: {state: "ready", todo_id: "todo-1"}, + settlement_plan: {schema_version: "quota_settlement_plan_v2", identity, ordered_steps: []}, + }, + }, + }; + const prefix = "/interaction_contract/agent_channel/work_context/sources/0/content/goal_acceptance_contract/outcome_requirements/outcomes"; + const request = { + scope: {goal_id: "goal-scoped", agent_id: "agent-1", session_id: "sess-1", context_epoch: "ep-1"}, + capture_id: "cap-scoped", surface: "quota_packet", + context: scopedContext, include_initial_read_plan: true, + native_projection: { + path: "projection.json", sha256: "e".repeat(64), initial_read_output_bytes: 12000, + command_template: "loopx --format json quota context-read --capture-file projection.json --capture-sha256 " + "e".repeat(64) + " --select ''", + }, + }; + const {changes} = prepareProgressiveContextDelivery(request, [], ["ok", "goal_id"]) as { + changes: {path: (string | number)[]; from?: (string | number)[]; value?: unknown; remove?: true}[]; + }; + const applied = structuredClone(request) as Record; + const get = (root: unknown, path: (string | number)[]) => + path.reduce((node, key) => (node as Record)[key], root); + for (const edit of changes) { + const parent = get(applied, edit.path.slice(0, -1)) as Record; + const key = edit.path.at(-1)!; + if (edit.remove) delete parent[key]; + else parent[key] = structuredClone(edit.from ? get(request, edit.from) : edit.value); + } + const initialSelections = ((applied.initial_read_plan as {plan: {selections: {pointer: string}[]}}).plan.selections) + .map(sel => sel.pointer); + const reqBase = "/interaction_contract/agent_channel/work_context/sources/0/content/goal_acceptance_contract/outcome_requirements"; + assert.ok(initialSelections.includes(reqBase + "/capture_read_command")); + assert.ok(initialSelections.includes(reqBase + "/cold_read_command")); + assert.ok(initialSelections.includes(prefix + "/0")); + assert.equal(initialSelections.some(p => p.startsWith(prefix + "/1")), false); + assert.equal(initialSelections.some(p => p.startsWith(prefix + "/8")), false); + + // Delivered required-context projection still preserves per-row #9395 commands and read_modes verbatim. + const deliveredSummaryRow = (get(applied, ["context", "interaction_contract", "agent_channel", "work_context", "sources", 0, + "content", "goal_acceptance_contract", "outcome_requirements", "outcomes", 1]) as Record); + assert.equal(deliveredSummaryRow.summary_only, true); + assert.ok(typeof deliveredSummaryRow.capture_read_command === "string"); + assert.ok(typeof deliveredSummaryRow.cold_read_command === "string"); + assert.ok(typeof deliveredSummaryRow.read_modes === "string"); + + // Boundary <= 6 outcomes retains summary_only rows in initial read selections. + const smallContext = structuredClone(scopedContext); + const smallReqs = (smallContext.interaction_contract.agent_channel.work_context.sources[0].content + .goal_acceptance_contract.outcome_requirements as {outcomes: unknown[]; full_outcome_count: number; compacted_outcome_count: number}); + smallReqs.outcomes = smallReqs.outcomes.slice(0, 6); + smallReqs.full_outcome_count = 6; + smallReqs.compacted_outcome_count = 5; + const smallPointers = initialContextReadPointers(smallContext, []); + assert.ok(smallPointers.includes(prefix + "/1/capture_read_command")); +}); diff --git a/tests/control_plane_ts/turn_envelope_scoping.test.ts b/tests/control_plane_ts/turn_envelope_scoping.test.ts index c1203685fc..16aa67c8af 100644 --- a/tests/control_plane_ts/turn_envelope_scoping.test.ts +++ b/tests/control_plane_ts/turn_envelope_scoping.test.ts @@ -777,3 +777,110 @@ test("captured scoped goal_acceptance preserves full admission outcomes in defer assert.equal(indexRows[0].capture_read_command, compactRows[0].capture_read_command); assert.equal(indexRows[0].read_modes, compactRows[0].read_modes); }); + +test("scopeTurnGoalAcceptance scopes unsettled recovery planning_horizon and standalone agent_todo_summary without selected_todo", () => { + const withoutWorkContextAcceptance = (payload: JsonObject): JsonObject => { + const ic = payload.interaction_contract as JsonObject; + const ac = ic.agent_channel as JsonObject; + const wc = ac.work_context as JsonObject; + return { + ...payload, + interaction_contract: { + ...ic, + agent_channel: { + ...ac, + work_context: { + ...wc, + sources: (wc.sources as JsonObject[]).filter(row => row.source !== "goal_acceptance"), + }, + }, + }, + }; + }; + + // 1. UNSETTLED_HOST_TURN_RECOVERY with planning_horizon only and selected_todo: null + // derives todo_id from heartbeat_receipt.settlement_identity and scopes 12 outcomes. + const unsettledHorizonBase = withoutWorkContextAcceptance(baseNormalPayload(12, "a1", "todo-current")); + delete unsettledHorizonBase.agent_todo_summary; + const unsettledHorizon: JsonObject = { + ...unsettledHorizonBase, + should_run: false, + normal_delivery_allowed: false, + effective_action: "unsettled_host_turn_recovery", + selected_todo: null, + }; + const scopedHorizon = scopeTurnGoalAcceptance(unsettledHorizon, {captureReferenceFile: "/tmp/ref.json"}); + const horizonReqs = ((scopedHorizon.planning_horizon as JsonObject).core_goal as JsonObject) + .acceptance_contract as JsonObject; + const horizonOutcomeReqs = horizonReqs.outcome_requirements as JsonObject; + assert.equal(horizonOutcomeReqs.projection_mode, SCOPED_OUTCOME_PROJECTION_MODE); + assert.equal(horizonOutcomeReqs.full_outcome_count, 12); + assert.equal(horizonOutcomeReqs.inline_outcome_count, 1); + assert.equal(horizonOutcomeReqs.compacted_outcome_count, 11); + assert.equal(((horizonOutcomeReqs.outcomes as JsonObject[])[0] as JsonObject).id, "out-current"); + assert.equal((((scopedHorizon.deferred_settlement_details as JsonObject).goal_acceptance as JsonObject) + .outcome_requirements as JsonObject).outcomes instanceof Array, true); + assert.equal(((((scopedHorizon.deferred_settlement_details as JsonObject).goal_acceptance as JsonObject) + .outcome_requirements as JsonObject).outcomes as JsonObject[]).length, 12); + + // 2. Pre-claim normal_run with planning_horizon only and selected_todo: null also scopes, + // while work_context without selected_todo stays fail-closed. + const preClaimHorizon = scopeTurnGoalAcceptance( + {...unsettledHorizon, effective_action: "normal_run", should_run: true, normal_delivery_allowed: true}, + {captureReferenceFile: "/tmp/ref.json"}, + ); + assert.equal( + ((((preClaimHorizon.planning_horizon as JsonObject).core_goal as JsonObject) + .acceptance_contract as JsonObject).outcome_requirements as JsonObject).projection_mode, + SCOPED_OUTCOME_PROJECTION_MODE, + ); + const preClaimWorkContextInput = {...baseNormalPayload(12, "a1", "todo-current"), selected_todo: null}; + const preClaimWorkContext = scopeTurnGoalAcceptance( + preClaimWorkContextInput, + {captureReferenceFile: "/tmp/ref.json"}, + ); + assert.equal(preClaimWorkContext, preClaimWorkContextInput); + assert.equal( + ((((((preClaimWorkContext.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 && + (((((((preClaimWorkContext.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).projection_mode, + undefined, + ); + + // 3. UNSETTLED_HOST_TURN_RECOVERY + standalone agent_todo_summary (--include-detail agent-todos), + // evaluated via evaluateTurnEnvelope end-to-end. + const standaloneSummaryBase = withoutWorkContextAcceptance(baseNormalPayload(12, "a1", "todo-current")); + delete standaloneSummaryBase.planning_horizon; + const capturedSummary = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: { + ...standaloneSummaryBase, + should_run: false, + normal_delivery_allowed: false, + effective_action: "unsettled_host_turn_recovery", + selected_todo: null, + }, + scheduler_execution_args: "", + capture_reference_file: "/tmp/ref.json", + }); + const summaryOutcomeReqs = ((capturedSummary.agent_todo_summary as JsonObject) + .goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject; + assert.equal(summaryOutcomeReqs.projection_mode, SCOPED_OUTCOME_PROJECTION_MODE); + assert.equal(summaryOutcomeReqs.full_outcome_count, 12); + assert.equal(summaryOutcomeReqs.inline_outcome_count, 1); + assert.equal(summaryOutcomeReqs.compacted_outcome_count, 11); + + // 4. autonomous_replan_required remains fail-closed even with planning_horizon only. + const replanHorizon = scopeTurnGoalAcceptance( + {...unsettledHorizon, effective_action: "autonomous_replan_required"}, + {captureReferenceFile: "/tmp/ref.json"}, + ); + assert.equal( + ((((replanHorizon.planning_horizon as JsonObject).core_goal as JsonObject) + .acceptance_contract as JsonObject).outcome_requirements as JsonObject).projection_mode, + undefined, + ); +});