88import hashlib
99import shlex
1010import json
11+ import re
1112import shutil
1213import sys
1314from 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+
106214def _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
0 commit comments