Repository navigation
perf(cli): load heartbeat prompt on demand - #7704
Conversation
|
Author validation for Changed surfaces: selected CLI registration/dispatch, extracted heartbeat transport, real File/SQLite entrypoint tests, and command-ownership smokes. The handler body is AST-identical to the baseline. Existing typed state, domain-neutral control contracts, defaults, and machine-enforced obligations keep their original owners and text. The future-facing pass reused the existing registrar/dispatcher and removed the obsolete handler branch. Validation: 156 Python tests passed; 37 immutable-baseline output cases match exactly; the replay below independently passes 40 public-entrypoint observations and proves all three isolation tests fail on baseline and pass on this head. Standard canary passed 6 direct plus 11 selected checks with no failures, warnings or skips. Its initial failure was an obsolete quota renderer-location assertion reproduced on baseline, then repaired against the existing presentation owner. Focused lint and public-boundary scans passed. Remaining gates: hosted CI is queued and maintainer runtime review/merge authorization is still required. This author validation is limited to the CLI loading seam; no benchmark runs or managed-task throughput qualification were performed. Replay from this head after BASE_CHECKOUT="$(mktemp -d)"
git worktree add --detach "$BASE_CHECKOUT" a36e01c32b0a290a96466c766629a0b01850f823
export LOOPX_COMPARE_BASE="$BASE_CHECKOUT"
uv run --extra test python - <<'PY'
import os
from pathlib import Path
import sys
import tempfile
sys.path[:0] = [str(Path.cwd() / 'tests'), str(Path.cwd() / 'tests/control_plane')]
import test_cli_entrypoint as helpers
import test_heartbeat_cli as cases
candidate = Path.cwd()
baseline = Path(os.environ['LOOPX_COMPARE_BASE']).resolve()
original_batch = helpers.run_cli_batch
def compare_batch(module, argv):
helpers.REPO_ROOT = baseline if module == 'loopx.cli' else candidate
return original_batch('loopx.entrypoint', argv)
cases.run_cli_batch = compare_batch
with tempfile.TemporaryDirectory(prefix='heartbeat-replay-') as temp:
root = Path(temp)
cases.test_heartbeat_parser_and_full_diagnostics_match()
for index, formats in enumerate([('json', None), ('markdown', None), ('markdown', 'json')]):
cases.test_heartbeat_output_and_format_precedence(root / str(index), *formats)
cases.test_heartbeat_semantic_errors_keep_recovery_and_exit_status(root / 'errors')
cases.test_heartbeat_explicit_missing_registry_retains_fallback_contract(root / 'registry')
for mode in ('help', 'thin', 'bootstrap'):
helpers.REPO_ROOT = baseline
try:
cases.test_cold_heartbeat_avoids_unrelated_modules_and_external_io(root / ('base-' + mode), mode)
except AssertionError as error:
assert 'unexpected module import: loopx.cli' in str(error), str(error)
else:
raise AssertionError('baseline unexpectedly passed isolation')
helpers.REPO_ROOT = candidate
cases.test_cold_heartbeat_avoids_unrelated_modules_and_external_io(root / ('head-' + mode), mode)
print('40 public-entrypoint observations match; 3 isolation cases fail on baseline and pass on head.')
PY |
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · gpt-6.1-sol · OpenAI · runtime_reported · reasoning_effort=max
APPROVE:当前完整源码切片未发现阻断问题。 精确头 bc5d1306a23fb0204208f25d771a311c44564864;实际差异基点 a36e01c32b0a290a96466c766629a0b01850f823。主干 225698b313f3bcd5c967220013b4a2254c586792 已在同一旧 smoke 断言处修改,独立合并预览发生冲突;这是待作者解决的合并条件,当前评审不执行合并,更新 head 后须重新核验。
动机 / Motivation
周期性运行 heartbeat-prompt 的维护者和 Agent,每次都要先加载完整 CLI 及无关的聊天、Dashboard 和状态服务代码。
例如只读一次薄提示,旧入口仍导入约一千个 LoopX 模块;新入口只构造该命令的 parser,再进入原处理逻辑,减少每次唤醒的启动开销。
本轮独立验证了命令输出、错误恢复和权限提示保持原义,并观察到所选三个冷进程入口的加载量和启动时间下降。
本 PR 的验收边界是 heartbeat CLI 加载路径;minimal/standard 安装、真实模型采用、受管任务吞吐及完整长程成本仍由原有验收分别判断。
改动思路 / Approach
选中命令的加载属于现有 Python CLI transport;实际工作、权限和结算仍由原 typed owner 决定。复用 canonical registrar 和共同 dispatcher,并删除旧 handler 分支,足以解决本次加载问题。
当前边界是一个可直接调用和回退的 heartbeat 路由,不增加配置、服务、持久状态或第二套决策实现。
_SELECTED_COMMANDS 决定是否先构造局部 parser。合法输入直接进入共同分发;局部 parser 拒绝时,既有完整 parser 负责原诊断。完整 CLI 也调用同一个新位置的 handler,因此保留它的内部兼容 wrapper 反而会增加维护面。检索基点与 head 的 registrar、dispatcher、旧集合和调用方后,没有发现需要保留旧内部心跳分支的生产消费者。
这里采用下表呈现独立执行观察,未生成流程图。
| 真实 console 对照 | 结果 |
|---|---|
| 默认、thin/brief/compact/full/bootstrap、JSON/Markdown 与格式优先级 | 基点与 head 完整 stdout/stderr/exit 相同 |
| Kiro/generic/Codex、显式/省略/空/缺失 registry、context on/off | 保留成功或原拒绝及恢复命令 |
| 缺参数、缩写、冲突 flags、未知 Agent/Goal、无效 envelope/socket | 保留完整诊断和退出状态 |
具体改动 / Changes
先读的接受依据为 Monorepo Distribution and Small-Kernel Runtime Composition,spec_revision a36e01c32b0a290a96466c766629a0b01850f823。I2 的单一决策 owner、I3 的内部调用迁移与删除、I6 的既有协议/边界保持、I7 的未选中组件不激活、I8 的完整上下文及 I9 的测量范围披露,在本次 CLI seam 内均有实现和对应验证;这不宣告 RFC 的整套安装与 managed-task 里程碑完成。当前主干新增的 provider-routing guard 说明不改变本次所用条款。
完整八文件 +415/-236:三个生产文件 +260/-230,五个测试/演练文件 +155/-6。旧处理分支的完整函数体与新函数体 AST 相同,209 行处理逻辑是移动;其余生产变化用于导入边界、类型及共同分发。没有通过删提示或截断输出获得这个结果。
关键代码讲解
_build_selected_parser:遇到 heartbeat-prompt 才调用既有 registrar。没有复制参数语法;帮助只加载自身 parser。解析失败仍由_run_command回到完整 CLI 的 canonical diagnostic。_dispatch_common_command:合法输入才导入处理模块;原 registry 是否显式提供的含义仍通过not allow_missing_registry传递。完整与局部分发共享此处及原 effect request scope。handle_heartbeat_prompt_command:保留注册 Agent 核验、runtime alias 冲突、机器 context 默认、bootstrap、错误恢复及 recurring thin 投影。Python 继续运输输入,未接管准入或结算。
对主干的风险 / Risks
最强反例是局部 parser 看似更快,却在错误输入、隐式 registry 或 context 关闭时改变恢复指令。独立 console 驱动在不可变基点和精确 head 执行相同 37 组输入,共 74 次调用;完整输出和退出码逐字相同,无归一化,夹具前后摘要相同。含成功、解析拒绝和语义拒绝,未将无效 visible-host 组合误报为成功路径。
help、thin、bootstrap 的另六个冷进程 trace 均无 subprocess/socket 事件;基点三例都会加载五个无关模块,head 三例全部避开,构成加载隔离断言的缺陷敏感性证据。LoopX 子模块数分别从 1146/1150/1150 降到 25/212/213。上下文中的 actor、权限、当前 guard、必读、继续及停止/结算条款没有删改;完整输出配对及原处理体对照共同支持这个判断,不能从模块数推断模型遵循程度。
独立测试为 323 PASS、5 SKIP;五项跳过来自显式 native Codex loopback 资格入口未配置,没有发起模型调用。Ruff、配置指定 17 文件 mypy、编译、双语 RFC、公开边界和 standard premerge 的 6 direct +11 selected PASS。未查询、轮询或等待远端 CI。DCO trailers 已核对。需要真实 Node/权限的后续 guard/结算仍由原 owner 拒绝或执行;更快的只读提示不授权业务。
复跑入口包括 uv run --extra test pytest -q tests/test_cli_entrypoint.py tests/control_plane/test_heartbeat_cli.py tests/control_plane/test_heartbeat_registry_route.py tests/control_plane/test_heartbeat_agent_input.py tests/control_plane/test_heartbeat_prompt_support.py tests/control_plane/test_context_machine_configuration.py tests/control_plane/test_heartbeat_envelope_transport.py tests/control_plane/test_heartbeat_command_authority.py;本轮 standard premerge 使用 --from-git-diff --git-diff-base 225698b313f3bcd5c967220013b4a2254c586792。作者另附的可重放脚本保留其作者来源,本轮配对和 trace 独立执行。
语义与 CI 对齐
这里复用已有命令名,在局部 dispatch 集合注册现有入口;没有新的共享状态词汇或 default-off 能力。机器 context 自身的 opt-in 及 off 路径保留,所选 on/off 输出对照通过。两处旧 module-location smoke 改为检查当前真实 owner,产品逻辑与真实入口测试另有覆盖,未降低语义断言。相邻整理已应用:移走处理体并删除旧分支;进一步拆治理 owner 对本问题没有必要。
我的整体评价 / Verdict
本次达到所声明的 CLI 加载结果。long_horizon 为 preserved:原工作义务和后续命令保持;user_experience 为 improved:相同请求更快得到相同可执行提示,不新增用户确认或配置步骤。
独立启动测量使用 macOS arm64、Python 3.12.15、warm filesystem/fresh process,每例各两次预热后七组交替配对;停止本评审其他验证后采样,但机器仍为共享主机。help/thin/bootstrap 中位数为 716.58→91.89、560.22→162.92、661.96→174.50 ms;样本最大值为 999.05→127.94、806.91→219.23、759.78→354.46 ms。它们不是通用 p95 门限、安装态资格或任务收益;作者另一个环境的时间/RSS 数字不冒充本轮测量。
已检查 CLI、提示 renderer 及现有 companion 入口;本差异没有渲染页面或布局变化,视觉评审不适用。视觉未验证范围:none。
源码切片可批准,实际合入仍须解决上述 smoke 冲突并保留主干的新断言,再对更新 head 重新评审和运行所需门禁。原生 Windows、物理发行包、真实 Host/模型采用与完整成本不在本轮资格内。此评审不授予合并、升级或默认切换权限。
English verdict: APPROVE — bc5d130. The complete heartbeat loading seam preserves 37 console cases byte-for-byte and avoids unrelated loading on all three cold paths; focused and required local checks pass. The current-main smoke conflict remains a separate merge hold. Package/host adoption and long-horizon benefit are not certified.
|
This pull request has merge conflicts with Choose the remote for the base repository, not an out-of-date fork. 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 HEADFor a same-repository clone whose Keep the DCO |
Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> Co-authored-by: TRAE CLI <traecli@bytedance.com>
Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> Co-authored-by: TRAE CLI <traecli@bytedance.com>
bc5d130 to
4f9a2e5
Compare
huangruiteng
left a comment
There was a problem hiding this comment.
APPROVE — exact head 4f9a2e50ea4fd7201e68e0f0f7e21bfe1192770f. No blocking finding remains. The rebased proposal preserves the current mainline quota presentation assertion, keeps the heartbeat handler behavior, and passes the complete affected suite plus the repository premerge gate.
Reviewer: model_agent; GPT-5; OpenAI; self_reported
动机 / Motivation
Agents and operators invoking heartbeat-prompt on repeated scheduled wakes. They previously paid for constructing the complete CLI and importing chat, dashboard and status-server code even when they requested only one read-only prompt. That cost repeats across long-running work, so a cheap periodic decision became a relatively expensive process start on every wake.
Before the change, even heartbeat help and thin prompt generation entered the full CLI path. After the change, the entrypoint recognizes heartbeat-prompt, builds only its selected parser, validates the arguments and imports the existing handler through the common dispatcher. The public heartbeat prompt and recovery contract stays unchanged while cold help, thin and bootstrap paths avoid the full CLI and unrelated server modules.
This PR does not qualify minimal or standard package distribution, managed-task throughput, live model adherence, installed-host migration or a broader TypeScript command migration.
改动思路 / Approach
loopx.entrypoint already knew how to dispatch a selected command without building every parser. This change registers the existing heartbeat-prompt parser in that selected path and sends both selected and full CLI calls through one common dispatcher. The existing handler body moves into support_control_heartbeat.py; no second command grammar or decision path is introduced.
That design is proportionate because the problem is parser and import fan-out, not prompt semantics. Keeping the large handler in support_control.py would force the selected process to import all support/control dependencies. Adding another routing state machine would duplicate the canonical registrar and dispatcher. The current PR boundary is the smallest reusable CLI transport change that removes the measured fan-out. One existing command's loading seam; package distribution and managed-task throughput remain separate milestones.
具体改动 / Changes
The final exact-head slice is seven files, +411/-235: three production files, one command-ownership smoke and three focused tests. The production change adds 13 lines to cli_runtime.py, moves the 230-line heartbeat branch out of support_control.py, and creates support_control_heartbeat.py containing the existing handler plus its dependencies.
The accepted basis is docs/architecture/rfcs/monorepo-distribution-split-v0.md at current main 186582b30c306559398a653e964a33bd6e43f135. I2 single decision owner remains true: the prompt handler and typed control-plane owners are reused. I3 internal migration and deletion is applied by removing the old support-control branch. I6 keeps existing protocol fields and public CLI syntax. I7 inactive components remain unloaded is directly exercised by cold-process tests. I8 bounded complete context preserves the full prompt and recovery context. I9 measurement boundary limits the claimed result to the CLI loading seam.
关键代码讲解
_build_selected_parseratloopx/cli_runtime.py:308recognizesheartbeat-promptand loads the existing registrar instead of duplicating its flags. A parse failure still reaches the full parser's canonical diagnostics._dispatch_common_commandatloopx/cli_runtime.py:407is the shared post-parse boundary. It importssupport_control_heartbeatonly for valid heartbeat calls and passes the original registry-routing fact throughregistry_was_supplied.handle_heartbeat_prompt_commandatloopx/cli_commands/support_control_heartbeat.py:30retains registered-agent validation, runtime alias checks, bootstrap behavior, context defaults, error recovery and thin projections while continuing to delegate decisions and effects to existing owners.handle_support_control_commandatloopx/cli_commands/support_control.py:204no longer retains a parallel heartbeat branch; the public support/control registrar remains the compatibility entrypoint for all other commands.- The mainline quota presentation assertion is retained in
examples/cli-control-plane-command-modularization-smoke.py; the rebase did not overwrite the newer owner-location check.
语义与 CI 对齐
No new state vocabulary, permission or default is added. The cold help path loads only the selected parser, while valid thin and bootstrap paths load the extracted handler after parse. The semantic-vocabulary and output-budget smokes pass, and the budget expectations used by the changed tests match the current heartbeat budget owner.
对主干的风险 / Risks
The strongest regression scenario is a selected parser accepting syntax or returning recovery output that differs from the full CLI. Negative cases cover missing options, abbreviations, mutually exclusive flags, unknown profiles, invalid formats, conflicting context roots, missing registry/Goal/Agent, capture refusal and native-hook incompatibility; selected and full commands are compared without normalizing stdout, stderr or exit status.
The second risk is masking the loading win by deleting prompt guidance. The handler body is moved rather than shortened, real File/SQLite guard/selection/reentry/settlement paths remain covered, and the three cold-process isolation tests assert both the absence of unrelated modules and the absence of subprocess/network events. These tests establish the local loading invariant, not end-to-end model adherence or package-size qualification.
Exact-head validation passed 326 tests with 5 expected native-Codex skips using pytest -q -n auto --dist loadfile. The same command took 16:34 serially and 3:22 in parallel, without changing test inputs or assertions. Ruff, Python compilation, diff hygiene, the changed-line semantic advisory, public-boundary scan and standard premerge (9/9, including output-budget and maintainability smokes) passed. Remote CI remains a separate merge-readiness gate.
我的整体评价 / Verdict
The requested CLI loading outcome is achieved within a reversible application-layer change. Repeated heartbeat wakes reuse the canonical parser/dispatcher and avoid unrelated imports while preserving the existing prompt contract, failure recovery and authority boundaries. Long-horizon work is improved through lower per-wake overhead; the user-facing CLI journey remains familiar and faster rather than adding a new configuration step.
The future-facing refactor opportunity was applied: one existing registrar, one common dispatcher, one extracted handler owner and deletion of the old branch. A broader command migration, additional abstraction or prompt compaction would be unrelated to this demonstrated problem. Visual review is not applicable because this is a CLI-only loading change.
Residual risk is limited to the unverified live-host/package and model-adoption boundaries and to remote CI finishing independently. No blocking code or semantic finding remains.
English verdict: APPROVE — 4f9a2e5. The heartbeat command uses the existing selected parser and shared dispatcher, preserves public behavior and authority, keeps the current mainline quota assertion, and passes 326 tests, 9 premerge checks and the required cold-process isolation cases.
|
Self-merge decision for exact head The rebase resolved the quota presentation smoke conflict without dropping main's newer The owner explicitly directed self-merge without depending on hosted CI results. Hosted checks remain queued and are recorded as intentionally pending rather than claimed green. Local exact-head evidence covers the changed CLI loading invariant; package distribution, installed-host startup and live-model adoption remain outside this slice. Merge authority: maintainer self-merge authorization for #7704. |
heartbeat-promptpreviously built the complete CLI and loaded unrelated chat, dashboard and status-server modules on every wake. Route it through the existing selected parser and the common dispatcher, and move its existing handler into a focused CLI transport module. The canonical registrar, recovery output, registry routing, machine-context defaults and typed decision owners are retained.The validation changes exercise the shipped entrypoint for real File/SQLite prompt, guard and settlement paths, add parser/output parity and cold-process loading regressions, and update two obsolete module-location entrypoints. The adjacent refactor pass reused the command registrar and dispatcher and deleted the old handler branch; no compatibility wrapper or new capability was needed.
Validation on head
4f9a2e50ea4fd7201e68e0f0f7e21bfe1192770fagainst currentmain186582b30c306559398a653e964a33bd6e43f135:QUOTA_PRESENTATION_MODULEassertion. The final seven-file diff contains no accidental deletion of newer mainline checks.326 passed, 5 skippedusingpytest -q -n auto --dist loadfile. The five skips require an explicitly configured native Codex loopback environment. The same suite took16:34serially and3:22withloadfileparallelism, without changing inputs or assertions.help,thinandbootstrapavoidloopx.cliand unrelated services and emit no subprocess/socket audit event. Real File/SQLite guard, selection, reentry and one-spend settlement paths remain covered.9/9checks with zero failures, warnings or manual holds.Author startup measurements on macOS / Python 3.12.13, two warmups and nine alternating baseline/candidate pairs per case; each invocation starts a fresh Python process with warm filesystem caches, synthetic state, explicit context off and usage telemetry disabled:
Thin prompt LoopX imports fell from 1,151 to 213; help imports fell from 1,147 to 26. A separate instrumented thin invocation observed peak RSS of 84.6 MB vs 36.0 MB and file opens of 1,323 vs 304, with zero child-process/network events for both.
This qualifies the heartbeat CLI loading seam only. Minimal/standard distribution qualification, installed-package startup, live model adoption and managed-task throughput remain separate RFC milestones.