Skip to content

Commit 37067ba

Browse files
committed
feat: make the complete work contract the quota default
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent d519e98 commit 37067ba

20 files changed

Lines changed: 655 additions & 314 deletions

‎docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,37 @@ unbound request keeps its original readiness route without inventing a Turn.
2020
This is a bounded Host handoff repair, not C1 cutover, installed adoption or
2121
qualification of model cost and long-horizon benefit.
2222

23-
The source already shares more than the output names suggest. `_emit_quota_result`
24-
captures the complete decision **before** `_project_quota_cli_payload` chooses
25-
ordinary CLI compaction or `buildTurnEnvelope`. The latter delegates to the
26-
TypeScript owner; its Python module is a transport adapter. Both quota capture
27-
and Turn journal capture call `write_decision_capture` in
23+
The ordinary CLI cutover composes every decided `quota should-run` through the
24+
existing TypeScript `composeCompleteTurnDecision` owner **before** capture.
25+
Default calls and the compatibility aliases `--turn-envelope` / `--complete-turn`
26+
share this source. Explicit context-delivery off returns that complete source
27+
inline; it does not choose an older format or enable progressive delivery.
28+
Full Goal material is collected independently of that presentation choice.
29+
The active CLI selection between its compactor and `buildTurnEnvelope` is
30+
removed. Status, plan and scheduler-observation retain their separate purposes;
31+
historical readers and other remaining callers are not retired by this slice.
32+
Both quota capture and Turn journal capture call `write_decision_capture` in
2833
[`decision_capture.py`](../../../../loopx/control_plane/turn_driver/decision_capture.py).
2934
Native context delivery and explicit host handoff also reuse that module and
3035
the existing context-delivery owner. C1 must converge the remaining composition
3136
and consumer assumptions, rather than introduce another capture service or
32-
rewrite already shared delta/native-resume logic.
37+
rewrite already shared delta/native-resume logic. When an original capture is
38+
requested, its advertised `detail_ref.full_decision` uses the existing immutable
39+
reader sidecar. The route is signed before capture and its final byte digest is
40+
published afterward, avoiding a circular self-hash. Reader publication failure
41+
retains the committed source and receipt; reads never re-admit or settle work.
42+
43+
The same frozen `ef099ae3` small/crowded/multi-agent quota fixtures measure
44+
JSON characters **23,289/42,965/25,514 → 24,984/53,441/29,574** and Markdown
45+
**7,476/8,143/6,441 → 25,083/53,543/29,674**. Full Goal bytes previously required
46+
a separate read, and the complete Markdown carrier preserves all source fields.
47+
These are stdout measurements, not model cost, latency or accepted-outcome
48+
results. Keep the original 25k/51k/26.5k JSON and 10k/17k/7k Markdown ceiling
49+
failures. The bounded new ceilings are 26k/55k/31k for either format; line limits
50+
stay unchanged. Crowded-minus-small JSON growth is 19,676 → 28,457 characters:
51+
the per-Todo allowance becomes 600 while the fixed 9,700 allowance is unchanged.
52+
This engineering calibration does not waive the independent matched single-session
53+
outcome/full-cost gate, other Hosts, packaging, installed adoption or native Windows.
3354

3455
Optional host polling is part of that original observation. The source-fidelity
3556
slice records `--record-host-poll` once before capture and reuses its receipt in

‎docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,31 @@ Turn 的 ready 决策。Host 将该原件交给既有 saved-capture 展示/reade
1414
readiness 路径,不补造 Turn。这只是有界的 Host 交接修复,不代表 C1 切换、已安装
1515
采用,或模型费用与长程收益已取得资格。
1616

17-
源码实际共享的部分比输出名称体现的更多。`_emit_quota_result` 在
18-
`_project_quota_cli_payload` 选择普通 CLI 压缩或 `buildTurnEnvelope` **之前**,
19-
已经捕获完整决策。后者委托 TypeScript owner,Python 模块是传输 adapter。
17+
普通 CLI 切换让每个已形成决策的 `quota should-run` 在 capture **之前**复用既有
18+
TypeScript `composeCompleteTurnDecision` owner。默认调用及兼容别名
19+
`--turn-envelope` / `--complete-turn` 使用同一来源。显式关闭 context delivery 时,
20+
完整来源以内联形式返回,不选择旧格式,也不打开渐进交付;完整 Goal 材料的取得与
21+
此展示选择分开。CLI 中选择 compactor 或 `buildTurnEnvelope` 的活跃分支删除。
22+
Status、plan 与 scheduler-observation 保留各自用途;本切片不退役历史 reader 或
23+
其他剩余调用方。
2024
Quota capture 与 Turn journal capture 都调用
2125
[`decision_capture.py`](../../../../loopx/control_plane/turn_driver/decision_capture.py)
2226
中的 `write_decision_capture`。原生上下文交付与显式宿主 handoff 也复用该模块和既有
2327
context-delivery owner。C1 应收敛剩余的组合逻辑与消费者假设,不另建 capture service,
24-
也不重写已经共享的差分与 native-resume 逻辑。
28+
也不重写已经共享的差分与 native-resume 逻辑。请求保存原 capture 时,公布的
29+
`detail_ref.full_decision` 复用既有不可变 reader sidecar:先将路由纳入签名,再在
30+
capture 发布后写入最终字节摘要,避免循环自哈希。Reader 发布失败仍保留已提交
31+
来源和回执;读取不重新准入或结算工作。
32+
33+
同一份冻结的 `ef099ae3` small/crowded/multi-agent quota fixture,JSON 字符数为
34+
**23,289/42,965/25,514 → 24,984/53,441/29,574**,Markdown 为
35+
**7,476/8,143/6,441 → 25,083/53,543/29,674**。完整 Goal 字节此前需要另行读取,
36+
完整 Markdown carrier 现保留所有来源字段。这些只是 stdout 测量,不代表模型费用、
37+
时延或验收成果。保留原 JSON 25k/51k/26.5k 与 Markdown 10k/17k/7k 上限失败。
38+
新有界上限两种格式均为 26k/55k/31k,行数限制不变。Crowded 减 small 的 JSON
39+
增长为 19,676 → 28,457 字符:每 Todo 允许量调整为 600,固定 9,700 允许量不变。
40+
此工程校准不豁免独立的匹配单会话成果/完整成本 gate、其他 Host、打包、安装采用
41+
或原生 Windows 验收。
2542

2643
可选 host poll 也是该次原始观测的一部分。来源保真切片在 capture 前仅记录一次
2744
`--record-host-poll`,普通 CLI、envelope 与原生上下文交付复用同一回执;恢复读取不再

‎examples/cli-control-plane-command-modularization-smoke.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def assert_source_shape() -> None:
6464
assert_contains(todo_text, "render_todo_markdown", "todo module")
6565
assert_contains(todo_text, "append_cli_rollout_event", "todo module")
6666
assert_contains(quota_text, "from .quota_presentation import", "quota module")
67-
assert_contains(quota_presentation_text, "render_quota_should_run_markdown", "quota presentation")
67+
assert_contains(quota_presentation_text, "render_turn_context_markdown", "quota presentation")
6868
assert_contains(quota_text, "append_cli_rollout_event", "quota module")
6969

7070

‎examples/control_plane/cli-output-probe-runner.py‎

Lines changed: 126 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import hashlib
99
import shlex
1010
import json
11+
import re
1112
import shutil
1213
import sys
1314
from pathlib import Path
@@ -103,6 +104,113 @@ def _turn_plan_control_observation(value: Any, *, goal_state: dict[str, str] | N
103104

104105

105106

107+
def _quota_control_observation(value: Any, *, goal_state: dict[str, str] | None = None) -> dict[str, Any] | None:
108+
"""Observe the same current controls in the two declared quota carriers.
109+
110+
This is a frozen fixture oracle, not full-source parity or an authority
111+
decoder. Compare original values, including read/settlement prose; the
112+
complete-source and real recovery suites retain their separate coverage.
113+
"""
114+
if not isinstance(value, dict) or value.get("mode") != "should-run":
115+
return None
116+
version = value.get("schema_version")
117+
if version not in {None, "loopx_turn_envelope_v0", "loopx_turn_envelope_v1"}:
118+
return None
119+
if version == "loopx_turn_envelope_v1":
120+
from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision
121+
assert_complete_turn_decision(value)
122+
legacy = version == "loopx_turn_envelope_v0"
123+
channel = value["action"] if legacy else value["interaction_contract"]["agent_channel"]
124+
cli = value["writeback"] if legacy else value["interaction_contract"]["cli_channel"]
125+
capsule = value["contract_capsule"] if legacy else value
126+
boundary = value["boundary"] if legacy else value["goal_boundary"]
127+
selected = channel.get("selected_todo") if legacy else value.get("selected_todo")
128+
selection = None
129+
if isinstance(selected, dict):
130+
selection = {key: selected.get(key) for key in (
131+
"todo_id", "priority", "status", "task_class", "action_kind", "claimed_by",
132+
)}
133+
# The historical codec's exact, local text reference is not a new
134+
# selection. Unknown references must not be silently treated as text.
135+
if legacy and "text_ref" in selected:
136+
assert selected["text_ref"] == "action.recommended_action"
137+
selection["text"] = channel["recommended_action"]
138+
else:
139+
selection["text"] = selected.get("text")
140+
user = value["user"] if legacy else value["interaction_contract"]["user_channel"]
141+
reads = value["required_reads"] if legacy else channel["required_reads"]
142+
if goal_state is not None:
143+
goal_read = {"command": goal_state["command"], "source": "goal_state", "ordering": "before_work",
144+
"reason": "Read full Goal intent, acceptance, stops. No summaries; failed/changed sources need a fresh guard."}
145+
reads = [row for row in reads if row != goal_read]
146+
controls = {
147+
"goal_id": value["goal_id"],
148+
"agent_id": value["agent_id"] if legacy else value["agent_identity"]["agent_id"],
149+
"decision": value["decision"], "should_run": value["should_run"],
150+
"effective_action": value["effective_action"], "selected_todo": selection,
151+
"execution": {key: channel[key] for key in ("must_attempt", "delivery_allowed", "quiet_noop_allowed")},
152+
"boundary": {key: boundary[key] for key in ("write_scope", "stop_condition", "rule")},
153+
"required_reads": {"pending": reads, "goal_material": goal_state},
154+
"next_cli_actions": cli["next_cli_actions"],
155+
"spend": {key: cli[key] for key in ("spend_allowed_now", "spend_after_validation", "spend_policy")},
156+
"work_lane_contract": capsule["work_lane_contract"],
157+
"execution_obligation": capsule["execution_obligation"],
158+
"execution_profile": capsule["execution_profile"], "task_scope": capsule["task_scope"],
159+
"replan_action_packet": value.get("replan_action_packet"),
160+
"notify": user["notify"], "user_action_required": user["action_required"],
161+
"scheduler_action": value["scheduler"]["action"] if legacy else value["scheduler_hint"]["action"],
162+
}
163+
def digest(child):
164+
return hashlib.sha256(json.dumps(child, ensure_ascii=False,
165+
sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
166+
return {"source_schema": version, "controls_sha256": digest(controls),
167+
"field_sha256": {key: digest(child) for key, child in controls.items()}}
168+
169+
170+
def _quota_markdown_field_observations(text: str) -> dict[str, str]:
171+
"""Read the five scalar controls printed by the historical fixture renderer.
172+
173+
Legacy narrative is not a complete source. Its paired JSON supplies the
174+
remaining fixture controls only after these actually printed values match.
175+
These observations never classify a live request or operator's authority.
176+
"""
177+
values: dict[str, Any] = {}
178+
for field in ("goal_id", "decision", "should_run", "effective_action"):
179+
matches = re.findall(rf"^- {field}: `([^`\n]*)`$", text, re.MULTILINE)
180+
if len(matches) != 1:
181+
return {}
182+
values[field] = matches[0]
183+
if values["should_run"] not in {"True", "False"}:
184+
return {}
185+
values["should_run"] = values["should_run"] == "True"
186+
actors = re.findall(r"^- agent_id: `([^`\n]*)`$", text, re.MULTILINE)
187+
actors += re.findall(r"^- agent_identity: agent_id=(\S+) agent_model=\S+$", text, re.MULTILINE)
188+
if len(actors) != 1:
189+
return {}
190+
values["agent_id"] = actors[0]
191+
return {key: hashlib.sha256(json.dumps(child, ensure_ascii=False,
192+
sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
193+
for key, child in values.items()}
194+
195+
196+
def _quota_goal_material(source: dict) -> dict[str, str] | None:
197+
"""Compare delivered full bytes with the original fixture's pending cat."""
198+
channel = source.get("action") if source.get("schema_version") == "loopx_turn_envelope_v0" else source.get("interaction_contract", {}).get("agent_channel", {})
199+
reads = source.get("required_reads", []) if source.get("schema_version") == "loopx_turn_envelope_v0" else channel.get("required_reads", [])
200+
for row in channel.get("work_context", {}).get("sources", []):
201+
content = row.get("content", {})
202+
if row.get("source") == "goal_state" and content.get("full_source") is True:
203+
revision = "sha256:" + hashlib.sha256(content["text"].encode("utf-8")).hexdigest()
204+
assert revision == content["revision"] and row["ordering"] == "before_work"
205+
return {"command": row["command"], "ordering": row["ordering"], "revision": revision}
206+
for row in reads:
207+
words = shlex.split(row.get("command", ""))
208+
if row.get("source") == "goal_state" and row.get("ordering") == "before_work" and words[:2] == ["cat", "--"] and len(words) == 3:
209+
return {"command": row["command"], "ordering": row["ordering"],
210+
"revision": "sha256:" + hashlib.sha256(Path(words[2]).read_bytes()).hexdigest()}
211+
return None
212+
213+
106214
def _receipt_row(
107215
*,
108216
semantics: ModuleType,
@@ -119,6 +227,11 @@ def _receipt_row(
119227
output_contract_version: str | None = None,
120228
) -> dict:
121229
payload = measurement.get("resolved_payload", measurement.get("payload"))
230+
quota_source = payload
231+
if surface_id == "quota_should_run" and payload is None and "```json\n" in text:
232+
decoded = json.loads(text.split("```json\n", 1)[1].split("\n```", 1)[0])
233+
quota_source = decoded if decoded.get("schema_version") == "loopx_turn_envelope_v1" else None
234+
quota_material = _quota_goal_material(quota_source) if surface_id == "quota_should_run" and isinstance(quota_source, dict) else None
122235
plan, material, detail_cost = payload, None, None
123236
if isinstance(plan, dict) and plan.get("schema_version") == "loopx_turn_plan_v1":
124237
if "detail_ref" in plan:
@@ -147,7 +260,9 @@ def _receipt_row(
147260
"scenario": scenario,
148261
"format": output_format,
149262
"qualification_policy": qualification_policy,
150-
"output_contract_version": output_contract_version,
263+
"output_contract_version": ("loopx_turn_envelope_v1" if surface_id == "quota_should_run"
264+
and isinstance(quota_source, dict) and quota_source.get("schema_version") == "loopx_turn_envelope_v1"
265+
else output_contract_version),
151266
"chars": measurement["chars"],
152267
"utf8_bytes": measurement["utf8_bytes"],
153268
"lines": measurement["lines"],
@@ -165,6 +280,10 @@ def _receipt_row(
165280
"markdown_headings": semantics.markdown_headings(text),
166281
"markdown_anchor": markdown_anchor,
167282
"turn_plan_controls": _turn_plan_control_observation(plan, goal_state=material),
283+
**({"quota_controls": _quota_control_observation(quota_source, goal_state=quota_material)}
284+
if surface_id == "quota_should_run" and isinstance(quota_source, dict) else {}),
285+
**({"quota_markdown_fields": _quota_markdown_field_observations(text)}
286+
if surface_id == "quota_should_run" and output_format == "markdown" and quota_source is None else {}),
168287
**({"inspection_source_read": detail_cost} if detail_cost is not None else {}),
169288
"action_signature_sha256": (
170289
semantics.action_signature_semantic_sha256(payload)
@@ -212,7 +331,8 @@ def _receipt_row(
212331
else []
213332
),
214333
"projection_envelope_schema_versions": (
215-
semantics.projection_envelope_schema_versions(payload if isinstance(payload, dict) else text)
334+
semantics.projection_envelope_schema_versions(quota_source if surface_id == 'quota_should_run'
335+
and isinstance(quota_source, dict) else payload if isinstance(payload, dict) else text)
216336
),
217337
"todo_work_counts_schema_versions": (
218338
semantics.todo_work_counts_schema_versions(payload)
@@ -239,6 +359,10 @@ def _link_turn_warning_basis(rows: list[dict]) -> list[dict]:
239359
paired = by_id.get(row["row_id"].removesuffix("markdown") + "json")
240360
if paired is not None:
241361
row["turn_envelope_cost_basis"] = paired["continuation_instructions"]
362+
visible, controls = row.get("quota_markdown_fields"), paired.get("quota_controls")
363+
if visible and controls:
364+
assert all(controls["field_sha256"].get(key) == digest for key, digest in visible.items()), "Markdown quota controls differ from paired JSON"
365+
row["quota_controls"] = controls
242366
return rows
243367

244368

‎examples/control_plane/quota-scheduler-registry-route-smoke.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,10 @@ def main() -> None:
112112
"external_write",
113113
"--codex-app-current-rrule",
114114
"FREQ=MINUTELY;INTERVAL=3",
115-
"--turn-envelope",
116115
cwd=project,
117116
)
118-
ack_cli_args = decision["scheduler"]["codex_app"]["ack_cli_args"]
117+
assert decision["schema_version"] == "loopx_turn_envelope_v1", decision
118+
ack_cli_args = decision["scheduler_hint"]["app_automation"]["ack_hint"]["cli_args"]
119119
assert ack_cli_args[:4] == [
120120
"--registry",
121121
str(global_registry.resolve()),
@@ -148,7 +148,7 @@ def main() -> None:
148148
"--codex-app",
149149
cwd=project,
150150
)
151-
stateful = follow_up["scheduler_hint"]["codex_app"]["stateful_backoff"]
151+
stateful = follow_up["scheduler_hint"]["app_automation"]["stateful_backoff"]
152152
assert stateful["state_status"] == "same_identity", follow_up
153153

154154
print("quota scheduler registry route smoke passed")

‎loopx/cli_commands/quota.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
from ..usage_goal import observe_quota_result as observe_quota_result # noqa: PLC0414
1818
from .quota_capture import handle_native_context_command, prepare_quota_capture
1919
from .quota_presentation import (
20-
_compose_explicit_turn_context as _compose_explicit_turn_context,
2120
_project_native_cli_settlement as _project_native_cli_settlement,
2221
_project_quota_cli_payload as _project_quota_cli_payload,
2322
_quota_renderer as _quota_renderer,

0 commit comments

Comments
 (0)