From 93493f55637ed895c729aed6d01cc442ced3d6e5 Mon Sep 17 00:00:00 2001 From: aihop <4408344+hhyykk@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:32:49 +0800 Subject: [PATCH 1/3] fix(cli): repair CLI, host, Lark, and packaging contracts Signed-off-by: aihop <4408344+hhyykk@users.noreply.github.com> --- apps/presentation/dashboard/vite.config.ts | 1 + loopx/agy_goal_mode/host_runtime.py | 72 +++++++++------ loopx/capabilities/change_quality/cli.py | 2 + loopx/capabilities/content_ops/cli.py | 65 ++++++++++---- .../content_ops/connector_packets.py | 28 ++---- loopx/capabilities/content_ops/layout.py | 50 ++++++----- loopx/capabilities/content_ops/markdown.py | 24 ++--- loopx/capabilities/explore/router_state.py | 2 +- .../native_chat/antigravity_adapter.py | 10 ++- loopx/chat_attachments.py | 4 +- loopx/claude_goal_mode/hooks/goal_policy.py | 24 ++--- .../claude_goal_mode/scripts/goalmode_cmd.py | 17 +++- loopx/cli.py | 62 +------------ loopx/cli_commands/explore.py | 10 +-- loopx/cli_commands/opencode2_goal_worker.py | 10 ++- loopx/extensions/lark/cli_resolution.py | 2 +- .../lark/presentation/issue_fix_surface.py | 2 +- .../lark/presentation/sync_receipt.py | 12 ++- loopx/extensions/lark/private_progress.py | 35 ++++++-- loopx/help_surface.py | 2 + .../opencode2-goal-worker.mjs | 34 +++++-- .../goal-bridge-runtime.mjs | 88 +++++++++++++++---- loopx/pi_goal_mode/loopx-goal.ts | 13 ++- loopx/presentation/explore_results_api.py | 25 ++++-- loopx/presentation/runtime_workspace.py | 7 +- loopx/presets.py | 39 +++++--- man/loopx.1 | 1 + .../loopx_codex_provider_routing/__init__.py | 2 +- packages/loopx-core/prepare.py | 4 +- packages/loopx-core/pyproject.toml | 2 +- scripts/loopx | 10 +-- scripts/loopx.ps1 | 5 +- tests/opencode2_goal_worker.test.mjs | 50 +++++++++++ tests/opencode_goal_bridge_runtime.test.mjs | 69 ++++++++++++++- tests/test_core_distribution.py | 3 +- 35 files changed, 522 insertions(+), 264 deletions(-) diff --git a/apps/presentation/dashboard/vite.config.ts b/apps/presentation/dashboard/vite.config.ts index dc2328fd91..d55764f6e0 100644 --- a/apps/presentation/dashboard/vite.config.ts +++ b/apps/presentation/dashboard/vite.config.ts @@ -36,6 +36,7 @@ export default defineConfig({ "/ssh-hosts": chatProxy, "/api/chat": chatProxy, "/api/actions": chatProxy, + "/api/goals": chatProxy, "/api/ssh-source": chatProxy, }, }, diff --git a/loopx/agy_goal_mode/host_runtime.py b/loopx/agy_goal_mode/host_runtime.py index 96e207b865..c9ccd9953d 100644 --- a/loopx/agy_goal_mode/host_runtime.py +++ b/loopx/agy_goal_mode/host_runtime.py @@ -120,6 +120,7 @@ def _reserve_retry(state: dict[str, Any], input_key: str) -> bool: def _native_input(args: argparse.Namespace, text: str) -> tuple[str, str, int] | None: """Freeze the native input identity, including repeated identical messages.""" + from ..chat_agent import CodexChatAgentError from ..capabilities.native_chat.antigravity_adapter import ( _local_url, _observed_turn_steps, @@ -127,7 +128,7 @@ def _native_input(args: argparse.Namespace, text: str) -> tuple[str, str, int] | discover_antigravity_language_server, ) - address = os.environ.get("ANTIGRAVITY_LS_ADDRESS") + address = os.environ.get("ANTIGRAVITY_LS_ADDRESS") or os.environ.get("ANTIGRAVITY_LS_URL") token = os.environ.get("ANTIGRAVITY_CSRF_TOKEN") if not address and not token: endpoint = discover_antigravity_language_server() @@ -136,46 +137,59 @@ def _native_input(args: argparse.Namespace, text: str) -> tuple[str, str, int] | address, token = endpoint["url"], endpoint["csrf_token"] elif not address or not token: return None - url = _local_url(address if "://" in address else "http://" + address) - payload = {"cascadeId": args.conversation_id} - before = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) - total = before.get("numTotalSteps") - status = before.get("status") - if ( - type(total) is not int - or total < 1 - or status not in {"CASCADE_RUN_STATUS_IDLE", "CASCADE_RUN_STATUS_RUNNING"} - or (before.get("trajectory") or {}).get("cascadeId") != args.conversation_id - ): + try: + url = _local_url(address if "://" in address else "http://" + address) + payload = {"cascadeId": args.conversation_id} + before = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) + total = before.get("numTotalSteps") + status = before.get("status") + trajectory = before.get("trajectory") + if ( + type(total) is not int + or total < 1 + or not isinstance(status, str) + or status not in {"CASCADE_RUN_STATUS_IDLE", "CASCADE_RUN_STATUS_RUNNING"} + or not isinstance(trajectory, dict) + or trajectory.get("cascadeId") != args.conversation_id + ): + return None + raw = _rpc_post( + url, + token, + "GetCascadeTrajectorySteps", + {**payload, "startIndex": 0, "endIndex": total}, + timeout=2, + ).get("steps") + if not isinstance(raw, list) or len(raw) != total: + return None + indexed, covered = _observed_turn_steps(raw, 0, total) + inputs = [ + (index, step) + for index, step in indexed + if step.get("type") == "CORTEX_STEP_TYPE_USER_INPUT" + ] + after = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) + except (ValueError, CodexChatAgentError, OSError): return None - raw = _rpc_post( - url, - token, - "GetCascadeTrajectorySteps", - {**payload, "startIndex": 0, "endIndex": total}, - timeout=2, - ).get("steps") - indexed, covered = _observed_turn_steps(raw, 0, total) - inputs = [ - (index, step) - for index, step in indexed - if step.get("type") == "CORTEX_STEP_TYPE_USER_INPUT" - ] - after = _rpc_post(url, token, "GetCascadeTrajectory", payload, timeout=2) + trajectory = after.get("trajectory") if ( not inputs or covered != total or after.get("status") != status or after.get("numTotalSteps") != total - or (after.get("trajectory") or {}).get("cascadeId") != args.conversation_id + or not isinstance(trajectory, dict) + or trajectory.get("cascadeId") != args.conversation_id ): return None index, user = inputs[-1] - created = (user.get("metadata") or {}).get("createdAt") + metadata = user.get("metadata") + created = metadata.get("createdAt") if isinstance(metadata, dict) else None + user_input = user.get("userInput") if ( not isinstance(created, str) or not created - or (user.get("userInput") or {}).get("userResponse") != text + or not isinstance(user_input, dict) + or user_input.get("userResponse") != text ): return None anchor = json.dumps([args.conversation_id, index, created, text]) diff --git a/loopx/capabilities/change_quality/cli.py b/loopx/capabilities/change_quality/cli.py index 0387d8d8ec..5764348dcf 100644 --- a/loopx/capabilities/change_quality/cli.py +++ b/loopx/capabilities/change_quality/cli.py @@ -116,6 +116,8 @@ def render_change_quality_markdown(payload: dict[str, object]) -> str: ) if payload.get("required_action"): lines.append(f"- required_action: {payload.get('required_action')}") + if payload.get("error"): + lines.append(f"- error: {payload.get('error')}") return "\n".join(lines).rstrip() + "\n" diff --git a/loopx/capabilities/content_ops/cli.py b/loopx/capabilities/content_ops/cli.py index d5f27890ef..33d6e3c72b 100644 --- a/loopx/capabilities/content_ops/cli.py +++ b/loopx/capabilities/content_ops/cli.py @@ -552,35 +552,60 @@ def register_content_ops_commands( ) +def _render_pretty_json(value: dict[str, Any]) -> str: + return json.dumps(value, ensure_ascii=False, indent=2) + "\n" + + +def _render_content_ops_error_markdown(payload: dict[str, Any]) -> str: + lines = [ + "# LoopX Content-Ops", + "", + f"- ok: `{payload.get('ok')}`", + ] + if payload.get("error"): + lines.extend(["", "## Error", "", str(payload.get("error"))]) + return "\n".join(lines) + "\n" + + def handle_content_ops_command( args: argparse.Namespace, *, output_format: FormatSelector, print_payload: PrintPayload, ) -> int: + stdin_used = False + + def read_json(path_text: str) -> dict[str, Any]: + nonlocal stdin_used + if path_text == "-": + if stdin_used: + raise ValueError("stdin ('-') can only be used for one JSON input argument per command") + stdin_used = True + return _load_json_object(path_text, args.max_input_bytes) + try: issue_fix_result = handle_content_ops_issue_fix_command(args) if issue_fix_result is not None: payload, renderer = issue_fix_result elif args.content_ops_command in {"media", "generation", "image"}: payload = handle_media_command(args) - renderer = lambda value: json.dumps(value, ensure_ascii=False, indent=2) + "\n" + renderer = _render_pretty_json elif args.content_ops_command == "reference": if args.operation == "inventory": if not args.goal_id or not args.store_id or not args.observed_at or args.library_json == "-": raise ValueError("inventory requires a catalog file, --goal-id, --store-id and --observed-at") payload = inspect_reference_materials(library_path=Path(args.library_json).expanduser(), goal_id=args.goal_id, store_id=args.store_id, observed_at=args.observed_at) else: - request = _load_json_object(args.input_json, args.max_input_bytes) if args.input_json else {} + request = read_json(args.input_json) if args.input_json else {} if args.operation in {"capture", "draft"} and not args.input_json: raise ValueError("capture/draft require --input-json") - request["library"] = _load_json_object(args.library_json, args.max_input_bytes) + request["library"] = read_json(args.library_json) if args.operation == "search": request.update(query=args.query, structure=args.structure) payload = content_reference_operation(args.operation, request) if args.output_json: write_reference_artifact(Path(args.output_json).expanduser(), payload) - renderer = lambda value: json.dumps(value, ensure_ascii=False, indent=2) + "\n" + renderer = _render_pretty_json elif args.content_ops_command == "preview": payload = build_content_ops_preview_packet(generated_at=args.generated_at) renderer = render_content_ops_preview_markdown @@ -616,10 +641,10 @@ def handle_content_ops_command( elif args.content_ops_command == "aggregate-packets": payload = build_content_ops_packet_aggregation_packet( public_handle_packets=[ - _load_json_object(path, args.max_input_bytes) for path in args.public_packet_json + read_json(path) for path in args.public_packet_json ], private_connector_gate_packets=[ - _load_json_object(path, args.max_input_bytes) for path in args.private_gate_packet_json + read_json(path) for path in args.private_gate_packet_json ], surface_id=args.surface_id, generated_at=args.generated_at, @@ -666,14 +691,14 @@ def handle_content_ops_command( renderer = render_content_ops_item_packet_markdown elif args.content_ops_command == "item-transition": payload = apply_content_ops_item_event( - _load_json_object(args.item_json, args.max_input_bytes), - _load_json_object(args.event_json, args.max_input_bytes), + read_json(args.item_json), + read_json(args.event_json), ) renderer = render_content_ops_item_packet_markdown elif args.content_ops_command == "queue-status": payload = build_content_ops_queue_status_packet( items=[ - _load_json_object(path, args.max_input_bytes) for path in args.item_json + read_json(path) for path in args.item_json ], queue_id=args.queue_id, generated_at=args.generated_at, @@ -697,19 +722,19 @@ def handle_content_ops_command( renderer = render_layout_packet_markdown elif args.content_ops_command == "layout-check": payload = check_layout_packet( - _load_json_object(args.plan_json, args.max_input_bytes), - _load_json_object(args.measurement_json, args.max_input_bytes), + read_json(args.plan_json), + read_json(args.measurement_json), ) renderer = render_layout_packet_markdown else: raise ValueError( - "content-ops requires `preview`, `exploration-plan`, " - "`issue-fix-intake`, `issue-fix-metadata-preview`, " - "`observe-public-handle`, `project-private-connector-gate`, " - "`aggregate-packets`, `project-chatview-report`, or " - "`walkthrough-artifact`, `item-create`, `item-transition`, " - "`queue-status`, `template-list`, `template-show`, " - "`layout-plan`, or `layout-check`" + "content-ops requires `media`, `generation`, `image`, `reference`, " + "`preview`, `exploration-plan`, `issue-fix-intake`, " + "`issue-fix-metadata-preview`, `observe-public-handle`, " + "`project-private-connector-gate`, `aggregate-packets`, " + "`project-chatview-report`, `walkthrough-artifact`, " + "`item-create`, `item-transition`, `queue-status`, " + "`template-list`, `template-show`, `layout-plan`, or `layout-check`" ) except Exception as exc: payload = { @@ -724,7 +749,9 @@ def handle_content_ops_command( "layout-check", }: renderer = render_layout_packet_markdown - else: + elif args.content_ops_command == "project-private-connector-gate": renderer = render_content_ops_private_connector_gate_markdown + else: + renderer = _render_content_ops_error_markdown print_payload(payload, output_format(args), renderer) return 0 if payload.get("ok") else 1 diff --git a/loopx/capabilities/content_ops/connector_packets.py b/loopx/capabilities/content_ops/connector_packets.py index 4733e34bae..f433bbdd5a 100644 --- a/loopx/capabilities/content_ops/connector_packets.py +++ b/loopx/capabilities/content_ops/connector_packets.py @@ -21,11 +21,8 @@ def _connector_trial_from_public_packet( runtime_policy: Mapping[str, Any], index: int, ) -> dict[str, Any]: - observation = ( - packet.get("observation") - if isinstance(packet.get("observation"), Mapping) - else {} - ) + raw_observation = packet.get("observation") + observation = raw_observation if isinstance(raw_observation, Mapping) else {} surface = str(packet.get("surface") or observation.get("surface") or "public_feed") source_item_id = str(source_item.get("source_item_id") or "").strip() if not source_item_id: @@ -58,11 +55,8 @@ def _connector_trial_from_private_gate_packet( source_item: Mapping[str, Any], index: int, ) -> dict[str, Any]: - connector = ( - packet.get("connector") - if isinstance(packet.get("connector"), Mapping) - else {} - ) + raw_connector = packet.get("connector") + connector = raw_connector if isinstance(raw_connector, Mapping) else {} source_item_id = str(source_item.get("source_item_id") or "").strip() if not source_item_id: raise ValueError("private connector gate source_item_id is required") @@ -107,11 +101,8 @@ def source_item_and_trial_from_public_packet( _require_packet_flag(packet, "external_writes_performed", False) _require_packet_flag(packet, "private_source_content_read", False) _require_packet_flag(packet, "autopublish_allowed", False) - runtime_policy = ( - packet.get("runtime_policy") - if isinstance(packet.get("runtime_policy"), Mapping) - else {} - ) + raw_runtime_policy = packet.get("runtime_policy") + runtime_policy = raw_runtime_policy if isinstance(raw_runtime_policy, Mapping) else {} if runtime_policy.get("safe_default") != "head_only_metadata_probe": raise ValueError("public packet runtime policy must be HEAD-only") if runtime_policy.get("browser_open_allowed_before_gate") is not False: @@ -145,11 +136,8 @@ def source_item_and_trial_from_private_gate_packet( _require_packet_flag(packet, "external_writes_performed", False) _require_packet_flag(packet, "private_source_content_read", False) _require_packet_flag(packet, "autopublish_allowed", False) - runtime_policy = ( - packet.get("runtime_policy") - if isinstance(packet.get("runtime_policy"), Mapping) - else {} - ) + raw_runtime_policy = packet.get("runtime_policy") + runtime_policy = raw_runtime_policy if isinstance(raw_runtime_policy, Mapping) else {} if runtime_policy.get("safe_default") != "gate_projection_only": raise ValueError("private packet runtime policy must be gate-only") if runtime_policy.get("browser_open_allowed_before_gate") is not False: diff --git a/loopx/capabilities/content_ops/layout.py b/loopx/capabilities/content_ops/layout.py index 93ca2a2fd2..72a6766c7a 100644 --- a/loopx/capabilities/content_ops/layout.py +++ b/loopx/capabilities/content_ops/layout.py @@ -417,35 +417,45 @@ def check_layout_packet( def render_layout_packet_markdown(packet: Mapping[str, object]) -> str: if not packet.get("ok") and "error" in packet: - return f"# Content-Ops Layout\n\nError: {packet['error']}\n" + return f"# Content-Ops Layout\n\nError: {packet.get('error', 'unknown error')}\n" if packet.get("schema_version") == "content_ops_layout_template_catalog_packet_v0": lines = ["# Content-Ops Layout Templates", ""] - for template in packet["templates"]: # type: ignore[union-attr] - lines.append(f"- `{template['template_id']}` — {template['title']}") + templates = packet.get("templates") + if isinstance(templates, list): + for template in templates: + if isinstance(template, Mapping): + lines.append(f"- `{template.get('template_id')}` — {template.get('title')}") return "\n".join(lines) + "\n" if packet.get("schema_version") == "content_ops_layout_template_packet_v0": - template = packet["template"] # type: ignore[assignment] - return ( - "# Content-Ops Layout Template\n\n" - f"- id: `{template['template_id']}`\n" - f"- title: {template['title']}\n" - f"- intent: {template['intent']}\n" - ) + template = packet.get("template") + if isinstance(template, Mapping): + return ( + "# Content-Ops Layout Template\n\n" + f"- id: `{template.get('template_id')}`\n" + f"- title: {template.get('title')}\n" + f"- intent: {template.get('intent')}\n" + ) if packet.get("schema_version") == "content_ops_layout_plan_packet_v0": - plan = packet["plan"] # type: ignore[assignment] - return ( - "# Content-Ops Layout Plan\n\n" - f"- plan: `{plan['plan_id']}`\n" - f"- template: `{plan['template_id']}`\n" - f"- pages: {len(plan['pages'])}\n" - f"- closing role: `{plan['closing_role']}`\n" - ) + plan = packet.get("plan") + if isinstance(plan, Mapping): + pages = plan.get("pages") + page_count = len(pages) if isinstance(pages, list) else 0 + return ( + "# Content-Ops Layout Plan\n\n" + f"- plan: `{plan.get('plan_id')}`\n" + f"- template: `{plan.get('template_id')}`\n" + f"- pages: {page_count}\n" + f"- closing role: `{plan.get('closing_role')}`\n" + ) lines = [ "# Content-Ops Layout Check", "", f"- status: `{packet.get('status')}`", f"- next action: `{packet.get('next_action')}`", ] - for failure in packet.get("failures", []): # type: ignore[union-attr] - lines.append(f"- `{failure['code']}`: {failure['message']}") + failures = packet.get("failures") + if isinstance(failures, list): + for failure in failures: + if isinstance(failure, Mapping): + lines.append(f"- `{failure.get('code')}`: {failure.get('message')}") return "\n".join(lines) + "\n" diff --git a/loopx/capabilities/content_ops/markdown.py b/loopx/capabilities/content_ops/markdown.py index f2bd102825..eb6133409f 100644 --- a/loopx/capabilities/content_ops/markdown.py +++ b/loopx/capabilities/content_ops/markdown.py @@ -47,7 +47,8 @@ def render_content_ops_exploration_plan_markdown(payload: dict[str, Any]) -> str ) validation = payload.get("validation") if isinstance(validation, Mapping): - errors = validation.get("errors") if isinstance(validation.get("errors"), list) else [] + raw_errors = validation.get("errors") + errors = raw_errors if isinstance(raw_errors, list) else [] lines.extend( [ "", @@ -58,6 +59,8 @@ def render_content_ops_exploration_plan_markdown(payload: dict[str, Any]) -> str f"- error_count: `{len(errors)}`", ] ) + if payload.get("error"): + lines.extend(["", "## Error", "", str(payload.get("error"))]) return "\n".join(lines) + "\n" @@ -162,11 +165,8 @@ def render_content_ops_packet_aggregation_markdown(payload: dict[str, Any]) -> s ) validation = payload.get("validation") if isinstance(validation, Mapping): - errors = ( - validation.get("errors") - if isinstance(validation.get("errors"), list) - else [] - ) + raw_errors = validation.get("errors") + errors = raw_errors if isinstance(raw_errors, list) else [] lines.extend( [ "", @@ -259,11 +259,8 @@ def render_content_ops_walkthrough_artifact_markdown(payload: dict[str, Any]) -> ) validation = payload.get("validation") if isinstance(validation, Mapping): - errors = ( - validation.get("errors") - if isinstance(validation.get("errors"), list) - else [] - ) + raw_errors = validation.get("errors") + errors = raw_errors if isinstance(raw_errors, list) else [] lines.extend( [ "", @@ -443,7 +440,8 @@ def render_content_ops_preview_markdown(payload: dict[str, Any]) -> str: ) validation = payload.get("validation") if isinstance(validation, Mapping): - errors = validation.get("errors") if isinstance(validation.get("errors"), list) else [] + raw_errors = validation.get("errors") + errors = raw_errors if isinstance(raw_errors, list) else [] lines.extend( [ "", @@ -453,4 +451,6 @@ def render_content_ops_preview_markdown(payload: dict[str, Any]) -> str: f"- error_count: `{len(errors)}`", ] ) + if payload.get("error"): + lines.extend(["", "## Error", "", str(payload.get("error"))]) return "\n".join(lines) + "\n" diff --git a/loopx/capabilities/explore/router_state.py b/loopx/capabilities/explore/router_state.py index 1cc21da374..258c33bd80 100644 --- a/loopx/capabilities/explore/router_state.py +++ b/loopx/capabilities/explore/router_state.py @@ -184,7 +184,7 @@ def observe_epoch( accept_weight = 1.0 accepted_count = probe.get("accepted_count") attempt_count = probe.get("attempt_count") - if accepted_count is not None or attempt_count is not None: + if accepted_count is not None and attempt_count is not None: try: accepted_total = float(accepted_count) attempt_total = float(attempt_count) diff --git a/loopx/capabilities/native_chat/antigravity_adapter.py b/loopx/capabilities/native_chat/antigravity_adapter.py index bd2587a677..0c9499a23a 100644 --- a/loopx/capabilities/native_chat/antigravity_adapter.py +++ b/loopx/capabilities/native_chat/antigravity_adapter.py @@ -80,9 +80,13 @@ def _observed_turn_steps(steps: list[Any], start: int, total: int) -> tuple[list for offset, step in enumerate(steps): if not isinstance(step, dict): raise ValueError("Antigravity returned an invalid trajectory step") - metadata = step.get("metadata") or {} - source = metadata.get("sourceTrajectoryStepInfo") or {} - index = source.get("stepIndex") + metadata = step.get("metadata") + if metadata is not None and not isinstance(metadata, dict): + raise ValueError("Antigravity returned invalid trajectory step metadata") + source = metadata.get("sourceTrajectoryStepInfo") if metadata else None + if source is not None and not isinstance(source, dict): + raise ValueError("Antigravity returned invalid trajectory step source metadata") + index = source.get("stepIndex") if source else None if index is not None: if type(index) is not int or index < 0: raise ValueError("Antigravity returned an invalid trajectory index") diff --git a/loopx/chat_attachments.py b/loopx/chat_attachments.py index 1b4d4e971c..deb71abe9f 100644 --- a/loopx/chat_attachments.py +++ b/loopx/chat_attachments.py @@ -80,7 +80,9 @@ def normalize_chat_image_attachments(value: Any) -> list[dict[str, Any]]: if decoded_size > CHAT_IMAGE_MAX_BYTES: raise ValueError("image attachment exceeds the 5MB limit") declared_size = raw.get("size") - if declared_size is not None and int(declared_size) != decoded_size: + if declared_size is not None and ( + type(declared_size) is not int or declared_size != decoded_size + ): raise ValueError("image attachment size does not match its data") total_bytes += decoded_size if total_bytes > CHAT_IMAGE_MAX_TOTAL_BYTES: diff --git a/loopx/claude_goal_mode/hooks/goal_policy.py b/loopx/claude_goal_mode/hooks/goal_policy.py index a794800dca..293d527dba 100644 --- a/loopx/claude_goal_mode/hooks/goal_policy.py +++ b/loopx/claude_goal_mode/hooks/goal_policy.py @@ -116,19 +116,6 @@ def _gh_prefix(): return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] -def emit(decision=None, reason=""): - if decision is None: - sys.stdout.write("{}") # no-op: defer to normal permission flow - return - sys.stdout.write(json.dumps({ - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": decision, - "permissionDecisionReason": reason, - } - })) - - def _runtime_profile_flag_is_unsupported(out: subprocess.CompletedProcess) -> bool: diagnostic = str(out.stderr or "").lower() return ( @@ -270,8 +257,15 @@ def d(decision, reason): # gate Bash with the destructive denylist (the hook is the whole gate). if tool in WRITE_TOOLS: fp = ti.get("file_path") or ti.get("notebook_path") or "" - if scope and not any(within(fp, s) for s in scope): - return d("deny", f"'{fp}' outside goal write_scope {scope}") + if scope: + if not fp.strip(): + return d( + "deny", + "unreadable PreToolUse event (missing file_path/notebook_path) - failing closed under goal-mode", + ) + resolved_fp = fp if Path(fp).is_absolute() else str(Path(cwd) / fp) + if not any(within(resolved_fp, s) for s in scope): + return d("deny", f"'{fp}' outside goal write_scope {scope}") return d("allow", "write within goal scope") if tool == "Bash": low = (ti.get("command") or "").lower() diff --git a/loopx/claude_goal_mode/scripts/goalmode_cmd.py b/loopx/claude_goal_mode/scripts/goalmode_cmd.py index 23b97fdbe8..29002f47f2 100644 --- a/loopx/claude_goal_mode/scripts/goalmode_cmd.py +++ b/loopx/claude_goal_mode/scripts/goalmode_cmd.py @@ -182,7 +182,8 @@ def print_status(ctx): t = (it.get("text") or "").strip() if t: print(f" ▸ {t}") - armed = "armed (.claude/loop.md present)" if loop_md_path(Path.cwd()).exists() else "not armed (run /loopx to arm)" + armed_root = Path(ctx.get("project_root") or Path.cwd()) + armed = "armed (.claude/loop.md present)" if loop_md_path(armed_root).exists() else "not armed (run /loopx to arm)" print(f"loop : {armed} — drive with native /loop") @@ -193,7 +194,9 @@ def main(): # off: remove the loop protocol; native /loop then has nothing to run. if first == "off": - lp = loop_md_path(proj) + reg = find_registry(proj) + target_root = reg.parent.parent if reg is not None else proj + lp = loop_md_path(target_root) if not lp.exists(): print("goal-mode OFF (no .claude/loop.md here).") return @@ -250,10 +253,16 @@ def main(): sys.exit(1) # register the default agent (identity contract) and add the task as a todo - gh(["--registry", registry, "configure-goal", "--goal-id", goal_id, - "--agent-model", "peer_v1", "--registered-agent", DEFAULT_AGENT, "--execute"]) + cfg = gh(["--registry", registry, "configure-goal", "--goal-id", goal_id, + "--agent-model", "peer_v1", "--registered-agent", DEFAULT_AGENT, "--execute"]) + if cfg.returncode != 0: + print("[loopx] configure-goal failed:\n" + (cfg.stdout + cfg.stderr)[:600]) + sys.exit(1) add = gh(["--registry", registry, "--format", "json", "todo", "add", "--goal-id", goal_id, "--role", "agent", "--text", task]) + if add.returncode != 0: + print("[loopx] todo add failed:\n" + (add.stdout + add.stderr)[:600]) + sys.exit(1) todo_id = "" try: todo_id = json.loads(add.stdout).get("todo_id", "") diff --git a/loopx/cli.py b/loopx/cli.py index 8df03d42e9..c5173eef78 100644 --- a/loopx/cli.py +++ b/loopx/cli.py @@ -41,7 +41,6 @@ register_integration_branch_commands, ) from .capabilities.repository_change_window.cli import ( - handle_repository_change_window_command, register_repository_change_window_commands, ) from .capabilities.decision_context.cli import ( @@ -92,9 +91,7 @@ ) from .cli_commands import ( handle_benchmark_command, - handle_bootstrap_connect_command, handle_canary_command, - handle_coordination_shadow_command, handle_capability_command, handle_dreaming_command, handle_explore_command, @@ -115,12 +112,9 @@ handle_registry_admin_command, handle_starter_command, handle_support_control_command, - handle_task_lease_command, handle_authority_shadow_command, - handle_postgres_command, handle_version_command, handle_usage_ping_command, - handle_host_mode_plan_command, handle_worker_bridge_command, handle_workflow_skills_command, register_benchmark_command_group, @@ -332,6 +326,7 @@ def build_parser() -> LoopXArgumentParser: register_coordination_shadow_command(sub, add_subcommand_format) register_automation_cadence_command(sub, add_subcommand_format) register_authority_archive_command(sub, add_subcommand_format) + register_postgres_commands(sub, add_subcommand_format) register_task_lease_command(sub, add_subcommand_format) register_authority_shadow_command(sub, add_subcommand_format) register_todo_continuation(sub, add_subcommand_format) @@ -378,14 +373,6 @@ def _main(argv: list[str] | None = None) -> int: if version_result is not None: return version_result - bootstrap_connect_result = handle_bootstrap_connect_command( - args, - registry_path=registry_path, - print_payload=print_payload, - ) - if bootstrap_connect_result is not None: - return bootstrap_connect_result - starter_result = handle_starter_command(args, print_payload) if starter_result is not None: return starter_result @@ -487,27 +474,9 @@ def _main(argv: list[str] | None = None) -> int: if integration_branch_result is not None: return integration_branch_result - repository_change_window_result = handle_repository_change_window_command( - args, - registry_path=registry_path, - runtime_root_arg=args.runtime_root, - output_format=output_format, - print_payload=print_payload, - ) - if repository_change_window_result is not None: - return repository_change_window_result - if args.command == "ml-experiment": return handle_ml_experiment_command(args, output_format=output_format, print_payload=print_payload) - host_mode_plan_result = handle_host_mode_plan_command( - args, - output_format=output_format, - print_payload=print_payload, - ) - if host_mode_plan_result is not None: - return host_mode_plan_result - preset_result = handle_preset_command( args, output_format=output_format, @@ -781,25 +750,6 @@ def _main(argv: list[str] | None = None) -> int: ) if cadence_result is not None: return cadence_result - coordination_shadow_result = handle_coordination_shadow_command( - args, - registry_path=registry_path, - runtime_root_arg=args.runtime_root, - output_format=output_format, - print_payload=print_payload, - ) - if coordination_shadow_result is not None: - return coordination_shadow_result - - task_lease_result = handle_task_lease_command( - args, - registry_path=registry_path, - runtime_root_arg=args.runtime_root, - output_format=output_format, - print_payload=print_payload, - ) - if task_lease_result is not None: - return task_lease_result authority_shadow_result = handle_authority_shadow_command( args, @@ -811,16 +761,6 @@ def _main(argv: list[str] | None = None) -> int: if authority_shadow_result is not None: return authority_shadow_result - postgres_result = handle_postgres_command( - args, - registry_path=registry_path, - runtime_root_arg=args.runtime_root, - output_format=output_format, - print_payload=print_payload, - ) - if postgres_result is not None: - return postgres_result - shared_goal_alignment_result = handle_shared_goal_alignment_command( args, registry_path=registry_path, diff --git a/loopx/cli_commands/explore.py b/loopx/cli_commands/explore.py index ab8f42c9b9..e5e938b46e 100644 --- a/loopx/cli_commands/explore.py +++ b/loopx/cli_commands/explore.py @@ -556,17 +556,13 @@ def handle_explore_command( config_path = ( Path(args.config_path).expanduser() if getattr(args, "config_path", None) - else default_lark_explore_config_path( - Path(str(source_runtime_route["source_registry"])) - if source_runtime_route is not None - else registry_path - ) + else default_lark_explore_config_path(source_registry) ) if args.explore_command == "schema": payload = lark_explore_schema_payload() elif args.explore_command == "turn-context": from ..capabilities.explore.turn_context import explore_turn_context - payload = explore_turn_context(registry_path=Path(str(source_runtime_route["source_registry"])), runtime_root=runtime_root, + payload = explore_turn_context(registry_path=source_registry, runtime_root=runtime_root, goal_id=args.goal_id, agent_id=args.agent_id, todo_id=args.todo_id, result_limit=args.result_limit, result_offset=args.result_offset, @@ -637,7 +633,7 @@ def handle_explore_command( payload = append_research_observation( explore_result_log_path(runtime_root, args.goal_id), goal_id=args.goal_id, observation=observation, agent_id=args.agent_id, - registry_path=Path(str(source_runtime_route["source_registry"])) if source_runtime_route else registry_path, + registry_path=source_registry, runtime_root=runtime_root, ) elif args.explore_command == "summary": diff --git a/loopx/cli_commands/opencode2_goal_worker.py b/loopx/cli_commands/opencode2_goal_worker.py index e02d663a88..48fe613318 100644 --- a/loopx/cli_commands/opencode2_goal_worker.py +++ b/loopx/cli_commands/opencode2_goal_worker.py @@ -4,6 +4,7 @@ import json import os import subprocess +import sys import tempfile import threading from pathlib import Path @@ -139,7 +140,7 @@ def _drain(stream: Iterable[str]) -> None: nonlocal worker_log_tail with log_path.open("a", encoding="utf-8") as log_handle: for line in stream: - print(line, end="", flush=True) + print(line, end="", file=sys.stderr, flush=True) log_handle.write(line) log_handle.flush() tail = log_path.read_text(encoding="utf-8").splitlines()[-120:] @@ -189,18 +190,19 @@ def _drain(stream: Iterable[str]) -> None: log_path.unlink(missing_ok=True) print_payload(payload, args.format, _render_worker_markdown) return 1 + ok = process.returncode == 0 and parsed.get("ok", True) is not False payload: dict[str, object] = { - "ok": process.returncode == 0 and parsed.get("ok", True) is not False, "schema_version": "loopx_opencode2_worker_result_v0", "operation": "opencode2_goal_worker", - "exit_code": process.returncode, } payload.update(parsed) + payload["ok"] = ok + payload["exit_code"] = process.returncode if worker_log_tail: payload["worker_log_tail"] = worker_log_tail[-1200:] log_path.unlink(missing_ok=True) print_payload(payload, args.format, _render_worker_markdown) - return process.returncode + return 0 if ok else (process.returncode or 1) def _render_worker_markdown(payload: dict[str, object]) -> str: diff --git a/loopx/extensions/lark/cli_resolution.py b/loopx/extensions/lark/cli_resolution.py index acac8668a6..981798caf7 100644 --- a/loopx/extensions/lark/cli_resolution.py +++ b/loopx/extensions/lark/cli_resolution.py @@ -92,7 +92,7 @@ def _semantic_version(path: Path) -> tuple[int, int, int] | None: match = _SEMVER_DIRECTORY.fullmatch(path.name) if not match: return None - return tuple(int(part) for part in match.groups()) + return (int(match.group(1)), int(match.group(2)), int(match.group(3))) def _nvm_candidates(home: Path) -> list[Path]: diff --git a/loopx/extensions/lark/presentation/issue_fix_surface.py b/loopx/extensions/lark/presentation/issue_fix_surface.py index 5969e31f0a..4f73710086 100644 --- a/loopx/extensions/lark/presentation/issue_fix_surface.py +++ b/loopx/extensions/lark/presentation/issue_fix_surface.py @@ -270,7 +270,7 @@ def issue_fix_record_values( } -def todo_record_values() -> dict[str, str]: +def todo_record_values() -> dict[str, Any]: return { "Work Item Type": "Todo", "Repository": "", diff --git a/loopx/extensions/lark/presentation/sync_receipt.py b/loopx/extensions/lark/presentation/sync_receipt.py index a113e1cebb..ef2aaa7dc7 100644 --- a/loopx/extensions/lark/presentation/sync_receipt.py +++ b/loopx/extensions/lark/presentation/sync_receipt.py @@ -35,8 +35,10 @@ def compact_lark_kanban_sync_receipt( *, include_command_details: bool = False, ) -> dict[str, Any]: - records = [item for item in payload.get("records", []) if isinstance(item, dict)] - commands = [item for item in payload.get("commands", []) if isinstance(item, dict)] + raw_records = payload.get("records") + raw_commands = payload.get("commands") + records = [item for item in (raw_records if isinstance(raw_records, list) else []) if isinstance(item, dict)] + commands = [item for item in (raw_commands if isinstance(raw_commands, list) else []) if isinstance(item, dict)] result = dict(payload) result.update( { @@ -65,8 +67,10 @@ def compact_lark_kanban_sync_receipt( compact_records: list[dict[str, Any]] = [] for item in records: - command = item.get("command") if isinstance(item.get("command"), dict) else {} - values = item.get("values") if isinstance(item.get("values"), dict) else {} + raw_command = item.get("command") + raw_values = item.get("values") + command = raw_command if isinstance(raw_command, dict) else {} + values = raw_values if isinstance(raw_values, dict) else {} compact_records.append( { "todo_id": item.get("todo_id"), diff --git a/loopx/extensions/lark/private_progress.py b/loopx/extensions/lark/private_progress.py index 188a190e98..fc8492db23 100644 --- a/loopx/extensions/lark/private_progress.py +++ b/loopx/extensions/lark/private_progress.py @@ -19,14 +19,24 @@ def presentation_phase(record: Mapping[str, Any], phase: str) -> str: """A continuation has its own presentation, alongside the old failure.""" recovery = record.get("context_recovery") or {} if recovery and phase in {"admission", "progress", "terminal", "commission_result"}: - return f"{phase}.recovery.{recovery.get('presentation_key', recovery['version'])}" + recovery_key = ( + recovery["presentation_key"] + if "presentation_key" in recovery + else recovery.get("version") + ) + return f"{phase}.recovery.{recovery_key}" return phase def presentation_stream(record: dict[str, Any]) -> dict[str, Any]: recovery = record.get("context_recovery") or {} if recovery: - return record.setdefault("recovery_streams", {}).setdefault(str(recovery.get("presentation_key", recovery["version"])), {}) + recovery_key = ( + recovery["presentation_key"] + if "presentation_key" in recovery + else recovery.get("version") + ) + return record.setdefault("recovery_streams", {}).setdefault(str(recovery_key), {}) return record.setdefault("stream", {}) @@ -109,9 +119,10 @@ def project_progress(state: dict[str, Any], events: list[dict[str, Any]], *, if isinstance(summary, str) and summary.strip(): cleaned = " ".join(summary.split())[:280] step_id = str(step.get("id") or "reasoning") + raw_summaries = state.get("thinking_summaries") summaries = [ row - for row in state.get("thinking_summaries", []) + for row in (raw_summaries if isinstance(raw_summaries, list) else []) if isinstance(row, Mapping) and row.get("id") != step_id ] summaries.append({"id": step_id, "text": cleaned}) @@ -139,10 +150,20 @@ def project_progress(state: dict[str, Any], events: list[dict[str, Any]], *, state["label"] = label elif payload.get("method") == "item/started": # Older adapters emit only this fixed vocabulary, without steps. - label = {"Agent 正在思考": "正在思考", "Agent 正在执行命令": "正在执行命令", "Agent 正在调用工具": "正在调用工具", - "Agent 正在检索": "正在检索资料", "Agent 正在修改文件": "正在修改文件", - "Agent 正在生成回答": "正在生成回答", - "Agent 正在压缩会话上下文": "正在压缩会话上下文"}.get(payload.get("label")) + raw_label = payload.get("label") + label = ( + { + "Agent 正在思考": "正在思考", + "Agent 正在执行命令": "正在执行命令", + "Agent 正在调用工具": "正在调用工具", + "Agent 正在检索": "正在检索资料", + "Agent 正在修改文件": "正在修改文件", + "Agent 正在生成回答": "正在生成回答", + "Agent 正在压缩会话上下文": "正在压缩会话上下文", + }.get(raw_label) + if isinstance(raw_label, str) + else None + ) if label: state["label"] = label elif (payload.get("method") == "item/completed" diff --git a/loopx/help_surface.py b/loopx/help_surface.py index c6b938ed26..1cc28e9ecd 100644 --- a/loopx/help_surface.py +++ b/loopx/help_surface.py @@ -395,6 +395,7 @@ def register_command_reference(subparsers: argparse._SubParsersAction[argparse.A "ml-experiment", "opencode2-goal-worker", "operator-gate", + "postgres", "pr-review", "promotion-gate", "read-only-map", @@ -614,6 +615,7 @@ def render_manpage(*, version: str = __version__) -> str: r"[\fB\-\-registry\fR \fIPATH\fR]", r"[\fB\-\-runtime\-root\fR \fIPATH\fR]", r"[\fB\-\-format\fR \fImarkdown|json\fR]", + r"[\fB\-\-cli\-bin\fR \fIPROGRAM\fR]", r"\fICOMMAND\fR", r"[\fIARGS\fR]", ".br", diff --git a/loopx/opencode2_goal_mode/opencode2-goal-worker.mjs b/loopx/opencode2_goal_mode/opencode2-goal-worker.mjs index cec9de63f8..7f5be755a7 100644 --- a/loopx/opencode2_goal_mode/opencode2-goal-worker.mjs +++ b/loopx/opencode2_goal_mode/opencode2-goal-worker.mjs @@ -169,7 +169,7 @@ export function createStateStore({ root = defaultStateRoot(), now = () => Date.n async function readLock(lockPath) { try { const payload = JSON.parse(await fs.readFile(lockPath, "utf8")) - if (!Number.isInteger(payload?.pid)) return null + if (!Number.isInteger(payload?.pid) || payload.pid <= 0) return null return payload } catch (error) { if (error?.code === "ENOENT") return null @@ -184,6 +184,7 @@ async function readLock(lockPath) { export function pidIsAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false try { process.kill(pid, 0) return true @@ -226,13 +227,34 @@ export function shouldRunNow(decision) { export function waitPlan(decision, state) { - const local = decision?.scheduler_hint?.unchanged_poll?.local_scheduler - if (!local || local === "stop") return { stop: true } - const token = decision?.scheduler_hint?.reset_policy?.reset_token || "" + const hint = decision?.scheduler_hint || {} + const unchanged = hint?.unchanged_poll || {} + const legacyLocal = + typeof unchanged?.local_scheduler === "object" && unchanged.local_scheduler !== null + ? unchanged.local_scheduler + : null + const local = hint?.cold_path_detail?.local_scheduler || legacyLocal + if ( + !local || + unchanged?.local_scheduler === "stop" || + unchanged?.local_scheduler === "stop_until_context_repaired" + ) { + return { stop: true } + } + const token = hint?.reset_policy?.reset_token || "" const sameIdentity = token && token === state.schedulerToken const unchangedPolls = sameIdentity ? Number(state.unchangedPolls || 0) : 0 - const limit = Number.isInteger(local.unchanged_poll_limit) ? local.unchanged_poll_limit : null - if (limit !== null && unchangedPolls >= limit) return { stop: true } + const hasHintLimits = Number.isInteger(unchanged?.limits?.local_scheduler) + if (hasHintLimits) { + const limit = Number(unchanged.limits.local_scheduler) + const afterLimit = String(unchanged?.after_limits?.local_scheduler || "") + if (unchangedPolls + 1 >= limit && afterLimit === "stop_tick_loop") { + return { stop: true } + } + } else { + const limit = Number.isInteger(local.unchanged_poll_limit) ? local.unchanged_poll_limit : null + if (limit !== null && unchangedPolls >= limit) return { stop: true } + } const progression = Array.isArray(local.example_progression_minutes) ? local.example_progression_minutes.filter((value) => Number(value) > 0) : [] diff --git a/loopx/opencode_goal_mode/goal-bridge-runtime.mjs b/loopx/opencode_goal_mode/goal-bridge-runtime.mjs index d4bfcaccd2..ab7b7e367a 100644 --- a/loopx/opencode_goal_mode/goal-bridge-runtime.mjs +++ b/loopx/opencode_goal_mode/goal-bridge-runtime.mjs @@ -1,5 +1,6 @@ // import { execFile as execFileCallback } from "node:child_process" +import { randomUUID } from "node:crypto" import { promises as fs } from "node:fs" import os from "node:os" import path from "node:path" @@ -155,6 +156,7 @@ export function probeRetryPlan(binding) { export function pidIsAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false try { process.kill(pid, 0) return true @@ -177,7 +179,7 @@ export function createFileLockStore({ root = defaultStateRoot() } = {}) { async read(sessionID) { try { const payload = JSON.parse(await fs.readFile(target(sessionID), "utf8")) - if (!Number.isInteger(payload?.pid)) return null + if (!Number.isInteger(payload?.pid) || payload.pid <= 0) return null return payload } catch (error) { if (error?.code === "ENOENT") return null @@ -186,24 +188,59 @@ export function createFileLockStore({ root = defaultStateRoot() } = {}) { }, async acquire(sessionID, { staleMs = BINDING_LOCK_STALE_MS } = {}) { const lockPath = target(sessionID) + await fs.mkdir(root, { recursive: true, mode: 0o700 }) const existing = await this.read(sessionID) if (existing && (await leaseIsLive(existing, { staleMs }))) { return { acquired: false, holder: existing } } - await fs.mkdir(root, { recursive: true, mode: 0o700 }) - const temporary = `${lockPath}.${process.pid}.${Date.now()}.tmp` - await fs.writeFile( - temporary, - `${JSON.stringify({ pid: process.pid, heartbeatAt: new Date().toISOString() })}\n`, - { encoding: "utf8", mode: 0o600 }, - ) - await fs.rename(temporary, lockPath) + if (existing) { + try { + await fs.unlink(lockPath) + } catch (error) { + if (error?.code !== "ENOENT") throw error + } + } + const token = randomUUID() + const holder = { pid: process.pid, token, heartbeatAt: new Date().toISOString() } + const writeExclusive = async () => { + const handle = await fs.open(lockPath, "wx", 0o600) + try { + await handle.writeFile(`${JSON.stringify(holder)}\n`, "utf8") + } finally { + await handle.close() + } + } + try { + await writeExclusive() + } catch (error) { + if (error?.code !== "EEXIST") throw error + const raceHolder = await this.read(sessionID) + if (raceHolder) return { acquired: false, holder: raceHolder } + try { + const stat = await fs.stat(lockPath) + if (Date.now() - stat.mtimeMs < staleMs) { + return { acquired: false, holder: null } + } + await fs.unlink(lockPath) + await writeExclusive() + } catch (retryError) { + if (retryError?.code === "EEXIST") { + return { acquired: false, holder: await this.read(sessionID) } + } + if (retryError?.code === "ENOENT") { + return { acquired: false, holder: null } + } + throw retryError + } + } await fs.chmod(lockPath, 0o600) return { acquired: true, holder: { pid: process.pid }, release: async () => { try { + const current = await this.read(sessionID) + if (current && current.token !== undefined && current.token !== token) return await fs.unlink(lockPath) } catch (error) { if (error?.code !== "ENOENT") throw error @@ -286,14 +323,35 @@ function shouldRunNow(decision) { } -function waitPlan(decision, binding) { - const local = decision?.scheduler_hint?.unchanged_poll?.local_scheduler - if (!local || local === "stop") return { stop: true } - const token = decision?.scheduler_hint?.reset_policy?.reset_token || "" +export function waitPlan(decision, binding) { + const hint = decision?.scheduler_hint || {} + const unchanged = hint?.unchanged_poll || {} + const legacyLocal = + typeof unchanged?.local_scheduler === "object" && unchanged.local_scheduler !== null + ? unchanged.local_scheduler + : null + const local = hint?.cold_path_detail?.local_scheduler || legacyLocal + if ( + !local || + unchanged?.local_scheduler === "stop" || + unchanged?.local_scheduler === "stop_until_context_repaired" + ) { + return { stop: true } + } + const token = hint?.reset_policy?.reset_token || "" const sameIdentity = token && token === binding.schedulerToken const unchangedPolls = sameIdentity ? Number(binding.unchangedPolls || 0) : 0 - const limit = Number.isInteger(local.unchanged_poll_limit) ? local.unchanged_poll_limit : null - if (limit !== null && unchangedPolls >= limit) return { stop: true } + const hasHintLimits = Number.isInteger(unchanged?.limits?.local_scheduler) + if (hasHintLimits) { + const limit = Number(unchanged.limits.local_scheduler) + const afterLimit = String(unchanged?.after_limits?.local_scheduler || "") + if (unchangedPolls + 1 >= limit && afterLimit === "stop_tick_loop") { + return { stop: true } + } + } else { + const limit = Number.isInteger(local.unchanged_poll_limit) ? local.unchanged_poll_limit : null + if (limit !== null && unchangedPolls >= limit) return { stop: true } + } const progression = Array.isArray(local.example_progression_minutes) ? local.example_progression_minutes.filter((value) => Number(value) > 0) : [] diff --git a/loopx/pi_goal_mode/loopx-goal.ts b/loopx/pi_goal_mode/loopx-goal.ts index e4c8b751ce..051d1c4254 100644 --- a/loopx/pi_goal_mode/loopx-goal.ts +++ b/loopx/pi_goal_mode/loopx-goal.ts @@ -221,7 +221,18 @@ async function runLoopxTaskLeaseCli( async function probeLoopxQuota(binding: Record): Promise> { const args = buildQuotaArgs(binding); - const stdout = await runLoopxCli(args, String(binding.directory || "")); + let stdout: string; + try { + stdout = await runLoopxCli(args, String(binding.directory || "")); + } catch (error) { + // A denied/gated decision exits non-zero while still carrying the authoritative + // JSON decision payload on stdout; only rethrow when stdout lacks a JSON object. + const failure = error as { stdout?: unknown }; + const candidate = typeof failure?.stdout === "string" ? failure.stdout.trim() : ""; + const parsed = candidate ? parseJsonObject(candidate) : null; + if (!parsed) throw error; + return parsed as Record; + } const decision: unknown = JSON.parse(stdout || "{}"); if (!decision || typeof decision !== "object" || Array.isArray(decision)) { throw new Error("loopx quota should-run returned a non-object payload"); diff --git a/loopx/presentation/explore_results_api.py b/loopx/presentation/explore_results_api.py index cdb4f42d46..9512dc9795 100644 --- a/loopx/presentation/explore_results_api.py +++ b/loopx/presentation/explore_results_api.py @@ -6,6 +6,7 @@ from ..control_plane.todos.list_readback import list_goal_todos from ..control_plane.coordination.local_authority import LocalCoordinationAuthorityUnavailable +from ..control_plane.status.goal_source import SourceScopeError from ..capabilities.explore.result_log import ( build_explore_result_projection, @@ -33,14 +34,15 @@ def _result_rows(runtime_root, goal_id, registry_path): # Task authority is independent of the verified evidence log. Reuse # the source reader's unavailable-associations view; never present a # partial list as complete or fall back to legacy task state. - return _finding_rows(events, None, goal_id=goal_id) - return _finding_rows(events, todos.values(), goal_id=goal_id) + return _finding_rows(events, None, goal_id=goal_id, validated=True) + return _finding_rows(events, todos.values(), goal_id=goal_id, validated=True) -def _finding_rows(events, todos, *, goal_id): +def _finding_rows(events, todos, *, goal_id, validated: bool = False): """Same Explore projection and task associations for every physical source.""" from ..control_plane.work_items.yardstick_decision import project_work_yardstick_presentations - events = [validate_explore_result_event(event, expected_goal_id=goal_id) for event in events] + if not validated: + events = [validate_explore_result_event(event, expected_goal_id=goal_id) for event in events] projection = build_explore_result_projection( events, goal_id=goal_id, finding_limit=len(events), ) @@ -150,13 +152,24 @@ def _explore_results(self): original_goal_id = reader.source.goal_id if view == "history-timing": status = reader.registered_status(original_goal_id, fresh=True) + native_goals = (status.get("run_history") or {}).get("goals") or [] + native_goal = next( + ( + goal + for goal in native_goals + if isinstance(goal, dict) and goal.get("id") == original_goal_id + ), + None, + ) + if native_goal is None: + raise SourceScopeError("The original Goal is no longer registered") events = ( validate_explore_result_event(event, expected_goal_id=original_goal_id) for event in reader.source.read_events(original_goal_id) ) page = _history_timing( events, goal_id=original_goal_id, source_namespace=reader.source.namespace, - native_goal=status["run_history"]["goals"][0], + native_goal=native_goal, ) elif view == "history": page = reader.history(original_goal_id, cursor) @@ -192,6 +205,8 @@ def _explore_results(self): _result_rows(runtime_root, goal_id, self.server.registry_path), ) self._send_json({**page, "goal_id": goal_id}) + except SourceScopeError: + self._send_error("Goal or connection is not available in this source.", status=404) except ValueError as exc: expired = str(exc) == "history_cursor_expired" self._send_error( diff --git a/loopx/presentation/runtime_workspace.py b/loopx/presentation/runtime_workspace.py index a0d918ee36..92ca88c9ef 100644 --- a/loopx/presentation/runtime_workspace.py +++ b/loopx/presentation/runtime_workspace.py @@ -15,7 +15,7 @@ from pathlib import Path import subprocess from threading import Thread -from urllib.parse import parse_qs, urlencode, urlparse +from urllib.parse import parse_qs, unquote, urlencode, urlparse from ..capabilities.explore.result_log import explore_history_rows from ..control_plane.status.goal_source import GoalSource, GoalSourceReader, SourceScopeError @@ -46,6 +46,8 @@ def status_url(self): class RuntimeWorkspaceHandler(ResearchAnalysisRequestMixin, BaseHTTPRequestHandler): + server: RuntimeWorkspaceServer + def log_message(self, *_args): pass @@ -224,7 +226,8 @@ def do_GET(self): self._json({"ok": False, "error": "原运行来源暂不可读,请刷新重试;未替换来源。"}, 503) def _asset(self, path): - relative = "index.html" if path in {"/", "/chat", "/chat/"} else path.removeprefix("/chat/") + decoded = unquote(path) + relative = "index.html" if decoded in {"/", "/chat", "/chat/"} else decoded.removeprefix("/chat/") target = (self.server.assets_dir / relative).resolve() if not target.is_relative_to(self.server.assets_dir) or not target.is_file(): self._json({"ok": False, "error": "Asset not found."}, 404) diff --git a/loopx/presets.py b/loopx/presets.py index 34ee9af964..ce3beac5e1 100644 --- a/loopx/presets.py +++ b/loopx/presets.py @@ -221,19 +221,20 @@ def _preset_commands( agent_id: str, agent_scope: str, ) -> dict[str, str]: + quoted_cli = _shell(cli_bin) return { "slash_start": f"/loopx {preset.goal_text}", "cli_start": ( - f"{cli_bin} start-goal --guided --project {_shell(project)} " + f"{quoted_cli} start-goal --guided --project {_shell(project)} " f"--goal-text {_shell(preset.goal_text)}" ), "quota_guard": ( - f"{cli_bin} --format json quota should-run " + f"{quoted_cli} --format json quota should-run " f"--goal-id {_shell(goal_id)} --agent-id {_shell(agent_id)} " "--runtime-profile codex_app_heartbeat" ), "heartbeat_prompt": ( - f"{cli_bin} heartbeat-prompt --thin --goal-id {_shell(goal_id)} " + f"{quoted_cli} heartbeat-prompt --thin --goal-id {_shell(goal_id)} " f"--agent-id {_shell(agent_id)} --agent-scope {_shell(agent_scope)} " "--runtime-profile codex_app_heartbeat" ), @@ -304,9 +305,9 @@ def build_beginner_preset_packet( "project": project, }, "common_setup": [ - f"{cli_bin} doctor", - f"{cli_bin} slash-commands --install", - f"{cli_bin} preset list", + f"{_shell(cli_bin)} doctor", + f"{_shell(cli_bin)} slash-commands --install", + f"{_shell(cli_bin)} preset list", ], "presets": [ _preset_to_dict( @@ -332,10 +333,18 @@ def render_beginner_preset_markdown(payload: dict[str, Any]) -> str: "", "Common setup:", ] - for command in payload.get("common_setup", []): + raw_setup = payload.get("common_setup") + common_setup = raw_setup if isinstance(raw_setup, list) else [] + for command in common_setup: lines.append(f"- `{command}`") lines.append("") - presets = payload.get("presets") if isinstance(payload.get("presets"), list) else [] + cli_prefix = ( + str(common_setup[0]).rsplit(" ", 1)[0] + if common_setup and isinstance(common_setup[0], str) + else "loopx" + ) + raw_presets = payload.get("presets") + presets = raw_presets if isinstance(raw_presets, list) else [] for preset in presets: if not isinstance(preset, dict): continue @@ -353,17 +362,21 @@ def render_beginner_preset_markdown(payload: dict[str, Any]) -> str: "Useful when:", ] ) - for item in preset.get("useful_when", []): + raw_useful = preset.get("useful_when") + for item in raw_useful if isinstance(raw_useful, list) else []: lines.append(f"- {item}") lines.extend(["", "Safety defaults:"]) - for item in preset.get("safety_defaults", []): + raw_safety = preset.get("safety_defaults") + for item in raw_safety if isinstance(raw_safety, list) else []: lines.append(f"- {item}") lines.extend(["", "Commands:", ""]) - commands = preset.get("commands") if isinstance(preset.get("commands"), dict) else {} + raw_commands = preset.get("commands") + commands = raw_commands if isinstance(raw_commands, dict) else {} for label in ("slash_start", "cli_start", "quota_guard", "heartbeat_prompt"): command = commands.get(label) if command: - lines.extend([f"{label}:", "```bash", str(command), "```", ""]) - lines.append(f"Show only this preset: `loopx preset show {preset.get('id')}`") + fence = "text" if label == "slash_start" else "bash" + lines.extend([f"{label}:", f"```{fence}", str(command), "```", ""]) + lines.append(f"Show only this preset: `{cli_prefix} preset show {preset.get('id')}`") lines.append("") return "\n".join(lines).rstrip() + "\n" diff --git a/man/loopx.1 b/man/loopx.1 index bda8dcb29b..42e4c50a19 100644 --- a/man/loopx.1 +++ b/man/loopx.1 @@ -6,6 +6,7 @@ loopx \- control-plane helper for long-running agent work [\fB\-\-registry\fR \fIPATH\fR] [\fB\-\-runtime\-root\fR \fIPATH\fR] [\fB\-\-format\fR \fImarkdown|json\fR] +[\fB\-\-cli\-bin\fR \fIPROGRAM\fR] \fICOMMAND\fR [\fIARGS\fR] .br diff --git a/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/__init__.py b/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/__init__.py index 35654d1d8c..d27286bd38 100644 --- a/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/__init__.py +++ b/packages/loopx-codex-provider-routing/src/loopx_codex_provider_routing/__init__.py @@ -1,3 +1,3 @@ __all__ = ["__version__"] -__version__ = "0.14.0" +__version__ = "0.15.8" diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index 6fd749cc23..d53291b160 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -14,7 +14,7 @@ # These are distribution exclusions, not an authority or activation policy. EXCLUDED_TREES = ("loopx/chat/", "loopx/web/", "loopx/canary/") EXCLUDED_MODULES = {"loopx/cli.py", "loopx/chat.py"} -SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md"} +SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md", ".toml"} def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: @@ -48,7 +48,7 @@ def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: for name in ("LICENSE", "LICENSE-MIT", "NOTICE"): shutil.copyfile(repository / name, output / name) (output / "MANIFEST.in").write_text( - "recursive-include loopx *.py *.ts *.json *.mjs *.js *.md\n", encoding="utf-8", + "recursive-include loopx *.py *.ts *.json *.mjs *.js *.md *.toml\n", encoding="utf-8", ) return output diff --git a/packages/loopx-core/pyproject.toml b/packages/loopx-core/pyproject.toml index 3fe9ed8f10..18055fa421 100644 --- a/packages/loopx-core/pyproject.toml +++ b/packages/loopx-core/pyproject.toml @@ -22,7 +22,7 @@ version = {attr = "loopx.__version__"} include = ["loopx*"] [tool.setuptools.package-data] -"*" = ["*.ts", "*.json", "*.mjs", "*.js", "README.md", "README.zh-CN.md", "docs/*.md", "docs/protocols/*.md"] +"*" = ["*.ts", "*.json", "*.mjs", "*.js", "*.toml", "README.md", "README.zh-CN.md", "docs/*.md", "docs/protocols/*.md"] [tool.setuptools.exclude-package-data] "loopx.semantics" = ["project_registry_io_manifest_v1.json"] diff --git a/scripts/loopx b/scripts/loopx index 7e37b2a0e4..57f5abd088 100755 --- a/scripts/loopx +++ b/scripts/loopx @@ -21,7 +21,7 @@ for arg in "$@"; do continue fi case "$arg" in - --format|--registry|--runtime-root|--goal-id|--agent-id|--git-diff-base|--tier|--timeout-seconds|--changed-file|--catalog|--surface|--family|--profile|--suite|--module|--exclude-module|--script|--limit|--offset|--max-checks-per-family|--max-checks-per-profile) + --format|--registry|--runtime-root|--cli-bin|--goal-id|--agent-id|--git-diff-base|--tier|--timeout-seconds|--changed-file|--catalog|--surface|--family|--profile|--suite|--module|--exclude-module|--script|--limit|--offset|--max-checks-per-family|--max-checks-per-profile) skip_next_arg=1 continue ;; @@ -40,7 +40,7 @@ done native_scheduler_facts=0 native_scheduler_turn=0 native_scheduler_host_match=0 -native_scheduler_trae=0 +native_scheduler_non_codex_app=0 for arg in "$@"; do case "$arg" in --scheduler-host-facts-chunk|--scheduler-host-facts-chunk=*) @@ -52,8 +52,8 @@ for arg in "$@"; do --host-match-observed) native_scheduler_host_match=1 ;; - --trae_app) - native_scheduler_trae=1 + --trae_app|--antigravity_app) + native_scheduler_non_codex_app=1 ;; esac done @@ -64,7 +64,7 @@ if [[ "$loopx_command" == "quota" \ && "$native_scheduler_turn" == "1" \ && "${LOOPX_KUNLUNCODE_OUTER_CONTROLLER:-}" != "1" \ && ! ( "$loopx_subcommand" == "scheduler-ack-current" \ - && "$native_scheduler_host_match" == "1" && "$native_scheduler_trae" == "0" ) ]]; then + && "$native_scheduler_host_match" == "1" && "$native_scheduler_non_codex_app" == "0" ) ]]; then native_scheduler_entry="$repo_root/loopx/control_plane/scheduler/heartbeat_followup_cli.ts" if ! command -v node >/dev/null 2>&1; then echo "loopx runtime error: native scheduler follow-up requires Node.js 22.22.3 or newer" >&2 diff --git a/scripts/loopx.ps1 b/scripts/loopx.ps1 index cad683426c..a7473e7d87 100644 --- a/scripts/loopx.ps1 +++ b/scripts/loopx.ps1 @@ -29,7 +29,7 @@ foreach ($argValue in $args) { $skipNextArg = $false continue } - if ($argValue -in @("--format", "--registry", "--runtime-root")) { + if ($argValue -in @("--format", "--registry", "--runtime-root", "--cli-bin")) { $skipNextArg = $true continue } @@ -57,7 +57,8 @@ $hasNativeSchedulerTurn = @( $needsCodexHostRead = ( $loopxSubcommand -eq "scheduler-ack-current" -and $args -contains "--host-match-observed" -and - $args -notcontains "--trae_app" + $args -notcontains "--trae_app" -and + $args -notcontains "--antigravity_app" ) $isNativeSchedulerFollowup = ( $loopxCommand -eq "quota" -and diff --git a/tests/opencode2_goal_worker.test.mjs b/tests/opencode2_goal_worker.test.mjs index df26cc1649..e4d6dc222f 100644 --- a/tests/opencode2_goal_worker.test.mjs +++ b/tests/opencode2_goal_worker.test.mjs @@ -14,6 +14,7 @@ import { leaseIsLive, parseExecFailure, parseWorkerArgs, + pidIsAlive, retryPlan, runWorker, sanitizedStateName, @@ -688,6 +689,7 @@ test("worker entry runs main() even when argv[1] goes through a symlinked path", path.join(import.meta.dirname, "..", "loopx", "opencode2_goal_mode", "opencode2-goal-worker.mjs"), ) const linkDir = path.join(os.tmpdir(), `loopx-worker-entry-${process.pid}`) + const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "loopx-worker-entry-state-")) await fs.rm(linkDir, { recursive: true, force: true }) await fs.mkdir(path.dirname(workerFile), { recursive: true }) await fs.symlink(path.dirname(workerFile), linkDir) @@ -697,6 +699,7 @@ test("worker entry runs main() even when argv[1] goes through a symlinked path", let exitCode = 0 try { const result = await execFile(process.execPath, [argvPath, "--goal-id", "x", "--directory", "/tmp"], { + env: { ...process.env, XDG_STATE_HOME: stateDir }, timeout: 30_000, maxBuffer: 4 * 1024 * 1024, }) @@ -715,6 +718,7 @@ test("worker entry runs main() even when argv[1] goes through a symlinked path", ) } finally { await fs.rm(linkDir, { recursive: true, force: true }) + await fs.rm(stateDir, { recursive: true, force: true }) } }) @@ -948,3 +952,49 @@ test("restart after denied initial dispatch preserves the original private task" assert.deepEqual(transport.calls.prompts, ["Original task"]) } finally { await fs.rm(root, { recursive: true, force: true }) } }) + + +test("waitPlan honors real scheduler_hint cold_path_detail and pid <= 0 lock rejection", async () => { + assert.equal(pidIsAlive(0), false) + assert.equal(pidIsAlive(-1), false) + const decision = { + should_run: false, + scheduler_hint: { + action: "backoff_waiting_for_user", + reset_policy: { reset_token: "hint-2" }, + cold_path_detail: { + local_scheduler: { + recommended_interval_minutes: 3, + example_progression_minutes: [3, 6], + }, + }, + unchanged_poll: { + limits: { local_scheduler: 2 }, + after_limits: { local_scheduler: "stop_tick_loop" }, + }, + }, + } + const first = waitPlan(decision, { schedulerToken: "", unchangedPolls: 0 }) + assert.deepEqual(first, { + stop: false, + minutes: 3, + schedulerToken: "hint-2", + unchangedPolls: 1, + }) + assert.deepEqual(waitPlan(decision, first), { stop: true }) + + const root = await fs.mkdtemp(path.join(os.tmpdir(), "worker-lock-pid-")) + try { + const store = createStateStore({ root }) + await fs.writeFile( + store.lockPath("goal-zero"), + `${JSON.stringify({ pid: -1, heartbeatAt: new Date(0).toISOString() })}\n`, + "utf8", + ) + const acquired = await store.acquireLock("goal-zero") + assert.equal(acquired.acquired, true) + await acquired.release() + } finally { + await fs.rm(root, { recursive: true, force: true }) + } +}) diff --git a/tests/opencode_goal_bridge_runtime.test.mjs b/tests/opencode_goal_bridge_runtime.test.mjs index fef3074ede..b37b4515f8 100644 --- a/tests/opencode_goal_bridge_runtime.test.mjs +++ b/tests/opencode_goal_bridge_runtime.test.mjs @@ -4,7 +4,13 @@ import { promises as fs } from "node:fs" import os from "node:os" import path from "node:path" -import { createLoopxGoalPlugin, createFileBindingStore } from "../loopx/opencode_goal_mode/goal-bridge-runtime.mjs" +import { + createLoopxGoalPlugin, + createFileBindingStore, + createFileLockStore, + pidIsAlive, + waitPlan, +} from "../loopx/opencode_goal_mode/goal-bridge-runtime.mjs" function fakeTool(spec) { @@ -858,3 +864,64 @@ test("filesystem binding preserves pause across bridge recreation", async () => await restored.dispose() } finally { await fs.rm(root, { recursive: true, force: true }) } }) + + +test("waitPlan supports real scheduler_hint cold_path_detail and limits contract", () => { + const decision = { + should_run: false, + scheduler_hint: { + action: "backoff_waiting_for_user", + reset_policy: { reset_token: "hint-tok" }, + cold_path_detail: { + local_scheduler: { + recommended_interval_minutes: 3, + example_progression_minutes: [3, 6, 12], + }, + }, + unchanged_poll: { + limits: { local_scheduler: 2 }, + after_limits: { local_scheduler: "stop_tick_loop" }, + }, + }, + } + const first = waitPlan(decision, { schedulerToken: "", unchangedPolls: 0 }) + assert.deepEqual(first, { + stop: false, + minutes: 3, + schedulerToken: "hint-tok", + unchangedPolls: 1, + }) + const second = waitPlan(decision, first) + assert.deepEqual(second, { stop: true }) + assert.deepEqual( + waitPlan( + { + should_run: false, + scheduler_hint: { + cold_path_detail: { local_scheduler: { recommended_interval_minutes: 3 } }, + unchanged_poll: { local_scheduler: "stop_until_context_repaired" }, + }, + }, + { schedulerToken: "", unchangedPolls: 0 }, + ), + { stop: true }, + ) +}) + + +test("file lock store ignores pid <= 0 lock payloads and cleans up safely", async () => { + assert.equal(pidIsAlive(0), false) + assert.equal(pidIsAlive(-1), false) + const root = await fs.mkdtemp(path.join(os.tmpdir(), "bridge-lock-pid-")) + try { + await fs.writeFile( + path.join(root, "ses_zero.lock"), + `${JSON.stringify({ pid: 0, heartbeatAt: new Date().toISOString() })}\n`, + "utf8", + ) + const store = createFileLockStore({ root }) + assert.equal(await store.read("ses_zero"), null) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } +}) diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index 81ff9aaba5..f39fae8197 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -60,7 +60,8 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): assert not (staged / "loopx" / name).exists() assert not list((staged / "loopx").glob("chat_*.py")) for name in ("entrypoint.py", "control_plane/turn_driver/executor.py", - "control_plane/coordination/sqlite_authority_store.ts"): + "control_plane/coordination/sqlite_authority_store.ts", + "extensions/lark/extension.toml"): assert (staged / "loopx" / name).read_bytes() == (REPOSITORY / "loopx" / name).read_bytes() assert not (staged / ".loopx").exists() assert not (staged / "tests").exists() From 7bea70136547b753e45257c56ca2b4885619379f Mon Sep 17 00:00:00 2001 From: aihop <4408344+hhyykk@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:32:50 +0800 Subject: [PATCH 2/3] fix(control-plane): harden host cleanup and retire unused paths Signed-off-by: aihop <4408344+hhyykk@users.noreply.github.com> --- loopx/canary/runner.py | 3 +- loopx/control_plane/agents/runtime_model.py | 7 - .../capabilities/explore_research_terminal.ts | 41 +- loopx/control_plane/collaboration/inbox.py | 12 - .../coordination/handoff_mode_facts.ts | 14 +- .../coordination/local_authority_shadow.ts | 22 - .../coordination/remote_authority_policy.ts | 6 +- .../coordination/shadow_drain_files.ts | 33 +- loopx/control_plane/effect_runtime.py | 48 +- .../control_plane/effect_runtime_handlers.ts | 1 - loopx/control_plane/goals/acceptance.py | 38 -- .../goals/acceptance_contract.ts | 7 - .../control_plane/goals/checkpoint_commit.ts | 3 +- loopx/control_plane/goals/dreaming.py | 3 +- loopx/control_plane/goals/goal_vision.py | 21 - .../control_plane/goals/goal_vision_policy.py | 11 - loopx/control_plane/goals/goal_vision_wait.py | 17 - .../quota/selected_todo_projection.py | 12 - .../quota/settlement_workspace_causality.py | 17 - loopx/control_plane/quota/stall_repair.py | 13 - loopx/control_plane/rollout_receipt_log.ts | 20 - .../shared_runtime_refresh_projection.py | 22 - .../control_plane/scheduler/scheduler_hint.py | 14 - loopx/control_plane/scheduler/state.py | 24 - .../scheduler/state_transition_rules.py | 13 - .../testing/shadow_drain_fault_process.ts | 19 - .../todos/active_state_editing.py | 16 - .../todos/completion_validation.py | 126 ----- loopx/control_plane/todos/monitor_metadata.py | 16 - loopx/control_plane/todos/monitor_scope.ts | 17 - loopx/control_plane/todos/quota_summary.py | 12 - loopx/control_plane/todos/todo_semantics.py | 5 - loopx/control_plane/todos/todo_summary.py | 20 - .../turn_driver/session_recovery.py | 16 - .../control_plane/turn_driver/transaction.py | 2 +- .../turn_driver/turn_contract_generated.py | 5 +- .../work_items/attention_item.py | 6 +- .../work_items/delivery_outcome.py | 5 - loopx/quota.py | 2 - loopx/semantics/project_registry_io.py | 8 +- loopx/status.py | 56 +-- scripts/generate_turn_contract.py | 5 +- .../test_status_facade_vocabulary_owners.py | 20 +- .../delivery_response.test.ts | 10 +- .../effect_runtime_handler_loading.test.ts | 7 +- .../effect_runtime_handlers.test.ts | 1 + .../usage_statistics_environment.test.ts | 15 +- .../control_plane_ts/zcode_app_server.test.ts | 2 +- tests/test_audit_cli_and_runtime_fixes.py | 455 ++++++++++++++++++ tsconfig.control-plane.json | 1 + 50 files changed, 622 insertions(+), 647 deletions(-) delete mode 100644 loopx/control_plane/testing/shadow_drain_fault_process.ts create mode 100644 tests/test_audit_cli_and_runtime_fixes.py diff --git a/loopx/canary/runner.py b/loopx/canary/runner.py index 515057d5a1..0aad388b88 100644 --- a/loopx/canary/runner.py +++ b/loopx/canary/runner.py @@ -7,6 +7,7 @@ import sys import tempfile import time +from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor, as_completed from functools import partial from pathlib import Path @@ -180,7 +181,7 @@ def _display_git_path(path: bytes | str) -> str: return repr(path) -def _display_git_paths(paths: list[bytes | str]) -> list[str]: +def _display_git_paths(paths: Sequence[bytes | str]) -> list[str]: return [_display_git_path(path) for path in paths] diff --git a/loopx/control_plane/agents/runtime_model.py b/loopx/control_plane/agents/runtime_model.py index 76d985d66f..060d6063e4 100644 --- a/loopx/control_plane/agents/runtime_model.py +++ b/loopx/control_plane/agents/runtime_model.py @@ -28,13 +28,6 @@ def agent_runtime_model_for_goal(goal: Mapping[str, Any] | None) -> AgentRuntime return AgentRuntimeModel.PEER_V1 -def agent_identity_is_peer(agent_identity: Mapping[str, Any] | None) -> bool: - return bool( - isinstance(agent_identity, Mapping) - and agent_identity.get("agent_model") == AgentRuntimeModel.PEER_V1.value - ) - - def normalized_peer_agent_ids(values: Iterable[Any]) -> list[str]: agents = sorted( { diff --git a/loopx/control_plane/capabilities/explore_research_terminal.ts b/loopx/control_plane/capabilities/explore_research_terminal.ts index b87f1d80e2..913acea760 100644 --- a/loopx/control_plane/capabilities/explore_research_terminal.ts +++ b/loopx/control_plane/capabilities/explore_research_terminal.ts @@ -51,12 +51,16 @@ export class ResearchTerminalEvidenceHost { return {allowed: false, reason_code: "research_evidence_host_required", reason: "Native research completion needs the source-selected Python adapter context; use the installed LoopX entrypoint."}; } + if (this.child) { + throw new Error("ResearchTerminalEvidenceHost.qualify() cannot run while a child host is already active"); + } this.child = spawn(python, ["-m", "loopx.capabilities.explore.research_snapshot_host"], { stdio: ["pipe", "pipe", "pipe"], env: {...process.env, PYTHONPATH: fileURLToPath(new URL("../../../", import.meta.url))}, }); this.exited = new Promise(resolve => this.child!.once("close", () => resolve())); this.child.on("error", () => {}); this.child.stdin.on("error", () => {}); this.child.stderr.resume(); - const replies = createInterface({input: this.child.stdout})[Symbol.asyncIterator](); + const rl = createInterface({input: this.child.stdout}); + const replies = rl[Symbol.asyncIterator](); this.child.stdin.write(JSON.stringify({runtime_root: this.root, goal_id: this.goal, graph: graph ?? {}, harness: harness ?? {}, agent_id: context.actor_agent_id ?? context.todo.claimed_by, todos: context.todos.map(todo => Object.fromEntries([ @@ -84,7 +88,10 @@ export class ResearchTerminalEvidenceHost { } return qualifyResearchCompletion({frontier: snapshot.frontier, todo: context.todo, actor_agent_id: context.actor_agent_id, goal_id: context.goal_id}); - } finally {clearTimeout(timer);} + } finally { + clearTimeout(timer); + rl.close(); + } }; current(): boolean { @@ -95,11 +102,31 @@ export class ResearchTerminalEvidenceHost { async close(): Promise { if (this.child) { - this.child.stdin.end("release\n"); - // The host exits after releasing its kernel lock. A bounded forced exit - // also closes the descriptors if its process cannot finish normally. - const timer = setTimeout(() => this.child?.kill(), 1000); - try {await this.exited;} finally {clearTimeout(timer);} + const child = this.child; + const exited = this.exited; + try { + child.stdin.end("release\n"); + } catch { + // Best-effort pipe close before waiting/escalating. + } + // The host exits after releasing its kernel lock. Escalate from SIGTERM + // to SIGKILL so close() cannot hang if Python blocks or ignores SIGTERM. + const termTimer = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM"); + }, 1000); + const killTimer = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + }, 2000); + try { + await exited; + } finally { + clearTimeout(termTimer); + clearTimeout(killTimer); + if (this.child === child) { + this.child = null; + this.exited = null; + } + } } } } diff --git a/loopx/control_plane/collaboration/inbox.py b/loopx/control_plane/collaboration/inbox.py index 0ed5db85a9..4acd4ad2f2 100644 --- a/loopx/control_plane/collaboration/inbox.py +++ b/loopx/control_plane/collaboration/inbox.py @@ -603,15 +603,3 @@ def reply_status(root, row, *, include_result_key=None, observe_result=None): item["verification"] = "reconciled_after_restart" result.append(item) return result - - -def prior_result_delivered(path, reply): - """Ordered transport: a newer update cannot race an uncertain earlier send.""" - from ..effect_runtime import effect_runtime_result - - previous = reply.get("previous_result_key") - state_path = path.with_name(previous + ".delivery.json") if previous else None - delivery = _read(state_path) if state_path and state_path.exists() else None - return effect_runtime_result("collaboration.result.delivery_ready", { - "result": reply, "previous_delivery": delivery, - })["ready"] diff --git a/loopx/control_plane/coordination/handoff_mode_facts.ts b/loopx/control_plane/coordination/handoff_mode_facts.ts index cdad54d7c9..4e0311f3f8 100644 --- a/loopx/control_plane/coordination/handoff_mode_facts.ts +++ b/loopx/control_plane/coordination/handoff_mode_facts.ts @@ -3,24 +3,12 @@ import type {JsonObject} from "../effect_program.ts"; import {requireJsonObject} from "../runtime_decode.ts"; import {parseIsoTimestamp} from "../runtime_timestamp.ts"; import {leaseIsActive, TASK_LEASE_SCHEMA_VERSION} from "../work_items/task_lease_acquire.ts"; -import {HANDOFF_MODES, type HandoffMode} from "./handoff_mode_policy.ts"; +import {type HandoffMode} from "./handoff_mode_policy.ts"; export type PersistedHandoffMode = | {kind: "valid"; value: HandoffMode} | {kind: "invalid"; value: string}; -export function persistedHandoffMode(value: unknown): PersistedHandoffMode { - const text = value == null ? "" : String(value).trim(); - if (!text) return {kind: "valid", value: "legacy"}; - const mode = HANDOFF_MODES.find(mode => mode === text); - return mode ? {kind: "valid", value: mode} : {kind: "invalid", value: text}; -} - -export function previousModeFields(mode: PersistedHandoffMode): JsonObject { - return {previous_mode: mode.value, previous_mode_valid: mode.kind === "valid", - ...(mode.kind === "invalid" ? {previous_mode_error_code: "invalid_handoff_mode"} : {})}; -} - export interface HandoffQuiescence { claimed_todos: JsonObject[]; active_leases: JsonObject[]; diff --git a/loopx/control_plane/coordination/local_authority_shadow.ts b/loopx/control_plane/coordination/local_authority_shadow.ts index 05316f5a54..5527f45939 100644 --- a/loopx/control_plane/coordination/local_authority_shadow.ts +++ b/loopx/control_plane/coordination/local_authority_shadow.ts @@ -722,28 +722,6 @@ export interface ValidatedShadowLineage { write_classes: string[]; } -/** The caller holds its primary partition lock. This is existing-only and - * never takes M or writes a cursor: management cannot complete a transition - * while that primary lock is held, and a changed binding still fails closed. - */ -export async function readProvenShadowSequence( - runtimeRoot: string, goalId: string, partition: ShadowPartition, expectedLineageId: string, - expectedGoalRef: unknown = null, -): Promise { - const binding = await requireShadowCaptureBinding(runtimeRoot, goalId); - if (expectedGoalRef === null) { - requireLineage(shadowBindingGoalRef(binding) === null, "legacy_goal_binding"); - } else { - requireShadowBindingGoalRef(binding, expectedGoalRef, goalId); - } - requireLineage(binding.capture_lineage_id === expectedLineageId, "stale_generation"); - const store = new FileAuthorityStore(join(runtimeRoot, "authority-shadow", "file-v0"), goalId, { existingOnly: true }); - const lineage = await loadValidatedShadowLineage(store, runtimeRoot, goalId, binding); - const current = await requireShadowCaptureBinding(runtimeRoot, goalId); - requireLineage(canonicalAuthorityBytes(binding).equals(canonicalAuthorityBytes(current)), "stale_generation"); - return lineage.last_sequences[partition]; -} - /** Validate the exact bootstrap, every transaction, and the final readback. * The caller owns maintenance exclusion; this function never takes M. */ diff --git a/loopx/control_plane/coordination/remote_authority_policy.ts b/loopx/control_plane/coordination/remote_authority_policy.ts index 79b09459e6..77f1b17e23 100644 --- a/loopx/control_plane/coordination/remote_authority_policy.ts +++ b/loopx/control_plane/coordination/remote_authority_policy.ts @@ -96,8 +96,10 @@ export function decodeRemoteAuthorityPolicy(value: unknown): JsonObject { export function remoteAuthorityPolicyAdmission(policy: JsonObject, credential: string, request: RemoteAuthorityRequest, mode: RemoteAuthorityMode = "execute"): RemoteAuthorityAdmission { const digest = createHash("sha256").update(credential).digest(); - const principal = (policy.principals as JsonObject[]).find(p => - timingSafeEqual(Buffer.from(String(p.credential_sha256), "hex"), digest)); + const principal = (policy.principals as JsonObject[]).find(p => { + const candidate = Buffer.from(String(p.credential_sha256), "hex"); + return candidate.length === digest.length && timingSafeEqual(candidate, digest); + }); if (!principal) return {status: "rejected", reason_code: "principal_unauthenticated"}; const scope = (policy.scopes as JsonObject[]).find(s => sameScope(s, request)); const scoped = policy.schema_version === REMOTE_AUTHORITY_SCOPED_READ_POLICY; diff --git a/loopx/control_plane/coordination/shadow_drain_files.ts b/loopx/control_plane/coordination/shadow_drain_files.ts index fcdf9bcf57..93d8099e4d 100644 --- a/loopx/control_plane/coordination/shadow_drain_files.ts +++ b/loopx/control_plane/coordination/shadow_drain_files.ts @@ -1,7 +1,7 @@ /** Filesystem effects for native drain. Receipt proof, not a cursor or filename, * authorizes cleanup. All callers hold the shadow maintenance guard. */ import {spawn, type ChildProcessWithoutNullStreams} from "node:child_process"; -import {createInterface} from "node:readline"; +import {createInterface, type Interface as ReadlineInterface} from "node:readline"; import {lstat, readFile, readdir, unlink} from "node:fs/promises"; import {join} from "node:path"; import {fileURLToPath} from "node:url"; @@ -94,6 +94,7 @@ export async function reclaimDrainFiles(files: [string, string][], afterUnlink?: export class DrainKernelLockHost { private readonly python: string; private child: ChildProcessWithoutNullStreams | null = null; + private rl: ReadlineInterface | null = null; private replies: AsyncIterator | null = null; private exited: Promise | null = null; constructor(python: string) {this.python = python;} @@ -107,7 +108,8 @@ export class DrainKernelLockHost { this.child.on("error", () => {}); // The closed reply stream reports an unavailable host. this.child.stdin.on("error", () => {}); this.child.stderr.resume(); - this.replies = createInterface({input: this.child.stdout})[Symbol.asyncIterator](); + this.rl = createInterface({input: this.child.stdout}); + this.replies = this.rl[Symbol.asyncIterator](); } let timer: ReturnType | undefined; try { @@ -119,6 +121,9 @@ export class DrainKernelLockHost { ]); if (reply === "failed") throw new ShadowLineageError("shadow_lock_host_unavailable"); return reply; + } catch { + await this.close(); + throw new ShadowLineageError("shadow_lock_host_unavailable"); } finally {clearTimeout(timer);} } @@ -127,13 +132,31 @@ export class DrainKernelLockHost { if (state !== "held") throw new ShadowLineageError(state === "busy" ? "primary_writer_busy" : "shadow_lock_host_unavailable"); try {return await operation();} finally { - if (await this.command("release") !== "released") throw new ShadowLineageError("shadow_lock_host_unavailable"); + if (await this.command("release") !== "released") { + throw new ShadowLineageError("shadow_lock_host_unavailable"); + } } } async close(): Promise { - if (this.child) { - this.child.stdin.end(); this.child.kill(); await this.exited; + const child = this.child; + const exited = this.exited; + this.rl?.close(); + this.rl = null; + this.replies = null; + if (child) { + try { child.stdin.end(); } catch {} + if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM"); + const killTimer = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + }, 1000); + try {await exited;} finally { + clearTimeout(killTimer); + if (this.child === child) { + this.child = null; + this.exited = null; + } + } } } } diff --git a/loopx/control_plane/effect_runtime.py b/loopx/control_plane/effect_runtime.py index e4f1fda620..4da59550d0 100644 --- a/loopx/control_plane/effect_runtime.py +++ b/loopx/control_plane/effect_runtime.py @@ -1,5 +1,6 @@ from __future__ import annotations +import errno import hashlib import json import math @@ -611,23 +612,50 @@ def _recorded_pid_alive(value: object) -> bool | None: return None -def _reap_exited_runtime_child(info: Mapping[str, Any] | None) -> None: +def _reap_exited_runtime_child(info: Mapping[str, Any] | None) -> bool: """Let a dead directly spawned child fail the next non-signaling probe. A stopped child can remain a zombie until its Python parent reaps it; - ``kill(pid, 0)`` still reports that zombie as present. This helper does - nothing for a live child or a runtime owned by another process. + ``kill(pid, 0)`` still reports that zombie as present. Returns ``True`` + only when POSIX ``waitpid`` confirms ``ECHILD`` (the target is not a child + of this process), and ``False`` otherwise. """ if os.name == "nt" or not isinstance(info, Mapping): - return + return False pid = info.get("pid") if isinstance(pid, bool) or not isinstance(pid, int) or pid <= 0: - return + return False try: os.waitpid(pid, os.WNOHANG) - except (ChildProcessError, OSError): - pass + except ChildProcessError: + return True + except OSError as exc: + return exc.errno == errno.ECHILD + return False + + +def _linux_thread_group_is_zombie(pid: int) -> bool: + """Return True only when every Linux thread in ``pid`` has exited to ``Z``. + + Detached runtimes spawned by short-lived CLI subprocesses reparent to + container PID 1 or a subreaper that may not reap orphans while running. + A zombie thread-group leader with any live worker thread returns False. + """ + if sys.platform != "linux": + return False + task_dir = Path("/proc") / str(pid) / "task" + try: + tids = os.listdir(task_dir) + if not tids: + return False + for tid in tids: + stat_text = (task_dir / tid / "stat").read_text(encoding="utf-8") + if stat_text.rsplit(")", 1)[1].split()[0] != "Z": + return False + return set(os.listdir(task_dir)) <= set(tids) + except (OSError, IndexError, ValueError): + return False def _start_lock_holder_pid(path: Path) -> int | None: @@ -927,8 +955,10 @@ def _stop_effect_runtime( if wait_for_process_exit: if isinstance(pid, bool) or not isinstance(pid, int) or pid <= 0: break - _reap_exited_runtime_child(info) - if not _pid_is_alive(pid): + not_caller_child = _reap_exited_runtime_child(info) + if not _pid_is_alive(pid) or ( + not_caller_child and _linux_thread_group_is_zombie(pid) + ): stopped = True break # A zombie leader can still have threads writing into the namespace. diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index a96846a9e7..91cf79b146 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -648,7 +648,6 @@ export function createEffectRuntimeHandlers( ["collaboration.conversation.request", lazyHandler(() => import("./collaboration/conversation_binding.ts"), ({planBoundConversationRequest}) => planBoundConversationRequest)], ["collaboration.conversation.agent_target", lazyHandler(() => import("./collaboration/conversation_binding.ts"), ({resolveConversationAgentTarget}) => resolveConversationAgentTarget)], ["collaboration.peer.context_access", lazyHandler(() => import("./collaboration/peer_context.ts"), ({requirePeerContextAccess}) => requirePeerContextAccess)], - ["collaboration.source.recipients", lazyHandler(() => import("./collaboration/source_grants.ts"), ({resolveSourceRecipients}) => resolveSourceRecipients)], ["collaboration.source.context_authority", lazyHandler(() => import("./collaboration/source_grants.ts"), ({resolveSourceContextAuthority}) => resolveSourceContextAuthority)], ["collaboration.source.ingress", lazyHandler(() => import("./collaboration/source_grants.ts"), ({validateSourceIngress}) => validateSourceIngress)], ["collaboration.source.execution_bindings", lazyHandler(() => import("./collaboration/source_grants.ts"), ({sourceExecutionBindings}) => sourceExecutionBindings)], diff --git a/loopx/control_plane/goals/acceptance.py b/loopx/control_plane/goals/acceptance.py index 27efca2718..aac272bd79 100644 --- a/loopx/control_plane/goals/acceptance.py +++ b/loopx/control_plane/goals/acceptance.py @@ -289,21 +289,6 @@ def _criterion_effects(criteria: list[dict[str, Any]]) -> list[dict[str, Any]]: ] -def goal_task_validation_files_current( - *, registry_path: Path, runtime_root: str, goal_id: str, agent_id: str, todo_id: str, -) -> bool: - """Check declared validator assets without executing output validation.""" - registry_path, _, route = _routing(registry_path, goal_id, runtime_root, agent_id) - route["todo_id"] = todo_id - basis = _result(_INSPECT_METHOD, route).get("completion_requirements") - if not isinstance(basis, dict) or not basis.get("criteria"): - return False - return validation_effect_files_current( - effects=_criterion_effects(basis["criteria"]), registry_path=registry_path, - goal_id=goal_id, - ) - - def validation_effect_files_current( *, effects: list[dict[str, Any]], registry_path: Path, goal_id: str, delivery_workspace: Mapping[str, Any] | None = None, @@ -328,29 +313,6 @@ def validation_effect_files_current( return True -def validate_goal_task_acceptance( - *, registry_path: Path, runtime_root: str, goal_id: str, agent_id: str, todo_id: str, -) -> dict[str, Any]: - """Read-only Turn validator for a task's current owner-pinned criteria. - - Completion still runs its own fresh validation and atomic TS commit. This - entrypoint cannot accept supplied commands, pass flags or saved receipts. - """ - registry_path, _, route = _routing(registry_path, goal_id, runtime_root, agent_id) - route["todo_id"] = todo_id - basis = _result(_INSPECT_METHOD, route).get("completion_requirements") - if not isinstance(basis, dict) or not basis.get("criteria"): - raise ValueError("delegated task requires configured owner-bound checks") - results = run_goal_acceptance_effects( - effects=_criterion_effects(basis["criteria"]), - registry_path=registry_path, goal_id=goal_id, - ) - current = _result(_INSPECT_METHOD, route).get("completion_requirements") - if current != basis: - raise ValueError("delegated task acceptance changed during validation") - return {"passed": all(row["passed"] for row in results), "results": results} - - def configure_goal_acceptance( *, registry_path: Path, diff --git a/loopx/control_plane/goals/acceptance_contract.ts b/loopx/control_plane/goals/acceptance_contract.ts index 267341d58b..e6a09a69cb 100644 --- a/loopx/control_plane/goals/acceptance_contract.ts +++ b/loopx/control_plane/goals/acceptance_contract.ts @@ -441,13 +441,6 @@ export function readGoalAcceptance(head: JsonObject, goalId: string): Acceptance return authority.owner_matches ? authority.state : null; } -/** Private same-snapshot host inputs for read-only freshness observation. - * They contain only already pinned files and oracle refs, never commands or - * a new result. Public summaries keep using the acceptance projection. */ -export function goalAcceptanceOracleObservationBasis(head: JsonObject, goalId: string): JsonObject | null { - return new GoalAcceptanceRead(head, goalId).oracleBasis(); -} - export function bindGoalAcceptanceStateOwner( state: AcceptanceState, ownerGoalRef: WireExactGoalRef, diff --git a/loopx/control_plane/goals/checkpoint_commit.ts b/loopx/control_plane/goals/checkpoint_commit.ts index 0802eb25bf..4fdbbcb904 100644 --- a/loopx/control_plane/goals/checkpoint_commit.ts +++ b/loopx/control_plane/goals/checkpoint_commit.ts @@ -84,7 +84,8 @@ export function inspectCheckpointReplay(value: unknown): JsonObject { const goal = goalPathSegment(request.goal_id); const runsDir = join(root, "goals", goal, "runs"); const rows = indexBytes(join(runsDir, "index.jsonl")).toString("utf8").split(/\r?\n/).filter(line => line.trim()); - if (!rows.some(line => canonicalAuthoritySha256(JSON.parse(line)) === canonicalAuthoritySha256(prior))) { + const priorDigest = canonicalAuthoritySha256(prior); + if (!rows.some(line => canonicalAuthoritySha256(JSON.parse(line)) === priorDigest)) { unknown("checkpoint replay is not an indexed record"); } return committedArtifacts(prior, runsDir); diff --git a/loopx/control_plane/goals/dreaming.py b/loopx/control_plane/goals/dreaming.py index 83e8561f1e..67db3bfffb 100644 --- a/loopx/control_plane/goals/dreaming.py +++ b/loopx/control_plane/goals/dreaming.py @@ -53,7 +53,8 @@ def compact_dreaming_proposal( classification = str(run.get("classification") or "") if classification not in dreaming_advisory_classifications: return None - raw = run.get("dreaming") if isinstance(run.get("dreaming"), dict) else {} + raw_dreaming = run.get("dreaming") + raw = raw_dreaming if isinstance(raw_dreaming, dict) else {} proposal: dict[str, Any] = { "schema_version": "dreaming_proposal_v0", "classification": classification, diff --git a/loopx/control_plane/goals/goal_vision.py b/loopx/control_plane/goals/goal_vision.py index 7f92bda520..baf7076ce3 100644 --- a/loopx/control_plane/goals/goal_vision.py +++ b/loopx/control_plane/goals/goal_vision.py @@ -200,24 +200,3 @@ def normalize_goal_vision_packet( merge_patch=False, require_path_delta_for_durable_change=False, ) - - -def normalize_goal_vision_update( - packet: dict[str, Any], - *, - goal_id: str, - agent_id: str | None, - existing_agent_vision: dict[str, Any] | None, - merge_patch: bool, - require_path_delta_for_durable_change: bool, -) -> dict[str, Any]: - """Compatibility entry point for the TS-owned Vision preflight.""" - - return prepare_vision_refresh( - packet, - goal_id=goal_id, - agent_id=agent_id, - existing_agent_vision=existing_agent_vision, - merge_patch=merge_patch, - require_path_delta_for_durable_change=require_path_delta_for_durable_change, - ) diff --git a/loopx/control_plane/goals/goal_vision_policy.py b/loopx/control_plane/goals/goal_vision_policy.py index 4a21b350ce..8286202513 100644 --- a/loopx/control_plane/goals/goal_vision_policy.py +++ b/loopx/control_plane/goals/goal_vision_policy.py @@ -50,17 +50,6 @@ def completed_todo_replan_threshold(profile: Any) -> int: return normalize_completed_todo_replan_threshold(profile["replan_after_completed_todos"]) -def normalize_goal_vision_advancement_policy(value: Any) -> str: - candidate = str(value or "").strip().lower().replace("-", "_") - try: - return GoalVisionAdvancementPolicy(candidate).value - except ValueError as exc: - raise ValueError( - "agent_vision.advancement_policy must be one of: " - + ", ".join(GOAL_VISION_ADVANCEMENT_POLICY_CHOICES) - ) from exc - - def goal_vision_repeats_advancement_until_closed(value: Any) -> bool: return ( str(value or "").strip() diff --git a/loopx/control_plane/goals/goal_vision_wait.py b/loopx/control_plane/goals/goal_vision_wait.py index 9cb77db0fa..e859b8fdd4 100644 --- a/loopx/control_plane/goals/goal_vision_wait.py +++ b/loopx/control_plane/goals/goal_vision_wait.py @@ -1,7 +1,5 @@ from __future__ import annotations -import hashlib -import json from typing import Any from ..effect_runtime import effect_runtime_result @@ -47,21 +45,6 @@ def exact_blocked_successor_wait_state(value: Any) -> dict[str, Any]: return candidate -def exact_blocked_successor_frontier_identity(value: Any) -> str | None: - wait = exact_blocked_successor_wait_state(value) - if not wait: - return None - parts = { - "agent_id": str(wait.get("agent_id") or "").strip(), - "reason_code": "exact_blocked_successor", - "selected_todo_id": normalize_todo_id(wait.get("selected_todo_id")), - "resume_when": str(wait.get("resume_when") or "").strip(), - } - return hashlib.sha256( - json.dumps(parts, ensure_ascii=True, sort_keys=True).encode("utf-8") - ).hexdigest()[:16] - - def build_goal_vision_wait_state( *, agent_todo_summary: dict[str, Any] | None, diff --git a/loopx/control_plane/quota/selected_todo_projection.py b/loopx/control_plane/quota/selected_todo_projection.py index 54249077cb..0bcc7e3a70 100644 --- a/loopx/control_plane/quota/selected_todo_projection.py +++ b/loopx/control_plane/quota/selected_todo_projection.py @@ -101,18 +101,6 @@ def selected_todo_projection( } -def first_todo_id_from_items(value: Any) -> str | None: - if not isinstance(value, list): - return None - for item in value: - if not isinstance(item, dict): - continue - todo_id = normalize_todo_id(item.get("todo_id") or item.get("id")) - if todo_id: - return todo_id - return None - - def _compact_selected_todo( item: dict[str, Any], *, diff --git a/loopx/control_plane/quota/settlement_workspace_causality.py b/loopx/control_plane/quota/settlement_workspace_causality.py index 7b785a4721..541dfe9d24 100644 --- a/loopx/control_plane/quota/settlement_workspace_causality.py +++ b/loopx/control_plane/quota/settlement_workspace_causality.py @@ -160,23 +160,6 @@ def build_delivery_workspace_causality( ) -def normalize_delivery_workspace_causality( - value: Any, - *, - todo_id: str | None = None, -) -> dict[str, str] | None: - prepared = _prepared_causality(value if isinstance(value, Mapping) else None) - if prepared is None: - return None - return _causality_result( - _runtime_result( - "normalize", - expected_todo_id=normalize_todo_id(todo_id), - causality=prepared, - ) - ) - - def delivery_workspace_causality_event_fields( causality: Mapping[str, Any] | None, ) -> dict[str, str]: diff --git a/loopx/control_plane/quota/stall_repair.py b/loopx/control_plane/quota/stall_repair.py index c24bfb61a7..d29235b5c0 100644 --- a/loopx/control_plane/quota/stall_repair.py +++ b/loopx/control_plane/quota/stall_repair.py @@ -384,16 +384,3 @@ def stall_repair_payload(repair: dict[str, Any] | None) -> dict[str, Any]: if not isinstance(consistency, dict): return {} return {"todo_decision_scope_consistency": consistency} - - -def stall_repair_suppresses_user_gate_notification( - repair: dict[str, Any] | None, -) -> bool: - return bool( - repair - and repair.get("trigger") - in { - USER_GATE_SCOPE_REPAIR_TRIGGER, - RUNTIME_CAPABILITY_USER_GATE_REPAIR_TRIGGER, - } - ) diff --git a/loopx/control_plane/rollout_receipt_log.ts b/loopx/control_plane/rollout_receipt_log.ts index a02c8464cc..abccaa8dc3 100644 --- a/loopx/control_plane/rollout_receipt_log.ts +++ b/loopx/control_plane/rollout_receipt_log.ts @@ -134,26 +134,6 @@ export function heartbeatReceiptsFromEvents( ); } -/** - * Read the heartbeat receipts this goal persisted for one Agent. - * - * The read mirrors the established non-strict reader: a malformed or - * differently versioned line is skipped rather than allowed to erase or - * manufacture a receipt, and an absent log is `null` because "no receipts yet" - * and "no log yet" are different facts for a caller that must report state. - */ -export async function readGoalHeartbeatReceipts( - runtimeRoot: string, - goalId: string, - agentId?: string | null, -): Promise { - return goalHeartbeatReceiptsFromSnapshot( - await readGoalRolloutEventSnapshot(runtimeRoot, goalId), - goalId, - agentId, - ); -} - export async function heartbeatReceiptStatus(params: { runtimeRoot: string; goalId: string; diff --git a/loopx/control_plane/runtime/shared_runtime_refresh_projection.py b/loopx/control_plane/runtime/shared_runtime_refresh_projection.py index 5c929e9cbc..5583062ec4 100644 --- a/loopx/control_plane/runtime/shared_runtime_refresh_projection.py +++ b/loopx/control_plane/runtime/shared_runtime_refresh_projection.py @@ -7,9 +7,6 @@ from typing import Any from ..goals.goal_vision import compact_goal_vision_packet -from .runtime_projection_route import ( - resolve_runtime_projection_route, -) from .runtime_projection_writer import write_compact_runtime_projection @@ -17,25 +14,6 @@ ISO_LIKE_TIMESTAMP_RE = re.compile(r"[0-9TZ:+.\-]{10,64}") -def registered_shared_runtime_root( - *, - registry_path: Path, - goal_id: str, - source_runtime_root: Path, -) -> Path | None: - """Compatibility wrapper over the first-class runtime projection route.""" - - route = resolve_runtime_projection_route( - registry_path=registry_path, - goal_id=goal_id, - source_runtime_root=source_runtime_root, - ) - if route.get("status") != "resolved": - return None - target = str(route.get("target_runtime_root") or "").strip() - return Path(target) if target else None - - def build_shared_runtime_projection( *, record: dict[str, Any], diff --git a/loopx/control_plane/scheduler/scheduler_hint.py b/loopx/control_plane/scheduler/scheduler_hint.py index 356ea03b99..f8d94cae55 100644 --- a/loopx/control_plane/scheduler/scheduler_hint.py +++ b/loopx/control_plane/scheduler/scheduler_hint.py @@ -406,17 +406,3 @@ def build_app_automation_scheduler_failure_hint( def build_codex_app_scheduler_ack_hint(**kwargs: Any) -> dict[str, Any]: return _followup("legacy_ack", kwargs) - - -def build_codex_app_scheduler_failure_hint(**kwargs: Any) -> dict[str, Any]: - return _followup("legacy_failure", kwargs) - - -def build_codex_app_scheduler_fallback_hint( - *, - goal_id: Any, - agent_id: Any, - automation_id: Any, - turn_instance_id: Any = "${LOOPX_TURN:?}", -) -> dict[str, Any]: - return _followup("fallback", dict(locals())) diff --git a/loopx/control_plane/scheduler/state.py b/loopx/control_plane/scheduler/state.py index cfeecac179..d4483ccec8 100644 --- a/loopx/control_plane/scheduler/state.py +++ b/loopx/control_plane/scheduler/state.py @@ -96,13 +96,6 @@ def scheduler_rrule_interval_minutes(value: Any) -> int | None: return interval -def normalize_scheduler_host_update_failure(value: Any) -> dict[str, Any] | None: - failure = _operation_result("normalize_failure", value=value) - if failure is not None and not isinstance(failure, dict): - raise RuntimeError("TypeScript scheduler failure must be an object or null") - return failure - - def _failure_list(value: Any, *, operation: str) -> list[dict[str, Any]]: if not isinstance(value, list) or any(not isinstance(item, dict) for item in value): raise RuntimeError(f"TypeScript scheduler {operation} must be an object list") @@ -141,23 +134,6 @@ def retained_scheduler_host_update_failures( ) -def merge_scheduler_host_update_failure( - value: Any, - failure: dict[str, Any], - *, - reference_time: datetime | str | None = None, -) -> list[dict[str, Any]]: - return _failure_list( - _operation_result( - "merge_failure", - value=value, - failure=failure, - reference_time=_reference_time(reference_time), - ), - operation="merged failures", - ) - - def normalize_scheduler_state( state: dict[str, Any], *, diff --git a/loopx/control_plane/scheduler/state_transition_rules.py b/loopx/control_plane/scheduler/state_transition_rules.py index baafcf8942..516e5230f7 100644 --- a/loopx/control_plane/scheduler/state_transition_rules.py +++ b/loopx/control_plane/scheduler/state_transition_rules.py @@ -42,19 +42,6 @@ class MonitorScheduleProjection: cadence_seconds: int | None -def project_settled_replay_schedule(*, observed_host_rrule: Any = None) -> dict[str, Any]: - """Adapt the typed scheduler owner's hold-only replay packet.""" - result = _runtime_result({ - "schema_version": SCHEDULER_STATE_TRANSITION_REQUEST_SCHEMA, - "operation": "settled_replay", - "observed_host_rrule": observed_host_rrule, - }) - hint = result.get("hint") - if result.get("operation") != "settled_replay" or not isinstance(hint, dict): - raise RuntimeError("TypeScript settled scheduler result shape mismatch") - return hint - - def project_monitor_todo_schedule( *, generated_at: str, diff --git a/loopx/control_plane/testing/shadow_drain_fault_process.ts b/loopx/control_plane/testing/shadow_drain_fault_process.ts deleted file mode 100644 index d6a7e3ca62..0000000000 --- a/loopx/control_plane/testing/shadow_drain_fault_process.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** Private-process test driver, never installed as an RPC effect. */ -import {existsSync} from "node:fs"; -import {drainShadowOutbox} from "../coordination/shadow_drain.ts"; -let input = ""; -for await (const bytes of process.stdin) input += bytes; -const request = JSON.parse(input); -const phase = process.argv[2] === "between_unlinks" ? "after_unlink" : process.argv[2]; -// Without a release path the observed barrier is terminal (a crash window). -// With one, the same real batch continues after the caller resumes it, which is -// what a management interleaving needs. -const release = process.argv[3]; -const result = await drainShadowOutbox(request, {afterEffect: async observed => { - if (observed === phase) { - process.stdout.write(`BARRIER ${JSON.stringify({native_pid: process.pid, request})}\n`); - if (release === undefined) await new Promise(() => {setInterval(() => {}, 1000);}); - else while (!existsSync(release)) await new Promise(resolve => {setTimeout(resolve, 10);}); - } -}}); -process.stdout.write(JSON.stringify(result) + "\n"); diff --git a/loopx/control_plane/todos/active_state_editing.py b/loopx/control_plane/todos/active_state_editing.py index 4d943ee363..ae6b0363c6 100644 --- a/loopx/control_plane/todos/active_state_editing.py +++ b/loopx/control_plane/todos/active_state_editing.py @@ -8,7 +8,6 @@ TODO_STATUS_OPEN, build_todo_id, normalize_todo_status, - parse_todo_metadata_line, todo_done_for_status, todo_marker_for_status, ) @@ -54,21 +53,6 @@ def find_todo_block( return None -def todo_metadata_would_change( - lines: list[str], - block: dict[str, Any], - metadata_line: str | None, -) -> bool: - if not metadata_line: - return False - start = int(block["start"]) - end = int(block["end"]) - for index in range(start + 1, end): - if parse_todo_metadata_line(lines[index]) is not None: - return lines[index] != metadata_line - return True - - def set_todo_marker(lines: list[str], block: dict[str, Any], status: str) -> bool: marker = todo_marker_for_status(status) index = int(block["start"]) diff --git a/loopx/control_plane/todos/completion_validation.py b/loopx/control_plane/todos/completion_validation.py index 1543377872..78d69e2cb1 100644 --- a/loopx/control_plane/todos/completion_validation.py +++ b/loopx/control_plane/todos/completion_validation.py @@ -22,10 +22,6 @@ build_completion_policy_request, linked_successors_from_state, ) -from .completion_transaction import ( - reduce_todo_completion_transaction, - todo_completion_source_snapshot, -) from .completion_validation_projection import ( completion_validation_declaration, completion_validation_declaration_sha256, @@ -479,128 +475,6 @@ def resolve_private_completion_validation_declaration( return declaration -def run_completion_validation_gate_with_source( - *, - state_file: Path, - todo_id: str, - role: str | None, - registry_path: Path, - goal_id: str, - dry_run: bool, - no_followup: bool = False, - completion_turn_key: str | None = None, - completion_identity_source: str | None = None, - requested_has_successor: bool = False, - completion_policy_facts: Mapping[str, Any] | None = None, - requested_successor_todo_ids: list[str] | None = None, - completion_delivery_workspace: Mapping[str, Any] | None = None, - completion_validation_workspace_path: Path | None = None, -) -> dict[str, Any]: - """Run the caller-approved completion validation gate, OUTSIDE the mutation lock. - - Returns one envelope containing the source snapshot and typed transaction. - ``failure`` is a ``validation_blocked_completion`` payload when a declared - command does not pass, otherwise ``None``. The caller returns failures - unchanged so durable writeback and quota spend are skipped. Dry runs and - terminal replays do not execute validation. This function is read-only - w.r.t. the state file and safe to call before acquiring the mutation lock, - so a multi-second validation command does not block concurrent Todo writes. - """ - from ...history import load_registry - from ...registry import registry_goals - from ..goals.legacy_event_source import require_no_legacy_todo_events - goal = next((item for item in registry_goals(load_registry(registry_path)) if item.get("id") == goal_id), {}) - require_no_legacy_todo_events(goal, state_path=state_file) - projection_source = "materialized" - source_authority: dict[str, Any] | None = None - todo = _materialized_todo_item(state_file=state_file, todo_id=todo_id, role=role) - if todo is None: - return {"todo": None, "validation": None, "failure": None, - "source_authority": None, "source_snapshot": None, "transaction": None} - source_snapshot = todo_completion_source_snapshot(todo) - completion_policy_source = None - if completion_policy_facts is not None: - try: - lines = state_file.read_text(encoding="utf-8").splitlines() - except FileNotFoundError: - lines = [] - completion_policy_source = completion_policy_source_from_state( - registry_path=registry_path, - goal_id=goal_id, - lines=lines, - successor_todo_ids=requested_successor_todo_ids or [], - facts=completion_policy_facts, - ) - transaction = reduce_todo_completion_transaction( - todo=todo, - projection_source=projection_source, - completion_turn_key=completion_turn_key, - no_followup=no_followup, - dry_run=dry_run, - completion_identity_source=completion_identity_source, - goal_id=goal_id, - todo_id=todo_id, - requested_has_successor=requested_has_successor, - validation_receipt=None, - # The coarse reducer returns policy success or typed failure as data. - # The public writer consumes that projection only after actor and lease - # admission, preserving legacy error priority without a second IPC. - completion_policy_request=completion_policy_source, - ) - completion_validation = None - if transaction["decision"] == "execute_validation": - effect = transaction["validation_effect"] - completion_validation = run_declared_completion_validation_effect( - effect=effect, - registry_path=registry_path, - goal_id=goal_id, - delivery_workspace=completion_delivery_workspace, - validation_workspace_path=completion_validation_workspace_path, - ) - if completion_validation is None: - raise RuntimeError("Todo completion validation effect produced no receipt") - transaction = reduce_todo_completion_transaction( - todo=todo, - projection_source=projection_source, - completion_turn_key=completion_turn_key, - no_followup=no_followup, - dry_run=dry_run, - completion_identity_source=completion_identity_source, - goal_id=goal_id, - todo_id=todo_id, - requested_has_successor=requested_has_successor, - validation_receipt=completion_validation, - completion_policy_request=completion_policy_source, - ) - if transaction["decision"] != "reject": - return { - "failure": None, - "source_authority": source_authority, - "source_snapshot": source_snapshot, - "completion_policy_source": completion_policy_source, - "transaction": transaction, - } - failure_payload = transaction["failure"] - completion_validation = dict(failure_payload["validation_receipt"]) - failure = { - "ok": False, - "dry_run": dry_run, - "completed": False, - "goal_id": goal_id, - "todo_id": todo_id, - "changed": False, - "validation": completion_validation, - "validation_blocked_completion": True, - } - return { - "failure": failure, - "source_authority": source_authority, - "source_snapshot": source_snapshot, - "completion_policy_source": completion_policy_source, - "transaction": transaction, - } - - def completion_policy_source_from_state( *, registry_path: Path, diff --git a/loopx/control_plane/todos/monitor_metadata.py b/loopx/control_plane/todos/monitor_metadata.py index b5f2476539..78fb6f8be7 100644 --- a/loopx/control_plane/todos/monitor_metadata.py +++ b/loopx/control_plane/todos/monitor_metadata.py @@ -51,19 +51,3 @@ def require_monitor_metadata_scope( or not isinstance(result.get("metadata"), dict)): raise RuntimeError("TypeScript monitor metadata result shape mismatch") return result["metadata"] - - -def require_locked_monitor_gate_scope(*, state_text: str, todo: dict[str, Any], - observation: dict[str, Any] | None, agent_id: str | None) -> None: - """Transport the caller-held complete legacy snapshot to the typed owner.""" - if observation is None: - raise ValueError("gate scope guard requires a Monitor observation") - effect = observation.get("monitor_effect_id") - if effect and todo.get("monitor_effect_id") == effect: - return # The normal metadata planner still verifies exact replay fields. - from .active_state_todo_parser import parse_todo_source - from .decision_scope import todo_gate_scope_projections - items, _, _ = parse_todo_source(state_text) - scope = todo_gate_scope_projections(items["user"], [todo], agent_id=agent_id)[0] - if scope["state"] == "blocked": - raise ValueError("Monitor observation is blocked by current User gate dependencies") diff --git a/loopx/control_plane/todos/monitor_scope.ts b/loopx/control_plane/todos/monitor_scope.ts index 4689c71d9d..945cf494bd 100644 --- a/loopx/control_plane/todos/monitor_scope.ts +++ b/loopx/control_plane/todos/monitor_scope.ts @@ -13,16 +13,6 @@ export function normalizeMonitorChangeScope(value: unknown): string | null { return MONITOR_SCOPE_PATTERN.test(normalized) ? normalized : null; } -export function requireMonitorChangeScope(value: unknown, label = "material_change_scope"): string { - const normalized = normalizeMonitorChangeScope(value); - if (normalized === null) { - throw new EffectRuntimeRequestError( - `${label} must be a lowercase public-safe token of at most 96 characters`, - ); - } - return normalized; -} - export function monitorChangeScopeDigest(scope: string): string { return createHash("sha256").update(scope, "utf8").digest("hex").slice(0, 24); } @@ -78,13 +68,6 @@ export function parseMonitorScopeGenerations(value: unknown): Map): string { - return [...generations.entries()] - .sort(([left], [right]) => left.localeCompare(right)) - .map(([digest, generation]) => `${digest}:${generation}`) - .join(","); -} - export function monitorScopeGeneration(value: unknown, scope: string): number { return parseMonitorScopeStates(value).get(monitorChangeScopeDigest(scope))?.generation ?? 0; } diff --git a/loopx/control_plane/todos/quota_summary.py b/loopx/control_plane/todos/quota_summary.py index 97f7272266..ea00d6ecbb 100644 --- a/loopx/control_plane/todos/quota_summary.py +++ b/loopx/control_plane/todos/quota_summary.py @@ -626,18 +626,6 @@ def select_quota_todo_source_items( return todo_summary_source_items(selected[1]) if selected is not None else [] -def select_quota_todo_display_views( - canonical_value: Any, - project_asset_value: Any, -) -> dict[str, list[dict[str, Any]]]: - """Select the source once for the quota caller's three consumed displays.""" - from .summary_item import todo_source_display_views - - selected = _select_todo_source(canonical_value, project_asset_value) - return (todo_source_display_views(selected[1]) if selected is not None - else {"summary": [], "planning": [], "terminal": []}) - - def select_planning_inventory_source_items( canonical_value: Any, project_asset_value: Any, diff --git a/loopx/control_plane/todos/todo_semantics.py b/loopx/control_plane/todos/todo_semantics.py index b0f7b29916..104f65e723 100644 --- a/loopx/control_plane/todos/todo_semantics.py +++ b/loopx/control_plane/todos/todo_semantics.py @@ -8,7 +8,6 @@ from ..scheduler.monitor_todo import ( monitor_todo_expires_at, - monitor_todo_has_schedule, monitor_todo_is_actionable_open, monitor_todo_is_due, monitor_todo_is_expired, @@ -231,10 +230,6 @@ def todo_item_next_due_at(item: dict[str, Any]) -> datetime | None: return monitor_todo_next_due_at(item) -def todo_item_has_monitor_schedule(item: dict[str, Any]) -> bool: - return monitor_todo_has_schedule(item) - - def todo_item_expires_at(item: dict[str, Any]) -> datetime | None: return monitor_todo_expires_at(item) diff --git a/loopx/control_plane/todos/todo_summary.py b/loopx/control_plane/todos/todo_summary.py index 79e01182bd..3561c4cfd4 100644 --- a/loopx/control_plane/todos/todo_summary.py +++ b/loopx/control_plane/todos/todo_summary.py @@ -519,30 +519,10 @@ def _task_orchestration_authority(lanes: dict[str, list[dict[str, Any]]], *, rol ("user_blocker_items", TASK_ORCHESTRATION_USER_BLOCKER_FIELDS))}} -def compact_active_next_action_todo_item(item: dict[str, Any]) -> dict[str, Any]: - compact = compact_todo_item(item) - for key in ( - "note", - "evidence", - "reason", - "completed_at", - "updated_at", - "superseded_by", - ): - compact.pop(key, None) - return compact - - def todo_item_task_class(item: dict[str, Any]) -> str: return projection_todo_item_task_class(item) -def count_advancement_todos(items: list[dict[str, Any]]) -> int: - return sum( - 1 for item in items if todo_item_task_class(item) == TODO_TASK_CLASS_ADVANCEMENT - ) - - def todo_item_is_actionable_open(item: dict[str, Any]) -> bool: return projection_todo_item_is_actionable_open(item) diff --git a/loopx/control_plane/turn_driver/session_recovery.py b/loopx/control_plane/turn_driver/session_recovery.py index 52b5cff51b..42b9aa0a60 100644 --- a/loopx/control_plane/turn_driver/session_recovery.py +++ b/loopx/control_plane/turn_driver/session_recovery.py @@ -36,22 +36,6 @@ def build_host_recovery_record(kind: str) -> dict[str, str]: } -def reconcile_failed_turn_retry_request( - request: Mapping[str, Any], - journal: Mapping[str, Any], - *, - session_binding_resolver: SessionBindingResolver | None, -) -> dict[str, Any]: - resolved, _check, error = assess_failed_turn_retry_request( - request, - journal, - session_binding_resolver=session_binding_resolver, - ) - if error is not None: - raise error - return resolved - - def assess_failed_turn_retry_request( request: Mapping[str, Any], journal: Mapping[str, Any], diff --git a/loopx/control_plane/turn_driver/transaction.py b/loopx/control_plane/turn_driver/transaction.py index 2b9fad11e6..fb3445223d 100644 --- a/loopx/control_plane/turn_driver/transaction.py +++ b/loopx/control_plane/turn_driver/transaction.py @@ -1,7 +1,7 @@ """Typed LoopX Turn transaction planning and receipt validation.""" from __future__ import annotations -from .turn_contract_generated import LoopXTurnResultKind # compatibility re-export +from .turn_contract_generated import LoopXTurnResultKind as LoopXTurnResultKind # compatibility re-export import json from collections.abc import Mapping diff --git a/loopx/control_plane/turn_driver/turn_contract_generated.py b/loopx/control_plane/turn_driver/turn_contract_generated.py index 1a12d54f5e..012ce066a8 100644 --- a/loopx/control_plane/turn_driver/turn_contract_generated.py +++ b/loopx/control_plane/turn_driver/turn_contract_generated.py @@ -3,6 +3,7 @@ SHA256: be2734e9f192e8d78598c06e338dafc72ed71bb0251a2ec3784cb8421c4fd78d""" from __future__ import annotations from enum import Enum +from typing import Any class LoopXTurnResultKind(str, Enum): VALIDATED_PROGRESS = "validated_progress" @@ -38,7 +39,7 @@ class LoopDisposition(str, Enum): REPLAN = "replan" TERMINAL = "terminal" -TURN_CONTROLLER_CONTRACT = {'schema_version': 'loop_turn_controller_decision_contract_v0', +TURN_CONTROLLER_CONTRACT: dict[str, Any] = {'schema_version': 'loop_turn_controller_decision_contract_v0', 'evaluation': 'ordered_checks_then_first_matching_return', 'qualification': {'receipt': 'TypeScript qualifyExecution; material settlement, durable ' 'completion and host failure qualification remain admission ' @@ -282,7 +283,7 @@ class LoopDisposition(str, Enum): 'REPLAN': 'replan', 'TERMINAL': 'terminal'}}} -ROUTE_TO_DISPOSITION = TURN_CONTROLLER_CONTRACT['route_projection'] +ROUTE_TO_DISPOSITION: dict[str, str | None] = TURN_CONTROLLER_CONTRACT['route_projection'] def project_turn_route(route: LoopXTurnRoute) -> LoopDisposition: """Public total route projection; contract_error explicitly rejects.""" diff --git a/loopx/control_plane/work_items/attention_item.py b/loopx/control_plane/work_items/attention_item.py index bc09e67090..94269ec4de 100644 --- a/loopx/control_plane/work_items/attention_item.py +++ b/loopx/control_plane/work_items/attention_item.py @@ -38,7 +38,7 @@ def attention_item( missing_gates=missing_gates, next_handoff_condition=next_handoff_condition, ) - item = { + item: dict[str, Any] = { "goal_id": goal_id, "status": status, "waiting_on": waiting_on, @@ -70,8 +70,8 @@ def attention_item( if dreaming_proposal: dreaming_lane_badge = compact_dreaming_lane_badge(dreaming_proposal) item["dreaming_proposal"] = dreaming_proposal - item["project_asset"]["dreaming_proposal"] = dreaming_proposal + project_asset["dreaming_proposal"] = dreaming_proposal if dreaming_lane_badge: item["dreaming_lane_badge"] = dreaming_lane_badge - item["project_asset"]["dreaming_lane_badge"] = dreaming_lane_badge + project_asset["dreaming_lane_badge"] = dreaming_lane_badge return item diff --git a/loopx/control_plane/work_items/delivery_outcome.py b/loopx/control_plane/work_items/delivery_outcome.py index 221af1de1c..c126559b07 100644 --- a/loopx/control_plane/work_items/delivery_outcome.py +++ b/loopx/control_plane/work_items/delivery_outcome.py @@ -229,11 +229,6 @@ def require_delivery_outcome(value: Any) -> DeliveryOutcome: return outcome -def delivery_outcome_value(value: Any) -> str | None: - outcome = normalize_delivery_outcome(value) - return outcome.value if outcome else None - - def normalize_delivery_turn_kind(value: Any) -> DeliveryTurnKind | None: if isinstance(value, DeliveryTurnKind): return value diff --git a/loopx/quota.py b/loopx/quota.py index 0c8bbfbfb6..bc9c60679c 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -36,7 +36,6 @@ MONITOR_DUE_ITEM_LIMIT, # noqa: F401 ) from .control_plane.quota.monitor_poll import ( - QUOTA_MONITOR_POLL_CLASSIFICATION as QUOTA_MONITOR_POLL_CLASSIFICATION, build_quota_monitor_poll_event as build_quota_monitor_poll_event, record_quota_monitor_poll_for_decision, resolve_monitor_poll_target, @@ -113,7 +112,6 @@ _PUBLIC_COMPAT_REEXPORTS = { "AUTONOMOUS_CANDIDATE_CONTEXT_FIELDS": "loopx.control_plane.quota.policy_constants", "MONITOR_DUE_ITEM_LIMIT": "loopx.control_plane.quota.policy_constants", - "QUOTA_MONITOR_POLL_CLASSIFICATION": "loopx.control_plane.quota.monitor_poll", "build_quota_monitor_poll_event": "loopx.control_plane.quota.monitor_poll", "render_quota_markdown": "loopx.presentation.renderers.quota_markdown", "render_quota_scheduler_ack_markdown": "loopx.presentation.renderers.quota_markdown", diff --git a/loopx/semantics/project_registry_io.py b/loopx/semantics/project_registry_io.py index 773f264e2a..6b7e661478 100644 --- a/loopx/semantics/project_registry_io.py +++ b/loopx/semantics/project_registry_io.py @@ -286,6 +286,12 @@ def visit_AnnAssign(self, node: ast.AnnAssign) -> None: self.generic_visit(node) def visit_With(self, node: ast.With) -> None: + self._visit_with(node) + + def visit_AsyncWith(self, node: ast.AsyncWith) -> None: + self._visit_with(node) + + def _visit_with(self, node: ast.With | ast.AsyncWith) -> None: handle_roles: dict[str, _PathRole] = {} for item in node.items: context = item.context_expr @@ -312,8 +318,6 @@ def visit_With(self, node: ast.With) -> None: self.visit(statement) self.handles.pop() - visit_AsyncWith = visit_With - def visit_Call(self, node: ast.Call) -> None: name = _terminal_name(node.func) if name in APPROVED_READ_APIS: diff --git a/loopx/status.py b/loopx/status.py index cbb5528f2f..01d7998acf 100644 --- a/loopx/status.py +++ b/loopx/status.py @@ -11,17 +11,6 @@ from .control_plane import compact_control_plane_policy from .control_plane.coordination.local_authority import CanonicalTodoSnapshot as _CanonicalTodoSnapshot from .control_plane.effect_runtime import effect_runtime_request_scope -# Refs #4447: one definition for each carrier this facade used to restate. The -# owner is the projection that feeds the value into a read model; `loopx/status.py` -# keeps exporting the established public name as an identity alias instead of -# writing the same literal a second time, so a change in the owner cannot quietly -# diverge from a change here. -from .control_plane.status.active_state_projection import ( - BACKLOG_HYGIENE_BULLET_PATTERN as BACKLOG_HYGIENE_BULLET_PATTERN, - BACKLOG_HYGIENE_HINT_PATTERN as BACKLOG_HYGIENE_HINT_PATTERN, - BACKLOG_HYGIENE_SECTION_HEADINGS as BACKLOG_HYGIENE_SECTION_HEADINGS, - SECTION_HEADING_PATTERN as SECTION_HEADING_PATTERN, -) from .control_plane.status.adapter_status_vocabulary import ( CONNECTED_ADAPTER_STATUSES as CONNECTED_ADAPTER_STATUSES, CONNECTED_DELIVERY_ADAPTER_STATUSES as CONNECTED_DELIVERY_ADAPTER_STATUSES, @@ -33,20 +22,12 @@ # instead of restating the values. from .control_plane.status.autonomous_replan_projection import ( AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD as AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD, - AUTONOMOUS_REPLAN_SCHEMA_VERSION as AUTONOMOUS_REPLAN_SCHEMA_VERSION, - DEAD_MONITOR_REPEAT_SCHEMA_VERSION as DEAD_MONITOR_REPEAT_SCHEMA_VERSION, DEAD_MONITOR_REPEAT_THRESHOLD as DEAD_MONITOR_REPEAT_THRESHOLD, ) from .control_plane.status.collection import ( StatusCollectionContext, collect_status as _collect_status_read_model, ) -from .control_plane.status.contract_projection import ( - MINIMUM_DASHBOARD_STATUS_CONTRACT_SCHEMA_VERSION as MINIMUM_DASHBOARD_STATUS_CONTRACT_SCHEMA_VERSION, - STATUS_CONTRACT_RELOAD_HINT as STATUS_CONTRACT_RELOAD_HINT, - STATUS_CONTRACT_SCHEMA_VERSION as STATUS_CONTRACT_SCHEMA_VERSION, - STATUS_CONTRACT_SIGNAL_LIMIT as STATUS_CONTRACT_SIGNAL_LIMIT, -) from .control_plane.status.goal_attention_projection import ( # Read, not only re-exported, by this facade, so this stays a plain import and # the name is absent from the identity-alias allowlist below. @@ -54,13 +35,7 @@ PLANNED_CONTROLLER_OPT_IN_RECOMMENDED_ACTION as PLANNED_CONTROLLER_OPT_IN_RECOMMENDED_ACTION, REGISTRY_WAITING_ON_OVERRIDES as REGISTRY_WAITING_ON_OVERRIDES, ) -# Refs #4447: one definition for this vocabulary. The control_plane projection -# owns it because it feeds the monitor/attention read models; this module keeps -# re-exporting each name for existing callers instead of restating its value. from .control_plane.status.monitor_display_projection import ( - MONITOR_DISPLAY_FALLBACK_ACTION as MONITOR_DISPLAY_FALLBACK_ACTION, - MONITOR_DISPLAY_SCHEMA_VERSION as MONITOR_DISPLAY_SCHEMA_VERSION, - MONITOR_DISPLAY_STOP_CONDITION as MONITOR_DISPLAY_STOP_CONDITION, MONITOR_SIGNAL_WAITING_ON, build_project_asset, ) @@ -234,9 +209,6 @@ sync_connected_attention_action_from_todos as _sync_connected_attention_action_from_todos_read_model, todo_lane_items as todo_lane_items, todo_item_is_deferred as todo_item_is_deferred, - todo_item_is_due_monitor as todo_item_is_due_monitor, - todo_item_missing_monitor_schedule as todo_item_missing_monitor_schedule, - todo_item_next_due_at as todo_item_next_due_at, todo_item_task_class as todo_item_task_class, todo_projection_sort_key as todo_projection_sort_key, ) @@ -273,37 +245,17 @@ "todo_item_task_class": "loopx.control_plane.todos.todo_summary", "todo_lane_items": "loopx.control_plane.todos.todo_summary", "todo_item_is_deferred": "loopx.control_plane.todos.todo_summary", - "todo_item_is_due_monitor": "loopx.control_plane.todos.todo_summary", - "todo_item_missing_monitor_schedule": "loopx.control_plane.todos.todo_summary", - "todo_item_next_due_at": "loopx.control_plane.todos.todo_summary", "todo_projection_sort_key": "loopx.control_plane.todos.todo_summary", "normalize_todo_task_class": "loopx.control_plane.todos.contract", "todo_item_is_expired_monitor": "loopx.control_plane.todos.todo_semantics", - # Refs #4447: single-sourced monitor/status vocabulary. Each name was already - # defined here and again in the control_plane projection that owns it; these - # entries keep the facade exporting one definition instead of a second copy. - "MONITOR_DISPLAY_STOP_CONDITION": "loopx.control_plane.status.monitor_display_projection", - "MONITOR_DISPLAY_FALLBACK_ACTION": "loopx.control_plane.status.monitor_display_projection", - "STATUS_CONTRACT_RELOAD_HINT": "loopx.control_plane.status.contract_projection", "PLANNED_CONTROLLER_OPT_IN_RECOMMENDED_ACTION": "loopx.control_plane.status.goal_attention_projection", - # Refs #4447: the facade restated thirteen carriers its own projections - # already own - the status contract schema numbers, the monitor display schema - # version, the goal-attention override set, and the active-state, autonomous- - # replan, dead-monitor and backlog-hygiene carriers. Each is now defined once - # by the projection that feeds it to a read model. + # Refs #4447: the facade restated three carriers its own projections already + # own - the autonomous-replan and dead-monitor thresholds and the goal-attention + # override set. Each is now defined once by the projection that feeds it to a + # read model. "AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD": "loopx.control_plane.status.autonomous_replan_projection", - "AUTONOMOUS_REPLAN_SCHEMA_VERSION": "loopx.control_plane.status.autonomous_replan_projection", - "BACKLOG_HYGIENE_BULLET_PATTERN": "loopx.control_plane.status.active_state_projection", - "BACKLOG_HYGIENE_HINT_PATTERN": "loopx.control_plane.status.active_state_projection", - "BACKLOG_HYGIENE_SECTION_HEADINGS": "loopx.control_plane.status.active_state_projection", - "DEAD_MONITOR_REPEAT_SCHEMA_VERSION": "loopx.control_plane.status.autonomous_replan_projection", "DEAD_MONITOR_REPEAT_THRESHOLD": "loopx.control_plane.status.autonomous_replan_projection", - "MINIMUM_DASHBOARD_STATUS_CONTRACT_SCHEMA_VERSION": "loopx.control_plane.status.contract_projection", - "MONITOR_DISPLAY_SCHEMA_VERSION": "loopx.control_plane.status.monitor_display_projection", "REGISTRY_WAITING_ON_OVERRIDES": "loopx.control_plane.status.goal_attention_projection", - "SECTION_HEADING_PATTERN": "loopx.control_plane.status.active_state_projection", - "STATUS_CONTRACT_SCHEMA_VERSION": "loopx.control_plane.status.contract_projection", - "STATUS_CONTRACT_SIGNAL_LIMIT": "loopx.control_plane.status.contract_projection", # Refs #4447: the connected-adapter sets were defined here and in both status # projections that pass them to the same injected read-model parameters. The # status package now owns each set once; the facade keeps exporting the diff --git a/scripts/generate_turn_contract.py b/scripts/generate_turn_contract.py index 046c19e897..775b596f6b 100644 --- a/scripts/generate_turn_contract.py +++ b/scripts/generate_turn_contract.py @@ -227,6 +227,7 @@ def build_artifacts(): '"""' + header + '"""', "from __future__ import annotations", "from enum import Enum", + "from typing import Any", "", ] ts = ["// " + line for line in header.splitlines()] + [""] @@ -245,9 +246,9 @@ def build_artifacts(): "", ] py += [ - "TURN_CONTROLLER_CONTRACT = " + pformat(contract, sort_dicts=False, width=100), + "TURN_CONTROLLER_CONTRACT: dict[str, Any] = " + pformat(contract, sort_dicts=False, width=100), "", - "ROUTE_TO_DISPOSITION = TURN_CONTROLLER_CONTRACT['route_projection']", + "ROUTE_TO_DISPOSITION: dict[str, str | None] = TURN_CONTROLLER_CONTRACT['route_projection']", "", "def project_turn_route(route: LoopXTurnRoute) -> LoopDisposition:", ' """Public total route projection; contract_error explicitly rejects."""', diff --git a/tests/control_plane/test_status_facade_vocabulary_owners.py b/tests/control_plane/test_status_facade_vocabulary_owners.py index 8e7677167a..9b6069fb2c 100644 --- a/tests/control_plane/test_status_facade_vocabulary_owners.py +++ b/tests/control_plane/test_status_facade_vocabulary_owners.py @@ -53,14 +53,14 @@ autonomous_replan_projection, (status,), ), - "AUTONOMOUS_REPLAN_SCHEMA_VERSION": (autonomous_replan_projection, (status,)), + "AUTONOMOUS_REPLAN_SCHEMA_VERSION": (autonomous_replan_projection, ()), "BACKLOG_HYGIENE_BULLET_PATTERN": ( active_state_projection, - (state_projection, status), + (state_projection,), ), - "BACKLOG_HYGIENE_HINT_PATTERN": (active_state_projection, (status,)), - "BACKLOG_HYGIENE_SECTION_HEADINGS": (active_state_projection, (status,)), - "DEAD_MONITOR_REPEAT_SCHEMA_VERSION": (autonomous_replan_projection, (status,)), + "BACKLOG_HYGIENE_HINT_PATTERN": (active_state_projection, ()), + "BACKLOG_HYGIENE_SECTION_HEADINGS": (active_state_projection, ()), + "DEAD_MONITOR_REPEAT_SCHEMA_VERSION": (autonomous_replan_projection, ()), "DEAD_MONITOR_REPEAT_THRESHOLD": (autonomous_replan_projection, (status,)), "LEGACY_EXTERNAL_EVIDENCE_CLASSIFICATION_PREFIXES": ( goal_attention_projection, @@ -68,9 +68,9 @@ ), "MINIMUM_DASHBOARD_STATUS_CONTRACT_SCHEMA_VERSION": ( contract_projection, - (status,), + (), ), - "MONITOR_DISPLAY_SCHEMA_VERSION": (monitor_display_projection, (status,)), + "MONITOR_DISPLAY_SCHEMA_VERSION": (monitor_display_projection, ()), "MONITOR_SIGNAL_WAITING_ON": ( monitor_display_projection, (attention_projection, goal_attention_projection, status), @@ -78,12 +78,12 @@ "REGISTRY_WAITING_ON_OVERRIDES": (goal_attention_projection, (status,)), "SECTION_HEADING_PATTERN": ( active_state_projection, - (state_projection, status), + (state_projection,), ), - "STATUS_CONTRACT_SCHEMA_VERSION": (contract_projection, (status,)), + "STATUS_CONTRACT_SCHEMA_VERSION": (contract_projection, ()), "STATUS_CONTRACT_SIGNAL_LIMIT": ( contract_projection, - (diagnose, status), + (diagnose,), ), } diff --git a/tests/control_plane_ts/delivery_response.test.ts b/tests/control_plane_ts/delivery_response.test.ts index 182a5e1f1c..d9dd5f87bd 100644 --- a/tests/control_plane_ts/delivery_response.test.ts +++ b/tests/control_plane_ts/delivery_response.test.ts @@ -18,7 +18,7 @@ const input = { run, todo: waiting, run_agent_id: "agent-a", agent_id: "agent-a" test("wait proof consumes the real resume evaluator for all five condition kinds", () => { const dependency = { todo_id: "todo_dependency", role: "agent", status: "open", task_class: "advancement_task" }; - for (const [resume, source, capabilities, valid] of [ + const cases: Array<[string, JsonObject[], string[] | null, boolean]> = [ ["todo_done:todo_dependency", [dependency], [], true], ["todo_done:todo_dependency", [], [], false], ["monitor_changed:todo_dependency", [{ ...dependency, task_class: "continuous_monitor", material_change_generation: 0 }], [], true], @@ -28,7 +28,8 @@ test("wait proof consumes the real resume evaluator for all five condition kinds ["pr_merged:example/project#1", [], [], false], ["pr_merged:#1", [], [], false], ["resume_at:2026-09-15T00:00:00Z", [], [], true], - ] as const) { + ]; + for (const [resume, source, capabilities, valid] of cases) { const todo = { ...waiting, resume_when: resume, resume_monitor_generation: 0 }; const evaluated = evaluateTodoResumeConditions({ schema_version: TODO_RESUME_EVALUATION_REQUEST_SCHEMA_VERSION, items: [todo], source_items: source, rollout_events: [], available_capabilities: capabilities, @@ -94,7 +95,7 @@ test("exact dependency identity and a supported completion class are required", }); test("history alone, missing source, invalid wait, and other actors cannot exempt the floor", () => { - for (const patch of [ + const patches: Record[] = [ { todo: null }, { agent_id: "agent-b" }, { run_agent_id: "agent-b" }, { agent_id: null }, { run_agent_id: null }, { agent_id: "", run_agent_id: "" }, { todo: { ...waiting, todo_id: "todo_other" } }, @@ -112,7 +113,8 @@ test("history alone, missing source, invalid wait, and other actors cannot exemp { run: { ...run, progress_observation: null, delivery_turn_kind: "blocker_writeback" } }, { run: { ...run, replan_obligation_id: "replan_other" } }, { run: { ...run, progress_observation: { ...run.progress_observation, evidence_ids: [] } } }, - ]) assert.equal(projectDeliveryResponse({ ...input, ...patch }).outcome_floor_applicable, true, JSON.stringify(patch)); + ]; + for (const patch of patches) assert.equal(projectDeliveryResponse({ ...input, ...patch }).outcome_floor_applicable, true, JSON.stringify(patch)); }); test("surface-only supervision and unknown remain distinct from durable work state", () => { diff --git a/tests/control_plane_ts/effect_runtime_handler_loading.test.ts b/tests/control_plane_ts/effect_runtime_handler_loading.test.ts index 64fd6e7df9..25d7a01fae 100644 --- a/tests/control_plane_ts/effect_runtime_handler_loading.test.ts +++ b/tests/control_plane_ts/effect_runtime_handler_loading.test.ts @@ -301,13 +301,12 @@ test("runtime loads selected owners without importing unrelated methods", () => assert.equal(context.contributions[0].capability_id, "goal_capability_organization"); const worker = {goal_id: "example", agent_id: "worker"}; const source = {sender_ids: ["owner"], targets: [{goal_id: "example"}]}; - assert.deepEqual(await dispatchEffectRuntimeMethod(handlers, "collaboration.source.recipients", - {sender_id: "owner", source, available: [worker]}), {targets: [worker]}); + const {resolveSourceRecipients} = await import(${JSON.stringify(new URL("../../loopx/control_plane/collaboration/source_grants.ts", import.meta.url).href)}); + assert.deepEqual(resolveSourceRecipients({sender_id: "owner", source, available: [worker]}), {targets: [worker]}); const revoked = await dispatchEffectRuntimeMethod(handlers, "collaboration.source.configure_recipient", {source, goal_id: "example", agent_id: "worker", grant: false, available: [worker], active_goal_ids: ["example"]}); - assert.deepEqual(await dispatchEffectRuntimeMethod(handlers, "collaboration.source.recipients", - {sender_id: "owner", source: revoked.source, available: [worker]}), {targets: []}); + assert.deepEqual(resolveSourceRecipients({sender_id: "owner", source: revoked.source, available: [worker]}), {targets: []}); const peer = {conversation: {channel_id: "goal.example", goal_id: "example", origin: "web"}, source_id: "fixture", goal_id: "example", agent_ids: ["worker"]}; assert.deepEqual(await dispatchEffectRuntimeMethod(handlers, "collaboration.peer.context_access", diff --git a/tests/control_plane_ts/effect_runtime_handlers.test.ts b/tests/control_plane_ts/effect_runtime_handlers.test.ts index 1dc0733f2e..0b19e40237 100644 --- a/tests/control_plane_ts/effect_runtime_handlers.test.ts +++ b/tests/control_plane_ts/effect_runtime_handlers.test.ts @@ -246,6 +246,7 @@ for (const retired of [ "governed_capability.validate_admission", "governed_capability.settlement_status", "collaboration.delegation.turn_plan", + "collaboration.source.recipients", "settlement.receipt_bound_terminal_phase", ]) { test(`unused leaf RPC ${retired} fails closed`, async () => { diff --git a/tests/control_plane_ts/usage_statistics_environment.test.ts b/tests/control_plane_ts/usage_statistics_environment.test.ts index 682b6dad0a..b7f6ac7a33 100644 --- a/tests/control_plane_ts/usage_statistics_environment.test.ts +++ b/tests/control_plane_ts/usage_statistics_environment.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { createServer } from "node:http"; import { mkdir, mkdtemp, readFile, rm, symlink } from "node:fs/promises"; -import { realpathSync } from "node:fs"; +import { accessSync, constants, mkdirSync, realpathSync } from "node:fs"; import { homedir, platform, tmpdir } from "node:os"; import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; @@ -58,7 +58,18 @@ const persistentFixtureBase = (): string => { // temp-root checkout skips for the documented reason while a classifier // regression on a persistent checkout still fails the assertions. if (independentlyTemporary(fileURLToPath(import.meta.url))) return ""; - return [homedir(), resolve(".")].find(base => !independentlyTemporary(join(base, "usage-ping.json"))) ?? ""; + const repoLocal = join(resolve("."), ".local"); + for (const base of [repoLocal, homedir(), resolve(".")]) { + if (independentlyTemporary(join(base, "usage-ping.json"))) continue; + try { + if (base === repoLocal) mkdirSync(base, { recursive: true }); + accessSync(base, constants.W_OK); + return base; + } catch { + // Unwritable HOME or candidate base falls through without EROFS. + } + } + return ""; }; test("temporary machine routes suppress every HTTP channel even with enabled/copied state", async t => { diff --git a/tests/control_plane_ts/zcode_app_server.test.ts b/tests/control_plane_ts/zcode_app_server.test.ts index 2ffdc053d7..b289ed170d 100644 --- a/tests/control_plane_ts/zcode_app_server.test.ts +++ b/tests/control_plane_ts/zcode_app_server.test.ts @@ -45,7 +45,7 @@ readline.createInterface({input:process.stdin}).on('line', line => { }); `; function host(mode = "normal", options: ConstructorParameters[3] = {}) { - return new ZCodeAppServer([process.execPath, "-e", HOST, mode], process.cwd(), { ...process.env }, { timeoutMs: 1000, ...options }); + return new ZCodeAppServer([process.execPath, "-e", HOST, mode], process.cwd(), { ...process.env }, { timeoutMs: 5000, ...options }); } function safeError(code: string) { return (error: unknown) => error instanceof ZCodeProtocolError && error.code === code && !String(error).includes("private-key-secret"); diff --git a/tests/test_audit_cli_and_runtime_fixes.py b/tests/test_audit_cli_and_runtime_fixes.py new file mode 100644 index 0000000000..aa08921c4c --- /dev/null +++ b/tests/test_audit_cli_and_runtime_fixes.py @@ -0,0 +1,455 @@ +"""Focused regressions for CLI, goal-mode, Lark, presentation, and capability fixes.""" + +from __future__ import annotations + +import argparse +import base64 +import importlib +import io +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +def test_cli_build_parser_accepts_postgres_subcommands() -> None: + from loopx.cli import build_parser + + parser = build_parser() + parsed = parser.parse_args(["postgres", "--format", "json", "setup", "--execute"]) + assert parsed.command == "postgres" + assert parsed.postgres_action == "setup" + assert parsed.subcommand_format == "json" + assert parsed.execute is True + + +def test_opencode2_goal_worker_routes_stderr_and_preserves_failure_exit( + tmp_path: Path, monkeypatch, capsys +) -> None: + from loopx.cli_commands import opencode2_goal_worker as mod + + fake_worker = tmp_path / "worker.mjs" + fake_worker.write_text("", encoding="utf-8") + monkeypatch.setattr(mod, "_materialized_worker_path", lambda: fake_worker) + + class _FakeProc: + def __init__(self, returncode: int, stdout: str, stderr: str) -> None: + self.returncode = returncode + self._stdout = stdout + self.stderr = io.StringIO(stderr) + + def communicate(self) -> tuple[str, None]: + return self._stdout, None + + def kill(self) -> None: + pass + + def wait(self) -> int: + return self.returncode + + payloads: list[tuple[dict[str, object], str]] = [] + + def capture_payload(payload: dict[str, object], fmt: str, _renderer) -> None: + payloads.append((payload, fmt)) + + args = argparse.Namespace( + goal_id="g1", + directory=str(tmp_path), + agent_id=None, + registry=None, + capability=[], + session_id=None, + task_body=None, + max_turns=None, + max_duration_minutes=None, + force_resume=False, + state_dir=None, + format="json", + ) + + monkeypatch.setattr( + mod.subprocess, + "Popen", + lambda *a, **k: _FakeProc( + 0, + json.dumps({"operation": "opencode2_goal_worker", "ok": False, "result": {"kind": "paused_state"}}), + "worker diagnostic line\n", + ), + ) + rc = mod.handle_opencode2_goal_worker_command(args, capture_payload) + captured = capsys.readouterr() + assert rc == 1 + assert captured.out == "" + assert "worker diagnostic line" in captured.err + assert payloads[-1][0]["ok"] is False + assert payloads[-1][0]["exit_code"] == 0 + + monkeypatch.setattr( + mod.subprocess, + "Popen", + lambda *a, **k: _FakeProc( + 2, + json.dumps({"operation": "opencode2_goal_worker", "ok": True, "result": {"kind": "done"}}), + "", + ), + ) + rc2 = mod.handle_opencode2_goal_worker_command(args, capture_payload) + assert rc2 == 2 + assert payloads[-1][0]["ok"] is False + assert payloads[-1][0]["exit_code"] == 2 + + +def test_explore_turn_context_with_empty_goal_id_uses_default_registry( + tmp_path: Path, monkeypatch +) -> None: + from loopx.cli_commands import explore as mod + + registry = tmp_path / ".loopx" / "registry.json" + registry.parent.mkdir(parents=True) + registry.write_text('{"schema_version": "0.1", "goals": []}', encoding="utf-8") + + turn_ctx_mod = importlib.import_module("loopx.capabilities.explore.turn_context") + seen: list[dict[str, object]] = [] + + def fake_turn_context(**kwargs): + seen.append(kwargs) + return {"ok": True, "goal_id": kwargs.get("goal_id")} + + monkeypatch.setattr(turn_ctx_mod, "explore_turn_context", fake_turn_context) + + printed: list[dict[str, object]] = [] + args = argparse.Namespace( + command="explore", + explore_command="turn-context", + goal_id="", + agent_id="a1", + todo_id=None, + result_limit=10, + result_offset=0, + result_node=None, + result_revision=None, + config_path=None, + format="json", + ) + rc = mod.handle_explore_command( + args, + registry_path=registry, + runtime_root_arg=str(tmp_path), + output_format=lambda a: "json", + print_payload=lambda payload, fmt, _renderer: printed.append(payload), + ) + assert rc == 0 + assert seen and seen[0]["registry_path"] == registry + assert printed[-1]["ok"] is True + + +@pytest.mark.parametrize( + "malformed_reply", + [ + None, + (0, {"status": []}), + (0, {"trajectory": "wrong shape"}), + (1, {"steps": None}), + (1, {"steps": [{"metadata": "wrong shape"}]}), + (1, {"steps": [{"metadata": {"sourceTrajectoryStepInfo": []}}]}), + (2, {"trajectory": "wrong shape"}), + ], +) +def test_agy_native_input_accepts_ls_url_and_rejects_malformed_replies( + monkeypatch, malformed_reply, +) -> None: + from loopx.agy_goal_mode import host_runtime as mod + from loopx.capabilities.native_chat import antigravity_adapter as provider + + monkeypatch.delenv("ANTIGRAVITY_LS_ADDRESS", raising=False) + monkeypatch.setenv("ANTIGRAVITY_LS_URL", "http://127.0.0.1:4321") + monkeypatch.setenv("ANTIGRAVITY_CSRF_TOKEN", "tok") + + args = argparse.Namespace(conversation_id="conv-1") + + snapshot = { + "numTotalSteps": 1, + "status": "CASCADE_RUN_STATUS_IDLE", + "trajectory": {"cascadeId": "conv-1"}, + } + steps = [{ + "type": "CORTEX_STEP_TYPE_USER_INPUT", + "status": "CORTEX_STEP_STATUS_DONE", + "metadata": {"createdAt": "2026-01-01T00:00:00Z"}, + "userInput": {"userResponse": "hello"}, + }] + replies = [snapshot.copy(), {"steps": steps}, snapshot.copy()] + if malformed_reply is not None: + index, override = malformed_reply + replies[index].update(override) + responses = iter(replies) + monkeypatch.setattr(provider, "_rpc_post", lambda *_a, **_k: next(responses)) + res = mod._native_input(args, "hello") + if malformed_reply is None: + assert res is not None and res[1:] == ("CASCADE_RUN_STATUS_IDLE", 1) + else: + assert res is None + + +def test_agy_native_input_returns_no_anchor_when_rpc_fails(monkeypatch) -> None: + from loopx.agy_goal_mode import host_runtime as mod + from loopx.capabilities.native_chat import antigravity_adapter as provider + from loopx.chat_agent import CodexChatAgentError + + monkeypatch.setenv("ANTIGRAVITY_LS_ADDRESS", "127.0.0.1:4321") + monkeypatch.setenv("ANTIGRAVITY_CSRF_TOKEN", "tok") + + def raise_rpc(*_a, **_k): + raise CodexChatAgentError("ls unavailable", gate=None) + + monkeypatch.setattr(provider, "_rpc_post", raise_rpc) + assert mod._native_input(argparse.Namespace(conversation_id="conv-1"), "hello") is None + + +def test_claude_goal_policy_fail_closed_empty_path_and_resolves_relative_cwd( + tmp_path: Path, monkeypatch +) -> None: + hooks_dir = str(REPO_ROOT / "loopx" / "claude_goal_mode" / "hooks") + if hooks_dir not in sys.path: + sys.path.insert(0, hooks_dir) + import goal_policy + + project = tmp_path / "proj" + project.mkdir() + other_dir = tmp_path / "elsewhere" + other_dir.mkdir() + monkeypatch.chdir(other_dir) + monkeypatch.setattr( + goal_policy, + "active_context", + lambda cwd: { + "goal_id": "g1", + "registry": str(project / ".loopx" / "registry.json"), + "agent_id": "cc", + "write_scope": [str(project)], + "project_root": str(project), + }, + ) + monkeypatch.setattr(goal_policy, "should_run", lambda *a, **k: True) + + missing = goal_policy.decide( + {"cwd": str(project), "tool_name": "Write", "tool_input": {"file_path": ""}} + )["hookSpecificOutput"] + assert missing["permissionDecision"] == "deny" + assert "missing file_path" in missing["permissionDecisionReason"] + + rel_ok = goal_policy.decide( + {"cwd": str(project), "tool_name": "Write", "tool_input": {"file_path": "src/app.py"}} + )["hookSpecificOutput"] + assert rel_ok["permissionDecision"] == "allow" + + +def test_lark_private_progress_handles_missing_version_null_summaries_and_list_label() -> None: + from loopx.extensions.lark.private_progress import ( + presentation_phase, + presentation_stream, + project_progress, + ) + + rec: dict[str, object] = {"context_recovery": {"presentation_key": "k1"}} + assert presentation_phase(rec, "progress") == "progress.recovery.k1" + stream = presentation_stream(rec) + assert isinstance(stream, dict) + + state: dict[str, object] = {"thinking_summaries": None} + events = [ + { + "event_id": "e1", + "kind": "agent.phase", + "payload": { + "method": "item/reasoning/summaryTextDelta", + "step": { + "kind": "reasoning", + "reasoning_summary": True, + "detail": "Checking state", + "id": "r1", + }, + }, + }, + { + "event_id": "e2", + "kind": "agent.phase", + "payload": {"method": "item/started", "label": ["unexpected-list"]}, + }, + ] + rendered = project_progress(state, events, owner_private=True) + assert rendered is not None and "Checking state" in rendered + + +def test_explore_results_api_skips_double_validation_matches_goal_and_returns_404( + monkeypatch, +) -> None: + from loopx.presentation import explore_results_api as mod + from loopx.control_plane.status.goal_source import SourceScopeError + + calls: list[dict[str, object]] = [] + monkeypatch.setattr( + mod, + "validate_explore_result_event", + lambda event, expected_goal_id=None: calls.append(event) or event, + ) + monkeypatch.setattr( + mod, + "build_explore_result_projection", + lambda events, goal_id, finding_limit: {"nodes": [], "findings": []}, + ) + import loopx.control_plane.work_items.yardstick_decision as ydec + + monkeypatch.setattr(ydec, "project_work_yardstick_presentations", lambda rows, goal_id: []) + + mod._finding_rows([{"x": 1}], None, goal_id="g1", validated=True) + assert calls == [] + mod._finding_rows([{"x": 1}], None, goal_id="g1", validated=False) + assert len(calls) == 1 + + class _FakeReader: + def __init__(self, raise_scope: bool = False) -> None: + self.raise_scope = raise_scope + self.source = SimpleNamespace( + namespace="ns-1", + goal_id="g-second", + read_events=lambda gid: [], + ) + + def registered_status(self, gid: str, fresh: bool = False): + if self.raise_scope: + raise SourceScopeError("missing") + return { + "run_history": { + "goals": [ + {"id": "g-first", "semantic_history": {}}, + { + "id": "g-second", + "semantic_history": { + "agents": [ + { + "latest_agent_vision_run": { + "generated_at": "2026-07-01T12:00:00Z", + "agent_vision": { + "vision_patch": {"vision_summary": "v"} + }, + } + } + ] + }, + }, + ] + } + } + + import loopx.presentation.goal_source_routing as gsr + + for raise_scope, expected_status in ((False, 200), (True, 404)): + reader = _FakeReader(raise_scope=raise_scope) + monkeypatch.setattr(gsr, "linked_goal_source", lambda srv, gid: ("row", reader)) + sent: list[tuple[int, dict[str, object]]] = [] + + class _Dummy(mod.ExploreResultsRequestMixin): + path = "/api/chat/explore-results?goal_id=g-second&source_namespace=ns-1&view=history-timing" + server = SimpleNamespace() + + def _require_loopback_origin(self) -> bool: + return True + + def _send_json(self, payload: dict[str, object], status: int = 200) -> None: + sent.append((status, payload)) + + def _send_error(self, message: str, status: int = 400) -> None: + sent.append((status, {"ok": False, "error": message})) + + _Dummy()._explore_results() + assert sent[-1][0] == expected_status + if expected_status == 200: + assert sent[-1][1]["strategy_recorded_at"] == "2026-07-01T12:00:00Z" + + +def test_chat_attachments_rejects_bool_and_list_sizes() -> None: + from loopx.chat_attachments import normalize_chat_image_attachments + + data = base64.b64encode(b"img").decode("ascii") + for bad_size in (True, False, [3], "3"): + with pytest.raises(ValueError): + normalize_chat_image_attachments( + [{"data_url": f"data:image/png;base64,{data}", "size": bad_size}] + ) + + +def test_presets_quotes_cli_bin_and_tolerates_none_lists() -> None: + from loopx.presets import build_beginner_preset_packet, render_beginner_preset_markdown + + pkt = build_beginner_preset_packet(preset_id="daily-triage", cli_bin="/opt/my loopx/bin/loopx") + assert pkt["common_setup"][0] == "'/opt/my loopx/bin/loopx' doctor" + assert pkt["presets"][0]["commands"]["cli_start"].startswith("'/opt/my loopx/bin/loopx' start-goal") + md = render_beginner_preset_markdown( + { + "summary": "s", + "mutation_policy": "m", + "common_setup": None, + "presets": [{"id": "x", "useful_when": None, "safety_defaults": None, "commands": None}], + } + ) + assert "LoopX beginner preset picker" in md + + +def test_content_ops_rejects_duplicate_stdin_and_uses_generic_error_header( + tmp_path: Path, monkeypatch +) -> None: + from loopx.capabilities.content_ops.cli import handle_content_ops_command + + monkeypatch.setattr(sys, "stdin", io.StringIO('{"a": 1}')) + printed: list[tuple[dict[str, object], str]] = [] + args = argparse.Namespace( + content_ops_command="item-transition", + item_json="-", + event_json="-", + max_input_bytes=1024, + format="markdown", + ) + rc = handle_content_ops_command( + args, + output_format=lambda a: "markdown", + print_payload=lambda payload, fmt, renderer: printed.append((payload, renderer(payload))), + ) + assert rc == 1 + payload, md = printed[-1] + assert payload["ok"] is False + assert "stdin ('-')" in str(payload["error"]) + assert md.startswith("# LoopX Content-Ops\n") + assert "Private Connector Gate" not in md + + +def test_effect_runtime_stop_recognizes_reparented_all_zombie_thread_group( + tmp_path: Path, monkeypatch +) -> None: + from loopx.control_plane import effect_runtime + + locator = tmp_path / "runtime.json" + info = {"pid": 424242, "token": "serving"} + monkeypatch.setattr(effect_runtime, "_request_with_info", lambda *a, **kw: {"stopped": True}) + monkeypatch.setattr(effect_runtime, "_pid_is_alive", lambda pid: True) + monkeypatch.setattr(effect_runtime, "_reap_exited_runtime_child", lambda _info: True) + + zombie = False + monkeypatch.setattr(effect_runtime, "_linux_thread_group_is_zombie", lambda pid: zombie) + pending = effect_runtime._stop_effect_runtime( + locator, info, timeout=0.05, wait_for_process_exit=True + ) + assert pending["stopped"] is False + assert pending["status"] == "shutdown_pending" + + zombie = True + stopped = effect_runtime._stop_effect_runtime( + locator, info, timeout=0.5, wait_for_process_exit=True + ) + assert stopped["stopped"] is True + assert stopped["status"] == "stopped" diff --git a/tsconfig.control-plane.json b/tsconfig.control-plane.json index abe6435c8e..febde3aafc 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -86,6 +86,7 @@ "tests/control_plane_ts/postgresql_authority_service_fixture.ts", "tests/control_plane_ts/delivery_continuity.test.ts", "tests/control_plane_ts/delivery_history.test.ts", + "tests/control_plane_ts/delivery_response.test.ts", "tests/control_plane_ts/delivery_workspace.test.ts", "tests/control_plane_ts/settlement_workspace_causality.test.ts", "tests/control_plane_ts/quota_settlement_readback.test.ts", From c4c30344e3e4d78019e5e51d72d6886f225487d7 Mon Sep 17 00:00:00 2001 From: aihop <4408344+hhyykk@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:32:50 +0800 Subject: [PATCH 3/3] chore(repo): align repository URLs, CI paths, and lint Signed-off-by: aihop <4408344+hhyykk@users.noreply.github.com> --- .github/CODEOWNERS | 1 - .github/workflows/full-public-smokes.yml | 2 +- .gitignore | 1 - CONTRIBUTING.md | 7 +-- docs/book/chapters/00-reading-guide.md | 2 +- docs/book/chapters/02-session-goal-loopx.md | 4 +- docs/book/chapters/core-state-machines.md | 22 ++++----- .../source-change-control-plane-rule.md | 8 ++-- docs/book/chapters/source-protocol-map.md | 46 +++++++++--------- .../chapters/source-trace-protocol-chain.md | 12 ++--- docs/book/chapters/source-validation-to-pr.md | 4 +- docs/book/en/chapters/00-reading-guide.md | 2 +- .../book/en/chapters/02-session-goal-loopx.md | 4 +- docs/book/en/chapters/core-state-machines.md | 22 ++++----- .../source-change-control-plane-rule.md | 8 ++-- docs/book/en/chapters/source-protocol-map.md | 48 +++++++++---------- .../chapters/source-trace-protocol-chain.md | 12 ++--- .../en/chapters/source-validation-to-pr.md | 4 +- docs/book/en/welcome-wagon.md | 16 +++---- docs/book/welcome-wagon.md | 16 +++---- docs/capability_docs.py | 2 +- .../github-maintenance-ops-best-practices.md | 6 +-- ...ub-maintenance-ops-best-practices.zh-CN.md | 6 +-- docs/development/README.md | 6 +-- docs/development/testing-and-quality.md | 2 +- docs/guides/getting-started.md | 10 ++-- docs/guides/minimal-custom-runtime-example.md | 2 +- .../minimal-custom-runtime-example.zh-CN.md | 2 +- docs/index.md | 2 +- .../worker-bridge-install-contract.md | 2 +- .../core-control-plane/state-machine.md | 12 ++--- docs/product/release-note-template.md | 4 +- .../codex-cli/codex-cli-packaged-install.md | 2 +- docs/project/authors.md | 4 +- docs/project/history.md | 8 ++-- docs/project/technical-directions.md | 6 +-- docs/project/technical-directions.zh-CN.md | 6 +-- docs/quota-allocation.md | 2 +- docs/research/README.md | 2 +- docs/showcases/cases/dsh-loopx-replan-demo.md | 4 +- examples/dev-book-publication-smoke.py | 6 +-- examples/export-frontstage-share-bundle.mjs | 2 +- examples/frontstage-share-bundle-smoke.mjs | 2 +- examples/release-artifacts-smoke.py | 6 ++- .../project_skill_delivery/README.md | 6 +-- .../tests/test_provider_lifecycle.py | 1 - .../tests/test_steward_native_owner.py | 1 - packages/loopx-repo-health/README.md | 4 +- .../src/loopx_repo_health/cli.py | 2 +- .../src/loopx_repo_health/github.py | 3 +- ...bao-capability-monitor-repair-tool-live.py | 4 +- ...-doubao-scoped-gate-successor-tool-live.py | 4 +- .../qualify-doubao-selected-todo-tool-live.py | 4 +- scripts/runtime_artifact.py | 4 +- skills/loopx-self-repair/SKILL.md | 12 ++--- .../references/repair-patterns.md | 4 +- .../references/upstream-issue-escalation.md | 4 +- sonar-project.properties | 10 ++-- .../test_premerge_public_boundary_run.py | 2 +- 59 files changed, 206 insertions(+), 206 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4c4948c346..a7f1e74ada 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -56,7 +56,6 @@ /tests/ @huangruiteng @songoow @loopx-agent /scripts/ @huangruiteng @songoow @loopx-agent /demo/ @huangruiteng @songoow @loopx-agent -/deprecate/ @huangruiteng @songoow @loopx-agent # --- Subsystem routes -------------------------------------------------------- diff --git a/.github/workflows/full-public-smokes.yml b/.github/workflows/full-public-smokes.yml index 8b2e68dd92..b8914525b4 100644 --- a/.github/workflows/full-public-smokes.yml +++ b/.github/workflows/full-public-smokes.yml @@ -148,7 +148,7 @@ jobs: retention-days: 7 smoke-fleet-health: - if: always() + if: always() && github.repository == 'loopx-project/loopx' needs: full-public-smokes runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.gitignore b/.gitignore index de759d548c..96b5096168 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .venv/ .idea node_modules/ -apps/dashboard/public/*.local.json apps/presentation/dashboard/public/*.local.json __pycache__/ *.pyc diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a75a60c2b3..b772c03d17 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -127,7 +127,8 @@ LoopX needs two runtimes: - **Python 3.11+.** `uv` installs a compatible one for you. - **Node.js 22.22.3 or newer**, with Node.js 24 LTS recommended. `pyproject.toml` - declares no Python dependencies, but the TypeScript control plane runs on the + declares no cross-platform Python dependencies (only `tzdata; sys_platform == 'win32'`), + but the TypeScript control plane runs on the system Node.js, both for `loopx` itself and for the test suite. `pip` and `uv` cannot install Node.js for you. @@ -193,7 +194,7 @@ touch, mention it in the PR instead of fixing it there. | `ci-maintenance.yml` | opened, reopened, edited, updated or closed PR (`pull_request_target`, trusted base code only) | no | inspects potential stale PR comparisons without mutating the head or target; cancels obsolete Python qualification runs after rechecking the PR and source branch | | `dependency-review.yml` | every PR | no | dependency changes introduced by the PR | | `postgresql-integration.yml` | control-plane or npm lockfile paths | no | PostgreSQL authority store and service on a temporary instance | -| `package-smoke.yml` | extension package paths | no | extension packages install, entrypoints, and example schemas | +| `package-smoke.yml` | `loopx-core` and extension package paths | no | `loopx-core` and extension packages install, entrypoints, and example schemas | | `release-artifacts.yml` | `loopx/`, packaging, and lockfile paths | no | release identity and a release build from this source | | `runtime-snapshots.yml` | runtime artifact, installer, and updater paths | no | qualified, revision-addressed runtime archives and the main channel pointer | | `ark-turn.yml` | Turn driver and collaboration paths | no | optional Ark Turn package, stdio MCP, and DSH parity | @@ -203,7 +204,7 @@ touch, mention it in the PR instead of fixing it there. | `frontstage-pages.yml` | README, dashboard, and chat bundle paths | no | public Pages build | | `desktop-release-artifacts.yml` | desktop app and dashboard paths | no | macOS and Windows desktop builds | | `desktop-updater.yml` | desktop app paths | no | desktop app build and updater feed | -| `full-public-smokes.yml` | no (push to `main`, schedule) | no | every public smoke, in shards | +| `full-public-smokes.yml` | no (manual, schedule) | no | every public smoke, in shards | | `sonarcloud.yml` | no (called by Python Tests) | no | SonarCloud analysis of that run's coverage | | `stale.yml` | no (schedule) | no | stale-issue reminders (never closes issues) | | `update-notes.yml` | no (schedule) | no | biweekly update notes | diff --git a/docs/book/chapters/00-reading-guide.md b/docs/book/chapters/00-reading-guide.md index aa32f61568..37a69cff4f 100644 --- a/docs/book/chapters/00-reading-guide.md +++ b/docs/book/chapters/00-reading-guide.md @@ -233,7 +233,7 @@ CLI/App convergence 与 Stage 4 distribution cleanup 仍是后续方向。 | 主题 | `v0.5.4` 已发布事实 | 深入入口 | | --- | --- | --- | | Control Plane | Turn/Host Todo settlement、quota commit、task-lease lifecycle、Vision refresh 与 scheduler heartbeat 等完整事务已迁入 typed TypeScript owner;Python facade 仍承担迁移期边界 | [迁移 RFC](/loopx/docs/architecture/rfcs/typescript-control-plane-migration-v0/) | -| Operator surface | Personal Workspace 已提供 Goal、Task、Chat 和 read-only status source 入口;界面不是新的事实源 | [Dashboard README](https://github.com/huangruiteng/loopx/blob/v0.5.4/apps/presentation/dashboard/README.md) | +| Operator surface | Personal Workspace 已提供 Goal、Task、Chat 和 read-only status source 入口;界面不是新的事实源 | [Dashboard README](https://github.com/loopx-project/loopx/blob/v0.5.4/apps/presentation/dashboard/README.md) | | Host runtime | Codex、Claude Code、OpenCode、Pi、KunlunCode、DeepSeek Harness 与 custom runner 具有不同 activation/stop contract | [Runtime Connector Catalog](/loopx/docs/integrations/runtime-connector-catalog/) | | Capability / Provider | Capability 由 package-owned catalog entry、真实 command 和 durable validation 共同定义;Provider/Extension 不继承 Kernel authority | [Capability Catalog](/loopx/docs/capabilities/) | | Shared authority | file、NoKV 与 PostgreSQL provider 仍是 staged candidate;安装 Provider 不会改变默认本地 authority | [Shared Authority RFC](/loopx/docs/architecture/rfcs/shared-goal-authority-state-provider-v0/) | diff --git a/docs/book/chapters/02-session-goal-loopx.md b/docs/book/chapters/02-session-goal-loopx.md index 145c0d1c05..3ec5625b16 100644 --- a/docs/book/chapters/02-session-goal-loopx.md +++ b/docs/book/chapters/02-session-goal-loopx.md @@ -145,7 +145,7 @@ same time and cost budget 记录 completion、独立 verifier、错误写入、人工介入、stop-policy、wall time 和 cost。没有 matched baseline 或独立 verifier 时,可以记录使用体验,不能声称产品能力提升。 -[Benchmark 研究 RFC](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) +[Benchmark 研究 RFC](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) 定义当前研究边界。Benchmark-native 研究必须明确 arm semantics、authority boundary 与独立 verifier,才能作为产品研究证据。 @@ -274,7 +274,7 @@ environment read 与 replan,不需要新 Host 继承旧 transcript。 ### Host 兼容矩阵 LoopX 保留同一 control-plane contract,但不同 Host 的启动和唤醒机制并不相同。当前公开 -[Runtime Connector Catalog](https://github.com/huangruiteng/loopx/blob/main/docs/integrations/runtime-connector-catalog.md) +[Runtime Connector Catalog](https://github.com/loopx-project/loopx/blob/main/docs/integrations/runtime-connector-catalog.md) 与各 Host adapter 文档给出的主要路径是: | Host surface | 驱动 | 关键限制 | diff --git a/docs/book/chapters/core-state-machines.md b/docs/book/chapters/core-state-machines.md index baadf6ceb6..71cf701880 100644 --- a/docs/book/chapters/core-state-machines.md +++ b/docs/book/chapters/core-state-machines.md @@ -231,11 +231,11 @@ flowchart TD - settlement 再以 `goal_id + agent_id + turn_instance_id` 绑定 writeback、spend 与 scheduler receipt。 对应的源码锚点分别是 -[`completion_transaction.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/completion_transaction.py)、 -[`local_state_write_correctness.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/runtime/local_state_write_correctness.py)、 -[`authority_store.ts`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/coordination/authority_store.ts)、 -[`coordination/authority_core.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/coordination/authority_core.py) -和 [`settlement.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/turn_driver/settlement.py)。 +[`completion_transaction.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/completion_transaction.py)、 +[`local_state_write_correctness.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/runtime/local_state_write_correctness.py)、 +[`authority_store.ts`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/coordination/authority_store.ts)、 +[`coordination/authority_core.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/coordination/authority_core.py) +和 [`settlement.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/turn_driver/settlement.py)。 所以正确流程是“读 basis -> 提案 -> 验证/guard -> guarded commit -> 事件或 receipt -> 回读”,而不是 Agent 直接覆盖一份看似完整的状态。 @@ -300,7 +300,7 @@ transition 仍由 write API、validation 和 receipt 完成。箭头表示事实 ### Todo lifecycle:只有四个持久 status -[`loopx/control_plane/todos/contract.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/contract.py) +[`loopx/control_plane/todos/contract.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/contract.py) 定义 Todo 的持久状态: ```text @@ -370,7 +370,7 @@ flowchart LR ### Handoff:clear 不等于路线完整 -[`handoff_gate.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py) +[`handoff_gate.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py) 从 Todo relation 派生六种 handoff state: | 派生状态 | 含义 | 下一步 | @@ -389,7 +389,7 @@ flowchart LR ### Quota runtime:先判定行为,再考虑 spend -[`loopx/control_plane/quota/states.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/states.py) +[`loopx/control_plane/quota/states.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/quota/states.py) 固定了 quota runtime state 的判定优先级: ```text @@ -424,7 +424,7 @@ guard、capability gate、selected Todo、execution obligation 和 scheduler hin ### Settlement:成功必须按事务顺序落地 -[`turn_transaction_contract.json`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/turn_transaction_contract.json) +[`turn_transaction_contract.json`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/turn_transaction_contract.json) 定义完整 Turn 的阶段: ```text @@ -525,7 +525,7 @@ effect;外部结果必须先成为 typed observation,才能进入 Monitor - 到达 expiry 或 stop condition:完成 Monitor,并连接 successor 或 `no_followup`。 对于已经显式提升到 shared authority 的 Goal, -[`todo_monitor_poll.ts`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/coordination/todo_monitor_poll.ts) +[`todo_monitor_poll.ts`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/coordination/todo_monitor_poll.ts) 会在同一个 canonical revision、同一次 CAS 和同一 durable operation receipt 中提交**无 lease 的 observation 与它请求的独立 successor**。事务先校验 actor 注册、claim/binding/exclusion、Monitor 仍处于 active 状态,以及 material-change generation 确实前进;任何校验失败都不会写入任一半。 @@ -643,7 +643,7 @@ flowchart TD ### Terminal 是严格合取,不是“队列看起来空了” -[`loopx/control_plane/goals/goal_frontier/terminal.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/goals/goal_frontier/terminal.py) +[`loopx/control_plane/goals/goal_frontier/terminal.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/goals/goal_frontier/terminal.py) 中的 `goal_frontier_is_terminal_no_followup` 不接受一个手写的 terminal flag。它要求 Todo source 完整且闭合,并且 advancement、monitor、successor、handoff、replan、acceptance、autonomy blocker 等 frontier 均无未解决项;同时还需要结构化的 `no_followup` intent。 diff --git a/docs/book/chapters/source-change-control-plane-rule.md b/docs/book/chapters/source-change-control-plane-rule.md index b07cdeb313..034040ae4e 100644 --- a/docs/book/chapters/source-change-control-plane-rule.md +++ b/docs/book/chapters/source-change-control-plane-rule.md @@ -64,8 +64,8 @@ problem 一个本来可以一行的修复带上一份长期兼容承诺。 本章案例属于第一类。现有 -[`decision_scope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) -已经规定 Gate 是 scoped authority;[State Machines](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/state-machine.md) +[`decision_scope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) +已经规定 Gate 是 scoped authority;[State Machines](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/state-machine.md) 也把 ambiguous scope 导向 repair。 如果实现把它变成全局 wait,应该修实现,无需新增一个"允许全局猜测"的兼容字段。 @@ -413,7 +413,7 @@ invariant、画完协议链,通常要几个小时。换到的东西是:这 一个真正的 additive protocol change 可以合理地跨十几个文件;一个 implementation repair 通常 不应该。 -**边界一:full validation 跑不起全套,这是设计如此。** 本仓库的 [PR 基线](https://github.com/huangruiteng/loopx/blob/main/docs/development/testing-and-quality.md) 包含 lint、type、 +**边界一:full validation 跑不起全套,这是设计如此。** 本仓库的 [PR 基线](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md) 包含 lint、type、 output budget smoke、`pytest` 分层、`loopx canary premerge --from-git-diff` 和 public/private scan;真实路径验证(例如 PostgreSQL integration)需要一个一次性隔离实例。开发阶段应当从最 聚焦的那条命令开始,无需等最宽矩阵。完整公开 smoke fleet 的职责是宽覆盖与健康观察,不是 @@ -443,7 +443,7 @@ diff 和描述来发现,这也是为什么下一章把 PR 描述本身当成 推导出来。 **在 Python facade 里重建 TypeScript 侧规则。** 这是本章开头提到的第二个错误。可以通过 -`loopx canary premerge --from-git-diff` 发现两侧漂移,也可以用 [TypeScript Control-Plane Migration RFC](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/typescript-control-plane-migration-v0.md) +`loopx canary premerge --from-git-diff` 发现两侧漂移,也可以用 [TypeScript Control-Plane Migration RFC](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/typescript-control-plane-migration-v0.md) 判断一处逻辑归谁:它是否已经是一个 domain-owned decision 或 effect receipt。如果答案是肯定的, 改动应落在 TypeScript 侧,Python 侧只做适配或兼容投影。 diff --git a/docs/book/chapters/source-protocol-map.md b/docs/book/chapters/source-protocol-map.md index db60d29766..be06c6307e 100644 --- a/docs/book/chapters/source-protocol-map.md +++ b/docs/book/chapters/source-protocol-map.md @@ -119,11 +119,11 @@ Why the nearest existing owner is or is not sufficient: authority 为准,见[状态底座](state-substrate.md)与 [Shared Goal authority RFC](/loopx/docs/architecture/rfcs/shared-goal-authority-state-provider-v0/); run history 与 rollout events 仍有各自的记录职责; -- [`active_state_structured_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/active-state-structured-projection-v0.md): +- [`active_state_structured_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/active-state-structured-projection-v0.md): 从 active-state workbench 生成 typed、read-only projection; -- [`task_graph_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md): +- [`task_graph_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md): 以只读图表达 Todo、Gate、dependency、validation 与 handoff; -- [`local_state_write_correctness_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/local-state-write-correctness-v0.md): +- [`local_state_write_correctness_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/local-state-write-correctness-v0.md): revision、lock、idempotency key、conflict 与 durable write。 适合从这组协议开始的任务包括: @@ -143,11 +143,11 @@ Why the nearest existing owner is or is not sufficient: 主要入口: -- [`decision_scope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md): +- [`decision_scope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md): Gate 的 kind、granularity、scope coverage 与 fail-closed 行为; -- [`goal_vision_replan_contract_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/goal-vision-replan-contract-v0.md): +- [`goal_vision_replan_contract_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/goal-vision-replan-contract-v0.md): per-Agent Vision、checkpoint、replan 与 bounded route; -- [`peer_agent_runtime_v1`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/peer-agent-runtime-v1.md): +- [`peer_agent_runtime_v1`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/peer-agent-runtime-v1.md): equal peer identity、claim、continuation 与协作边界。 适合从这组协议开始的任务包括: @@ -168,13 +168,13 @@ Why the nearest existing owner is or is not sufficient: 主要入口: -- [`turn_envelope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md): +- [`turn_envelope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md): 在已完成的 quota decision 上提供 bounded next-action read model; -- [`protocol_action_packet_decision_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/protocol-action-packet-decision-v0.md): +- [`protocol_action_packet_decision_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/protocol-action-packet-decision-v0.md): action packet 的决策语义; -- [Status Data Contract](https://github.com/huangruiteng/loopx/blob/main/docs/status-data-contract.md): +- [Status Data Contract](https://github.com/loopx-project/loopx/blob/main/docs/status-data-contract.md): status、attention 与 operator-facing 数据边界; -- [State Machines](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/state-machine.md): +- [State Machines](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/state-machine.md): Todo、Gate、Quota、Evidence 和 Scheduler 如何组合。 这组协议的核心是一个 `should_run` 布尔值之外的有优先级最终合同: @@ -197,15 +197,15 @@ source facts 主要入口: -- [`loopx_turn_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md): +- [`loopx_turn_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md): experimental 的 decide、execute、validate、writeback 与 spend transaction; -- [`session_runtime_loopx_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/session-runtime-loopx-projection-v0.md): +- [`session_runtime_loopx_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/session-runtime-loopx-projection-v0.md): 外部 runtime 到 LoopX 的 read-only first-screen projection; -- [`session_runtime_controlled_writeback_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/session-runtime-controlled-writeback-v0.md): +- [`session_runtime_controlled_writeback_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/session-runtime-controlled-writeback-v0.md): session runtime metadata controlled writeback 的 draft 边界; -- [`host_integration_surface_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md): +- [`host_integration_surface_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md): Host lifecycle read、CLI-equivalent controlled write、能力声明和 fallback; -- [`rollback_packet_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/rollback-packet-v0.md): +- [`rollback_packet_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/rollback-packet-v0.md): 补偿、回滚与证据链。 这里要保持三个责任分离: @@ -226,13 +226,13 @@ source facts 主要入口: -- [`model_behavior_qualification_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/model-behavior-qualification-v0.md): +- [`model_behavior_qualification_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/model-behavior-qualification-v0.md): 何时需要真实模型行为验证; -- [Benchmark 研究 RFC](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md): +- [Benchmark 研究 RFC](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md): 如何保证研究双臂可比并由独立 outcome evidence 支撑; -- [Testing and Quality](https://github.com/huangruiteng/loopx/blob/main/docs/development/testing-and-quality.md): +- [Testing and Quality](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md): unit、contract、smoke、decision replay、canary 与 release gate; -- [Public/Private Boundary](https://github.com/huangruiteng/loopx/blob/main/docs/public-private-boundary.md): +- [Public/Private Boundary](https://github.com/loopx-project/loopx/blob/main/docs/public-private-boundary.md): 哪些证据可以进入公开仓库。 这属于验证设计的一部分,而非最后才补的“测试部分”。协议卡中的 forbidden outcome 和 expected receipt 会直接决定验证形态。 @@ -312,7 +312,7 @@ source facts 外部开发者不应从本地 maintainer state 猜工作。公开入口是: 1. 阅读 - [Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md); + [Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md); 2. 选择 `Starter`、`Focused` 或已达成设计共识的任务; 3. 阅读任务涉及的协议和 validation; 4. 在关联 Issue 中声明准备处理的最小切片; @@ -368,7 +368,7 @@ acceptance、terminal closure、quota budget 与 monitor cadence 四个可检查 这些记录只是学习样本,并非当前任务状态的副本。准备参与时仍要重新打开 Issue,确认它尚未被 关闭、改向或认领,并以 -[Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +[Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) 为当前公开入口;`Maintainer-owned` 工作只能请求独立 helper slice,不能平行复刻。 @@ -379,7 +379,7 @@ acceptance、terminal closure、quota budget 与 monitor cadence 四个可检查 -先从 [RFC Index](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/README.md) +先从 [RFC Index](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/README.md) 读取正式状态。`Accepted`、`Active research`、`Draft` 与 `Draft integration proposal` 允许的动作 不同;一份 RFC 或 Discussion 存在,不等于某个实现已经发布,也不自动生成可认领任务。 @@ -399,7 +399,7 @@ acceptance、terminal closure、quota budget 与 monitor cadence 四个可检查 一份有用的 RFC review 应输出 `accept`、`revise`、`require_evidence` 或 `defer` 之类的明确 disposition,并指出 owner、下一产物与复核条件。需要跨方向同步讨论时,可以进入 -[Open Strategy Review](https://github.com/huangruiteng/loopx/blob/main/docs/community/open-strategy-reviews.md); +[Open Strategy Review](https://github.com/loopx-project/loopx/blob/main/docs/community/open-strategy-reviews.md); 会议不会替代版本化 RFC、bounded Issue、PR review 或 maintainer authority。 diff --git a/docs/book/chapters/source-trace-protocol-chain.md b/docs/book/chapters/source-trace-protocol-chain.md index a6d3d6d5ac..bc4b69054f 100644 --- a/docs/book/chapters/source-trace-protocol-chain.md +++ b/docs/book/chapters/source-trace-protocol-chain.md @@ -129,7 +129,7 @@ typed Todo / Gate facts } ``` -这里由 [`decision_scope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) +这里由 [`decision_scope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) 拥有 scope coverage 语义。最重要的在于: - Gate 明确声明 kind、granularity 与 scope key; @@ -160,7 +160,7 @@ Todo 和 Gate 会进入多个只读表面: - attention queue; - quota input。 -[`task_graph_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md) +[`task_graph_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md) 可以展示 `blocks`、`requires_decision`、`validates` 或 handoff relation,但它不创建 authority。 在本场景中,projection 至少要保留: @@ -251,8 +251,8 @@ if open_gate_count > 0, should_run = false? ### Policy 阅读断点 -以 [State Machines](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/state-machine.md) -和 [Control-Plane Rule Seam Map](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/rule-seam-map.md) +以 [State Machines](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/state-machine.md) +和 [Control-Plane Rule Seam Map](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/rule-seam-map.md) 为地图,确认: 1. 输入 facts 是否已经 normalized; @@ -297,7 +297,7 @@ agent still has independent T2 ## 第 5 站:TurnEnvelope 只承载已决定的下一轮 -[`turn_envelope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md) +[`turn_envelope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md) 是 quota decision 上的 bounded read model。它应携带足够信息,让执行者知道: - Goal、Agent 与 selected Todo; @@ -317,7 +317,7 @@ agent still has independent T2 ## 第 6 站:LoopX Turn 形成 bounded effect -[`loopx_turn_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md) +[`loopx_turn_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md) 把一轮执行约束为: ```text diff --git a/docs/book/chapters/source-validation-to-pr.md b/docs/book/chapters/source-validation-to-pr.md index bd706a3506..dc23375458 100644 --- a/docs/book/chapters/source-validation-to-pr.md +++ b/docs/book/chapters/source-validation-to-pr.md @@ -56,7 +56,7 @@ authority 的改动需要一个一次性隔离实例,跑完整套件是分钟 ## 六层质量证据 -[Testing and Quality](https://github.com/huangruiteng/loopx/blob/main/docs/development/testing-and-quality.md) +[Testing and Quality](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md) 定义了 LoopX 当前的质量分层。本书按外部贡献者的任务重新组织如下。 ### 1. Unit 与 Contract @@ -523,7 +523,7 @@ What remains owner-held? ## 关联 Issue 与公开任务 非 trivial 工作优先关联 -[Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +[Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) 或 GitHub Issue: - 在开始大改前声明准备处理的 slice; diff --git a/docs/book/en/chapters/00-reading-guide.md b/docs/book/en/chapters/00-reading-guide.md index 27ed08d881..073d83c86e 100644 --- a/docs/book/en/chapters/00-reading-guide.md +++ b/docs/book/en/chapters/00-reading-guide.md @@ -257,7 +257,7 @@ If you read an earlier edition of the Dev Book, recalibrate these five areas fir | Area | Shipped in `v0.5.4` | Continue with | | --- | --- | --- | | Control Plane | Complete Turn/Host Todo settlement, quota commit, task-lease lifecycle, Vision refresh, and scheduler-heartbeat transactions have typed TypeScript owners; Python facades still carry migration-time boundaries | [Migration RFC](/loopx/docs/architecture/rfcs/typescript-control-plane-migration-v0/) | -| Operator surface | Personal Workspace exposes Goal, Task, Chat, and read-only status-source entrypoints; the UI is not a new source of truth | [Dashboard README](https://github.com/huangruiteng/loopx/blob/v0.5.4/apps/presentation/dashboard/README.md) | +| Operator surface | Personal Workspace exposes Goal, Task, Chat, and read-only status-source entrypoints; the UI is not a new source of truth | [Dashboard README](https://github.com/loopx-project/loopx/blob/v0.5.4/apps/presentation/dashboard/README.md) | | Host runtime | Codex, Claude Code, OpenCode, Pi, KunlunCode, DeepSeek Harness, and custom runners have distinct activation and stop contracts | [Runtime Connector Catalog](/loopx/docs/integrations/runtime-connector-catalog/) | | Capability and Provider | A Capability is defined by a package-owned catalog entry, a real command, and durable validation; a Provider or Extension does not inherit Kernel authority | [Capability Catalog](/loopx/docs/capabilities/) | | Shared authority | File, NoKV, and PostgreSQL providers remain staged candidates; installing a Provider does not change the default local authority | [Shared Authority RFC](/loopx/docs/architecture/rfcs/shared-goal-authority-state-provider-v0/) | diff --git a/docs/book/en/chapters/02-session-goal-loopx.md b/docs/book/en/chapters/02-session-goal-loopx.md index 596fb26aa6..80630008e3 100644 --- a/docs/book/en/chapters/02-session-goal-loopx.md +++ b/docs/book/en/chapters/02-session-goal-loopx.md @@ -159,7 +159,7 @@ Record completion, independent verifier result, erroneous writes, human interven correctness, wall time, and cost. Without a matched baseline or independent verifier, report experience; do not claim product uplift. -The [benchmark research RFC](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) +The [benchmark research RFC](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) defines the current research boundary. Benchmark-native studies can inform product research only when their arm semantics, authority boundary, and independent verifier are stated explicitly. @@ -287,7 +287,7 @@ inherit the old transcript. LoopX preserves one control-plane contract, but Hosts do not share one wake-up implementation. The current public -[Runtime Connector Catalog](https://github.com/huangruiteng/loopx/blob/main/docs/integrations/runtime-connector-catalog.md) +[Runtime Connector Catalog](https://github.com/loopx-project/loopx/blob/main/docs/integrations/runtime-connector-catalog.md) and each Host adapter's documentation define these main paths: | Host surface | Driver | Key limit | diff --git a/docs/book/en/chapters/core-state-machines.md b/docs/book/en/chapters/core-state-machines.md index 7f49b0ee52..302c3ce1bd 100644 --- a/docs/book/en/chapters/core-state-machines.md +++ b/docs/book/en/chapters/core-state-machines.md @@ -256,11 +256,11 @@ Here, “CAS” is a concurrency-control principle, not a claim that the entire - settlement binds writeback, spend, and scheduler receipts to `goal_id + agent_id + turn_instance_id`. The matching source anchors are -[`completion_transaction.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/completion_transaction.py), -[`local_state_write_correctness.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/runtime/local_state_write_correctness.py), -[`authority_store.ts`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/coordination/authority_store.ts), -[`coordination/authority_core.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/coordination/authority_core.py), -and [`settlement.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/turn_driver/settlement.py). +[`completion_transaction.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/completion_transaction.py), +[`local_state_write_correctness.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/runtime/local_state_write_correctness.py), +[`authority_store.ts`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/coordination/authority_store.ts), +[`coordination/authority_core.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/coordination/authority_core.py), +and [`settlement.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/turn_driver/settlement.py). The real pattern is “read basis -> propose -> validate/guard -> guarded commit -> event or receipt -> readback,” not direct replacement of a state object that merely looks complete. @@ -328,7 +328,7 @@ fact and contract dependencies, not process messages between state machines. ### Todo lifecycle: only four durable statuses -[`loopx/control_plane/todos/contract.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/contract.py) +[`loopx/control_plane/todos/contract.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/contract.py) defines the durable Todo statuses: ```text @@ -400,7 +400,7 @@ that decision. ### Handoff: cleared does not mean the route is complete -[`handoff_gate.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py) +[`handoff_gate.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py) derives six handoff states from Todo relations: | Derived state | Meaning | Next step | @@ -420,7 +420,7 @@ a valid successor, reopening work, or recording `no_followup`, not by changing t ### Quota runtime: decide behavior before considering spend -[`loopx/control_plane/quota/states.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/states.py) +[`loopx/control_plane/quota/states.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/quota/states.py) fixes the decision precedence of quota runtime states: ```text @@ -457,7 +457,7 @@ infer the action from `NOTIFY` (which controls user output only) or from `should ### Settlement: success lands in transaction order -[`turn_transaction_contract.json`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/turn_transaction_contract.json) +[`turn_transaction_contract.json`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/turn_transaction_contract.json) defines the phases of a complete Turn: ```text @@ -565,7 +565,7 @@ it can enter the Monitor write transaction. - Expiry or stop condition reached: complete the Monitor and connect a successor or `no_followup`. For a Goal explicitly promoted to shared authority, -[`todo_monitor_poll.ts`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/coordination/todo_monitor_poll.ts) +[`todo_monitor_poll.ts`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/coordination/todo_monitor_poll.ts) commits a **lease-free observation and its requested independent successors** against one canonical revision, with one CAS and one durable operation receipt. The transaction first validates actor registration, claim/binding/exclusion, an active Monitor, and a genuinely advanced material-change generation. Any failed @@ -689,7 +689,7 @@ flowchart TD ### Terminal is a strict conjunction, not “the queue looks empty” `goal_frontier_is_terminal_no_followup` in -[`loopx/control_plane/goals/goal_frontier/terminal.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/goals/goal_frontier/terminal.py) +[`loopx/control_plane/goals/goal_frontier/terminal.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/goals/goal_frontier/terminal.py) does not accept a handwritten terminal flag. It requires complete and closed Todo sources; no unresolved advancement, monitor, successor, handoff, replan, acceptance, or autonomy-blocker frontier; and a structured `no_followup` intent. diff --git a/docs/book/en/chapters/source-change-control-plane-rule.md b/docs/book/en/chapters/source-change-control-plane-rule.md index 28bb35ba94..211b26f93e 100644 --- a/docs/book/en/chapters/source-change-control-plane-rule.md +++ b/docs/book/en/chapters/source-change-control-plane-rule.md @@ -69,9 +69,9 @@ Misclassifying amplifies the cost of every later step: turning an implementation additive change attaches a long compatibility promise to what should have been a one-line fix. This chapter's case is an implementation repair. Existing -[`decision_scope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) +[`decision_scope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) already makes Gates scoped authority. The public -[State Machines](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/state-machine.md) +[State Machines](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/state-machine.md) already route ambiguous scope toward repair. If implementation turns ambiguity into global wait, repair implementation. Do not add a compatibility flag @@ -428,7 +428,7 @@ requirement, not an estimate. A genuine additive protocol change can legitimatel implementation repair usually should not. **Boundary one: full validation does not fit in one sitting, by design.** The repository -[PR baseline](https://github.com/huangruiteng/loopx/blob/main/docs/development/testing-and-quality.md) includes lint, type, an output-budget smoke, layered `pytest`, `loopx canary premerge --from-git-diff`, +[PR baseline](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md) includes lint, type, an output-budget smoke, layered `pytest`, `loopx canary premerge --from-git-diff`, and a public/private scan; real-path validation such as the PostgreSQL integration suites needs a disposable isolated instance. Start development from the most focused command and do not wait for the widest matrix. The full public smoke fleet exists for broad coverage and health, not for each PR's @@ -465,7 +465,7 @@ can be derived without running the implementation at all. **Rebuilding a TypeScript-side rule inside the Python facade.** This is the second error from the top of the chapter. `loopx canary premerge --from-git-diff` can expose drift between the two sides, and the -[TypeScript Control-Plane Migration RFC](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/typescript-control-plane-migration-v0.md) +[TypeScript Control-Plane Migration RFC](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/typescript-control-plane-migration-v0.md) decides who owns a piece of logic: is it already a domain-owned decision or effect receipt? If it is, the change belongs on the TypeScript side and Python only adapts or projects it compatibly. diff --git a/docs/book/en/chapters/source-protocol-map.md b/docs/book/en/chapters/source-protocol-map.md index c52fdf304e..04b86d5450 100644 --- a/docs/book/en/chapters/source-protocol-map.md +++ b/docs/book/en/chapters/source-protocol-map.md @@ -122,11 +122,11 @@ Start with: - `event_sourced_state_contract_v0` is retired (historical design). Current Todo state follows the selected File/SQLite authority — see [the state substrate](state-substrate.md); run history and rollout events keep their own record responsibilities; -- [`active_state_structured_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/active-state-structured-projection-v0.md) +- [`active_state_structured_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/active-state-structured-projection-v0.md) for the typed read-only projection over the active-state workbench; -- [`task_graph_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md) +- [`task_graph_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md) for read-only Todo, Gate, dependency, validation, and handoff relations; -- [`local_state_write_correctness_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/local-state-write-correctness-v0.md) +- [`local_state_write_correctness_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/local-state-write-correctness-v0.md) for revisions, locks, idempotency keys, conflicts, and durable local writes. Typical jobs: @@ -146,13 +146,13 @@ This family answers: Start with: -- [`decision_scope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) +- [`decision_scope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) for Gate kind, granularity, coverage, and fail-closed behavior; -- [`goal_vision_replan_contract_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/goal-vision-replan-contract-v0.md) +- [`goal_vision_replan_contract_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/goal-vision-replan-contract-v0.md) for per-Agent Vision, checkpoints, replan, and bounded routing; -- [`peer_agent_runtime_v1`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/peer-agent-runtime-v1.md) +- [`peer_agent_runtime_v1`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/peer-agent-runtime-v1.md) for equal peer identity, claims, and continuation; -- [`host_integration_surface_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md) +- [`host_integration_surface_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md) for Host capabilities, controlled writes, and CLI-equivalent fallback. Typical jobs: @@ -173,13 +173,13 @@ This family answers: Start with: -- [`turn_envelope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md) +- [`turn_envelope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md) for a bounded next-action read model over an already computed quota decision; -- [`protocol_action_packet_decision_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/protocol-action-packet-decision-v0.md) +- [`protocol_action_packet_decision_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/protocol-action-packet-decision-v0.md) for action-packet decision semantics; -- the [Status Data Contract](https://github.com/huangruiteng/loopx/blob/main/docs/status-data-contract.md) +- the [Status Data Contract](https://github.com/loopx-project/loopx/blob/main/docs/status-data-contract.md) for status, attention, and operator-facing boundaries; -- [State Machines](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/state-machine.md) +- [State Machines](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/state-machine.md) for composition among Todo, Gate, quota, evidence, and scheduler state. The core contract is a precedence-ordered final result beyond one `should_run` boolean: @@ -202,15 +202,15 @@ This family answers: Start with: -- [`loopx_turn_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md) +- [`loopx_turn_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md) for the experimental decide, execute, validate, writeback, and spend transaction; -- [`session_runtime_loopx_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/session-runtime-loopx-projection-v0.md) +- [`session_runtime_loopx_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/session-runtime-loopx-projection-v0.md) for the read-only first-screen projection from an external runtime into LoopX; -- [`session_runtime_controlled_writeback_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/session-runtime-controlled-writeback-v0.md) +- [`session_runtime_controlled_writeback_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/session-runtime-controlled-writeback-v0.md) for the draft boundary around controlled session-runtime metadata writeback; -- [`host_integration_surface_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md) +- [`host_integration_surface_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md) for typed Host requests, results, capabilities, and fallback; -- [`rollback_packet_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/rollback-packet-v0.md) +- [`rollback_packet_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/rollback-packet-v0.md) for compensation, rollback, and evidence lineage. Keep three responsibilities separate: @@ -231,13 +231,13 @@ This family answers: Start with: -- [`model_behavior_qualification_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/model-behavior-qualification-v0.md) +- [`model_behavior_qualification_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/model-behavior-qualification-v0.md) for cases where real-model behavior adds signal beyond deterministic checks; -- [Benchmark research RFC](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) +- [Benchmark research RFC](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) for matched research arms and independent outcome evidence; -- [Testing and Quality](https://github.com/huangruiteng/loopx/blob/main/docs/development/testing-and-quality.md) +- [Testing and Quality](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md) for unit, contract, smoke, decision replay, canary, and release Gates; -- [Public/Private Boundary](https://github.com/huangruiteng/loopx/blob/main/docs/public-private-boundary.md) +- [Public/Private Boundary](https://github.com/loopx-project/loopx/blob/main/docs/public-private-boundary.md) for evidence that may enter the public repository. Quality is not a final testing appendix. The protocol card's forbidden outcomes and expected receipt should determine the validation design before implementation. @@ -317,7 +317,7 @@ If a document needs twenty function names to explain one behavior, it is probabl Do not infer public work from maintainer-local state. Use public surfaces: 1. Read - the [Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md). + the [Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md). 2. Choose a `Starter`, `Focused`, or already-agreed design task. 3. Read the protocols and validation named by that task. 4. State the smallest intended slice in the linked Issue. @@ -376,7 +376,7 @@ scheduler, storage system, or automatic lease lifecycle. These records are learning examples, not copies of current task state. Before participating, reopen the Issue to confirm that it has not been closed, redirected, or claimed, and use the -[Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +[Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) as the current public entrypoint. For `Maintainer-owned` work, ask for an independent helper slice instead of reproducing the active implementation in parallel. @@ -389,7 +389,7 @@ This section and its Chinese counterpart are semantic mirrors. Start with the -[RFC Index](https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/README.md) +[RFC Index](https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/README.md) and read the formal status. `Accepted`, `Active research`, `Draft`, and `Draft integration proposal` permit different actions. The existence of an RFC or Discussion does not prove that an implementation is shipped, and it does not automatically create claimable work. @@ -411,7 +411,7 @@ the proposed directory tree looks clean. Ask: A useful RFC review returns an explicit disposition such as `accept`, `revise`, `require_evidence`, or `defer`, plus an owner, next artifact, and review condition. Cross-direction questions may enter an -[Open Strategy Review](https://github.com/huangruiteng/loopx/blob/main/docs/community/open-strategy-reviews.md). +[Open Strategy Review](https://github.com/loopx-project/loopx/blob/main/docs/community/open-strategy-reviews.md). A meeting does not replace a versioned RFC, bounded Issue, PR review, or maintainer authority. diff --git a/docs/book/en/chapters/source-trace-protocol-chain.md b/docs/book/en/chapters/source-trace-protocol-chain.md index 20d347b8fa..0a826cd289 100644 --- a/docs/book/en/chapters/source-trace-protocol-chain.md +++ b/docs/book/en/chapters/source-trace-protocol-chain.md @@ -134,7 +134,7 @@ This simplified shape is explanatory, not an importable LoopX configuration: } ``` -[`decision_scope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) +[`decision_scope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/decision-scope-v0.md) owns coverage semantics. The important facts are: - the Gate declares kind, granularity, and scope key; @@ -165,7 +165,7 @@ Todo and Gate facts feed several read models: - attention queue; - quota input. -[`task_graph_projection_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md) +[`task_graph_projection_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/task-graph-projection-v0.md) may display `blocks`, `requires_decision`, `validates`, and handoff relations. It does not create authority. The scenario needs this relationship: @@ -256,8 +256,8 @@ Rules need an explainable first match, suppression conditions, and a reason. Neg ### Policy-reading breakpoints -Use [State Machines](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/state-machine.md) -and the [Rule Seam Map](https://github.com/huangruiteng/loopx/blob/main/docs/product/core-control-plane/rule-seam-map.md) +Use [State Machines](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/state-machine.md) +and the [Rule Seam Map](https://github.com/loopx-project/loopx/blob/main/docs/product/core-control-plane/rule-seam-map.md) to verify: 1. input facts are normalized; @@ -302,7 +302,7 @@ After `interaction_contract` arbitrates the turn, the Host must not reread statu ## Stop 5: TurnEnvelope carries an already-decided turn -[`turn_envelope_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md) +[`turn_envelope_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/turn-envelope-v0.md) is a bounded read model over the quota decision. It carries enough information for execution: - Goal, Agent, and selected Todo; @@ -322,7 +322,7 @@ If the Envelope selects `repair-link-checker`, the Turn remains bound to that ca ## Stop 6: LoopX Turn creates one bounded effect -[`loopx_turn_v0`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md) +[`loopx_turn_v0`](https://github.com/loopx-project/loopx/blob/main/docs/reference/protocols/loopx-turn-v0.md) constrains execution: ```text diff --git a/docs/book/en/chapters/source-validation-to-pr.md b/docs/book/en/chapters/source-validation-to-pr.md index 03aae71d8c..73824ff458 100644 --- a/docs/book/en/chapters/source-validation-to-pr.md +++ b/docs/book/en/chapters/source-validation-to-pr.md @@ -47,7 +47,7 @@ PR. ## Six evidence layers The official -[Testing and Quality](https://github.com/huangruiteng/loopx/blob/main/docs/development/testing-and-quality.md) +[Testing and Quality](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md) guide defines the current quality system. For external contributors, organize it around the job. ### 1. Unit and contract tests @@ -444,7 +444,7 @@ What remains owner-held? ## Link public work, not local runtime state Nontrivial contributions should link -the [Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +the [Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) or a GitHub Issue: - state the intended slice before a large change; diff --git a/docs/book/en/welcome-wagon.md b/docs/book/en/welcome-wagon.md index 425ae6934d..e392465b86 100644 --- a/docs/book/en/welcome-wagon.md +++ b/docs/book/en/welcome-wagon.md @@ -142,11 +142,11 @@ Review the draft and remove anything that should not be public before submitting | Your situation | Use this route | Include | | --- | --- | --- | -| First installation or connection | [First-run feedback](https://github.com/huangruiteng/loopx/issues/new?template=first_run.yml) | Version, OS, Host, and completed steps | -| A run lasting hours or days | [Usage story](https://github.com/huangruiteng/loopx/issues/new?template=usage_story.yml) | Duration, capabilities, recovery, and outcome | -| Reproducible incorrect behavior | [Bug report](https://github.com/huangruiteng/loopx/issues/new?template=bug_report.yml) | Minimal reproduction, expected/actual behavior, sanitized diagnostics | -| Usage or design question | [GitHub Q&A](https://github.com/huangruiteng/loopx/discussions/categories/q-a) | Goal, current version, and attempted route | -| A public workflow or outcome | [Show and tell](https://github.com/huangruiteng/loopx/discussions/categories/show-and-tell) | What ran, evidence, and limitations | +| First installation or connection | [First-run feedback](https://github.com/loopx-project/loopx/issues/new?template=first_run.yml) | Version, OS, Host, and completed steps | +| A run lasting hours or days | [Usage story](https://github.com/loopx-project/loopx/issues/new?template=usage_story.yml) | Duration, capabilities, recovery, and outcome | +| Reproducible incorrect behavior | [Bug report](https://github.com/loopx-project/loopx/issues/new?template=bug_report.yml) | Minimal reproduction, expected/actual behavior, sanitized diagnostics | +| Usage or design question | [GitHub Q&A](https://github.com/loopx-project/loopx/discussions/categories/q-a) | Goal, current version, and attempted route | +| A public workflow or outcome | [Show and tell](https://github.com/loopx-project/loopx/discussions/categories/show-and-tell) | What ran, evidence, and limitations | For informal conversation, join [Discord](https://discord.gg/XmGgQyCFZd). Chat is useful for exploration; final bugs, decisions, and reproducible conclusions should return to an Issue, Discussion, PR, or @@ -164,12 +164,12 @@ Read these in order: direction is shipped, incubating, research, draft, or held; 2. the [Contributor Task Board](/loopx/docs/development/contributor-tasks/) to choose a `Starter / Good First` task or another bounded task with design agreement; -3. [CONTRIBUTING](https://github.com/huangruiteng/loopx/blob/main/CONTRIBUTING.md) for setup, DCO, +3. [CONTRIBUTING](https://github.com/loopx-project/loopx/blob/main/CONTRIBUTING.md) for setup, DCO, public/private boundaries, and validation. The task board is a dynamic source of truth. This book does not copy its current rows. If a task has no Issue, open one with the -[Contributor task form](https://github.com/huangruiteng/loopx/issues/new?template=contributor-task.yml) +[Contributor task form](https://github.com/loopx-project/loopx/issues/new?template=contributor-task.yml) to establish a public coordination boundary. @@ -256,7 +256,7 @@ Include: Do not paste a large log without context or say only that something “does not work.” A good question lets another person reproduce the problem, locate the owner, and propose a next action. See -[LoopX Support](https://github.com/huangruiteng/loopx/blob/main/.github/SUPPORT.md) for channel and +[LoopX Support](https://github.com/loopx-project/loopx/blob/main/.github/SUPPORT.md) for channel and response boundaries. ## Where To Go Next {#next-stop} diff --git a/docs/book/welcome-wagon.md b/docs/book/welcome-wagon.md index 2114825c1c..8a38b2859f 100644 --- a/docs/book/welcome-wagon.md +++ b/docs/book/welcome-wagon.md @@ -136,11 +136,11 @@ loopx first-run-report | 你的情况 | 使用入口 | 应包含 | | --- | --- | --- | -| 第一次安装或连接 | [First-run feedback](https://github.com/huangruiteng/loopx/issues/new?template=first_run.yml) | 版本、OS、Host、完成步骤 | -| 运行了数小时或数天 | [Usage story](https://github.com/huangruiteng/loopx/issues/new?template=usage_story.yml) | 时长、使用能力、恢复方式、结果 | -| 可复现错误 | [Bug report](https://github.com/huangruiteng/loopx/issues/new?template=bug_report.yml) | 最小复现、期望、实际、脱敏诊断 | -| 使用或设计问题 | [GitHub Q&A](https://github.com/huangruiteng/loopx/discussions/categories/q-a) | 目标、当前版本、已尝试路径 | -| 可公开工作流或成果 | [Show and tell](https://github.com/huangruiteng/loopx/discussions/categories/show-and-tell) | 真实运行方式、证据与限制 | +| 第一次安装或连接 | [First-run feedback](https://github.com/loopx-project/loopx/issues/new?template=first_run.yml) | 版本、OS、Host、完成步骤 | +| 运行了数小时或数天 | [Usage story](https://github.com/loopx-project/loopx/issues/new?template=usage_story.yml) | 时长、使用能力、恢复方式、结果 | +| 可复现错误 | [Bug report](https://github.com/loopx-project/loopx/issues/new?template=bug_report.yml) | 最小复现、期望、实际、脱敏诊断 | +| 使用或设计问题 | [GitHub Q&A](https://github.com/loopx-project/loopx/discussions/categories/q-a) | 目标、当前版本、已尝试路径 | +| 可公开工作流或成果 | [Show and tell](https://github.com/loopx-project/loopx/discussions/categories/show-and-tell) | 真实运行方式、证据与限制 | 如果只是想先与其他使用者交流,可以加入 [Discord](https://discord.gg/XmGgQyCFZd)。聊天适合探索;最终 bug、决定和可复现结论应回到 @@ -158,11 +158,11 @@ Issue、Discussion、PR 或版本化文档。 shipped、incubating、research、draft 还是 held; 2. [Contributor Task Board](/loopx/docs/development/contributor-tasks/):选择 `Starter / Good First` 或已有共识的 bounded task; -3. [CONTRIBUTING](https://github.com/huangruiteng/loopx/blob/main/CONTRIBUTING.md):安装、DCO、 +3. [CONTRIBUTING](https://github.com/loopx-project/loopx/blob/main/CONTRIBUTING.md):安装、DCO、 public/private boundary 和验证要求。 任务板是动态事实源。本书不会复制“当前可认领任务”列表;如果任务没有关联 Issue,先用 -[Contributor task 表单](https://github.com/huangruiteng/loopx/issues/new?template=contributor-task.yml) +[Contributor task 表单](https://github.com/loopx-project/loopx/issues/new?template=contributor-task.yml) 建立公开协作边界。 @@ -249,7 +249,7 @@ problem 不要只贴一大段日志,也不要只说“不能用”。好的问题让其他人能复现、判断 owner,并给出下一条 可执行动作。渠道与响应边界见 -[LoopX Support](https://github.com/huangruiteng/loopx/blob/main/.github/SUPPORT.md)。 +[LoopX Support](https://github.com/loopx-project/loopx/blob/main/.github/SUPPORT.md)。 ## 你的下一站 {#next-stop} diff --git a/docs/capability_docs.py b/docs/capability_docs.py index 6560ab6312..98a570ef66 100644 --- a/docs/capability_docs.py +++ b/docs/capability_docs.py @@ -12,7 +12,7 @@ REPOSITORY_ROOT = Path(__file__).resolve().parents[1] -REPOSITORY_BLOB_ROOT = "https://github.com/huangruiteng/loopx/blob/main" +REPOSITORY_BLOB_ROOT = "https://github.com/loopx-project/loopx/blob/main" MARKDOWN_LINK = re.compile( r'(?P!?\[[^\]\n]*\]\()(?P<[^>\n]+>|[^)\s\n]+)(?P(?:\s+["\'][^)\n]*["\'])?\))' ) diff --git a/docs/community/github-maintenance-ops-best-practices.md b/docs/community/github-maintenance-ops-best-practices.md index 1360a2e422..022a8660b1 100644 --- a/docs/community/github-maintenance-ops-best-practices.md +++ b/docs/community/github-maintenance-ops-best-practices.md @@ -220,8 +220,8 @@ monitors actually running on this repository today, split by operating loop. | Loop | Monitor (`target_key`) | Cadence | What it does | | --- | --- | --- | --- | | Maintenance | GitHub issue intake (`github-open-issue-intake`) | 6h | Classify and route newly opened issues | -| Maintenance | Open PR review queue (`github:huangruiteng/loopx:open-pr-review-queue`) | 3m | Scan the PR queue; review only when gates pass | -| Maintenance | Public smoke quality repair (`github:huangruiteng/loopx:public-smoke-quality`) | 15m | Detect and repair public-smoke failures | +| Maintenance | Open PR review queue (`github:loopx-project/loopx:open-pr-review-queue`) | 3m | Scan the PR queue; review only when gates pass | +| Maintenance | Public smoke quality repair (`github:loopx-project/loopx:public-smoke-quality`) | 15m | Detect and repair public-smoke failures | | Maintenance | Non-benchmark quality watch (`public-nonbenchmark-quality-watch`) | 6h | Watch quality regressions outside benchmarks | | Maintenance | Repository quality (`repository-quality-monitor`) | 14d | README first screen, quickstart, public-boundary scan | | Maintenance | Community feedback funnel (`community-feedback-funnel`) | 14d | Align feedback entries and triage | @@ -320,4 +320,4 @@ readback, and publishing stays blocked until an explicit owner decision. - Content-ops capability: [`loopx/capabilities/content_ops/README.md`](../../loopx/capabilities/content_ops/README.md) - Releases v0.4.5 through v0.4.7: - [releases](https://github.com/huangruiteng/loopx/releases) + [releases](https://github.com/loopx-project/loopx/releases) diff --git a/docs/community/github-maintenance-ops-best-practices.zh-CN.md b/docs/community/github-maintenance-ops-best-practices.zh-CN.md index 2dee1d99f2..acb983baa2 100644 --- a/docs/community/github-maintenance-ops-best-practices.zh-CN.md +++ b/docs/community/github-maintenance-ops-best-practices.zh-CN.md @@ -186,8 +186,8 @@ loopx value-connectors source-map --format json # connector-first source map | 循环 | 监控(`target_key`) | cadence | 做什么 | | --- | --- | --- | --- | | 维护 | GitHub issue intake(`github-open-issue-intake`) | 6h | 新 issue 分类并路由 | -| 维护 | Open PR review queue(`github:huangruiteng/loopx:open-pr-review-queue`) | 3m | 扫 PR 队列,门禁通过才评审 | -| 维护 | Public smoke quality repair(`github:huangruiteng/loopx:public-smoke-quality`) | 15m | 发现并修复 public smoke 失败 | +| 维护 | Open PR review queue(`github:loopx-project/loopx:open-pr-review-queue`) | 3m | 扫 PR 队列,门禁通过才评审 | +| 维护 | Public smoke quality repair(`github:loopx-project/loopx:public-smoke-quality`) | 15m | 发现并修复 public smoke 失败 | | 维护 | Non-benchmark quality watch(`public-nonbenchmark-quality-watch`) | 6h | 观察 benchmark 之外的质量回归 | | 维护 | Repository quality(`repository-quality-monitor`) | 14d | README 首屏、quickstart、公开边界扫描 | | 维护 | Community feedback funnel(`community-feedback-funnel`) | 14d | 反馈入口与 triage 对齐 | @@ -279,4 +279,4 @@ item 走 source → angle → draft → feedback → publish gate → readback - Content-ops 能力: [`loopx/capabilities/content_ops/README.md`](../../loopx/capabilities/content_ops/README.md) - v0.4.5 至 v0.4.7: - [releases](https://github.com/huangruiteng/loopx/releases) + [releases](https://github.com/loopx-project/loopx/releases) diff --git a/docs/development/README.md b/docs/development/README.md index 27cbbdf210..83b2b5712d 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -9,7 +9,7 @@ not need these documents to start LoopX. ## Start Here / 从这里开始 -1. Read [Contributing](https://github.com/huangruiteng/loopx/blob/main/CONTRIBUTING.md) for repository boundaries and the +1. Read [Contributing](https://github.com/loopx-project/loopx/blob/main/CONTRIBUTING.md) for repository boundaries and the pull-request checklist. 2. Read [Current technical directions](../project/technical-directions.md) to choose an active program, understand its maturity, and find its tracker. @@ -34,7 +34,7 @@ not need these documents to start LoopX. 10. Follow the [documentation layout policy](documentation-layout.md) before adding or moving public documentation. -1. 先阅读[贡献指南](https://github.com/huangruiteng/loopx/blob/main/CONTRIBUTING.md),了解仓库边界和 PR 检查项。 +1. 先阅读[贡献指南](https://github.com/loopx-project/loopx/blob/main/CONTRIBUTING.md),了解仓库边界和 PR 检查项。 2. 阅读[当前技术方向](../project/technical-directions.zh-CN.md),选择活跃计划、了解 成熟度并找到对应 tracker。 3. 按顺序阅读[开发者手册](/loopx/docs/book/),从控制面基础到项目接入和开发者贡献。 @@ -69,7 +69,7 @@ not need these documents to start LoopX. | Quota and spend semantics / Quota 与 spend 语义 | [Quota allocation](../quota-allocation.md) | | Model-behavior shadow qualification / 模型行为影子验证 | [Model behavior qualification v0](../reference/protocols/model-behavior-qualification-v0.md) | | Release promotion / 发布晋级 | [Release readiness](../product/release-readiness.md) | -| Benchmark research / Benchmark 研究 | [Benchmark workspace](https://github.com/huangruiteng/loopx/blob/main/benchmark/README.md) · [Research RFC](../architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) | +| Benchmark research / Benchmark 研究 | [Benchmark workspace](https://github.com/loopx-project/loopx/blob/main/benchmark/README.md) · [Research RFC](../architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) | ## Change Loop / 变更闭环 diff --git a/docs/development/testing-and-quality.md b/docs/development/testing-and-quality.md index 3484bd5411..fe32212b3b 100644 --- a/docs/development/testing-and-quality.md +++ b/docs/development/testing-and-quality.md @@ -2505,7 +2505,7 @@ reasoning、timeout 与重复次数。任一不匹配或不完整都 fail closed Current benchmark studies follow the [research RFC](../architecture/rfcs/long-horizon-harness-benchmark-research-program-v0.md) -and live in the repository-level [benchmark workspace](https://github.com/huangruiteng/loopx/blob/main/benchmark/README.md). +and live in the repository-level [benchmark workspace](https://github.com/loopx-project/loopx/blob/main/benchmark/README.md). Legacy release reducers are archived and no longer form an active CLI or release qualification surface. diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index 666f1c4e91..508bc81a3a 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -471,7 +471,7 @@ Install one shared local checkout when you want to develop LoopX itself or test a live canary wrapper: ```bash -git clone https://github.com/huangruiteng/loopx ~/loopx +git clone https://github.com/loopx-project/loopx ~/loopx ~/loopx/scripts/install-local.sh loopx doctor ``` @@ -1037,7 +1037,7 @@ The dashboard should answer, before raw log drill-down: - what boundary cannot be crossed yet. See -[apps/presentation/dashboard/README.md](https://github.com/huangruiteng/loopx/blob/main/apps/presentation/dashboard/README.md). +[apps/presentation/dashboard/README.md](https://github.com/loopx-project/loopx/blob/main/apps/presentation/dashboard/README.md). ## Public / Private Boundary @@ -1110,7 +1110,7 @@ that omits dashboard validation; the runtime evidence records that skip. Start here: -- [Documentation index](https://github.com/huangruiteng/loopx/blob/main/docs/README.md) +- [Documentation index](https://github.com/loopx-project/loopx/blob/main/docs/README.md) - [Showcase catalog](../showcases/README.md) - [State interaction model](../state-interaction-model.md) - [Interaction pattern catalog](../concepts/interaction-pattern-catalog.md) @@ -1121,10 +1121,10 @@ Start here: - [Heartbeat automation prompt](../heartbeat-automation-prompt.md) - [Long-task cadence hint](../operations/long-task-cadence-policy.md) - [Public/private boundary](../public-private-boundary.md) -- [Benchmark research workspace](https://github.com/huangruiteng/loopx/blob/main/benchmark/README.md) +- [Benchmark research workspace](https://github.com/loopx-project/loopx/blob/main/benchmark/README.md) - [Dashboard status contract](../status-data-contract.md) - [Codex peer task orchestration](../integrations/codex-subagent-orchestration.md) -- [DeepSWE research practice](https://github.com/huangruiteng/loopx/blob/main/benchmark/deepswe/README.md) +- [DeepSWE research practice](https://github.com/loopx-project/loopx/blob/main/benchmark/deepswe/README.md) ## Command Reference diff --git a/docs/guides/minimal-custom-runtime-example.md b/docs/guides/minimal-custom-runtime-example.md index 0c60935ade..ced8b98753 100644 --- a/docs/guides/minimal-custom-runtime-example.md +++ b/docs/guides/minimal-custom-runtime-example.md @@ -85,4 +85,4 @@ shell, Grok Build, or other cooperative hosts. - [Custom agent runner integration](custom-agent-runner-integration.md) - [Runtime connector catalog](../integrations/runtime-connector-catalog.md) - [Host integration surface v0](../reference/protocols/host-integration-surface-v0.md) -- [LoopX Turn fake-host walkthrough smoke](https://github.com/huangruiteng/loopx/blob/main/examples/loopx-turn-fake-host-walkthrough-smoke.py) +- [LoopX Turn fake-host walkthrough smoke](https://github.com/loopx-project/loopx/blob/main/examples/loopx-turn-fake-host-walkthrough-smoke.py) diff --git a/docs/guides/minimal-custom-runtime-example.zh-CN.md b/docs/guides/minimal-custom-runtime-example.zh-CN.md index b95fa172e9..8c901eafa2 100644 --- a/docs/guides/minimal-custom-runtime-example.zh-CN.md +++ b/docs/guides/minimal-custom-runtime-example.zh-CN.md @@ -80,4 +80,4 @@ python3 examples/loopx-turn-fake-host-walkthrough-smoke.py - [Custom agent runner integration](custom-agent-runner-integration.md) - [Runtime connector catalog](../integrations/runtime-connector-catalog.md) - [Host integration surface v0](../reference/protocols/host-integration-surface-v0.md) -- [LoopX Turn fake-host walkthrough smoke](https://github.com/huangruiteng/loopx/blob/main/examples/loopx-turn-fake-host-walkthrough-smoke.py) +- [LoopX Turn fake-host walkthrough smoke](https://github.com/loopx-project/loopx/blob/main/examples/loopx-turn-fake-host-walkthrough-smoke.py) diff --git a/docs/index.md b/docs/index.md index d2ce1467d3..1a6e48416f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -84,7 +84,7 @@ The docs site is a published read model over repository Markdown. The canonical source remains the Markdown in `docs/`, while project-local runtime state stays ignored and private. -- [Project README](https://github.com/huangruiteng/loopx#readme) +- [Project README](https://github.com/loopx-project/loopx#readme) - [Public/private boundary](public-private-boundary.md) - [Status data contract](status-data-contract.md) - [Release readiness](product/release-readiness.md) diff --git a/docs/integrations/worker-bridge-install-contract.md b/docs/integrations/worker-bridge-install-contract.md index 824065d83f..f20e392cd7 100644 --- a/docs/integrations/worker-bridge-install-contract.md +++ b/docs/integrations/worker-bridge-install-contract.md @@ -43,7 +43,7 @@ archaeology in [Git history](https://github.com/loopx-project/loopx/tree/54d42da44283bb414b24f71d16642c25cbcaf5dd/deprecate/benchmark-legacy), outside the working tree. New benchmark work should start from the -[`benchmark/`](https://github.com/huangruiteng/loopx/blob/main/benchmark/README.md) research workspace and keep runner and +[`benchmark/`](https://github.com/loopx-project/loopx/blob/main/benchmark/README.md) research workspace and keep runner and verifier semantics benchmark-native. ## Validation diff --git a/docs/product/core-control-plane/state-machine.md b/docs/product/core-control-plane/state-machine.md index 01eb54c25f..c8879f4178 100644 --- a/docs/product/core-control-plane/state-machine.md +++ b/docs/product/core-control-plane/state-machine.md @@ -12,19 +12,19 @@ public-safe map over the current repository contracts, especially: derived runtime names; - [`interaction-catalog.md`](interaction-catalog.md) for reusable interaction patterns; -- [`loopx/control_plane/todos/contract.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/contract.py) for todo status, +- [`loopx/control_plane/todos/contract.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/contract.py) for todo status, task class, decision scope, resume, claim, and monitor metadata fields; -- [`loopx/quota.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/quota.py) for `quota should-run`, runtime +- [`loopx/quota.py`](https://github.com/loopx-project/loopx/blob/main/loopx/quota.py) for `quota should-run`, runtime states, `effective_action`, `interaction_contract`, spend, and monitor poll contracts; -- [`loopx/control_plane/scheduler/scheduler_hint.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/scheduler/scheduler_hint.py) +- [`loopx/control_plane/scheduler/scheduler_hint.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/scheduler/scheduler_hint.py) for cadence/backoff/reset-token behavior; - [`goal_vision_replan_contract_v0`](../../reference/protocols/goal-vision-replan-contract-v0.md) for bounded per-agent vision, replan transitions, and goal-route projection; - cross-agent handoff gate states in - [`loopx/control_plane/todos/handoff_gate.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py); -- [`loopx/project_map.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/project_map.py) and - [`loopx/bootstrap.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/bootstrap.py) for project registration, + [`loopx/control_plane/todos/handoff_gate.py`](https://github.com/loopx-project/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py); +- [`loopx/project_map.py`](https://github.com/loopx-project/loopx/blob/main/loopx/project_map.py) and + [`loopx/bootstrap.py`](https://github.com/loopx-project/loopx/blob/main/loopx/bootstrap.py) for project registration, read-only-map opt-in, global sync, and host-loop activation. ## Composition Contract diff --git a/docs/product/release-note-template.md b/docs/product/release-note-template.md index 3768704015..bdf5133831 100644 --- a/docs/product/release-note-template.md +++ b/docs/product/release-note-template.md @@ -152,7 +152,7 @@ opt-in surface, replace the no-change declaration with one entry per surface: **Authority boundary:** -**Docs:** https://github.com/huangruiteng/loopx/blob/vX.Y.Z/ +**Docs:** https://github.com/loopx-project/loopx/blob/vX.Y.Z/ ```bash @@ -256,4 +256,4 @@ Apache-2.0 不限制商业使用;显式专利框架服务于未来企业与生 - -Compare: https://github.com/huangruiteng/loopx/compare/vPREVIOUS...vX.Y.Z +Compare: https://github.com/loopx-project/loopx/compare/vPREVIOUS...vX.Y.Z diff --git a/docs/product/runtimes/codex-cli/codex-cli-packaged-install.md b/docs/product/runtimes/codex-cli/codex-cli-packaged-install.md index e92532e055..23055b3e52 100644 --- a/docs/product/runtimes/codex-cli/codex-cli-packaged-install.md +++ b/docs/product/runtimes/codex-cli/codex-cli-packaged-install.md @@ -122,7 +122,7 @@ For contributors and registered peers working on LoopX itself, keep using a real checkout: ```bash -git clone https://github.com/huangruiteng/loopx ~/loopx +git clone https://github.com/loopx-project/loopx ~/loopx ~/loopx/scripts/install-local.sh loopx doctor loopx-canary doctor diff --git a/docs/project/authors.md b/docs/project/authors.md index 3f8bb5ea58..a5779d3b6c 100644 --- a/docs/project/authors.md +++ b/docs/project/authors.md @@ -13,8 +13,8 @@ on 2026-05-31. The public product surface adopted the LoopX name on LoopX recognizes all accepted commit authors, co-authors, reviewers, issue reporters, and documentation contributors. The living contributor record is: -- the repository's [Git history](https://github.com/huangruiteng/loopx/commits/main/); -- GitHub's [Contributors view](https://github.com/huangruiteng/loopx/graphs/contributors); +- the repository's [Git history](https://github.com/loopx-project/loopx/commits/main/); +- GitHub's [Contributors view](https://github.com/loopx-project/loopx/graphs/contributors); - merged pull requests and their review history. This file intentionally does not maintain a ranked or hand-copied contributor diff --git a/docs/project/history.md b/docs/project/history.md index 2d5065cdd7..098907dd5b 100644 --- a/docs/project/history.md +++ b/docs/project/history.md @@ -2,7 +2,7 @@ This page records the public milestones that changed LoopX's identity, governance, or stable product direction. It is not a commit-by-commit changelog. -Ordinary release changes belong in [GitHub Releases](https://github.com/huangruiteng/loopx/releases) +Ordinary release changes belong in [GitHub Releases](https://github.com/loopx-project/loopx/releases) and the [update notes](../update-notes/README.md). ## Public Timeline @@ -54,7 +54,7 @@ and explicit handoff state. [LoopX v0.2.0](https://github.com/huangruiteng/loopx/releases/tag/v0.2.0) promoted the peer-agent runtime and expanded long-lived issue-fix, PR lifecycle, Explore, and control-plane validation surfaces. The v0.2 line continues in the -public [release archive](https://github.com/huangruiteng/loopx/releases). +public [release archive](https://github.com/loopx-project/loopx/releases). ## How This History Is Maintained @@ -66,7 +66,7 @@ public [release archive](https://github.com/huangruiteng/loopx/releases). - Keep private operating context, raw trajectories, internal links, and local paths out of the public timeline. -See [AUTHORS.md](https://github.com/huangruiteng/loopx/blob/main/docs/project/authors.md) for +See [AUTHORS.md](https://github.com/loopx-project/loopx/blob/main/docs/project/authors.md) for creator and contributor attribution and -[Governance](https://github.com/huangruiteng/loopx/blob/main/.github/GOVERNANCE.md) +[Governance](https://github.com/loopx-project/loopx/blob/main/.github/GOVERNANCE.md) for the current maintainer model. diff --git a/docs/project/technical-directions.md b/docs/project/technical-directions.md index e5ec5b468d..f1c634f56c 100644 --- a/docs/project/technical-directions.md +++ b/docs/project/technical-directions.md @@ -41,7 +41,7 @@ Use these delivery maturity terms consistently: Goals, typed todos, quota, scheduler hints, evidence, Effect Program settlement, recovery, and host parity remain the shared substrate under every strategic program. Their reliability work continues through the -[Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +[Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) and the `control-plane` label. It is ongoing product hardening, not a competing source of direction. @@ -107,7 +107,7 @@ Promotion to `main` follows this ledger: `@maxliux5` is the current implementation lead, not a repository-wide maintainer appointment. Lark-specific paths follow the subsystem review route -recorded in [project governance](https://github.com/huangruiteng/loopx/blob/main/.github/GOVERNANCE.md); +recorded in [project governance](https://github.com/loopx-project/loopx/blob/main/.github/GOVERNANCE.md); cross-subsystem and mainline promotion decisions remain with the lead maintainer. @@ -150,7 +150,7 @@ not change the stages, promotion gates or implementation authorization here. 1. Choose the closest direction tracker and read its current stage and boundary. 2. Find a bounded task on the - [Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md), + [Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md), or open a contributor task issue that names the direction, intended base branch, smallest slice, non-goals, and validation. diff --git a/docs/project/technical-directions.zh-CN.md b/docs/project/technical-directions.zh-CN.md index bdd7f46d8f..b556ad7a08 100644 --- a/docs/project/technical-directions.zh-CN.md +++ b/docs/project/technical-directions.zh-CN.md @@ -38,7 +38,7 @@ Goal、typed todo、quota、scheduler hint、evidence、Effect Program settlement、 recovery 与 host parity 是所有战略方向共用的底座。其可靠性工作继续通过 -[Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +[Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) 和 `control-plane` label 推进;这是持续的产品 hardening,不是另一套方向事实源。 @@ -97,7 +97,7 @@ matched baseline(或显式标为更弱的 baseline)、acceptance criteria、 public fixture 或浏览器状态。 `@maxliux5` 是当前 implementation lead,不代表仓库级 maintainer 任命。Lark 专属 -路径遵循[项目治理](https://github.com/huangruiteng/loopx/blob/main/.github/GOVERNANCE.md) +路径遵循[项目治理](https://github.com/loopx-project/loopx/blob/main/.github/GOVERNANCE.md) 记录的 subsystem review route; 跨子域和 mainline 晋级决策仍由 lead maintainer 负责。 @@ -131,7 +131,7 @@ module 或重复 authority。 ## 贡献与治理闭环 1. 选择最接近的 direction tracker,阅读当前阶段与边界。 -2. 在 [Contributor Task Board](https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md) +2. 在 [Contributor Task Board](https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md) 寻找有界任务;如果没有, 用 contributor task 模板创建 issue,写明方向、目标 base branch、最小切片、 non-goal 与验证方式。 diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index 567b79cb26..b907de93e3 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -2107,7 +2107,7 @@ Codex turn actually consumes quota. The smallest public-safe event is ``` The public fixture is -[`examples/quota-slot-spend-event.example.json`](https://github.com/huangruiteng/loopx/blob/main/examples/quota-slot-spend-event.example.json). +[`examples/quota-slot-spend-event.example.json`](https://github.com/loopx-project/loopx/blob/main/examples/quota-slot-spend-event.example.json). Validation rule: diff --git a/docs/research/README.md b/docs/research/README.md index c32aa3e7b9..a119eda477 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -38,7 +38,7 @@ establish an equal-budget efficiency gain or a general performance guarantee. ([中文](budgeted-research-planning.zh-CN.md)): why conditional plans, costly measurements and causal comparisons serve better long-budget outcomes; links the existing Stride/Yardstick owners to the EdgeBench pilot and later learning. -- [Benchmark research workspace](https://github.com/huangruiteng/loopx/blob/main/benchmark/README.md): current protocols, +- [Benchmark research workspace](https://github.com/loopx-project/loopx/blob/main/benchmark/README.md): current protocols, benchmark-specific practice, and links to the governing research RFC. - [Legacy benchmark history](https://github.com/loopx-project/loopx/tree/54d42da44283bb414b24f71d16642c25cbcaf5dd/deprecate/benchmark-legacy): retired runners, adapters, and historical packets removed from the working diff --git a/docs/showcases/cases/dsh-loopx-replan-demo.md b/docs/showcases/cases/dsh-loopx-replan-demo.md index 02e3a2178f..7cdea9dc69 100644 --- a/docs/showcases/cases/dsh-loopx-replan-demo.md +++ b/docs/showcases/cases/dsh-loopx-replan-demo.md @@ -91,7 +91,7 @@ request to post automatically. 约束变化,不应该抹掉长程任务的决策与证据链。 -https://github.com/huangruiteng/loopx +https://github.com/loopx-project/loopx ### English @@ -106,4 +106,4 @@ became 4, all 3 behavior tests passed, and the GoalBar closed at 2/2. Changing constraints should not erase the decision and evidence trail of a long-running task. -https://github.com/huangruiteng/loopx +https://github.com/loopx-project/loopx diff --git a/examples/dev-book-publication-smoke.py b/examples/dev-book-publication-smoke.py index c380293e6c..32092a6840 100644 --- a/examples/dev-book-publication-smoke.py +++ b/examples/dev-book-publication-smoke.py @@ -148,7 +148,7 @@ def assert_community_casebook_is_bilingual() -> None: "https://github.com/huangruiteng/loopx/discussions/3069", "https://github.com/huangruiteng/loopx/issues/2353", "https://github.com/huangruiteng/loopx/issues/3549", - "https://github.com/huangruiteng/loopx/blob/main/docs/development/contributor-tasks.md", + "https://github.com/loopx-project/loopx/blob/main/docs/development/contributor-tasks.md", ), ), ( @@ -156,9 +156,9 @@ def assert_community_casebook_is_bilingual() -> None: protocol_map_en, "rfc-review-lab", ( - "https://github.com/huangruiteng/loopx/blob/main/docs/architecture/rfcs/README.md", + "https://github.com/loopx-project/loopx/blob/main/docs/architecture/rfcs/README.md", "https://github.com/huangruiteng/loopx/discussions/3157", - "https://github.com/huangruiteng/loopx/blob/main/docs/community/open-strategy-reviews.md", + "https://github.com/loopx-project/loopx/blob/main/docs/community/open-strategy-reviews.md", ), ), ( diff --git a/examples/export-frontstage-share-bundle.mjs b/examples/export-frontstage-share-bundle.mjs index 910fb1e736..517e9d2871 100644 --- a/examples/export-frontstage-share-bundle.mjs +++ b/examples/export-frontstage-share-bundle.mjs @@ -188,7 +188,7 @@ async function copyInteractiveCasePages(siteDir) { if (/^(?:https?:|\/)/.test(href)) return match; const source = relative(repoRoot, resolve(dirname(sourcePath), href)); if (source === showcaseCatalogPath || source.startsWith("../")) return match; - return `href="https://github.com/huangruiteng/loopx/blob/main/${source}"`; + return `href="https://github.com/loopx-project/loopx/blob/main/${source}"`; }); await writeFile(targetPath, html); } diff --git a/examples/frontstage-share-bundle-smoke.mjs b/examples/frontstage-share-bundle-smoke.mjs index e9304c0c33..771d58f99e 100644 --- a/examples/frontstage-share-bundle-smoke.mjs +++ b/examples/frontstage-share-bundle-smoke.mjs @@ -226,7 +226,7 @@ run(process.execPath, [resolve(repoRoot, "examples/export-frontstage-share-bundl if (await readFile(resolve(siteDir, "index.html"), "utf8") !== originalHomepage) throw new Error("case restore replaced the homepage"); assertExists(resolve(siteDir, "docs/showcases/showcase-catalog.json")); const restoredCase = await readFile(resolve(siteDir, "docs/showcases/cases/0619-loopx-self-iteration.en.html"), "utf8"); -if (!restoredCase.includes("https://github.com/huangruiteng/loopx/blob/main/docs/showcases/cases/0619-loopx-self-iteration.md")) { +if (!restoredCase.includes("https://github.com/loopx-project/loopx/blob/main/docs/showcases/cases/0619-loopx-self-iteration.md")) { throw new Error("case narrative source must not point to an unshipped Markdown URL"); } diff --git a/examples/release-artifacts-smoke.py b/examples/release-artifacts-smoke.py index 0cda949886..97db89eb40 100644 --- a/examples/release-artifacts-smoke.py +++ b/examples/release-artifacts-smoke.py @@ -126,7 +126,11 @@ def commit(message: str) -> str: initializer.write('\nraise RuntimeError("artifact inspection executed the candidate")\n') artifacts = [*packages.iterdir(), root / "dist/SHA256SUMS"] before = {path.name: digest(path) for path in artifacts} - env = {**os.environ, "RELEASE_TAG": identity.tag, "GITHUB_SHA": correction, + python_bin = str(Path(sys.executable).resolve().parent) + path_value = os.pathsep.join( + [python_bin, *( [os.environ["PATH"]] if os.environ.get("PATH") else [] )] + ) + env = {**os.environ, "PATH": path_value, "RELEASE_TAG": identity.tag, "GITHUB_SHA": correction, "GITHUB_WORKFLOW_REF": "fixture/release-artifacts.yml@reviewed"} def execute(block: str, fixture: str = "") -> subprocess.CompletedProcess[str]: diff --git a/loopx/capabilities/project_skill_delivery/README.md b/loopx/capabilities/project_skill_delivery/README.md index c1257682b2..ba6b0ab962 100644 --- a/loopx/capabilities/project_skill_delivery/README.md +++ b/loopx/capabilities/project_skill_delivery/README.md @@ -99,9 +99,9 @@ workflow globally discoverable and also permits an explicitly requested project copy. Missing or unknown markers are rejected by project delivery; an unmarked source is not implicitly eligible. -The six packaged workflows (`loopx-project`, `loopx-self-repair`, -`loopx-pr-review`, `loopx-pr-program`, `loopx-doc-registry`, and -`loopx-benchmark`) declare `global`. Connection, repair, review, and shared +The seven packaged workflows (`loopx-project`, `loopx-self-repair`, +`loopx-pr-review`, `loopx-pr-program`, `loopx-doc-registry`, +`loopx-benchmark`, and `loopx-performance-diagnosis`) declare `global`. Connection, repair, review, and shared workflow instructions must be available before a project installs a local copy. Their existing task, project, and permission checks still apply. `loopx-material` and `loopx-change-quality` remain `project` workflows. diff --git a/packages/loopx-codex-provider-routing/tests/test_provider_lifecycle.py b/packages/loopx-codex-provider-routing/tests/test_provider_lifecycle.py index 57994001f7..406b402db0 100644 --- a/packages/loopx-codex-provider-routing/tests/test_provider_lifecycle.py +++ b/packages/loopx-codex-provider-routing/tests/test_provider_lifecycle.py @@ -2,7 +2,6 @@ import importlib import io import json -import os from pathlib import Path import subprocess import sys diff --git a/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py b/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py index 19e9a1f059..e7d1a269c7 100644 --- a/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py +++ b/packages/loopx-codex-provider-routing/tests/test_steward_native_owner.py @@ -1,5 +1,4 @@ """Read-only consumers reuse the native owner and exact host profile.""" -import json import sys from pathlib import Path diff --git a/packages/loopx-repo-health/README.md b/packages/loopx-repo-health/README.md index 9eaff8ffff..97c9f75f45 100644 --- a/packages/loopx-repo-health/README.md +++ b/packages/loopx-repo-health/README.md @@ -72,8 +72,8 @@ Direct CLI: ```bash loopx-repo-health --doctor -loopx-repo-health snapshot --owner huangruiteng --repo loopx --format json -loopx-repo-health snapshot --owner huangruiteng --repo loopx --format md +loopx-repo-health snapshot --owner loopx-project --repo loopx --format json +loopx-repo-health snapshot --owner loopx-project --repo loopx --format md ``` `schemas/request.schema.json` and `schemas/response.schema.json` are the diff --git a/packages/loopx-repo-health/src/loopx_repo_health/cli.py b/packages/loopx-repo-health/src/loopx_repo_health/cli.py index 54101b06d9..ad8ccf25d4 100644 --- a/packages/loopx-repo-health/src/loopx_repo_health/cli.py +++ b/packages/loopx-repo-health/src/loopx_repo_health/cli.py @@ -6,7 +6,7 @@ from collections.abc import Sequence from typing import Any -from .contract import SNAPSHOT_SCHEMA_VERSION, validate_snapshot +from .contract import validate_snapshot from .github import GitHubRepoHealthCollector from .render import render_markdown diff --git a/packages/loopx-repo-health/src/loopx_repo_health/github.py b/packages/loopx-repo-health/src/loopx_repo_health/github.py index 1f818b1e29..e4f4f2d2a6 100644 --- a/packages/loopx-repo-health/src/loopx_repo_health/github.py +++ b/packages/loopx-repo-health/src/loopx_repo_health/github.py @@ -10,7 +10,6 @@ import json import os import re -import time import urllib.error import urllib.parse import urllib.request @@ -19,7 +18,7 @@ from statistics import quantiles from typing import Any -from .contract import RepoHealthSnapshot, SNAPSHOT_SCHEMA_VERSION +from .contract import RepoHealthSnapshot API_BASE = "https://api.github.com" diff --git a/scripts/qualify-doubao-capability-monitor-repair-tool-live.py b/scripts/qualify-doubao-capability-monitor-repair-tool-live.py index db7a23c39d..e47f274e27 100755 --- a/scripts/qualify-doubao-capability-monitor-repair-tool-live.py +++ b/scripts/qualify-doubao-capability-monitor-repair-tool-live.py @@ -12,10 +12,10 @@ if sys.path[0] != repo_root_text: sys.path.insert(0, repo_root_text) -from loopx.control_plane.testing.capability_monitor_repair_tool_behavior import ( +from loopx.control_plane.testing.capability_monitor_repair_tool_behavior import ( # noqa: E402 DoubaoCapabilityMonitorRepairToolBehaviorActor, ) -from loopx.control_plane.testing.release_commit_qualification import ( +from loopx.control_plane.testing.release_commit_qualification import ( # noqa: E402 collect_release_source_identity, ) diff --git a/scripts/qualify-doubao-scoped-gate-successor-tool-live.py b/scripts/qualify-doubao-scoped-gate-successor-tool-live.py index e73f6e6094..7f4c2d59b0 100755 --- a/scripts/qualify-doubao-scoped-gate-successor-tool-live.py +++ b/scripts/qualify-doubao-scoped-gate-successor-tool-live.py @@ -12,10 +12,10 @@ if sys.path[0] != repo_root_text: sys.path.insert(0, repo_root_text) -from loopx.control_plane.testing.release_commit_qualification import ( +from loopx.control_plane.testing.release_commit_qualification import ( # noqa: E402 collect_release_source_identity, ) -from loopx.control_plane.testing.scoped_gate_successor_tool_behavior import ( +from loopx.control_plane.testing.scoped_gate_successor_tool_behavior import ( # noqa: E402 DoubaoScopedGateSuccessorToolBehaviorActor, ) diff --git a/scripts/qualify-doubao-selected-todo-tool-live.py b/scripts/qualify-doubao-selected-todo-tool-live.py index d9fa9ec851..e90827db78 100755 --- a/scripts/qualify-doubao-selected-todo-tool-live.py +++ b/scripts/qualify-doubao-selected-todo-tool-live.py @@ -12,10 +12,10 @@ if sys.path[0] != repo_root_text: sys.path.insert(0, repo_root_text) -from loopx.control_plane.testing.release_commit_qualification import ( +from loopx.control_plane.testing.release_commit_qualification import ( # noqa: E402 collect_release_source_identity, ) -from loopx.control_plane.testing.selected_todo_tool_behavior import ( +from loopx.control_plane.testing.selected_todo_tool_behavior import ( # noqa: E402 DoubaoSelectedTodoToolBehaviorActor, ) diff --git a/scripts/runtime_artifact.py b/scripts/runtime_artifact.py index 9c4316c700..537cdd52c3 100644 --- a/scripts/runtime_artifact.py +++ b/scripts/runtime_artifact.py @@ -22,8 +22,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -from loopx.presentation.chat_bundle import source_digest, validate_bundle -from loopx.cli_commands.update_artifact import RUNTIME_ARTIFACT_SCHEMA_VERSION, validate_manifest +from loopx.presentation.chat_bundle import source_digest, validate_bundle # noqa: E402 +from loopx.cli_commands.update_artifact import RUNTIME_ARTIFACT_SCHEMA_VERSION, validate_manifest # noqa: E402 PATHS = ("loopx", "scripts", "skills", "docs", "man", "examples", "apps/presentation", ".github", "README.md", "LICENSE", "NOTICE", "LICENSE-MIT", "pyproject.toml", "setup.py", "MANIFEST.in") diff --git a/skills/loopx-self-repair/SKILL.md b/skills/loopx-self-repair/SKILL.md index 3e3d0b632a..5898242056 100644 --- a/skills/loopx-self-repair/SKILL.md +++ b/skills/loopx-self-repair/SKILL.md @@ -83,7 +83,7 @@ verify that the public entrypoint admits independent work before continuing it. Preserve actual authority, budget and stop conditions; when no useful authorized work remains, retain the evidenced wait rather than inventing activity. Never erase receipts or fabricate progress to escape a wait. See -[settlement classification](../../docs/quota-allocation.md#allocation-contract). +[settlement classification](https://github.com/loopx-project/loopx/blob/main/docs/quota-allocation.md#allocation-contract). ## Upstream Issue Escalation @@ -187,9 +187,9 @@ replan, or terminal closeout must return to the strict semantic checkpoint. - For guarded public GitHub issue escalation, read `references/upstream-issue-escalation.md`. - For user/agent/state channel semantics, read - `../../docs/state-interaction-model.md` and - `../../docs/concepts/interaction-pattern-catalog.md`. + [docs/state-interaction-model.md](https://github.com/loopx-project/loopx/blob/main/docs/state-interaction-model.md) and + [docs/concepts/interaction-pattern-catalog.md](https://github.com/loopx-project/loopx/blob/main/docs/concepts/interaction-pattern-catalog.md). - For quota and heartbeat decisions, read - `../../docs/quota-allocation.md` and - `../../docs/heartbeat-automation-prompt.md`. -- For commit/PR hygiene failures, read `../../AGENTS.md`. + [docs/quota-allocation.md](https://github.com/loopx-project/loopx/blob/main/docs/quota-allocation.md) and + [docs/heartbeat-automation-prompt.md](https://github.com/loopx-project/loopx/blob/main/docs/heartbeat-automation-prompt.md). +- For commit/PR hygiene failures, read [AGENTS.md](https://github.com/loopx-project/loopx/blob/main/AGENTS.md). diff --git a/skills/loopx-self-repair/references/repair-patterns.md b/skills/loopx-self-repair/references/repair-patterns.md index 9d78b5c38d..647c7d22e2 100644 --- a/skills/loopx-self-repair/references/repair-patterns.md +++ b/skills/loopx-self-repair/references/repair-patterns.md @@ -65,7 +65,7 @@ teaches a reusable control-plane lesson. | `acceptance_hold_recovery_selection_split` | Newly created advancement work is acceptance-unbound, repeated vision replans never expose its hold, or a replan packet also selects an unrelated due monitor. | Canonical acceptance tasks, scoped source Todos, bounded trigger checkpoints, effective action and original Turn receipt. | Recovery covered stale associations only; generic vision gaps displaced hold identities; candidate inventory leaked into the selected execution target. | Route missing and stale associations through the existing bounded replan lane, retain exact hold checkpoints before generic gaps, and separate replan from candidate selection. Keep owner association and completion validation enforced. A new unbound repair Todo is not runnable recovery; only a qualified successor or concrete blocker settles the exact hold. Validate real File/SQLite CLI paths and receipt reentry without mutating an active Goal. | | `acceptance_validation_failure_flattened` | A bound Todo is `ready` and its ordinary validator passes, yet completion reports only `goal_acceptance_validation_rejected`; the agent searches contract bindings before discovering a workspace or runner failure. | Exact Todo acceptance state, completion's typed criterion failure, recorded delivery workspace, current worktree cleanliness, and the privacy-safe runner receipt. | The completion boundary collapsed a failed criterion receipt into a generic contract error, hiding the workspace or command status. | Project the failed criterion ID, allowlisted validation status, safe exit code and bounded next action without command output or local paths. Repair the execution context and retry under the same Turn/lease; do not rebind owner criteria or infer a Goal-wide hold. | | `review_compatibility_assumption_gap` | A correct fix retains parallel protocol paths, and the review treats historical receipt recovery as proof that every old request decoder is needed. | Published review, structured compatibility rationale, real caller/deployment inventory, stored request versus receipt shape, and smaller-design readback. | Re-review verifies the last bug but does not separate compatibility obligations or test consolidation; free-text claims pass as evidence. | Replace the capability's existing compatibility rationale with a bounded structured assessment. Distinguish transient requests, independent client rollout and persisted replay formats; compare one typed current contract; preserve real legacy consumers. Cover needless retention and unsafe removal with positive twins. Keep optional simplifications advisory and do not make field completeness certify evidence truth. | -| `review_outcome_continuity_gap` | Local feature checks pass while later work starves, recovery only records a blocker, or ordinary users face new repeated intervention. | Accepted product outcome, published review, real later invocations, affected user surfaces, durable progress and authorized recovery. | Review proved one operation or prevention of bypass without checking sustained progress and the complete user journey. | Make long-horizon continuity and user experience explicit judgments in the existing problem context. Reuse bounded real walkthroughs; apply scope counterexamples when gates are involved. Accept deliberate waits only with an independent basis and recovery or safe terminal route. Qualify with exact-source historical counterexamples and repaired positive controls; keep old verdicts out of model inputs and distinguish reported historical checks from newly executed tests. Section length and declared evidence cannot certify truth. For frontend friction, compare the shortest authorized task path before encoding the UI sequence; inspect populated composition and real state readback. Record fixture/build/install boundaries and repair the existing delivery workflow, not a second checklist. For architecture/RFC reviews, distinguish a docs-only diff from a design that commits future caller journeys. Reuse the [PR #5944 comparison and qualified experience](../../../loopx/capabilities/pr_review_queue/experiences/README.md); keep differing frames and unresolved outcomes, then test current-head adoption separately from context delivery and utility. | +| `review_outcome_continuity_gap` | Local feature checks pass while later work starves, recovery only records a blocker, or ordinary users face new repeated intervention. | Accepted product outcome, published review, real later invocations, affected user surfaces, durable progress and authorized recovery. | Review proved one operation or prevention of bypass without checking sustained progress and the complete user journey. | Make long-horizon continuity and user experience explicit judgments in the existing problem context. Reuse bounded real walkthroughs; apply scope counterexamples when gates are involved. Accept deliberate waits only with an independent basis and recovery or safe terminal route. Qualify with exact-source historical counterexamples and repaired positive controls; keep old verdicts out of model inputs and distinguish reported historical checks from newly executed tests. Section length and declared evidence cannot certify truth. For frontend friction, compare the shortest authorized task path before encoding the UI sequence; inspect populated composition and real state readback. Record fixture/build/install boundaries and repair the existing delivery workflow, not a second checklist. For architecture/RFC reviews, distinguish a docs-only diff from a design that commits future caller journeys. Reuse the [PR #5944 comparison and qualified experience](https://github.com/loopx-project/loopx/blob/main/loopx/capabilities/pr_review_queue/experiences/README.md); keep differing frames and unresolved outcomes, then test current-head adoption separately from context delivery and utility. | | `goal_activation_consumer_drift` | A canonically stopped Goal still accepts new peer requests, delegations, Chat execution, scheduled work, or another effect. | The registry Goal's `activation` object, any legacy top-level `status`, the active-admission predicate at every effect entrypoint, and state bytes or process calls before refusal. | The activation writer moved to the typed `activation.state` owner, but one or more consumers still read only the legacy top-level `status`. | Reuse `goal_activation_state()` or `goal_is_stopped()` in one domain predicate, retain only required legacy or archival compatibility, and route every effect entrypoint through that predicate. Run red-green tests for the canonical nested state and assert refusal occurs before writes, process launch, or external effects. Keep historical reads available after stop. | | `source_context_legacy_downgrade` | An unstamped record mutates state through a legacy path after the authoritative source disappears, although another record in the same owner context preserves an exact source identity. | Selected record identity, all same-context durable candidates, source path availability, operation entrypoint, and business-file bytes before and after refusal. | The adapter treated one selected record's missing identity as proof that the whole context was legacy and ignored exact historical evidence when the current authority could not be read. | Resolve source-context availability once for selection and mutation. Exact history may prove that legacy fallback is unsafe, but it must never supply or guess the current identity. Fail closed before writes when authority is unavailable; preserve contexts with no exact history through opposite legacy controls across every mutation entrypoint. | | `archive_capture_classification_gap` | Whole-Goal capture rejects a reachable archived Agent record although its active read was valid. | Recorded role/class, existing legacy read classification, transitive dependency closure, bootstrap and writer-outbox readback. | Archive storage preserved the role but omitted the resolved class; capture treated missing class as missing authority. | Keep recorded identity separate from compatibility classification. Only a recorded Agent role can adopt the existing read class; use it consistently for closure and materialization. Preserve the class on new archive moves, keep user authority fail-closed, and validate full source capture in disposable real providers without changing the active Goal. | @@ -74,7 +74,7 @@ teaches a reusable control-plane lesson. | `replan_projection_discharge_mismatch` | A projected refresh cannot satisfy its own vision obligation, or a required-vision qualification executes an ordinary repeated-progress fixture. | Typed trigger kinds, required outcomes, projected input/authoring contract, actual actor fixture, bound durable writeback, checkpoint and post-settlement readback. | Projection and admission encoded separate outcome rules; a successful narrow action was mistaken for a complete journey. | Share outcome matching and executable input projection at the typed owner. Preserve original-Turn recovery, authoring limits and legal successor/terminal exits. Match qualification scope to the fixture; distinguish accepted writeback, checkpoint and one-spend settlement. A new successor duty is not a failed closeout. Do not add ACK rituals, weaken acceptance or replay until green. Full closeout and one action need not share a call cap: an authorized, cost-disclosed budget revision is a new qualification and must retain old failures, not relabel them. | | `delegation_runtime_discovery_split` | A coordinator knows a child-count or model preference but cannot discover requester-authorized managed routes, so a direct SDK experiment is mistaken for formal LoopX delegation or the task stays unnecessarily serial. | Goal orchestration readback, requester-scoped binding directory, Turn host/profile readiness, operation journal, signed `before_plan`/`before_delegate`/`after_delegate_result` context, and parent artifact validation. | Execution grants and runtime facts existed only behind the dispatch CLI/MCP while planning consumed a separate prompt or model-preference snapshot; adding provider names to one skill would create another scheduler/config owner. | Store only an ignored Goal-local pointer to the existing operator binding file, project bounded public-safe requester routes through the generic capability context, and keep runtime readiness separate from route selection and task adoption. Recheck runtime/model/budget at dispatch, forbid silent substitution, and reconcile original operation receipts after return. Do not require every heartbeat to use every route or copy credentials/host arguments into registry, frontend, Lark or prompts. | | `goal_runtime_shadows_machine_credential` | A configured machine appears credential-less in another Goal or interpreter. | Machine credential status, Goal runtime root, launching interpreter SDK probe, Turn plan and dispatch. | Goal state location or process environment was mistaken for the machine authentication owner. | Resolve the canonical machine credential at planning and dispatch; keep SDK readiness interpreter-scoped and assignments requester/Goal-scoped. Verify two Goal roots, conflicting Goal-local stores, invalid machine-store refusal and explicit host selection. Never copy a credential or another Goal's grants to make readiness green. | -| `budget_metric_overfitting` | A budget failure triggers automatic expansion, or mechanical compaction that removes useful semantics or breaks consumers. | Owning limit, matched base/head measurements, consumer/caller contract, original failure and revised validation. | A regression metric became the objective; historical ceilings or green tests replaced semantic judgment. | Follow the [budget decision guide](../../../docs/development/testing-and-quality.md#budget-failure-decisions), compare true redundancy, compatibility cost and justified headroom, and repair the existing contract/tests and review evidence. Preserve hard limits and frozen qualification results. | +| `budget_metric_overfitting` | A budget failure triggers automatic expansion, or mechanical compaction that removes useful semantics or breaks consumers. | Owning limit, matched base/head measurements, consumer/caller contract, original failure and revised validation. | A regression metric became the objective; historical ceilings or green tests replaced semantic judgment. | Follow the [budget decision guide](https://github.com/loopx-project/loopx/blob/main/docs/development/testing-and-quality.md#budget-failure-decisions), compare true redundancy, compatibility cost and justified headroom, and repair the existing contract/tests and review evidence. Preserve hard limits and frozen qualification results. | | `validation_fixture_owner_drift` | CI repeatedly fails after a rebase because fixtures retain an old catalog count, omit current caller context or dispatch without the owning claim. | The current source contract, exact failing assertion, base/head entrypoint and durable state readback. | Validation encoded a dated snapshot or skipped current admission instead of preparing the operation it intended to challenge. | Reuse the shipped catalog and package metadata, explicitly isolate runtime routes, and acquire the real queue claim before dispatch. Retain the original negative invariant and exit/readback assertions. Do not weaken routing, execution admission or production boundaries to make stale fixtures pass. | | `skill_import_recreation` | Duplicate LoopX skills return after successful cleanup; imported entries display a fallback brand casing. | Compare installed files and metadata with source-host skills; correlate file creation times with structured host import receipts. | A later external-host import recreates command facades in another discovered root, omits display metadata, and bypasses installer reconciliation. | Attribute the writer from import receipts without guessing the human initiator; exclude already-installed LoopX skills from later imports and rerun managed reconciliation. Ensure standalone workflow entry installation writes Codex metadata, previews missing metadata repair, and records the full installed tree. Preserve user metadata and exact-host invocation behavior. | | `skill_discovery_split_ownership` | Duplicate skill names, conflicting PR-review routes, or canonical and legacy aliases appear together. | Enumerate discovered roots, resolve directory symlinks, compare skill hashes, managed markers, install receipts, and generated metadata. | Workflow and command installers wrote independently to overlapping host roots; dedupe was optional, omitted the bare entry name, or retired copies without proving a replacement. | Repair the shared installer reconciliation and every active installation path; preserve user changes and rich workflows, retire managed aliases from the Codex picker, test repeated installs and custom profiles, then verify a fresh host catalog. Do not treat deleting one visible duplicate or changing invocation policy as a durable fix. | diff --git a/skills/loopx-self-repair/references/upstream-issue-escalation.md b/skills/loopx-self-repair/references/upstream-issue-escalation.md index 2afd4e6c0b..19904240b0 100644 --- a/skills/loopx-self-repair/references/upstream-issue-escalation.md +++ b/skills/loopx-self-repair/references/upstream-issue-escalation.md @@ -81,7 +81,7 @@ the fingerprint marker: ```bash gh issue list \ - --repo huangruiteng/loopx \ + --repo loopx-project/loopx \ --state all \ --search "$fingerprint in:body" \ --limit 20 \ @@ -100,7 +100,7 @@ Verify authentication and create only after every earlier gate passes: ```bash gh auth status gh issue create \ - --repo huangruiteng/loopx \ + --repo loopx-project/loopx \ --title "$title" \ --body-file "$draft_file" ``` diff --git a/sonar-project.properties b/sonar-project.properties index 6bb23ba86f..c99f80ddc4 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -3,17 +3,17 @@ sonar.projectKey=huangruiteng_loopx sonar.projectName=LoopX # Public project links -sonar.links.homepage=https://github.com/huangruiteng/loopx -sonar.links.scm=https://github.com/huangruiteng/loopx +sonar.links.homepage=https://github.com/loopx-project/loopx +sonar.links.scm=https://github.com/loopx-project/loopx sonar.sourceEncoding=UTF-8 # Analyzed surfaces: Python product core, TypeScript/JavaScript product -# surfaces, and helper scripts. Generated frontend bundles, legacy -# deprecate/, and non-analyzed runtimes (Rust/Tauri) are excluded. +# surfaces, and helper scripts. Generated frontend bundles and non-analyzed +# runtimes (Rust/Tauri) are excluded. sonar.sources=loopx,apps,scripts sonar.tests=tests -sonar.exclusions=**/node_modules/**,**/dist/**,**/build/**,**/src-tauri/**,loopx/web/chat/assets/**,**/*.min.js,deprecate/** +sonar.exclusions=**/node_modules/**,**/dist/**,**/build/**,**/src-tauri/**,loopx/web/chat/assets/**,**/*.min.js # These settings components are declarative React wiring. They are exercised by # the packaged dashboard acceptance flow, while the repository's dashboard # coverage job instruments the framework-neutral data surface only. diff --git a/tests/canary/test_premerge_public_boundary_run.py b/tests/canary/test_premerge_public_boundary_run.py index 81a81301d9..db8c8a2378 100644 --- a/tests/canary/test_premerge_public_boundary_run.py +++ b/tests/canary/test_premerge_public_boundary_run.py @@ -1,4 +1,4 @@ -"""The premerge boundary check fails on an input the scan could not read. +"""The premerge boundary check fails on an input the scan could not read. `_public_boundary_changed_files_run` reads `scan_public_boundary`'s result, so a directory the scan could not list has to fail this check the way a recorded hit