diff --git a/benchmark/runtime/RUNTIME.md b/benchmark/runtime/RUNTIME.md index 86c265be1a..8f071d58c2 100644 --- a/benchmark/runtime/RUNTIME.md +++ b/benchmark/runtime/RUNTIME.md @@ -415,7 +415,10 @@ require separate run evidence. For an empty planning frontier, the model can save the same requirement declaration and ordered advancement Todos in one JSON proposal and invoke `python -m benchmark.runtime.planning_batch PROPOSAL.json` during the planning -wake. Use the checkpoint's exact input digest and acceptance provider revision. +wake (`--schema` prints the full JSON proposal schema and UTF-16 code unit field limits; +product CLI/HTTP callers reuse the same general `loopx.control_plane.goals.planning_batch` +owner via `loopx todo plan-batch` and `/api/chat/goal-acceptance` `plan-batch`). Use the +checkpoint's exact input digest and acceptance provider revision. The command declares requirements, writes Todos and binds their actual IDs through public LoopX operations. Each write has its own receipt. If the command is interrupted, reuse the unchanged proposal so the original effects can be diff --git a/benchmark/runtime/planning.py b/benchmark/runtime/planning.py index 4351bdf942..c824408cab 100644 --- a/benchmark/runtime/planning.py +++ b/benchmark/runtime/planning.py @@ -7,6 +7,10 @@ import subprocess from pathlib import Path +from loopx.control_plane.goals.task_planning import ( + validate_task_plan_readback as validate_plan_readback, +) + def render_planning_prompt(packet: dict, env: dict[str, str]) -> str: """Deliver the Core packet and explicitly selected observation tool context. @@ -70,45 +74,8 @@ def task_plan_packet(env: dict[str, str], cli: list[str]) -> dict: return packet -def validate_plan_readback(result: dict, before: dict, after: dict) -> dict: - if ( - result.get("input_digest") != before["input_digest"] - or after["input_digest"] != before["input_digest"] - ): - raise ValueError("planning input changed before readback") - status = result.get("status") - ids = result.get("todo_ids") - if ( - status not in {"ready", "blocked"} - or not isinstance(ids, list) - or not ids - or any(not isinstance(item, str) for item in ids) - or len(set(ids)) != len(ids) - ): - raise ValueError( - "planning result requires unique actual Todo ids and a typed status" - ) - todos = {item["todo_id"]: item for item in after["existing_todos"]} - if any(todo_id not in todos for todo_id in ids): - raise ValueError("planning referenced a missing or unrelated Todo") - if status == "ready" and not set(ids).issubset(after["runnable_todo_ids"]): - raise ValueError("planning referenced non-runnable or unclaimed work") - if status == "blocked" and not set(ids).issubset(after["blocking_todo_ids"]): - raise ValueError("blocked planning result requires unresolved blocking Todos") - requirements = after.get("goal_acceptance", {}).get("planning_requirements", {}) - if status == "ready" and ( - requirements.get("agent_id") != after["agent_id"] - or requirements.get("declaration_current") is not True - or not set(ids).issubset(requirements.get("linked_todo_ids", [])) - ): - raise ValueError("ready planning requires canonical overall requirements linked to its Todos") - return { - "input_digest": before["input_digest"], - "status": status, - "todo_ids": ids, - "goal_id": after["goal_id"], - "agent_id": after["agent_id"], - "state_readback_verified": True, - **({"goal_requirements_readback": requirements} if status == "ready" else {}), - "execution_owner": "caller", - } +__all__ = [ + "render_planning_prompt", + "task_plan_packet", + "validate_plan_readback", +] diff --git a/benchmark/runtime/planning_batch.py b/benchmark/runtime/planning_batch.py index 7b4a2fb200..69a8fac00e 100644 --- a/benchmark/runtime/planning_batch.py +++ b/benchmark/runtime/planning_batch.py @@ -1,201 +1,143 @@ -"""Apply one initial planning proposal through the existing LoopX owners.""" +"""Benchmark planning-batch CLI reusing LoopX's general planning-batch owner.""" from __future__ import annotations -import hashlib +import argparse import json import os from pathlib import Path import shlex import subprocess import sys -import tempfile +from typing import cast + +from loopx.control_plane.goals.planning_batch import ( + OBJECTIVE_MAX_CHARS, + OPAQUE_ID_MAX_CHARS, + OPAQUE_ID_PATTERN, + PlanningBatchCommandError, + REQUIREMENTS_MAX_ITEMS, + REQUIREMENT_DESCRIPTION_MAX_CHARS, + SOURCE_SUMMARY_MAX_CHARS, + TODOS_MAX_ITEMS, + CliPlanningBatchBackend, + apply_planning_batch, + planning_batch_schema as core_planning_batch_schema, + render_planning_batch_guidance, + validate_planning_batch_proposal, +) +from loopx.control_plane.todos.contract import TODO_ACTION_KIND_PATTERN from .planning import task_plan_packet - -def planning_batch_guidance() -> str: - command = shlex.join([sys.executable, "-m", "benchmark.runtime.planning_batch"]) - return ( - "Initial plan batch (optional for an empty work and requirements frontier). " - "After following the planner, save a JSON proposal alongside " - "LOOPX_PLANNING_RESULT with input_digest from " - "the checkpoint and expected_provider_revision from " - "goal_acceptance.provider_revision. Set outcome to the " - "declaration's objective, requirements and source. Set todos to the " - "ordered list of objects with text, action_kind and optional target_key. " - f"Run {command} and return the successful planning result. Keep the unchanged " - "proposal on interruption and rerun the same command. For existing work, " - "requirement revisions or blockers, follow the ordinary planning steps.\n\n" - ) - - -def _record(value, required: set[str], optional: set[str] | frozenset[str] = frozenset()) -> dict: - if not isinstance(value, dict) or not required <= value.keys() <= required | optional: - raise ValueError("Planning proposal has missing or unsupported fields") - return value - - -def _text(value) -> str: - if not isinstance(value, str) or not value.strip() or "\0" in value: - raise ValueError("Planning proposal requires non-empty text") - return value.strip() - - -def _request(proposal: dict) -> dict: - _record(proposal, {"input_digest", "expected_provider_revision", "outcome", "todos"}) - outcome = _record(proposal["outcome"], {"objective", "requirements", "source"}) - source = _record(outcome["source"], {"ref", "summary"}) - requirements, todos = outcome["requirements"], proposal["todos"] - if not all(isinstance(items, list) and items for items in (requirements, todos)): - raise ValueError("Planning proposal needs at least one requirement and one Todo") - requirements = [ - {key: _text(value) for key, value in _record(item, {"id", "description"}).items()} - for item in requirements - ] - todos = [ - {key: _text(value) for key, value in _record(todo, {"text", "action_kind"}, {"target_key"}).items()} - for todo in todos - ] - if len({item["id"] for item in requirements}) != len(requirements): - raise ValueError("Planning requirement IDs must be unique") - if len({todo["text"] for todo in todos}) != len(todos): - raise ValueError("Planning Todos must be distinct") - return { - "input_digest": _text(proposal["input_digest"]), - "expected_provider_revision": _text(proposal["expected_provider_revision"]), - "outcome": { - "objective": _text(outcome["objective"]), - "requirements": requirements, - "source": {key: _text(value) for key, value in source.items()}, - }, - "todos": todos, - } +__all__ = [ + "PlanningBatchCommandError", + "apply_initial_plan", + "main", + "planning_batch_guidance", + "planning_batch_schema", +] -def _outcomes(acceptance: dict) -> list[dict]: - return acceptance["goal_acceptance_contract"].get("outcome_requirements", {}).get("outcomes", []) +def planning_batch_schema() -> dict[str, object]: + """Return the benchmark checkpoint proposal schema backed by the general LoopX owner.""" + return core_planning_batch_schema( + require_input_digest=True, + allow_product_identities=False, + ) -def _declared_outcome(acceptance: dict, declaration: dict) -> dict: - state = acceptance["goal_acceptance_contract"].get("outcome_requirements", {}) - if state.get("current_lifetime") is not True: - raise ValueError("Planning declaration belongs to a different Goal lifetime") - for row in _outcomes(acceptance): - if row["id"] == declaration["outcome_id"]: - requirements = {item["id"]: item["description"] for item in row["requirements"]} - expected = {item["id"]: item["description"] for item in declaration["requirements"]} - if (row["owner_agent_id"] == declaration["owner_agent_id"] - and row["objective"] == declaration["objective"] - and requirements == expected): - return row - break - raise ValueError("Planning declaration is missing or changed; inspect the current Goal") +def planning_batch_guidance() -> str: + command = shlex.join([sys.executable, "-m", "benchmark.runtime.planning_batch"]) + return render_planning_batch_guidance( + command, + save_location_hint="save a JSON proposal alongside LOOPX_PLANNING_RESULT", + require_input_digest=True, + ) -def apply_initial_plan(env: dict[str, str], proposal: dict) -> dict: +def apply_initial_plan(env: dict[str, str], proposal: dict[str, object]) -> dict[str, object]: if env.get("LOOPX_TASK_STAGE") != "plan": raise ValueError("Planning batch requires the runner's planning stage") - proposal = _request(proposal) + validated = validate_planning_batch_proposal( + proposal, + require_input_digest=True, + allow_product_identities=False, + ) from .worker import loopx_command cli = loopx_command(env) - packet = task_plan_packet(env, cli) - if proposal["input_digest"] != packet["input_digest"]: - raise ValueError("Planning input changed") - revision = proposal["expected_provider_revision"] - acceptance = packet["goal_acceptance"] - if packet["goal_waiting_on"] or packet["blocking_todo_ids"]: - raise ValueError("Use the ordinary planning path for a Goal wait or blocker") - - def digest(value) -> str: - return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() - - # Bind all Todo intent to the declaration receipt. Two different proposals - # for one input cannot replay the same declaration and mix their Todo writes. - operation = f"benchmark-plan:{packet['input_digest']}" - declaration = { - **proposal["outcome"], - "outcome_id": f"benchmark-plan-{digest(proposal)[:32]}", - "owner_agent_id": packet["agent_id"], + backend = CliPlanningBatchBackend( + cli=cli, + cwd=env["LOOPX_PROJECT"], + env=env, + packet_reader=lambda: task_plan_packet(env, cli), + project=env["LOOPX_PROJECT"], + ) + result = apply_planning_batch( + proposal=validated, + backend=backend, + execute=True, + require_input_digest=True, + allow_product_identities=False, + id_prefix="benchmark-plan", + ) + return { + "input_digest": str(result["input_digest"]), + "status": str(result["status"]), + "todo_ids": cast(list[str], result["todo_ids"]), } - if acceptance["provider_revision"] == revision: - if packet["existing_todos"] or _outcomes(acceptance): - raise ValueError("Use the ordinary planning path for existing work or requirements") - else: - _declared_outcome(acceptance, declaration) - - goal = ["--goal-id", packet["goal_id"]] - actor = ["--agent-id", packet["agent_id"]] - - def call(*args: str) -> dict: - process = subprocess.run( - [*cli, *args], cwd=env["LOOPX_PROJECT"], env=env, text=True, - capture_output=True, timeout=120, - ) - try: - result = json.loads(process.stdout) - except ValueError: - raise ValueError(f"LoopX {args[0]} {args[1]} returned no JSON receipt") from None - if not isinstance(result, dict): - raise ValueError(f"LoopX {args[0]} {args[1]} returned an invalid receipt") - if process.returncode or result.get("ok") is not True: - reason = result.get("error_code") or result.get("error") or "unknown" - raise ValueError(f"LoopX {args[0]} {args[1]} failed: {reason}") - return result - - with tempfile.TemporaryDirectory(prefix="loopx-planning-") as directory: - document = Path(directory) / "refinement.json" - - def refine(value: dict, expected: str, effect: str) -> None: - document.write_text(json.dumps(value, ensure_ascii=False), encoding="utf-8") - call("goal-acceptance", "refine", *goal, *actor, "--document", str(document), - "--expected-provider-revision", expected, "--operation-id", effect, "--execute") - - refine(declaration, revision, f"{operation}:declare") - ids = [] - for index, item in enumerate(proposal["todos"]): - written = call( - "todo", "add", *goal, "--project", env["LOOPX_PROJECT"], - "--role", "agent", "--claimed-by", packet["agent_id"], - "--task-class", "advancement_task", - *(f"--{key.replace('_', '-')}={value}" for key, value in item.items()), - "--operation-id", f"{operation}:todo:{index}", "--execute", - ) - todo_id = written.get("todo_id") - if not isinstance(todo_id, str) or not todo_id or todo_id in ids: - raise ValueError("Planning writer did not return distinct real Todo IDs") - ids.append(todo_id) - - # Resolve the binding revision and check actual runnable ownership. A - # historical add receipt can be valid even if its Todo changed later. - current_packet = task_plan_packet(env, cli) - if current_packet["input_digest"] != packet["input_digest"]: - raise ValueError("Planning input changed before binding") - if not set(ids).issubset(current_packet["runnable_todo_ids"]): - raise ValueError("Planning Todos are no longer runnable by this agent") - if current_packet["goal_waiting_on"] or current_packet["blocking_todo_ids"]: - raise ValueError("Planning encountered a new Goal wait or blocker") - current = current_packet["goal_acceptance"] - linked = _declared_outcome(current, declaration)["todo_ids"] - if linked and linked != ids: - raise ValueError("Planning work links changed; inspect the current Goal") - if not linked: - basis = current["provider_revision"] - refine({"outcome_id": declaration["outcome_id"], "todo_ids": ids}, - basis, f"{operation}:bind:{digest(basis)[:32]}") - return {"input_digest": packet["input_digest"], "status": "ready", "todo_ids": ids} - - -def main() -> int: - if len(sys.argv) != 2: - print("Usage: python -m benchmark.runtime.planning_batch PROPOSAL.json", file=sys.stderr) - return 2 + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m benchmark.runtime.planning_batch", + description="Submit an initial planning batch proposal (outcome declaration + ordered advancement Todos).", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=( + "Proposal JSON schema summary (text limits in UTF-16 code units; non-BMP emoji count as 2):\n" + " Required root fields: input_digest, expected_provider_revision, outcome, todos\n" + f" outcome.objective: non-empty string (max {OBJECTIVE_MAX_CHARS} UTF-16 code units)\n" + f" outcome.requirements: 1..{REQUIREMENTS_MAX_ITEMS} items of {{id, description}} " + f"(description max {REQUIREMENT_DESCRIPTION_MAX_CHARS} UTF-16 code units)\n" + f" outcome.source: {{ref, summary}} (summary max {SOURCE_SUMMARY_MAX_CHARS} UTF-16 code units)\n" + f" Opaque IDs (outcome.requirements[*].id, outcome.source.ref): 1..{OPAQUE_ID_MAX_CHARS} UTF-16 code units " + f"matching {OPAQUE_ID_PATTERN.pattern} (no '/' paths or spaces)\n" + f" todos: 1..{TODOS_MAX_ITEMS} items of {{text, action_kind, target_key?}}\n" + f" action_kind: lowercase ASCII token matching {TODO_ACTION_KIND_PATTERN.pattern}\n\n" + "Pass --schema to print the full machine-readable JSON schema and example." + ), + ) + parser.add_argument( + "proposal", + nargs="?", + type=Path, + help="Path to the planning proposal JSON file.", + ) + parser.add_argument( + "--schema", + action="store_true", + help="Print the complete JSON schema, field limits, and an example proposal, then exit 0.", + ) + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = _build_parser() + args = parser.parse_args(argv) + if args.schema: + print(json.dumps(planning_batch_schema(), indent=2)) + return 0 + if args.proposal is None: + parser.error("the following arguments are required: proposal (or pass --schema)") try: - proposal = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) + proposal = json.loads(args.proposal.read_text(encoding="utf-8")) result = apply_initial_plan(dict(os.environ), proposal) except (ValueError, KeyError, OSError, subprocess.TimeoutExpired) as exc: - print(json.dumps({"ok": False, "error": str(exc)})) + payload: dict[str, object] = {"ok": False, "error": str(exc)} + if isinstance(exc, PlanningBatchCommandError) and exc.payload: + payload.update(exc.payload) + print(json.dumps(payload)) return 1 print(json.dumps(result)) return 0 diff --git a/loopx/cli_commands/goal_acceptance.py b/loopx/cli_commands/goal_acceptance.py index 85ec3f46f2..4b0cafc325 100644 --- a/loopx/cli_commands/goal_acceptance.py +++ b/loopx/cli_commands/goal_acceptance.py @@ -48,6 +48,12 @@ def register_goal_acceptance_command(subparsers: Any, add_format: Any) -> None: owner input nor adoption; only an applied objective revision needs adoption. Authority, budgets, stops and existing gated actions remain binding. +Outcome declaration (refine): + --document schema: {"outcome_id":"", "owner_agent_id":"AGENT", "objective":"...", "requirements":[{"id":"", "description":"..."}], "source":{"ref":"", "summary":"..."}} + Optional refine fields: "todo_ids":["todo_..."], "review":[...], "review_patch":[...], "storage_format":"records". + Opaque IDs (outcome_id, requirements[*].id, source.ref): <=128 UTF-16 code units matching ^[A-Za-z0-9][A-Za-z0-9_.:@-]*$ (no '/' paths or spaces). + Limits (UTF-16 code units): objective <=1024, requirements <=32 items (description <=2000 each), source.summary <=512. + Long-horizon requirements (refine): Keep the same outcome_id. Add "storage_format":"records" to the document to preview/commit lossless record storage with the next authorized refinement. diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index b864c7aa81..d7903f2b28 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -29,6 +29,12 @@ FirstPartyHostGoalAdmission, capture_first_party_host_goal_ref, ) +from ..control_plane.goals.planning_batch import ( + DirectPlanningBatchBackend, + apply_planning_batch, + planning_batch_schema, + render_planning_batch_markdown, +) from ..control_plane.goals.source_session_registry_state import exact_goal_ref from ..control_plane.goals.task_planning import ( build_task_planning_packet, @@ -58,6 +64,7 @@ validate_todo_claim_options, validate_todo_complete_options, validate_todo_execution_recovery_options, + validate_todo_plan_batch_options, validate_todo_plan_options, validate_todo_project_markdown_options, validate_todo_receipt_options, @@ -178,6 +185,8 @@ def handle_todo_command( renderer = render_todo_markdown if args.todo_command == "plan": renderer = render_task_planning_packet + elif args.todo_command == "plan-batch": + renderer = render_planning_batch_markdown elif args.todo_command == "receipt": renderer = _render_todo_receipt elif args.todo_command == "result-read": @@ -218,6 +227,28 @@ def handle_todo_command( text=args.text, project=Path(args.project).expanduser() if args.project else None, ) + elif args.todo_command == "plan-batch": + import json + + validate_todo_plan_batch_options(args) + if getattr(args, "schema", False): + payload = {"ok": True, "dry_run": True, **planning_batch_schema()} + else: + proposal = json.loads(Path(args.document).expanduser().read_text(encoding="utf-8")) + payload = apply_planning_batch( + proposal=proposal, + backend=DirectPlanningBatchBackend( + registry_path=registry_path, + runtime_root_arg=runtime_root_arg, + goal_id=args.goal_id, + agent_id=args.agent_id, + project=Path(args.project).expanduser() if args.project else None, + text=args.text, + ), + execute=bool(args.execute) and not bool(args.dry_run), + require_input_digest=bool(args.text), + operation_id=args.operation_id, + ) elif args.todo_command == "receipt": validate_todo_receipt_options(args) runtime_root = resolve_runtime_root( diff --git a/loopx/cli_commands/todo_argument_validation.py b/loopx/cli_commands/todo_argument_validation.py index 286e18fdfd..3dac064456 100644 --- a/loopx/cli_commands/todo_argument_validation.py +++ b/loopx/cli_commands/todo_argument_validation.py @@ -89,6 +89,8 @@ ("--state-file", "state_file"), ("--execute", "execute"), ("--provider-revision", "provider_revision"), + ("--document", "document"), + ("--schema", "schema"), ) _TODO_UPDATE_MUTABLE_FIELDS = ( @@ -152,6 +154,7 @@ "receipt": frozenset({"operation_id"}), "result-read": frozenset({"todo_id"}), "plan": frozenset({"text", "agent_id", "project"}), + "plan-batch": frozenset({"agent_id", "project", "text", "document", "operation_id", "execute", "dry_run", "schema"}), "project-markdown": frozenset({"state_file", "execute", "provider_revision", "project"}), "claim": frozenset({"role", "todo_id", "claimed_by", "agent_id", "state_file", "claim_operation_id", "ttl_seconds", "task_lease_idempotency_key", @@ -349,6 +352,24 @@ def validate_todo_plan_options(args: argparse.Namespace) -> None: raise ValueError("todo plan requires --text and a registered --agent-id") +def validate_todo_plan_batch_options(args: argparse.Namespace) -> None: + _validate_todo_option_subset( + args, + TODO_ACTION_FIELDS["plan-batch"], + "todo plan-batch only accepts --goal-id, --agent-id, --document, --text, --project, --operation-id, --dry-run, --execute, --schema and --format; unsupported: ", + ) + if getattr(args, "schema", False): + if any(getattr(args, field, None) for field in ("document", "text", "operation_id", "execute", "dry_run")): + raise ValueError("todo plan-batch --schema is read-only and cannot be combined with proposal execution flags") + return + if not getattr(args, "goal_id", None): + raise ValueError("todo plan-batch requires --goal-id (or pass --schema)") + if not args.agent_id or getattr(args, "document", None) is None: + raise ValueError("todo plan-batch requires --document and a registered --agent-id (or pass --schema)") + if args.dry_run and args.execute: + raise ValueError("todo plan-batch accepts either --dry-run or --execute, not both") + + def validate_todo_project_markdown_options(args: argparse.Namespace) -> None: if not getattr(args, "provider_revision", None): raise ValueError("todo project-markdown requires --provider-revision") @@ -661,8 +682,12 @@ def validate_todo_archive_completed_options(args: argparse.Namespace) -> None: def validate_shared_todo_options(args: argparse.Namespace) -> None: - if getattr(args, "operation_id", None) and args.todo_command not in {"receipt", "add"}: - raise ValueError("--operation-id is supported only by todo receipt and canonical todo add") + if getattr(args, "operation_id", None) and args.todo_command not in {"receipt", "add", "plan-batch"}: + raise ValueError("--operation-id is supported only by todo receipt, canonical todo add, and todo plan-batch") + if getattr(args, "document", None) is not None and args.todo_command != "plan-batch": + raise ValueError("--document is supported only by todo plan-batch") + if getattr(args, "schema", False) and args.todo_command != "plan-batch": + raise ValueError("--schema is supported only by todo plan-batch") if args.result_file and args.todo_command != "complete": raise ValueError("--result-file is supported only by todo complete") agent_id_allowed_for_user_authoring = ( @@ -740,7 +765,7 @@ def validate_shared_todo_options(args: argparse.Namespace) -> None: "--authority-reason is supported only by todo update/complete/supersede" ) if ( - args.todo_command != "plan" + args.todo_command not in {"plan", "plan-batch"} and args.agent_id and not agent_id_allowed_for_user_authoring and not agent_id_allowed_for_read diff --git a/loopx/cli_commands/todo_event.py b/loopx/cli_commands/todo_event.py index 43df125345..763a4ff68d 100644 --- a/loopx/cli_commands/todo_event.py +++ b/loopx/cli_commands/todo_event.py @@ -20,6 +20,7 @@ "complete": "todo_complete", "supersede": "todo_supersede", "archive-completed": "todo_archive_completed", + "plan-batch": "todo_plan_batch", } @@ -161,6 +162,11 @@ def todo_error_payload( payload["error_code"] = exc.code if exc.authoring_contract is not None: payload["authoring_contract"] = exc.authoring_contract + else: + from ..control_plane.goals.planning_batch import PlanningBatchCommandError + + if isinstance(exc, PlanningBatchCommandError) and exc.payload: + payload.update(exc.payload) _route_native_recovery(payload, args, registry_path=registry_path, runtime_root_arg=runtime_root_arg) return payload diff --git a/loopx/cli_commands/todo_registration.py b/loopx/cli_commands/todo_registration.py index 1b92fc0d48..acd81ab26a 100644 --- a/loopx/cli_commands/todo_registration.py +++ b/loopx/cli_commands/todo_registration.py @@ -2,6 +2,7 @@ import argparse from collections.abc import Callable +from pathlib import Path from ..control_plane.todos.contract import TODO_CONTINUATION_POLICY_VALUES from ..control_plane.todos.completed_archive import ARCHIVE_COMPLETED_DEFAULT_MAX_ACTIVE_DONE @@ -13,6 +14,26 @@ from .action_help import install_action_help +class _PlanBatchSchemaAction(argparse.Action): + """Allow `loopx todo plan-batch --schema` without requiring --goal-id.""" + + def __init__(self, option_strings: list[str], dest: str, **kwargs: object) -> None: + super().__init__(option_strings, dest, nargs=0, default=False, **kwargs) # type: ignore[arg-type] + + def __call__( + self, + parser: argparse.ArgumentParser, + namespace: argparse.Namespace, + values: object, + option_string: str | None = None, + ) -> None: + setattr(namespace, self.dest, True) + if getattr(namespace, "todo_command", None) == "plan-batch": + for action in parser._actions: + if action.dest == "goal_id": + action.required = False + + def register_todo_command( subparsers: argparse._SubParsersAction, add_subcommand_format: Callable[[argparse.ArgumentParser], None], @@ -41,6 +62,7 @@ def register_todo_command( "supersede", "archive-completed", "plan", + "plan-batch", "project-markdown", ], default=None, @@ -48,7 +70,8 @@ def register_todo_command( "Use add to append a checkbox todo, claim to prepare execution by registered " "agent id, list to read projected todos, update/complete/supersede to transition by todo_id, or " "archive-completed to move older completed todos into Completed Work Archive. " - "Use plan with --text and --agent-id for the existing Goal's model planning checkpoint; the caller owns subsequent execution." + "Use plan with --text and --agent-id for the existing Goal's model planning checkpoint, or " + "plan-batch with --document and --agent-id to preview/apply one initial outcome + Todo batch." ), ) todo_parser.add_argument("--goal-id", required=True, help="Goal id whose active state should receive the todo.") @@ -505,7 +528,7 @@ def register_todo_command( todo_parser.add_argument( "--execute", action="store_true", - help="For archive-completed or project-markdown, write the active-state edit.", + help="For archive-completed, project-markdown, or plan-batch, write the active-state edit.", ) todo_parser.add_argument( "--provider-revision", @@ -514,6 +537,16 @@ def register_todo_command( "into the Todo section markers." ), ) + todo_parser.add_argument( + "--document", + type=Path, + help="For todo plan-batch, path to the initial planning batch JSON proposal.", + ) + todo_parser.add_argument( + "--schema", + action=_PlanBatchSchemaAction, + help="For todo plan-batch, print the self-contained JSON proposal schema and example.", + ) install_action_help(todo_parser, command_dest="todo_command", action_fields=TODO_ACTION_FIELDS, common_fields=frozenset({"goal_id", "subcommand_format"})) diff --git a/loopx/control_plane/goals/acceptance_http.py b/loopx/control_plane/goals/acceptance_http.py index 081da2b389..7912927f18 100644 --- a/loopx/control_plane/goals/acceptance_http.py +++ b/loopx/control_plane/goals/acceptance_http.py @@ -61,12 +61,14 @@ def _goal_acceptance_update(self) -> None: public_goal_acceptance, verify_goal_acceptance, goal_acceptance_route, ) + from .planning_batch import DirectPlanningBatchBackend, apply_planning_batch try: body = self._read_json() if set(body) - { "goal_id", "action", + "agent_id", "document", "refinement", "expected_provider_revision", @@ -89,7 +91,46 @@ def _goal_acceptance_update(self) -> None: str(self.server.runtime_root)), "execute": True, } - if action in {"preview-handoff", "handoff"}: + if action in {"preview-plan-batch", "plan-batch"}: + allowed = {"goal_id", "action", "agent_id", "document", "expected_provider_revision", "operation_id"} + if set(body) - allowed or not {"goal_id", "action", "agent_id", "document", "expected_provider_revision"} <= set(body): + raise ValueError("plan-batch requires goal_id, agent_id, document and expected_provider_revision") + agent_id = body.get("agent_id") + document = body.get("document") + operation_id = body.get("operation_id") + if ( + not isinstance(agent_id, str) + or not agent_id.strip() + or not isinstance(document, dict) + or (operation_id is not None and (not isinstance(operation_id, str) or not operation_id.strip())) + ): + raise ValueError("plan-batch requires a registered agent_id and proposal document") + if "expected_provider_revision" in document and document["expected_provider_revision"] != revision: + raise ValueError("plan-batch expected_provider_revision mismatch") + proposal = {**document, "expected_provider_revision": revision} + route = goal_acceptance_route(self.server.registry_path, goal_id, str(self.server.runtime_root)) + batch = apply_planning_batch( + proposal=proposal, + backend=DirectPlanningBatchBackend( + registry_path=route["registry_path"], + runtime_root_arg=route["runtime_root"], + goal_id=goal_id, + agent_id=agent_id, + ), + execute=action == "plan-batch", + operation_id=operation_id, + ) + result = { + **public_goal_acceptance(batch), + "agent_id": batch["agent_id"], + "outcome_id": batch["outcome_id"], + **( + {"todo_ids": batch["todo_ids"], "state_readback_verified": batch["state_readback_verified"]} + if "todo_ids" in batch + else {"planned_todo_count": batch["planned_todo_count"]} + ), + } + elif action in {"preview-handoff", "handoff"}: if set(body) != {"goal_id", "action", "document", "expected_provider_revision", "operation_id"}: raise ValueError("unexpected handoff fields") if not isinstance(body["document"], dict) or not isinstance(body["operation_id"], str) or not body["operation_id"]: @@ -111,6 +152,8 @@ def _goal_acceptance_update(self) -> None: **common, expected_provider_revision=revision ) elif action in {"configure", "clear-checks"}: + if set(body) - {"goal_id", "action", "document", "expected_provider_revision", "operation_id"}: + raise ValueError("unexpected configure fields") document = body.get("document") if ( action == "configure" diff --git a/loopx/control_plane/goals/outcome_requirements.ts b/loopx/control_plane/goals/outcome_requirements.ts index de5d65b958..3eff8ece35 100644 --- a/loopx/control_plane/goals/outcome_requirements.ts +++ b/loopx/control_plane/goals/outcome_requirements.ts @@ -32,26 +32,58 @@ interface OutcomeState extends JsonObject { * Caller values and arbitrary provider/IO errors must never use this marker. */ export class GoalOutcomeValidationError extends AuthorityStoreProtocolError {} +const OPAQUE_ID_MAX = 128; +const OPAQUE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/; +const OPAQUE_ID_HINT = "ASCII letters/digits and . _ : @ -, no '/' paths or spaces"; + function requireValue(condition: unknown, reason: string): asserts condition { if (!condition) throw new GoalOutcomeValidationError(reason); } +function describeTextFailure(value: unknown, max: number): string { + if (typeof value !== "string") { + const kind = Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + return `expected string, got ${kind}; max ${max} UTF-16 code units`; + } + if (value.length === 0) return `must not be empty; max ${max} UTF-16 code units`; + if (value.includes("\0")) return `NUL characters are not allowed; max ${max} UTF-16 code units`; + if (value !== value.trim()) return `no leading/trailing whitespace; max ${max} UTF-16 code units`; + return `got ${value.length} UTF-16 code units, max ${max}`; +} function text(value: unknown, label: string, max = 512): string { - requireValue(typeof value === "string" && value === value.trim() && !!value && value.length <= max && !value.includes("\0"), `${label} must be bounded nonempty text`); + if (typeof value !== "string" || value !== value.trim() || !value || value.length > max || value.includes("\0")) { + throw new GoalOutcomeValidationError(`${label} must be bounded nonempty text (${describeTextFailure(value, max)})`); + } return value; } function id(value: unknown, label: string): string { - const result = text(value, label, 128); - requireValue( - /^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result), - `${label} must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`, - ); - return result; + if (typeof value !== "string" || value !== value.trim() || !value || value.length > OPAQUE_ID_MAX || value.includes("\0")) { + const textDetail = describeTextFailure(value, OPAQUE_ID_MAX); + const idNote = typeof value === "string" && value.length > OPAQUE_ID_MAX + ? `; must also be an opaque identifier (${OPAQUE_ID_HINT})` + : ""; + throw new GoalOutcomeValidationError(`${label} must be bounded nonempty text (${textDetail})${idNote}`); + } + requireValue(OPAQUE_ID_PATTERN.test(value), `${label} must be an opaque identifier (${OPAQUE_ID_HINT})`); + return value; } function keys(row: JsonObject, required: string[], optional: string[] = []): void { - requireValue(required.every(key => Object.hasOwn(row, key)) && Object.keys(row).every(key => [...required, ...optional].includes(key)), "outcome fields are missing or unsupported"); + const allowed = [...required, ...optional]; + const missing = required.filter(key => !Object.hasOwn(row, key)); + const unsupportedCount = Object.keys(row).filter(key => !allowed.includes(key)).length; + if (missing.length > 0 || unsupportedCount > 0) { + const details = [ + ...(missing.length > 0 ? [`missing: ${missing.join(", ")}`] : []), + ...(unsupportedCount > 0 ? [`unsupported field count: ${unsupportedCount}`] : []), + `allowed: ${allowed.join(", ")}`, + ]; + throw new GoalOutcomeValidationError(`outcome fields are missing or unsupported (${details.join("; ")})`); + } } function list(value: unknown, label: string, max: number): unknown[] { - requireValue(Array.isArray(value) && value.length <= max, `${label} exceeds its supported capacity`); + if (!Array.isArray(value)) { + throw new GoalOutcomeValidationError(`${label} must be an array (max ${max} items)`); + } + requireValue(value.length <= max, `${label} exceeds its supported capacity (got ${value.length} items, max ${max})`); return value; } function unique(values: string[], label: string): void {requireValue(new Set(values).size === values.length, `${label} contains duplicate ids`);} diff --git a/loopx/control_plane/goals/planning_batch.py b/loopx/control_plane/goals/planning_batch.py new file mode 100644 index 0000000000..3bc387548d --- /dev/null +++ b/loopx/control_plane/goals/planning_batch.py @@ -0,0 +1,881 @@ +"""General initial planning batch owner shared by LoopX CLI, HTTP, and benchmark.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +import hashlib +import json +from pathlib import Path +import re +import subprocess +import tempfile +from typing import Protocol, TypedDict, cast + +from ..todos.contract import ( + TODO_ACTION_KIND_PATTERN, + TODO_TASK_CLASS_ADVANCEMENT, + normalize_todo_action_kind, +) +from ..todos.mutation_api import add_goal_todo +from .acceptance import ( + GoalAcceptanceRejected, + public_goal_acceptance, + refine_goal_outcome, +) +from .task_planning import compute_task_planning_input_digest, inspect_goal_planning_frontier + +PLANNING_BATCH_SCHEMA_VERSION = "loopx_planning_batch_proposal_v1" +TODO_PRIORITY_VALUES = ("P0", "P1", "P2", "P3", "P4") + +OPAQUE_ID_MAX_CHARS = 128 +OPAQUE_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:@-]*$") +OPAQUE_ID_HINT = "ASCII letters/digits and . _ : @ -, no '/' paths or spaces" +OBJECTIVE_MAX_CHARS = 1024 +REQUIREMENT_DESCRIPTION_MAX_CHARS = 2000 +REQUIREMENTS_MAX_ITEMS = 32 +SOURCE_SUMMARY_MAX_CHARS = 512 +TODOS_MAX_ITEMS = 64 + + +def utf16_code_unit_len(value: str) -> int: + """Count UTF-16 code units so Python limits match TypeScript String.length.""" + return len(value.encode("utf-16-le")) // 2 + + +class PlanningBatchCommandError(ValueError): + """Preserve structured LoopX owner rejection details without echoing values.""" + + def __init__(self, message: str, payload: Mapping[str, object] | None = None) -> None: + super().__init__(message) + self.payload: dict[str, object] = dict(payload or {}) + + +class PlanningFrontierSnapshot(TypedDict): + goal_id: str + agent_id: str + input_digest: str | None + existing_todos: list[dict[str, object]] + runnable_todo_ids: list[str] + blocking_todo_ids: list[str] + goal_waiting_on: object + goal_acceptance: dict[str, object] + + +class PlanningBatchBackend(Protocol): + def inspect_state(self) -> PlanningFrontierSnapshot: ... + + def refine_outcome( + self, + value: dict[str, object], + expected_provider_revision: str, + operation_id: str, + *, + execute: bool, + ) -> dict[str, object]: ... + + def add_todo( + self, + item: dict[str, str], + operation_id: str, + *, + execute: bool, + ) -> dict[str, object]: ... + + +def planning_batch_schema( + *, + schema_version: str = PLANNING_BATCH_SCHEMA_VERSION, + require_input_digest: bool = False, + allow_product_identities: bool = True, +) -> dict[str, object]: + """Return the complete self-contained JSON proposal schema and field rules.""" + required_fields = ( + ["input_digest", "expected_provider_revision", "outcome", "todos"] + if require_input_digest + else ["expected_provider_revision", "outcome", "todos"] + ) + optional_root: list[str] = [] + if not require_input_digest: + optional_root.append("input_digest") + if allow_product_identities: + optional_root.extend(["outcome_id", "operation_id"]) + todo_optional = ["target_key", "priority"] if allow_product_identities else ["target_key"] + fields: dict[str, object] = { + "input_digest": { + "type": "string", + "optional": not require_input_digest, + "description": "Exact packet.input_digest when bound to a `loopx todo plan` checkpoint.", + }, + "expected_provider_revision": { + "type": "string", + "description": "Exact goal_acceptance.provider_revision from `goal-acceptance inspect` or `todo plan`.", + }, + "outcome": { + "type": "object", + "required_fields": ["objective", "requirements", "source"], + "properties": { + "objective": { + "type": "string", + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": OBJECTIVE_MAX_CHARS, + }, + "requirements": { + "type": "array", + "min_items": 1, + "max_items": REQUIREMENTS_MAX_ITEMS, + "items": { + "required_fields": ["id", "description"], + "id": { + "type": "string", + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": OPAQUE_ID_MAX_CHARS, + "pattern": OPAQUE_ID_PATTERN.pattern, + "unique": True, + }, + "description": { + "type": "string", + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": REQUIREMENT_DESCRIPTION_MAX_CHARS, + }, + }, + }, + "source": { + "type": "object", + "required_fields": ["ref", "summary"], + "ref": { + "type": "string", + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": OPAQUE_ID_MAX_CHARS, + "pattern": OPAQUE_ID_PATTERN.pattern, + "note": "Use an opaque identifier such as checkpoint:initial or task:readme; never file paths or spaces.", + }, + "summary": { + "type": "string", + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": SOURCE_SUMMARY_MAX_CHARS, + }, + }, + }, + }, + "todos": { + "type": "array", + "min_items": 1, + "max_items": TODOS_MAX_ITEMS, + "items": { + "required_fields": ["text", "action_kind"], + "optional_fields": todo_optional, + "text": {"type": "string", "min_utf16_code_units": 1, "unique": True}, + "action_kind": { + "type": "string", + "pattern": TODO_ACTION_KIND_PATTERN.pattern, + "examples": ["implement", "validate", "investigate", "submit"], + }, + "target_key": {"type": "string", "optional": True, "min_utf16_code_units": 1}, + **( + { + "priority": { + "type": "string", + "optional": True, + "enum": list(TODO_PRIORITY_VALUES), + } + } + if allow_product_identities + else {} + ), + }, + }, + } + if allow_product_identities: + fields["outcome_id"] = { + "type": "string", + "optional": True, + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": OPAQUE_ID_MAX_CHARS, + "pattern": OPAQUE_ID_PATTERN.pattern, + "description": "Optional stable outcome identifier; derived deterministically when omitted.", + } + fields["operation_id"] = { + "type": "string", + "optional": True, + "length_unit": "utf16_code_units", + "min_utf16_code_units": 1, + "max_utf16_code_units": OPAQUE_ID_MAX_CHARS, + "pattern": OPAQUE_ID_PATTERN.pattern, + "description": "Optional stable batch operation prefix for idempotent retries.", + } + example: dict[str, object] = { + **({"input_digest": ""} if require_input_digest else {}), + "expected_provider_revision": "", + "outcome": { + "objective": "Concise task objective (<=1024 UTF-16 code units).", + "requirements": [ + { + "id": "req-1", + "description": "Verifiable requirement description (<=2000 UTF-16 code units).", + }, + ], + "source": { + "ref": "checkpoint:initial", + "summary": "Host-supplied planning checkpoint (<=512 UTF-16 code units).", + }, + }, + "todos": [ + {"text": "[P0] First ordered work step", "action_kind": "implement"}, + {"text": "[P1] Verify and test result", "action_kind": "validate", "target_key": "verification"}, + ], + } + return { + "schema_version": schema_version, + "length_unit": "utf16_code_units", + "required_fields": required_fields, + **({"optional_fields": optional_root} if optional_root else {}), + "fields": fields, + "example": example, + } + + +def render_planning_batch_guidance( + command: str, + *, + schema_command: str | None = None, + proposal_arg_template: str = "", + save_location_hint: str = "save a JSON proposal", + require_input_digest: bool = False, +) -> str: + """Render concise, self-contained batch planning instructions for prompts/checkpoints.""" + effective_schema_cmd = schema_command or f"{command} --schema" + digest_clause = ( + '"input_digest": "", ' + if require_input_digest + else "" + ) + return ( + "Initial plan batch (optional for an empty work and requirements frontier). " + f"After following the planner, {save_location_hint} with exact keys: " + "{" + + digest_clause + + '"expected_provider_revision": "", ' + '"outcome": {"objective": "", ' + '"requirements": [{"id": "", "description": ""}], ' + '"source": {"ref": "", "summary": ""}}, ' + '"todos": [{"text": "", "action_kind": "", "target_key": ""}]}. ' + "Constraint: bounded string limits are measured in UTF-16 code units (non-BMP emoji count as 2); " + "outcome.source.ref and requirements[*].id must be opaque ASCII IDs " + f"(1..{OPAQUE_ID_MAX_CHARS} UTF-16 code units matching {OPAQUE_ID_PATTERN.pattern}, NO '/' paths or spaces, " + 'e.g. "checkpoint:initial"); todos[*].action_kind must match ^[a-z][a-z0-9_-]{0,63}$ ' + "(e.g. implement, validate, investigate, submit); inspect full schema with " + f"`{effective_schema_cmd}`. " + f"Run {command} {proposal_arg_template} and return the successful planning result JSON directly " + '(when it exits 0 with status="ready", do not make extra todo list or goal-acceptance calls). ' + "Keep the unchanged proposal on interruption and rerun the same command. For existing work, " + "requirement revisions or blockers, follow the ordinary planning steps.\n\n" + ) + + +def _record( + value: object, + required: set[str], + optional: set[str] | frozenset[str] = frozenset(), + *, + path: str = "proposal", +) -> dict[str, object]: + allowed = required | optional + if not isinstance(value, dict): + expected = ", ".join(sorted(allowed)) + raise ValueError(f"Planning proposal has invalid {path}: expected JSON object with fields ({expected})") + missing = sorted(required - value.keys()) + unsupported_count = len(value.keys() - allowed) + if missing or unsupported_count: + details = [] + if missing: + details.append(f"missing: {', '.join(missing)}") + if unsupported_count: + details.append(f"unsupported field count: {unsupported_count}") + details.append(f"allowed: {', '.join(sorted(allowed))}") + raise ValueError(f"Planning proposal has missing or unsupported fields at {path} ({'; '.join(details)})") + return cast(dict[str, object], value) + + +def _text(value: object, *, path: str = "field", max_chars: int | None = None) -> str: + if not isinstance(value, str) or "\0" in value: + raise ValueError(f"Planning proposal requires non-empty text at {path} (expected string without NUL)") + normalized = value.strip() + if not normalized: + raise ValueError(f"Planning proposal requires non-empty text at {path}") + if max_chars is not None: + units = utf16_code_unit_len(normalized) + if units > max_chars: + raise ValueError( + f"Planning proposal field {path} exceeds max length (got {units} UTF-16 code units, max {max_chars})" + ) + return normalized + + +def _opaque_id(value: object, *, path: str) -> str: + text = _text(value, path=path) + units = utf16_code_unit_len(text) + too_long = units > OPAQUE_ID_MAX_CHARS + invalid_chars = not OPAQUE_ID_PATTERN.match(text) + if too_long or invalid_chars: + reasons = [] + if too_long: + reasons.append(f"got {units} UTF-16 code units, max {OPAQUE_ID_MAX_CHARS}") + if invalid_chars: + reasons.append(f"must match {OPAQUE_ID_PATTERN.pattern} ({OPAQUE_ID_HINT})") + raise ValueError(f"Planning proposal field {path} must be an opaque identifier ({'; '.join(reasons)})") + return text + + +def _action_kind(value: object, *, path: str) -> str: + raw = _text(value, path=path) + if not normalize_todo_action_kind(raw): + raise ValueError( + f"Planning proposal field {path} must match {TODO_ACTION_KIND_PATTERN.pattern} " + "(lowercase ASCII token, e.g. implement, validate, investigate, submit)" + ) + # Preserve raw casing in the normalized proposal dict so deterministic + # outcome/operation digests stay identical across upgrades when Todo owners + # normalize action_kind on commit. + return raw + + +def _priority(value: object, *, path: str) -> str: + raw = _text(value, path=path).upper() + if raw not in TODO_PRIORITY_VALUES: + raise ValueError( + f"Planning proposal field {path} must be one of {', '.join(TODO_PRIORITY_VALUES)}" + ) + return raw + + +def validate_planning_batch_proposal( + proposal: object, + *, + require_input_digest: bool = False, + allow_product_identities: bool = True, +) -> dict[str, object]: + """Validate proposal structure, UTF-16 lengths, and opaque IDs before state IO.""" + required_root = {"expected_provider_revision", "outcome", "todos"} + optional_root: set[str] = set() + if require_input_digest: + required_root.add("input_digest") + else: + optional_root.add("input_digest") + if allow_product_identities: + optional_root.update({"outcome_id", "operation_id"}) + root = _record(proposal, required_root, optional_root, path="proposal") + outcome = _record(root["outcome"], {"objective", "requirements", "source"}, path="outcome") + source = _record(outcome["source"], {"ref", "summary"}, path="outcome.source") + raw_requirements, raw_todos = outcome["requirements"], root["todos"] + if not isinstance(raw_requirements, list) or not raw_requirements: + raise ValueError("Planning proposal needs at least one requirement in outcome.requirements") + if len(raw_requirements) > REQUIREMENTS_MAX_ITEMS: + raise ValueError( + f"Planning proposal outcome.requirements exceeds capacity (got {len(raw_requirements)} items, max {REQUIREMENTS_MAX_ITEMS})" + ) + if not isinstance(raw_todos, list) or not raw_todos: + raise ValueError("Planning proposal needs at least one Todo in todos") + if len(raw_todos) > TODOS_MAX_ITEMS: + raise ValueError( + f"Planning proposal todos exceeds capacity (got {len(raw_todos)} items, max {TODOS_MAX_ITEMS})" + ) + requirements: list[dict[str, str]] = [] + for index, item in enumerate(raw_requirements): + row = _record(item, {"id", "description"}, path=f"outcome.requirements[{index}]") + requirements.append({ + "id": _opaque_id(row["id"], path=f"outcome.requirements[{index}].id"), + "description": _text( + row["description"], + path=f"outcome.requirements[{index}].description", + max_chars=REQUIREMENT_DESCRIPTION_MAX_CHARS, + ), + }) + todo_optional = {"target_key", "priority"} if allow_product_identities else {"target_key"} + todos: list[dict[str, str]] = [] + for index, todo in enumerate(raw_todos): + row = _record(todo, {"text", "action_kind"}, todo_optional, path=f"todos[{index}]") + todo_item: dict[str, str] = { + "text": _text(row["text"], path=f"todos[{index}].text"), + "action_kind": _action_kind(row["action_kind"], path=f"todos[{index}].action_kind"), + } + if "target_key" in row: + todo_item["target_key"] = _text(row["target_key"], path=f"todos[{index}].target_key") + if "priority" in row: + todo_item["priority"] = _priority(row["priority"], path=f"todos[{index}].priority") + todos.append(todo_item) + if len({item["id"] for item in requirements}) != len(requirements): + raise ValueError("Planning requirement IDs in outcome.requirements must be unique") + if len({todo["text"] for todo in todos}) != len(todos): + raise ValueError("Planning Todos in todos must have distinct text") + normalized: dict[str, object] = { + "expected_provider_revision": _text( + root["expected_provider_revision"], path="expected_provider_revision" + ), + "outcome": { + "objective": _text(outcome["objective"], path="outcome.objective", max_chars=OBJECTIVE_MAX_CHARS), + "requirements": requirements, + "source": { + "ref": _opaque_id(source["ref"], path="outcome.source.ref"), + "summary": _text( + source["summary"], path="outcome.source.summary", max_chars=SOURCE_SUMMARY_MAX_CHARS + ), + }, + }, + "todos": todos, + } + if "input_digest" in root: + normalized["input_digest"] = _text(root["input_digest"], path="input_digest") + if "outcome_id" in root: + normalized["outcome_id"] = _opaque_id(root["outcome_id"], path="outcome_id") + if "operation_id" in root: + normalized["operation_id"] = _opaque_id(root["operation_id"], path="operation_id") + return normalized + + +def _digest(value: object) -> str: + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _outcomes(acceptance: Mapping[str, object]) -> list[dict[str, object]]: + contract = acceptance.get("goal_acceptance_contract") + if not isinstance(contract, Mapping): + return [] + req_block = contract.get("outcome_requirements") + if not isinstance(req_block, Mapping): + return [] + outcomes = req_block.get("outcomes") + return [cast(dict[str, object], row) for row in outcomes] if isinstance(outcomes, list) else [] + + +def _declared_outcome(acceptance: Mapping[str, object], declaration: Mapping[str, object]) -> dict[str, object]: + contract = acceptance.get("goal_acceptance_contract") + state = contract.get("outcome_requirements") if isinstance(contract, Mapping) else None + if not isinstance(state, Mapping) or state.get("current_lifetime") is not True: + raise ValueError("Planning declaration belongs to a different Goal lifetime") + expected_reqs = { + str(item["id"]): str(item["description"]) + for item in cast(list[dict[str, str]], declaration["requirements"]) + } + for row in _outcomes(acceptance): + if row.get("id") == declaration["outcome_id"]: + raw_reqs = row.get("requirements") + requirements = ( + {str(item["id"]): str(item["description"]) for item in raw_reqs if isinstance(item, Mapping)} + if isinstance(raw_reqs, list) + else {} + ) + if ( + row.get("owner_agent_id") == declaration["owner_agent_id"] + and row.get("objective") == declaration["objective"] + and requirements == expected_reqs + ): + return row + break + raise ValueError("Planning declaration is missing or changed; inspect the current Goal") + + +class DirectPlanningBatchBackend: + """In-process product backend backed directly by canonical Goal and Todo owners.""" + + def __init__( + self, + *, + registry_path: Path, + runtime_root_arg: str | None, + goal_id: str, + agent_id: str, + project: Path | None = None, + text: str | None = None, + ) -> None: + self.registry_path = registry_path + self.runtime_root_arg = runtime_root_arg + self.goal_id = goal_id.strip() + self.agent_id = agent_id.strip() + self.project = project + self.text = text + + def inspect_state(self) -> PlanningFrontierSnapshot: + frontier = inspect_goal_planning_frontier( + registry_path=self.registry_path, + runtime_root_arg=self.runtime_root_arg, + goal_id=self.goal_id, + agent_id=self.agent_id, + project=self.project, + ) + canonical_agent_id = str(frontier["agent_id"]) + self.agent_id = canonical_agent_id + input_digest: str | None = None + if self.text is not None: + if not self.text.strip(): + raise ValueError("todo plan-batch requires non-empty --text when supplied") + input_digest = compute_task_planning_input_digest( + goal_id=self.goal_id, + agent_id=canonical_agent_id, + text=self.text, + ) + return { + "goal_id": self.goal_id, + "agent_id": canonical_agent_id, + "input_digest": input_digest, + "existing_todos": cast(list[dict[str, object]], frontier["existing_todos"]), + "runnable_todo_ids": cast(list[str], frontier["runnable_todo_ids"]), + "blocking_todo_ids": cast(list[str], frontier["blocking_todo_ids"]), + "goal_waiting_on": frontier["goal_waiting_on"], + "goal_acceptance": cast(dict[str, object], frontier["goal_acceptance"]), + } + + def refine_outcome( + self, + value: dict[str, object], + expected_provider_revision: str, + operation_id: str, + *, + execute: bool, + ) -> dict[str, object]: + try: + raw = refine_goal_outcome( + registry_path=self.registry_path, + runtime_root=self.runtime_root_arg, + goal_id=self.goal_id, + agent_id=self.agent_id, + refinement=dict(value), + expected_provider_revision=expected_provider_revision, + operation_id=operation_id, + execute=execute, + ) + return public_goal_acceptance(raw) + except GoalAcceptanceRejected as exc: + detail = exc.payload.get("error_detail") + message = f"LoopX goal-acceptance refine failed: {exc.code}" + if isinstance(detail, str) and detail: + message = f"{message}: {detail}" + raise PlanningBatchCommandError( + message, + {"stage": "goal-acceptance refine", "error_code": exc.code, **exc.payload}, + ) from None + except ValueError as exc: + code = str(exc) + raise PlanningBatchCommandError( + f"LoopX goal-acceptance refine failed: {code}", + {"stage": "goal-acceptance refine", "error_code": code}, + ) from None + + def add_todo( + self, + item: dict[str, str], + operation_id: str, + *, + execute: bool, + ) -> dict[str, object]: + monitor_meta = {"target_key": item["target_key"]} if "target_key" in item else None + result = add_goal_todo( + registry_path=self.registry_path, + runtime_root_arg=self.runtime_root_arg, + goal_id=self.goal_id, + role="agent", + claimed_by=self.agent_id, + agent_id=None, + task_class=TODO_TASK_CLASS_ADVANCEMENT, + text=item["text"], + action_kind=item["action_kind"], + priority=item.get("priority"), + monitor_metadata=monitor_meta, + project=self.project, + dry_run=not execute, + operation_id=operation_id, + ) + if result.get("ok") is not True: + reason = str(result.get("error_code") or result.get("error") or "unknown") + raise PlanningBatchCommandError( + f"LoopX todo add failed: {reason}", + {"stage": "todo add", "error_code": reason}, + ) + return result + + +class CliPlanningBatchBackend: + """Routed subprocess CLI backend for callers executing through an external LOOPX_CLI.""" + + def __init__( + self, + *, + cli: list[str], + cwd: str | Path, + env: Mapping[str, str], + packet_reader: Callable[[], dict[str, object]], + project: str, + ) -> None: + self.cli = list(cli) + self.cwd = str(cwd) + self.env = dict(env) + self.packet_reader = packet_reader + self.project = project + self._goal_id = "" + self._agent_id = "" + + def inspect_state(self) -> PlanningFrontierSnapshot: + packet = self.packet_reader() + self._goal_id = str(packet["goal_id"]) + self._agent_id = str(packet["agent_id"]) + raw_digest = packet.get("input_digest") + return { + "goal_id": self._goal_id, + "agent_id": self._agent_id, + "input_digest": str(raw_digest) if isinstance(raw_digest, str) else None, + "existing_todos": cast(list[dict[str, object]], packet.get("existing_todos") or []), + "runnable_todo_ids": cast(list[str], packet.get("runnable_todo_ids") or []), + "blocking_todo_ids": cast(list[str], packet.get("blocking_todo_ids") or []), + "goal_waiting_on": packet.get("goal_waiting_on"), + "goal_acceptance": cast(dict[str, object], packet["goal_acceptance"]), + } + + def _call(self, *args: str) -> dict[str, object]: + process = subprocess.run( + [*self.cli, *args], + cwd=self.cwd, + env=self.env, + text=True, + capture_output=True, + timeout=120, + ) + try: + result = json.loads(process.stdout) + except ValueError: + raise ValueError(f"LoopX {args[0]} {args[1]} returned no JSON receipt") from None + if not isinstance(result, dict): + raise ValueError(f"LoopX {args[0]} {args[1]} returned an invalid receipt") + if process.returncode or result.get("ok") is not True: + reason = str(result.get("error_code") or result.get("error") or "unknown") + detail = result.get("error_detail") + message = f"LoopX {args[0]} {args[1]} failed: {reason}" + if isinstance(detail, str) and detail: + message = f"{message}: {detail}" + extra: dict[str, object] = {"stage": f"{args[0]} {args[1]}"} + for key in ("error_code", "error_detail", "current_provider_revision"): + val = result.get(key) + if isinstance(val, str) and val: + extra[key] = val + upstream = result.get("error") + if isinstance(upstream, str) and upstream and upstream != reason: + extra["upstream_error"] = upstream + raise PlanningBatchCommandError(message, extra) + return cast(dict[str, object], result) + + def refine_outcome( + self, + value: dict[str, object], + expected_provider_revision: str, + operation_id: str, + *, + execute: bool, + ) -> dict[str, object]: + with tempfile.TemporaryDirectory(prefix="loopx-planning-") as directory: + document = Path(directory) / "refinement.json" + document.write_text(json.dumps(value, ensure_ascii=False), encoding="utf-8") + argv = [ + "goal-acceptance", + "refine", + "--goal-id", + self._goal_id, + "--agent-id", + self._agent_id, + "--document", + str(document), + "--expected-provider-revision", + expected_provider_revision, + "--operation-id", + operation_id, + ] + if execute: + argv.append("--execute") + return self._call(*argv) + + def add_todo( + self, + item: dict[str, str], + operation_id: str, + *, + execute: bool, + ) -> dict[str, object]: + argv = [ + "todo", + "add", + "--goal-id", + self._goal_id, + "--project", + self.project, + "--role", + "agent", + "--claimed-by", + self._agent_id, + "--task-class", + TODO_TASK_CLASS_ADVANCEMENT, + *(f"--{key.replace('_', '-')}={val}" for key, val in item.items()), + "--operation-id", + operation_id, + ] + argv.append("--execute" if execute else "--dry-run") + return self._call(*argv) + + +def apply_planning_batch( + *, + proposal: Mapping[str, object] | object, + backend: PlanningBatchBackend, + execute: bool = True, + require_input_digest: bool = False, + allow_product_identities: bool = True, + id_prefix: str = "plan", + operation_id: str | None = None, +) -> dict[str, object]: + """Validate, preview or commit an initial outcome + Todo planning batch.""" + validated = validate_planning_batch_proposal( + proposal, + require_input_digest=require_input_digest, + allow_product_identities=allow_product_identities, + ) + snapshot = backend.inspect_state() + expected_digest = snapshot.get("input_digest") + proposal_digest_field = validated.get("input_digest") + if expected_digest is not None: + if proposal_digest_field is not None and proposal_digest_field != expected_digest: + raise ValueError("Planning input changed") + if require_input_digest and proposal_digest_field != expected_digest: + raise ValueError("Planning input changed") + elif isinstance(proposal_digest_field, str) and require_input_digest: + raise ValueError("Planning input changed") + + revision = str(validated["expected_provider_revision"]) + acceptance = snapshot["goal_acceptance"] + if snapshot["goal_waiting_on"] or snapshot["blocking_todo_ids"]: + raise ValueError("Use the ordinary planning path for a Goal wait or blocker") + + explicit_op = _opaque_id(operation_id, path="operation_id") if operation_id is not None else None + proposal_hash = _digest(validated) + outcome_id = str( + validated.get("outcome_id") or f"{id_prefix}-{proposal_hash[:32]}" + ) + effective_operation = str( + explicit_op + or validated.get("operation_id") + or (f"{id_prefix}:{expected_digest}" if expected_digest else f"{id_prefix}:{proposal_hash[:32]}") + ) + outcome_body = cast(dict[str, object], validated["outcome"]) + declaration: dict[str, object] = { + **outcome_body, + "outcome_id": outcome_id, + "owner_agent_id": snapshot["agent_id"], + } + current_rev = str(acceptance["provider_revision"]) + if current_rev == revision: + if snapshot["existing_todos"] or _outcomes(acceptance): + raise ValueError("Use the ordinary planning path for existing work or requirements") + else: + _declared_outcome(acceptance, declaration) + + todos = cast(list[dict[str, str]], validated["todos"]) + if not execute: + preview_acceptance = acceptance + if current_rev == revision: + preview_acceptance = backend.refine_outcome( + declaration, revision, f"{effective_operation}:declare", execute=False + ) + for index, item in enumerate(todos): + backend.add_todo(item, f"{effective_operation}:todo:{index}", execute=False) + return { + "ok": True, + "command": "plan-batch", + "status": "planned", + "dry_run": True, + "changed": False, + "goal_id": snapshot["goal_id"], + "agent_id": snapshot["agent_id"], + "outcome_id": outcome_id, + "operation_id": effective_operation, + "provider_revision": current_rev, + "planned_todo_count": len(todos), + "goal_acceptance_contract": preview_acceptance.get("goal_acceptance_contract"), + **({"input_digest": expected_digest} if expected_digest is not None else {}), + } + + backend.refine_outcome(declaration, revision, f"{effective_operation}:declare", execute=True) + ids: list[str] = [] + for index, item in enumerate(todos): + written = backend.add_todo(item, f"{effective_operation}:todo:{index}", execute=True) + todo_id = written.get("todo_id") + if not isinstance(todo_id, str) or not todo_id or todo_id in ids: + raise ValueError("Planning writer did not return distinct real Todo IDs") + ids.append(todo_id) + + current_snapshot = backend.inspect_state() + if expected_digest is not None and current_snapshot.get("input_digest") != expected_digest: + raise ValueError("Planning input changed before binding") + if not set(ids).issubset(current_snapshot["runnable_todo_ids"]): + raise ValueError("Planning Todos are no longer runnable by this agent") + if current_snapshot["goal_waiting_on"] or current_snapshot["blocking_todo_ids"]: + raise ValueError("Planning encountered a new Goal wait or blocker") + current_acceptance = current_snapshot["goal_acceptance"] + declared_row = _declared_outcome(current_acceptance, declaration) + linked = declared_row.get("todo_ids") + linked_ids = [str(x) for x in linked] if isinstance(linked, list) else [] + final_acceptance = current_acceptance + if linked_ids and linked_ids != ids: + raise ValueError("Planning work links changed; inspect the current Goal") + if not linked_ids: + basis = str(current_acceptance["provider_revision"]) + final_acceptance = backend.refine_outcome( + {"outcome_id": outcome_id, "todo_ids": ids}, + basis, + f"{effective_operation}:bind:{_digest(basis)[:32]}", + execute=True, + ) + + final_rev = str(final_acceptance.get("provider_revision") or current_acceptance["provider_revision"]) + return { + "ok": True, + "command": "plan-batch", + "status": "ready", + "dry_run": False, + "changed": current_rev == revision or not linked_ids, + "idempotent_replay": current_rev != revision and bool(linked_ids), + "goal_id": snapshot["goal_id"], + "agent_id": snapshot["agent_id"], + "outcome_id": outcome_id, + "operation_id": effective_operation, + "todo_ids": ids, + "provider_revision": final_rev, + "state_readback_verified": True, + "execution_owner": "caller", + "goal_acceptance_contract": final_acceptance.get("goal_acceptance_contract"), + **({"input_digest": expected_digest} if expected_digest is not None else {}), + } + + +def render_planning_batch_markdown(payload: Mapping[str, object]) -> str: + if payload.get("schema_version") == PLANNING_BATCH_SCHEMA_VERSION: + return json.dumps(payload, ensure_ascii=False, indent=2) + lines = ["# Todo plan-batch", "", f"- ok: {payload.get('ok')}"] + if payload.get("error"): + lines.append(f"- error: {payload['error']}") + if payload.get("error_detail"): + lines.append(f"- detail: {payload['error_detail']}") + return "\n".join(lines) + lines.extend([ + f"- status: {payload.get('status')}", + f"- goal_id: {payload.get('goal_id')}", + f"- agent_id: {payload.get('agent_id')}", + f"- outcome_id: {payload.get('outcome_id')}", + f"- provider_revision: {payload.get('provider_revision')}", + ]) + todo_ids = payload.get("todo_ids") + if isinstance(todo_ids, list) and todo_ids: + lines.append(f"- todo_ids: {', '.join(str(item) for item in todo_ids)}") + elif payload.get("planned_todo_count") is not None: + lines.append(f"- planned_todo_count: {payload['planned_todo_count']}") + return "\n".join(lines) diff --git a/loopx/control_plane/goals/start_goal_todo_delta.py b/loopx/control_plane/goals/start_goal_todo_delta.py index b45052e705..aff650aeaa 100644 --- a/loopx/control_plane/goals/start_goal_todo_delta.py +++ b/loopx/control_plane/goals/start_goal_todo_delta.py @@ -191,6 +191,7 @@ def todo_authoring_steps( "Repeat goal_requirements.inspect_command from the planning checkpoint after linking." ) if not existing_runnable_frontier: + batch_prefix = f"{prefix} --format json todo plan-batch" return [ { "id": "plan_ranked_todos", @@ -208,11 +209,16 @@ def todo_authoring_steps( "id": "write_ordered_todos", "kind": "operator_or_agent_actions", "command_template": add_template, + "batch_command_template": ( + f"{batch_prefix} {route} --project . " + "--document '' --execute" + ), + "batch_schema_command": f"{batch_prefix} --schema", "purpose": ( "write only the current checkpoint Todo; the existing replan path " "qualifies any successor after completion evidence" if fine_grained - else "write todos in planner order; capability successors preserve " + else "write todos in planner order (or submit one initial outcome + Todo batch via batch_command_template when requirements and Todos are both empty); capability successors preserve " "the admitted action_kind and target_key for later quota re-entry" ), }, diff --git a/loopx/control_plane/goals/task_planning.py b/loopx/control_plane/goals/task_planning.py index ccf9e86183..4a84bdcc75 100644 --- a/loopx/control_plane/goals/task_planning.py +++ b/loopx/control_plane/goals/task_planning.py @@ -39,18 +39,20 @@ } -def build_task_planning_packet( +def compute_task_planning_input_digest(*, goal_id: str, agent_id: str, text: str) -> str: + identity = {"goal_id": goal_id, "agent_id": agent_id, "text": text} + return hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + + +def inspect_goal_planning_frontier( *, registry_path: Path, goal_id: str, agent_id: str, - text: str, project: Path | None = None, runtime_root_arg: str | None = None, ) -> dict[str, Any]: - """Read canonical planning inputs; create no Goal, Todo, Turn or host loop.""" - if not text.strip(): - raise ValueError("todo plan requires non-empty --text") + """Read canonical Goal Todos, blockers, and acceptance basis without mutating state.""" agent_id = require_registered_agent_id( registry_path=registry_path, goal_id=goal_id, @@ -79,6 +81,114 @@ def build_task_planning_packet( and t.get("task_class") == TODO_TASK_CLASS_ADVANCEMENT and todo_item_is_actionable_open(t) ] + acceptance = inspect_goal_acceptance( + registry_path=registry_path, + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root_arg, + include_work_details=False, + ) + return { + "agent_id": agent_id, + "goal": goal, + "existing_todos": todos, + "runnable": runnable, + "runnable_todo_ids": [ + t["todo_id"] for t in runnable if t.get("claimed_by") == agent_id + ], + "blocking_todo_ids": [ + t["todo_id"] + for t in todos + if t.get("status") not in TODO_TERMINAL_STATUS_VALUES + and ( + t.get("status") == TODO_STATUS_BLOCKED + or t.get("task_class") + in {TODO_TASK_CLASS_BLOCKER, TODO_TASK_CLASS_USER_GATE} + ) + ], + "goal_waiting_on": goal.get("waiting_on"), + "goal_acceptance": { + key: acceptance[key] + for key in ( + "provider_revision", + "source_authority", + "goal_acceptance_contract", + "planning_requirements", + ) + }, + } + + +def validate_task_plan_readback( + result: dict[str, Any], before: dict[str, Any], after: dict[str, Any] +) -> dict[str, Any]: + """Verify a task-planning checkpoint result against canonical post-plan state.""" + if ( + result.get("input_digest") != before["input_digest"] + or after["input_digest"] != before["input_digest"] + ): + raise ValueError("planning input changed before readback") + status = result.get("status") + ids = result.get("todo_ids") + if ( + status not in {"ready", "blocked"} + or not isinstance(ids, list) + or not ids + or any(not isinstance(item, str) for item in ids) + or len(set(ids)) != len(ids) + ): + raise ValueError( + "planning result requires unique actual Todo ids and a typed status" + ) + todos = {item["todo_id"]: item for item in after["existing_todos"]} + if any(todo_id not in todos for todo_id in ids): + raise ValueError("planning referenced a missing or unrelated Todo") + if status == "ready" and not set(ids).issubset(after["runnable_todo_ids"]): + raise ValueError("planning referenced non-runnable or unclaimed work") + if status == "blocked" and not set(ids).issubset(after["blocking_todo_ids"]): + raise ValueError("blocked planning result requires unresolved blocking Todos") + requirements = after.get("goal_acceptance", {}).get("planning_requirements", {}) + if status == "ready" and ( + requirements.get("agent_id") != after["agent_id"] + or requirements.get("declaration_current") is not True + or not set(ids).issubset(requirements.get("linked_todo_ids", [])) + ): + raise ValueError("ready planning requires canonical overall requirements linked to its Todos") + return { + "input_digest": before["input_digest"], + "status": status, + "todo_ids": ids, + "goal_id": after["goal_id"], + "agent_id": after["agent_id"], + "state_readback_verified": True, + **({"goal_requirements_readback": requirements} if status == "ready" else {}), + "execution_owner": "caller", + } + + +def build_task_planning_packet( + *, + registry_path: Path, + goal_id: str, + agent_id: str, + text: str, + project: Path | None = None, + runtime_root_arg: str | None = None, +) -> dict[str, Any]: + """Read canonical planning inputs; create no Goal, Todo, Turn or host loop.""" + if not text.strip(): + raise ValueError("todo plan requires non-empty --text") + frontier = inspect_goal_planning_frontier( + registry_path=registry_path, + goal_id=goal_id, + agent_id=agent_id, + project=project, + runtime_root_arg=runtime_root_arg, + ) + agent_id = str(frontier["agent_id"]) + goal = frontier["goal"] + todos = frontier["existing_todos"] + runnable = frontier["runnable"] fine = execution_profile_is_fine_grained(goal.get("execution_profile")) prefix = ["loopx", "--format", "json", "--registry", str(registry_path)] if runtime_root_arg: @@ -95,11 +205,32 @@ def build_task_planning_packet( registry_path=registry_path, ) identity = {"goal_id": goal_id, "agent_id": agent_id, "text": text} - digest = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() - acceptance = inspect_goal_acceptance( - registry_path=registry_path, goal_id=goal_id, agent_id=agent_id, - runtime_root=runtime_root_arg, include_work_details=False, + digest = compute_task_planning_input_digest( + goal_id=goal_id, agent_id=agent_id, text=text + ) + goal_acceptance = frontier["goal_acceptance"] + outcomes = ( + (goal_acceptance.get("goal_acceptance_contract") or {}) + .get("outcome_requirements", {}) + .get("outcomes", []) + ) + batch_applicable = ( + not todos + and not outcomes + and not frontier["goal_waiting_on"] + and not frontier["blocking_todo_ids"] ) + project_args = ["--project", str(project)] if project is not None else [] + batch_route = shlex.join([ + *prefix, + "todo", + "plan-batch", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + *project_args, + ]) return { "ok": True, "read_only": True, @@ -111,25 +242,19 @@ def build_task_planning_packet( "planner": goal_planner_contract(fine_grained=fine), # Planning needs declarations and revision-bound work links, not private # check commands or a second copy of every task's validation details. - "goal_acceptance": {key: acceptance[key] for key in ( - "provider_revision", "source_authority", "goal_acceptance_contract", "planning_requirements", - )}, + "goal_acceptance": goal_acceptance, + "planning_batch": { + "schema_version": "loopx_planning_batch_proposal_v1", + "applicable": batch_applicable, + "schema_command": f"{cli} todo plan-batch --schema", + "preview_command_template": f"{batch_route} --document '' --dry-run", + "apply_command_template": f"{batch_route} --document '' --execute", + }, "ordered_steps": steps, "existing_todos": todos, - "runnable_todo_ids": [ - t["todo_id"] for t in runnable if t.get("claimed_by") == agent_id - ], - "blocking_todo_ids": [ - t["todo_id"] - for t in todos - if t.get("status") not in TODO_TERMINAL_STATUS_VALUES - and ( - t.get("status") == TODO_STATUS_BLOCKED - or t.get("task_class") - in {TODO_TASK_CLASS_BLOCKER, TODO_TASK_CLASS_USER_GATE} - ) - ], - "goal_waiting_on": goal.get("waiting_on"), + "runnable_todo_ids": frontier["runnable_todo_ids"], + "blocking_todo_ids": frontier["blocking_todo_ids"], + "goal_waiting_on": frontier["goal_waiting_on"], "result_schema": TASK_PLAN_RESULT_SCHEMA, "execution_handoff": { "owner": "caller", @@ -143,7 +268,9 @@ def build_task_planning_packet( "Use the attached planner and ordered_steps, shared with /loopx. Read the exact text " "and inspect the workspace as needed; follow goal_requirements_guidance to " "reuse existing requirements or declare missing sourced requirements through the existing outcome owner, " - "link actual work and read it back before ready. Make the approach explicit " + "link actual work and read it back before ready (when planning_batch.applicable is true, " + "you may submit one initial outcome + Todo batch via planning_batch.apply_command_template). " + "Make the approach explicit " "before writing task Todos through the routed public CLI. Compare all existing " "work and waits; reuse/update covered work and add only uncovered work. " "Do not create a planning/setup Todo, restart the Goal, complete task Todos, " diff --git a/tests/control_plane/test_benchmark_planning_batch.py b/tests/control_plane/test_benchmark_planning_batch.py index f95e81849c..1814783e30 100644 --- a/tests/control_plane/test_benchmark_planning_batch.py +++ b/tests/control_plane/test_benchmark_planning_batch.py @@ -139,3 +139,415 @@ def read(): events = fixture._heartbeat_receipt_events(runtime, "batch-fixture-execution") assert [entry["event_id"] for entry in events] == [admitted["heartbeat_receipt"]["event_id"]] assert fixture._spend_run_count(runtime) == 0 + + +def test_planning_batch_cli_help_and_schema_are_self_contained(): + import subprocess + from benchmark.runtime.planning_batch import planning_batch_guidance, planning_batch_schema + + help_proc = subprocess.run( + [sys.executable, "-m", "benchmark.runtime.planning_batch", "--help"], + capture_output=True, text=True, timeout=30, + ) + assert help_proc.returncode == 0, help_proc.stderr + assert "--schema" in help_proc.stdout + assert "outcome.source.ref" in help_proc.stdout + assert "UTF-16 code units" in help_proc.stdout + + schema_proc = subprocess.run( + [sys.executable, "-m", "benchmark.runtime.planning_batch", "--schema"], + capture_output=True, text=True, timeout=30, + ) + assert schema_proc.returncode == 0, schema_proc.stderr + schema = json.loads(schema_proc.stdout) + assert schema == planning_batch_schema() + assert schema["length_unit"] == "utf16_code_units" + assert schema["fields"]["outcome"]["properties"]["source"]["ref"]["max_utf16_code_units"] == 128 + assert schema["fields"]["outcome"]["properties"]["requirements"]["max_items"] == 32 + guidance = planning_batch_guidance() + assert "--schema" in guidance + assert 'status="ready"' in guidance + assert "UTF-16 code units" in guidance + + +def _base_proposal(): + return { + "input_digest": "digest-1", + "expected_provider_revision": "rev-1", + "outcome": { + "objective": "Deliver fix", + "requirements": [{"id": "req-1", "description": "Requirement passes"}], + "source": {"ref": "checkpoint:init", "summary": "Initial planning checkpoint"}, + }, + "todos": [{"text": "[P0] Implement fix", "action_kind": "implement"}], + } + + +@pytest.mark.parametrize(("mutate", "expected_substrings", "forbidden"), [ + ( + lambda p: p["outcome"]["source"].__setitem__("ref", "/frontier/task/repo/SECRET_REF/" + "x" * 120), + ("outcome.source.ref", "got 151 UTF-16 code units, max 128", "no '/' paths or spaces"), + "SECRET_REF", + ), + ( + lambda p: p["outcome"]["requirements"][0].__setitem__("id", "bad id with spaces"), + ("outcome.requirements[0].id", "opaque identifier"), + "bad id with spaces", + ), + ( + lambda p: p["todos"][0].__setitem__("action_kind", "do invalid action"), + ("todos[0].action_kind", "^[a-z][a-z0-9_-]{0,63}$"), + "do invalid action", + ), + ( + lambda p: p["outcome"].__setitem__("PRIVATE_EXTRA_KEY", "SECRET_VAL"), + ("outcome", "unsupported field count: 1", "allowed: objective, requirements, source"), + "PRIVATE_EXTRA_KEY", + ), + ( + lambda p: p["outcome"]["source"].__setitem__("summary", "S" * 513), + ("outcome.source.summary", "got 513 UTF-16 code units, max 512"), + "SSSSSSSS", + ), + ( + lambda p: p["outcome"].__setitem__("objective", "O" * 1025), + ("outcome.objective", "got 1025 UTF-16 code units, max 1024"), + "OOOOOOOO", + ), + ( + lambda p: p["outcome"]["requirements"][0].__setitem__("description", "D" * 2001), + ("outcome.requirements[0].description", "got 2001 UTF-16 code units, max 2000"), + "DDDDDDDD", + ), + ( + lambda p: p["outcome"].__setitem__("objective", "\U0001f600" * 513), + ("outcome.objective", "got 1026 UTF-16 code units, max 1024"), + "\U0001f600", + ), + ( + lambda p: p["outcome"]["requirements"][0].__setitem__("description", "\U0001f600" * 1001), + ("outcome.requirements[0].description", "got 2002 UTF-16 code units, max 2000"), + "\U0001f600", + ), + ( + lambda p: p["outcome"]["source"].__setitem__("summary", "\U0001f600" * 257), + ("outcome.source.summary", "got 514 UTF-16 code units, max 512"), + "\U0001f600", + ), + ( + lambda p: p["outcome"].__setitem__( + "requirements", + [{"id": f"r-{i}", "description": f"desc {i}"} for i in range(33)], + ), + ("outcome.requirements exceeds capacity", "got 33 items, max 32"), + None, + ), + ( + lambda p: p["todos"][0].__setitem__("target_key", None), + ("todos[0].target_key", "non-empty text"), + None, + ), +]) +def test_planning_batch_upfront_validation_rejects_invalid_proposals_without_loopx( + tmp_path, mutate, expected_substrings, forbidden, +): + import subprocess + from benchmark.runtime.planning_batch import apply_initial_plan + + proposal = _base_proposal() + mutate(proposal) + env = {"LOOPX_TASK_STAGE": "plan", "LOOPX_CLI": str(tmp_path / "missing-loopx")} + with pytest.raises(ValueError) as exc_info: + apply_initial_plan(env, proposal) + message = str(exc_info.value) + for snippet in expected_substrings: + assert snippet in message, message + if forbidden: + assert forbidden not in message + + proposal_path = tmp_path / "bad-proposal.json" + proposal_path.write_text(json.dumps(proposal)) + proc = subprocess.run( + [sys.executable, "-m", "benchmark.runtime.planning_batch", str(proposal_path)], + env={"PATH": "", "PYTHONPATH": str(Path(__file__).resolve().parents[2]), "LOOPX_TASK_STAGE": "plan"}, + capture_output=True, text=True, timeout=30, + ) + assert proc.returncode == 1 + payload = json.loads(proc.stdout) + assert payload["ok"] is False + for snippet in expected_substrings: + assert snippet in payload["error"], payload + if forbidden: + assert forbidden not in proc.stdout + + +def test_planning_batch_preserves_upstream_error_detail_on_refine_rejection(tmp_path, monkeypatch): + from benchmark.runtime import planning_batch + + fake_cli = write_python_host_fixture(tmp_path / "fake-loopx", f"""#!{sys.executable} +import json, sys +args = sys.argv[1:] +if "todo" in args and "plan" in args: + print(json.dumps({{ + "ok": True, + "schema_version": "loopx_task_planning_v0", + "goal_id": "goal-1", + "agent_id": "agent-1", + "execution_handoff": {{"owner": "caller"}}, + "input_digest": "digest-1", + "existing_todos": [], + "goal_waiting_on": [], + "blocking_todo_ids": [], + "goal_acceptance": {{ + "provider_revision": "rev-1", + "goal_acceptance_contract": {{}}, + }}, + }})) + raise SystemExit(0) +if "goal-acceptance" in args and "refine" in args: + print(json.dumps({{ + "ok": False, + "error": "goal_acceptance_invalid_request", + "error_code": "goal_acceptance_invalid_request", + "error_detail": "source ref must be bounded nonempty text (got 144 UTF-16 code units, max 128)", + }})) + raise SystemExit(1) +raise AssertionError(args) +""") + proposal_path = tmp_path / "proposal.json" + proposal = _base_proposal() + proposal["todos"][0]["target_key"] = "refine-target" + proposal_path.write_text(json.dumps(proposal)) + monkeypatch.setenv("LOOPX_TASK_STAGE", "plan") + monkeypatch.setenv("LOOPX_CLI", str(fake_cli)) + monkeypatch.setenv("LOOPX_GOAL_ID", "goal-1") + monkeypatch.setenv("LOOPX_AGENT_ID", "agent-1") + monkeypatch.setenv("LOOPX_PROJECT", str(tmp_path)) + monkeypatch.setenv("LOOPX_REGISTRY", str(tmp_path / "registry.json")) + monkeypatch.setenv("LOOPX_RUNTIME_ROOT", str(tmp_path / "runtime")) + task_doc = tmp_path / "task.md" + task_doc.write_text("Task description\n") + monkeypatch.setenv("LOOPX_TASK_DOC", str(task_doc)) + + import contextlib + import io + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + code = planning_batch.main([str(proposal_path)]) + assert code == 1 + payload = json.loads(stdout.getvalue()) + assert payload["ok"] is False + assert payload["stage"] == "goal-acceptance refine" + assert payload["error_code"] == "goal_acceptance_invalid_request" + assert payload["error_detail"] == "source ref must be bounded nonempty text (got 144 UTF-16 code units, max 128)" + assert payload["error_detail"] in payload["error"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_planning_batch_non_bmp_utf16_boundaries_match_real_cli(tmp_path, monkeypatch, provider): + from benchmark.runtime.planning_batch import apply_initial_plan + + env, _, _, _, _ = _environment(tmp_path, monkeypatch, provider, replan="empty") + env["LOOPX_TASK_STAGE"] = "plan" + packet = task_plan_packet(env, loopx_command(env)) + emoji = "\U0001f600" + + # Over-limit non-BMP counts (1026, 2002, 514 UTF-16 code units) fail upfront in + # planning_batch using the same UTF-16 unit rule enforced by TS goal acceptance. + base = { + "input_digest": packet["input_digest"], + "expected_provider_revision": packet["goal_acceptance"]["provider_revision"], + "outcome": { + "objective": emoji * 512, + "requirements": [{"id": "req-1", "description": emoji * 1000}], + "source": {"ref": "checkpoint:emoji", "summary": emoji * 256}, + }, + "todos": [{"text": "[P0] Deliver non-BMP boundary test", "action_kind": "implement"}], + } + for bad_outcome, snippet in [ + ({**base["outcome"], "objective": emoji * 513}, "got 1026 UTF-16 code units, max 1024"), + ({**base["outcome"], "requirements": [{"id": "req-1", "description": emoji * 1001}]}, "got 2002 UTF-16 code units, max 2000"), + ({**base["outcome"], "source": {"ref": "checkpoint:emoji", "summary": emoji * 257}}, "got 514 UTF-16 code units, max 512"), + ]: + with pytest.raises(ValueError, match=snippet): + apply_initial_plan(env, {**base, "outcome": bad_outcome}) + + # Exact-limit non-BMP counts (512, 1000, 256 emoji = 1024, 2000, 512 UTF-16 units) + # pass planning_batch and commit through the real File/SQLite goal-acceptance CLI. + ready = apply_initial_plan(env, base) + assert ready["status"] == "ready" + assert len(ready["todo_ids"]) == 1 + after = task_plan_packet(env, loopx_command(env)) + outcome = after["goal_acceptance"]["goal_acceptance_contract"]["outcome_requirements"]["outcomes"][0] + assert outcome["objective"] == emoji * 512 + assert outcome["requirements"][0]["description"] == emoji * 1000 + assert outcome["sources"][0]["summary"] == emoji * 256 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_planning_batch_target_key_boundary_real_cli_state(tmp_path, monkeypatch, provider): + import os + import subprocess + + env, _, _, _, _ = _environment(tmp_path, monkeypatch, provider, replan="empty") + env["LOOPX_TASK_STAGE"] = "plan" + before = task_plan_packet(env, loopx_command(env)) + cli_env = {**os.environ, **env} + + # Explicit null target_key must reject upfront (rc=1) with zero Goal or Todo state changes. + bad_path = tmp_path / "null-target-key.json" + bad_path.write_text(json.dumps({ + "input_digest": before["input_digest"], + "expected_provider_revision": before["goal_acceptance"]["provider_revision"], + "outcome": { + "objective": "Verify target_key boundary.", + "requirements": [{"id": "req-1", "description": "Valid string passes and null rejects."}], + "source": {"ref": "checkpoint:target-key", "summary": "Target key CLI regression."}, + }, + "todos": [{"text": "[P0] Null target key todo", "action_kind": "implement", "target_key": None}], + })) + bad_proc = subprocess.run( + [sys.executable, "-m", "benchmark.runtime.planning_batch", str(bad_path)], + env=cli_env, cwd=str(tmp_path), capture_output=True, text=True, timeout=120, + ) + assert bad_proc.returncode == 1 + assert "todos[0].target_key" in json.loads(bad_proc.stdout)["error"] + after_bad = task_plan_packet(env, loopx_command(env)) + assert after_bad["goal_acceptance"]["provider_revision"] == before["goal_acceptance"]["provider_revision"] + assert after_bad["existing_todos"] == [] + + # Omitted and valid-string target_key both commit cleanly on the same real CLI boundary. + good_path = tmp_path / "valid-target-key.json" + good_path.write_text(json.dumps({ + "input_digest": after_bad["input_digest"], + "expected_provider_revision": after_bad["goal_acceptance"]["provider_revision"], + "outcome": { + "objective": "Verify target_key boundary.", + "requirements": [{"id": "req-1", "description": "Valid string passes and null rejects."}], + "source": {"ref": "checkpoint:target-key", "summary": "Target key CLI regression."}, + }, + "todos": [ + {"text": "[P0] Omitted target key todo", "action_kind": "implement"}, + {"text": "[P1] Valid target key todo", "action_kind": "validate", "target_key": "bench-target"}, + ], + })) + good_proc = subprocess.run( + [sys.executable, "-m", "benchmark.runtime.planning_batch", str(good_path)], + env=cli_env, cwd=str(tmp_path), capture_output=True, text=True, timeout=120, + ) + assert good_proc.returncode == 0, good_proc.stdout + good_proc.stderr + assert json.loads(good_proc.stdout)["status"] == "ready" + after_good = task_plan_packet(env, loopx_command(env)) + by_text = {item["text"]: item for item in after_good["existing_todos"]} + assert by_text["[P0] Omitted target key todo"].get("target_key") is None + assert by_text["[P1] Valid target key todo"]["target_key"] == "bench-target" + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_planning_batch_cross_version_interrupted_retry_preserves_padded_ids_and_mixed_case_action_kind( + tmp_path, monkeypatch, provider, +): + import hashlib + import os + import subprocess + + env, project, _, _, _ = _environment(tmp_path, monkeypatch, provider, replan="empty") + env["LOOPX_TASK_STAGE"] = "plan" + cli = loopx_command(env) + before = task_plan_packet(env, cli) + cli_env = {**os.environ, **env} + + # Unchanged proposal matching pre-upgrade accepted input: whitespace-padded + # opaque IDs plus mixed-case action tokens (" Implement ", "Validate"). + proposal = { + "input_digest": before["input_digest"], + "expected_provider_revision": before["goal_acceptance"]["provider_revision"], + "outcome": { + "objective": "Verify cross-version interrupted retry recovery.", + "requirements": [{"id": " req-legacy ", "description": "Preserve trimmed ID and raw-case digest."}], + "source": {"ref": " checkpoint:legacy ", "summary": "Legacy interrupted batch retry."}, + }, + "todos": [ + {"text": "[P0] Implement legacy step", "action_kind": " Implement "}, + {"text": "[P1] Validate legacy step", "action_kind": "Validate"}, + ], + } + proposal_path = tmp_path / "legacy-proposal.json" + proposal_path.write_text(json.dumps(proposal)) + + # Simulate a pre-upgrade partial commit where baseline stripped whitespace + # while keeping raw-case action_kind in the proposal digest before binding. + baseline_normalized = { + "input_digest": before["input_digest"], + "expected_provider_revision": before["goal_acceptance"]["provider_revision"], + "outcome": { + "objective": "Verify cross-version interrupted retry recovery.", + "requirements": [{"id": "req-legacy", "description": "Preserve trimmed ID and raw-case digest."}], + "source": {"ref": "checkpoint:legacy", "summary": "Legacy interrupted batch retry."}, + }, + "todos": [ + {"text": "[P0] Implement legacy step", "action_kind": "Implement"}, + {"text": "[P1] Validate legacy step", "action_kind": "Validate"}, + ], + } + legacy_digest = hashlib.sha256(json.dumps(baseline_normalized, sort_keys=True).encode()).hexdigest() + legacy_outcome_id = f"benchmark-plan-{legacy_digest[:32]}" + operation = f"benchmark-plan:{before['input_digest']}" + + declaration_path = tmp_path / "legacy-declare.json" + declaration_path.write_text(json.dumps({ + **baseline_normalized["outcome"], + "outcome_id": legacy_outcome_id, + "owner_agent_id": before["agent_id"], + })) + declare_proc = subprocess.run( + [ + *cli, "goal-acceptance", "refine", + "--goal-id", before["goal_id"], "--agent-id", before["agent_id"], + "--document", str(declaration_path), + "--expected-provider-revision", before["goal_acceptance"]["provider_revision"], + "--operation-id", f"{operation}:declare", "--execute", + ], + cwd=str(project), env=cli_env, capture_output=True, text=True, timeout=120, + ) + assert declare_proc.returncode == 0, declare_proc.stdout + declare_proc.stderr + assert json.loads(declare_proc.stdout)["ok"] is True + + first_todo_proc = subprocess.run( + [ + *cli, "todo", "add", + "--goal-id", before["goal_id"], "--project", str(project), + "--role", "agent", "--claimed-by", before["agent_id"], + "--task-class", "advancement_task", + "--text=[P0] Implement legacy step", "--action-kind=Implement", + "--operation-id", f"{operation}:todo:0", "--execute", + ], + cwd=str(project), env=cli_env, capture_output=True, text=True, timeout=120, + ) + assert first_todo_proc.returncode == 0, first_todo_proc.stdout + first_todo_proc.stderr + first_todo_receipt = json.loads(first_todo_proc.stdout) + assert first_todo_receipt["ok"] is True + first_todo_id = first_todo_receipt["todo_id"] + + # Interrupted recovery on candidate must finish writing todo:1 and bind the + # original declaration + first_todo_id from the unchanged legacy proposal. + retry_proc = subprocess.run( + [sys.executable, "-m", "benchmark.runtime.planning_batch", str(proposal_path)], + env=cli_env, cwd=str(tmp_path), capture_output=True, text=True, timeout=120, + ) + assert retry_proc.returncode == 0, retry_proc.stdout + retry_proc.stderr + retry_payload = json.loads(retry_proc.stdout) + assert retry_payload["status"] == "ready" + todo_ids = retry_payload["todo_ids"] + assert len(todo_ids) == 2 and todo_ids[0] == first_todo_id + + after = task_plan_packet(env, cli) + assert after["goal_acceptance"]["planning_requirements"]["linked_todo_ids"] == todo_ids + outcomes = after["goal_acceptance"]["goal_acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(outcomes) == 1 + assert outcomes[0]["id"] == legacy_outcome_id + assert outcomes[0]["requirements"][0]["id"] == "req-legacy" + assert outcomes[0]["sources"][0]["ref"] == "checkpoint:legacy" + by_id = {item["todo_id"]: item for item in after["existing_todos"]} + assert set(by_id) == set(todo_ids) + assert [by_id[item]["action_kind"] for item in todo_ids] == ["implement", "validate"] diff --git a/tests/control_plane/test_goal_outcome_diagnostics.py b/tests/control_plane/test_goal_outcome_diagnostics.py index 27985fe0a4..67ea126cbc 100644 --- a/tests/control_plane/test_goal_outcome_diagnostics.py +++ b/tests/control_plane/test_goal_outcome_diagnostics.py @@ -44,7 +44,15 @@ def arguments(project, cli, entrypoint, document, operation): "synthetic/private-ref", "source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)", ), - ("synthetic-private-ref ", "source ref must be bounded nonempty text"), + ( + "synthetic-private-ref ", + "source ref must be bounded nonempty text (no leading/trailing whitespace; max 128 UTF-16 code units)", + ), + ( + "/private/path/" + ("x" * 130), + "source ref must be bounded nonempty text (got 144 UTF-16 code units, max 128); " + "must also be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)", + ), ]) def test_native_rejection_then_corrected_same_operation(acceptance_goal, entrypoint, source_ref, detail): project, _, cli, run = acceptance_goal @@ -165,3 +173,99 @@ def test_review_capacity_diagnosis_and_lossless_review_recovery(acceptance_goal, assert code == 0, replay assert (replay if entrypoint == "refine" else replay["goal_outcome_update"])["status"] == "replayed" assert cli("inspect")[1] == current + + +def test_outcome_schema_rejection_explains_limits_and_missing_fields_without_leaks(acceptance_goal): + project, _, cli, run = acceptance_goal + revision = cli("inspect")[1]["provider_revision"] + path = project / "bad-refinement.json" + bad_document = { + "outcome_id": "export", + "owner_agent_id": "agent-a", + "objective": "Produce a usable export", + "requirements": [{"id": "content", "SECRET_CALLER_KEY": "SECRET_CALLER_VAL"}], + "source": {"ref": "evidence:v1", "summary": "ok"}, + } + path.write_text(json.dumps(bad_document)) + code, rejected = run( + "goal-acceptance", "refine", "--goal-id", "goal-acceptance", + "--agent-id", "agent-a", "--document", str(path), "--operation-id", "missing-req-desc", + "--expected-provider-revision", revision, "--execute", + ) + assert code == 1 and rejected["error"] == "goal_acceptance_invalid_request", rejected + assert rejected["error_detail"] == ( + "outcome fields are missing or unsupported " + "(missing: description; unsupported field count: 1; allowed: id, description)" + ) + serialized = json.dumps(rejected) + assert "SECRET_CALLER_KEY" not in serialized and "SECRET_CALLER_VAL" not in serialized + + oversized_summary = refinement("evidence:v2") + oversized_summary["source"]["summary"] = "S" * 513 + path.write_text(json.dumps(oversized_summary)) + code, rejected_summary = run( + "goal-acceptance", "refine", "--goal-id", "goal-acceptance", + "--agent-id", "agent-a", "--document", str(path), "--operation-id", "oversized-summary", + "--expected-provider-revision", revision, "--execute", + ) + assert code == 1 + assert rejected_summary["error_detail"] == "source summary must be bounded nonempty text (got 513 UTF-16 code units, max 512)" + assert "S" * 20 not in json.dumps(rejected_summary) + + emoji = "\U0001f600" + exact_non_bmp = { + "outcome_id": "emoji-boundary", + "owner_agent_id": "agent-a", + "objective": emoji * 512, + "requirements": [{"id": "req-1", "description": emoji * 1000}], + "source": {"ref": "evidence:emoji-ok", "summary": emoji * 256}, + } + path.write_text(json.dumps(exact_non_bmp, ensure_ascii=False), encoding="utf-8") + code, accepted_emoji = run( + "goal-acceptance", "refine", "--goal-id", "goal-acceptance", + "--agent-id", "agent-a", "--document", str(path), "--operation-id", "emoji-at-limit", + "--expected-provider-revision", revision, "--execute", + ) + assert code == 0 and accepted_emoji["status"] == "applied", accepted_emoji + revision = accepted_emoji["provider_revision"] + + for idx, (field, bad_doc, expected_detail) in enumerate([ + ( + "objective", + {**refinement("evidence:over-obj"), "objective": emoji * 513}, + "outcome objective must be bounded nonempty text (got 1026 UTF-16 code units, max 1024)", + ), + ( + "description", + { + **refinement("evidence:over-desc"), + "requirements": [{"id": "content", "description": emoji * 1001}], + }, + "requirement description must be bounded nonempty text (got 2002 UTF-16 code units, max 2000)", + ), + ( + "summary", + { + **refinement("evidence:over-sum"), + "source": {"ref": "evidence:over-sum", "summary": emoji * 257}, + }, + "source summary must be bounded nonempty text (got 514 UTF-16 code units, max 512)", + ), + ]): + path.write_text(json.dumps(bad_doc, ensure_ascii=False), encoding="utf-8") + code, rejected_emoji = run( + "goal-acceptance", "refine", "--goal-id", "goal-acceptance", + "--agent-id", "agent-a", "--document", str(path), "--operation-id", f"emoji-over-{idx}-{field}", + "--expected-provider-revision", revision, "--execute", + ) + assert code == 1 and rejected_emoji["error"] == "goal_acceptance_invalid_request", rejected_emoji + assert rejected_emoji["error_detail"] == expected_detail + assert emoji not in json.dumps(rejected_emoji, ensure_ascii=False) + + help_result = subprocess.run( + [sys.executable, "-m", "loopx.cli", "goal-acceptance", "--help"], + capture_output=True, text=True, timeout=60, + ) + assert help_result.returncode == 0 + assert "Outcome declaration (refine):" in help_result.stdout + assert "requirements[*].id" in help_result.stdout and "UTF-16 code units" in help_result.stdout diff --git a/tests/control_plane/test_planning_batch_product.py b/tests/control_plane/test_planning_batch_product.py new file mode 100644 index 0000000000..415c4b8972 --- /dev/null +++ b/tests/control_plane/test_planning_batch_product.py @@ -0,0 +1,459 @@ +"""Product CLI, task-planning checkpoint, and HTTP tests for general planning_batch.""" + +from __future__ import annotations + +import contextlib +import http.client +import io +import json +from pathlib import Path +import subprocess +import sys +import threading + +import pytest + +from canonical_authority_fixture import initialize_canonical_source_fixture +from loopx.chat_action_store import ChatActionStore +from loopx.chat_actions import ChatActionService +from loopx.chat_server import ChatHTTPServer, ChatRequestHandler +from loopx.cli import main +from loopx.control_plane.goals.planning_batch import ( + PLANNING_BATCH_SCHEMA_VERSION, + planning_batch_schema, +) +from loopx.control_plane.goals.task_planning import ( + build_task_planning_packet, + validate_task_plan_readback, +) + + +@pytest.fixture(params=["file", "sqlite"]) +def product_goal(tmp_path: Path, request: pytest.FixtureRequest) -> dict[str, object]: + state = tmp_path / "state.md" + state.write_text("# Active Goal State\n\n## Agent Todos\n\n## User Todos\n") + runtime_root = tmp_path / "runtime" + registry = tmp_path / "registry.json" + registry.write_text( + json.dumps( + { + "schema_version": "0.1", + "common_runtime_root": str(runtime_root), + "goals": [ + { + "id": "product-plan-goal", + "repo": str(tmp_path), + "state_file": str(state), + "status": "active", + "coordination": {"registered_agents": ["planner", "peer"]}, + } + ], + } + ) + ) + initialize_canonical_source_fixture( + runtime_root, "product-plan-goal", state_path=state, provider=request.param + ) + return { + "project": tmp_path, + "registry": registry, + "runtime_root": runtime_root, + "goal_id": "product-plan-goal", + "agent_id": "planner", + "provider": request.param, + } + + +def _run_cli(*argv: str, expected_rc: int = 0) -> dict[str, object]: + out = io.StringIO() + with contextlib.redirect_stdout(out): + rc = main(list(argv)) + payload = json.loads(out.getvalue()) + assert rc == expected_rc, payload + return payload + + +def test_todo_plan_batch_schema_and_help_work_without_goal_id(): + out = io.StringIO() + with contextlib.redirect_stdout(out): + rc = main(["--format", "json", "todo", "plan-batch", "--schema"]) + assert rc == 0 + schema = json.loads(out.getvalue()) + expected = planning_batch_schema() + assert schema["schema_version"] == PLANNING_BATCH_SCHEMA_VERSION + assert schema["required_fields"] == ["expected_provider_revision", "outcome", "todos"] + assert schema["optional_fields"] == ["input_digest", "outcome_id", "operation_id"] + assert schema["fields"] == expected["fields"] + + # Subprocess CLI invocation without --goal-id also succeeds cleanly. + proc = subprocess.run( + [sys.executable, "-m", "loopx.cli", "--format", "json", "todo", "plan-batch", "--schema"], + capture_output=True, + text=True, + timeout=30, + ) + assert proc.returncode == 0, proc.stderr + assert json.loads(proc.stdout)["schema_version"] == PLANNING_BATCH_SCHEMA_VERSION + + help_proc = subprocess.run( + [sys.executable, "-m", "loopx.cli", "todo", "plan-batch", "--help"], + capture_output=True, + text=True, + timeout=30, + ) + assert help_proc.returncode == 0, help_proc.stderr + assert "--document" in help_proc.stdout + assert "--schema" in help_proc.stdout + assert "--execute" in help_proc.stdout + + +def test_product_cli_plan_batch_preview_apply_replay_and_checkpoint_readback( + product_goal: dict[str, object], +): + project = Path(str(product_goal["project"])) + registry = Path(str(product_goal["registry"])) + runtime_root = Path(str(product_goal["runtime_root"])) + goal_id = str(product_goal["goal_id"]) + agent_id = str(product_goal["agent_id"]) + task_text = "Unify batch planning across LoopX product CLI/HTTP and benchmark." + + prefix = ["--format", "json", "--registry", str(registry), "--runtime-root", str(runtime_root)] + before = build_task_planning_packet( + registry_path=registry, + runtime_root_arg=str(runtime_root), + goal_id=goal_id, + agent_id=agent_id, + text=task_text, + project=project, + ) + assert before["planning_batch"]["applicable"] is True + assert before["planning_batch"]["schema_version"] == PLANNING_BATCH_SCHEMA_VERSION + write_step = before["ordered_steps"][1] + assert write_step["id"] == "write_ordered_todos" + assert "todo plan-batch" in write_step["batch_command_template"] + assert "todo plan-batch --schema" in write_step["batch_schema_command"] + + proposal = { + "input_digest": before["input_digest"], + "expected_provider_revision": before["goal_acceptance"]["provider_revision"], + "outcome_id": "unified-batch-planning", + "operation_id": "product-batch-op-1", + "outcome": { + "objective": "Provide one reusable batch planning capability in LoopX.", + "requirements": [ + {"id": "cli-reuse", "description": "Expose `loopx todo plan-batch` for product callers."}, + {"id": "bench-reuse", "description": "Reuse the core owner in `benchmark.runtime.planning_batch`."}, + ], + "source": {"ref": "checkpoint:product", "summary": "Product task-planning checkpoint."}, + }, + "todos": [ + {"text": "[P0] Implement core planning_batch owner", "action_kind": "implement"}, + { + "text": "Validate CLI and HTTP batch readback", + "action_kind": "validate", + "priority": "P1", + "target_key": "batch-readback", + }, + ], + } + proposal_path = project / "proposal.json" + proposal_path.write_text(json.dumps(proposal), encoding="utf-8") + + # 1. Dry-run preview mutates neither Goal acceptance nor Todos nor rollout logs. + preview = _run_cli( + *prefix, + "todo", + "plan-batch", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--project", + str(project), + "--text", + task_text, + "--document", + str(proposal_path), + "--dry-run", + ) + assert preview["status"] == "planned" + assert preview["dry_run"] is True + assert preview["changed"] is False + assert preview["planned_todo_count"] == 2 + assert preview["outcome_id"] == "unified-batch-planning" + mid = build_task_planning_packet( + registry_path=registry, + runtime_root_arg=str(runtime_root), + goal_id=goal_id, + agent_id=agent_id, + text=task_text, + project=project, + ) + assert mid["existing_todos"] == [] + assert mid["goal_acceptance"]["provider_revision"] == before["goal_acceptance"]["provider_revision"] + assert not list(runtime_root.rglob("*rollout*")) + + # 2. Reject secret/over-limit values upfront without leaking caller content. + bad_path = project / "bad-proposal.json" + bad_path.write_text( + json.dumps( + { + **proposal, + "outcome": { + **proposal["outcome"], + "source": {"ref": "/private/secret/path/ref", "summary": "Summary"}, + }, + } + ), + encoding="utf-8", + ) + rejected = _run_cli( + *prefix, + "todo", + "plan-batch", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--project", + str(project), + "--text", + task_text, + "--document", + str(bad_path), + "--execute", + expected_rc=1, + ) + assert "outcome.source.ref" in str(rejected["error"]) + assert "/private/secret/path/ref" not in json.dumps(rejected) + + # 3. Apply batch and verify full canonical readback + validate_task_plan_readback. + applied = _run_cli( + *prefix, + "todo", + "plan-batch", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--project", + str(project), + "--text", + task_text, + "--document", + str(proposal_path), + "--execute", + ) + assert applied["status"] == "ready" + assert applied["dry_run"] is False + assert applied["changed"] is True + assert applied["state_readback_verified"] is True + todo_ids = applied["todo_ids"] + assert isinstance(todo_ids, list) and len(todo_ids) == 2 + + after = build_task_planning_packet( + registry_path=registry, + runtime_root_arg=str(runtime_root), + goal_id=goal_id, + agent_id=agent_id, + text=task_text, + project=project, + ) + assert after["planning_batch"]["applicable"] is False + verified = validate_task_plan_readback( + {"input_digest": applied["input_digest"], "status": applied["status"], "todo_ids": todo_ids}, + before, + after, + ) + assert verified["state_readback_verified"] is True + assert verified["goal_requirements_readback"]["outcome_ids"] == ["unified-batch-planning"] + assert verified["goal_requirements_readback"]["linked_todo_ids"] == todo_ids + + by_id = {item["todo_id"]: item for item in after["existing_todos"]} + assert [by_id[tid]["priority"] for tid in todo_ids] == ["P0", "P1"] + assert by_id[todo_ids[1]]["target_key"] == "batch-readback" + + # 4. Idempotent replay with the unchanged proposal and initial provider_revision. + replayed = _run_cli( + *prefix, + "todo", + "plan-batch", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--project", + str(project), + "--text", + task_text, + "--document", + str(proposal_path), + "--execute", + ) + assert replayed["status"] == "ready" + assert replayed["idempotent_replay"] is True + assert replayed["changed"] is False + assert replayed["todo_ids"] == todo_ids + assert replayed["provider_revision"] == applied["provider_revision"] + + +def test_http_goal_acceptance_plan_batch_preview_apply_and_replay( + product_goal: dict[str, object], +): + registry = Path(str(product_goal["registry"])) + runtime_root = Path(str(product_goal["runtime_root"])) + goal_id = str(product_goal["goal_id"]) + agent_id = str(product_goal["agent_id"]) + + store = ChatActionStore(runtime_root / "chat/actions") + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.registry_path, server.runtime_root = registry, runtime_root + server.verbose = False + server.action_store = store + server.action_service = ChatActionService( + store=store, registry_path=registry, runtime_root_override=str(runtime_root) + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + def request(method: str, path: str, body: dict[str, object] | None = None) -> tuple[int, dict[str, object]]: + conn = http.client.HTTPConnection(*server.server_address, timeout=30) + conn.request( + method, + path, + body=json.dumps(body) if body is not None else None, + headers={"Content-Type": "application/json"}, + ) + resp = conn.getresponse() + data = json.loads(resp.read()) + conn.close() + return resp.status, data + + try: + status_code, inspected = request("GET", f"/api/chat/goal-acceptance?goal_id={goal_id}") + assert status_code == 200, inspected + initial_rev = str(inspected["provider_revision"]) + + doc = { + "outcome_id": "http-plan-batch", + "outcome": { + "objective": "Plan initial work through the local HTTP product API.", + "requirements": [ + {"id": "http-preview", "description": "Support dry-run preview without writes."}, + {"id": "http-apply", "description": "Commit and link Todos with idempotent replay."}, + ], + "source": {"ref": "api:goal-acceptance", "summary": "Local product HTTP request."}, + }, + "todos": [ + {"text": "[P0] Wire HTTP plan-batch endpoint", "action_kind": "implement"}, + {"text": "[P1] Verify HTTP readback", "action_kind": "validate", "target_key": "http-plan"}, + ], + } + + status_code, preview = request( + "POST", + "/api/chat/goal-acceptance", + { + "goal_id": goal_id, + "action": "preview-plan-batch", + "agent_id": agent_id, + "document": doc, + "expected_provider_revision": initial_rev, + "operation_id": "http-batch-op", + }, + ) + assert status_code == 200, preview + assert preview["status"] == "planned" + assert preview["dry_run"] is True + assert preview["changed"] is False + assert preview["planned_todo_count"] == 2 + _, after_preview = request("GET", f"/api/chat/goal-acceptance?goal_id={goal_id}") + assert after_preview["provider_revision"] == initial_rev + + status_code, applied = request( + "POST", + "/api/chat/goal-acceptance", + { + "goal_id": goal_id, + "action": "plan-batch", + "agent_id": agent_id, + "document": doc, + "expected_provider_revision": initial_rev, + "operation_id": "http-batch-op", + }, + ) + assert status_code == 200, applied + assert applied["status"] == "ready" + assert applied["dry_run"] is False + assert applied["state_readback_verified"] is True + assert len(applied["todo_ids"]) == 2 + outcomes = applied["goal_acceptance_contract"]["outcome_requirements"]["outcomes"] + assert len(outcomes) == 1 + assert outcomes[0]["id"] == "http-plan-batch" + assert outcomes[0]["todo_ids"] == applied["todo_ids"] + + # Replay via HTTP returns the same Todo IDs and provider revision without re-writing. + status_code, replayed = request( + "POST", + "/api/chat/goal-acceptance", + { + "goal_id": goal_id, + "action": "plan-batch", + "agent_id": agent_id, + "document": doc, + "expected_provider_revision": initial_rev, + "operation_id": "http-batch-op", + }, + ) + assert status_code == 200, replayed + assert replayed["todo_ids"] == applied["todo_ids"] + assert replayed["provider_revision"] == applied["provider_revision"] + assert replayed["changed"] is False + + # Reject unregistered agent with 409 error envelope. + bad_code, bad_resp = request( + "POST", + "/api/chat/goal-acceptance", + { + "goal_id": goal_id, + "action": "plan-batch", + "agent_id": "intruder", + "document": doc, + "expected_provider_revision": str(applied["provider_revision"]), + "operation_id": "http-batch-intruder", + }, + ) + assert bad_code == 409, bad_resp + assert bad_resp["error_code"] == "goal_acceptance_operation_failed" + + # Reject explicit expected_provider_revision: null inside document. + null_rev_code, _ = request( + "POST", + "/api/chat/goal-acceptance", + { + "goal_id": goal_id, + "action": "preview-plan-batch", + "agent_id": agent_id, + "document": {**doc, "expected_provider_revision": None}, + "expected_provider_revision": str(applied["provider_revision"]), + }, + ) + assert null_rev_code == 409 + + # Reject agent_id field on non-batch actions such as configure. + extra_field_code, _ = request( + "POST", + "/api/chat/goal-acceptance", + { + "goal_id": goal_id, + "action": "clear-checks", + "agent_id": agent_id, + "expected_provider_revision": str(applied["provider_revision"]), + "operation_id": "http-clear-extra-field", + }, + ) + assert extra_field_code == 409 + finally: + server.shutdown() + thread.join(timeout=5) + server.server_close() diff --git a/tests/control_plane_ts/goal_outcome_refinement.test.ts b/tests/control_plane_ts/goal_outcome_refinement.test.ts index c280f0f74e..7116f73c24 100644 --- a/tests/control_plane_ts/goal_outcome_refinement.test.ts +++ b/tests/control_plane_ts/goal_outcome_refinement.test.ts @@ -542,3 +542,49 @@ for (const checksConfigured of [false, true]) test(`upgrade: every Goal receives assert.equal(((review.goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject).goal_completion_assessed, false); assert.equal((((review.goal_acceptance_contract as JsonObject).outcome_requirements as JsonObject).acceptance_gaps as JsonObject[]).length, 1); }); + +test("outcome validation errors report exact limits, missing keys and opaque-id rules without echoing inputs", () => { + const head = fixture(); + assert.throws( + () => refineGoalOutcome(head, goal, null, "author", patch({source: {ref: "/tmp/SECRET_PATH/" + "x".repeat(130), summary: "ok"}})), + error => { + assert.match(String(error), /source ref must be bounded nonempty text \(got 147 UTF-16 code units, max 128\)/); + assert.match(String(error), /must also be an opaque identifier/); + assert.doesNotMatch(String(error), /SECRET_PATH/); + return true; + }, + ); + assert.throws( + () => refineGoalOutcome(head, goal, null, "author", patch({requirements: [{id: "r1", SECRET_EXTRA: "SECRET_VAL"}] as unknown as JsonObject[]})), + error => { + assert.equal( + (error as Error).message, + "outcome fields are missing or unsupported (missing: description; unsupported field count: 1; allowed: id, description)", + ); + assert.doesNotMatch((error as Error).message, /SECRET_EXTRA|SECRET_VAL/); + return true; + }, + ); + assert.throws( + () => refineGoalOutcome(head, goal, null, "author", patch({ + requirements: Array.from({length: 33}, (_, i) => ({id: `r${i}`, description: `Keep ${i}`})), + })), + /requirements exceeds its supported capacity \(got 33 items, max 32\)/, + ); + const emoji = "\u{1F600}"; + const accepted = refineGoalOutcome(head, goal, null, "author", patch({ + objective: emoji.repeat(512), + requirements: [{id: "opening", description: emoji.repeat(1000)}], + source: {ref: "message:emoji-boundary", summary: emoji.repeat(256)}, + })); + assert.equal(accepted.outcomes[0].objective.length, 1024); + assert.equal(accepted.outcomes[0].requirements[0].description.length, 2000); + assert.equal(accepted.outcomes[0].sources[0].summary.length, 512); + for (const [overflow, expected] of [ + [{objective: emoji.repeat(513)}, /outcome objective must be bounded nonempty text \(got 1026 UTF-16 code units, max 1024\)/], + [{requirements: [{id: "opening", description: emoji.repeat(1001)}]}, /requirement description must be bounded nonempty text \(got 2002 UTF-16 code units, max 2000\)/], + [{source: {ref: "message:emoji-over", summary: emoji.repeat(257)}}, /source summary must be bounded nonempty text \(got 514 UTF-16 code units, max 512\)/], + ] as const) { + assert.throws(() => refineGoalOutcome(head, goal, null, "author", patch(overflow)), expected); + } +});