Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions loopx/capabilities/configuration_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ def capability_configuration_editor(
_field("max_trials", "Maximum proposed trials", "number", minimum=0, maximum=2, required=True),
],
},
"goal_closeout": {
"supported_scopes": ["machine"], "writable_scopes": ["machine"],
"fields": [
_field("timeout_seconds", "Closeout timeout (seconds)", "number",
minimum=1, maximum=600, required=True,
description="Bounds one terminal hook invocation. The command itself is local-private: configure it with the machine-config CLI, never through the Dashboard."),
],
},
"goal_storage": {
"supported_scopes": ["machine"], "writable_scopes": ["machine"],
"fields": [_field("new_goal_provider", "New Goal storage provider", "select",
Expand Down
1 change: 1 addition & 0 deletions loopx/capabilities/goal_closeout/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Terminal Goal closeout hooks owned by the machine configuration."""
146 changes: 146 additions & 0 deletions loopx/capabilities/goal_closeout/machine_defaults.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from ..machine_configuration.contract import MachineConfigurationNamespace

GOAL_CLOSEOUT_CONFIGURATION_SCHEMA = "loopx_goal_closeout_configuration_v0"
DEFAULT_CLOSEOUT_TIMEOUT_SECONDS = 30
MAX_CLOSEOUT_TIMEOUT_SECONDS = 600


def normalize_goal_closeout_configuration(
raw: Mapping[str, Any],
) -> dict[str, Any]:
unknown = sorted(set(raw) - {"schema_version", "command", "timeout_seconds"})
if unknown:
raise ValueError(
"goal_closeout contains unsupported fields: " + ", ".join(unknown)
)
if raw.get("schema_version") != GOAL_CLOSEOUT_CONFIGURATION_SCHEMA:
raise ValueError(
"goal_closeout must use " + GOAL_CLOSEOUT_CONFIGURATION_SCHEMA
)
raw_command = raw.get("command", [])
if not isinstance(raw_command, (list, tuple)):
raise ValueError("goal_closeout command must be an array of strings")
command: list[str] = []
for part in raw_command:
if not isinstance(part, str) or not part.strip():
raise ValueError(
"goal_closeout command entries must be non-empty strings"
)
command.append(part)
raw_timeout = raw.get("timeout_seconds", DEFAULT_CLOSEOUT_TIMEOUT_SECONDS)
if isinstance(raw_timeout, bool) or not isinstance(raw_timeout, int):
raise ValueError("goal_closeout timeout_seconds must be an integer")
if not 1 <= raw_timeout <= MAX_CLOSEOUT_TIMEOUT_SECONDS:
raise ValueError(
"goal_closeout timeout_seconds must be between 1 and "
f"{MAX_CLOSEOUT_TIMEOUT_SECONDS}"
)
return {
"schema_version": GOAL_CLOSEOUT_CONFIGURATION_SCHEMA,
"command": command,
"timeout_seconds": raw_timeout,
}


def _public_goal_closeout_configuration(
value: Mapping[str, Any],
) -> dict[str, Any]:
"""Publish whether a command exists, never the local program or its path."""

normalized = normalize_goal_closeout_configuration(value)
return {
"schema_version": GOAL_CLOSEOUT_CONFIGURATION_SCHEMA,
"configured": bool(normalized["command"]),
"timeout_seconds": normalized["timeout_seconds"],
}


def _apply_goal_closeout_public_update(
current: Mapping[str, Any] | None,
update: Mapping[str, Any],
) -> dict[str, Any]:
"""Let the Dashboard change only the public timeout, not the command."""

base = (
normalize_goal_closeout_configuration(current)
if current is not None
else {
"schema_version": GOAL_CLOSEOUT_CONFIGURATION_SCHEMA,
"command": [],
"timeout_seconds": DEFAULT_CLOSEOUT_TIMEOUT_SECONDS,
}
)
unknown = sorted(set(update) - {"schema_version", "configured", "timeout_seconds"})
if unknown:
raise ValueError(
"goal_closeout public update contains unsupported fields: "
+ ", ".join(unknown)
)
if "schema_version" in update and (
update["schema_version"] != GOAL_CLOSEOUT_CONFIGURATION_SCHEMA
):
raise ValueError(
"goal_closeout must use " + GOAL_CLOSEOUT_CONFIGURATION_SCHEMA
)
if "configured" in update and bool(update["configured"]) != bool(base["command"]):
raise ValueError(
"goal_closeout configured is derived from the locally configured command"
)
merged = dict(base)
if "timeout_seconds" in update:
merged["timeout_seconds"] = update["timeout_seconds"]
return normalize_goal_closeout_configuration(merged)


def _apply_goal_closeout_local_update(
current: Mapping[str, Any] | None,
update: Mapping[str, Any],
) -> dict[str, Any]:
"""Let the local operator CLI write the command the Dashboard cannot."""

base = (
normalize_goal_closeout_configuration(current)
if current is not None
else {
"schema_version": GOAL_CLOSEOUT_CONFIGURATION_SCHEMA,
"command": [],
"timeout_seconds": DEFAULT_CLOSEOUT_TIMEOUT_SECONDS,
}
)
unknown = sorted(set(update) - {"schema_version", "command", "timeout_seconds"})
if unknown:
raise ValueError(
"goal_closeout update contains unsupported fields: " + ", ".join(unknown)
)
return normalize_goal_closeout_configuration({**base, **dict(update)})


def goal_closeout_machine_configuration_namespace() -> MachineConfigurationNamespace:
return MachineConfigurationNamespace(
namespace="goal_closeout",
schema_versions=frozenset({GOAL_CLOSEOUT_CONFIGURATION_SCHEMA}),
normalize=normalize_goal_closeout_configuration,
project_public=_public_goal_closeout_configuration,
apply_public_update=_apply_goal_closeout_public_update,
local_only_fields=frozenset({"command"}),
apply_local_update=_apply_goal_closeout_local_update,
title="Terminal Goal closeout command",
description=(
"Optional machine-wide command run after a Goal reaches a terminal "
"transition (stop, retirement or runtime archive). The command is "
"best effort, receives one bounded JSON payload on stdin, and can "
"never block the LoopX command that triggered it. Keep the command "
"local-private: write it with the machine-config CLI; the Dashboard "
"only sees whether one is configured and may adjust the timeout."
),
default_configuration={
"schema_version": GOAL_CLOSEOUT_CONFIGURATION_SCHEMA,
"command": [],
"timeout_seconds": DEFAULT_CLOSEOUT_TIMEOUT_SECONDS,
},
)
5 changes: 5 additions & 0 deletions loopx/capabilities/machine_configuration/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
"loopx.capabilities.machine_configuration.goal_storage",
"goal_storage_machine_configuration_namespace",
),
(
"goal_closeout",
"loopx.capabilities.goal_closeout.machine_defaults",
"goal_closeout_machine_configuration_namespace",
),
(
"manager_runtime",
"loopx.capabilities.manager_runtime.machine_profile",
Expand Down
6 changes: 6 additions & 0 deletions loopx/capabilities/machine_configuration/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@ def handle_machine_configuration_command(
namespace=args.namespace,
namespace_configuration=configuration,
registry=registry,
# The local operator CLI is the trusted writer for fields
# the loopback Dashboard may only read.
allow_local_only=True,
)
payload = configure_machine_configuration(
runtime_root=runtime_root,
Expand All @@ -290,6 +293,9 @@ def handle_machine_configuration_command(
namespace=args.namespace,
namespace_configuration=configuration,
registry=registry,
# The local operator CLI is the trusted writer for fields
# the loopback Dashboard may only read.
allow_local_only=True,
)
payload = configure_machine_configuration(
runtime_root=runtime_root,
Expand Down
20 changes: 19 additions & 1 deletion loopx/capabilities/machine_configuration/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ class MachineConfigurationNamespace:
description: str | None = None
documentation: Mapping[str, str] | None = None
default_configuration: Mapping[str, Any] | None = None
# Fields only the local operator CLI may write. The loopback Dashboard
# routes merge through this contract too, so without this split a public
# namespace update could persist an arbitrary executable path.
local_only_fields: frozenset[str] = frozenset()
apply_local_update: PublicUpdater | None = None

def __post_init__(self) -> None:
if not _NAMESPACE_RE.fullmatch(self.namespace):
Expand Down Expand Up @@ -197,10 +202,18 @@ def merge_machine_configuration_namespace(
namespace: str,
namespace_configuration: Mapping[str, Any],
registry: MachineConfigurationRegistry,
allow_local_only: bool = False,
) -> dict[str, Any]:
"""Build one whole-document update while preserving sibling namespaces."""

contract = registry.resolve(namespace)
if not allow_local_only:
blocked = sorted(set(namespace_configuration) & contract.local_only_fields)
if blocked:
raise ValueError(
"machine-configuration namespace only accepts these fields from "
f"the local CLI: {', '.join(blocked)}"
)
# Namespace updates are also the recovery path for an installed namespace
# whose previously valid value no longer satisfies the current contract.
# Keep the stored value opaque until the owning namespace has replaced it;
Expand Down Expand Up @@ -228,8 +241,13 @@ def merge_machine_configuration_namespace(
raise TypeError(
f"machine_configuration.namespaces.{namespace} must be an object"
)
updater = (
contract.apply_local_update
if allow_local_only and contract.apply_local_update is not None
else contract.apply_public_update
)
updated_namespace = _mapping(
contract.apply_public_update(current_namespace, namespace_configuration),
updater(current_namespace, namespace_configuration),
f"machine_configuration.namespaces.{namespace}",
)
return normalize_machine_configuration(
Expand Down
50 changes: 50 additions & 0 deletions loopx/control_plane/goals/activation_service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from collections.abc import Mapping
from contextlib import ExitStack, nullcontext
from dataclasses import dataclass
from enum import Enum
Expand Down Expand Up @@ -472,6 +473,7 @@ def set_goal_activation_state(
)
return payload
locked_goal = _goal(source_payload, normalized_goal_id)
closeout_goal = dict(locked_goal)
locked_state = goal_activation_state(locked_goal)
if locked_state is not before_state:
payload.update(
Expand Down Expand Up @@ -544,9 +546,57 @@ def set_goal_activation_state(
(sync_payload or {}).get("recommended_action")
or f"rerun loopx sync-global --goal-id {normalized_goal_id} after repairing the shared registry route"
)
if (
execute
and target_state is GoalActivationState.STOPPED
and changed
and payload.get("ok")
and payload.get("written")
and closeout_goal is not None
):
payload["closeout"] = _stop_closeout_payload(
source_registry=source_registry,
runtime_root_override=runtime_root_override,
goal_id=normalized_goal_id,
closeout_goal=closeout_goal,
)
return payload


def _stop_closeout_payload(
*,
source_registry: Path,
runtime_root_override: str | None,
goal_id: str,
closeout_goal: Mapping[str, Any],
) -> dict[str, Any]:
"""Run the terminal hook after a committed stop transition."""

from ...lifecycle.goal_closeout import run_goal_closeout

closeout_runtime_root = resolve_runtime_root(
load_registry(source_registry),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 保留已提交的停止回执

这个 load_registry 发生在两份注册表都读回 stopped 之后。用相同 fixture 只让这次读失败,基线退出 0,当前 head 退出 1 并报告 written=false,但写入已经完成。空配置也会进入这里。请从已验证的快照取所需参数,并把剩余准备异常记入钩子诊断。回归用例应在真实 goal-lifecycle --operation stop --execute 上同时断言退出码、written 和两份持久状态。

runtime_root_override,
registry_path=source_registry,
)
state_file = closeout_goal.get("state_file")
if not state_file:
state_file = (
source_registry.parent
/ "goals"
/ goal_id
/ "ACTIVE_GOAL_STATE.md"
)
return run_goal_closeout(
runtime_root=closeout_runtime_root,
goal_id=goal_id,
repo=str(closeout_goal.get("repo")) if closeout_goal.get("repo") else None,
state_file=str(state_file),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 使用注册表解析后的绝对状态路径

相对 state_file 是已有的合法注册值。从独立目录执行真实 CLI 时,接收器收到原始相对路径,因不符合 Issue #8918 的载荷约定而失败。停止、退役和归档外部状态文件的分支都复现了。请复用已有注册路径规则,并在归档后按文件是否移动生成目标路径。用等义的相对/绝对注册各跑三条公开入口,核对接收路径和 ledger。

terminal_reason="stopped",
trigger="goal-lifecycle-stop",
)


def render_goal_activation_markdown(payload: dict[str, Any]) -> str:
lines = [
"# Goal Activation",
Expand Down
2 changes: 2 additions & 0 deletions loopx/extensions/process_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ class CappedProcessResult:
returncode: int
stdout: bytes
failure_kind: str | None = None
stderr: bytes = b""


def _wait_for_process(process: subprocess.Popen[bytes] | subprocess.Popen[str], timeout: float) -> bool:
Expand Down Expand Up @@ -713,4 +714,5 @@ def write_stdin() -> None:
returncode=returncode,
stdout=bytes(stdout),
failure_kind="timeout" if timed_out else limit_kind,
stderr=bytes(stderr),
)
37 changes: 37 additions & 0 deletions loopx/global_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,9 @@ def _retire_global_registry_reduction(
"inspections": inspections,
"global_goal_count_before": len(current_goals),
"global_goal_count_after": len(retained_goals),
"retired_goals": [
dict(matches_by_id[goal_id][0]) for goal_id in requested_ids
],
},
backup_label="retire-goal-backup",
)
Expand Down Expand Up @@ -656,6 +659,39 @@ def retire_global_registry_goals(
receipt = mutation["receipt"]
backup_path = mutation["backup_path"]

closeouts: list[dict[str, Any]] = []
if execute:
from .lifecycle.goal_closeout import run_goal_closeout

for retired_goal in receipt.get("retired_goals", []):
goal_id = str(retired_goal.get("id") or "").strip()
if not goal_id:
continue
state_file = retired_goal.get("state_file")
if not state_file:
state_file = runtime_root / "goals" / goal_id / "ACTIVE_GOAL_STATE.md"
goal_runtime_dir = runtime_root / "goals" / goal_id
closeout_ledger_dir = (
goal_runtime_dir
if goal_runtime_dir.is_dir()
else runtime_root / "closeout" / goal_id
)
closeouts.append(
run_goal_closeout(
runtime_root=runtime_root,
goal_id=goal_id,
repo=(
str(retired_goal.get("repo"))
if retired_goal.get("repo")
else None
),
state_file=str(state_file),
terminal_reason="retired",
trigger="retire-global-goal",
ledger_dir=closeout_ledger_dir,
)
)

return {
"ok": True,
"schema_version": "loopx_global_goal_retirement_v0",
Expand All @@ -674,6 +710,7 @@ def retire_global_registry_goals(
"wrote": execute,
"updated_at": updated_at,
"global_registry_writability": writability,
"closeouts": closeouts,
}


Expand Down
Empty file added loopx/lifecycle/__init__.py
Empty file.
Loading
Loading