diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index 74c2172e4c..2f8e461873 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -659,10 +659,20 @@ export async function readTodoRequest(goalId: string, todoId: string, signal: Ab ok: z.literal(true), goal_id: z.string(), todo_id: z.string(), text: z.string(), status: z.string(), archive_state: z.string(), updated_at: z.string().nullable(), evidence: z.string().nullable().optional(), note: z.string().nullable().optional(), + stride_meta_goal: z.union([z.object({unavailable: z.literal(true)}), z.object({ + decision_ref: z.string(), agent_id: z.string(), action: z.string(), + meta_goal: z.object({todo_id: z.string(), objective: z.string(), resolution_criterion: z.string(), + resolution: z.string().optional(), previous_decision_ref: z.string().optional()}), + next_probe: z.object({scope: z.string(), prediction: z.string(), adoption_criterion: z.string(), + cost_bound: z.string(), minimum_evidence: z.string()}), + evidence: z.array(z.object({evidence_ref: z.string(), summary: z.string().nullish()})), + })]).optional(), review_basis: todoUpdateSourceBasisSchema.optional(), source_access: z.object({namespace: z.string()}).optional(), }).parse(await requestJson(url, {signal})); if (result.goal_id !== goalId || result.todo_id !== todoId) throw new Error("Task source changed"); + if (result.stride_meta_goal && "meta_goal" in result.stride_meta_goal && + result.stride_meta_goal.meta_goal.todo_id !== todoId) throw new Error("Meta-goal source changed"); if (expectedNamespace && result.source_access?.namespace !== expectedNamespace) throw new Error("Task source changed"); return result; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx index 71e75b04b5..b42009ee4e 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx @@ -548,6 +548,14 @@ const en = { "drawer.requestLocalOnly": "This source provides a summary. Open its local workspace to read the full request.", "drawer.requestUnidentified": "Showing the received text. This legacy Task has no authority id for a full request read.", "drawer.requestRetry": "Retry full request", + "drawer.metaGoal": "Meta-goal", + "drawer.metaGoalCriterion": "Evidence needed to decide", + "drawer.metaGoalResolution": "Conclusion", + "drawer.metaGoalAction": "Decision action", + "drawer.metaGoalProbe": "Next probe", + "drawer.metaGoalEvidence": "Evidence for this decision", + "drawer.metaGoalEvidenceUnavailable": "Source evidence unavailable", + "drawer.metaGoalUnavailable": "The meta-goal could not be read.", "drawer.taskManage": "Manage task", "drawer.taskCompletionProof": "Original execution proof (optional)", "drawer.taskCompletionProofHint": "For a task requiring an execution lease, paste the responsible Agent's original JSON with agent_id, task_lease_idempotency_key and task_lease_expected_version. This does not acquire a lease or change ownership. Review and confirm completion normally.", @@ -2175,6 +2183,14 @@ const zhCN: Record = { "drawer.requestLocalOnly": "此来源提供摘要,请在它的本机工作区读取完整要求。", "drawer.requestUnidentified": "显示已收到的正文。此旧版任务缺少原始 ID,无法另行读取完整要求。", "drawer.requestRetry": "重试读取完整要求", + "drawer.metaGoal": "元目标", + "drawer.metaGoalCriterion": "作出选择所需的证据", + "drawer.metaGoalResolution": "结论", + "drawer.metaGoalAction": "元决策动作", + "drawer.metaGoalProbe": "下一探针", + "drawer.metaGoalEvidence": "本次决策的依据", + "drawer.metaGoalEvidenceUnavailable": "原始证据暂不可读", + "drawer.metaGoalUnavailable": "暂时无法读取元目标。", "drawer.taskManage": "管理任务", "drawer.taskCompletionProof": "原执行证明(可选)", "drawer.taskCompletionProofHint": "需要执行租约的任务,可粘贴负责 Agent 提供的原 JSON:agent_id、task_lease_idempotency_key、task_lease_expected_version。这不会领取租约或改变归属;仍需检查并确认完成。", diff --git a/apps/presentation/dashboard/src/features/personal-workspace/task-request.tsx b/apps/presentation/dashboard/src/features/personal-workspace/task-request.tsx index a99525808f..bcabf457fa 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/task-request.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/task-request.tsx @@ -57,6 +57,7 @@ export function TaskRequest({todo, local, sourceNamespace, onSave, onRead}: {tod }, [identity, local, retry, todo.goalId, sourceId, sourceNamespace, publishRead]); const current = local && read?.identity === identity ? read : null; const detail = current?.phase === "ready" ? current.detail : null; + const stride = detail?.stride_meta_goal; const editable = local && onSave && todo.claimedBy && sourceId && detail?.review_basis && detail.archive_state === "active" && detail.status !== "done"; const draftLength = compactPythonTextLength(draft?.text ?? ""); @@ -87,6 +88,23 @@ export function TaskRequest({todo, local, sourceNamespace, onSave, onRead}: {tod } return
{!draft ? : null} + {stride && "meta_goal" in stride ?
+ {t("drawer.metaGoal")} + +
+
{t("drawer.metaGoalCriterion")}
+ {stride.meta_goal.resolution ? <>
{t("drawer.metaGoalResolution")}
+
: null} +
{t("drawer.metaGoalAction")}
{stride.action}
+
{t("drawer.metaGoalProbe")}
+
+ {stride.evidence.length ? <>

{t("drawer.metaGoalEvidence")}

    {stride.evidence.map(row => +
  • + {row.evidence_ref}
  • )}
: null} +
: stride?.unavailable ?
+ {t("drawer.metaGoalUnavailable")} + +
: null} {current?.phase !== "ready" ?
{t(!local ? "drawer.requestLocalOnly" : !sourceId ? "drawer.requestUnidentified" : current?.phase === "error" ? "drawer.requestError" : "drawer.requestLoading")} {current?.phase === "error" ? : null} diff --git a/docs/reference/protocols/goal-vision-replan-contract-v0.md b/docs/reference/protocols/goal-vision-replan-contract-v0.md index 5b77a43c5e..0fbc489c69 100644 --- a/docs/reference/protocols/goal-vision-replan-contract-v0.md +++ b/docs/reference/protocols/goal-vision-replan-contract-v0.md @@ -804,6 +804,48 @@ not improved model decisions or net efficiency. 任务缺失、关闭、改由他人认领或关联改变时旧页失效。未携带任务 ID 的全局页面保持 原契约;任务范围只改变证据相关性,不授予准入或强制选题。 +### Todo meta-goal / Todo 内的元目标 + +An admitted Stride review can attach `agent_vision.stride_decision.meta_goal` +to one open Agent Todo it retains in `todo_delta`. If the Turn is bound to a +Todo, use that Todo's exact ID. The optional object contains `todo_id`, +`objective`, `resolution_criterion`, and `evidence_refs`. Start a question +with empty references. The enclosing Stride `action` and `next_probe` express +the chosen response and the first work slice. + +An open meta-goal follows the Todo across ordinary Turns in +`work_context.stride_meta_goal`. In the next applicable Stride review, carry +the same objective and criterion with `previous_decision_ref` from +`todo_meta_goals`. Cite the exact references to subsequent work on that Todo +when changing the action or recording a `resolution`. The journal's append +order and the settled work identity qualify the references, including evidence +against a route. Omission preserves the last recorded question. A resolution +ends the question, and a later review can start another one on the same Todo. +All authored text and refs share the existing Vision budget. + +Read the latest question, action, probe and cited evidence in the App's Task +Request details or with `loopx --format json todo list --goal-id --todo-id +`. The exact CLI read also provides recent eligible source refs under +`subsequent_evidence` for an open question. Use `loopx --format json history --goal-id --agent-id +--evidence-ref ` to resolve the exact decision and each cited source row. +The references document which evidence the Agent cites for its choice. +Execution, Goal acceptance and gain follow their existing evidence contracts. + +在已准入的 Stride 复盘中,Agent 可用 `agent_vision.stride_decision.meta_goal` +为 `todo_delta` 中保留的一项开放 Todo 声明元目标。如果 Turn 已绑定 Todo,使用该 Todo 的 +精确 ID。首次写入 `todo_id`、`objective`、`resolution_criterion` 和空的 `evidence_refs`。 +外层的 `action` 和 `next_probe` 表达所选元决策动作及首个工作切片。 + +普通工作 Turn 通过 `work_context.stride_meta_goal` 接续未决目标。复盘时从 +`todo_meta_goals` 取得 `previous_decision_ref`,沿用原目标和证据条件。改变动作或写入 +`resolution` 时,引用该 Todo 后续工作的精确证据。系统核对日志追加顺序和已结算工作身份, +并保留反证。省略字段则沿用上次记录。元目标收口后,可在后续复盘中为同一 Todo 提出新问题。 +字段与引用计入已有 Vision 预算。 + +在 App 的任务要求详情或用 `todo list --todo-id` 回读元目标、动作、探针及证据, +用 `history --evidence-ref` 回读原决策和原证据。引用记录的是 Agent 作出选择所用的证据, +实际执行、Goal 验收和收益沿用各自的证据契约。 + ### Source-bound comparison selection With Explore planning and `evidence_conditioned_v1` enabled, the existing diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index 900e993e7e..3b95558018 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -1291,6 +1291,7 @@ def _read_stage(cmd_str: Any) -> dict[str, Any] | None: "triggers": review_view.get("triggers"), "recent_evidence": list(review_view.get("evidence") or [])[:12], "decision_followthrough": review_view.get("decision_followthrough"), + **({"todo_meta_goals": review_view["todo_meta_goals"]} if "todo_meta_goals" in review_view else {}), } writeback_view = _read_stage(packet.get("writeback")) if writeback_view is not None: diff --git a/loopx/chat/todo_detail.py b/loopx/chat/todo_detail.py index 43fd4cad99..b2b2b8dc5d 100644 --- a/loopx/chat/todo_detail.py +++ b/loopx/chat/todo_detail.py @@ -52,6 +52,7 @@ def _todo_detail(self) -> None: "text": item["text"], "status": item["status"], "archive_state": item.get("archive_state", "active"), "updated_at": item.get("updated_at"), + **({"stride_meta_goal": item["stride_meta_goal"]} if "stride_meta_goal" in item else {}), **({"review_basis": basis} if basis is not None else {}), }) except ValueError: diff --git a/loopx/control_plane/goals/vision_checkpoint.ts b/loopx/control_plane/goals/vision_checkpoint.ts index c8557ed3f3..37169df921 100644 --- a/loopx/control_plane/goals/vision_checkpoint.ts +++ b/loopx/control_plane/goals/vision_checkpoint.ts @@ -12,7 +12,7 @@ import { type DeliveryOutcome, } from "../work_items/delivery_outcome.ts"; -import {normalizeStrideDecision, STRIDE_DECISION_SCHEMA, RECORDED_STRIDE_SCHEMA, STRIDE_PROBE_LIMITS, STRIDE_AXIS_NAMES, STRIDE_PLAN_LIMIT, STRIDE_REASON_LIMIT, STRIDE_REVIEW_LIMIT} from "../work_items/stride_policy.ts"; +import {normalizeStrideDecision, STRIDE_DECISION_SCHEMA, RECORDED_STRIDE_SCHEMA, STRIDE_PROBE_LIMITS, STRIDE_META_GOAL_LIMITS, STRIDE_AXIS_NAMES, STRIDE_PLAN_LIMIT, STRIDE_REASON_LIMIT, STRIDE_REVIEW_LIMIT} from "../work_items/stride_policy.ts"; import lifecycle from "../goal_vision_lifecycle.json" with {type: "json"}; export const VISION_REFRESH_REQUEST_SCHEMA = "loopx_vision_refresh_request_v0"; @@ -836,6 +836,9 @@ function prepareVisionRefresh(request: VisionRefreshPrepareRequest): JsonObject fieldLimits[`stride_decision.axes.${axis}.reason`] = STRIDE_REASON_LIMIT; } if (strideDecision.previous_review) fieldLimits["stride_decision.previous_review.lesson"] = STRIDE_REVIEW_LIMIT; + if (strideDecision.meta_goal) for (const [field, limit] of Object.entries(STRIDE_META_GOAL_LIMITS)) { + if (Object.hasOwn(strideDecision.meta_goal as JsonObject, field)) fieldLimits[`stride_decision.meta_goal.${field}`] = limit; + } if (strideDecision.explore_review) fieldLimits["stride_decision.explore_review.reason"] = STRIDE_REVIEW_LIMIT; } fieldLimits["fallback_declarations"] = VISION_FALLBACK_DECLARATION_ENTRY_LIMIT; diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index d5d79f15c0..83f3f3e7dc 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -1148,11 +1148,13 @@ def observe_app_scheduler_state(readback: Mapping[str, Any]) -> None: registry_path=registry_path, runtime_root=runtime_root, ) - from ..work_items.context_readback import attach_work_context + from ..work_items.context_readback import attach_work_context, attach_stride_meta_goal_context attach_work_context(payload, registry_path=registry_path, runtime_root=runtime_root, hook_dispatch=turn_start_hook_dispatch, context_navigation=context_navigation, inline_goal_source=inline_goal_source) + attach_stride_meta_goal_context(payload, status_payload=decision_status_payload, + registry_goal=registered_goal, runtime_root=runtime_root) return payload diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index e918cda866..b94cda7340 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -1046,6 +1046,9 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly if (!attentionSources.length) include(...requiredReadsPath); const work = ["interaction_contract", "agent_channel", "work_context"]; include(...work, "instruction"); + if (normalWork && object(channel?.work_context)?.stride_meta_goal) { + include(...work, "stride_meta_goal"); + } if (deferredReentry) { // Surface the owner's reopen and same-Turn guard before the long read. for (const field of admissionFields) include("interaction_contract", "cli_channel", field); diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 55ba8de80c..f9cd7c3cfc 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1027,6 +1027,7 @@ function projectReplanView(request: JsonObject, payload: JsonObject, sourceHash: ...(acceptanceIndex ? {acceptance_index: acceptanceIndex} : {}), triggers: obligation.triggers, decision_followthrough: Object.keys(follow).length ? follow : null, + ...(Array.isArray(context.todo_meta_goals) ? {todo_meta_goals: context.todo_meta_goals} : {}), planning_horizon: payload.planning_horizon == null ? null : horizon, action_portfolio: payload.action_portfolio ?? null, ...(context.explore_basis ? {capabilities: {explore: retain({ diff --git a/loopx/control_plane/runtime/run_context_retention.py b/loopx/control_plane/runtime/run_context_retention.py index 583e61eef7..be88c77709 100644 --- a/loopx/control_plane/runtime/run_context_retention.py +++ b/loopx/control_plane/runtime/run_context_retention.py @@ -137,6 +137,7 @@ def goal_semantic_history_from_runs( """ from ..work_items.recommendation_source_io import recommendation_run_decision + from ..work_items.replan_context_codec import recorded_stride_meta_goal contexts: dict[str, dict[str, Any]] = {} resolved_agent_vision: set[str] = set() @@ -164,6 +165,8 @@ def goal_semantic_history_from_runs( if index in qualification.active_turn_retries: active_blocked_retry_runs.append(run) context = contexts.setdefault(agent_id, {"agent_id": agent_id}) + if "has_stride_meta_goal" not in context and recorded_stride_meta_goal(run) is not None: + context["has_stride_meta_goal"] = True if ("latest_lane_step_run" not in context and run.get("agent_id") == agent_id and recommendation_run_decision(run) is not None): @@ -275,6 +278,8 @@ def compact_goal_semantic_history( if not agent_id: continue context: dict[str, Any] = {"agent_id": agent_id} + if raw_context.get("has_stride_meta_goal") is True: + context["has_stride_meta_goal"] = True retired_at = str(raw_context.get("vision_retired_at") or "").strip() if retired_at: context["vision_retired_at"] = retired_at diff --git a/loopx/control_plane/stride_decision_schema.json b/loopx/control_plane/stride_decision_schema.json index 537b6c268a..32a9c5b751 100644 --- a/loopx/control_plane/stride_decision_schema.json +++ b/loopx/control_plane/stride_decision_schema.json @@ -5,6 +5,7 @@ "actions": ["grow", "switch", "verify"], "axis_plan_limit": 120, "probe_field_limits": {"scope": 120, "prediction": 120, "adoption_criterion": 120, "cost_bound": 100, "minimum_evidence": 120}, + "meta_goal_field_limits": {"objective": 144, "resolution_criterion": 144, "resolution": 120}, "axis_reason_limit": 96, "review_text_limit": 120, "review_reference_limit": 3, diff --git a/loopx/control_plane/todos/list_readback.py b/loopx/control_plane/todos/list_readback.py index 233b94cec7..9209dcfbc0 100644 --- a/loopx/control_plane/todos/list_readback.py +++ b/loopx/control_plane/todos/list_readback.py @@ -118,4 +118,19 @@ def list_goal_todos( from .goal_todo_projection import observe_todo_acceptance payload = observe_todo_acceptance(payload, result["canonical_acceptance"], registry_path=source_registry, goal_id=goal_id) + item = payload.get("todo") + if normalized_todo_id and isinstance(item, dict) and item.get("role") == "agent": + from ..work_items.replan_context_codec import read_todo_stride_meta_goal + + instance = goal.get("goal_instance_id") + try: + meta_goal = read_todo_stride_meta_goal( + runtime_root=runtime_root, goal_id=goal_id, todo_id=normalized_todo_id, + agent_id=normalized_agent_id, include_evidence=True, + goal_ref={"goal_id": goal_id, "goal_instance_id": instance} if instance else None, + ) + except (ValueError, OSError, RuntimeError): + meta_goal = {"unavailable": True} + if meta_goal is not None: + payload["todo"] = {**item, "stride_meta_goal": meta_goal} return payload diff --git a/loopx/control_plane/work_items/context_readback.py b/loopx/control_plane/work_items/context_readback.py index 6ecefac7c1..7fbdf3436c 100644 --- a/loopx/control_plane/work_items/context_readback.py +++ b/loopx/control_plane/work_items/context_readback.py @@ -98,6 +98,42 @@ def _user_context( "todos": inventory["todos"]} +def attach_stride_meta_goal_context( + payload: dict[str, Any], *, status_payload: dict[str, Any], + registry_goal: dict[str, Any] | None, runtime_root: Path, +) -> None: + if registry_goal is None or not payload.get("should_run") or not payload.get("normal_delivery_allowed"): + return + selected = payload.get("selected_todo") + agent = (payload.get("agent_identity") or {}).get("agent_id") + goal_id = payload.get("goal_id") + channel = (payload.get("interaction_contract") or {}).get("agent_channel") or {} + context = channel.get("work_context") + if not agent or not goal_id or not isinstance(context, dict) or not isinstance(selected, dict): + return + todo_id = selected.get("todo_id") + if not isinstance(todo_id, str) or not any( + lane.get("agent_id") == agent and lane.get("has_stride_meta_goal") is True + for goal in (status_payload.get("run_history") or {}).get("goals", []) if goal.get("id") == goal_id + for lane in (goal.get("semantic_history") or {}).get("agents", []) + ): + return + from ...capabilities.todo_replan_cadence.machine_defaults import resolve_todo_replan_cadence_goal + from .replan_context_codec import read_todo_stride_meta_goal + + profile = resolve_todo_replan_cadence_goal(registry_goal, runtime_root).get("execution_profile") or {} + if profile.get("stride_strategy", "off") == "off": + return + try: + record = read_todo_stride_meta_goal(runtime_root=runtime_root, goal_id=goal_id, + todo_id=todo_id, agent_id=agent, goal_ref=payload.get("goal_ref")) + except (ValueError, OSError, RuntimeError): + context["stride_meta_goal"] = {"unavailable": True} + return + if record is not None and not record["meta_goal"].get("resolution"): + context["stride_meta_goal"] = record + + def attach_work_context(payload: dict[str, Any], *, registry_path: Path, runtime_root: Path, hook_dispatch: dict[str, Any] | None, context_navigation: bool = False, diff --git a/loopx/control_plane/work_items/replan_context.ts b/loopx/control_plane/work_items/replan_context.ts index 1ed7d528c2..2217ed6a04 100644 --- a/loopx/control_plane/work_items/replan_context.ts +++ b/loopx/control_plane/work_items/replan_context.ts @@ -126,15 +126,19 @@ function isAccountingRow(row: JsonObject): boolean { } /** Preserve historical references even when a record fails work qualification. */ -function workEvidenceRef(row: JsonObject): string { +function settledTodoEvidenceRef(row: JsonObject): string | null { const source = objectOrNull(row._source_facts); - if (row.progress_observation !== null || isAccountingRow(row)) return historicalEvidenceRef(row); const identity = recordedTodoIdentity(row); - if (!identity) return historicalEvidenceRef(row); + if (!identity) return null; const goalRef = objectOrNull(source?.goal_ref); return "replan-evidence-" + digest([readableEvidenceRow(row), identity, goalRef?.goal_instance_id ?? null]); } +function workEvidenceRef(row: JsonObject): string { + if (row.progress_observation !== null || isAccountingRow(row)) return historicalEvidenceRef(row); + return settledTodoEvidenceRef(row) ?? historicalEvidenceRef(row); +} + function evidenceFactsKey(row: JsonObject): string { const {generated_at: _time, evidence_ref: _ref, ...facts} = readableEvidenceRow(row); return digest(facts); @@ -215,6 +219,12 @@ function recordedDecision(row: JsonObject): JsonObject | null { catch { return null; } const identity = objectOrNull(source.settlement_identity)!; const autonomous = identity.binding_kind === "autonomous_replan"; + const metaGoal = objectOrNull(stride?.meta_goal); + const todoDelta = objectOrNull(source.agent_vision)?.todo_delta; + if (metaGoal && ((!autonomous && metaGoal.todo_id !== row.todo_id) || + !Array.isArray(todoDelta) || !todoDelta.includes(`retain:${metaGoal.todo_id}`))) { + return null; + } const decision = {history_evidence_ref: "replan-evidence-" + digest(readableEvidenceRow(row)), generated_at: row.generated_at, todo_id: autonomous ? null : row.todo_id, turn_instance_id: identity.turn_instance_id, ...(autonomous ? {replan_obligation_id: source.replan_obligation_id} : {}), @@ -259,6 +269,117 @@ function plannedObservationTodo(row: JsonObject, targets: ReadonlySet): return todo !== null && targets.has(todo) ? todo : null; } +function eligibleMetaGoalTodo(todo: JsonObject, goal: string, agent: string): boolean { + return todo.role === "agent" && todo.status === "open" && + (todo.goal_id == null || todo.goal_id === goal) && + (todo.claimed_by == null || todo.claimed_by === "" || todo.claimed_by === agent); +} + +type MetaGoalDecision = {row: JsonObject; decision: JsonObject; stride: JsonObject; goal: JsonObject}; + +function metaGoalTodoId(row: JsonObject): unknown { + const vision = objectOrNull(objectOrNull(row._source_facts)?.agent_vision); + return objectOrNull(objectOrNull(vision?.stride_decision)?.meta_goal)?.todo_id; +} + +function metaGoalDecisions(scoped: JsonObject[], todoIds: ReadonlySet): Map { + const latest = new Map(); + const seen = new Set(); + for (const row of scoped) { + const todoId = metaGoalTodoId(row); + if (!todoIds.has(todoId) || seen.has(todoId) || !acceptedDecisionSource(row)) continue; + seen.add(todoId); + const decision = recordedDecision(row); + const stride = objectOrNull(decision?.stride_decision); + const goal = objectOrNull(stride?.meta_goal); + if (!decision || !stride || !goal) { + throw new EffectRuntimeRequestError("Recorded Todo meta-goal is unavailable; reread the original decision"); + } + latest.set(todoId, {row, decision, stride, goal}); + } + return latest; +} + +function metaGoalWorkEvidence(scoped: JsonObject[], todoId: unknown, after: JsonObject): {ref: string; row: JsonObject}[] { + const position = Number(objectOrNull(after._source_facts)?.history_position); + return scoped.flatMap(row => { + const order = Number(objectOrNull(row._source_facts)?.history_position); + if (order <= position || observationTodo(row) !== todoId || isAccountingRow(row) || + acceptedDecisionSource(row) || hasConflictingTodoSettlement(row) || + !MATERIAL_DELIVERY_OUTCOMES.some(outcome => outcome === row.delivery_outcome)) return []; + const ref = settledTodoEvidenceRef(row); + return ref ? [{ref, row}] : []; + }); +} + +function metaGoalEvidencePreview(recorded: MetaGoalDecision, scoped: JsonObject[]): JsonObject[] { + if (recorded.goal.resolution) return []; + return metaGoalWorkEvidence(scoped, recorded.goal.todo_id, recorded.row).slice(0, 6) + .map(({ref, row}) => ({evidence_ref: ref, generated_at: row.generated_at, delivery_outcome: row.delivery_outcome, + result_class: objectOrNull(row.progress_observation)?.result_class ?? null})); +} + +function metaGoalView(recorded: MetaGoalDecision): JsonObject { + return {decision_ref: recorded.decision.evidence_ref, generated_at: recorded.decision.generated_at, + agent_id: recorded.row.agent_id, meta_goal: recorded.goal, + action: recorded.stride.action, next_probe: recorded.stride.next_probe}; +} + +function todoMetaGoal(request: JsonObject, scoped: JsonObject[], goal: string, agent: string | null): JsonObject { + const todoId = identifier(request.todo_id, "meta-goal Todo"); + const decision = normalizeRecordedStrideDecision(request.proposal); + const proposed = objectOrNull(decision?.meta_goal); + const previous = metaGoalDecisions(scoped, new Set([todoId])).get(todoId); + if (!proposed) { + if (!previous) return {current: null}; + const current = metaGoalView(previous); + if (request.include_evidence === true) { + const refs = previous.goal.evidence_refs as string[]; + current.evidence = refs.map(ref => { + const row = scoped.find(row => row.todo_id === todoId && row.agent_id === previous.row.agent_id && + !isAccountingRow(row) && !hasConflictingTodoSettlement(row) && settledTodoEvidenceRef(row) === ref); + return row ? {evidence_ref: ref, generated_at: row.generated_at, + summary: row.recommended_action ?? row.health_check ?? row.classification ?? null} : {evidence_ref: ref}; + }); + current.subsequent_evidence = metaGoalEvidencePreview(previous, + scoped.filter(row => row.agent_id === previous.row.agent_id)); + } + return {current}; + } + + const todo = requireJsonObject(request.todo, "canonical meta-goal Todo"); + if (!agent || proposed.todo_id !== todoId || todo.todo_id !== todoId || !eligibleMetaGoalTodo(todo, goal, agent) || + request.settlement_todo_id != null && request.settlement_todo_id !== todoId || + !Array.isArray(request.todo_delta) || !request.todo_delta.includes(`retain:${todoId}`)) { + throw new EffectRuntimeRequestError("A meta-goal requires the current open Agent Todo, retained in the Stride decision"); + } + if (!previous || previous.goal.resolution) { + if (proposed.previous_decision_ref) throw new EffectRuntimeRequestError("Start a new meta-goal without a previous decision reference"); + return {current: null}; + } + if (proposed.previous_decision_ref !== previous.decision.evidence_ref || + proposed.objective !== previous.goal.objective || proposed.resolution_criterion !== previous.goal.resolution_criterion) { + throw new EffectRuntimeRequestError("Carry forward the current Todo meta-goal and its exact previous decision reference"); + } + const refs = proposed.evidence_refs as string[]; + if (decision!.action !== previous.stride.action && refs.length === 0) { + throw new EffectRuntimeRequestError("Changing a meta-decision action requires subsequent evidence for the same Todo"); + } + const allowed = new Set(metaGoalWorkEvidence(scoped, todoId, previous.row).map(({ref}) => ref)); + if (refs.some(ref => !allowed.has(ref))) { + throw new EffectRuntimeRequestError("Meta-goal evidence must come from subsequent settled work on the same Todo"); + } + return {current: metaGoalView(previous)}; +} + +function projectTodoMetaGoals(rows: JsonObject[], request: JsonObject, goal: string, agent: string): JsonObject[] { + if (!rows.some(row => metaGoalTodoId(row) !== undefined)) return []; + const scoped = orderedDecisionRows(rows, request.goal_facts); + const eligible = objects(request.todo_items, "Todo source").filter(todo => eligibleMetaGoalTodo(todo, goal, agent)); + return [...metaGoalDecisions(scoped, new Set(eligible.map(todo => todo.todo_id))).values()] + .slice(0, 6).map(recorded => ({...metaGoalView(recorded), evidence: metaGoalEvidencePreview(recorded, scoped)})); +} + /** Reserve one source-ordered observation per displayed planned Todo before * filling the remaining slots. Repetition on one work item must not hide all * followthrough on another; the cap is presentation, never evidence eligibility. */ @@ -288,6 +409,7 @@ function workResultUse(scoped: JsonObject[]): JsonObject | null { const followed: JsonObject[] = []; const seen = new Set(); const legacyResultRefs = new Map(); + let hasMetaGoal = false; for (const row of [...scoped].reverse()) { if (isAccountingRow(row)) continue; const source = objectOrNull(row._source_facts)!; @@ -296,12 +418,17 @@ function workResultUse(scoped: JsonObject[]): JsonObject | null { if (!decision) { origin.clear(); proposed.clear(); continue; } const id = String(decision.evidence_ref), targets = plannedTodoIds(source); const path = decision.path_delta as JsonObject; - const review = objectOrNull(objectOrNull(decision.stride_decision)?.previous_review); - const refs = [...(path.evidence_refs as string[]), - ...(Array.isArray(review?.evidence_refs) ? review.evidence_refs as string[] : [])] - .map(ref => pending.has(ref) ? ref : legacyResultRefs.get(ref) ?? ref) - .filter(ref => pending.has(ref)); + const stride = objectOrNull(decision.stride_decision); + const review = objectOrNull(stride?.previous_review); + const metaGoal = objectOrNull(stride?.meta_goal); + if (metaGoal) hasMetaGoal = true; + const pathRefs = [...(path.evidence_refs as string[]), + ...(Array.isArray(review?.evidence_refs) ? review.evidence_refs as string[] : [])]; for (const todo of targets) { + const metaRefs = metaGoal?.todo_id === todo ? metaGoal.evidence_refs as string[] : []; + const refs = [...pathRefs, ...metaRefs] + .map(ref => pending.has(ref) ? ref : legacyResultRefs.get(ref) ?? ref) + .filter(ref => pending.has(ref)); origin.set(todo, id); // A newer plan for the same work replaces its unexecuted proposal, // not the source evidence still waiting for attributable followthrough. @@ -324,6 +451,8 @@ function workResultUse(scoped: JsonObject[]): JsonObject | null { // citation matches multiple formerly collapsed rows, use that alias once. const legacyRef = historicalEvidenceRef(row); if (!legacyResultRefs.has(legacyRef)) legacyResultRefs.set(legacyRef, ref); + const settledRef = hasMetaGoal ? settledTodoEvidenceRef(row) : null; + if (settledRef) legacyResultRefs.set(settledRef, ref); if (seen.has(ref)) continue; seen.add(ref); const adoption = proposed.get(todo); @@ -366,6 +495,7 @@ function reviewEvidence(rows: JsonObject[], request: JsonObject): JsonObject { const targets = new Set(plannedTodoIds(source)); const citations = refs.map(ref => { const matches = scoped.filter(row => workEvidenceRef(row) === ref || historicalEvidenceRef(row) === ref + || (!isAccountingRow(row) && !hasConflictingTodoSettlement(row) && settledTodoEvidenceRef(row) === ref) || (objectOrNull(row.progress_observation)?.evidence_ids as unknown[] | undefined)?.includes(ref)); const subsequent = matches.filter(row => { const facts = objectOrNull(row._source_facts)!; @@ -609,7 +739,8 @@ export async function projectReplanContextSnapshot(value: unknown): Promise Number(b.observed_at) - Number(a.observed_at) || JSON.stringify(readableEvidenceRow(a)).localeCompare(JSON.stringify(readableEvidenceRow(b)))); // Unpaired accounting can still explain a failure. It never contributes @@ -656,7 +790,10 @@ export function projectReplanContext(value: unknown): JsonObject { if (!agent) throw new EffectRuntimeRequestError("evidence resolution requires agent_id"); const ref = identifier(request.evidence_ref, "evidence_ref"); const legacy = rows.find(row => historicalEvidenceRef(row) === ref); + const settled = rows.find(row => !isAccountingRow(row) && !hasConflictingTodoSettlement(row) && + settledTodoEvidenceRef(row) === ref); const match = unique.get(ref) ?? (legacy && {...readableEvidenceRow(legacy), evidence_ref: ref}) + ?? (settled && {...readableEvidenceRow(settled), evidence_ref: ref}) ?? rows.map(recordedDecision).find(decision => decision?.evidence_ref === ref); if (!match) throw new EffectRuntimeRequestError( "evidence reference is unavailable in this Goal and Agent history window; refresh replan_context", @@ -751,10 +888,13 @@ export function projectReplanContext(value: unknown): JsonObject { const exploreBasis = strideStrategy !== "off" ? projectStrideExploreBasis(request.explore_context, goal, agent) : null; const followthrough = agent ? decisionFollowthrough(rows, request.goal_facts, request.from_full_index === true, request.todo_items) : null; + const todoMetaGoals = agent && strideStrategy !== "off" && request.todo_items != null + ? projectTodoMetaGoals(rows, request, goal, agent) : []; const contextId = "replan-context-" + digest({goal, agent, obligationId, core, ledger, shown, frontier, ...(evidenceReadTemplate ? {evidence_read_action_template: evidenceReadTemplate} : {}), ...(strideStrategy !== "off" ? {stride_strategy: strideStrategy} : {}), ...(followthrough ? {decision_followthrough: followthrough} : {}), + ...(todoMetaGoals.length ? {todo_meta_goals: todoMetaGoals} : {}), ...(exploreBasis ? {explore_basis: exploreBasis} : {})}); const context: JsonObject = { schema_version: CONTEXT_SCHEMA, context_id: contextId, goal_id: goal, agent_id: agent, @@ -769,6 +909,7 @@ export function projectReplanContext(value: unknown): JsonObject { }; if (strideStrategy !== "off") context.stride_strategy = strideStrategy; if (followthrough) context.decision_followthrough = followthrough; + if (todoMetaGoals.length) context.todo_meta_goals = todoMetaGoals; if (exploreBasis) context.explore_basis = exploreBasis; // Source-replayed supplemental pages qualify a proposal, not a new admission // context. They must not change the original context or bounded basis IDs. diff --git a/loopx/control_plane/work_items/replan_context_codec.py b/loopx/control_plane/work_items/replan_context_codec.py index f5d927c7b3..e8611f8cc6 100644 --- a/loopx/control_plane/work_items/replan_context_codec.py +++ b/loopx/control_plane/work_items/replan_context_codec.py @@ -230,6 +230,51 @@ def validate_replan_context(context: Any) -> dict[str, Any]: raise ValueError(str(exc)) from None +def recorded_stride_meta_goal(run: Mapping[str, Any]) -> Mapping[str, Any] | None: + """Presence in a journal row only. TypeScript qualifies identity and evidence.""" + vision = run.get("agent_vision") + stride = vision.get("stride_decision") if isinstance(vision, Mapping) else None + meta_goal = stride.get("meta_goal") if isinstance(stride, Mapping) else None + return meta_goal if isinstance(meta_goal, Mapping) else None + + +def project_todo_stride_meta_goal( + *, goal_id: str, agent_id: str | None, todo_id: str, goal_ref: Mapping[str, Any] | None, + runs: Iterable[Mapping[str, Any]], history_newest_first: bool, + **fields: Any, +) -> dict[str, Any] | None: + from .replan_history_codec import project_replan_request + + try: + result = project_replan_request({ + "operation": "todo_meta_goal", "obligation": None, "goal_id": goal_id, + "agent_id": agent_id, "todo_id": todo_id, "goal_facts": {"goal_ref": goal_ref}, + "rows": replan_evidence_rows(runs, goal_id=goal_id, agent_id=agent_id, + include_decisions=True, history_newest_first=history_newest_first), + **fields, + }, method="work_item.replan_context") + except EffectRuntimeRejected as exc: + raise ValueError(str(exc)) from None + return cast(dict[str, Any] | None, result.get("current")) + + +def read_todo_stride_meta_goal( + *, runtime_root: Path, goal_id: str, todo_id: str, agent_id: str | None = None, + goal_ref: Mapping[str, Any] | None = None, include_evidence: bool = False, +) -> dict[str, Any] | None: + from ...history import load_index_snapshot, validate_goal_id_path_segment + + goal_id = validate_goal_id_path_segment(goal_id) + runs = load_index_snapshot(runtime_root / "goals" / goal_id / "runs" / "index.jsonl", + include_artifact_status=False).records + if not any((recorded_stride_meta_goal(run) or {}).get("todo_id") == todo_id for run in runs): + return None + return project_todo_stride_meta_goal( + goal_id=goal_id, agent_id=agent_id, todo_id=todo_id, goal_ref=goal_ref, + runs=runs, history_newest_first=False, include_evidence=include_evidence, + ) + + def replay_stride_review_evidence( *, context: Mapping[str, Any], review: Mapping[str, Any], runs: Iterable[Mapping[str, Any]], ) -> dict[str, Any]: diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index 31e62ea64f..494670ebf6 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -681,6 +681,10 @@ export function projectReplanSemantics(value: unknown): JsonObject { const context = object(obligation.replan_context); const [strideDecision] = normalizeStrideDecision(vision.stride_decision); const structuredReview = normalizeStrideStrategy(context.stride_strategy) !== "off"; + const hasMetaGoal = strideDecision?.meta_goal != null; + if (hasMetaGoal && !structuredReview) { + throw new EffectRuntimeRequestError("Todo meta-goal requires an enabled Stride review"); + } const selectedComparison = object(strideDecision?.explore_review).selected_candidate != null; const requiredStrideReview = requiresStrideDecision(obligation); const pathOutcome = String(path.outcome ?? "").trim(); @@ -690,11 +694,11 @@ export function projectReplanSemantics(value: unknown): JsonObject { const independentStride = strideDecision?.schema_version === STRIDE_DECISION_SCHEMA; const missingStride = structuredReview && (freshPath || requiredStrideReview) && (!strideDecision || !independentStride); - const missingStridePath = requiredStrideReview && !evidenceLinkedPath; + const missingStridePath = (requiredStrideReview && !evidenceLinkedPath) || (hasMetaGoal && !freshPath); const staleStride = !!strideDecision && (structuredReview || selectedComparison) && strideDecision.reference_obligation_id !== obligation.obligation_id; const reviewContextChanged = !!strideDecision && (structuredReview || selectedComparison) - && (requiredStrideReview || selectedComparison) && strideDecision.reference_context_id !== context.context_id; + && (requiredStrideReview || selectedComparison || hasMetaGoal) && strideDecision.reference_context_id !== context.context_id; const reviewMismatch = strideDecision && (structuredReview || selectedComparison) ? reviewContextChanged ? "Stride decision references a different review context. Read the returned context_recovery before retrying the original writeback." @@ -728,7 +732,7 @@ export function projectReplanSemantics(value: unknown): JsonObject { outcomes.push("fresh_vision_path_outcome"); } if (staleStride || missingStride || reviewMismatch) outcomes = outcomes.filter(outcome => outcome !== "fresh_vision_path_outcome"); - const satisfying = inconsistentTerminal || (requiredStrideReview && (missingStride || missingStridePath || staleStride || reviewMismatch)) + const satisfying = inconsistentTerminal || ((requiredStrideReview || hasMetaGoal) && (missingStride || missingStridePath || staleStride || reviewMismatch)) || (selectedComparison && (staleStride || reviewMismatch)) ? [] : outcomes.filter(outcome => required.includes(outcome as SemanticOutcome)); const replayRefused = (replayed || knownBlocker) && !satisfying.length && !inconsistentTerminal; diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 38ff46c6b3..dfbbba9808 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -38,6 +38,7 @@ ) from .progress_observation import guarded_replan_transition_delta, semantic_delta_from_writeback from .lifecycle_recovery import attach_receipt_replan_context +from .replan_context_codec import project_todo_stride_meta_goal, recorded_stride_meta_goal, replan_history_from_status from .replan_semantics_codec import project_replan_semantics from ..effect_runtime import effect_runtime_request_scope from .repair_delta import ( @@ -318,6 +319,7 @@ def qualify_replan_writeback( external_progress_review: Mapping[str, Any] | None = None, effective_turn_cadence: dict[str, Any] | None = None, guard_scoped: bool = False, + settlement_todo_id: str | None = None, guard_semantic_replan_obligation_id: str | None = None, capability_evidence: CapabilityReplanEvidence | None = None, guard_capability: Mapping[str, Any] | None = None, @@ -339,6 +341,9 @@ def qualify_replan_writeback( """ safe_agent_id = str(agent_id or "").strip() + meta_goal = recorded_stride_meta_goal({"agent_vision": agent_vision}) + if meta_goal is not None and not (safe_agent_id and guard_scoped and guard_semantic_replan_obligation_id): + raise ValueError("A Todo meta-goal requires an admitted Stride review") if not safe_agent_id: return None, None todo_projection = todo_fields if todo_fields is not None else parse_active_state_todos( @@ -484,6 +489,19 @@ def qualify_replan_writeback( agent_vision=agent_vision, history_runs=newest_first_runs, ) + if meta_goal is not None and semantic_delta.get("accepted") is True: + todo_id = str(meta_goal["todo_id"]) + matches = [item for item in agent_todo_completion_items if item.get("todo_id") == todo_id] + if len(matches) != 1: + raise ValueError("The Todo targeted by the meta-goal is missing or ambiguous") + assert agent_vision is not None + project_todo_stride_meta_goal( + goal_id=goal_id, agent_id=safe_agent_id, todo_id=todo_id, goal_ref=goal_ref, + runs=replan_history_from_status(status_payload, goal_id), + history_newest_first=not bool(status_payload.get("registry") and status_payload.get("runtime_root")), + proposal=agent_vision["stride_decision"], todo_delta=agent_vision.get("todo_delta"), + todo=matches[0], settlement_todo_id=settlement_todo_id, + ) if ( "coverage_backed_no_followup" in set(semantic_delta.get("outcomes") or []) @@ -515,6 +533,7 @@ def enforce_open_replan_writeback( completion_todo_id: str | None = None, completion_turn_key: str | None = None, guard_scoped: bool = False, + settlement_todo_id: str | None = None, guard_semantic_replan_obligation_id: str | None = None, receipt_bound_guard_recorded_at: str | None = None, receipt_bound_guard_turn_instance_id: str | None = None, @@ -552,6 +571,7 @@ def enforce_open_replan_writeback( completion_turn_key=completion_turn_key, todo_fields=todo_fields, guard_scoped=guard_scoped, + settlement_todo_id=settlement_todo_id, guard_semantic_replan_obligation_id=guard_semantic_replan_obligation_id, capability_evidence=capability_evidence, guard_capability=guard_capability, @@ -691,6 +711,7 @@ def qualify_refresh_replan_writeback( completion_todo_id=completion_todo_id, completion_turn_key=completion_turn_key, guard_scoped=settlement_guard_scoped, + settlement_todo_id=settlement_todo_id, todo_fields=todo_fields, guard_semantic_replan_obligation_id=( settlement_guard_semantic_replan_obligation_id @@ -702,6 +723,10 @@ def qualify_refresh_replan_writeback( replan_source_route=replan_source_route, replan_explore_reader=replan_explore_reader, goal_ref=goal_ref, ) + if recorded_stride_meta_goal({"agent_vision": agent_vision}) is not None and ( + not semantic_delta or "fresh_vision_path_outcome" not in semantic_delta.get("satisfying_outcomes", []) + ): + raise ValueError("A Todo meta-goal requires a fresh, accepted Stride path decision") if semantic_delta: if semantic_delta.get("retirement") and delivery_outcome != "outcome_gap": raise ValueError("capability duty retirement requires outcome_gap; it is not delivery progress") diff --git a/loopx/control_plane/work_items/stride_policy.ts b/loopx/control_plane/work_items/stride_policy.ts index 58d5e4219e..67c5e7c4a5 100644 --- a/loopx/control_plane/work_items/stride_policy.ts +++ b/loopx/control_plane/work_items/stride_policy.ts @@ -35,6 +35,7 @@ const decisionValueReview = { export const STRIDE_DECISION_SCHEMA = decisionSchema.schema_version; export const STRIDE_PROBE_LIMITS = decisionSchema.probe_field_limits; +export const STRIDE_META_GOAL_LIMITS = decisionSchema.meta_goal_field_limits; export const STRIDE_AXIS_NAMES = decisionSchema.axis_names; export const STRIDE_PLAN_LIMIT = decisionSchema.axis_plan_limit; export const STRIDE_REASON_LIMIT = decisionSchema.axis_reason_limit; @@ -59,6 +60,29 @@ function refs(value: unknown, label: string): string[] { } return value as string[]; } +function normalizeMetaGoal(value: unknown, checked: BoundedText, usage: Record): JsonObject { + const label = "stride_decision.meta_goal"; + const input = requireJsonObject(value, label); + exactFields(input, ["todo_id", "objective", "resolution_criterion", "previous_decision_ref", "evidence_refs", "resolution"], label); + const todoId = requireNonEmptyString(input.todo_id, `${label}.todo_id`); + if (!PLANNING_TODO_ID.test(todoId)) throw new EffectRuntimeRequestError(`${label} requires an exact Todo id`); + const evidence = refs(input.evidence_refs, `${label}.evidence_refs`); + const prior = input.previous_decision_ref; + if (prior !== undefined && (typeof prior !== "string" || !/^replan-decision-[a-f0-9]{24}$/.test(prior))) { + throw new EffectRuntimeRequestError(`${label} requires a recorded previous decision reference`); + } + if ((!prior && evidence.length) || (input.resolution !== undefined && !evidence.length)) { + throw new EffectRuntimeRequestError(`${label} resolution and evidence require a previous decision and subsequent Todo evidence`); + } + usage[`${label}.todo_id`] = todoId.length; + if (typeof prior === "string") usage[`${label}.previous_decision_ref`] = prior.length; + usage[`${label}.evidence_refs`] = evidence.join("").length; + return {todo_id: todoId, + objective: checked("meta_goal.objective", input.objective, STRIDE_META_GOAL_LIMITS.objective), + resolution_criterion: checked("meta_goal.resolution_criterion", input.resolution_criterion, STRIDE_META_GOAL_LIMITS.resolution_criterion), + ...(prior ? {previous_decision_ref: prior} : {}), evidence_refs: evidence, + ...(input.resolution !== undefined ? {resolution: checked("meta_goal.resolution", input.resolution, STRIDE_META_GOAL_LIMITS.resolution)} : {})}; +} function selectedCandidate(value: unknown): JsonObject { const input = requireJsonObject(value, "explore_review.selected_candidate"); exactFields(input, ["todo_id", "node_id", "finding_id", "source_sha256"], "selected_candidate"); @@ -101,7 +125,7 @@ export function normalizeStrideDecision(value: unknown, bounded: BoundedText = t const historical = input.schema_version === RECORDED_STRIDE_SCHEMA; if (historical && input.axis_reasons === undefined) return normalizeHistoricalStrideDecision(input, bounded); exactFields(input, ["schema_version", "strategy_version", "reference_context_id", "reference_obligation_id", "basis", - "axes", ...(historical ? ["axis_reasons"] : ["action"]), "next_probe", "previous_review", "explore_review"], "stride_decision"); + "axes", ...(historical ? ["axis_reasons"] : ["action", "meta_goal"]), "next_probe", "previous_review", "explore_review"], "stride_decision"); if ((!historical && input.schema_version !== decisionSchema.schema_version) || normalizeStrideStrategy(input.strategy_version) !== "evidence_conditioned_v1") { throw new EffectRuntimeRequestError("stride_decision requires stride_decision_v2 and evidence_conditioned_v1; v1 is historical only"); } @@ -150,6 +174,7 @@ export function normalizeStrideDecision(value: unknown, bounded: BoundedText = t basis: input.basis, ...(historical ? {axes: {...axes}, axis_reasons: axisReasons} : {action: input.action, axes: axisPlans}), next_probe: normalized}; for (const key of ["strategy_version", "reference_context_id", "reference_obligation_id", "basis"]) usage[`stride_decision.${key}`] = String(input[key]).length; + if (Object.hasOwn(input, "meta_goal")) output.meta_goal = normalizeMetaGoal(input.meta_goal, checked, usage); if (input.previous_review != null) { const review = requireJsonObject(input.previous_review, "stride_decision.previous_review"); exactFields(review, ["reference_decision_ref", "adoption", "information_gain", "goal_gain", "evidence_refs", "lesson"], "previous_review"); @@ -412,6 +437,14 @@ export function strideControlContract(context: JsonObject, obligationId: unknown decision_value_review: {...decisionValueReview}, review_text_limit: decisionSchema.review_text_limit, review_reference_limit: STRIDE_REVIEW_REFERENCE_LIMIT, + meta_goal_option: { + attachment: "agent_vision.stride_decision.meta_goal", + required_fields: ["todo_id", "objective", "resolution_criterion", "evidence_refs"], + field_limits: STRIDE_META_GOAL_LIMITS, + rule: "Optionally set a question and evidence criterion for one open Todo you can retain. Add retain: to todo_delta. " + + "Start with empty evidence_refs. To carry an open question forward, copy its objective, criterion and previous_decision_ref. " + + "Cite exact subsequent work evidence for this Todo when changing the action or recording a resolution. Leave resolution absent while the question remains open.", + }, previous_decision_ref: previous, ...(follow ? {decision_followthrough: follow} : {}), previous_review_options: {adoption: decisionSchema.adoption_options, information_gain: decisionSchema.information_options, goal_gain: decisionSchema.gain_options}, diff --git a/loopx/presentation/goal_source_routing.py b/loopx/presentation/goal_source_routing.py index 4889efed82..684f5f9d20 100644 --- a/loopx/presentation/goal_source_routing.py +++ b/loopx/presentation/goal_source_routing.py @@ -148,6 +148,7 @@ def _todo_detail(self): self._send_json({"ok": True, "goal_id": goal_id, "todo_id": todo_id, "text": item["text"], "status": item["status"], "evidence": item.get("evidence"), "note": item.get("note"), + **({"stride_meta_goal": item["stride_meta_goal"]} if "stride_meta_goal" in item else {}), "archive_state": item.get("archive_state", "active"), "updated_at": item.get("updated_at"), "source_access": row["source_access"]}) except (ValueError, TypeError, KeyError): diff --git a/tests/control_plane/test_todo_stride_meta_goal_cli.py b/tests/control_plane/test_todo_stride_meta_goal_cli.py new file mode 100644 index 0000000000..543949308a --- /dev/null +++ b/tests/control_plane/test_todo_stride_meta_goal_cli.py @@ -0,0 +1,145 @@ +"""A Todo's evidence must survive normal Turns and bind its next Stride action.""" + +from copy import deepcopy +import json +from pathlib import Path + +import pytest + +from canonical_authority_fixture import isolate_sqlite_runtime +from loopx.control_plane.quota.turn_envelope import build_turn_envelope +from research_comparison_fixture import vision +import test_quota_settlement_cli as fixture + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_todo_meta_goal_survives_turns_and_links_decisive_evidence(tmp_path, monkeypatch, provider): + isolate_sqlite_runtime(tmp_path, monkeypatch) + monkeypatch.setenv("LOOPX_USAGE_PING", "0") + project, runtime, registry = fixture._write_fixture(tmp_path) + config = json.loads(registry.read_text()) + config["goals"][0]["quota"]["allowed_slots"] = 12 + registry.write_text(json.dumps(config)) + fixture._initialize_fixture_authority(project, runtime, provider=provider) + goal, agent, todo = fixture.GOAL_ID, fixture.AGENT_ID, fixture.TODO_ID + identity = ("--goal-id", goal, "--agent-id", agent) + journal = runtime / "goals" / goal / "runs/index.jsonl" + + def cli(*arguments, expected=0): + code, packet = fixture._run_cli(registry, runtime, *arguments, cwd=project) + assert code == expected, packet.get("error") or packet.get("reason") or packet + return packet + + def cadence(count): + cli("configure-goal", "--goal-id", goal, "--execution-stride-strategy", "evidence_conditioned_v1", + "--execution-replan-after-turns", str(count), "--execute") + + def guard(turn, task=None): + return cli("quota", "should-run", *identity, "--codex-app", "--turn-instance-id", turn, + *(("--todo-id", task) if task else ())) + + def spend(turn, task): + cli("quota", "spend-slot", *identity, "--todo-id", task, "--turn-instance-id", turn, + "--slots", "1", "--source", "heartbeat", "--execute") + + def work(turn, task, times, *, meta_decision=None, expect_gap=False): + packet = guard(turn, task) + assert packet["should_run"] and packet["selected_todo"]["todo_id"] == task + work_context = packet["interaction_contract"]["agent_channel"].get("work_context", {}) + if meta_decision is None: + assert "stride_meta_goal" not in work_context + else: + assert work_context["stride_meta_goal"]["decision_ref"] == meta_decision + assert build_turn_envelope(packet)["work_context"]["stride_meta_goal"]["decision_ref"] == meta_decision + # Use an actual deterministic input/result pair and independently derive the verdict. + worst = max(times) + (project / f"{turn}.json").write_text(json.dumps({"samples": times, "worst_seconds": worst})) + assert (worst >= 30) == expect_gap + cli("refresh-state", *identity, "--todo-id", task, "--turn-instance-id", turn, + "--classification", "fixture_peak_measurement", "--delivery-batch-scale", "implementation", + "--delivery-outcome", "outcome_progress", + "--delivery-boundary", "in_flight_continuation", + "--progress-result-class", "unchanged" if expect_gap else "advanced", + "--progress-surface-id", turn, "--progress-probe-kind", "peak-measurement", + "--progress-evidence-id", f"measurement:{turn}", "--recommended-action", f"Worst sample was {worst} seconds.", + "--no-global-sync", "--suppress-external-sinks") + spend(turn, task) + + def review(turn, *, scope=todo): + guard(turn) + packet = guard(turn, scope) + return (packet["autonomous_replan_obligation"]["replan_context"], + deepcopy(packet["replan_action_packet"]["stride_control"]["minimal_example"])) + + def store(turn, packet, *, expected=0): + path = project / "stride-vision.json" + path.write_text(json.dumps(packet)) + return cli("refresh-state", *identity, "--todo-id", todo, "--turn-instance-id", turn, + "--classification", "fixture_stride_decision", "--delivery-batch-scale", "implementation", + "--delivery-outcome", "outcome_progress", "--agent-vision-json", str(path), + "--no-global-sync", "--suppress-external-sinks", expected=expected) + + def task_record(): + return cli("todo", "list", "--goal-id", goal, "--todo-id", todo)["todo"]["stride_meta_goal"] + + def proposal(context, stride): + return {**vision({"objective": "Preserve the original Todo acceptance."}, + context["evidence"][0]["evidence_ref"]), "stride_decision": stride, "todo_delta": [f"retain:{todo}"]} + + cadence(1) + other = cli("todo", "add", "--goal-id", goal, "--role", "agent", "--claimed-by", agent, + "--text", "Measure a different work item.", "--task-class", "advancement_task", + "--action-kind", "validate", "--target-key", "independent-peak-observation")["todo_id"] + work("peak-baseline", todo, [16, 19]) + context, stride = review("review-initial-question") + meta = {"todo_id": todo, "objective": "Does the candidate still meet the peak time limit?", + "resolution_criterion": "Compare the worst measured sample with the 30 second limit.", "evidence_refs": []} + stride["meta_goal"] = meta + stride["next_probe"]["scope"] = "Compare the incumbent and candidate on the same representative peak samples." + packet = proposal(context, stride) + wrong_todo = deepcopy(packet) + wrong_todo["stride_decision"]["meta_goal"]["todo_id"] = other + wrong_todo["todo_delta"] = [f"retain:{other}"] + before = journal.read_bytes() + assert "open Agent Todo" in store("review-initial-question", wrong_todo, expected=1)["error"] + assert journal.read_bytes() == before + store("review-initial-question", packet) + initial = task_record() + assert initial["meta_goal"] == meta and initial["action"] == "verify" + spend("review-initial-question", todo) + + cadence(3) + work("peak-representative", todo, [17, 25], meta_decision=initial["decision_ref"]) + work("peak-unrelated", other, [6, 8]) + work("peak-tail", todo, [22, 32], meta_decision=initial["decision_ref"], expect_gap=True) + context, stride = review("review-peak-result") + [basis] = context["todo_meta_goals"] + assert basis["decision_ref"] == initial["decision_ref"] + assert len(basis["evidence"]) == 2 + tail = next(row for row in basis["evidence"] if row["result_class"] == "unchanged") + foreign = next(row for row in context["decision_followthrough"]["observations"] if row["todo_id"] == other) + stride.update(action="switch", meta_goal={**meta, "previous_decision_ref": initial["decision_ref"], + "resolution": "The tail exceeded the limit at 32 seconds. Compare a different mechanism next.", + "evidence_refs": [foreign["evidence_ref"]]}) + stride["next_probe"]["scope"] = "Test the streaming mechanism on the 32-second tail workload." + packet = proposal(context, stride) + before = journal.read_bytes() + assert "subsequent settled work on the same Todo" in store("review-peak-result", packet, expected=1)["error"] + assert journal.read_bytes() == before + stride["meta_goal"]["evidence_refs"] = [tail["evidence_ref"]] + accepted = store("review-peak-result", packet) + assert accepted["autonomous_replan_ack"]["semantic_delta"]["accepted"] + assert json.loads(Path(accepted["json_path"]).read_text())["agent_vision"]["stride_decision"]["meta_goal"] == stride["meta_goal"] + current = task_record() + assert current["action"] == "switch" and current["meta_goal"]["previous_decision_ref"] == initial["decision_ref"] + assert current["next_probe"]["scope"] == "Test the streaming mechanism on the 32-second tail workload." + assert current["evidence"][0]["evidence_ref"] == tail["evidence_ref"] + exact = cli("history", *identity, "--evidence-ref", tail["evidence_ref"])["evidence"] + assert exact["progress_observation"]["evidence_ids"] == ["measurement:peak-tail"] + prior = cli("history", *identity, "--evidence-ref", initial["decision_ref"])["evidence"] + assert prior["stride_decision"]["meta_goal"] == meta + spend("review-peak-result", todo) + later = guard("peak-after-resolution", todo) + assert later["selected_todo"]["todo_id"] == todo + assert "stride_meta_goal" not in later["interaction_contract"]["agent_channel"]["work_context"] + assert task_record() == current