From 6c354c6460184e2d6593638100376c5328b8bcf7 Mon Sep 17 00:00:00 2001 From: Yuchao Wang Date: Wed, 25 Nov 2026 07:15:37 +0000 Subject: [PATCH 1/2] feat(cli): discover registered Goals with scoped search and paging Signed-off-by: Yuchao Wang --- docs/guides/getting-started.md | 25 +++ loopx/cli_commands/registry_inspection.py | 72 +++++++ loopx/cli_runtime.py | 13 +- loopx/registry.py | 9 + tests/cli_commands/test_registry_discovery.py | 180 ++++++++++++++++++ 5 files changed, 298 insertions(+), 1 deletion(-) create mode 100644 loopx/cli_commands/registry_inspection.py create mode 100644 tests/cli_commands/test_registry_discovery.py diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index f23c4b8ffb..e0184aef21 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -171,6 +171,31 @@ project state. The legacy `codex-ide` value remains an accepted compatibility alias but is no longer advertised. This prevents an upgrade from silently routing an IDE plugin or terminal start to a desktop-app heartbeat. +## Find Goals in the selected registry + +Use `registry` to discover Goal IDs before choosing a Goal-specific command: + +```bash +loopx registry --query research --limit 10 +loopx --format json registry --query research --limit 10 --offset 10 +loopx registry --goal-id +``` + +The query is a case-insensitive, Unicode-normalized literal substring of the +Goal ID, repository path, domain, status, or adapter kind. Exact `--goal-id` and +`--query` filters compose. Filtering happens before pagination, in registry +declaration order. Any selection option enables a default page size of 20; +`--limit` must be positive and `--offset` non-negative. JSON `selection` reports +matching and returned counts and `next_offset` (null at the end). Offsets apply +to the current registry snapshot; edits between requests can change pages. + +Without selection options, `registry` keeps its complete existing output. +Selection only narrows displayed Goal rows: registry-wide totals, status counts, +diagnostics, and failure exit status remain complete. An unknown exact Goal ID +fails, while a query with no matches returns an empty selection. Inspection still +reads and validates the whole selected registry; pagination does not bound scan +work or follow entries into their source registries. + ## Inspect an earlier run-history window To investigate an earlier day without dumping all newer runs, select a time diff --git a/loopx/cli_commands/registry_inspection.py b/loopx/cli_commands/registry_inspection.py new file mode 100644 index 0000000000..660087abef --- /dev/null +++ b/loopx/cli_commands/registry_inspection.py @@ -0,0 +1,72 @@ +"""Optional display selection over one complete registry inspection.""" + +from __future__ import annotations + +from collections.abc import Mapping +import unicodedata + + +def _search_text(value: object) -> str: + return unicodedata.normalize("NFKC", str(value or "")).casefold() + + +def select_registry_goals( + payload: dict[str, object], + *, + goal_id: str | None, + query: str | None, + limit: int | None, + offset: int | None, +) -> dict[str, object]: + if goal_id is None and query is None and limit is None and offset is None: + return payload + page_size = 20 if limit is None else limit + start = 0 if offset is None else offset + if page_size < 1 or start < 0: + raise ValueError("--limit must be positive and --offset must be non-negative") + if goal_id is not None and not goal_id.strip(): + raise ValueError("--goal-id must not be empty") + term = _search_text(query).strip() if query is not None else None + if term is not None and not term: + raise ValueError("--query must contain non-whitespace text") + # An unavailable source must retain its original failure, not become an + # apparently successful empty search or an invented missing-Goal error. + if "goals" not in payload: + return payload + raw_goals = payload.get("goals") + goals = ( + [row for row in raw_goals if isinstance(row, Mapping)] + if isinstance(raw_goals, list) + else [] + ) + if goal_id is not None and not any(row.get("id") == goal_id for row in goals): + raise ValueError(f"Goal is not present in this registry: {goal_id}") + matches = [ + row + for row in goals + if (goal_id is None or row.get("id") == goal_id) + and ( + term is None + or any( + term in _search_text(row.get(field)) + for field in ("id", "repo", "domain", "status", "adapter_kind") + ) + ) + ] + selected = matches[start : start + page_size] + end = start + len(selected) + # Keep global health/provenance and collision diagnostics intact. Selection + # narrows the displayed Goal rows, never the inspection or its authority. + return { + **payload, + "goals": selected, + "selection": { + "goal_id": goal_id, + "query": query, + "offset": start, + "limit": page_size, + "matched_goal_count": len(matches), + "returned_goal_count": len(selected), + "next_offset": end if end < len(matches) else None, + }, + } diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index ee911d0059..23dba82cac 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -346,9 +346,13 @@ def cli_invocation_route(argv: list[str]): def _register_registry_inspection_commands(subparsers: argparse._SubParsersAction) -> None: """Share the existing registry grammar with the complete support parser.""" - subparsers.add_parser( + registry_parser = subparsers.add_parser( "registry", help="Inspect registry goals and adapter declarations." ) + registry_parser.add_argument("--goal-id", help="Show one exact Goal id; keep registry-wide diagnostics.") + registry_parser.add_argument("--query", help="Case-insensitive literal search in Goal id, repo, domain, status or adapter kind.") + registry_parser.add_argument("--limit", type=int, help="Maximum matching Goal rows (default 20 when selecting).") + registry_parser.add_argument("--offset", type=int, help="Skip this many matches in registry order (default 0).") registry_boundary_parser = subparsers.add_parser( "registry-boundary", help="Classify a registry file as local-only, global-local, public projection, or public fixture.", @@ -385,6 +389,13 @@ def _handle_registry_inspection_command( """Keep one inspection adapter and the full CLI's existing patch points.""" if args.command == "registry": payload = inspect_registry(registry_path) + from .cli_commands.registry_inspection import select_registry_goals + + try: + payload = select_registry_goals(payload, goal_id=args.goal_id, query=args.query, + limit=args.limit, offset=args.offset) + except ValueError as exc: + payload = {**payload, "ok": False, "error": str(exc), "goals": []} print_payload(payload, args.format, render_registry_markdown) return 0 if payload.get("ok") else 1 diff --git a/loopx/registry.py b/loopx/registry.py index 25e0777dae..e64de57775 100644 --- a/loopx/registry.py +++ b/loopx/registry.py @@ -559,6 +559,15 @@ def render_registry_markdown(payload: dict[str, Any]) -> str: lines.append(f"- error: {payload.get('error')}") return "\n".join(lines) + selection = payload.get("selection") + if isinstance(selection, dict): + lines.extend([ + f"- matching Goals: `{selection.get('matched_goal_count')}`", + f"- returned Goals: `{selection.get('returned_goal_count')}` (offset `{selection.get('offset')}`)", + f"- next offset: `{selection.get('next_offset')}`", + "- Goal totals, status counts and diagnostics below cover the entire registry.", + ]) + lines.extend( [ f"- schema_version: `{payload.get('schema_version')}`", diff --git a/tests/cli_commands/test_registry_discovery.py b/tests/cli_commands/test_registry_discovery.py new file mode 100644 index 0000000000..75c2493168 --- /dev/null +++ b/tests/cli_commands/test_registry_discovery.py @@ -0,0 +1,180 @@ +"""Real CLI discovery selects after full inspection without hiding diagnostics.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from loopx.registry import inspect_registry + + +@pytest.fixture +def registry_path(tmp_path: Path) -> Path: + goals = [] + for index in range(31): + repo = tmp_path / f"project-{index:02d}" + repo.mkdir() + (repo / "STATE.md").write_text("# Synthetic Goal\n", encoding="utf-8") + goals.append( + { + "id": f"{'target' if index in (3, 17, 28) else 'other'}-{index:02d}", + "repo": str(repo), + "state_file": "STATE.md", + "domain": "software", + "status": "active", + "adapter": {"kind": "read_only_project_map_v0"}, + } + ) + path = tmp_path / "registry.json" + path.write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": goals, + "common_runtime_root": str(tmp_path / "runtime"), + } + ), + encoding="utf-8", + ) + return path + + +def read_registry(path, *arguments, markdown=False): + before = {p: p.read_bytes() for p in path.parent.rglob("*") if p.is_file()} + result = subprocess.run( + [ + sys.executable, + "-m", + "loopx.entrypoint", + "--registry", + str(path), + "--format", + "markdown" if markdown else "json", + "registry", + *arguments, + ], + text=True, + capture_output=True, + timeout=60, + env={**os.environ, "LOOPX_USAGE_PING": "0"}, + ) + assert {p: p.read_bytes() for p in path.parent.rglob("*") if p.is_file()} == before + return result, result.stdout if markdown else json.loads(result.stdout) + + +def test_query_filters_before_paging_and_defaults_remain_complete(registry_path): + result, full = read_registry(registry_path) + assert result.returncode == 0, result.stderr + assert full == inspect_registry(registry_path) + assert len(full["goals"]) == 31 and "selection" not in full + result, first = read_registry(registry_path, "--query", "TARGET", "--limit", "2") + assert result.returncode == 0 + assert [g["id"] for g in first["goals"]] == ["target-03", "target-17"] + assert first["goal_count"] == 31 + assert first["selection"] == { + "goal_id": None, + "query": "TARGET", + "offset": 0, + "limit": 2, + "matched_goal_count": 3, + "returned_goal_count": 2, + "next_offset": 2, + } + _, second = read_registry( + registry_path, "--query", "TARGET", "--limit", "2", "--offset", "2" + ) + assert [g["id"] for g in second["goals"]] == ["target-28"] + assert second["selection"]["next_offset"] is None + _, beyond = read_registry(registry_path, "--query", "TARGET", "--offset", "50") + assert beyond["goals"] == [] and beyond["selection"]["matched_goal_count"] == 3 + + +def test_exact_goal_and_query_compose_without_prefix_match(registry_path): + _, payload = read_registry( + registry_path, "--goal-id", "target-17", "--query", "PROJECT-17" + ) + assert [g["id"] for g in payload["goals"]] == ["target-17"] + _, empty = read_registry( + registry_path, "--goal-id", "target-17", "--query", "project-03" + ) + assert empty["ok"] and empty["goals"] == [] + result, missing = read_registry(registry_path, "--goal-id", "target-1") + assert result.returncode == 1 and missing["ok"] is False + + +def test_selection_keeps_unrelated_registry_problems_visible(registry_path): + raw = json.loads(registry_path.read_text()) + raw["goals"][0].pop("state_file") + registry_path.write_text(json.dumps(raw)) + _, full = read_registry(registry_path) + result, selected = read_registry(registry_path, "--goal-id", "target-17") + assert result.returncode == 1 and selected["ok"] is False + assert [g["id"] for g in selected["goals"]] == ["target-17"] + for field in ("problems", "problem_diagnostics", "status_counts", "goal_count"): + assert selected[field] == full[field] + result, markdown = read_registry( + registry_path, "--goal-id", "target-17", markdown=True + ) + assert result.returncode == 1 + assert "entire registry" in markdown and "missing state_file" in markdown + + +@pytest.mark.parametrize( + "arguments", + [ + ["--query", " "], + ["--goal-id", ""], + ["--limit", "0"], + ["--limit", "-1"], + ["--offset", "-1"], + ], +) +def test_invalid_selection_reports_failure(registry_path, arguments): + result, payload = read_registry(registry_path, *arguments) + assert result.returncode == 1 and payload["ok"] is False and payload["error"] + + +def test_unicode_and_literal_search_and_default_page_size(registry_path): + raw = json.loads(registry_path.read_text()) + raw["goals"][17]["domain"] = "研究[候选]" + registry_path.write_text(json.dumps(raw, ensure_ascii=False)) + _, payload = read_registry(registry_path, "--query", "研究[") + assert [g["id"] for g in payload["goals"]] == ["target-17"] + _, normalized = read_registry(registry_path, "--query", "TARGET") + assert normalized["selection"]["matched_goal_count"] == 3 + _, default_page = read_registry(registry_path, "--offset", "0") + assert len(default_page["goals"]) == 20 + assert default_page["selection"]["next_offset"] == 20 + + +def test_unavailable_registry_keeps_original_error(tmp_path): + result, payload = read_registry(tmp_path / "absent.json", "--query", "target") + assert result.returncode == 1 and payload["error"] == "registry file does not exist" + assert "selection" not in payload + + +def test_global_registry_selection_does_not_follow_source_and_keeps_duplicate_diagnostics( + registry_path, +): + raw = json.loads(registry_path.read_text()) + raw["registry_role"] = "global-local" + source = registry_path.parent / "source.json" + source.write_text("not a registry") + raw["goals"][17]["source_registry"] = str(source) + raw["goals"].append(dict(raw["goals"][17])) + registry_path.write_text(json.dumps(raw)) + _, full = read_registry(registry_path) + result, selected = read_registry( + registry_path, "--goal-id", "target-17", "--limit", "1" + ) + assert result.returncode == 1 + assert selected["problems"] == full["problems"] + assert selected["selection"]["matched_goal_count"] == 2 + assert selected["selection"]["next_offset"] == 1 + assert len(selected["goals"]) == 1 + assert selected["goal_count"] == 32 From 91e0d5ef930b1f44bd7062c3264aef80ce412283 Mon Sep 17 00:00:00 2001 From: Yuchao Wang Date: Wed, 25 Nov 2026 10:03:29 +0000 Subject: [PATCH 2/2] fix(cli): retain registry diagnostics when Goal selection fails Signed-off-by: Yuchao Wang --- loopx/registry.py | 5 ++- tests/cli_commands/test_registry_discovery.py | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/loopx/registry.py b/loopx/registry.py index e64de57775..6fd0df49ca 100644 --- a/loopx/registry.py +++ b/loopx/registry.py @@ -557,7 +557,10 @@ def render_registry_markdown(payload: dict[str, Any]) -> str: ] if payload.get("error"): lines.append(f"- error: {payload.get('error')}") - return "\n".join(lines) + # Selection may fail after a complete inspection. Keep its global + # counts and diagnostics; only source-load failures lack that evidence. + if "goal_count" not in payload: + return "\n".join(lines) selection = payload.get("selection") if isinstance(selection, dict): diff --git a/tests/cli_commands/test_registry_discovery.py b/tests/cli_commands/test_registry_discovery.py index 75c2493168..8350f01a62 100644 --- a/tests/cli_commands/test_registry_discovery.py +++ b/tests/cli_commands/test_registry_discovery.py @@ -158,6 +158,38 @@ def test_unavailable_registry_keeps_original_error(tmp_path): assert "selection" not in payload +def test_unknown_goal_keeps_global_diagnostics_in_both_formats(registry_path): + raw = json.loads(registry_path.read_text()) + raw["goals"][0].pop("state_file") + registry_path.write_text(json.dumps(raw)) + _, full = read_registry(registry_path) + result, selected = read_registry(registry_path, "--goal-id", "unknown-goal") + assert result.returncode == 1 and selected["ok"] is False + assert selected["error"] == "Goal is not present in this registry: unknown-goal" + assert selected["goals"] == [] + for field in ("problems", "problem_diagnostics", "status_counts", "goal_count"): + assert selected[field] == full[field] + result, markdown = read_registry( + registry_path, "--goal-id", "unknown-goal", markdown=True + ) + assert result.returncode == 1 + assert selected["error"] in markdown + assert "- goals: `31`" in markdown + assert "missing state_file" in markdown + + +def test_unreadable_registry_selection_keeps_short_original_error(tmp_path): + path = tmp_path / "registry.json" + _, original = read_registry(path) + result, selected = read_registry(path, "--goal-id", "unknown-goal") + assert result.returncode == 1 and selected == original + result, markdown = read_registry(path, "--goal-id", "unknown-goal", markdown=True) + assert result.returncode == 1 + assert original["error"] in markdown + assert "Goal is not present" not in markdown + assert "- goals:" not in markdown and "## Problems" not in markdown + + def test_global_registry_selection_does_not_follow_source_and_keeps_duplicate_diagnostics( registry_path, ):