Skip to content

feat(goal-closeout): invoke terminal hook on stop, retire and archive - #9065

Open
gcl-coder wants to merge 5 commits into
loopx-project:mainfrom
gcl-coder:codex/goal-closeout-hook
Open

gcl-coder wants to merge 5 commits into
loopx-project:mainfrom
gcl-coder:codex/goal-closeout-hook

Conversation

@gcl-coder

@gcl-coder gcl-coder commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #8918.

Goal And Delivered Outcome

  • Outcome basis / optional anchor: Feature request: a terminal-state (closeout) hook so finished goal worktrees can be reclaimed #8918, proposal 1 — a terminal-state command declared in machine configuration.
  • Goal/source and gap: LoopX can stop, retire or archive a Goal, but it had no LoopX-owned seam for running a closeout step at that moment. Operators had to hook each host separately, and LoopX never recorded whether cleanup ran.
  • Observable before → after: Before this change, a configured closeout command was never invoked. After this change, goal-lifecycle stop, retire-global-goal and archive-runtime invoke the configured goal_closeout command after the terminal transition commits. The command receives one bounded JSON payload on stdin, runs with a finite timeout under the shared capped-process runtime (process-tree cleanup, bounded stdout/stderr), and the attempt is appended to a closeout ledger. A command failure, timeout or launch error never changes the triggering command's result.
  • Issue/task and intended base: Closes Feature request: a terminal-state (closeout) hook so finished goal worktrees can be reclaimed #8918. Intended base: main.

Review follow-up (3d784d44a)

Finding Fix
[P0] Three directory/contract tests still expect the old namespace list Updated the pinned lists and the machine-only capability set; real loopback HTTP tests pass.
[P0] Unauthenticated loopback HTTP can persist an arbitrary command command is a local-only field: the namespace merge used by /preview and /apply rejects it, project_public returns only configured and timeout_seconds, and the local machine-config CLI keeps write access. A real HTTP request now returns 400 and writes no file.
[P1] goal_id path traversal Validated with validate_goal_id_path_segment before reading the configuration or writing a ledger; an invalid id returns invalid_goal_id with no disk change.
[P1] cwd=repo held a handle inside a worktree being archived The command runs with cwd=None.
[P1] Missing executable fell into internal_error with ledger_recorded=false Launch errors are recorded as launch_error in the ledger and returned without raising.
[P1] Hand-rolled process handling Reuses run_capped_process / terminate_process_tree; CappedProcessResult now also exposes the bounded stderr.
[P1] mypy no-any-return in the capture helper The helper is gone; mypy is clean on the changed modules.
[P1] git diff --check blank line at EOF Removed; committed diff check passes.
[P1] Archive ledger recreated goals/<id> Archive writes into the archive destination, retire falls back to runtime/closeout/<id>; the archive test asserts the source directory stays gone.
Dashboard namespace had no editor Added a machine editor with timeout_seconds; the command stays CLI-only and the field copy says so.

The executor moved from loopx/capabilities/goal_closeout/hooks.py to loopx/lifecycle/goal_closeout.py so loopx/control_plane does not depend on loopx.capabilities and the stop function stays under the decision-size ratchet.

Review follow-up (a00dd3763)

Finding Fix
The archive transition ran the terminal command while it still held the runtime-artifact, source, maintenance and registry locks, so one slow hook could block every registry writer for up to the configured timeout archive_runtime_goal now resolves the hook facts inside the locked snapshot and invokes run_goal_closeout only after the ExitStack releases all canonical locks. The stop and retire paths already ran the hook outside their locks.
Regression coverage for the lock boundary New test_archive_runs_closeout_after_canonical_locks_are_released configures a real probe command that tries to acquire the runtime-artifact and registry locks with a zero deadline from a child process, and asserts both are free when the hook runs. The test fails against the previous head and passes with a00dd3763.

Author Declaration

  • Written by: model_agent, reviewed and submitted by the human operator.

Implemented against

Criterion (spec clause) Disposition Symbol / path Test or command
Terminal-state command declared in machine configuration implemented loopx/capabilities/goal_closeout/machine_defaults.py configuration plus executor unit tests
Command stays local-private; Dashboard read-only implemented loopx/capabilities/machine_configuration/contract.py, loopx/capabilities/goal_closeout/machine_defaults.py projection/update tests and real HTTP rejection test
Bounded JSON payload on stdin implemented loopx/lifecycle/goal_closeout.py payload and ledger unit test
Finite timeout; bounded output; failure never blocks the triggering command implemented loopx/lifecycle/goal_closeout.py timeout, launch-error and command-failure unit tests
Invocation recorded in an append-only ledger implemented loopx/lifecycle/goal_closeout.py ledger unit tests
Invoked after stop implemented loopx/control_plane/goals/activation_service.py stop entry-point test
Invoked after retire implemented loopx/global_registry.py retire entry-point test
Invoked after archive implemented loopx/runtime.py archive entry-point test
  • Self-check before submission: Reproduced each review finding on the prior head, then re-ran the focused suites on the new head on local macOS, including a real loopback HTTP request, an invalid Goal id, a missing executable and the archived-directory ledger path.

Scope And Continuation

  • Completed scope and remaining work: Complete within this scope. The executor is invoked from goal-lifecycle stop, retire-global-goal and archive-runtime; each path has an entry-point test.
  • Slice boundary / successor: Complete within this scope; no successor needed.

Validation

  • Tested revision: a00dd3763
  • Run state: finished
  • Input classes: synthetic
Check kind Result Public-safe evidence / limitation
unit passed python3 -m pytest tests/control_plane/test_goal_activation.py tests/capabilities/test_goal_closeout_hook.py tests/capabilities/test_goal_closeout_terminal_hooks.py tests/test_runtime_archive.py tests/test_global_registry_write_serialization.py tests/extensions/test_process_runtime.py tests/extensions/test_process_runtime_startup.py -q — 173 passed, 1 skipped.
real_entrypoint passed stop, retire and archive entry-point tests in tests/capabilities/test_goal_closeout_terminal_hooks.py.
real_entrypoint passed python3 -m pytest tests/test_chat_machine_configuration_api.py tests/capabilities/test_machine_configuration_contract.py -q — 50 passed, including the real loopback HTTP command rejection.
real_entrypoint passed python3 -m pytest tests/control_plane/test_goal_activation.py -q — 55 passed; the archive lock probe in test_archive_runs_closeout_after_canonical_locks_are_released asserts the child process can take the runtime-artifact and registry locks while the hook runs.
static passed python3 -m mypy loopx/lifecycle loopx/capabilities/goal_closeout loopx/capabilities/machine_configuration/contract.py loopx/runtime.py; git diff --check; loopx canary premerge --tier quick --from-git-diff direct checks pass (diff hygiene, compile, module ceiling).
regression_parity passed python3 -m pytest tests/architecture -q — 1798 passed, 98 failed on both this head and the base commit; 94 failures share the missing local npm dev dependencies.
static not_run The maintainability, semantic-vocabulary and quota-plan canaries are blocked by the same missing npm/TS local setup at both base and head; the maintainability result for this diff is advisory and inherited.
  • Coverage and gaps: Configuration, projection, HTTP rejection, invalid Goal id, missing executable, timeout, command failure and ledger paths are covered by focused tests; stop, retire and archive each have an entry-point test. Windows process handling and an installed-wheel invocation remain untested.

Frontend / Visual Evidence

  • UI impact: none (the Dashboard receives the existing capability catalog entry with a timeout_seconds editor field only).

Type of Change

  • New feature

LoopX Area

  • Control plane (goals, todos, quota, scheduler, registry, runtime)

Technical Direction

  • Direction / acceptance reference, when applicable: N/A — issue-scoped feature.

Shared-authority RFC fixture impact

  • Production-scale fixture schema: N/A
  • Semantic dimensions changed, or reviewed no-impact rationale: N/A
  • Provider conformance arms run: N/A
  • Read-only legacy/file/PostgreSQL three-arm rehearsal: N/A

Boundary Checklist

  • Neither the diff nor this PR body/comments/attachments disclose private state, credentials, raw traces or verifier output, internal links, or local machine paths.
  • I did not duplicate maintainer-owned benchmark work.
  • I kept the change scoped to the linked issue/task.
  • No paired RFC changed; the bilingual RFC check is not applicable.
  • UI impact is marked none.
  • Every commit includes a DCO Signed-off-by trailer.

Refs loopx-project#8918.

Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

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.

Reviewer: model_agent (self_reported, Gemini, Google)

动机 / Motivation

面向的问题对象与触发任务:需要自动清理已完成 Goal 工作树并审计执行结果的运维者与代理宿主。

改动前后场景对照:改动前:停止、注销或归档 Goal 时不触发任何外部清理命令,且配置中心不存在该项;改动后:仅直接调用 Python 函数 run_goal_closeout 可执行命令并记账,但 CLI 与 Dashboard 已可见 goal_closeout 命名空间,而 stop、retire 与 archive 仍完全不调用它。

当前可观测结果与非目标范围:目前仅单元测试直接调用 run_goal_closeout 可验证 payload、超时与失败返回;任意生产终态命令均无行为变化,且 machine-config 注册表与 HTTP 目录已发生变化。非目标边界:不包含内置 git worktree 清理逻辑(proposal 2)、worktree 状态发现命令(proposal 3)以及在本次提交内完成终态入口接线或 Dashboard 可视化编辑器。

放任现状不修会持续累积数十 GB 孤立工作树,但当前 PR 以正式非 Draft 状态提交了一个“配置已暴露、调用方为零、安全与静态检查均有缺失”的半成品,不仅无法交付终态自动清理,反而破坏既有机器配置目录契约。

改动思路 / Approach

该实现将尚未接线的执行器提前注册进公开 machine_configuration 目录,既破坏现有配置契约又通过未鉴权 HTTP 接口开放任意命令写入,且重复实现了 process_runtime.py 与 paths.py 的既有能力。

当前边界判断:必须先收回或隔离公开 HTTP 命令写入面、复用既有进程树与 goal_id 校验所有者并接通至少真实终态入口或退回 Draft,当前边界不具备合并条件。

按代码路径追踪,PR 在 loopx/capabilities/goal_closeout/machine_defaults.py 定义 goal_closeout 命名空间,通过 loopx/capabilities/machine_configuration/builtins.py 注册进全局配置注册表;执行层 loopx/capabilities/goal_closeout/hooks.py 通过 read_machine_configuration 读取配置,启动 subprocess.Popen(..., start_new_session=True) 传入 JSON stdin 并写 closeout-ledger.jsonl。与仓库既有方案相比,loopx/extensions/process_runtime.py 已经提供了带跨平台进程树清理和实时字节上限的 run_capped_process / terminate_process_tree,loopx/paths.py 也提供了防穿越的 validate_goal_id_path_segment,本 PR 均未复用;同时本 PR 直接将任意命令 command: list[str] 暴露到了无认证 loopback HTTP 的 machine_configuration 读写面,但未在 configuration_ui.py 注册对应界面字段,也未在 set_goal_activation_state、retire_global_registry_goals 或 archive_runtime_goal 中接入调用。

具体改动 / Changes

本次共涉及 5 个文件(+433 / -0):新增 loopx/capabilities/goal_closeout/__init__.py、machine_defaults.py、hooks.py 与 tests/capabilities/test_goal_closeout_hook.py,修改 loopx/capabilities/machine_configuration/builtins.py。

对照规格 Issue #8918(基准版本 issue-8918-opened-by-cuipengcx90-0-comments,proposal 1)的逐项验收如下:

Criterion 要求 当前 Head 状态 依据 / 缺口
C-1 配置声明 closeout 命令与超时 not_met 允许经无认证 loopback HTTP /apply 写入任意可执行命令并回显;未补齐 configuration_ui.py 与既有目录测试
C-2 stdin 传递有界 JSON 负载(loopx_goal_closeout_v1) implemented hooks.py::run_goal_closeout + 单元测试
C-3 有界超时且失败不阻塞主命令 not_met 未复用 process_runtime.py,Windows 无法清理后代进程,临时文件无运行期上限且 cwd=repo 锁死待删工作树
C-4 每次调用记入关闭账本 not_met goal_id 未校验可路径穿越、FileNotFoundError 跳入 internal_error 漏记账、archive 后写盘会重建 goals/<id> 目录
C-5 stop / retire / archive 后自动触发 not_met 全仓搜索显示 0 处生产调用点

关键代码讲解

  1. loopx/capabilities/goal_closeout/hooks.py#L95 (run_goal_closeout):读取 goal_closeout 配置并以 subprocess.Popen 执行,捕获超时与异常后通过 _write_ledger 追加账本。问题在于将 Path(repo).is_dir() 与 Popen 放在同一外层 try 块中,缺失二进制触发 FileNotFoundError 时直接落入 internal_error 而不写入账本,且 cwd=repo 会在待删除 worktree 内持有目录句柄。
  2. loopx/capabilities/goal_closeout/hooks.py#L35 (goal_closeout_ledger_path):直接返回 runtime_root / "goals" / goal_id / "closeout-ledger.jsonl",既未调用 validate_goal_id_path_segment 防穿越,也会在 archive_runtime_goal 搬走 goals/<id> 后因 mkdir(parents=True) 重新造出空目录。
  3. loopx/capabilities/goal_closeout/hooks.py#L30 (_Capture.text) & #L59 (_terminate):前者因 handle: Any 导致 mypy 报 no-any-return 且不限制进程运行期写入临时文件的总大小;后者仅用 os.killpg 清理进程组,在 Windows 回退到单进程 process.kill()。
  4. loopx/capabilities/goal_closeout/machine_defaults.py#L50 (goal_closeout_machine_configuration_namespace):以 project_public=dict、apply_public_update=dict 注册了包含任意 command: list[str] 的命名空间,使得公开 HTTP API 既可写也可回显本机可执行路径与脚本参数。
  5. loopx/capabilities/machine_configuration/builtins.py#L82 (build_builtin_machine_configuration_registry):延迟注册了 goal_closeout,立即改变了默认可用命名空间集合与 /api/chat/machine-configuration 目录输出,破坏了 3 项既有测试。

对主干的风险 / Risks

  1. [P0] 暴露无生产调用方的配置面且破坏 3 项既有契约测试:在 builtins.py 注册 goal_closeout 后,未配置状态下也会改变默认目录,实测导致 test_builtin_catalog_lists_every_owner_in_namespace_order、test_inspection_lists_registered_namespaces_without_local_refs、test_machine_catalog_discovers_goal_features_without_granting_machine_writes 全部 FAIL(207 passed, 3 failed, 41 skipped)。同时操作者在配置后不会看到 stop/retire/archive 有任何效果,违反 AGENTS.md 关于不得只交付未接入真实触发点空壳的要求。最小修复:接通 set_goal_activation_state、retire_global_registry_goals、archive_runtime_goal 并更新契约测试,或在完成前退回 Draft 并移除 builtins.py 注册。
  2. [P0] 无认证 loopback HTTP 接口允许写入任意操作系统命令:ChatRequestHandler._require_loopback_origin 允许无 Origin 头的本地请求与同源浏览器请求调用 POST /api/chat/machine-configuration/preview 与 /apply。反事实测试实测直接通过 HTTP 成功持久化了 ['/bin/sh', '-c', 'id > /tmp/pwned'](HTTP 201 -> 200 applied),并在 GET 响应中回显。最小修复:禁止经由公开 HTTP apply_public_update 写入任意 command(或仅限受保护的本地 CLI / 0600 配置文件 / 显式扩展清单注册),并对 project_public 脱敏本机路径。
  3. [P1] goal_id 路径穿越与 archive 幽灵目录复活:反事实测试传入 goal_id="../../evil",run_goal_closeout 未拒绝而是返回 ledger_recorded=True 并写入越界路径;此外 archive_runtime_goal 移除 runtime_root/goals/<id> 后若写同位置账本会重建空目录,被 loopx/history.py 再次识别为运行时 Goal。最小修复:使用 validate_goal_id_path_segment(goal_id),移除 cwd=repo,并将账本改为不会在归档后复活 goals/<id> 的路径。
  4. [P1] mypy 失败、canary premerge 失败及跨平台/漏记账缺陷:mypy 对 5 个文件实测 FAIL(hooks.py:32: error: Returning Any from function declared to return "str" [no-any-return]);loopx canary premerge --tier quick --from-git-diff --git-diff-base 5cfd6ae7d571f2f97da40982db23f76540723c89 实测 FAIL(git diff --check 报 hooks.py:218: new blank line at EOF.)。此外反事实测试确认不存在的二进制文件会落入 internal_error 且 ledger_recorded=False。最小修复:修复类型注解与 EOF 空行,复用 loopx/extensions/process_runtime.py 并把启动失败记入账本。

我的整体评价 / Verdict

基于当前精确 head 7423d748adbfd7cee0c01ff03e314ed82bc5a8ee 的实测验证,本次评审结论为请求修改(REQUEST_CHANGES)。

  • 长程与用户体验影响:long_horizon 与 user_experience 均判定为 regression(visual_review 为 not_applicable:本 PR 未改动前端源码,仅核对了 configuration_ui.py 与 Settings 界面回退行为)。在未接线终态调用点且未收紧 HTTP 写入边界的情况下向 builtins.py 注册该命名空间,会同时造成配置假象与安全面扩大。
  • 本地验证摘要:
    • pytest tests/capabilities/test_goal_closeout_hook.py:PASS(4 passed,仅测孤立函数)
    • pytest(机器配置/API/分布/语义/边界/ratchet 合集):FAIL(207 passed, 3 failed, 41 skipped;核心分布安装态因未设 LOOPX_CORE_TEST_PYTHON 跳过)
    • pytest tests/capabilities/test_capability_configuration_ui.py tests/test_configuration_backup.py:PASS(82 passed)
    • ruff check 与 node --test personal-workspace-contract.test.mjs:PASS
    • mypy(5 个改动文件):FAIL(hooks.py:32 no-any-return)
    • loopx canary premerge --tier quick:FAIL(hooks.py:218: new blank line at EOF.;另 control-plane-maintainability-ratchet-smoke.py 有 2 条基线无关 advisory 告警)
    • 反事实验证(../../evil 穿越、缺失二进制漏记账、无认证 HTTP 写 shell 命令):FAIL(均已实测复现)
    • 远端 CI:UNVERIFIED / not_applicable(遵循 wait_for_ci=false 策略,未查询或等待远端 CI)
  • 语义词表结论:semantic_alignment 判定为 not_applicable——PR 未改动 loopx/semantics/vocabulary_v0.json 中任何跨运行时词表,hooks.py 新增的状态字符串为局部结果字段,且 examples/semantic-vocabulary-drift-smoke.py(29/29 词表)PASS;不过 hooks.py 的 trigger 与 terminal_reason 建议后续收敛为显式 Literal 或 StrEnum。
  • 残留风险:Windows 进程树清理与 loopx-core 独立 wheel 安装态尚未在本机验证。请作者修复上述 4 项阻塞缺陷(接入终态入口或撤回 builtins.py 暴露、收敛 HTTP 命令写入安全边界、校验 goal_id 并解决 archive 冲突、修复 mypy/EOF 空行并复用 process_runtime.py)后重新提交复审。

English verdict: REQUEST_CHANGES on 9065@7423d748adbfd7cee0c01ff03e314ed82bc5a8ee due to unwired terminal lifecycle callers exposing a dead config namespace (breaking 3 contract tests), unauthenticated loopback HTTP command registration in machine_configuration, unvalidated goal_id path traversal, missing ledger recording on spawn errors, mypy failure, and canary premerge diff check failure.

Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com>
Run the command from the lifecycle layer so control-plane keeps its import boundary, validate the Goal id before any write, reuse the capped process runtime for bounded output and process-tree cleanup, and record launch failures in the ledger. Keep the command local-private: the Dashboard sees configured/timeout only and cannot persist a command.

Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com>
@gcl-coder gcl-coder changed the title feat(goal-closeout): add bounded terminal-state hook executor feat(goal-closeout): invoke terminal hook on stop, retire and archive Nov 19, 2026
@gcl-coder

Copy link
Copy Markdown
Contributor Author

已在 3d784d44a 处理上一轮评审的全部阻塞项,PR 正文的 “Review follow-up” 表逐项对应。

  • [P0] 目录契约测试:更新了三处命名空间/能力清单,补齐 goal_closeout 的模板断言和 machine-only 集合。tests/test_chat_machine_configuration_api.py 与 tests/capabilities/test_machine_configuration_contract.py 共 50 项通过。
  • [P0] 匿名 loopback HTTP 写 command:command 现在是 local-only 字段。/preview 和 /apply 走的 namespace merge 会拒绝它,project_public 只返回 configured 与 timeout_seconds,本机 machine-config CLI 仍可写。真实 HTTP 测试断言 400、错误文案与 machine/configuration.json 不存在;Dashboard 编辑器只保留 timeout,并注明 command 仅限本机 CLI。
  • [P1] Goal ID 路径穿越:在任何读取配置或写账本之前调用 validate_goal_id_path_segment;非法 ID 返回 invalid_goal_id,不落盘、不执行。
  • [P1] cwd=repo:改为 cwd=None,归档时不再持有待删 worktree 内的目录句柄。
  • [P1] 缺失可执行文件:启动失败记为 launch_error 并写入账本,ledger_recorded=true,不再落进 internal_error。
  • [P1] 进程治理:复用 run_capped_process(超时终止进程组、stdout/stderr 有界);CappedProcessResult 增加 stderr 字段。mypy 与 git diff --check 均通过。
  • [P1] 归档账本重建 goals/<id>:归档写回 archive 目标目录,retire 在源目录不存在时写 runtime/closeout/<id>;归档测试断言源目录保持消失。
  • Dashboard 无编辑器:补了 goal_closeout 的 timeout_seconds 机器编辑器。

执行器从 loopx/capabilities/goal_closeout/hooks.py 移到 loopx/lifecycle/goal_closeout.py:loopx/control_plane 不再依赖 loopx.capabilities,set_goal_activation_state 也回到决策规模上限内(maintainability 棘轮只剩基线上已存在的两项,且本 diff 为 advisory inherited)。

验证:closeout/archive/registry/process-runtime 117 passed、1 skipped;goal activation 55 passed;架构套件在基线与本头均为 1798 passed,98 failed(94 项同为本机缺少 npm dev dependencies)。canary quick 的六项直接检查通过;semantic-vocabulary 与 quota-plan canary 在基线同样因本机 npm/TS 环境失败。

archive_runtime_goal held the runtime-artifact, source, maintenance and
registry locks while the terminal hook ran, so a slow operator command
blocked every other registry writer for up to the configured timeout.
The archive transition now resolves the hook facts under the locked
snapshot and invokes the hook once every lock is released.

Signed-off-by: ChengLong GU <88359731+gcl-coder@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

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.

Reviewer: model_agent (self_reported, Gemini, Google)

动机 / Motivation

面向的问题对象与触发任务:需要自动回收已完成 Goal 工作树并保留执行审计记录的运维者与代理宿主。

改动前后场景对照:改动前:执行 goal-lifecycle stop、retire-global-goal 或 archive-runtime 仅更新注册表或移动目录,不触发任何本机清理命令,也不写关闭账本;改动后:若本机通过 CLI 配置了 goal_closeout.command,三条终态路径在事务提交且释放全部规范锁之后,自动以受限子进程执行该命令、通过 stdin 传入 loopx_goal_closeout_v1 JSON 负载并将结果追加到 closeout-ledger.jsonl。

当前可观测结果与非目标边界:当前可观测结果:配置 goal_closeout 后,stop(仅首次切换至 stopped,重复调用幂等不重触发)、retire 与 archive 均在提交并释放锁后触发命令并记账,超时/失败/缺失二进制绝不阻塞或改写主命令结果;未配置时三条终态命令保持零副作用且不生成账本;loopback HTTP 接口无法写入或读取本机 command。非目标边界:不包含内置 git worktree 自动删除逻辑(proposal 2)、worktree 状态发现命令(proposal 3)、经由无认证 HTTP 注册可执行命令,以及在 Dashboard 中新增本地命令路径编辑框。

对上一轮审查 #5968911212(head 7423d748ad)提出的 4 项阻塞缺陷,本轮精确头 f92547362cfd10dce59e8912dfe067776064b028 已逐项完成修复并闭环了 archive 锁边界问题,交付了一个完整、可逆且默认关闭的终态钩子切片。

改动思路 / Approach

架构边界与所有权拆分合理:配置契约留在 machine_configuration 注册表并隔离 command 为本机 CLI 私有,子进程执行下沉至 loopx/lifecycle/goal_closeout.py 并复用 process_runtime 进程树清理与 paths 路径段校验,终态调用方在提交并释放规范锁之后以尽力而为方式触发,既未引入跨层依赖也未创建重复控制面决策所有者。

当前 PR 边界为 Issue #8918 方案一的完整可逆交付:覆盖 machine_configuration 命名空间(CLI 写 command、Dashboard 仅调 timeout_seconds)、stop/retire/archive 终态后锁外调用、以及 closeout-ledger.jsonl 账本;不包含内置 git worktree 自动删除与 worktree 状态扫描命令。

关于 TypeScript-First 与模块落点:machine_configuration 注册表、三个终态入口(activation_service.py、global_registry.py、runtime.py)及受限子进程调度(process_runtime.py)均属 Python 运行时所有者,将 run_goal_closeout 置于 loopx/lifecycle/goal_closeout.py 使 loopx/control_plane 无需反向依赖 loopx.capabilities(test_control_plane_import_boundaries.py 全部通过)。

路径 / 阶段 7423d74(旧) f925473(当前 Head)
终态入口接线 0 处生产调用点 stop / retire / archive 均在提交且释放全部规范锁后调用
HTTP 安全边界 允许经 loopback HTTP 写入任意 command local_only_fields 拒绝 HTTP 写 command(400),公开投影脱敏为 configured
路径与账本 未校验 goal_id、cwd=repo、归档重建 goals/<id> validate_goal_id_path_segment、cwd=None、归档写目标目录、retire 回退 closeout/<id>
进程治理 自写 Popen/临时文件、mypy 与 EOF 失败 复用 run_capped_process 并暴露 stderr,启动失败记为 launch_error

具体改动 / Changes

本次基于合并基线 9dbe0f2a56077ed133d5bb3796bc2fa6df7d75a2 至精确 head f92547362cfd10dce59e8912dfe067776064b028 共改动 16 个文件(+1213 / -3),其中生产代码 12 个文件(+535 / -1),测试 4 个文件(+678 / -2)。

对照规格 Issue #8918(基准版本 issue-8918-opened-by-cuipengcx90-0-comments,proposal 1)的逐项验收如下:

Criterion 要求 当前 Head 状态 依据 / 验证
C-1 配置声明 closeout 命令与超时且安全隔离 implemented goal_closeout/machine_defaults.py + contract.py + configuration_ui.py;HTTP 写 command 实测返回 400
C-2 stdin 传递有界 JSON 负载(loopx_goal_closeout_v1) implemented loopx/lifecycle/goal_closeout.py::run_goal_closeout + 单元测试与 SQLite CLI 探针
C-3 有限超时、受限输出与失败不阻塞主命令 implemented 复用 process_runtime.py::run_capped_process(cwd=None);实测 exit 42、1s 超时与缺失二进制均不阻塞主命令
C-4 每次调用记入只追加账本且防越界/不复活目录 implemented validate_goal_id_path_segment + exclusive_file_lock;archive 写目标目录、retire 回退 closeout/<id>
C-5 stop / retire / archive 提交并释放锁后触发 implemented activation_service.py、global_registry.py、runtime.py;stop 幂等重跑不重触发,archive 锁探针 FREE/FREE

关键代码讲解

  1. loopx/capabilities/goal_closeout/machine_defaults.py (goal_closeout_machine_configuration_namespace):定义 loopx_goal_closeout_configuration_v0,通过 local_only_fields=frozenset({"command"}) 将 command 锁定为本机 CLI 专属字段;_public_goal_closeout_configuration 仅向 Dashboard/API 暴露 configured 布尔值与 timeout_seconds(1–600),_apply_goal_closeout_public_update 允许在线调整超时并原样保留已配置的 command。
  2. loopx/capabilities/machine_configuration/contract.py (merge_machine_configuration_namespace):新增 allow_local_only: bool = False 默认保护。MachineConfigurationRequestMixin(loopback HTTP)默认拒绝任何命中 local_only_fields 的键并落回 HTTP 400;machine_configuration/cli.py 在 preview/apply 时显式传入 allow_local_only=True。
  3. loopx/lifecycle/goal_closeout.py (run_goal_closeout):入口先调用 validate_goal_id_path_segment 防路径穿越,再按 namespace_ids=("goal_closeout",) 惰性读取配置;未配置时零盘写直接返回 not_configured。启用时经 run_capped_process(..., cwd=None) 启动进程组并截断捕获 8 KiB stdout/stderr,所有启动、超时、超输出与写账本异常均转化为结构化状态并写回 closeout-ledger.jsonl,绝不向上抛错。
  4. loopx/control_plane/goals/activation_service.py (set_goal_activation_state / _stop_closeout_payload):在 project_registry_transaction 锁块外、仅当 execute and target_state is GoalActivationState.STOPPED and changed and payload.get("ok") and payload.get("written") 时调用一次钩子;已处于 STOPPED 状态的幂等重试 changed=False,不会重复触发。
  5. loopx/runtime.py (archive_runtime_goal) & loopx/global_registry.py (retire_global_registry_goals):retire_global_registry_goals 在释放维护锁与全局注册表锁后遍历 retired_goals,当 goals/<id> 不存在时改写 runtime/closeout/<id>;archive_runtime_goal(a00dd3763a)在 4 重规范锁内完成移动与元数据快照,退出 ExitStack 释放全部锁后再执行 run_goal_closeout(..., ledger_dir=destination),实测子进程检查运行期产物锁与注册表锁均为 FREE。

对主干的风险 / Risks

未发现阻塞主干或破坏兼容性的 P0/P1 缺陷;与上一轮 #5968911212 相比,3 项破坏的契约测试已全部通过,HTTP 任意命令写入、goal_id 越界、cwd=repo 锁目录、缺失二进制漏记账、mypy 报错及 EOF 空行均已修复。

  • 禁用态隔离与基线对等(default_off_isolation):基于基线 9dbe0f2a56 与当前 head f92547362c 的同构对照执行显示,未配置 goal_closeout 时 stop / retire / archive 均正常提交(ok=true),不产生进程或账本副作用,仅在配置目录新增 goal_closeout 条目与返回体附加 status='not_configured' 状态对象。
  • 两项非阻塞 P3 观察:
    1. loopx/runtime.py::archive_runtime_goal 在加锁前从 registry 提取 archive_goal 元数据,而非从锁内 locked_registry 再次取值;虽有 locked_source_registry_paths 与 _archive_source_goal_refs 预检保护,后续可顺手改读 locked_registry 以保持单快照一致。
    2. apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts 尚未补充 goal_closeout 的中文翻译键,界面目前安全回退展示后端英文标题与说明;此外 Dashboard 通用的移除按钮可删除整个 goal_closeout 命名空间,但不构成命令注入风险。

我的整体评价 / Verdict

基于对精确 head f92547362cfd10dce59e8912dfe067776064b028 的独立测试、基线对照与真实 SQLite/CLI/HTTP 端到端探针验证,当前评审结论为建议批准(APPROVE)。

  • 长程与用户体验影响:long_horizon 与 user_experience 均判定为 improved(visual_review 为 not_applicable:本 PR 未修改前端代码,已核对 configuration_ui.py、machine-configuration-settings.tsx 与 capability-localization.ts 的 timeout_seconds 表单消费及回退路径)。钩子严格在提交且释锁后执行,失败不阻塞终态,且通过本机 CLI 与 loopback HTTP 权限切分降低了配置风险与运维负担。
  • 本地验证摘要(wait_for_ci=false,未查询或等待远端 GitHub Actions CI):
    • pytest(closeout / 终端钩子 / machine-config API & 契约 / UI 编辑器 / 备份 / goal activation / runtime archive / global registry / process_runtime 共 11 个测试集):PASS(305 passed, 1 skipped——Windows 专属用例在 macOS 跳过)
    • pytest tests/test_runtime_archive_concurrency.py -q:PASS(9 passed)
    • pytest tests/architecture/test_control_plane_import_boundaries.py tests/architecture/test_goal_id_path_segment_owner.py -q:PASS(47 passed)
    • pytest tests/architecture -q(带完整 node_modules):1894 passed, 2 failed——两项失败(test_retrodiction_holds_its_frozen_baseline 在 E07 报 11/15 < 12/15,以及 test_direct_project_registry_loaders_have_source_session_denial 报未改动文件 loopx/presentation/goal_storage_api.py)已在不可变合并基线 9dbe0f2a56 上复现出完全一致的失败签名(pre_existing_unrelated)
    • 真实 SQLite/CLI/HTTP 端到端隔离探针:PASS(覆盖 3 个 SQLite Goal:goal_closeout 禁用态、启用态 stop→幂等重复 stop→retire→archive、缺失 goals/<id> 目录回退 closeout/<id>、exit 42、1s 超时、缺失二进制 launch_error、../escape 拒绝以及真实 ChatHTTPServer 拦截 command 注入返回 400)
    • 静态与契约检查:ruff check 全通过;mypy --follow-imports=silent(12 个改动文件)0 报错;git diff --check 9dbe0f2a56..HEAD 通过;Dashboard tsc --noEmit 与 node --test personal-workspace-contract.test.mjs(4/4)通过
    • loopx check --scan-path ...:PASS(16 个改动文件公开边界扫描 0 error / 0 warning)
    • loopx canary premerge --tier quick --from-git-diff --git-diff-base 9dbe0f2a56077ed133d5bb3796bc2fa6df7d75a2:PASS(ok=true, merge_gate_passed=true;direct checks 4/4、semantic-vocabulary-drift-smoke.py、quota-plan-smoke.py 均通过;control-plane-maintainability-ratchet-smoke.py 仅有 1 条基线已存在的 interaction_contract.py::_admitted_interaction_next_cli_actions advisory 告警)
  • 语义词表 conclusions / semantic_alignment:判定为 not_applicable——PR 未修改 loopx/semantics/vocabulary_v0.json 中任何跨运行时词表,新增字段均为 goal_closeout 模块局部值且 semantic-vocabulary-drift-smoke.py 通过。
  • 残留风险:Windows 平台进程树终止(CREATE_NEW_PROCESS_GROUP + taskkill)与独立安装态 loopx-core wheel 尚未在当前 macOS 宿主验证;远端 CI 按 wait_for_ci=false 策略未查询。批准本评审本身不构成合并授权,是否合并及基线同步由维护者依据仓库策略决定。

English verdict: APPROVE on 9065@f92547362cfd10dce59e8912dfe067776064b028 — all prior blockers from review 5968911212 and the archive lock-release boundary are resolved and verified via 305 focused tests, static/canary checks, and isolated SQLite CLI/HTTP probes.

@mergify

mergify Bot commented Nov 19, 2026

Copy link
Copy Markdown

This pull request has merge conflicts with main and cannot be merged
until they are resolved. Please rebase or merge the base branch, @gcl-coder.

Choose the remote for the base repository, not an out-of-date fork.
For a fork clone, first inspect git remote -v; upstream must point
to https://github.com/loopx-project/loopx.git. If it is absent, add it
with git remote add upstream https://github.com/loopx-project/loopx.git.
Then run:

git fetch upstream
git rebase upstream/main
# Resolve each conflict, git add the resolved files, then git rebase --continue.
git push --force-with-lease origin HEAD

For a same-repository clone whose origin points to
https://github.com/loopx-project/loopx.git, use origin instead of
upstream for fetch/rebase. If you prefer merging the base, use
git merge <base-remote>/main and push normally.

Keep the DCO Signed-off-by trailer on every commit when you rebase.
https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify Bot added the needs-rebase Mergify: the pull request has merge conflicts with its base branch label Nov 19, 2026

@loopx-agent loopx-agent left a comment

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.

Reviewer: model_agent · gpt-6.2-sol · OpenAI (runtime_reported, max)

Reviewed head f92547362cfd10dce59e8912dfe067776064b028

  • [P2] 保留已经提交并确认的停止结果。两份注册表都确认停止后,钩子的参数准备仍会重新读取来源。读失败时 CLI 退出 1 并返回 written=false。建议利用已确认的快照准备参数,并把准备失败纳入钩子诊断。停止后的注册表读取

  • [P2] 用注册表解析后的绝对路径填充钩子载荷。使用已有的相对 state_file 注册时,停止、退役和归档的外部状态文件分支都把相对值传给子进程。请复用现有路径解析,归档后按文件实际位置生成路径。停止 · 退役 · 归档

动机 / Motivation

用独立 Git worktree 执行 Goal 的操作者,在停止、退役或归档之后需要知道何时可以开始整理工作目录。

过去归档只移动 LoopX 运行目录,操作者还要逐个对照 Goal 和工作目录,或为每种宿主维护一套清理入口。这个 PR 允许操作者设置一次本机命令,让三种操作在提交后把 Goal 和路径交给同一个程序,并留下一条调用记录。

用真实 CLI 验证了三条成功路径。现有注册的相对状态路径会让消费方拿不到所需的绝对路径,停止后读取注册表的异常还会掩盖已经提交的结果。

范围限于提供终态通知和调用记录。目录清理规则和通用扩展触发器属于 Issue 中的其他提案。

改动思路 / Approach

三个生命周期入口各自保留已有的权限检查、锁和提交顺序。已提交的终态才产生可选通知。执行器从本机配置读命令,使用已有进程约束处理退出、超时与输出,并把此次执行追加到本机记录。 终态钩子实现 · 通用进程执行器

把机器配置当作一次注册,将命令放在终态确认之后,复用通用进程边界。提交后的通知仍要隔离路径解析和读取异常。 本 PR 可在既有状态路径解析和终态写回的边界内补齐,不需要新增运行时或扩展调度。 项目注册的状态路径已有明确规则,退役资格检查也已解析相对值。这两处规则能直接支撑载荷中的路径语义。 项目注册路径 · 全局路径解析

具体改动 / Changes

本次改动涉及 16 个文件,+1213 / −3。主要新增集中在机器配置、三个提交后的调用点、钩子执行和验证。验收依据为 Issue #8918 的 Proposal 1,读到的正文版本为 sha256:aa2fd7a4818b17cf5627f14fd7b557706548e16eb1297c3b90b3308e70e6ba3d。 Issue #8918

  • terminal-triggers。停止、退役和运行目录归档成功提交后触发一次。 已验证。set_goal_activation_state、retire_global_registry_goals、archive_runtime_goal 三条真实 CLI 执行及无写入预览对照。
  • stdin-payload。向标准输入提供 loopx_goal_closeout_v1 及 Goal、绝对 worktree 和状态路径、终态原因和 runtime root。 未满足。相对 state_file 从三个入口原样进入载荷。 通过各入口现有注册表路径所有者生成绝对路径。
  • timeout。执行有有限超时。 已验证。run_goal_closeout 与 run_capped_process 本地 1 秒超时、普通命令退出及启动失败用例。
  • best-effort。钩子失败时触发命令仍报告实际完成的终态。 未满足。停止后准备参数的注册表读取失败会覆盖已写入结果。 将准备异常与执行异常放在同一 best-effort 边界,保留原有终态回执。
  • ledger。记录已执行的调用。 已验证。_write_ledger 三个 CLI 的合成 ledger 行及归档后位置读回。

关键代码讲解

  • merge_machine_configuration_namespace 通过已有机器配置事务写入。CLI 可设置命令,Dashboard 表单可设置超时;配置投影只返回是否已有命令及超时值。 命名空间更新 · 编辑器描述

  • set_goal_activation_state 先完成注册表写回和验证,再根据本次是否确实进入停止状态调用钩子。相同状态的重复停止不产生第二条调用记录。 停止触发门

  • retire_global_registry_goals 从实际移除的记录取信息,保留原有备份与资格检查,释放维护锁后逐项通知。 退役后通知

  • archive_runtime_goal 在原锁内移动运行目录,释放锁后执行。随目录移动的状态文件与留在项目中的状态文件需要各自准确定位。 归档与位置选择

  • run_goal_closeout 复用进程执行器处理退出、超时和诊断输出,给尝试过的调用追加 ledger。未设置命令时没有子进程或账本记录。 执行与记录 · 执行器用例

对主干的风险 / Risks

用同一合成状态分别运行基线 9dbe0f2a56077ed133d5bb3796bc2fa6df7d75a2 和当前 head,检查进程退出、终态读回和账本结果。

验证条件 实际结果
缺省配置,正常执行三种操作 基线与 head 都完成相同终态,预览无调用;head 增加可选的钩子结果字段。
成功读回后注入来源注册表读取错误 基线退出 0。head 退出 1,报告 written=false,持久化状态已经停止。
在项目之外调用,用相对路径登记状态 三条命令完成终态,接收方因路径不符合契约退出,账本各留一条失败。绝对路径对照组各留一条成功。

两个失败都可以在一次小修后重跑。停止保留原回执并单独记录钩子准备错误,路径修复复用注册表解析。建议回归用例从另一个目录走真实 CLI,并同时检查返回值、注册表和账本。

本地定向测试 223 项通过,1 项 Windows 用例跳过。标准 premerge 通过,有一条与本 diff 无关的既有可维护性 advisory。已观察到目标分支存在测试文件冲突,合并前需更新分支并验证新 head。

语义与 CI 对齐

终态成功的判定仍由写入和读回构成。可选钩子仅消费该结果;当前 head 的准备异常改变了可观察行为。新版本化载荷与账本记录作为生命周期接口扩展,解决路径和返回值契约后,用同一文件系统 fixture 重跑三条命令。GitHub CI 未纳入本次验证。

我的整体评价 / Verdict

REQUEST_CHANGES。长期运行中,停止已提交却显示失败会引发多余的重试。用户操作方面,设置页的超时预览和应用已在实际 Chat HTTP 后端读回,过期预览被拒绝,重新加载并应用后保留了本机命令。三个终态入口仍需把报告的结果与持久状态、路径对齐。

在同一源码构建的能力中心,超时输入和变更按钮集中在一个卡片。桌面默认视图显示配置来源,是否有命令要展开原始 JSON 才看得到。窄屏保留了可读的超时值,展开后能读到配置状态。 浏览器覆盖本地构建和合成机器配置。正式打包安装、Lark 界面及更长的真实目录数据保留为未验证。

范围和共用进程执行器都适合这项需求。当前最有价值的收敛是共用已有路径规则,并保持通知失败的诊断留在钩子结果里。修复后请用相同 fixture 验证缺省关闭、相对路径、提交后读失败和正常重试。

English verdict: REQUEST_CHANGES. At f92547362cfd10dce59e8912dfe067776064b028, the stop hook can mask a committed stop after a registry read error, and supported relative registrations reach the hook without the required absolute state path. Local CLI, browser settings, and focused tests were run.

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=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。

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-rebase Mergify: the pull request has merge conflicts with its base branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: a terminal-state (closeout) hook so finished goal worktrees can be reclaimed

2 participants