From 759ab87ca760b31e56a78d69e34b22aa7c34cbd8 Mon Sep 17 00:00:00 2001 From: ChengLong GU <88359731+gcl-coder@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:04:18 +0800 Subject: [PATCH 1/3] feat(global): add a cross-Goal lifecycle board over status projections Aggregate the per-Goal goal_artifact_lifecycle_projection_v0 that status already derives into one read-only board: phase rollup, guard owners with the Goals they block, reached milestones, and the next transition per Goal. The projection envelope keeps global scope: the denominator is global membership, unprojected or unnamed Goals and Goals outside a bounded status scan are named omissions, and the top-level complete verdict repeats the envelope's answer so a partial scan cannot read as a whole estate. The returned page is filtered, the rollups are not. `--agent-id` lists only Goals whose recorded `coordination.registered_agents` roster registers that exact identity, and the flag's presence arms the filter: an unknown identity, one the roster shape rejects, and an explicitly blank value all return an empty page instead of widening back to the estate. Goal ids are matched, deduplicated and published as the complete validated identity so two long ids sharing a display prefix stay distinct rows. The envelope sizes its page from the filtered row count measured before the limit, so an empty phase filter is an empty page while a real limit still reports truncation; coverage and the cross-Goal rollups keep describing every inspected Goal. Refs #4128. Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com> --- .../contracts/projection-envelope-contract.md | 1 + .../protocols/global-manager-command-v0.md | 90 +- .../global-manager-command-cli-smoke.py | 249 +++++ loopx/canary/workflow_domain_profiles.py | 1 + loopx/cli_commands/global_lifecycle.py | 516 +++++++++++ loopx/cli_commands/summary_all.py | 22 + .../cli_commands/summary_all_registration.py | 22 + loopx/control_plane/goals/lifecycle_board.py | 385 ++++++++ loopx/help_surface.py | 1 + tests/test_cli_entrypoint.py | 7 +- tests/test_global_lifecycle.py | 861 ++++++++++++++++++ tests/test_projection_envelope.py | 2 + tests/test_public_check_disclosure.py | 1 + 13 files changed, 2147 insertions(+), 11 deletions(-) create mode 100644 loopx/cli_commands/global_lifecycle.py create mode 100644 loopx/control_plane/goals/lifecycle_board.py create mode 100644 tests/test_global_lifecycle.py diff --git a/docs/reference/contracts/projection-envelope-contract.md b/docs/reference/contracts/projection-envelope-contract.md index 70654b7693..41f3161214 100644 --- a/docs/reference/contracts/projection-envelope-contract.md +++ b/docs/reference/contracts/projection-envelope-contract.md @@ -23,6 +23,7 @@ Python-owned projections do so through `loopx/control_plane/projection_envelope_ | `loopx global-gates` | `global_gates` | `global` | | `loopx global-todos` | `global_todos` | `global` | | `loopx global-risks` | `global_risks` | `global` | +| `loopx global-lifecycle` | `global_goal_lifecycle` | `global` | | `loopx quota should-run` | `quota_should_run` | `goal` | | Delegation operations (CLI, MCP, Goal Chat) | `delegation_inventory` | `requester_page` | | Goal task map in delivery review | `goal_task_map` | `goal_task_map` | diff --git a/docs/reference/protocols/global-manager-command-v0.md b/docs/reference/protocols/global-manager-command-v0.md index 30c38bac06..45432e73fd 100644 --- a/docs/reference/protocols/global-manager-command-v0.md +++ b/docs/reference/protocols/global-manager-command-v0.md @@ -2,7 +2,7 @@ `global_manager_command_v0` is a read-first protocol for operator commands such as `/loopx-global-summary`, `/loopx-global-gates`, -`/loopx-global-todos`, and `/loopx-global-risks`. +`/loopx-global-todos`, `/loopx-global-risks`, and `/loopx-global-lifecycle`. The product goal is to let a user act as a manager across long-running agent work: ask for the last day of progress, see blocked decisions, compare agent @@ -16,12 +16,13 @@ existing command behavior remains the baseline until each stage is qualified. This protocol is not a general chat-command router yet. It defines the request, allowed sources, response shape, privacy boundary, and action ladder -for Codex hosts, CLI wrappers, or dashboard command palettes. The four -implemented global-manager CLI wrappers are `loopx global-summary`, for the -broad compact `/loopx-global-summary` digest; `loopx global-gates`, for the -focused current-state gate inbox; `loopx global-todos`, for the focused -current-state work inbox; and `loopx global-risks`, for the focused -current-state risk inbox. +for Codex hosts, CLI wrappers, or dashboard command palettes. Five +global-manager CLI wrappers implement it: `loopx global-summary` for the broad +compact `/loopx-global-summary` digest, `loopx global-gates` for the focused +current-state gate inbox, `loopx global-todos` for the focused current-state +work inbox, `loopx global-risks` for the focused current-state risk inbox, and +`loopx global-lifecycle` for the cross-Goal lifecycle board derived from the +status read model. ## Command Set @@ -33,6 +34,7 @@ Recommended first commands: | `/loopx-global-gates` | Show open user/controller gates and what each blocks. | current state | | `/loopx-global-todos` | Show top runnable, blocked, deferred-ready, and review todos. | current state | | `/loopx-global-risks` | Show stale runs, public/private boundary warnings, failing checks, and rollback candidates. | 24 hours | +| `/loopx-global-lifecycle` | Show the cross-Goal lifecycle board: phases, reached milestones, blocking guards with owners, and the next transition per Goal. | current state | | `/loopx-pr-review` | Walk the current project's or explicit repository's open and merged GitHub PRs one by one with motivation, scope, checks, risks, and review prompts. | current open + merged PRs, optionally bounded by `--since` | | `/loop-goal-summary ` | Drill into one goal without scanning unrelated projects. | 24 hours | @@ -55,6 +57,7 @@ falling back to a broader status or summary dump. | `/loop-global-gates` | `/loopx-global-gates` | | `/loop-global-todos` | `/loopx-global-todos` | | `/loop-global-risks` | `/loopx-global-risks` | +| `/loop-global-lifecycle` | `/loopx-global-lifecycle` | Related project-local command: `/loopx ` is covered by [`loopx_goal_command_v0`](loopx-goal-command-v0.md). It is not a global manager @@ -472,6 +475,68 @@ history rewrite, external cleanup, or merge. Any future candidate must still use destructive action; this command never sets `requires_user_approval=true` on a first-version risk row merely to imply that authority. +### Focused Global Lifecycle Response + +`loopx global-lifecycle` keeps `global_manager_command_response_v0` and returns a +`global_goal_lifecycle_board_v0` payload under `board_schema_version`, built only +from the status read model: + +- `summary` counts inspected, projected and unprojected Goals, guard-blocked + Goals, Agent-scoped Goals, filtered and returned rows, truncation, and the + requested phase and Agent filters; +- `phases` lists each derived phase with its Goal count and Goal ids, in the + operator order `waiting_owner`, `qualifying`, `starting`, `closing`, `closed`; +- `guards` rolls open guards up by `kind` and `owner` with the blocked Goal ids; +- `milestones` rolls reached milestone ids up across Goals; +- `goals` carries the bounded per-Goal rows: phase, reached vs total milestones, + open guards, and the first next transition; +- `gaps` names each Goal whose projection the status owner could not derive as a + `global_goal_lifecycle_gap_v0` row with `reason=projection_not_derived`, and + `complete=false` says the board is missing evidence rather than healthy. + +The projection envelope keeps the same global scope as its peer commands. The +denominator is `global_registry.global_goal_count`, never the local registry the +process happened to read: Goals outside the current registry are named under +`reason=outside_current_registry`, unprojected Goals under +`reason=projection_not_derived`, a Goal whose identity cannot be published +under `reason=goal_identity_unavailable`, and a Goal the single bounded status +read never reached under `reason=goal_scan_omitted`. When global membership is +missing or unreadable the denominator stays `null` and the envelope reports +`missing_required_sources`, so an unknown estate is never certified as whole. +A status read that returned an unhealthy or absent model records +`reason=status_unavailable` instead of an empty omission list. + +The top-level `complete` repeats the envelope verdict: it is `true` only when +every Goal in global scope carried a derived projection and no source was +omitted. A board can therefore be whole for the Goals the status read returned +(`goals_without_projection=0`) while `complete=false` still says the global +estate behind it is unproven. + +`--limit` bounds returned Goal rows only. Phase, guard and milestone rollups +still describe every inspected Goal, so a truncated page cannot read as a +smaller estate. `--phase` narrows the returned rows and is echoed in +`request.phase_filter`; an unsupported phase fails before any status read. + +`--agent-id` narrows the returned rows to Goals whose recorded +`coordination.registered_agents` roster registers that exact identity, and the +applied scope is echoed in `request.agent_filter` and `summary.agent_filter`. +The flag's presence arms the filter, never its text: an identity no inspected +Goal registers, an identity the roster shape rejects, and an explicitly blank +value all return an empty page with `agent_scope_goal_count=0` and +`summary.agent_scope_requested=true`; none of them widens back to the whole +estate. Goal ids are matched, deduplicated and published as the complete +validated identity, so two long ids that share a truncated display prefix stay +distinct rows. The page +counts follow the same rule as the phase filter: `summary.filtered_goal_count` +is measured after both filters and before the limit, and the envelope's +`available_count` repeats that count, so an empty filtered page is not reported +as truncated. Coverage and the cross-Goal rollups keep describing the inspected +estate rather than the filtered page. + +This read never closes a Goal, resolves a guard, spends quota or derives a +second lifecycle; ordinary status and settlement reads keep their strict +decoding. + ## Action Ladder Responses may include actions, but each action must declare its authority: @@ -512,9 +577,14 @@ or omission, not the material itself. A first implementation is acceptable when: - command responses are read-only by default; -- `loopx global-summary`, `loopx global-gates`, `loopx global-todos`, and - `loopx global-risks` emit their matching canonical command responses, while - only goal summary stays host-only; +- `loopx global-summary`, `loopx global-gates`, `loopx global-todos`, + `loopx global-risks`, and `loopx global-lifecycle` emit their matching + canonical command responses, while only goal summary stays host-only; +- global-lifecycle reuses the status owner's + `goal_artifact_lifecycle_projection_v0` and never derives a second lifecycle; + a Goal without a projection is a typed `global_goal_lifecycle_gap_v0` row and + marks the board incomplete, and `--limit` bounds returned rows while phase, + guard and milestone rollups still cover every inspected Goal; - each command names its compact LoopX source surfaces; - gates name owner, formally related blocked todo or goal scope, question, and next safe action; diff --git a/examples/project/global-manager-command-cli-smoke.py b/examples/project/global-manager-command-cli-smoke.py index 6a292eee6f..86608be904 100644 --- a/examples/project/global-manager-command-cli-smoke.py +++ b/examples/project/global-manager-command-cli-smoke.py @@ -28,6 +28,8 @@ RUNNABLE_GOAL_ID = "smoke-goal-runnable" DEFERRED_GOAL_ID = "smoke-goal-deferred" AGENT_ID = "codex-smoke" +SECOND_AGENT_ID = "codex-smoke-secondary" +UNKNOWN_AGENT_ID = "codex-smoke-unknown" BLOCKED_TODO_ID = "todo_blocked" RUNNABLE_REVIEW_TODO_ID = "todo_runnable_review" DEFERRED_TODO_ID = "todo_deferred_ready" @@ -385,6 +387,178 @@ def assert_risks_markdown(markdown: str, *, private_root: Path) -> None: assert marker not in markdown, marker +def assert_lifecycle_agent_scope( + root: Path, *, registry: Path, runtime: Path, +) -> None: + """The public CLI must apply --agent-id to the same Goal set it reads. + + One registry copy registers the second Agent on two of the three Goals, so + the unfiltered, registered and unknown-Agent reads share one fixture and + differ only by the identity on the command line. + """ + + scoped_registry = root / "lifecycle-agent-registry.json" + scoped_payload = json.loads(registry.read_text(encoding="utf-8")) + for goal in scoped_payload["goals"]: + agents = list(goal["coordination"]["registered_agents"]) + if goal["id"] != GOAL_ID and SECOND_AGENT_ID not in agents: + agents.append(SECOND_AGENT_ID) + goal["coordination"]["registered_agents"] = agents + scoped_registry.write_text( + json.dumps(scoped_payload, ensure_ascii=False), encoding="utf-8" + ) + + def lifecycle(payload_args: list[str]) -> dict[str, object]: + proc = run_cli( + registry=scoped_registry, + runtime=runtime, + command="global-lifecycle", + output_format="json", + command_args=payload_args, + ) + payload = json.loads(proc.stdout) + assert payload["ok"] is True, payload + assert_public_safe(payload) + return payload + + unfiltered = lifecycle(["--limit", "8"]) + assert unfiltered["request"]["agent_filter"] == [], unfiltered + assert [row["goal_id"] for row in unfiltered["goals"]] == [ + GOAL_ID, + DEFERRED_GOAL_ID, + RUNNABLE_GOAL_ID, + ], unfiltered + + registered = lifecycle(["--agent-id", SECOND_AGENT_ID, "--limit", "8"]) + assert registered["request"]["agent_filter"] == [SECOND_AGENT_ID], registered + assert registered["summary"]["agent_filter"] == [SECOND_AGENT_ID], registered + assert [row["goal_id"] for row in registered["goals"]] == [ + DEFERRED_GOAL_ID, + RUNNABLE_GOAL_ID, + ], registered + assert registered["summary"]["goals_inspected"] == 3, registered + coverage = registered["projection_envelope"]["coverage"] + assert coverage["shown_count"] == 2, coverage + assert coverage["available_count"] == 2, coverage + assert coverage["truncated"] is False, coverage + + unknown = lifecycle(["--agent-id", UNKNOWN_AGENT_ID, "--limit", "8"]) + assert unknown["request"]["agent_filter"] == [UNKNOWN_AGENT_ID], unknown + assert unknown["goals"] == [], unknown + assert unknown["summary"]["filtered_goal_count"] == 0, unknown + assert unknown["summary"]["truncated"] is False, unknown + unknown_coverage = unknown["projection_envelope"]["coverage"] + assert unknown_coverage["shown_count"] == 0, unknown_coverage + assert unknown_coverage["available_count"] == 0, unknown_coverage + assert unknown_coverage["truncated"] is False, unknown_coverage + + paged = lifecycle(["--agent-id", SECOND_AGENT_ID, "--limit", "1"]) + assert [row["goal_id"] for row in paged["goals"]] == [DEFERRED_GOAL_ID], paged + assert paged["summary"]["filtered_goal_count"] == 2, paged + assert paged["summary"]["truncated"] is True, paged + paged_coverage = paged["projection_envelope"]["coverage"] + assert paged_coverage["shown_count"] == 1, paged_coverage + assert paged_coverage["available_count"] == 2, paged_coverage + assert paged_coverage["truncated"] is True, paged_coverage + + blank = lifecycle(["--agent-id", "", "--limit", "8"]) + # The flag is present, so the scope is armed even with an empty value: the + # page must not widen back to the estate. + assert blank["request"]["agent_filter"] == [""], blank + assert blank["summary"]["agent_scope_requested"] is True, blank + assert blank["goals"] == [], blank + blank_coverage = blank["projection_envelope"]["coverage"] + assert blank_coverage["shown_count"] == 0, blank_coverage + assert blank_coverage["available_count"] == 0, blank_coverage + assert blank_coverage["truncated"] is False, blank_coverage + + empty_phase = lifecycle(["--agent-id", SECOND_AGENT_ID, "--phase", "closed"]) + assert empty_phase["goals"] == [], empty_phase + assert empty_phase["summary"]["filtered_goal_count"] == 0, empty_phase + empty_coverage = empty_phase["projection_envelope"]["coverage"] + assert empty_coverage["shown_count"] == 0, empty_coverage + assert empty_coverage["available_count"] == 0, empty_coverage + assert empty_coverage["truncated"] is False, empty_coverage + + +def assert_lifecycle_payload(payload: dict[str, object]) -> None: + assert payload["ok"] is True, payload + request = payload["request"] + assert request["command"] == "/loopx-global-lifecycle", request + assert request["legacy_aliases"] == ["/loop-global-lifecycle"], request + assert request["cli_command"] == "loopx global-lifecycle", request + assert request["phase_filter"] == [], request + assert request["dry_run"] is True, request + assert payload["board_schema_version"] == "global_goal_lifecycle_board_v0", payload + summary = payload["summary"] + assert summary["goals_inspected"] == 3, payload + assert summary["goals_with_projection"] == 3, payload + assert summary["goals_without_projection"] == 0, payload + assert summary["blocked_goal_count"] == 1, payload + assert summary["phase_counts"] == {"waiting_owner": 1, "qualifying": 2}, payload + # This fixture has no global registry, so the board covers every Goal the + # status read returned while refusing to certify the whole global estate. + assert payload["complete"] is False, payload + # The owner-gated Goal leads; unfiltered rows keep the phase order. + assert payload["phases"] == [ + { + "lifecycle_phase": "waiting_owner", + "goal_count": 1, + "goal_ids": [GOAL_ID], + }, + { + "lifecycle_phase": "qualifying", + "goal_count": 2, + "goal_ids": [DEFERRED_GOAL_ID, RUNNABLE_GOAL_ID], + }, + ], payload + assert payload["guards"] == [ + { + "kind": "owner_decision", + "owner": "user", + "blocked_goal_count": 1, + "blocked_goal_ids": [GOAL_ID], + } + ], payload + assert [row["goal_id"] for row in payload["goals"]] == [ + GOAL_ID, + DEFERRED_GOAL_ID, + RUNNABLE_GOAL_ID, + ], payload + blocked = payload["goals"][0] + assert blocked["lifecycle_phase"] == "waiting_owner", blocked + assert blocked["guards_open"][0]["id"] == "todo_gate_approve", blocked + assert blocked["next_transition"]["precondition"] == ( + "resolve the open owner decision" + ), blocked + assert payload["gaps"] == [], payload + # This fixture has no global registry, so the global membership denominator + # is unknown: the board is whole for the Goals status returned, while the + # envelope refuses to certify global scope, exactly like its peer commands. + envelope = payload["projection_envelope"] + # The board covers every Goal status returned, but this fixture has no + # global registry, so no answer here can certify the whole global estate. + # `complete` repeats the envelope verdict rather than contradicting it. + assert payload["complete"] is False, payload + assert envelope["coverage"]["expected_count"] is None, envelope + assert envelope["complete"] is False, envelope + assert "missing_required_sources" in envelope["alert_reasons"], envelope + assert envelope["coverage"]["available_count"] == 3, envelope + assert_public_safe(payload) + + +def assert_lifecycle_markdown(markdown: str, *, private_root: Path) -> None: + assert "# LoopX Global Lifecycle" in markdown, markdown + assert "`/loopx-global-lifecycle`" in markdown, markdown + assert "## Phases" in markdown, markdown + assert "## Blocking Guards" in markdown, markdown + assert "blocked_by owner_decision(user):todo_gate_approve" in markdown, markdown + assert "Read-only report" in markdown, markdown + assert str(private_root) not in markdown, markdown + for marker in synthetic_private_markers().values(): + assert marker not in markdown, marker + + def assert_error_envelope(root: Path, *, runtime: Path) -> None: error_registry = root / "private" / "error-registry" error_registry.mkdir(parents=True) @@ -402,6 +576,29 @@ def assert_error_envelope(root: Path, *, runtime: Path) -> None: assert "" in error_proc.stdout, error_proc.stdout assert_public_safe(payload) + for output_format in ("json", "markdown"): + lifecycle_error_proc = run_cli( + registry=error_registry, + runtime=runtime, + command="global-lifecycle", + output_format=output_format, + check=False, + ) + assert lifecycle_error_proc.returncode != 0, lifecycle_error_proc + assert str(error_registry) not in lifecycle_error_proc.stdout, lifecycle_error_proc.stdout + assert "" in lifecycle_error_proc.stdout, lifecycle_error_proc.stdout + if output_format == "json": + lifecycle_payload = json.loads(lifecycle_error_proc.stdout) + assert lifecycle_payload["ok"] is False, lifecycle_payload + assert ( + lifecycle_payload["error_code"] == "status_collection_unavailable" + ), lifecycle_payload + assert "phases" not in lifecycle_payload, lifecycle_payload + assert "goals" not in lifecycle_payload, lifecycle_payload + assert_public_safe(lifecycle_payload) + else: + assert "# LoopX Global Lifecycle Unavailable" in lifecycle_error_proc.stdout + todos_error_proc = run_cli( registry=error_registry, runtime=runtime, @@ -508,6 +705,22 @@ def assert_unhealthy_status_envelope( output_format="json", check=False, ) + + lifecycle_proc = run_cli( + registry=unhealthy_registry, + runtime=runtime, + command="global-lifecycle", + output_format="json", + check=False, + ) + assert lifecycle_proc.returncode != 0, lifecycle_proc + lifecycle_payload = json.loads(lifecycle_proc.stdout) + assert lifecycle_payload["ok"] is False, lifecycle_payload + assert lifecycle_payload["error_code"] == "status_collection_unavailable", lifecycle_payload + assert "summary" not in lifecycle_payload, lifecycle_payload + assert "goals" not in lifecycle_payload, lifecycle_payload + assert str(root) not in lifecycle_proc.stdout, lifecycle_proc.stdout + assert_public_safe(lifecycle_payload) assert risks_proc.returncode == 0, risks_proc risks_payload = json.loads(risks_proc.stdout) assert risks_payload["ok"] is True, risks_payload @@ -612,6 +825,28 @@ def run_scenario(provider: str | None) -> None: output_format="markdown", command_args=risks_args, ) + lifecycle_args = ["--agent-id", AGENT_ID, "--limit", "8"] + lifecycle_proc = run_cli( + registry=registry, + runtime=runtime, + command="global-lifecycle", + output_format="json", + command_args=lifecycle_args, + ) + lifecycle_markdown_proc = run_cli( + registry=registry, + runtime=runtime, + command="global-lifecycle", + output_format="markdown", + command_args=lifecycle_args, + ) + phase_proc = run_cli( + registry=registry, + runtime=runtime, + command="global-lifecycle", + output_format="json", + command_args=[*lifecycle_args, "--phase", "qualifying", "--limit", "1"], + ) assert_summary_payload(json.loads(summary_proc.stdout)) assert_gates_payload(json.loads(gates_proc.stdout)) @@ -620,6 +855,20 @@ def run_scenario(provider: str | None) -> None: assert_todos_markdown(todos_markdown_proc.stdout, private_root=root) assert_risks_payload(json.loads(risks_proc.stdout), unresolved_failure=False) assert_risks_markdown(risks_markdown_proc.stdout, private_root=root) + assert_lifecycle_payload(json.loads(lifecycle_proc.stdout)) + assert_lifecycle_markdown(lifecycle_markdown_proc.stdout, private_root=root) + assert_lifecycle_agent_scope(root, registry=registry, runtime=runtime) + phase_payload = json.loads(phase_proc.stdout) + # A phase filter narrows returned rows, never the rollups. + assert phase_payload["request"]["phase_filter"] == ["qualifying"], phase_payload + assert phase_payload["summary"]["goals_inspected"] == 3, phase_payload + assert phase_payload["summary"]["returned_goal_count"] == 1, phase_payload + assert phase_payload["summary"]["truncated"] is True, phase_payload + assert [ + row["lifecycle_phase"] for row in phase_payload["goals"] + ] == ["qualifying"], phase_payload + assert len(phase_payload["phases"]) == 2, phase_payload + assert_public_safe(phase_payload) assert snapshot_files(files) == before # Change only this synthetic historical run: real failures must not be diff --git a/loopx/canary/workflow_domain_profiles.py b/loopx/canary/workflow_domain_profiles.py index 7a52e23f20..95acaa8efe 100644 --- a/loopx/canary/workflow_domain_profiles.py +++ b/loopx/canary/workflow_domain_profiles.py @@ -249,6 +249,7 @@ "/loopx-global-gates", "/loopx-global-todos", "/loopx-global-risks", + "/loopx-global-lifecycle", "global-manager", "global manager", "host command", diff --git a/loopx/cli_commands/global_lifecycle.py b/loopx/cli_commands/global_lifecycle.py new file mode 100644 index 0000000000..c401218f3e --- /dev/null +++ b/loopx/cli_commands/global_lifecycle.py @@ -0,0 +1,516 @@ +"""Read-only cross-Goal lifecycle board over already-collected status. + +`loopx global-lifecycle` is the CLI face of the accepted RFC +`goal-artifact-lifecycle-projection-v0` §4 application 1: one cross-Goal view +of phases, milestone coverage, blocking guards and the next transition per +Goal. It collects status exactly once and aggregates the projections the +status owner already derived; it never derives a second lifecycle, writes no +state and spends no quota. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from ..control_plane.goals.lifecycle_board import ( + GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION, + GAP_PROJECTION_NOT_DERIVED, + PHASE_ORDER, + build_global_goal_lifecycle_board, +) +from ..control_plane.projection_envelope_facts import ( + render_projection_envelope_markdown, + seal_projection_envelope, + source_fact, +) +from ..control_plane.runtime.time import now_utc_iso +from ..presentation.markdown import as_dict, as_list +from ..presentation.public_safety import public_safe_boundary, redact_public_text +from ..status import collect_status + + +COMMAND = "/loopx-global-lifecycle" +SCHEMA_VERSION = "global_manager_command_response_v0" +GAP_LIMIT = 8 + + +def _redact_text(value: object, *, limit: int = 220) -> str: + redacted: str = redact_public_text( + value, + limit=limit, + replacements={"/loop-global-lifecycle": COMMAND}, + truncation_marker="…", + ) + return redacted + + +def _request( + *, limit: int, phases: list[str], agent_id: str | None = None +) -> dict[str, Any]: + return { + "schema_version": "global_manager_command_request_v0", + "command": COMMAND, + "legacy_aliases": ["/loop-global-lifecycle"], + "cli_command": "loopx global-lifecycle", + "include": ["phases", "milestones", "guards", "next_transitions"], + "phase_filter": list(phases), + # The request states the Agent scope it actually applied, so a reader + # cannot take an unfiltered estate for a filtered page. Presence is what + # arms the filter, so an explicitly blank value is echoed, never dropped. + "agent_filter": [agent_id] if agent_id is not None else [], + "limit": limit, + "privacy_mode": "public_safe_summary", + "dry_run": True, + } + + +def _scope_counts( + status_payload: dict[str, Any], summary: dict[str, Any] +) -> dict[str, int | None]: + """Global scope accounting shared by the envelope and the top-level verdict. + + The scope is global, so the denominator is global membership, never the + local registry this process happened to read. A bounded status read that + never reached some in-scope Goals is an omission, not a smaller estate. + """ + + global_registry = as_dict(status_payload.get("global_registry")) + available = global_registry.get("available") is True + global_count = global_registry.get("global_goal_count") + expected = ( + global_count + if available and isinstance(global_count, int) and not isinstance(global_count, bool) + else None + ) + excluded = ( + int(global_registry.get("current_registry_excluded_goal_count") or 0) + if available + else 0 + ) + inspected = summary.get("goals_inspected") + unscanned = ( + max(0, expected - excluded - inspected) + if expected is not None and isinstance(inspected, int) + else 0 + ) + return {"expected": expected, "excluded": excluded, "inspected": inspected, "unscanned": unscanned} + + +def _envelope( + status_payload: dict[str, Any], + *, + status_read_at: str | None, + board: dict[str, Any] | None, + failed_status_goals: int = 0, +) -> dict[str, Any]: + status_envelope = as_dict(status_payload.get("projection_envelope")) + # Only a sealed upstream envelope may be composed; an absent or foreign + # status envelope stays out rather than failing this read. + upstream = ( + [status_envelope] + if isinstance(status_envelope.get("coverage"), dict) + and isinstance(status_envelope.get("sources"), list) + else [] + ) + global_registry = as_dict(status_payload.get("global_registry")) + global_source = next( + ( + row + for row in as_list(status_envelope.get("sources")) + if isinstance(row, dict) and row.get("source_id") == "global_registry" + ), + {}, + ) + summary = as_dict(as_dict(board).get("summary")) + scope = _scope_counts(status_payload, summary) + shown = summary.get("returned_goal_count") + if not isinstance(shown, int) or isinstance(shown, bool): + shown = None + filtered = summary.get("filtered_goal_count") + if not isinstance(filtered, int) or isinstance(filtered, bool): + filtered = None + available = global_registry.get("available") is True + expected = scope["expected"] + excluded = scope["excluded"] or 0 + unscanned = scope["unscanned"] or 0 + omitted: list[dict[str, Any]] = [] + if excluded: + omitted.append( + { + "reason": "outside_current_registry", + "count": excluded, + "refs": [ + _redact_text(ref, limit=120) + for ref in as_list( + global_registry.get("current_registry_excluded_goal_ids") + )[:8] + ], + } + ) + if failed_status_goals: + omitted.append({"reason": "status_unavailable", "count": failed_status_goals}) + elif status_payload.get("ok") is not True: + # Whether the read raised before producing a payload or returned an + # unhealthy one, the estate behind this answer is missing; say so + # rather than reporting an empty omission list next to `not_read`. + omitted.append({"reason": "status_unavailable", "count": 1}) + without_projection = summary.get("goals_without_projection") + if isinstance(without_projection, int) and without_projection: + omitted.append( + {"reason": GAP_PROJECTION_NOT_DERIVED, "count": without_projection} + ) + without_identity = summary.get("goals_without_identity") + if isinstance(without_identity, int) and without_identity: + omitted.append({"reason": "goal_identity_unavailable", "count": without_identity}) + if unscanned: + omitted.append({"reason": "goal_scan_omitted", "count": unscanned}) + projected = summary.get("goals_with_projection") + # Included means "carried a derived projection in this answer". It can never + # exceed what was inspected or what remains inside the current registry. + included = ( + min(projected, max(0, expected - excluded)) + if isinstance(projected, int) and expected is not None + else 0 + ) + sealed: dict[str, Any] = seal_projection_envelope( + projection="global_goal_lifecycle", + observed_at=now_utc_iso(), + sources=[ + source_fact( + "global_registry", + read_status=( + str(global_source.get("read_status") or "read") + if available + else str( + global_registry.get("read_status") + or ("missing" if status_read_at else "not_read") + ) + ), + last_read_at=global_source.get("last_read_at") + or (status_read_at if available else None), + item_count=expected, + ), + *( + [] + if upstream + else [ + source_fact( + "status", + read_status="read" if status_read_at else "not_read", + last_read_at=status_read_at, + item_count=summary.get("goals_inspected"), + ) + ] + ), + ], + coverage={ + "scope": "global", + "expected_count": expected, + "included_count": included, + "omitted": omitted, + "shown_count": shown, + # A display limit can only page through the rows the filters + # selected. `available_count` is that pageable count — after Agent + # and phase selection, before the limit — so an empty filtered page + # is not reported as a truncated one. + "available_count": filtered if filtered is not None else shown, + }, + upstream=upstream, + ) + return sealed + + +def build_global_lifecycle_error( + error: object, + *, + limit: int, + phases: list[str], + agent_id: str | None = None, + status_payload: dict[str, Any] | None = None, + status_read_at: str | None = None, + error_code: str = "global_lifecycle_unavailable", +) -> dict[str, Any]: + payload: dict[str, Any] = { + "ok": False, + "schema_version": SCHEMA_VERSION, + "request": _request(limit=limit, phases=phases, agent_id=agent_id), + "generated_at": now_utc_iso(), + "error_code": _redact_text(error_code, limit=120), + "error": _redact_text(error), + "omissions": [ + "Raw/private failure details and local paths were intentionally omitted." + ], + "boundary": public_safe_boundary(), + } + try: + payload["projection_envelope"] = _envelope( + status_payload or {}, + status_read_at=status_read_at, + board=None, + ) + except Exception: + pass + return payload + + +def _status_failure_count(status_payload: dict[str, Any]) -> int: + contract = as_dict(status_payload.get("contract")) + diagnostics = contract.get("error_diagnostics") + if not isinstance(diagnostics, list): + return 0 + return sum( + 1 + for row in diagnostics + if isinstance(row, dict) and row.get("goal_id") + ) + + +def build_global_lifecycle( + *, + registry_path: Path, + runtime_root_override: str | None, + limit: int, + phases: list[str] | None = None, + agent_id: str | None = None, +) -> dict[str, Any]: + wanted = [str(phase) for phase in (phases or []) if phase] + # A blank value still means "the caller asked for an Agent scope": dropping + # it here would silently return the unfiltered estate. + requested_agent = _redact_text(agent_id, limit=120) if agent_id is not None else None + unknown = sorted(set(wanted) - set(PHASE_ORDER)) + if unknown: + return build_global_lifecycle_error( + "Unsupported lifecycle phase filter: " + ", ".join(unknown) + ".", + limit=max(1, limit), + phases=wanted, + agent_id=requested_agent, + error_code="unsupported_phase_filter", + ) + # One bounded status read feeds every rollup, so the envelope names the + # in-scope Goals this cap never reached instead of presenting the sample as + # the whole estate. The cap is generous enough to cover ordinary estates. + scan_limit = max(min(max(1, limit), 200) * 25, 2500) + try: + status_payload = collect_status( + registry_path=registry_path, + runtime_root_override=runtime_root_override, + limit=scan_limit, + agent_lane_id=requested_agent, + ) + except Exception as exc: + return build_global_lifecycle_error( + exc, + limit=max(1, limit), + phases=wanted, + agent_id=requested_agent, + error_code="status_collection_unavailable", + ) + status_read_at = now_utc_iso() + if status_payload.get("ok") is not True: + return build_global_lifecycle_error( + "Global status source unavailable.", + limit=max(1, limit), + phases=wanted, + agent_id=requested_agent, + status_payload=status_payload, + status_read_at=status_read_at, + error_code="status_collection_unavailable", + ) + try: + board = build_global_goal_lifecycle_board( + status_payload, + limit=max(1, limit), + phases=wanted, + agent_id=requested_agent, + ) + except ValueError as exc: + return build_global_lifecycle_error( + exc, + limit=max(1, limit), + phases=wanted, + agent_id=requested_agent, + status_payload=status_payload, + status_read_at=status_read_at, + error_code="lifecycle_board_boundary_rejected", + ) + summary = as_dict(board.get("summary")) + envelope = _envelope( + status_payload, + status_read_at=status_read_at, + board=board, + failed_status_goals=_status_failure_count(status_payload), + ) + return { + "ok": True, + "schema_version": SCHEMA_VERSION, + "request": _request( + limit=max(1, limit), phases=wanted, agent_id=requested_agent + ), + "generated_at": now_utc_iso(), + "board_schema_version": GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION, + "summary": { + **summary, + "headline": ( + f"{summary.get('goals_with_projection')} of " + f"{summary.get('goals_inspected')} Goals carry a derived lifecycle " + f"projection; {summary.get('blocked_goal_count')} are guard-blocked." + ), + }, + "phases": board["phases"], + "guards": board["guards"], + "milestones": board["milestones"], + "goals": board["goals"], + "gaps": board["gaps"][:GAP_LIMIT], + "gaps_truncated": len(board["gaps"]) > GAP_LIMIT, + # One verdict, one meaning: the board is complete only when every Goal + # in global scope carried a projection and no source was omitted. The + # envelope decides scope; this field repeats it so a JSON consumer that + # reads only `complete` cannot mistake a partial scan for a whole estate. + "complete": bool(board["complete"] and envelope.get("complete") is True), + "projection_envelope": envelope, + "omissions": [ + ( + "Raw logs, transcripts, connector payloads, credential values, local " + "paths and private source bodies were intentionally omitted." + ), + ( + "Milestones and guards are the status owner's derived projection; this " + "board never re-derives a lifecycle or a second acceptance verdict." + ), + ], + "boundary": public_safe_boundary(), + } + + +def _render_goal_line(goal: dict[str, Any]) -> str: + line = ( + f"- goal=`{_redact_text(goal.get('goal_id'), limit=120)}` " + f"phase=`{_redact_text(goal.get('lifecycle_phase'), limit=40)}` " + f"milestones=`{goal.get('milestones_reached_count')}/" + f"{goal.get('milestones_total_count')}` " + f"open_guards=`{goal.get('guards_open_count')}`" + ) + reached = [ + _redact_text(item, limit=60) + for item in as_list(goal.get("milestones_reached")) + if _redact_text(item, limit=60) + ] + if reached: + line += " reached=" + ", ".join(reached) + "." + for guard in as_list(goal.get("guards_open")): + record = as_dict(guard) + line += ( + f" blocked_by {_redact_text(record.get('kind'), limit=60)}" + f"({_redact_text(record.get('owner'), limit=80)}):" + f"{_redact_text(record.get('id'), limit=120)}." + ) + transition = as_dict(goal.get("next_transition")) + if transition: + line += ( + f" Next: {_redact_text(transition.get('target_phase'), limit=40)} — " + f"{_redact_text(transition.get('precondition'))}" + ) + return line + + +def render_global_lifecycle_markdown(payload: dict[str, Any]) -> str: + if not payload.get("ok"): + lines = [ + "# LoopX Global Lifecycle Unavailable", + "", + "- ok: `False`", + f"- error_code: `{_redact_text(payload.get('error_code'), limit=120)}`", + f"- error: {_redact_text(payload.get('error'))}", + *render_projection_envelope_markdown(payload.get("projection_envelope")), + ] + omissions = [ + _redact_text(item) + for item in as_list(payload.get("omissions")) + if _redact_text(item) + ] + if omissions: + lines.extend(["", "## Omissions"]) + lines.extend(f"- {item}" for item in omissions) + return "\n".join(lines) + + summary = as_dict(payload.get("summary")) + request = as_dict(payload.get("request")) + lines = [ + "# LoopX Global Lifecycle", + "", + f"- command: `{_redact_text(request.get('command'), limit=120)}`", + f"- {_redact_text(summary.get('headline'))}", + f"- complete: `{bool(payload.get('complete'))}`", + f"- truncated: `{bool(summary.get('truncated'))}`", + *render_projection_envelope_markdown(payload.get("projection_envelope")), + "", + "Phases, guards and milestones are the status owner's derived projection.", + ] + lines.extend(["", "## Phases"]) + phase_rows = [as_dict(item) for item in as_list(payload.get("phases"))] + if phase_rows: + lines.extend( + f"- `{_redact_text(row.get('lifecycle_phase'), limit=40)}`: " + f"{row.get('goal_count')} goal(s)" + for row in phase_rows + ) + else: + lines.append("- No Goal carries a derived lifecycle projection.") + lines.extend(["", "## Blocking Guards"]) + guards = [as_dict(item) for item in as_list(payload.get("guards"))] + if guards: + lines.extend( + f"- `{_redact_text(row.get('kind'), limit=60)}` " + f"owner=`{_redact_text(row.get('owner'), limit=80)}` blocks " + f"{row.get('blocked_goal_count')} goal(s): " + + ", ".join( + _redact_text(goal_id, limit=120) + for goal_id in as_list(row.get("blocked_goal_ids"))[:8] + ) + for row in guards + ) + else: + lines.append("- None.") + lines.extend(["", "## Milestones Reached"]) + milestones = [as_dict(item) for item in as_list(payload.get("milestones"))] + if milestones: + lines.extend( + f"- `{_redact_text(row.get('milestone_id'), limit=60)}`: " + f"{row.get('reached_goal_count')} goal(s)" + for row in milestones + ) + else: + lines.append("- None.") + lines.extend(["", "## Goals"]) + goals = [as_dict(item) for item in as_list(payload.get("goals"))] + if goals: + lines.extend(_render_goal_line(goal) for goal in goals) + else: + lines.append("- None.") + gaps = [as_dict(item) for item in as_list(payload.get("gaps"))] + if gaps: + lines.extend(["", "## Lifecycle Gaps"]) + lines.extend( + f"- goal=`{_redact_text(gap.get('goal_id'), limit=120)}` " + f"reason=`{_redact_text(gap.get('reason'), limit=80)}`" + for gap in gaps + ) + if payload.get("gaps_truncated"): + lines.append("- Further gaps were omitted from display; see the envelope.") + lines.extend( + [ + "", + "## Boundary", + "- Read-only report; it does not close Goals, resolve guards or spend quota.", + ] + ) + return "\n".join(lines) + + +__all__ = [ + "COMMAND", + "build_global_lifecycle", + "build_global_lifecycle_error", + "render_global_lifecycle_markdown", +] diff --git a/loopx/cli_commands/summary_all.py b/loopx/cli_commands/summary_all.py index 5b2b735d98..f87cd28e55 100644 --- a/loopx/cli_commands/summary_all.py +++ b/loopx/cli_commands/summary_all.py @@ -23,6 +23,11 @@ render_global_gates_markdown, render_summary_all_markdown, ) +from .global_lifecycle import ( + build_global_lifecycle, + build_global_lifecycle_error, + render_global_lifecycle_markdown, +) from .summary_all_registration import register_summary_all_command as register_summary_all_command @@ -48,6 +53,7 @@ def handle_summary_all_command( "global-gates", "global-todos", "global-risks", + "global-lifecycle", }: return None if args.command == "goal-portfolio": @@ -79,6 +85,22 @@ def handle_summary_all_command( } print_payload(payload, output_format(args), render_goal_portfolio) return 0 if payload.get("ok") else 1 + if args.command == "global-lifecycle": + phases = list(getattr(args, "lifecycle_phases", None) or []) + try: + payload = build_global_lifecycle( + registry_path=registry_path, + runtime_root_override=runtime_root_arg, + limit=max(1, args.limit), + phases=phases, + agent_id=args.agent_id, + ) + except Exception as exc: + payload = build_global_lifecycle_error( + exc, limit=max(1, args.limit), phases=phases + ) + print_payload(payload, output_format(args), render_global_lifecycle_markdown) + return 0 if payload.get("ok") else 1 if args.command == "global-risks": try: payload = build_global_risks( diff --git a/loopx/cli_commands/summary_all_registration.py b/loopx/cli_commands/summary_all_registration.py index 04a15d6f00..7c9e8b026d 100644 --- a/loopx/cli_commands/summary_all_registration.py +++ b/loopx/cli_commands/summary_all_registration.py @@ -6,6 +6,7 @@ GLOBAL_READ_COMMANDS = frozenset({ "goal-portfolio", "global-summary", "global-gates", "global-todos", "global-risks", + "global-lifecycle", }) @@ -114,3 +115,24 @@ def register_summary_all_command( "current risks remain visible." ), ) + + lifecycle_parser = subparsers.add_parser( + "global-lifecycle", + help=( + "Read a public-safe cross-Goal lifecycle board (phases, milestones, " + "blocking guards, next transition) from existing status projections." + ), + ) + add_subcommand_format(lifecycle_parser) + _add_current_manager_flags( + lifecycle_parser, + agent_help="Registered agent id used to narrow the status read.", + limit_help="Maximum returned Goal rows; rollups still cover every Goal.", + ) + lifecycle_parser.add_argument( + "--phase", + action="append", + dest="lifecycle_phases", + choices=("starting", "qualifying", "waiting_owner", "closing", "closed"), + help="Exact lifecycle phase to include; repeat to widen scope.", + ) diff --git a/loopx/control_plane/goals/lifecycle_board.py b/loopx/control_plane/goals/lifecycle_board.py new file mode 100644 index 0000000000..5aac4be352 --- /dev/null +++ b/loopx/control_plane/goals/lifecycle_board.py @@ -0,0 +1,385 @@ +"""Read-only cross-Goal view over the derived artifact lifecycle projection. + +The accepted RFC `goal-artifact-lifecycle-projection-v0` §4 names one mid-term +application: aggregate the per-Goal projection across Goals into a single +board that answers "which Goals reached which milestones, which guards block +how many Goals, and what is the next transition per Goal". + +This module is that aggregation and nothing more. Every input is a status +payload the caller already collected; it reads no files, writes no state and +grants no authority. A Goal whose projection the status owner could not derive +becomes a typed gap row, never a re-derivation and never a silent omission, so +"not derived" and "nobody looked" stay distinguishable to the operator. +""" + +from __future__ import annotations + +from collections import Counter +from typing import Any + +from ...public_safe_text import ARTIFACT_LIFECYCLE_CATEGORIES, classify_private_text +from ..runtime.public_safety import ( + public_safe_compact_text, + validate_public_safe_value, +) +from ...agent_registry import normalize_registered_agents, registered_agent_ids_for_goal +from .artifact_lifecycle import ( + GOAL_ARTIFACT_LIFECYCLE_PROJECTION_SCHEMA_VERSION, + PHASE_CLOSED, + PHASE_CLOSING, + PHASE_QUALIFYING, + PHASE_STARTING, + PHASE_WAITING_OWNER, +) + +GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION = "global_goal_lifecycle_board_v0" +GLOBAL_GOAL_LIFECYCLE_GAP_SCHEMA_VERSION = "global_goal_lifecycle_gap_v0" + +# Display order only; a Goal moves between phases without a durable transition. +PHASE_ORDER = ( + PHASE_WAITING_OWNER, + PHASE_QUALIFYING, + PHASE_STARTING, + PHASE_CLOSING, + PHASE_CLOSED, +) +_PHASE_RANK = {phase: index for index, phase in enumerate(PHASE_ORDER)} +UNKNOWN_PHASE = "unknown" + +GAP_PROJECTION_NOT_DERIVED = "projection_not_derived" + + +def _mapping(value: Any) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + +def _list(value: Any) -> list[Any]: + return value if isinstance(value, list) else [] + + +def _label(value: Any, *, limit: int = 120) -> str | None: + """Bound one already-derived label without widening the public boundary. + + The projection validated its own text before publishing it. Re-validating + the complete source keeps this board from minting a wider label if a future + producer hands it an unchecked string. + """ + + if not isinstance(value, str): + return None + text = value.strip() + if not text: + return None + try: + validate_public_safe_value(text) + except ValueError: + return None + if classify_private_text(text, categories=ARTIFACT_LIFECYCLE_CATEGORIES) is not None: + return None + compact: str | None = public_safe_compact_text(text, limit=limit) + return compact + + +def _identity(value: Any) -> str | None: + """Validate one machine identity without truncating it. + + A Goal id decides roster membership, rollup dedupe and the row key a + consumer joins on, so two ids must stay distinguishable even when their + first characters agree. Display bounds are applied separately by `_label`; + identity keeps the validated text exactly as the status owner published it. + """ + + if not isinstance(value, str): + return None + text = value.strip() + if not text: + return None + try: + validate_public_safe_value(text) + except ValueError: + return None + if classify_private_text(text, categories=ARTIFACT_LIFECYCLE_CATEGORIES) is not None: + return None + return text + + +def _is_projection(value: Any) -> bool: + projection = _mapping(value) + return ( + projection.get("schema_version") + == GOAL_ARTIFACT_LIFECYCLE_PROJECTION_SCHEMA_VERSION + and isinstance(projection.get("milestones"), list) + ) + + +def _goal_row( + goal_id: str, projection: dict[str, Any], *, status: dict[str, Any] +) -> dict[str, Any]: + guards = [ + guard for guard in _list(projection.get("guards")) if _mapping(guard) + ] + open_guards = [guard for guard in guards if guard.get("blocked") is True] + milestones = [ + milestone + for milestone in _list(projection.get("milestones")) + if _mapping(milestone) + ] + reached = [ + milestone + for milestone in milestones + if milestone.get("reached") is True + ] + transitions = [ + transition + for transition in _list(projection.get("next_transitions")) + if _mapping(transition) + ] + seen_guards: set[tuple[str, str, str]] = set() + open_guard_rows: list[dict[str, str]] = [] + for guard in open_guards: + row = { + "id": _label(guard.get("id"), limit=120) or "unnamed_guard", + "kind": _label(guard.get("kind"), limit=60) or "unknown", + "owner": _label(guard.get("owner"), limit=120) or "unowned", + } + key = (row["id"], row["kind"], row["owner"]) + if key in seen_guards: + continue + seen_guards.add(key) + open_guard_rows.append(row) + phase = _label(projection.get("lifecycle_phase"), limit=40) or UNKNOWN_PHASE + # Count what this row publishes, not what it received: a milestone id that + # cannot be published is dropped from the list, and a count that still + # included it would describe a row the operator cannot see. + reached_ids: list[str] = [] + for item in reached: + label = _label(item.get("id"), limit=60) + # A producer that repeats a milestone must not make the row claim more + # reached milestones than the rollup credits this Goal with. + if label and label not in reached_ids: + reached_ids.append(label) + return { + "goal_id": goal_id, + "goal_status": _label(status.get("status"), limit=40), + "activation_state": _label(status.get("activation_state"), limit=40), + "lifecycle_phase": phase, + "projection_status": "derived", + "milestones_reached_count": len(reached_ids), + "milestones_total_count": len(milestones), + "milestones_reached": reached_ids, + "guards_open_count": len(open_guard_rows), + "guards_open": open_guard_rows, + "next_transition": ( + { + "target_phase": _label(transitions[0].get("target_phase"), limit=40) + or UNKNOWN_PHASE, + "precondition": _label(transitions[0].get("precondition")), + "reason_codes": [ + code + for code in ( + _label(item, limit=60) + for item in _list(transitions[0].get("reason_codes")) + ) + if code + ], + } + if transitions + else None + ), + } + + +def _gap_row(goal_id: str, *, reason: str) -> dict[str, Any]: + return { + "schema_version": GLOBAL_GOAL_LIFECYCLE_GAP_SCHEMA_VERSION, + "goal_id": goal_id, + "projection_status": "unavailable", + "reason": reason, + } + + +def _phase_rank(row: dict[str, Any]) -> tuple[int, str]: + phase = str(row.get("lifecycle_phase") or "") + return (_PHASE_RANK.get(phase, len(PHASE_ORDER)), str(row.get("goal_id") or "")) + + +def build_global_goal_lifecycle_board( + status_payload: dict[str, Any] | None, + *, + limit: int = 50, + phases: list[str] | None = None, + agent_id: str | None = None, +) -> dict[str, Any]: + """Aggregate every derived projection the status payload already carries. + + `limit` bounds returned Goal rows, not what was inspected: the phase, guard + and milestone rollups always describe every projected Goal so a truncated + page cannot read as a smaller estate. Unknown projection schemas are typed + gaps rather than silently skipped Goals. + + `phases` and `agent_id` choose which rows the page lists. A phase is a + window over an already-derived phase, and an agent matches only Goals whose + recorded roster registers that exact identity, so both filters can only + narrow the page: coverage and the cross-Goal rollups keep describing the + whole inspected estate. An unknown agent matches nothing instead of + silently widening back to every Goal. + """ + + bounded_limit = max(1, int(limit)) + status = _mapping(status_payload) + run_history = _mapping(status.get("run_history")) + goals = [goal for goal in _list(run_history.get("goals")) if _mapping(goal)] + + rows: list[dict[str, Any]] = [] + gaps: list[dict[str, Any]] = [] + scoped_goal_ids: set[str] = set() + unidentified = 0 + # The flag's presence decides whether a filter applies, never its text: an + # identity that does not normalize matches no roster, so it selects an empty + # page instead of silently widening back to the whole estate. + agent_scope_requested = agent_id is not None + requested_agents = ( + normalize_registered_agents(agent_id) if agent_scope_requested else [] + ) + for goal in goals: + goal_id = _identity(goal.get("id")) + if goal_id and ( + not agent_scope_requested + or any( + agent in registered_agent_ids_for_goal(goal) + for agent in requested_agents + ) + ): + scoped_goal_ids.add(goal_id) + if not goal_id: + # A Goal whose identity cannot be published is still part of the + # inspected estate. Dropping it would shrink the board silently and + # let a partial answer read as complete. + unidentified += 1 + continue + projection = goal.get("artifact_lifecycle") + if not _is_projection(projection): + gaps.append(_gap_row(goal_id, reason=GAP_PROJECTION_NOT_DERIVED)) + continue + rows.append(_goal_row(goal_id, _mapping(projection), status=goal)) + + # One ordering pass decides every row list: phase rank for the operator + # order, then Goal id, so the rollups and the page agree regardless of the + # order the status payload happened to use. + rows.sort(key=_phase_rank) + phase_counts = Counter(str(row["lifecycle_phase"]) for row in rows) + # Known phases keep the operator order; a phase a future producer adds is + # still listed after them instead of vanishing from the rollup. + rollup_phases = [ + phase for phase in PHASE_ORDER if phase_counts.get(phase) + ] + sorted(set(phase_counts) - set(PHASE_ORDER)) + phases_summary = [ + { + "lifecycle_phase": phase, + "goal_count": phase_counts.get(phase, 0), + "goal_ids": [ + str(row["goal_id"]) + for row in rows + if row["lifecycle_phase"] == phase + ], + } + for phase in rollup_phases + ] + + guard_rollup: dict[tuple[str, str], set[str]] = {} + milestone_rollup: dict[str, set[str]] = {} + for row in rows: + goal_id = str(row["goal_id"]) + # One Goal blocked by two guards of the same kind/owner is one blocked + # Goal for that guard, not two; otherwise the board overstates reach. + for guard in row["guards_open"]: + key = (str(guard["kind"]), str(guard["owner"])) + guard_rollup.setdefault(key, set()).add(goal_id) + for milestone in row["milestones_reached"]: + milestone_rollup.setdefault(milestone, set()).add(goal_id) + guards_summary: list[dict[str, Any]] = [ + { + "kind": kind, + "owner": owner, + "blocked_goal_count": len(blocked), + "blocked_goal_ids": sorted(blocked), + } + for (kind, owner), blocked in sorted( + guard_rollup.items(), + key=lambda entry: (-len(entry[1]), entry[0][0], entry[0][1]), + ) + ] + milestones_summary: list[dict[str, Any]] = [ + { + "milestone_id": milestone_id, + "reached_goal_count": len(reached), + "reached_goal_ids": sorted(reached), + } + for milestone_id, reached in sorted(milestone_rollup.items()) + ] + + wanted = {str(phase) for phase in (phases or []) if phase} + # The page is the only filtered surface: an agent-scoped Goal row is listed + # when its roster registers the requested identity, and a phase narrows that + # page further. `filtered_goal_count` is measured after both filters and + # before the page limit so the envelope can describe the same page. + page_rows = [ + row + for row in rows + if (not agent_scope_requested or row["goal_id"] in scoped_goal_ids) + and (not wanted or row["lifecycle_phase"] in wanted) + ] + page_gaps = [ + gap + for gap in gaps + if not agent_scope_requested or gap["goal_id"] in scoped_goal_ids + ] + returned_rows = page_rows[:bounded_limit] + board = { + "schema_version": GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION, + "summary": { + "goals_inspected": len(rows) + len(gaps) + unidentified, + "goals_with_projection": len(rows), + "goals_without_projection": len(gaps), + "goals_without_identity": unidentified, + "agent_scope_goal_count": ( + len(scoped_goal_ids) + if agent_scope_requested + else len(rows) + len(gaps) + ), + "filtered_goal_count": len(page_rows), + "returned_goal_count": len(returned_rows), + "blocked_goal_count": sum(1 for row in rows if row["guards_open_count"]), + "phase_counts": dict(phase_counts), + "truncated": len(page_rows) > len(returned_rows), + "phase_filter": sorted(wanted) if wanted else [], + "agent_filter": list(requested_agents), + # A blank or malformed Agent value still arms the scope; without + # this flag an empty page would be indistinguishable from an + # unfiltered read that happened to match nothing. + "agent_scope_requested": agent_scope_requested, + }, + "phases": phases_summary, + "guards": guards_summary, + "milestones": milestones_summary, + "goals": returned_rows, + "gaps": page_gaps, + "complete": not gaps and not unidentified, + } + try: + validate_public_safe_value(board) + except ValueError: + # Fail closed: a board that cannot prove its own boundary is not + # published as a partial board, because the omitted Goal would read as + # "no lifecycle evidence" instead of "this read is unavailable". + raise ValueError("lifecycle board violates the public-safe boundary") from None + return board + + +__all__ = [ + "GAP_PROJECTION_NOT_DERIVED", + "GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION", + "GLOBAL_GOAL_LIFECYCLE_GAP_SCHEMA_VERSION", + "PHASE_ORDER", + "build_global_goal_lifecycle_board", +] diff --git a/loopx/help_surface.py b/loopx/help_surface.py index 99a336d72e..87a5246c94 100644 --- a/loopx/help_surface.py +++ b/loopx/help_surface.py @@ -383,6 +383,7 @@ def register_command_reference(subparsers: argparse._SubParsersAction[argparse.A "demo", "dreaming", "global-gates", + "global-lifecycle", "global-risks", "global-summary", "global-todos", diff --git a/tests/test_cli_entrypoint.py b/tests/test_cli_entrypoint.py index 0e83ba6b0f..2299fb704f 100644 --- a/tests/test_cli_entrypoint.py +++ b/tests/test_cli_entrypoint.py @@ -526,6 +526,7 @@ def test_command_reference_does_not_require_default_runtime_route( (["global-gates", "--help"], "loopx.cli_commands.summary_all_registration", "loopx.cli_commands.summary_all"), (["global-todos", "--help"], "loopx.cli_commands.summary_all_registration", "loopx.cli_commands.summary_all"), (["global-risks", "--help"], "loopx.cli_commands.summary_all_registration", "loopx.cli_commands.summary_all"), + (["global-lifecycle", "--help"], "loopx.cli_commands.summary_all_registration", "loopx.cli_commands.summary_all"), (["turn", "--help"], "loopx.cli_commands.turn_registration", "loopx.cli_commands.turn"), (["turn", "run-once", "--help"], "loopx.cli_commands.turn_registration", "loopx.cli_commands.turn"), *[( [command, "--help"], "loopx.cli_commands.project_lifecycle", "loopx.cli_commands.project_lifecycle") @@ -990,7 +991,10 @@ def test_selected_parser_matches_full_help_and_diagnostics() -> None: ["quota", "unknown-command"], ["--format", "unknown", "status"], ] - for command in ("goal-portfolio", "global-summary", "global-gates", "global-todos", "global-risks"): + for command in ( + "goal-portfolio", "global-summary", "global-gates", "global-todos", + "global-risks", "global-lifecycle", + ): argv_cases.extend([[command, "--help"], [command, "--unknown-option"], [command, "--limit", "invalid"]]) argv_cases.append(["goal-portfolio", "--manager-view", "unknown"]) for command in ("agent-context", "agent-directory", "agent-capabilities"): @@ -2035,6 +2039,7 @@ def test_console_native_scheduler_followup_fails_closed_without_node( @pytest.mark.parametrize("command", [ "goal-portfolio", "global-summary", "global-gates", "global-todos", "global-risks", + "global-lifecycle", ]) def test_global_read_preserves_empty_coverage_without_loading_full_cli(tmp_path, command): registry, runtime = tmp_path / "registry.json", tmp_path / "runtime" diff --git a/tests/test_global_lifecycle.py b/tests/test_global_lifecycle.py new file mode 100644 index 0000000000..1bebc1985d --- /dev/null +++ b/tests/test_global_lifecycle.py @@ -0,0 +1,861 @@ +from __future__ import annotations + +import json +from copy import deepcopy +from pathlib import Path +from typing import Any + +import pytest + +import loopx.cli_commands.summary_all as manager_cli +import loopx.cli_commands.global_lifecycle as global_lifecycle +from loopx.cli import build_parser +from loopx.control_plane.goals.lifecycle_board import ( + GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION, + build_global_goal_lifecycle_board, +) + +FROZEN_TIME = "2026-11-27T09:00:00Z" +PROJECTION = "goal_artifact_lifecycle_projection_v0" + + +def projection( + goal_id: str, + *, + phase: str = "qualifying", + milestones: list[dict[str, Any]] | None = None, + guards: list[dict[str, Any]] | None = None, + transitions: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + return { + "schema_version": PROJECTION, + "goal_id": goal_id, + "lifecycle_phase": phase, + "milestones": milestones + if milestones is not None + else [ + { + "id": "outcome_progress", + "label": "Progress", + "reached": True, + "reached_evidence_refs": ["run-1"], + "source": "evidence", + } + ], + "guards": guards if guards is not None else [], + "next_transitions": transitions + if transitions is not None + else [ + { + "target_phase": "qualifying", + "precondition": "reach the unreached acceptance milestones with evidence", + "reason_codes": ["milestone_unreached"], + } + ], + } + + +def status_payload(*goals: dict[str, Any], ok: bool = True) -> dict[str, Any]: + return { + "ok": ok, + "run_history": {"goals": list(goals)}, + # A whole global estate: the local registry is also the global one. + "global_registry": { + "available": True, + "global_goal_count": len(goals), + "current_registry_excluded_goal_count": 0, + "current_registry_excluded_goal_ids": [], + }, + "projection_envelope": { + "schema_version": "loopx_projection_envelope_v0", + "sources": [ + { + "source_id": "registry", + "read_status": "read", + "last_read_at": "2026-11-27T08:59:00Z", + "required": True, + } + ], + }, + } + + +def patch_status(monkeypatch: pytest.MonkeyPatch, payload: object) -> list[dict[str, Any]]: + calls: list[dict[str, Any]] = [] + + def collect_status(**kwargs: Any) -> object: + calls.append(kwargs) + return deepcopy(payload) + + monkeypatch.setattr(global_lifecycle, "collect_status", collect_status) + monkeypatch.setattr(global_lifecycle, "now_utc_iso", lambda: FROZEN_TIME) + return calls + + +def build(tmp_path: Path, **kwargs: Any) -> dict[str, Any]: + return global_lifecycle.build_global_lifecycle( + registry_path=tmp_path / "registry.json", + runtime_root_override=None, + limit=kwargs.pop("limit", 8), + **kwargs, + ) + + +def test_aggregates_phases_guards_and_milestones_across_goals( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + blocking = [ + { + "id": "todo-1", + "kind": "owner_decision", + "blocked": True, + "owner": "user", + } + ] + status = status_payload( + { + "id": "goal-a", + "artifact_lifecycle": projection( + "goal-a", + phase="waiting_owner", + guards=blocking, + transitions=[ + { + "target_phase": "waiting_owner", + "precondition": "resolve the open owner decision", + "reason_codes": ["guard_open"], + } + ], + ), + }, + { + "id": "goal-b", + "artifact_lifecycle": projection( + "goal-b", + phase="closed", + milestones=[ + { + "id": "primary_goal_outcome", + "label": "Outcome", + "reached": True, + "reached_evidence_refs": [], + "source": "evidence", + } + ], + transitions=[], + ), + }, + { + "id": "goal-c", + "artifact_lifecycle": projection( + "goal-c", + phase="waiting_owner", + guards=[ + { + "id": "gap-evidence", + "kind": "evidence_precondition", + "blocked": True, + "owner": "agent", + } + ], + ), + }, + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + assert payload["ok"] is True + assert payload["board_schema_version"] == GLOBAL_GOAL_LIFECYCLE_BOARD_SCHEMA_VERSION + summary = payload["summary"] + assert summary["goals_inspected"] == 3 + assert summary["goals_with_projection"] == 3 + assert summary["goals_without_projection"] == 0 + assert summary["blocked_goal_count"] == 2 + assert summary["phase_counts"] == {"waiting_owner": 2, "closed": 1} + assert payload["complete"] is True + # Blocked Goals lead the display so the operator sees the work first. + assert [row["goal_id"] for row in payload["goals"]] == ["goal-a", "goal-c", "goal-b"] + assert payload["phases"][0] == { + "lifecycle_phase": "waiting_owner", + "goal_count": 2, + "goal_ids": ["goal-a", "goal-c"], + } + assert payload["guards"] == [ + { + "kind": "evidence_precondition", + "owner": "agent", + "blocked_goal_count": 1, + "blocked_goal_ids": ["goal-c"], + }, + { + "kind": "owner_decision", + "owner": "user", + "blocked_goal_count": 1, + "blocked_goal_ids": ["goal-a"], + }, + ] + assert [row["milestone_id"] for row in payload["milestones"]] == [ + "outcome_progress", + "primary_goal_outcome", + ] + assert payload["goals"][2]["next_transition"] is None + assert payload["projection_envelope"]["coverage"]["shown_count"] == 3 + markdown = global_lifecycle.render_global_lifecycle_markdown(payload) + assert "phase=`waiting_owner`" in markdown + assert "blocked_by owner_decision(user):todo-1" in markdown + + +def test_goals_without_a_projection_are_typed_gaps_not_silent_omissions( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-derived", "artifact_lifecycle": projection("goal-derived")}, + {"id": "goal-legacy"}, + { + "id": "goal-foreign", + "artifact_lifecycle": {"schema_version": "some_other_v1", "milestones": []}, + }, + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + assert payload["summary"]["goals_inspected"] == 3 + assert payload["summary"]["goals_with_projection"] == 1 + assert payload["summary"]["goals_without_projection"] == 2 + assert payload["complete"] is False + assert payload["gaps"] == [ + { + "schema_version": "global_goal_lifecycle_gap_v0", + "goal_id": "goal-legacy", + "projection_status": "unavailable", + "reason": "projection_not_derived", + }, + { + "schema_version": "global_goal_lifecycle_gap_v0", + "goal_id": "goal-foreign", + "projection_status": "unavailable", + "reason": "projection_not_derived", + }, + ] + envelope = payload["projection_envelope"] + assert { + "reason": "projection_not_derived", + "count": 2, + "refs": [], + } in envelope["coverage"]["omitted"] + + +def test_limit_bounds_returned_rows_but_rollups_cover_every_goal( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + *[ + { + "id": f"goal-{index}", + "artifact_lifecycle": projection( + f"goal-{index}", + phase="waiting_owner", + guards=[ + { + "id": f"guard-{index}", + "kind": "owner_decision", + "blocked": True, + "owner": "user", + } + ], + ), + } + for index in range(5) + ] + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path, limit=2) + + assert len(payload["goals"]) == 2 + assert payload["summary"]["returned_goal_count"] == 2 + assert payload["summary"]["truncated"] is True + assert payload["summary"]["goals_with_projection"] == 5 + assert payload["guards"][0]["blocked_goal_count"] == 5 + assert payload["projection_envelope"]["coverage"]["available_count"] == 5 + + +def test_phase_filter_narrows_rows_without_hiding_the_rollup( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-wait", "artifact_lifecycle": projection("goal-wait", phase="waiting_owner")}, + {"id": "goal-closed", "artifact_lifecycle": projection("goal-closed", phase="closed")}, + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path, phases=["closed"]) + + assert [row["goal_id"] for row in payload["goals"]] == ["goal-closed"] + assert payload["summary"]["phase_filter"] == ["closed"] + assert payload["summary"]["phase_counts"] == {"waiting_owner": 1, "closed": 1} + assert payload["request"]["phase_filter"] == ["closed"] + + +def test_unknown_phase_filter_fails_without_collecting_status( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + calls = patch_status(monkeypatch, status_payload()) + + payload = build(tmp_path, phases=["nonsense"]) + + assert payload["ok"] is False + assert payload["error_code"] == "unsupported_phase_filter" + assert calls == [] + + +def test_status_failure_returns_public_safe_error_payload( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status(monkeypatch, status_payload(ok=False)) + + payload = build(tmp_path) + + assert payload["ok"] is False + assert payload["error_code"] == "status_collection_unavailable" + assert payload["boundary"]["raw_logs_recorded"] is False + assert "projection_envelope" in payload + assert json.dumps(payload, ensure_ascii=False) + + +def test_status_collection_exception_is_reported_without_leaking_paths( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + def collect_status(**_kwargs: Any) -> object: + raise RuntimeError(f"cannot read {tmp_path}/private/goal.json") + + monkeypatch.setattr(global_lifecycle, "collect_status", collect_status) + monkeypatch.setattr(global_lifecycle, "now_utc_iso", lambda: FROZEN_TIME) + + payload = build(tmp_path) + + assert payload["ok"] is False + assert str(tmp_path) not in json.dumps(payload) + assert "" in payload["error"] + + +def test_board_rejects_a_projection_that_breaks_the_public_boundary() -> None: + status = status_payload( + { + "id": "goal-leak", + "artifact_lifecycle": { + **projection("goal-leak"), + "guards": [ + { + "id": "/Users/someone/private/notes.md", + "kind": "owner_decision", + "blocked": True, + "owner": "user", + } + ], + }, + } + ) + + board = build_global_goal_lifecycle_board(status) + + # A rejected label is bounded to a stable placeholder, never republished. + assert board["goals"][0]["guards_open"][0]["id"] == "unnamed_guard" + + +def test_cli_registers_global_lifecycle_and_handles_json( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + parser = build_parser() + args = parser.parse_args( + [ + "--registry", + str(tmp_path / "registry.json"), + "--format", + "json", + "global-lifecycle", + "--limit", + "3", + ] + ) + assert args.command == "global-lifecycle" + assert args.limit == 3 + patch_status( + monkeypatch, + status_payload({"id": "goal-a", "artifact_lifecycle": projection("goal-a")}), + ) + + def print_payload(payload: dict[str, Any], fmt: str, renderer: Any) -> None: + print(json.dumps({"format": fmt, "ok": payload.get("ok")})) + + code = manager_cli.handle_summary_all_command( + args, + registry_path=tmp_path / "registry.json", + runtime_root_arg=None, + output_format=lambda _args: "json", + print_payload=print_payload, + ) + + assert code == 0 + assert json.loads(capsys.readouterr().out) == {"format": "json", "ok": True} + + +def test_goal_without_a_publishable_identity_is_counted_not_dropped( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-known", "artifact_lifecycle": projection("goal-known")}, + {"artifact_lifecycle": projection("goal-nameless")}, + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + summary = payload["summary"] + assert summary["goals_inspected"] == 2 + assert summary["goals_with_projection"] == 1 + assert summary["goals_without_identity"] == 1 + # An unnamed Goal still makes the answer partial. + assert payload["complete"] is False + assert { + "reason": "goal_identity_unavailable", + "count": 1, + "refs": [], + } in payload["projection_envelope"]["coverage"]["omitted"] + assert [row["goal_id"] for row in payload["goals"]] == ["goal-known"] + + +def test_rollups_count_a_goal_once_per_guard_and_milestone( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + guard = { + "id": "gate-1", + "kind": "owner_decision", + "blocked": True, + "owner": "user", + } + status = status_payload( + { + "id": "goal-a", + "artifact_lifecycle": projection("goal-a", guards=[guard, {**guard, "id": "gate-2"}]), + } + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + # Two guards of one kind/owner block one Goal once, not twice. + assert payload["guards"] == [ + { + "kind": "owner_decision", + "owner": "user", + "blocked_goal_count": 1, + "blocked_goal_ids": ["goal-a"], + } + ] + assert payload["summary"]["blocked_goal_count"] == 1 + assert payload["milestones"][0]["reached_goal_count"] == 1 + assert payload["milestones"][0]["reached_goal_ids"] == ["goal-a"] + + +def test_rollup_rows_are_deterministic_across_goal_order( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + goals = [ + { + "id": goal_id, + "artifact_lifecycle": projection( + goal_id, + guards=[ + { + "id": f"gate-{goal_id}", + "kind": "owner_decision", + "blocked": True, + "owner": "user", + } + ], + ), + } + for goal_id in ("goal-c", "goal-a", "goal-b") + ] + patch_status(monkeypatch, status_payload(*goals)) + + payload = build(tmp_path) + + assert payload["guards"][0]["blocked_goal_ids"] == ["goal-a", "goal-b", "goal-c"] + assert payload["phases"][0]["goal_ids"] == ["goal-a", "goal-b", "goal-c"] + + +def test_agent_id_narrows_the_single_status_read( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + calls = patch_status( + monkeypatch, + status_payload({"id": "goal-a", "artifact_lifecycle": projection("goal-a")}), + ) + + payload = build(tmp_path, agent_id="agent-7") + + assert payload["ok"] is True + assert len(calls) == 1 + assert calls[0]["agent_lane_id"] == "agent-7" + assert payload["request"]["limit"] == 8 + + +def test_phase_a_future_producer_adds_still_appears_in_the_rollup( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-future", "artifact_lifecycle": projection("goal-future", phase="archived")}, + {"id": "goal-now", "artifact_lifecycle": projection("goal-now", phase="closed")}, + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + # A phase a future producer adds keeps its own row after the known phases, + # so the rollup still sums to every projected Goal instead of hiding it. + phases = [row["lifecycle_phase"] for row in payload["phases"]] + assert phases == ["closed", "archived"] + assert sum(row["goal_count"] for row in payload["phases"]) == 2 + assert payload["summary"]["phase_counts"] == {"archived": 1, "closed": 1} + + +def test_markdown_render_covers_an_unavailable_read_and_an_empty_board( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status(monkeypatch, status_payload(ok=False)) + failed = build(tmp_path) + unavailable = global_lifecycle.render_global_lifecycle_markdown(failed) + assert unavailable.startswith("# LoopX Global Lifecycle Unavailable") + assert "status_collection_unavailable" in unavailable + + patch_status(monkeypatch, status_payload()) + empty = build(tmp_path) + markdown = global_lifecycle.render_global_lifecycle_markdown(empty) + assert "# LoopX Global Lifecycle" in markdown + assert "- No Goal carries a derived lifecycle projection." in markdown + # Empty rollup sections stay explicit instead of disappearing. + assert markdown.count("- None.") == 3 + + +def test_global_membership_sets_the_denominator_and_names_exclusions( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")}, + {"id": "goal-b", "artifact_lifecycle": projection("goal-b")}, + {"id": "goal-c", "artifact_lifecycle": projection("goal-c")}, + ) + status["global_registry"] = { + **status["global_registry"], + "global_goal_count": 5, + "current_registry_excluded_goal_count": 2, + "current_registry_excluded_goal_ids": ["goal-x", "goal-y"], + } + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + coverage = payload["projection_envelope"]["coverage"] + # Global scope is denominated by global membership, never by the local + # registry this process happened to read. + assert coverage["expected_count"] == 5 + assert coverage["included_count"] == 3 + assert coverage["complete"] is False + assert { + "reason": "outside_current_registry", + "count": 2, + "refs": ["goal-x", "goal-y"], + } in coverage["omitted"] + assert payload["projection_envelope"]["complete"] is False + + +def test_unknown_global_membership_never_certifies_the_board( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")} + ) + status["global_registry"] = {"available": False, "read_status": "missing"} + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + envelope = payload["projection_envelope"] + # The board is whole for the Goals status returned, but a global board + # cannot certify an estate whose membership it never read. + assert payload["complete"] is False + assert envelope["coverage"]["expected_count"] is None + assert envelope["coverage"]["included_count"] == 0 + assert envelope["complete"] is False + assert "missing_required_sources" in envelope["alert_reasons"] + # The status read happened and is reported as such; only the membership + # denominator is unknown, which is what keeps the envelope incomplete. + own = [row for row in envelope["sources"] if "via" not in row] + assert [(row["source_id"], row["read_status"]) for row in own] == [ + ("global_registry", "missing"), + ("status", "read"), + ] + + +def test_a_bounded_status_read_reports_the_goals_it_never_scanned( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")} + ) + status["global_registry"] = {**status["global_registry"], "global_goal_count": 4} + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + coverage = payload["projection_envelope"]["coverage"] + # One status read is bounded: three in-scope Goals were never inspected, so + # the answer cannot describe itself as a whole estate. + assert coverage["expected_count"] == 4 + assert coverage["included_count"] == 1 + assert {"reason": "goal_scan_omitted", "count": 3, "refs": []} in coverage["omitted"] + assert coverage["complete"] is False + assert payload["projection_envelope"]["alert"] is True + + +def test_a_milestone_whose_id_cannot_be_published_is_not_counted_as_reached( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + { + "id": "goal-a", + "artifact_lifecycle": projection( + "goal-a", + milestones=[ + { + "id": "/Users/someone/private/notes.md", + "label": "Progress", + "reached": True, + "reached_evidence_refs": ["run-1"], + "source": "evidence", + }, + { + "id": "outcome_progress", + "label": "Progress", + "reached": True, + "reached_evidence_refs": ["run-2"], + "source": "evidence", + }, + ], + ), + } + ) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + row = payload["goals"][0] + # The row states what it publishes: one reached milestone id, not two. + assert row["milestones_reached"] == ["outcome_progress"] + assert row["milestones_reached_count"] == 1 + assert row["milestones_total_count"] == 2 + assert payload["milestones"] == [ + { + "milestone_id": "outcome_progress", + "reached_goal_count": 1, + "reached_goal_ids": ["goal-a"], + } + ] + + +def _agent_goal(goal_id: str, *, phase: str = "qualifying", agents: list[str]) -> dict[str, Any]: + return { + "id": goal_id, + "artifact_lifecycle": projection(goal_id, phase=phase), + "coordination": {"agent_model": "peer_v1", "registered_agents": agents}, + } + + +def test_agent_filter_lists_only_goals_that_register_the_agent( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status( + monkeypatch, + status_payload( + _agent_goal("goal-a", phase="waiting_owner", agents=["agent-one"]), + _agent_goal("goal-b", agents=["agent-one", "agent-two"]), + _agent_goal("goal-c", phase="closed", agents=["agent-two"]), + ), + ) + + scoped = build(tmp_path, agent_id="agent-one") + + assert [row["goal_id"] for row in scoped["goals"]] == ["goal-a", "goal-b"] + assert scoped["request"]["agent_filter"] == ["agent-one"] + assert scoped["summary"]["agent_filter"] == ["agent-one"] + assert scoped["summary"]["filtered_goal_count"] == 2 + assert scoped["summary"]["agent_scope_goal_count"] == 2 + assert scoped["summary"]["truncated"] is False + # Only the page narrows: the estate rollups still describe every Goal the + # single status read inspected. + assert scoped["summary"]["goals_inspected"] == 3 + assert scoped["summary"]["phase_counts"] == { + "waiting_owner": 1, + "qualifying": 1, + "closed": 1, + } + assert scoped["projection_envelope"]["coverage"]["available_count"] == 2 + assert scoped["projection_envelope"]["coverage"]["shown_count"] == 2 + assert scoped["projection_envelope"]["coverage"]["truncated"] is False + + unknown = build(tmp_path, agent_id="ghost-agent") + + assert unknown["ok"] is True + assert unknown["goals"] == [] + assert unknown["request"]["agent_filter"] == ["ghost-agent"] + assert unknown["summary"]["filtered_goal_count"] == 0 + assert unknown["summary"]["agent_scope_goal_count"] == 0 + assert unknown["summary"]["truncated"] is False + # An unknown identity matches nothing; it never widens back to the estate. + assert unknown["projection_envelope"]["coverage"]["shown_count"] == 0 + assert unknown["projection_envelope"]["coverage"]["available_count"] == 0 + assert unknown["projection_envelope"]["coverage"]["truncated"] is False + + +def test_agent_and_phase_filters_page_together( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status( + monkeypatch, + status_payload( + _agent_goal("goal-a", agents=["agent-one"]), + _agent_goal("goal-b", phase="closed", agents=["agent-one"]), + _agent_goal("goal-c", phase="closed", agents=["agent-one"]), + _agent_goal("goal-d", phase="closed", agents=["agent-two"]), + ), + ) + + payload = build(tmp_path, agent_id="agent-one", phases=["closed"], limit=1) + + assert [row["goal_id"] for row in payload["goals"]] == ["goal-b"] + assert payload["summary"]["filtered_goal_count"] == 2 + assert payload["summary"]["returned_goal_count"] == 1 + assert payload["summary"]["truncated"] is True + assert payload["request"]["agent_filter"] == ["agent-one"] + assert payload["request"]["phase_filter"] == ["closed"] + coverage = payload["projection_envelope"]["coverage"] + assert coverage["shown_count"] == 1 + assert coverage["available_count"] == 2 + assert coverage["truncated"] is True + # Coverage still describes the global estate read, not the filtered page. + assert payload["summary"]["goals_inspected"] == 4 + assert payload["summary"]["phase_counts"] == {"qualifying": 1, "closed": 3} + + +def test_phase_filter_with_no_match_is_an_empty_page_not_a_truncated_one( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status( + monkeypatch, + status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")}, + {"id": "goal-b", "artifact_lifecycle": projection("goal-b", phase="waiting_owner")}, + {"id": "goal-c", "artifact_lifecycle": projection("goal-c")}, + ), + ) + + payload = build(tmp_path, phases=["closed"]) + + assert payload["goals"] == [] + assert payload["summary"]["filtered_goal_count"] == 0 + assert payload["summary"]["truncated"] is False + coverage = payload["projection_envelope"]["coverage"] + assert coverage["shown_count"] == 0 + # A page limit can only page through matching rows: zero matches cannot + # claim three Goals are waiting behind the limit. + assert coverage["available_count"] == 0 + assert coverage["truncated"] is False + assert coverage["expected_count"] == 3 + + +def test_an_unusable_agent_identity_selects_nothing( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status( + monkeypatch, + status_payload( + _agent_goal("goal-a", agents=["agent-one"]), + _agent_goal("goal-b", agents=["agent-two"]), + ), + ) + + payload = build(tmp_path, agent_id="not a usable/identity") + + # An identity the roster shape rejects cannot match anything; it must not + # fall back to an unfiltered estate. + assert payload["goals"] == [] + assert payload["summary"]["agent_scope_goal_count"] == 0 + assert payload["summary"]["filtered_goal_count"] == 0 + assert payload["request"]["agent_filter"] == ["not a usable/identity"] + assert payload["projection_envelope"]["coverage"]["available_count"] == 0 + + +def test_an_explicitly_blank_agent_arms_the_scope_instead_of_widening_it( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + patch_status( + monkeypatch, + status_payload( + _agent_goal("goal-a", agents=["agent-one"]), + _agent_goal("goal-b", agents=["agent-two"]), + ), + ) + + for blank in ("", " "): + payload = build(tmp_path, agent_id=blank) + + # The caller passed the flag, so the filter is armed: a value that + # normalizes to nothing matches no roster. + assert payload["goals"] == [], (blank, payload) + assert payload["request"]["agent_filter"] == [""], (blank, payload) + assert payload["summary"]["agent_scope_requested"] is True, (blank, payload) + assert payload["summary"]["filtered_goal_count"] == 0, (blank, payload) + assert payload["summary"]["agent_scope_goal_count"] == 0, (blank, payload) + coverage = payload["projection_envelope"]["coverage"] + assert coverage["shown_count"] == 0, (blank, coverage) + assert coverage["available_count"] == 0, (blank, coverage) + assert coverage["truncated"] is False, (blank, coverage) + + +def test_long_goal_ids_sharing_a_display_prefix_keep_their_identity( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + shared = "goal-" + "x" * 140 + registered = shared + "-registered" + other = shared + "-other" + patch_status( + monkeypatch, + status_payload( + _agent_goal(registered, agents=["agent-one"]), + _agent_goal(other, agents=["agent-two"]), + ), + ) + + payload = build(tmp_path, agent_id="agent-one") + + # Both ids collapse to the same display prefix, so matching on the shortened + # label would leak the other Goal into the Agent's page. + assert [row["goal_id"] for row in payload["goals"]] == [registered] + assert payload["summary"]["agent_scope_goal_count"] == 1 + assert payload["summary"]["filtered_goal_count"] == 1 + coverage = payload["projection_envelope"]["coverage"] + assert coverage["shown_count"] == 1 + assert coverage["available_count"] == 1 + + unfiltered = build(tmp_path) + + # Identity stays distinct everywhere a consumer joins on it. + assert [row["goal_id"] for row in unfiltered["goals"]] == sorted( + [registered, other] + ) + ids = [goal_id for phase in unfiltered["phases"] for goal_id in phase["goal_ids"]] + assert sorted(ids) == sorted([registered, other]) diff --git a/tests/test_projection_envelope.py b/tests/test_projection_envelope.py index f9214fc56a..5ef977e151 100644 --- a/tests/test_projection_envelope.py +++ b/tests/test_projection_envelope.py @@ -1123,6 +1123,7 @@ def cli(command, registry_path=registry): "global-gates", "global-todos", "global-risks", + "global-lifecycle", ): envelope = cli(command)["projection_envelope"] assert envelope["coverage"]["expected_count"] is None @@ -1138,6 +1139,7 @@ def cli(command, registry_path=registry): "global-gates", "global-todos", "global-risks", + "global-lifecycle", ): local = cli(command)["projection_envelope"] assert (local["coverage"]["included_count"], local["coverage"]["expected_count"]) == (1, 2) diff --git a/tests/test_public_check_disclosure.py b/tests/test_public_check_disclosure.py index c3b6879091..2b0346b567 100644 --- a/tests/test_public_check_disclosure.py +++ b/tests/test_public_check_disclosure.py @@ -108,6 +108,7 @@ def test_invalid_utf8_is_unexamined_and_never_clean(tmp_path): ["turn", "run-once", "--goal-id", "fixture", "--agent-id", "fixture", "--project", "."], ["ready-score"], ["agent-directory", "--goal-id", "fixture"], ["global-summary"], ["global-gates"], ["global-todos"], ["global-risks"], + ["global-lifecycle"], ]) @pytest.mark.parametrize("option", ["--scan-root", "--scan-path"]) def test_operational_commands_reject_retired_scan_options(command, option): From be88454b728cd9d2424d6774c066dac4c43d3844 Mon Sep 17 00:00:00 2001 From: ChengLong GU <88359731+gcl-coder@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:30:02 +0800 Subject: [PATCH 2/3] fix(global): bind the lifecycle board to current global membership Retained run history for a Goal that already left the global registry no longer appears in the board rows, phase rollups or coverage. The registry health payload now publishes the complete membership so aggregation can filter on the same set, and an identity-less Goal still counts as an identity gap instead of disappearing. Refs #4128. Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com> --- loopx/cli_commands/global_lifecycle.py | 17 ++++ .../goals/global_registry_health.py | 4 + loopx/control_plane/goals/lifecycle_board.py | 20 +++++ tests/test_global_lifecycle.py | 84 ++++++++++++++++++- tests/test_projection_envelope.py | 79 +++++++++++++++++ 5 files changed, 203 insertions(+), 1 deletion(-) diff --git a/loopx/cli_commands/global_lifecycle.py b/loopx/cli_commands/global_lifecycle.py index c401218f3e..ca59bbd5b2 100644 --- a/loopx/cli_commands/global_lifecycle.py +++ b/loopx/cli_commands/global_lifecycle.py @@ -65,6 +65,22 @@ def _request( } +def _global_member_ids(status_payload: dict[str, Any]) -> set[str] | None: + """The complete current global membership, when the status owner published it. + + A `None` answer means the payload cannot bind rows to membership, and the + board must stay uncertified rather than describe an unknown estate as whole. + """ + + global_registry = as_dict(status_payload.get("global_registry")) + if global_registry.get("available") is not True: + return None + ids = global_registry.get("global_goal_ids") + if not isinstance(ids, list): + return None + return {item for item in ids if isinstance(item, str) and item} + + def _scope_counts( status_payload: dict[str, Any], summary: dict[str, Any] ) -> dict[str, int | None]: @@ -323,6 +339,7 @@ def build_global_lifecycle( limit=max(1, limit), phases=wanted, agent_id=requested_agent, + member_goal_ids=_global_member_ids(status_payload), ) except ValueError as exc: return build_global_lifecycle_error( diff --git a/loopx/control_plane/goals/global_registry_health.py b/loopx/control_plane/goals/global_registry_health.py index f2e3e1ebc2..3271fe0571 100644 --- a/loopx/control_plane/goals/global_registry_health.py +++ b/loopx/control_plane/goals/global_registry_health.py @@ -301,6 +301,10 @@ def collect_global_registry_health( "current_registry": str(registry_path), "current_registry_is_global": current_is_global, "global_goal_count": len(global_goals), + # The complete registered membership, so a consumer can bind its rows to + # the current global estate instead of trusting whatever history its + # status read retained for Goals that already left the registry. + "global_goal_ids": sorted(global_id_set), "current_goal_count": len(current_goals), "current_registry_excluded_goal_count": 0 if current_is_global else len(missing_from_current), "current_registry_excluded_goal_ids": [] if current_is_global else missing_from_current[:8], diff --git a/loopx/control_plane/goals/lifecycle_board.py b/loopx/control_plane/goals/lifecycle_board.py index 5aac4be352..3d8d2161ef 100644 --- a/loopx/control_plane/goals/lifecycle_board.py +++ b/loopx/control_plane/goals/lifecycle_board.py @@ -209,6 +209,7 @@ def build_global_goal_lifecycle_board( limit: int = 50, phases: list[str] | None = None, agent_id: str | None = None, + member_goal_ids: set[str] | None = None, ) -> dict[str, Any]: """Aggregate every derived projection the status payload already carries. @@ -223,12 +224,31 @@ def build_global_goal_lifecycle_board( narrow the page: coverage and the cross-Goal rollups keep describing the whole inspected estate. An unknown agent matches nothing instead of silently widening back to every Goal. + + `member_goal_ids`, when given, is the current global membership this read + was asked to describe. A status payload can retain history for a Goal that + has already left the global registry; such a row is not current work, so it + is dropped before any rollup or coverage count instead of inflating them. """ bounded_limit = max(1, int(limit)) status = _mapping(status_payload) run_history = _mapping(status.get("run_history")) goals = [goal for goal in _list(run_history.get("goals")) if _mapping(goal)] + if member_goal_ids is not None: + # Membership decides the estate; a history row for a Goal no longer + # registered must not appear as an operator's current Goal. Matching + # uses the complete recorded id so a display truncation can never merge + # two members or admit a non-member. + goals = [ + goal + for goal in goals + # A Goal without a publishable identity cannot be matched to a + # member list; it stays visible as an identity gap rather than + # disappearing from the inspected count. + if _identity(goal.get("id")) is None + or str(goal.get("id")) in member_goal_ids + ] rows: list[dict[str, Any]] = [] gaps: list[dict[str, Any]] = [] diff --git a/tests/test_global_lifecycle.py b/tests/test_global_lifecycle.py index 1bebc1985d..981cc05242 100644 --- a/tests/test_global_lifecycle.py +++ b/tests/test_global_lifecycle.py @@ -63,6 +63,7 @@ def status_payload(*goals: dict[str, Any], ok: bool = True) -> dict[str, Any]: "global_registry": { "available": True, "global_goal_count": len(goals), + "global_goal_ids": [str(goal["id"]) for goal in goals if goal.get("id")], "current_registry_excluded_goal_count": 0, "current_registry_excluded_goal_ids": [], }, @@ -552,6 +553,13 @@ def test_global_membership_sets_the_denominator_and_names_exclusions( status["global_registry"] = { **status["global_registry"], "global_goal_count": 5, + "global_goal_ids": [ + "goal-a", + "goal-b", + "goal-c", + "goal-x", + "goal-y", + ], "current_registry_excluded_goal_count": 2, "current_registry_excluded_goal_ids": ["goal-x", "goal-y"], } @@ -573,6 +581,76 @@ def test_global_membership_sets_the_denominator_and_names_exclusions( assert payload["projection_envelope"]["complete"] is False +def test_global_membership_binds_rows_and_rollups_to_registered_goals( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")}, + {"id": "goal-b", "artifact_lifecycle": projection("goal-b")}, + { + "id": "goal-retired", + "artifact_lifecycle": projection("goal-retired", phase="closed"), + }, + ) + # Three records still carry history, but the global registry now holds two: + # the retired Goal already left the estate the operator asked about. + status["global_registry"] = { + **status["global_registry"], + "global_goal_count": 2, + "global_goal_ids": ["goal-a", "goal-b"], + } + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + goal_ids = [row["goal_id"] for row in payload["goals"]] + assert goal_ids == ["goal-a", "goal-b"] + rolled_up = { + row["lifecycle_phase"]: row["goal_ids"] for row in payload["phases"] + } + assert set(rolled_up) == {"qualifying"} + assert rolled_up["qualifying"] == ["goal-a", "goal-b"] + assert payload["summary"]["goals_inspected"] == 2 + assert payload["summary"]["phase_counts"] == {"qualifying": 2} + coverage = payload["projection_envelope"]["coverage"] + assert coverage["expected_count"] == 2 + assert coverage["included_count"] == 2 + assert coverage["shown_count"] == 2 + assert coverage["omitted"] == [] + assert coverage["complete"] is True + assert payload["complete"] is True + + +def test_a_project_registry_with_stale_membership_does_not_reenlist_it( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")}, + {"id": "goal-b", "artifact_lifecycle": projection("goal-b")}, + { + "id": "goal-retired", + "artifact_lifecycle": projection("goal-retired", phase="qualifying"), + }, + ) + # A project registry can still list the retired record while global + # membership no longer does; membership, not the local file, decides scope. + status["global_registry"] = { + **status["global_registry"], + "global_goal_count": 2, + "global_goal_ids": ["goal-a", "goal-b"], + "current_registry_is_global": False, + } + patch_status(monkeypatch, status) + + board = build_global_goal_lifecycle_board( + status, member_goal_ids={"goal-a", "goal-b"} + ) + + assert [row["goal_id"] for row in board["goals"]] == ["goal-a", "goal-b"] + assert board["summary"]["goals_inspected"] == 2 + assert board["complete"] is True + + def test_unknown_global_membership_never_certifies_the_board( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: @@ -607,7 +685,11 @@ def test_a_bounded_status_read_reports_the_goals_it_never_scanned( status = status_payload( {"id": "goal-a", "artifact_lifecycle": projection("goal-a")} ) - status["global_registry"] = {**status["global_registry"], "global_goal_count": 4} + status["global_registry"] = { + **status["global_registry"], + "global_goal_count": 4, + "global_goal_ids": ["goal-a", "goal-b", "goal-c", "goal-d"], + } patch_status(monkeypatch, status) payload = build(tmp_path) diff --git a/tests/test_projection_envelope.py b/tests/test_projection_envelope.py index 5ef977e151..6f0ea67857 100644 --- a/tests/test_projection_envelope.py +++ b/tests/test_projection_envelope.py @@ -1084,6 +1084,85 @@ def test_receipt_case_collection_does_not_depend_on_the_collecting_process_clock assert collections[0] == collections[1], "independent worker clocks changed collection identity" +def test_real_cli_lifecycle_board_drops_a_goal_outside_global_membership(tmp_path): + """History retained for a retired Goal must not appear as current work.""" + import os + import subprocess + import sys + + registry = _registry(tmp_path, ("goal-a",)) + runtime = tmp_path / "runtime" + runtime.mkdir(exist_ok=True) + states = {} + for goal_id in ("goal-a", "goal-b", "goal-retired"): + state = tmp_path / f"{goal_id}_STATE.md" + state.write_text( + "# Goal\n\n## User Todo\n\n## Agent Todo\n\n## Next Action\n\n- Inspect current evidence.\n", + encoding="utf-8", + ) + states[goal_id] = state + if goal_id != "goal-a": + # `_registry` already initialized goal-a's canonical source. + initialize_canonical_source_fixture(runtime, goal_id, state_path=state) + base_goal = json.loads(registry.read_text())["goals"][0] + global_path = runtime / "registry.global.json" + # All three Goals left history in the runtime; only two remain registered. + global_path.write_text( + json.dumps( + { + "common_runtime_root": str(runtime), + "goals": [ + { + **base_goal, + "id": goal_id, + "state_file": str(states[goal_id]), + } + for goal_id in ("goal-a", "goal-b") + ], + } + ) + ) + + def cli(command, registry_path=global_path): + result = subprocess.run( + [ + sys.executable, + "-c", + "from loopx.cli_runtime import main; raise SystemExit(main())", + "--registry", + str(registry_path), + "--format", + "json", + command, + "--limit", + "8", + ], + text=True, + capture_output=True, + timeout=60, + env={**os.environ, "PYTHONPATH": os.pathsep.join(( + str(Path(__file__).resolve().parents[1]), + os.environ.get("PYTHONPATH", ""), + ))}, + ) + assert result.returncode == 0, result.stderr + return json.loads(result.stdout) + + payload = cli("global-lifecycle") + goal_ids = sorted(row["goal_id"] for row in payload["goals"]) + assert goal_ids == ["goal-a", "goal-b"] + rolled_up = sorted( + goal_id for row in payload["phases"] for goal_id in row["goal_ids"] + ) + assert rolled_up == ["goal-a", "goal-b"] + coverage = payload["projection_envelope"]["coverage"] + assert coverage["expected_count"] == 2 + assert coverage["included_count"] == 2 + assert coverage["shown_count"] == 2 + assert payload["complete"] is True + assert payload["projection_envelope"]["complete"] is True + + def test_real_cli_global_membership_failure_and_recovery(tmp_path): """Global scope must never use local membership as its denominator.""" import subprocess From cf1f370dc4837242c9c2ec2ed8aa8f911b28ecce Mon Sep 17 00:00:00 2001 From: ChengLong GU <88359731+gcl-coder@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:52:04 +0800 Subject: [PATCH 3/3] fix(global): require consistent membership evidence before certifying coverage The complete global membership is now collected only for the lifecycle board read, so ordinary status keeps its bounded registry facts. A member list that is missing, malformed or conflicts with the published denominator no longer lets the board claim complete coverage: it records the evidence gap and counts no row as included. Refs #4128. Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com> --- loopx/cli_commands/global_lifecycle.py | 55 +++++++++++++---- .../goals/global_registry_health.py | 8 +-- loopx/control_plane/status/collection.py | 2 + .../status/registry_health_projection.py | 2 + loopx/status.py | 4 ++ tests/test_global_lifecycle.py | 59 +++++++++++++++++++ tests/test_projection_envelope.py | 6 ++ 7 files changed, 120 insertions(+), 16 deletions(-) diff --git a/loopx/cli_commands/global_lifecycle.py b/loopx/cli_commands/global_lifecycle.py index ca59bbd5b2..f8ae7eba08 100644 --- a/loopx/cli_commands/global_lifecycle.py +++ b/loopx/cli_commands/global_lifecycle.py @@ -65,20 +65,36 @@ def _request( } -def _global_member_ids(status_payload: dict[str, Any]) -> set[str] | None: - """The complete current global membership, when the status owner published it. +GAP_MEMBERSHIP_UNAVAILABLE = "global_membership_unavailable" +GAP_MEMBERSHIP_INCONSISTENT = "global_membership_inconsistent" - A `None` answer means the payload cannot bind rows to membership, and the - board must stay uncertified rather than describe an unknown estate as whole. + +def _global_membership( + status_payload: dict[str, Any], +) -> tuple[frozenset[str] | None, str | None]: + """Parse the opt-in membership list the lifecycle collector requested. + + Returns the complete current membership, or a typed evidence gap when the + payload cannot bind rows to it. A list that is absent, malformed or + contradicts the published denominator must never certify a whole estate. """ global_registry = as_dict(status_payload.get("global_registry")) if global_registry.get("available") is not True: - return None + # The envelope already reports the membership source itself as missing. + return None, None ids = global_registry.get("global_goal_ids") - if not isinstance(ids, list): - return None - return {item for item in ids if isinstance(item, str) and item} + if not isinstance(ids, list) or any( + not isinstance(item, str) or not item for item in ids + ): + return None, GAP_MEMBERSHIP_UNAVAILABLE + members = frozenset(ids) + if len(members) != len(ids): + return None, GAP_MEMBERSHIP_INCONSISTENT + count = global_registry.get("global_goal_count") + if isinstance(count, int) and not isinstance(count, bool) and len(members) != count: + return None, GAP_MEMBERSHIP_INCONSISTENT + return members, None def _scope_counts( @@ -140,6 +156,7 @@ def _envelope( ) summary = as_dict(as_dict(board).get("summary")) scope = _scope_counts(status_payload, summary) + members, membership_error = _global_membership(status_payload) shown = summary.get("returned_goal_count") if not isinstance(shown, int) or isinstance(shown, bool): shown = None @@ -181,12 +198,20 @@ def _envelope( omitted.append({"reason": "goal_identity_unavailable", "count": without_identity}) if unscanned: omitted.append({"reason": "goal_scan_omitted", "count": unscanned}) + if membership_error: + # A membership list the board could not bind must be a stated coverage + # gap, never an implicitly complete answer. + omitted.append({"reason": membership_error, "count": 1}) projected = summary.get("goals_with_projection") - # Included means "carried a derived projection in this answer". It can never - # exceed what was inspected or what remains inside the current registry. + # Included means "proved to carry a derived projection in this answer". + # It can never exceed what was inspected, what remains inside the current + # registry, or what verified global membership admits. included = ( min(projected, max(0, expected - excluded)) - if isinstance(projected, int) and expected is not None + if membership_error is None + and members is not None + and isinstance(projected, int) + and expected is not None else 0 ) sealed: dict[str, Any] = seal_projection_envelope( @@ -313,6 +338,9 @@ def build_global_lifecycle( runtime_root_override=runtime_root_override, limit=scan_limit, agent_lane_id=requested_agent, + # The complete membership is internal to this board read; the shared + # default status output keeps its bounded registry facts. + include_global_member_ids=True, ) except Exception as exc: return build_global_lifecycle_error( @@ -333,13 +361,16 @@ def build_global_lifecycle( status_read_at=status_read_at, error_code="status_collection_unavailable", ) + members, membership_error = _global_membership(status_payload) try: board = build_global_goal_lifecycle_board( status_payload, limit=max(1, limit), phases=wanted, agent_id=requested_agent, - member_goal_ids=_global_member_ids(status_payload), + member_goal_ids=( + set(members) if members is not None and membership_error is None else None + ), ) except ValueError as exc: return build_global_lifecycle_error( diff --git a/loopx/control_plane/goals/global_registry_health.py b/loopx/control_plane/goals/global_registry_health.py index 3271fe0571..4e7a1b801b 100644 --- a/loopx/control_plane/goals/global_registry_health.py +++ b/loopx/control_plane/goals/global_registry_health.py @@ -88,6 +88,7 @@ def collect_global_registry_health( registry_path: Path, runtime_root: Path, current_registry: dict[str, Any], + include_member_ids: bool = False, global_registry_path: Callable[[Path], Path], load_registry: Callable[[Path], dict[str, Any]], registry_goals: Callable[[dict[str, Any]], list[dict[str, Any]]], @@ -301,10 +302,9 @@ def collect_global_registry_health( "current_registry": str(registry_path), "current_registry_is_global": current_is_global, "global_goal_count": len(global_goals), - # The complete registered membership, so a consumer can bind its rows to - # the current global estate instead of trusting whatever history its - # status read retained for Goals that already left the registry. - "global_goal_ids": sorted(global_id_set), + # Opt-in only: the cross-Goal lifecycle board binds its rows to this + # complete membership, while ordinary status keeps its bounded output. + **({"global_goal_ids": sorted(global_id_set)} if include_member_ids else {}), "current_goal_count": len(current_goals), "current_registry_excluded_goal_count": 0 if current_is_global else len(missing_from_current), "current_registry_excluded_goal_ids": [] if current_is_global else missing_from_current[:8], diff --git a/loopx/control_plane/status/collection.py b/loopx/control_plane/status/collection.py index 46abee332a..da678955d9 100644 --- a/loopx/control_plane/status/collection.py +++ b/loopx/control_plane/status/collection.py @@ -91,6 +91,7 @@ def collect_status( allow_missing_registry: bool = False, include_presentation_projections: bool = True, tolerate_malformed_settlement_history: bool = False, + include_global_member_ids: bool = False, ) -> dict[str, Any]: """Collect the status read model. @@ -125,6 +126,7 @@ def collect_status( registry_path=registry_path, runtime_root=runtime_root, current_registry=registry, + include_member_ids=include_global_member_ids, ) global_registry_read_at = now_utc_iso() include_runtime_goals = bool(global_registry.get("current_registry_is_global")) diff --git a/loopx/control_plane/status/registry_health_projection.py b/loopx/control_plane/status/registry_health_projection.py index c45068f5a1..6fbf409952 100644 --- a/loopx/control_plane/status/registry_health_projection.py +++ b/loopx/control_plane/status/registry_health_projection.py @@ -61,11 +61,13 @@ def collect_global_registry_health( registry_path: Path, runtime_root: Path, current_registry: dict[str, Any], + include_member_ids: bool = False, ) -> dict[str, Any]: return _collect_global_registry_health( registry_path=registry_path, runtime_root=runtime_root, current_registry=current_registry, + include_member_ids=include_member_ids, global_registry_path=global_registry_path, load_registry=load_registry, registry_goals=registry_goals, diff --git a/loopx/status.py b/loopx/status.py index c942e5edcf..d9f65c67c5 100644 --- a/loopx/status.py +++ b/loopx/status.py @@ -810,6 +810,7 @@ def collect_global_registry_health( registry_path: Path, runtime_root: Path, current_registry: dict[str, object], + include_member_ids: bool = False, ) -> dict[str, object]: from .control_plane.status.registry_health_projection import ( collect_global_registry_health as _collect_global_registry_health, @@ -819,6 +820,7 @@ def collect_global_registry_health( registry_path=registry_path, runtime_root=runtime_root, current_registry=current_registry, + include_member_ids=include_member_ids, ) @@ -1313,6 +1315,7 @@ def collect_status( allow_missing_registry: bool = False, include_presentation_projections: bool = True, tolerate_malformed_settlement_history: bool = False, + include_global_member_ids: bool = False, ) -> dict[str, object]: with effect_runtime_request_scope(): return _collect_status_read_model( @@ -1331,6 +1334,7 @@ def collect_status( activation_state_filter=activation_state_filter, agent_lane_id=agent_lane_id, include_presentation_projections=include_presentation_projections, + include_global_member_ids=include_global_member_ids, context=build_status_collection_context( tolerate_malformed_settlement_history=( tolerate_malformed_settlement_history diff --git a/tests/test_global_lifecycle.py b/tests/test_global_lifecycle.py index 981cc05242..176c9951d6 100644 --- a/tests/test_global_lifecycle.py +++ b/tests/test_global_lifecycle.py @@ -621,6 +621,65 @@ def test_global_membership_binds_rows_and_rollups_to_registered_goals( assert payload["complete"] is True +def test_missing_membership_evidence_never_certifies_coverage( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")}, + {"id": "goal-b", "artifact_lifecycle": projection("goal-b")}, + {"id": "goal-retired", "artifact_lifecycle": projection("goal-retired")}, + ) + status["global_registry"] = { + **status["global_registry"], + "global_goal_count": 2, + } + status["global_registry"].pop("global_goal_ids", None) + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + coverage = payload["projection_envelope"]["coverage"] + # Without the member list the board cannot prove any row belongs to the + # current estate, so it must not report a whole one. + assert coverage["expected_count"] == 2 + assert coverage["included_count"] == 0 + assert any( + row["reason"] == "global_membership_unavailable" and row["count"] == 1 + for row in coverage["omitted"] + ) + assert coverage["complete"] is False + assert payload["projection_envelope"]["complete"] is False + assert payload["complete"] is False + + +def test_membership_list_conflicting_with_the_denominator_never_certifies( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + status = status_payload( + {"id": "goal-a", "artifact_lifecycle": projection("goal-a")}, + {"id": "goal-b", "artifact_lifecycle": projection("goal-b")}, + {"id": "goal-retired", "artifact_lifecycle": projection("goal-retired")}, + ) + status["global_registry"] = { + **status["global_registry"], + "global_goal_count": 2, + "global_goal_ids": ["goal-a", "goal-b", "goal-retired"], + } + patch_status(monkeypatch, status) + + payload = build(tmp_path) + + coverage = payload["projection_envelope"]["coverage"] + assert coverage["expected_count"] == 2 + assert coverage["included_count"] == 0 + assert any( + row["reason"] == "global_membership_inconsistent" and row["count"] == 1 + for row in coverage["omitted"] + ) + assert coverage["complete"] is False + assert payload["complete"] is False + + def test_a_project_registry_with_stale_membership_does_not_reenlist_it( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: diff --git a/tests/test_projection_envelope.py b/tests/test_projection_envelope.py index 6f0ea67857..f94af8c76d 100644 --- a/tests/test_projection_envelope.py +++ b/tests/test_projection_envelope.py @@ -1148,6 +1148,12 @@ def cli(command, registry_path=global_path): assert result.returncode == 0, result.stderr return json.loads(result.stdout) + # Ordinary status keeps its bounded registry facts; only the board asks + # for the complete membership it must bind rows to. + default_status = cli("status") + assert "global_goal_ids" not in default_status["global_registry"] + assert default_status["global_registry"]["current_registry_excluded_goal_ids"] == [] + payload = cli("global-lifecycle") goal_ids = sorted(row["goal_id"] for row in payload["goals"]) assert goal_ids == ["goal-a", "goal-b"]