Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,56 @@ unbound request keeps its original readiness route without inventing a Turn.
This is a bounded Host handoff repair, not C1 cutover, installed adoption or
qualification of model cost and long-horizon benefit.

The source already shares more than the output names suggest. `_emit_quota_result`
captures the complete decision **before** `_project_quota_cli_payload` chooses
ordinary CLI compaction or `buildTurnEnvelope`. The latter delegates to the
TypeScript owner; its Python module is a transport adapter. Both quota capture
and Turn journal capture call `write_decision_capture` in
The ordinary CLI cutover composes every decided `quota should-run` through the
existing TypeScript `composeCompleteTurnDecision` owner **before** capture.
Default calls and the compatibility aliases `--turn-envelope` / `--complete-turn`
share this source. Explicit context-delivery off returns that complete source
inline; it does not choose an older format or enable progressive delivery.
Full Goal material is collected independently of that presentation choice.
The active CLI selection between its compactor and `buildTurnEnvelope` is
removed. Status, plan and scheduler-observation retain their separate purposes;
historical readers and other remaining callers are not retired by this slice.
The current model-behavior portfolio also composes its should-run inputs through
this complete-source owner; it no longer exercises the retired CLI compactor as
the product default. Candidate context, planning relations, task continuation and
diagnostics stay intact. The crowded regression's pretty JSON changes from
86,172 compact bytes to 121,318 complete bytes (120,963 source bytes); its old
90,000-byte compact-output allowance characterizes the historical fixture, not
the new full carrier. Wire/page limits and the terminal actor's ten-call budget
do not change. Frozen raw/v0 model comparison controls remain separate.

Todo completion, replan-successor return and blocked-completion recovery use the
existing TypeScript settlement composer for their current continuation plans.
They retain the original identity, route and supplied lease proof. JSON and
Markdown expose the runtime-owned debit with writeback, without a second model
spend command. The current terminal qualifier verifies committed receipts for
that original effect and rejects missing, foreign, unknown or uncommitted
receipts and duplicate model spend. A post-effect command failure still stops
the actor; independently committed writeback/debit receipts are not rolled back
or reported as absent. Historical plan rendering/decoding remains supported;
these engineering checks do not establish live-model adoption or cost benefit.
Both quota capture and Turn journal capture call `write_decision_capture` in
[`decision_capture.py`](../../../../loopx/control_plane/turn_driver/decision_capture.py).
Native context delivery and explicit host handoff also reuse that module and
the existing context-delivery owner. C1 must converge the remaining composition
and consumer assumptions, rather than introduce another capture service or
rewrite already shared delta/native-resume logic.
rewrite already shared delta/native-resume logic. When an original capture is
requested, its advertised `detail_ref.full_decision` uses the existing immutable
reader sidecar. The route is signed before capture and its final byte digest is
published afterward, avoiding a circular self-hash. Reader publication failure
retains the committed source and receipt; reads never re-admit or settle work.

The same frozen `ef099ae3` small/crowded/multi-agent quota fixtures measure
JSON characters **23,289/42,965/25,514 → 24,984/53,441/29,574** and Markdown
**7,476/8,143/6,441 → 25,083/53,543/29,674**. Full Goal bytes previously required
a separate read, and the complete Markdown carrier preserves all source fields.
These are stdout measurements, not model cost, latency or accepted-outcome
results. Keep the original 25k/51k/26.5k JSON and 10k/17k/7k Markdown ceiling
failures. The bounded new ceilings are 26k/55k/31k for either format; line limits
stay unchanged. Crowded-minus-small JSON growth is 19,676 → 28,457 characters:
the per-Todo allowance becomes 600 while the fixed 9,700 allowance is unchanged.
This engineering calibration does not waive the independent matched single-session
outcome/full-cost gate, other Hosts, packaging, installed adoption or native Windows.

Optional host polling is part of that original observation. The source-fidelity
slice records `--record-host-poll` once before capture and reuses its receipt in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,45 @@ Turn 的 ready 决策。Host 将该原件交给既有 saved-capture 展示/reade
readiness 路径,不补造 Turn。这只是有界的 Host 交接修复,不代表 C1 切换、已安装
采用,或模型费用与长程收益已取得资格。

源码实际共享的部分比输出名称体现的更多。`_emit_quota_result` 在
`_project_quota_cli_payload` 选择普通 CLI 压缩或 `buildTurnEnvelope` **之前**,
已经捕获完整决策。后者委托 TypeScript owner,Python 模块是传输 adapter。
普通 CLI 切换让每个已形成决策的 `quota should-run` 在 capture **之前**复用既有
TypeScript `composeCompleteTurnDecision` owner。默认调用及兼容别名
`--turn-envelope` / `--complete-turn` 使用同一来源。显式关闭 context delivery 时,
完整来源以内联形式返回,不选择旧格式,也不打开渐进交付;完整 Goal 材料的取得与
此展示选择分开。CLI 中选择 compactor 或 `buildTurnEnvelope` 的活跃分支删除。
Status、plan 与 scheduler-observation 保留各自用途;本切片不退役历史 reader 或
其他剩余调用方。
当前 model-behavior portfolio 的 should-run 输入也复用该完整来源 owner,不再把
已退役 CLI compactor 当作产品默认路径。候选上下文、规划关系、任务续接与诊断事实
保留。Crowded 回归的 pretty JSON 从压缩后的 86,172 字节变为完整的 121,318 字节
(原来源 120,963 字节);旧 90,000 字节压缩输出允许量只刻画历史 fixture,不约束
新的完整 carrier。Wire/page 上限和终态 actor 的十次调用预算不变。冻结的 raw/v0
模型对照继续独立保留。

Todo 验收完成、replan-successor 返回及 blocked-completion 恢复的当前续接计划复用
既有 TypeScript 结算 composer,保留原身份、路由与已提供的 lease 证明。JSON 与
Markdown 展示随写回执行的运行时扣额,不再要求模型执行第二条 spend 命令。
当前终态 qualifier 校验原 effect 的已提交回执,拒绝缺失、其他身份、未知或未提交
的回执及模型重复 spend。副作用之后的命令失败仍停止 actor;独立提交的写回/扣额
回执不回滚,也不能报告为不存在。历史 plan 展示/解码继续支持;这些工程检查
不代表真实模型采用或成本收益。
Quota capture 与 Turn journal capture 都调用
[`decision_capture.py`](../../../../loopx/control_plane/turn_driver/decision_capture.py)
中的 `write_decision_capture`。原生上下文交付与显式宿主 handoff 也复用该模块和既有
context-delivery owner。C1 应收敛剩余的组合逻辑与消费者假设,不另建 capture service,
也不重写已经共享的差分与 native-resume 逻辑。
也不重写已经共享的差分与 native-resume 逻辑。请求保存原 capture 时,公布的
`detail_ref.full_decision` 复用既有不可变 reader sidecar:先将路由纳入签名,再在
capture 发布后写入最终字节摘要,避免循环自哈希。Reader 发布失败仍保留已提交
来源和回执;读取不重新准入或结算工作。

同一份冻结的 `ef099ae3` small/crowded/multi-agent quota fixture,JSON 字符数为
**23,289/42,965/25,514 → 24,984/53,441/29,574**,Markdown 为
**7,476/8,143/6,441 → 25,083/53,543/29,674**。完整 Goal 字节此前需要另行读取,
完整 Markdown carrier 现保留所有来源字段。这些只是 stdout 测量,不代表模型费用、
时延或验收成果。保留原 JSON 25k/51k/26.5k 与 Markdown 10k/17k/7k 上限失败。
新有界上限两种格式均为 26k/55k/31k,行数限制不变。Crowded 减 small 的 JSON
增长为 19,676 → 28,457 字符:每 Todo 允许量调整为 600,固定 9,700 允许量不变。
此工程校准不豁免独立的匹配单会话成果/完整成本 gate、其他 Host、打包、安装采用
或原生 Windows 验收。

可选 host poll 也是该次原始观测的一部分。来源保真切片在 capture 前仅记录一次
`--record-host-poll`,普通 CLI、envelope 与原生上下文交付复用同一回执;恢复读取不再
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def assert_source_shape() -> None:
assert_contains(todo_text, "render_todo_markdown", "todo module")
assert_contains(todo_text, "append_cli_rollout_event", "todo module")
assert_contains(quota_text, "from .quota_presentation import", "quota module")
assert_contains(quota_presentation_text, "render_quota_should_run_markdown", "quota presentation")
assert_contains(quota_presentation_text, "render_turn_context_markdown", "quota presentation")
assert_contains(quota_text, "append_cli_rollout_event", "quota module")


Expand Down
128 changes: 126 additions & 2 deletions examples/control_plane/cli-output-probe-runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import hashlib
import shlex
import json
import re
import shutil
import sys
from pathlib import Path
Expand Down Expand Up @@ -103,6 +104,113 @@ def _turn_plan_control_observation(value: Any, *, goal_state: dict[str, str] | N



def _quota_control_observation(value: Any, *, goal_state: dict[str, str] | None = None) -> dict[str, Any] | None:
"""Observe the same current controls in the two declared quota carriers.

This is a frozen fixture oracle, not full-source parity or an authority
decoder. Compare original values, including read/settlement prose; the
complete-source and real recovery suites retain their separate coverage.
"""
if not isinstance(value, dict) or value.get("mode") != "should-run":
return None
version = value.get("schema_version")
if version not in {None, "loopx_turn_envelope_v0", "loopx_turn_envelope_v1"}:
return None
if version == "loopx_turn_envelope_v1":
from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision
assert_complete_turn_decision(value)
legacy = version == "loopx_turn_envelope_v0"
channel = value["action"] if legacy else value["interaction_contract"]["agent_channel"]
cli = value["writeback"] if legacy else value["interaction_contract"]["cli_channel"]
capsule = value["contract_capsule"] if legacy else value
boundary = value["boundary"] if legacy else value["goal_boundary"]
selected = channel.get("selected_todo") if legacy else value.get("selected_todo")
selection = None
if isinstance(selected, dict):
selection = {key: selected.get(key) for key in (
"todo_id", "priority", "status", "task_class", "action_kind", "claimed_by",
)}
# The historical codec's exact, local text reference is not a new
# selection. Unknown references must not be silently treated as text.
if legacy and "text_ref" in selected:
assert selected["text_ref"] == "action.recommended_action"
selection["text"] = channel["recommended_action"]
else:
selection["text"] = selected.get("text")
user = value["user"] if legacy else value["interaction_contract"]["user_channel"]
reads = value["required_reads"] if legacy else channel["required_reads"]
if goal_state is not None:
goal_read = {"command": goal_state["command"], "source": "goal_state", "ordering": "before_work",
"reason": "Read full Goal intent, acceptance, stops. No summaries; failed/changed sources need a fresh guard."}
reads = [row for row in reads if row != goal_read]
controls = {
"goal_id": value["goal_id"],
"agent_id": value["agent_id"] if legacy else value["agent_identity"]["agent_id"],
"decision": value["decision"], "should_run": value["should_run"],
"effective_action": value["effective_action"], "selected_todo": selection,
"execution": {key: channel[key] for key in ("must_attempt", "delivery_allowed", "quiet_noop_allowed")},
"boundary": {key: boundary[key] for key in ("write_scope", "stop_condition", "rule")},
"required_reads": {"pending": reads, "goal_material": goal_state},
"next_cli_actions": cli["next_cli_actions"],
"spend": {key: cli[key] for key in ("spend_allowed_now", "spend_after_validation", "spend_policy")},
"work_lane_contract": capsule["work_lane_contract"],
"execution_obligation": capsule["execution_obligation"],
"execution_profile": capsule["execution_profile"], "task_scope": capsule["task_scope"],
"replan_action_packet": value.get("replan_action_packet"),
"notify": user["notify"], "user_action_required": user["action_required"],
"scheduler_action": value["scheduler"]["action"] if legacy else value["scheduler_hint"]["action"],
}
def digest(child):
return hashlib.sha256(json.dumps(child, ensure_ascii=False,
sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
return {"source_schema": version, "controls_sha256": digest(controls),
"field_sha256": {key: digest(child) for key, child in controls.items()}}


def _quota_markdown_field_observations(text: str) -> dict[str, str]:
"""Read the five scalar controls printed by the historical fixture renderer.

Legacy narrative is not a complete source. Its paired JSON supplies the
remaining fixture controls only after these actually printed values match.
These observations never classify a live request or operator's authority.
"""
values: dict[str, Any] = {}
for field in ("goal_id", "decision", "should_run", "effective_action"):
matches = re.findall(rf"^- {field}: `([^`\n]*)`$", text, re.MULTILINE)
if len(matches) != 1:
return {}
values[field] = matches[0]
if values["should_run"] not in {"True", "False"}:
return {}
values["should_run"] = values["should_run"] == "True"
actors = re.findall(r"^- agent_id: `([^`\n]*)`$", text, re.MULTILINE)
actors += re.findall(r"^- agent_identity: agent_id=(\S+) agent_model=\S+$", text, re.MULTILINE)
if len(actors) != 1:
return {}
values["agent_id"] = actors[0]
return {key: hashlib.sha256(json.dumps(child, ensure_ascii=False,
sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
for key, child in values.items()}


def _quota_goal_material(source: dict) -> dict[str, str] | None:
"""Compare delivered full bytes with the original fixture's pending cat."""
channel = source.get("action") if source.get("schema_version") == "loopx_turn_envelope_v0" else source.get("interaction_contract", {}).get("agent_channel", {})
reads = source.get("required_reads", []) if source.get("schema_version") == "loopx_turn_envelope_v0" else channel.get("required_reads", [])
for row in channel.get("work_context", {}).get("sources", []):
content = row.get("content", {})
if row.get("source") == "goal_state" and content.get("full_source") is True:
revision = "sha256:" + hashlib.sha256(content["text"].encode("utf-8")).hexdigest()
assert revision == content["revision"] and row["ordering"] == "before_work"
return {"command": row["command"], "ordering": row["ordering"], "revision": revision}
for row in reads:
words = shlex.split(row.get("command", ""))
if row.get("source") == "goal_state" and row.get("ordering") == "before_work" and words[:2] == ["cat", "--"] and len(words) == 3:
return {"command": row["command"], "ordering": row["ordering"],
"revision": "sha256:" + hashlib.sha256(Path(words[2]).read_bytes()).hexdigest()}
return None


def _receipt_row(
*,
semantics: ModuleType,
Expand All @@ -119,6 +227,11 @@ def _receipt_row(
output_contract_version: str | None = None,
) -> dict:
payload = measurement.get("resolved_payload", measurement.get("payload"))
quota_source = payload
if surface_id == "quota_should_run" and payload is None and "```json\n" in text:
decoded = json.loads(text.split("```json\n", 1)[1].split("\n```", 1)[0])
quota_source = decoded if decoded.get("schema_version") == "loopx_turn_envelope_v1" else None
quota_material = _quota_goal_material(quota_source) if surface_id == "quota_should_run" and isinstance(quota_source, dict) else None
plan, material, detail_cost = payload, None, None
if isinstance(plan, dict) and plan.get("schema_version") == "loopx_turn_plan_v1":
if "detail_ref" in plan:
Expand Down Expand Up @@ -147,7 +260,9 @@ def _receipt_row(
"scenario": scenario,
"format": output_format,
"qualification_policy": qualification_policy,
"output_contract_version": output_contract_version,
"output_contract_version": ("loopx_turn_envelope_v1" if surface_id == "quota_should_run"
and isinstance(quota_source, dict) and quota_source.get("schema_version") == "loopx_turn_envelope_v1"
else output_contract_version),
"chars": measurement["chars"],
"utf8_bytes": measurement["utf8_bytes"],
"lines": measurement["lines"],
Expand All @@ -165,6 +280,10 @@ def _receipt_row(
"markdown_headings": semantics.markdown_headings(text),
"markdown_anchor": markdown_anchor,
"turn_plan_controls": _turn_plan_control_observation(plan, goal_state=material),
**({"quota_controls": _quota_control_observation(quota_source, goal_state=quota_material)}
if surface_id == "quota_should_run" and isinstance(quota_source, dict) else {}),
**({"quota_markdown_fields": _quota_markdown_field_observations(text)}
if surface_id == "quota_should_run" and output_format == "markdown" and quota_source is None else {}),
**({"inspection_source_read": detail_cost} if detail_cost is not None else {}),
"action_signature_sha256": (
semantics.action_signature_semantic_sha256(payload)
Expand Down Expand Up @@ -212,7 +331,8 @@ def _receipt_row(
else []
),
"projection_envelope_schema_versions": (
semantics.projection_envelope_schema_versions(payload if isinstance(payload, dict) else text)
semantics.projection_envelope_schema_versions(quota_source if surface_id == 'quota_should_run'
and isinstance(quota_source, dict) else payload if isinstance(payload, dict) else text)
),
"todo_work_counts_schema_versions": (
semantics.todo_work_counts_schema_versions(payload)
Expand All @@ -239,6 +359,10 @@ def _link_turn_warning_basis(rows: list[dict]) -> list[dict]:
paired = by_id.get(row["row_id"].removesuffix("markdown") + "json")
if paired is not None:
row["turn_envelope_cost_basis"] = paired["continuation_instructions"]
visible, controls = row.get("quota_markdown_fields"), paired.get("quota_controls")
if visible and controls:
assert all(controls["field_sha256"].get(key) == digest for key, digest in visible.items()), "Markdown quota controls differ from paired JSON"
row["quota_controls"] = controls
return rows


Expand Down
Loading
Loading