PeterXie666 commited on
Commit
a1dba15
·
verified ·
1 Parent(s): 14f5a5b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_lh_order_dispatch.py +73 -0
  2. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/rpent_player.sh +23 -0
  3. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/validate_parts_cart_isolated.py +54 -0
  4. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
  5. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +14 -0
  6. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +27 -0
  7. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json +15 -0
  8. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/outcome_audit.py +52 -0
  9. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/summarize_lh_order_dispatch.py +39 -0
  10. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/trajectory.py +86 -0
  11. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gpt_batch.py +192 -0
  12. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/outcome_audit.py +52 -0
  13. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/audit_subagent.py +130 -0
  14. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/mismatch_plan.py +149 -0
  15. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/start_real_session.sh +30 -0
  16. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/trace_gpt_html.py +118 -0
  17. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/__init__.py +1 -0
  18. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json +15 -0
  19. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json +15 -0
  20. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +23 -0
  21. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json +23 -0
  22. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +18 -0
  23. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/tasks/l4_fit.py +574 -0
  24. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/scripts/agent_viewer/viewer.html +111 -0
  25. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/sensenova.py +24 -0
  26. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/api_batch.py +704 -0
  27. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_breakfast_geometry.py +41 -0
  28. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py +57 -0
  29. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_compound_public.py +19 -0
  30. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_desk_mechanisms.py +20 -0
  31. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py +138 -0
  32. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/compound_thumbnails.py +10 -0
  33. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/feedback_ladder.py +428 -0
  34. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/gpt_batch.py +192 -0
  35. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/gpt_player.py +20 -0
  36. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/gptpolicy_player.sh +37 -0
  37. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/ladder_plan.py +120 -0
  38. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/layer4_plan.py +174 -0
  39. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/make_dossier.py +103 -0
  40. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/make_video.py +132 -0
  41. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/qwen_vl_server.py +535 -0
  42. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/real_check_driver.py +163 -0
  43. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/record_compound_remaining.py +62 -0
  44. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/summarize.py +33 -0
  45. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/validate.py +79 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/release/image_stats.json +1387 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/evaluation_tool_caps.json +5 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +23 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_lh_order_dispatch.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small physical development check; no agent/API calls. Every case starts from a reset.
2
+ Oracle recovery is explicitly diagnostic, not learned behaviour.
3
+ """
4
+ import argparse,copy,json,sys,time
5
+ from pathlib import Path
6
+ from PIL import Image
7
+ import hashlib
8
+ from lffbench import envs
9
+ import numpy as np
10
+ from lffbench.tasks.lh_order_dispatch import OrderDispatch,PRODUCTS
11
+ from lffbench.tasks.l3_card_edge import CardEdge
12
+ from lffbench.tasks.l7_offcenter_push import OffcenterPush
13
+ p=argparse.ArgumentParser();p.add_argument('--seeds',default='1000,1001,1002');p.add_argument('--cases',default='baseline,oracle_all,L1,L3,L5,combined_recovery');p.add_argument('--out',required=True);a=p.parse_args()
14
+ source=Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()
15
+ code_sha256=hashlib.sha256(source).hexdigest()
16
+ Path(a.out).parent.mkdir(exist_ok=True,parents=True)
17
+ Path(a.out).with_suffix('.source.py').write_bytes(source)
18
+ task=OrderDispatch(cam_res=512);rows=[]
19
+ def capture(label):
20
+ dest=Path(a.out).parent/(Path(a.out).stem+'_frames')/f'{seed}_{case}_{label}.png';dest.parent.mkdir(exist_ok=True)
21
+ Image.fromarray(envs.render(task.env,res=512)).save(dest)
22
+ return dict(path=str(dest.resolve()),sim_step=task.sk.n_steps)
23
+
24
+ for seed in map(int,a.seeds.split(',')):
25
+ for case in a.cases.split(','):
26
+ inst=task.sample_instance(seed);inst['mechanisms']={x:case in ('oracle_all','combined_recovery') or x==case for x in ['L1','L3','L5']};task.reset_instance(inst)
27
+ frames=[capture('initial')]
28
+ base_move=task.sk.move_to
29
+ captured_l5=[False]
30
+ def observed_move(*args,**kwargs):
31
+ result=base_move(*args,**kwargs)
32
+ if task.sk.box_moves and task.sk.box_moves[-1].get('bad') and task.mon['loaded'] and not task.sk.box_moves[-1].get('gripper_open') and not captured_l5[0]:
33
+ frames.append(capture('L5_failure'));captured_l5[0]=True
34
+ return result
35
+ task.sk.move_to=observed_move
36
+ try:
37
+ failure=None
38
+ if case in ('baseline','oracle_all'):
39
+ task.execute(inst,task.oracle_params(inst))
40
+ elif case=='L1':
41
+ task.load_product(PRODUCTS[0],0);failure=copy.deepcopy(task.outcome(inst))
42
+ frames.append(capture('L1_failure'));measured=failure['l1_attempts'][0]['approach_offset'];task.execute(inst,dict(mode='oracle',correction=[*measured,0],c=0.))
43
+ elif case=='L3':
44
+ for k,o in enumerate(PRODUCTS):task.load_product(o,k)
45
+ CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'));failure=copy.deepcopy(task.outcome(inst))
46
+ CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10)
47
+ if all(task.in_cargo(o) for o in task.mon['states']):OffcenterPush.execute(task,inst,dict(c=0.))
48
+ pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8)
49
+ elif case=='combined_recovery':
50
+ task.load_product(PRODUCTS[0],0);frames.append(capture('L1_failure'));failure=copy.deepcopy(task.outcome(inst))
51
+ estimate=np.array([*failure['l1_attempts'][0]['approach_offset'],0.]);task.sk.correction=estimate
52
+ for k,o in enumerate(PRODUCTS):
53
+ task.load_product(o,k)
54
+ estimate+=np.array([*task.mon['l1_attempts'][-1]['approach_offset'],0.]);task.sk.correction=estimate.copy()
55
+ CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'))
56
+ CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10)
57
+ if all(task.in_cargo(o) for o in task.mon['states']):
58
+ OffcenterPush.adaptive_attempt(task,inst,0.)
59
+ if not task.in_cargo('card_1'):task.repair_card()
60
+ pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8)
61
+ else:
62
+ # Original corrector takes its estimate only from observed pushes, not hidden com_offset.
63
+ task.execute(inst,dict(mode='adaptive',c=0.))
64
+ out=task.outcome(inst);frames.append(capture('final'))
65
+ trigger=(not failure['l1_attempts'][0]['held'] if case=='L1' else
66
+ not any(c['held'] for c in failure['card_closes'] if c['card_on_board'] and c['overhang']<=0) if case=='L3' else
67
+ out['l5_triggered'] if case=='L5' else None)
68
+ diagnostics=dict(L1=bool(out['l1_attempts'] and not out['l1_attempts'][0]['held']),L3=any(c['card_on_board'] and c['overhang']<=.001 and abs(c['local'][0])<.05 and abs(c['local'][1])<.05 and c['tips_above_card']<.02 and not c['held'] for c in out['card_closes']),L5=out['l5_triggered'])
69
+ row=dict(seed=seed,case=case,diagnostics=diagnostics,mechanisms=inst['mechanisms'],triggered=trigger,recovered=out['success'],before_recovery=failure,outcome=out,frames=frames)
70
+ except Exception as e:
71
+ row=dict(seed=seed,case=case,error=repr(e))
72
+ assert hashlib.sha256(Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest()==code_sha256,'source changed during run'
73
+ rows.append(row);Path(a.out).write_text(json.dumps(dict(code_sha256=code_sha256,rows=rows),indent=2));print(seed,case,{k:row.get(k) for k in ('triggered','recovered','error')},flush=True)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/rpent_player.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run one RPent (Harness VLA framework) agent on an LFF-Bench robot_server session.
3
+ # usage: scripts/rpent_player.sh <run log dir>/session.json [--model gpt-6-astra] [--effort medium] [--max-turns 400] ...
4
+ # Start a v2 session first (the RPent robot `lffbench` speaks interface v2 only), e.g.:
5
+ # LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10330 direct 3 rpent rgb 1
6
+ # RPent checkout with the LFF-Bench robot (`lffbench`, planner `api`): integrations/rpent/setup.sh puts it in
7
+ # third_party/rpent with its venv in third_party/rpent/.venv (override: RPENT_DIR / RPENT_VENV, e.g. in env.local.sh).
8
+ # API key / endpoint: OPENAI_API_KEY / OPENAI_BASE_URL from the environment or from .env (LFF_ENV_FILE).
9
+ # Writes into the session's log dir: rpent_transcript.jsonl (every model request/response, images as file refs),
10
+ # final_report.md, rpent_result.json, rpent_player.log and rpent/ (RPent's own run.log / transcript / step artifacts).
11
+ set -e
12
+ [ -f "$1" ] || { echo "usage: $0 <session.json> [player args]"; exit 2; }
13
+ SESSION=$(readlink -f "$1"); shift
14
+ LOG=$(dirname "$SESSION")
15
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
16
+ [ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh"
17
+ RPENT=${RPENT_DIR:-$ROOT/third_party/rpent}
18
+ VENV=${RPENT_VENV:-$RPENT/.venv}
19
+ ENVF=${LFF_ENV_FILE:-$ROOT/.env}
20
+ [ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; }
21
+ cd "$RPENT"
22
+ PYTHONPATH="$RPENT" "$VENV/bin/python" -m robots.lffbench.player --session "$SESSION" "$@" 2>&1 | tee -a "$LOG/rpent_player.log"
23
+ exit "${PIPESTATUS[0]}"
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/validate_parts_cart_isolated.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Development physical validation; no model API, no pose injection after reset."""
2
+ import argparse,copy,json,time,hashlib
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from PIL import Image
6
+ from lffbench.tasks.lh_parts_cart import PartsCart
7
+ from lffbench import envs
8
+
9
+ def main():
10
+ p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args()
11
+ out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
12
+ x=PartsCart(cam_res=512);rows=[]
13
+ def clean(obj):
14
+ if isinstance(obj,np.ndarray):return obj.tolist()
15
+ if isinstance(obj,np.generic):return obj.item()
16
+ raise TypeError(type(obj).__name__)
17
+ for seed in a.seeds:
18
+ i=x.sample_instance(seed)
19
+ if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']}
20
+ x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r)
21
+ def snap(label):
22
+ o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q)
23
+ r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve())))
24
+ (out/'results.json').write_text(json.dumps(rows,indent=2,default=clean))
25
+ print(seed,label,o['success'],o['traps'],o['stages'],flush=True)
26
+ snap('initial')
27
+ if a.case=='oracle':
28
+ x.execute(i,x.oracle_params(i));snap('oracle_final');continue
29
+ if a.case in ['combined','l4']:
30
+ x.tool_push_out();snap('L4_blocked')
31
+ x.tool_push_front();snap('L4_retrieved')
32
+ x.load(careful=a.case not in ['combined','l2']);snap('loaded')
33
+ if a.case in ['l4','l5']:
34
+ x.repair_load();snap('loading_prerequisite_repaired')
35
+ if a.case in ['combined','l2']:
36
+ x.repair_load();snap('L2_restored')
37
+ if all(x.cargo_ok(j) for j in range(2)):
38
+ if a.case in ['combined','l5']:
39
+ # First full naive push, then reuse correction loop without its initial push.
40
+ x.transport(0.,False);snap('L5_naive_push')
41
+ x._transport_only=True
42
+ # Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged.
43
+ original=x.execute
44
+ x.execute=lambda inst,params:None
45
+ try:
46
+ from lffbench.tasks.l7_offcenter_push import OffcenterPush
47
+ OffcenterPush.adaptive_attempt(x,i,0.)
48
+ finally:x.execute=original;x._transport_only=False
49
+ snap('L5_corrected')
50
+ else:x.transport(i['com_offset'] if i['traps']['L5'] else 0.,False)
51
+ x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final')
52
+ x.env.close()
53
+ (out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2))
54
+ if __name__=='__main__':main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-opus-5-5|high",
3
+ "fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6",
4
+ "written": "2026-10-20 02:16:17",
5
+ "summary": {
6
+ "system_chars": 6048,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-opus-5-5"
14
+ }
15
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "embodied_evo_codex-generic-646620c9aa77|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
4
+ "written": "2026-10-25 04:39:36",
5
+ "summary": {
6
+ "report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json",
7
+ "checks": 10,
8
+ "framework": {
9
+ "commit": "470278c478bdb5e4b6f17dde1ea0393761f230f0",
10
+ "tree_sha256": "1aeeee06baa254fce963c153f883e3605180d0f39e06e5f8fd6ac15f3c10e0c1",
11
+ "workflow_sha256": "95bcf2e05ad493f808aa03aa6a17fc7c7c470a1c5a25075247b864c008132ba2"
12
+ }
13
+ }
14
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "rpent_codex-generic-9f0e3aafc10c|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9",
4
+ "written": "2026-10-24 07:27:13",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6.1-sol",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ },
22
+ "middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
23
+ "rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25",
24
+ "rpent_prefix_chars": 2789,
25
+ "anchor_status": "match"
26
+ }
27
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-flash|high",
3
+ "fingerprint_sha256": "189cde183af8b300854d48b4f8952a6ebdf53462343e87c0062ad4c761943d9c",
4
+ "written": "2026-10-30 15:54:07",
5
+ "summary": {
6
+ "system_chars": 6047,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "deepseek-flash"
14
+ }
15
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/outcome_audit.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit, hash-bound adjudications; no keyword inference from agent prose.
2
+
3
+ The original evaluator is retained for comparisons. A reviewed verdict requires
4
+ the identical source files and a successful first attempt. Unreviewed successes
5
+ stay S? in audit mode, including legacy CS based only on absent trap counters.
6
+ """
7
+ import hashlib
8
+ import json
9
+ from pathlib import Path
10
+
11
+
12
+ def sha256(path):
13
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
14
+
15
+
16
+ def load_audit(path):
17
+ data = json.loads(Path(path).read_text())
18
+ if data.get("schema") != "lff-outcome-audit-1":
19
+ raise ValueError("Unsupported outcome audit schema")
20
+ result = {}
21
+ for entry in data["entries"]:
22
+ key = (entry["batch"], entry["run_id"])
23
+ if key in result:
24
+ raise ValueError(f"Duplicate audit entry: {key}")
25
+ if entry["verdict"] not in ("CS", "IR", "S?"):
26
+ raise ValueError(f"Invalid audit verdict: {key}")
27
+ if entry.get("attempt", 1) != 1:
28
+ raise ValueError(f"Audit entry must refer to attempt 1: {key}")
29
+ if not entry.get("basis") or not entry.get("sources"):
30
+ raise ValueError(f"Missing basis/source binding: {key}")
31
+ if entry["verdict"] == "IR" and not all(entry.get(k) for k in ("failure", "repair")):
32
+ raise ValueError(f"IR requires physical failure and agent repair evidence: {key}")
33
+ if entry["verdict"] == "CS" and entry.get("coverage") != "all_recorded_commands":
34
+ raise ValueError(f"CS requires full command review: {key}")
35
+ result[key] = entry
36
+ return result
37
+
38
+
39
+ def adjudicate(audit, batch, run, first_success):
40
+ entry = audit.get((batch, run["id"]))
41
+ if entry is None:
42
+ return "S?", "No reviewed evidence for this successful first attempt."
43
+ if not first_success or entry["task"] != run["task"] or entry["seed"] != run["seed"]:
44
+ raise ValueError("Audit does not match the run / first-attempt success")
45
+ root = Path(run["log"]).resolve()
46
+ if "events.jsonl" not in entry["sources"]:
47
+ raise ValueError("Audit must bind events.jsonl")
48
+ for name, digest in entry["sources"].items():
49
+ path = (root / name).resolve()
50
+ if not path.is_relative_to(root) or sha256(path) != digest:
51
+ raise ValueError(f"Audit source changed or escaped run directory: {name}")
52
+ return entry["verdict"], entry["basis"]
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/summarize_lh_order_dispatch.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assert the final scoped development results. Does not run simulation."""
2
+ from pathlib import Path
3
+ import hashlib,json
4
+ root=Path(__file__).resolve().parents[1]
5
+ p=root/'results/lh_order_dispatch/development_20261102/accepted_development'
6
+ d=json.loads((p/'physical_checks.json').read_text())
7
+ source_sha=hashlib.sha256((root/'lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest()
8
+ assert d['code_sha256']==source_sha
9
+ assert hashlib.sha256((p/'physical_checks.source.py').read_bytes()).hexdigest()==source_sha
10
+ assert len(d['rows'])==6
11
+ for row in d['rows']:
12
+ assert not row.get('error'),row
13
+ assert row['recovered'] is True,(row['seed'],row['case'])
14
+ out=row['outcome']
15
+ assert out['success'] and out['static'] and out['upright'] and not out['touching'] and not out['departed_unloaded']
16
+ assert out['commands']<=180 and out['sim_s']<=540
17
+ if row['case']=='combined_recovery':
18
+ assert all(row['diagnostics'].values()),(row['seed'],row['diagnostics'])
19
+ first=out['l1_attempts'][0]
20
+ assert not first['held'] and sum(v*v for v in first['offset'])**.5>.025
21
+ assert any(c['card_on_board'] and c['overhang']<=.001 and abs(c['local'][0])<.05 and abs(c['local'][1])<.05 and c['tips_above_card']<.02 and not c['held'] for c in out['card_closes'])
22
+ assert any(m.get('bad') and not m.get('gripper_open') and m['step']>=out['load_step'] for m in out['box_moves'])
23
+ steps=[x['sim_step'] for x in row['frames']]
24
+ assert len(steps)==5 and all(b>a for a,b in zip(steps,steps[1:])),steps
25
+ h=json.loads((p/'headroom_n3.json').read_text())
26
+ assert h['n']==3 and h['k']==5
27
+ assert (p/'headroom_n3.sha256').read_text().split()[0]==source_sha
28
+ assert hashlib.sha256((p/'headroom_n3.source.py').read_bytes()).hexdigest()==source_sha
29
+ summary=dict(code_sha256=source_sha,physical_cases=6,physical_successes=6,
30
+ oracle_all_completed=3,combined_three_trigger_and_completion=3,
31
+ max_commands=max(r['outcome']['commands'] for r in d['rows']),max_sim_s=max(r['outcome']['sim_s'] for r in d['rows']),
32
+ headroom_n3_k5=h['succ_at_k'],
33
+ limitations=['Three development seeds, fixed layout and signed hidden parameters; not n>=20 acceptance.',
34
+ 'Scripted references use privileged scene measurements. Adaptive calibrates L1/steers L5 from measured residuals, but card edge subpolicy is predesigned.',
35
+ 'Combined diagnostic deliberately attempts direct card grasp before switching, with real failed-close evidence.',
36
+ 'Not RGB/F1 model-learning results; task is not in the 34-task main evaluation set.'],
37
+ physical_evidence=str(p/'physical_checks.json'),headroom_evidence=str(p/'headroom_n3.json'))
38
+ (p/'summary.json').write_text(json.dumps(summary,indent=2)+'\n')
39
+ print(json.dumps(summary,indent=2))
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/trajectory.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unified trajectory (minimal, field names follow Harbor's ATIF where there is one).
2
+
3
+ <log_dir>/trajectory.jsonl, one JSON object per line:
4
+ line 1 {"kind": "header", "schema": "lff-traj-0", "atif_like": "ATIF v1.x field names", "session_id",
5
+ "agent": {"name", "version", "model_name", "effort"}, "tools": [...], "source": "<native log file>"}
6
+ steps {"kind": "step", "step_id", "timestamp", "source": "user"|"agent"|"system", "message",
7
+ "reasoning_content", "tool_calls": [{"tool_call_id", "function_name", "arguments"}],
8
+ "observation": {"results": [{"source_call_id", "content", "is_error", "images"}]},
9
+ "metrics": {"prompt_tokens", "completion_tokens", "cached_tokens", "cost_usd"}}
10
+ last {"kind": "final", "final_metrics": {"total_prompt_tokens", "total_completion_tokens",
11
+ "total_cached_tokens", "total_cost_usd", "total_steps"}, "exit_reason", "native_result"}
12
+ Not full ATIF: no per-step model name, no subagent trajectories, images only counted (bytes stay in the workspace).
13
+ Tool names are reported without the MCP prefix (robot / shell / view_images), so all harnesses line up.
14
+ """
15
+ import json
16
+ import os
17
+
18
+ SCHEMA = "lff-traj-0"
19
+
20
+
21
+ def strip_mcp(name):
22
+ for p in ("mcp__lff__", "lff."):
23
+ if name and name.startswith(p):
24
+ return name[len(p):]
25
+ return name
26
+
27
+
28
+ class TrajWriter:
29
+ def __init__(self, path):
30
+ self.path = path
31
+ self.steps = []
32
+ self.header = None
33
+ self.final = None
34
+
35
+ def set_header(self, **kw):
36
+ self.header = dict(kind="header", schema=SCHEMA, atif_like="field names follow Harbor ATIF", **kw)
37
+
38
+ def add_step(self, source, message="", reasoning="", tool_calls=None, timestamp=None, metrics=None, **extra):
39
+ st = dict(kind="step", step_id=len(self.steps) + 1, timestamp=timestamp, source=source, message=message or "",
40
+ reasoning_content=reasoning or "", tool_calls=tool_calls or [],
41
+ observation=dict(results=[]), metrics=metrics or {})
42
+ st.update(extra)
43
+ self.steps.append(st)
44
+ return st
45
+
46
+ def add_result(self, call_id, content, is_error=False, images=0):
47
+ for st in reversed(self.steps):
48
+ if any(tc["tool_call_id"] == call_id for tc in st["tool_calls"]):
49
+ st["observation"]["results"].append(dict(source_call_id=call_id, content=content, is_error=is_error,
50
+ images=images))
51
+ return True
52
+ return False
53
+
54
+ def set_final(self, exit_reason, native_result=None, **metrics):
55
+ fm = dict(total_prompt_tokens=0, total_completion_tokens=0, total_cached_tokens=0, total_cost_usd=None,
56
+ total_steps=len(self.steps))
57
+ fm.update({k: v for k, v in metrics.items() if v is not None})
58
+ self.final = dict(kind="final", final_metrics=fm, exit_reason=exit_reason, native_result=native_result)
59
+
60
+ def write(self):
61
+ with open(self.path, "w") as f:
62
+ for d in [self.header] + self.steps + [self.final]:
63
+ if d is not None:
64
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
65
+ return self.path
66
+
67
+ def tool_call_names(self):
68
+ return [tc["function_name"] for st in self.steps for tc in st["tool_calls"]]
69
+
70
+
71
+ def read(path):
72
+ with open(path) as f:
73
+ return [json.loads(line) for line in f if line.strip()]
74
+
75
+
76
+ def usage_summary(log_dir):
77
+ """Token / cost totals from trajectory.jsonl (None if missing)."""
78
+ p = os.path.join(log_dir or "", "trajectory.jsonl")
79
+ if not os.path.exists(p):
80
+ return None
81
+ rows = read(p)
82
+ fin = next((r for r in rows if r.get("kind") == "final"), None)
83
+ steps = [r for r in rows if r.get("kind") == "step" and r.get("source") == "agent"]
84
+ out = dict(calls=len(steps), exit_reason=(fin or {}).get("exit_reason"))
85
+ out.update((fin or {}).get("final_metrics") or {})
86
+ return out
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gpt_batch.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch of GPT-player runs on robot_server sessions (same sessions / README / images as the Claude players).
2
+
3
+ start python scripts/gpt_batch.py start --batch exp2 --model gpt-6-astra --perception rgb --video \
4
+ --tasks l1_bias_place:1000,1001 l5_slide_to_target:1000,1001 --port0 9710
5
+ -> one server + one gpt_player process per (task, seed); manifest at runs/gpt/<batch>/manifest.json
6
+ status python scripts/gpt_batch.py status --batch exp2
7
+ table python scripts/gpt_batch.py table --batch exp2
8
+ stop python scripts/gpt_batch.py stop --batch exp2 (stops the robot servers and any player still running)
9
+ """
10
+ import argparse
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+
16
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
18
+ from claude_batch import run_stats # noqa: E402
19
+
20
+ RUNS = os.path.join(ROOT, "runs", "gpt")
21
+ # OPENAI_API_KEY / OPENAI_BASE_URL: taken from this file if it exists (KEY=value lines), else from the environment
22
+ ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
23
+
24
+
25
+ def mpath(batch):
26
+ return os.path.join(RUNS, batch, "manifest.json")
27
+
28
+
29
+ def load(batch):
30
+ return json.load(open(mpath(batch)))
31
+
32
+
33
+ def save(batch, m):
34
+ os.makedirs(os.path.dirname(mpath(batch)), exist_ok=True)
35
+ json.dump(m, open(mpath(batch), "w"), indent=1)
36
+
37
+
38
+ def port_free(port):
39
+ import socket
40
+ with socket.socket() as so:
41
+ try:
42
+ so.bind(("127.0.0.1", port))
43
+ return True
44
+ except OSError:
45
+ return False
46
+
47
+
48
+ def cmd_start(a):
49
+ m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[])
50
+ used = {r["port"] for r in m["runs"]}
51
+ port = a.port0
52
+ env = dict(os.environ, LFF_RUNS_DIR=os.path.join(RUNS, a.batch), LFF_STYLE=a.style,
53
+ LFF_EXTRA_ARGS="--nominal" if a.nominal else "")
54
+ for spec in a.tasks:
55
+ task, seeds = spec.split(":")
56
+ for seed in seeds.split(","):
57
+ while port in used or not port_free(port):
58
+ port += 1
59
+ out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, seed, "full", a.feedback,
60
+ str(port), "direct", str(a.k), f"{a.batch}-{a.harness}" + ("-nominal" if a.nominal else ""), a.perception,
61
+ "1" if a.video else "0"], capture_output=True, text=True, env=env)
62
+ kv = dict(l.split("=", 1) for l in out.stdout.splitlines() if l.startswith(("SANDBOX=", "LOG=")))
63
+ if "LOG" not in kv:
64
+ print("server failed", task, seed, out.stdout[-500:], out.stderr[-500:])
65
+ continue
66
+ used.add(port)
67
+ log = kv["LOG"]
68
+ if a.harness == "gpt_player":
69
+ player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
70
+ f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
71
+ f"exec python scripts/gpt_player.py --session {log}/session.json --model {a.model} "
72
+ f"--effort {a.effort} --style {a.style} > {log}/gpt_player.log 2>&1")
73
+ elif a.harness == "rpent":
74
+ player = (f"bash {ROOT}/scripts/rpent_player.sh {log}/session.json --model {a.model} --effort {a.effort} "
75
+ f"> {log}/rpent_player.out 2>&1")
76
+ else: # gptpolicy
77
+ player = (f"GPTPOLICY_MODEL={a.model} GPTPOLICY_EFFORT={a.effort} GPTPOLICY_KEEP_SERVER=1 "
78
+ f"bash {ROOT}/scripts/gptpolicy_player.sh {log}/session.json > {log}/gptpolicy_player.out 2>&1")
79
+ # detach stdio: otherwise a player that does not exec keeps the caller's stdout pipe open and the
80
+ # caller (e.g. `gpt_batch.py start ... | grep`) blocks until the run ends
81
+ p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
82
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
83
+ r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, effort=a.effort, cond="harness",
84
+ rep=0, k=a.k, port=port, sandbox=kv["SANDBOX"], log=log, perception=a.perception, player_pid=p.pid,
85
+ harness=a.harness, style=a.style, nominal=a.nominal)
86
+ m["runs"].append(r)
87
+ print(json.dumps(dict(run=r["run"], pid=p.pid)), flush=True)
88
+ save(a.batch, m)
89
+
90
+
91
+ def cmd_status(a):
92
+ for r in load(a.batch)["runs"]:
93
+ tr = os.path.join(r["log"], "gpt_transcript.jsonl")
94
+ errs = 0
95
+ end = None
96
+ if os.path.exists(tr):
97
+ for l in open(tr):
98
+ d = json.loads(l)
99
+ errs += d["ev"] == "api_error"
100
+ if d["ev"] in ("end", "abort"):
101
+ end = d
102
+ ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
103
+ n = sum(1 for e in ev if e["ev"] == "call")
104
+ dones = [e for e in ev if e["ev"] == "done"]
105
+ alive = True
106
+ try:
107
+ os.kill(r["player_pid"], 0)
108
+ except (ProcessLookupError, KeyError, PermissionError):
109
+ alive = False
110
+ if end:
111
+ state = "END" if end["ev"] == "end" else "ABORT " + end.get("reason", "")
112
+ else:
113
+ state = "running" if alive else ("END" if dones and (dones[-1]["success"] or len(dones) >= r["k"]) else "ABORT player exited")
114
+ print(f"{r.get('harness', 'gpt_player'):10s} {r['task']:24s} s{r['seed']} cmds={n:3d} api_err={errs} "
115
+ f"attempts={[('S' if d['success'] else 'F') for d in dones]} {state}")
116
+
117
+
118
+ def cmd_table(a):
119
+ import collections
120
+ rows = []
121
+ for b in a.batch:
122
+ for r in load(b)["runs"]:
123
+ try:
124
+ st = run_stats(r)
125
+ except FileNotFoundError:
126
+ continue
127
+ rows.append(dict(r, **st, first_grasp=first_grasp(r), harness=r.get("harness", "gpt_player")))
128
+ lines = ["| harness | task | seed | attempts | first success | cmds | close_gripper (held / total) | think s/cmd | wall min |",
129
+ "|---|---|---|---|---|---|---|---|---|"]
130
+ for x in sorted(rows, key=lambda x: (x["task"], x["harness"], x["seed"])):
131
+ lines.append(f"| {x['harness']} | {x['task']} | {x['seed']} | {x['attempts']} | {x['first_success'] or '—'} | "
132
+ f"{x['n_calls']} | {x['first_grasp'][1]}/{x['first_grasp'][0]} | "
133
+ f"{(x['think_per_cmd'] or 0):.1f} | {(x['wall_s'] or 0) / 60:.1f} |")
134
+ by = collections.defaultdict(list)
135
+ for x in rows:
136
+ by[x["harness"]].append(x)
137
+ lines.append("")
138
+ for h, xs in sorted(by.items()):
139
+ n = len(xs)
140
+ g = [sum(x["first_grasp"][i] for x in xs) for i in (0, 1)]
141
+ lines.append(f"{h}: @1 = {sum(1 for x in xs if x['first_success'] == 1)}/{n}, "
142
+ f"@k = {sum(1 for x in xs if x['first_success'])}/{n}, close_gripper held {g[1]}/{g[0]}")
143
+ print("\n".join(lines))
144
+
145
+
146
+ def cmd_stop(a):
147
+ for r in load(a.batch)["runs"]:
148
+ pids = [r.get("player_pid")]
149
+ pf = os.path.join(r["log"], "server.pid")
150
+ if os.path.exists(pf):
151
+ pids.append(int(open(pf).read()))
152
+ for pid in pids:
153
+ if pid:
154
+ try:
155
+ os.kill(pid, 15) # SIGTERM: the server closes rollout.mp4 first
156
+ except (ProcessLookupError, PermissionError):
157
+ pass
158
+
159
+
160
+ def first_grasp(r):
161
+ """(close_gripper calls, of which ended holding an object) over the whole run."""
162
+ tot = held = 0
163
+ for l in open(os.path.join(r["log"], "events.jsonl")):
164
+ d = json.loads(l)
165
+ if d.get("ev") == "call" and d.get("cmd") == "close_gripper":
166
+ tot += 1
167
+ held += bool(d.get("report", {}).get("holding_object"))
168
+ return tot, held
169
+
170
+
171
+ def main():
172
+ ap = argparse.ArgumentParser()
173
+ sub = ap.add_subparsers(dest="cmd")
174
+ s = sub.add_parser("start")
175
+ s.add_argument("--batch", required=True); s.add_argument("--model", default="gpt-6-astra")
176
+ s.add_argument("--effort", default="medium"); s.add_argument("--tasks", nargs="+", required=True)
177
+ s.add_argument("--k", type=int, default=3); s.add_argument("--port0", type=int, default=9710)
178
+ s.add_argument("--perception", default="rgb", choices=["rgb", "depth", "rgbd"]); s.add_argument("--video", action="store_true")
179
+ s.add_argument("--harness", default="gpt_player", choices=["gpt_player", "rpent", "gptpolicy"])
180
+ s.add_argument("--style", default="v1", choices=["v1", "v2", "la"])
181
+ s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
182
+ s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"],
183
+ help="F1 = success/failure only (default since 2026-10-08); F2 = measured error, ablation only")
184
+ st = sub.add_parser("status"); st.add_argument("--batch", required=True)
185
+ t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True)
186
+ sp = sub.add_parser("stop"); sp.add_argument("--batch", required=True)
187
+ a = ap.parse_args()
188
+ dict(start=cmd_start, status=cmd_status, table=cmd_table, stop=cmd_stop)[a.cmd](a)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/outcome_audit.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit, hash-bound adjudications; no keyword inference from agent prose.
2
+
3
+ The original evaluator is retained for comparisons. A reviewed verdict requires
4
+ the identical source files and a successful first attempt. Unreviewed successes
5
+ stay S? in audit mode, including legacy CS based only on absent trap counters.
6
+ """
7
+ import hashlib
8
+ import json
9
+ from pathlib import Path
10
+
11
+
12
+ def sha256(path):
13
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
14
+
15
+
16
+ def load_audit(path):
17
+ data = json.loads(Path(path).read_text())
18
+ if data.get("schema") != "lff-outcome-audit-1":
19
+ raise ValueError("Unsupported outcome audit schema")
20
+ result = {}
21
+ for entry in data["entries"]:
22
+ key = (entry["batch"], entry["run_id"])
23
+ if key in result:
24
+ raise ValueError(f"Duplicate audit entry: {key}")
25
+ if entry["verdict"] not in ("CS", "IR", "S?"):
26
+ raise ValueError(f"Invalid audit verdict: {key}")
27
+ if entry.get("attempt", 1) != 1:
28
+ raise ValueError(f"Audit entry must refer to attempt 1: {key}")
29
+ if not entry.get("basis") or not entry.get("sources"):
30
+ raise ValueError(f"Missing basis/source binding: {key}")
31
+ if entry["verdict"] == "IR" and not all(entry.get(k) for k in ("failure", "repair")):
32
+ raise ValueError(f"IR requires physical failure and agent repair evidence: {key}")
33
+ if entry["verdict"] == "CS" and entry.get("coverage") != "all_recorded_commands":
34
+ raise ValueError(f"CS requires full command review: {key}")
35
+ result[key] = entry
36
+ return result
37
+
38
+
39
+ def adjudicate(audit, batch, run, first_success):
40
+ entry = audit.get((batch, run["id"]))
41
+ if entry is None:
42
+ return "S?", "No reviewed evidence for this successful first attempt."
43
+ if not first_success or entry["task"] != run["task"] or entry["seed"] != run["seed"]:
44
+ raise ValueError("Audit does not match the run / first-attempt success")
45
+ root = Path(run["log"]).resolve()
46
+ if "events.jsonl" not in entry["sources"]:
47
+ raise ValueError("Audit must bind events.jsonl")
48
+ for name, digest in entry["sources"].items():
49
+ path = (root / name).resolve()
50
+ if not path.is_relative_to(root) or sha256(path) != digest:
51
+ raise ValueError(f"Audit source changed or escaped run directory: {name}")
52
+ return entry["verdict"], entry["basis"]
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/audit_subagent.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit an isolated policy subagent: every tool call it made must stay inside its sandbox.
2
+
3
+ python scripts/audit_subagent.py <transcript.jsonl> <sandbox_dir> [--out audit.json]
4
+ Allowed: Bash `cd <sandbox> && ./robot ...` (or `<sandbox>/robot ...`); Read of <sandbox>/README.md or <sandbox>/obs/*.
5
+ With --la (LIBERO-Agent-style workspace): also Bash `cd <sandbox> && ./shell '<cmd>'` / `./shell <<'TAG' ... TAG` (the
6
+ command runs inside the jail; anything the OUTER shell would execute or expand is a violation), and Read / Write / Edit
7
+ of any file inside <sandbox>.
8
+ Everything else is reported as a violation. Prints counts + violations only (the transcript itself is large).
9
+ """
10
+ import argparse
11
+ import json
12
+ import re
13
+
14
+
15
+ def tool_uses(obj):
16
+ if isinstance(obj, dict):
17
+ if obj.get("type") == "tool_use" and "name" in obj:
18
+ yield obj
19
+ for v in obj.values():
20
+ yield from tool_uses(v)
21
+ elif isinstance(obj, list):
22
+ for v in obj:
23
+ yield from tool_uses(v)
24
+
25
+
26
+ def extra_shell_ops(cmd, sb):
27
+ """True if the command contains shell operators / substitutions outside quotes, apart from the
28
+ allowed leading `cd <sandbox> &&`."""
29
+ import shlex
30
+ body = re.sub(r"^\s*cd\s+%s\s*&&\s*" % re.escape(sb), "", cmd)
31
+ if "`" in body or "$(" in body:
32
+ return True
33
+ try:
34
+ lex = shlex.shlex(body, posix=True, punctuation_chars=True)
35
+ toks = list(lex)
36
+ except ValueError:
37
+ return True
38
+ return any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
39
+
40
+
41
+ def shell_call_ok(cmd, sb):
42
+ """la: `cd <sb> && ./shell ...` where nothing runs outside the jail: either one heredoc with a QUOTED tag (no outer
43
+ expansion) and nothing after it, or plain arguments without outer operators / substitutions."""
44
+ m = re.match(r"^\s*cd\s+%s\s*&&\s*(\./shell|%s/shell)(.*)$" % (re.escape(sb), re.escape(sb)), cmd, re.S)
45
+ if not m:
46
+ return False
47
+ rest = m.group(2)
48
+ s = rest.strip()
49
+ if rest[:1].isspace() and len(s) >= 2 and s[0] == "'" and s[-1] == "'" and "'" not in s[1:-1]:
50
+ return True # one single-quoted argument: the outer shell expands nothing (an inner `<<EOF` runs in the jail)
51
+ if "<<" in rest:
52
+ first, _, body = rest.partition("\n")
53
+ hm = re.match(r"^\s*<<-?\s*(['\"])(\w+)\1\s*$", first)
54
+ if not hm:
55
+ return False # unquoted tag: the outer shell would expand $(...) inside the heredoc
56
+ tag = hm.group(2)
57
+ lines = body.rstrip("\n").split("\n")
58
+ return bool(lines) and lines[-1].strip() == tag and tag not in [l.strip() for l in lines[:-1]]
59
+ if "`" in rest or "$(" in rest.replace("'", "\x00").split("\x00")[0::2].__str__():
60
+ return False
61
+ import shlex
62
+ try:
63
+ toks = list(shlex.shlex(rest, posix=True, punctuation_chars=True))
64
+ except ValueError:
65
+ return False
66
+ return not any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
67
+
68
+
69
+ def main():
70
+ ap = argparse.ArgumentParser()
71
+ ap.add_argument("transcript")
72
+ ap.add_argument("sandbox")
73
+ ap.add_argument("--out")
74
+ ap.add_argument("--la", action="store_true", help="LIBERO-Agent-style workspace: ./shell and workspace files allowed")
75
+ a = ap.parse_args()
76
+ sb = a.sandbox.rstrip("/")
77
+ ok_bash = re.compile(r"^\s*(cd\s+%s\s*&&\s*)?(\./robot|%s/robot)(\s|$)" % (re.escape(sb), re.escape(sb)))
78
+ seen, calls, viol = set(), [], []
79
+ injected = [] # context Claude Code attached on its own: the user's memory index / identity
80
+ with open(a.transcript) as f:
81
+ for line in f:
82
+ try:
83
+ rec = json.loads(line)
84
+ except ValueError:
85
+ continue
86
+ if rec.get("type") == "attachment":
87
+ at = rec.get("attachment", {})
88
+ if at.get("type") == "instructions":
89
+ for fi in at.get("files", []):
90
+ if "memory" in (fi.get("path") or "").lower() or fi.get("type") == "AutoMem":
91
+ injected.append(dict(kind="memory_index", path=fi.get("path"), chars=len(fi.get("content", ""))))
92
+ elif at.get("type") == "session_context":
93
+ injected.append(dict(kind="session_context", keys=sorted((at.get("context") or {}).keys())))
94
+ for tu in tool_uses(rec):
95
+ if tu.get("id") in seen:
96
+ continue
97
+ seen.add(tu.get("id"))
98
+ name, inp = tu["name"], tu.get("input", {})
99
+ calls.append(name)
100
+ if name == "SubagentHandback": # the final report back to the orchestrator
101
+ continue
102
+ if name == "Bash":
103
+ cmd = inp.get("command", "")
104
+ bad = (not ok_bash.match(cmd)) or extra_shell_ops(cmd, sb)
105
+ if bad and a.la and shell_call_ok(cmd, sb):
106
+ bad = False
107
+ if bad:
108
+ viol.append(dict(tool=name, command=cmd))
109
+ elif name in ("Read", "Write", "Edit") and a.la:
110
+ import os
111
+ p = os.path.normpath(inp.get("file_path", ""))
112
+ if not p.startswith(sb + "/"):
113
+ viol.append(dict(tool=name, path=inp.get("file_path", "")))
114
+ elif name == "Read":
115
+ p = inp.get("file_path", "")
116
+ if not (p == f"{sb}/README.md" or p.startswith(f"{sb}/obs/")):
117
+ viol.append(dict(tool=name, path=p))
118
+ else:
119
+ viol.append(dict(tool=name, input=json.dumps(inp)[:300]))
120
+ from collections import Counter
121
+ res = dict(n_calls=len(calls), by_tool=dict(Counter(calls)), n_violations=len(viol), violations=viol,
122
+ memory_injected=any(i["kind"] == "memory_index" for i in injected), injected=injected)
123
+ print(json.dumps(res, indent=1, ensure_ascii=False))
124
+ if a.out:
125
+ with open(a.out, "w") as f:
126
+ json.dump(res, f, indent=1, ensure_ascii=False)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/mismatch_plan.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol).
2
+
3
+ Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance
4
+ (Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed.
5
+ Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI:
6
+ tw_<m> twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the
7
+ mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_<m>), then give up.
8
+ do_<m> own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py)
9
+ dm_<m> mismatched record: history/ = the failed twin run. README byte-identical to do_<m>; only history/ differs.
10
+
11
+ python3 scripts/mismatch_plan.py own build own records + write <OUT>/<m>/own.json and tasks_<m>.txt
12
+ python3 scripts/mismatch_plan.py twin <m> build twin records from tw_<m> (+ tw2_<m>) -> <OUT>/<m>/twin.json;
13
+ prints the instances still without a failed twin run
14
+ python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first
15
+ memory-free retry (N2), Do, Dm, twin; totals and paired counts
16
+ -> <OUT>/report.json + markdown on stdout
17
+ """
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+
23
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
+ API = os.path.join(ROOT, "runs", "api")
25
+ OUT = os.path.join(API, "mismatch_20261027")
26
+ TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
27
+ "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"]
28
+ MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]}
29
+
30
+
31
+ def runs(batch):
32
+ return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
33
+
34
+
35
+ def attempt1(log):
36
+ for line in open(os.path.join(log, "events.jsonl")):
37
+ e = json.loads(line)
38
+ if e.get("ev") == "done" and e.get("attempt") == 1:
39
+ return e
40
+ return None
41
+
42
+
43
+ def dossier(log, out):
44
+ if not os.path.isdir(out):
45
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True,
46
+ capture_output=True)
47
+ return out
48
+
49
+
50
+ def cmd_own():
51
+ for m, batches in MAIN.items():
52
+ own, tasks = {}, []
53
+ for b in batches:
54
+ for r in runs(b):
55
+ if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done":
56
+ continue
57
+ d = attempt1(r["log"])
58
+ if d is None or d["success"]:
59
+ continue
60
+ key = f"{r['task']}:{r['seed']}"
61
+ own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}"))
62
+ tasks.append(key)
63
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
64
+ json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1)
65
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n")
66
+ print(m, len(tasks))
67
+
68
+
69
+ def cmd_twin(m):
70
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
71
+ twin = {}
72
+ for b in (f"tw_{m}", f"tw2_{m}"):
73
+ if not os.path.exists(os.path.join(API, b, "manifest.json")):
74
+ continue
75
+ for r in runs(b):
76
+ key = f"{r['task']}:{r['seed']}"
77
+ if key in twin or r["status"] != "done":
78
+ continue
79
+ d = attempt1(r["log"])
80
+ if d is not None and not d["success"]:
81
+ twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}"))
82
+ json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1)
83
+ print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin])))
84
+
85
+
86
+ # twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there
87
+ WEAK = {"l3_wall_flush", "l3_under_table_tool"}
88
+
89
+
90
+ def single(batch):
91
+ """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished."""
92
+ out = {}
93
+ if not os.path.exists(os.path.join(API, batch, "manifest.json")):
94
+ return out
95
+ for r in runs(batch):
96
+ if r["status"] == "done":
97
+ d = attempt1(r["log"])
98
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
99
+ return out
100
+
101
+
102
+ def main_rows(batches):
103
+ rows = {}
104
+ for b in batches:
105
+ tmp = os.path.join(OUT, f".oc_{b}.json")
106
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp],
107
+ check=True, capture_output=True)
108
+ for r in json.load(open(tmp))["rows"]:
109
+ rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"])
110
+ os.remove(tmp)
111
+ return rows
112
+
113
+
114
+ def cmd_report():
115
+ rep, md = {}, []
116
+ for m, batches in MAIN.items():
117
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
118
+ main = main_rows(batches)
119
+ do, dm = single(f"do_{m}"), single(f"dm_{m}")
120
+ t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists)
121
+ tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)}
122
+ rows = []
123
+ for k in want:
124
+ h, mf = main[k]["history"] or "", main[k]["memfree"] or ""
125
+ rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK,
126
+ H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None,
127
+ Do=do.get(k), Dm=dm.get(k), twin=tw.get(k)))
128
+ def rate(key, sub):
129
+ v = [r[key] for r in sub if r[key] is not None]
130
+ return f"{sum(v)}/{len(v)}" if v else "-"
131
+ both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None]
132
+ pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both),
133
+ dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both))
134
+ rep[m] = dict(rows=rows, pairs=pairs)
135
+ md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |",
136
+ "|---|---|---|---|---|---|"]
137
+ f = lambda v: "-" if v is None else ("S" if v else "F")
138
+ for r in rows:
139
+ md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |")
140
+ strong = [r for r in rows if not r["weak"]]
141
+ md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; "
142
+ f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; "
143
+ f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""]
144
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
145
+ print("\n".join(md))
146
+
147
+
148
+ if __name__ == "__main__":
149
+ {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/start_real_session.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as
3
+ # scripts/start_robot_session.sh (SANDBOX=, LOG=, <LOG>/session.json), so harness_run.py / api_player.py run on it unchanged.
4
+ # usage: scripts/start_real_session.sh <task> <seed> <memory full|none> <feedback F0|F1> <port> [instruction direct|indirect] [k] [tag]
5
+ # The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN.
6
+ # Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600).
7
+ set -e
8
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
9
+ TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}
10
+ RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
11
+ SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
12
+ LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN
13
+ mkdir -p "$SANDBOX" "$LOG"
14
+ cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
15
+ KARG=""; [ -n "$K" ] && KARG="--k $K"
16
+ nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
17
+ --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \
18
+ > "$LOG/server.log" 2>&1 &
19
+ echo $! > "$LOG/server.pid"
20
+ WAIT=${LFF_REAL_READY_WAIT:-3600}
21
+ for i in $(seq 1 "$WAIT"); do
22
+ [ -f "$LOG/READY" ] && break
23
+ kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break
24
+ [ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2
25
+ sleep 1
26
+ done
27
+ [ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; }
28
+ echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
29
+ echo "SANDBOX=$SANDBOX"
30
+ echo "LOG=$LOG"
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/trace_gpt_html.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render one GPT-player run as a self-contained HTML trace: the instructions and tool the model received,
2
+ every request's new content (text + images), the model's reasoning summaries and commands, every server
3
+ report, the server-side ground truth and the done verdicts. Optionally embeds the rollout video.
4
+
5
+ python scripts/trace_gpt_html.py --log runs/gpt/exp2/<run> --out traces/<name>.html [--title ...] [--video]
6
+ """
7
+ import argparse
8
+ import base64
9
+ import html
10
+ import json
11
+ import os
12
+
13
+ from trace_html import CSS
14
+
15
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
+
17
+
18
+ def esc(s):
19
+ return html.escape(str(s))
20
+
21
+
22
+ def img_tag(path):
23
+ if not os.path.exists(path):
24
+ return f"<span class='lbl'>[missing {esc(os.path.basename(path))}]</span>"
25
+ b = base64.b64encode(open(path, "rb").read()).decode()
26
+ return f"<img src='data:image/jpeg;base64,{b}' title='{esc(os.path.basename(path))}'>"
27
+
28
+
29
+ def main():
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("--log", required=True)
32
+ ap.add_argument("--out", required=True)
33
+ ap.add_argument("--title", default="")
34
+ ap.add_argument("--video", action="store_true", help="embed rollout.mp4 (base64)")
35
+ a = ap.parse_args()
36
+ sess = json.load(open(os.path.join(a.log, "session.json")))
37
+ sb = sess["sandbox"]
38
+ tp = os.path.join(a.log, "transcript.jsonl") # api_player; older gpt_player runs: gpt_transcript.jsonl
39
+ tr = [json.loads(l) for l in open(tp if os.path.exists(tp) else os.path.join(a.log, "gpt_transcript.jsonl"))]
40
+ ev = [json.loads(l) for l in open(os.path.join(a.log, "events.jsonl"))]
41
+ start = next(e for e in ev if e["ev"] == "session_start")
42
+ dones = [e for e in ev if e["ev"] == "done"]
43
+ http = [e for e in ev if e["ev"] == "http"]
44
+ asst = [d for d in tr if d["ev"] == "assistant"]
45
+ st = next(d for d in tr if d["ev"] == "start")
46
+ end = next((d for d in tr if d["ev"] in ("end", "abort")), {})
47
+ tot = end.get("usage_total") or {}
48
+
49
+ out = [f"<!doctype html><html lang='zh'><head><meta charset='utf-8'><meta name='viewport' "
50
+ f"content='width=device-width,initial-scale=1'><title>{esc(a.title or 'GPT trace')}</title>"
51
+ f"<style>{CSS}</style></head><body><h1>{esc(a.title or os.path.basename(a.log))}</h1><div class='card'><table>"]
52
+ rows = [("任务 / 种子", f"{start['task']} / {start['seed']}"), ("模型", f"{st['model']}(reasoning effort {st['effort']})"),
53
+ ("感知", start.get("perception", "depth") + "(rgb = 只有彩色图,没有深度工具)"),
54
+ ("结果", ";".join(f"第{d['attempt']}次 {'成功' if d['success'] else '失败'}" for d in dones) or "—"),
55
+ ("机器人命令数", sum(1 for e in ev if e["ev"] == "call")),
56
+ ("模型调用次数 / 平均每次延迟", f"{len(asst)} / {sum(d['latency_s'] for d in asst) / max(len(asst), 1):.1f} s"),
57
+ ("仿真执行总时长", f"{sum(h['server_s'] for h in http):.0f} s"),
58
+ ("token(输入 / 其中缓存 / 输出 / 其中推理)",
59
+ f"{tot.get('input_tokens', 0)} / {tot.get('cached_tokens', 0)} / {tot.get('output_tokens', 0)} / {tot.get('reasoning_tokens', 0)}")]
60
+ out += [f"<tr><th>{esc(k)}</th><td>{esc(v)}</td></tr>" for k, v in rows] + ["</table></div>"]
61
+ inst = {k: v for k, v in start["inst"].items()}
62
+ out.append("<div class='card'><div class='lbl'>服务端真值(模型从未看到)</div><pre>"
63
+ + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "</pre></div>")
64
+ if a.video and os.path.exists(os.path.join(a.log, "rollout.mp4")):
65
+ b = base64.b64encode(open(os.path.join(a.log, "rollout.mp4"), "rb").read()).decode()
66
+ out.append("<h2>录像(左:第三视角,右:腕部;3 倍速)</h2><video controls style='max-width:100%' "
67
+ f"src='data:video/mp4;base64,{b}'></video>")
68
+
69
+ out.append("<h2>1. 模型收到的系统指令和工具(原文,每次请求都一样)</h2>")
70
+ out.append("<div class='card'>这就是发给 GPT 的全部固定内容:沙箱 README 原文加一句开头说明,以及唯一的 robot 工具。"
71
+ "没有文件、记忆、深度、物体坐标。</div>")
72
+ out.append(f"<details class='card' open><summary>instructions({len(st['instructions'])} 字符)</summary><pre>{esc(st['instructions'])}</pre></details>")
73
+ out.append(f"<details class='card'><summary>tool</summary><pre>{esc(json.dumps(st['tool'], indent=1, ensure_ascii=False))}</pre></details>")
74
+
75
+ out.append("<h2>2. 逐步过程</h2>")
76
+ t0 = tr[0]["t"]
77
+ n = 0
78
+ for d in tr:
79
+ tt = f"+{d['t'] - t0:6.0f}s"
80
+ if d["ev"] == "user":
81
+ imgs = "".join(img_tag(os.path.join(sb, p)) for p in d.get("images", []))
82
+ out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>发给模型</span><pre>{esc(d['text'])}</pre>{imgs}</div>")
83
+ elif d["ev"] == "assistant":
84
+ blk = [f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>模型回复</span> "
85
+ f"<span class='lbl'>({d['latency_s']:.1f} s,输出 {d['usage'].get('output_tokens', 0)} token,"
86
+ f"其中推理 {d['usage'].get('reasoning_tokens', 0)})</span>"]
87
+ if d.get("reasoning_summary"):
88
+ blk.append(f"<div class='lbl think'>推理摘要(模型自己的思考摘要)</div><pre class='think'>{esc(d['reasoning_summary'])}</pre>")
89
+ if d.get("text"):
90
+ blk.append(f"<div class='lbl'>文字</div><pre>{esc(d['text'])}</pre>")
91
+ for c in d["tool_calls"]:
92
+ n += 1
93
+ blk.append(f"<div>#{n} <span class='cmd'>./robot {esc(c['arguments'].get('command', ''))}</span></div>")
94
+ out.append("".join(blk) + "</div>")
95
+ elif d["ev"] == "tool":
96
+ imgs = "".join(img_tag(os.path.join(sb, p)) for p in d.get("images", []))
97
+ txt = d["output"]
98
+ out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>服务器返回(作为工具结果发给模型)</span>"
99
+ f"<details {'open' if len(txt) < 1500 else ''}><summary>{len(txt)} 字符</summary><pre>{esc(txt)}</pre></details>"
100
+ + (f"<div class='lbl'>随后附上的图像</div>{imgs}" if imgs else "") + "</div>")
101
+ elif d["ev"] in ("api_error", "abort"):
102
+ out.append(f"<div class='card bad'>{esc(json.dumps(d, ensure_ascii=False))}</div>")
103
+ out.append("<h2>3. 服务端每次 done 的判定</h2>")
104
+ for e in dones:
105
+ out.append(f"<div class='card'>第 {e['attempt']} 次:<span class='{'ok' if e['success'] else 'bad'}'>"
106
+ f"{'成功' if e['success'] else '失败'}</span>(agent 的理由:{esc(e.get('reason', ''))})<pre>{esc(e.get('feedback', ''))}</pre></div>")
107
+ rep = os.path.join(a.log, "final_report.md")
108
+ if os.path.exists(rep):
109
+ out.append(f"<h2>4. 模型最后的报告</h2><div class='card'><pre>{esc(open(rep).read())}</pre></div>")
110
+ out.append("</body></html>")
111
+ os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
112
+ with open(a.out, "w") as f:
113
+ f.write("\n".join(out))
114
+ print(a.out, os.path.getsize(a.out), "bytes; commands", n)
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner."""
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-opus-5-5|high",
3
+ "fingerprint_sha256": "1e12511be3f4985ca25bad34cc2db4a0b317d6565b2d12034672aaac2d97bc85",
4
+ "written": "2026-10-21 05:19:32",
5
+ "summary": {
6
+ "system_chars": 5629,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-opus-5-5"
14
+ }
15
+ }
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-flash|high",
3
+ "fingerprint_sha256": "189cde183af8b300854d48b4f8952a6ebdf53462343e87c0062ad4c761943d9c",
4
+ "written": "2026-10-30 15:54:07",
5
+ "summary": {
6
+ "system_chars": 6047,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "deepseek-flash"
14
+ }
15
+ }
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
4
+ "written": "2026-10-26 07:02:41",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6.1-sol",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-v4.1-flash|high",
3
+ "fingerprint_sha256": "52d7de20832981196514c20e91635e50a2dc6241fa45a1bbfd863d08dc8cc740",
4
+ "written": "2026-10-29 16:15:13",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "deepseek-v4.1-flash",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9",
4
+ "written": "2026-10-26 07:08:06",
5
+ "summary": {
6
+ "report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json",
7
+ "checks": 10,
8
+ "framework": {
9
+ "commit": "b513a1c7289ab11eb844856588b64c378705c405",
10
+ "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823",
11
+ "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350",
12
+ "untracked": [
13
+ "lff_integration/__init__.py",
14
+ "lff_integration/run.py"
15
+ ]
16
+ }
17
+ }
18
+ }
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/tasks/l4_fit.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L4-A fit_container: put the phone flat inside the one box it fits into.
2
+
3
+ v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and
4
+ phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time.
5
+ v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is
6
+ rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn
7
+ against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone:
8
+ fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight),
9
+ snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps,
10
+ short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps,
11
+ narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow,
12
+ small 0.5..1.0 cm too short.
13
+ A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the
14
+ images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it
15
+ appears to (by about the overlap seen) -> the box with the most length to spare.
16
+
17
+ The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as
18
+ the capped length. v2 is kept in l4_fit.py.bak-20261008-height.
19
+
20
+ v2 description:
21
+
22
+ Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open
23
+ boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES):
24
+ fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side),
25
+ short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest),
26
+ narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest),
27
+ small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions),
28
+ short 0.8-2.0 cm too short, as wide as the fitting box.
29
+ Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it
30
+ (+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be
31
+ turned by ~90 deg.
32
+
33
+ Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the
34
+ fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in
35
+ sim.model, so a single env serves every instance.
36
+
37
+ Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed
38
+ 2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first
39
+ failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too
40
+ long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger
41
+ in that dimension and turn the phone.
42
+ """
43
+ import numpy as np
44
+
45
+ from .. import envs
46
+ from ..bddl import write_bddl
47
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
48
+ from ..skills import _rot_err
49
+ from ..task_base import LFFTask, register_task
50
+
51
+ # phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it
52
+ PL, PW, PT = 0.140, 0.068, 0.012
53
+ CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden)
54
+ # boxes (local x = long axis of the opening)
55
+ WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035
56
+ BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height
57
+ RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
58
+ N_BOXES = 5
59
+ ROWS_X = (-0.30, -0.08) # back row (near the robot), front row
60
+ COLS_Y = (-0.22, 0.0, 0.22)
61
+ DROP = 0.012 # phone bottom this far above the rim when released
62
+ Z_CARRY = envs.TABLE_Z + 0.15
63
+ PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way
64
+ PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates
65
+ JITTER_DEG = 15.0
66
+ # inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side).
67
+ # The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has
68
+ # the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio.
69
+ # Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box.
70
+ # v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap)
71
+ BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small")
72
+ INNER_RANGES = {
73
+ "fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest)
74
+ "snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable
75
+ "short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box
76
+ "narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow
77
+ "small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short
78
+ }
79
+ VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps)
80
+ BOX_RGBA = (0.70, 0.60, 0.46, 1.0)
81
+
82
+
83
+ def phone_xml(model_name):
84
+ hx, hy, hz = PL / 2, PW / 2, PT / 2
85
+ body = (0.13, 0.13, 0.15, 1.0)
86
+ screen = (0.02, 0.025, 0.04, 1.0)
87
+ g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" '
88
+ f'density="1500" friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
89
+ f' <geom type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" conaffinity="0" contype="0" '
90
+ f'group="1" />\n'
91
+ f' <geom type="box" pos="0 0 {hz:.5f}" size="{_fmt((hx - 0.004, hy - 0.003, 0.0003))}" '
92
+ f'rgba="{_fmt(screen)}" conaffinity="0" contype="0" group="1" />')
93
+ # v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered).
94
+ # Resized per instance in apply_instance (inst["cap"]).
95
+ c = CAP_RANGE[1]
96
+ for k, sx in enumerate((1, -1)):
97
+ g += (f'\n <geom name="{model_name}_cap{k}" type="box" pos="{_fmt((sx * (hx + c / 2), 0, 0))}" '
98
+ f'size="{_fmt((c / 2, hy - 0.001, hz))}" rgba="1 1 1 0" density="400" friction="1.0 0.005 0.0001" '
99
+ f'{_SOLID} group="0" />')
100
+ return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy)))
101
+
102
+
103
+ def wrap_half(a):
104
+ """angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)"""
105
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
106
+
107
+
108
+ def wrap_quarter(a):
109
+ """angle modulo pi/2 into [-pi/4, pi/4)"""
110
+ return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
111
+
112
+
113
+ def fits_some_yaw(a, b, clearance=0.002, length=PL):
114
+ """Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in
115
+ total)?"""
116
+ th = np.linspace(0.0, np.pi / 2, 181)
117
+ e1 = length * np.cos(th) + PW * np.sin(th)
118
+ e2 = length * np.sin(th) + PW * np.cos(th)
119
+ return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance)))
120
+
121
+
122
+ def _rect_corners(xy, yaw, half):
123
+ c, s = np.cos(yaw), np.sin(yaw)
124
+ R = np.array([[c, -s], [s, c]])
125
+ pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
126
+ return pts @ R.T + np.asarray(xy)
127
+
128
+
129
+ def _rects_overlap(r1, r2):
130
+ """separating-axis test for two rotated rectangles given as (xy, yaw, half)"""
131
+ c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
132
+ for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
133
+ ax = np.array([np.cos(yaw), np.sin(yaw)])
134
+ p1, p2 = c1 @ ax, c2 @ ax
135
+ if p1.max() < p2.min() or p2.max() < p1.min():
136
+ return False
137
+ return True
138
+
139
+
140
+ @register_task
141
+ class FitContainer(LFFTask):
142
+ name = "l4_fit_container"
143
+ level = "L4"
144
+ category = "geometry_inference"
145
+ capabilities = ("Perceive", "Reason")
146
+ instruction = "Put the phone flat inside a box that it fits into completely."
147
+ instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely."
148
+
149
+ # ------------------------------------------------------------ scene
150
+ def make_bddl(self):
151
+ phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone"))
152
+ # one category per box (BDDL lists one object per line; same-category lines would overwrite each
153
+ # other). All share the same MJCF; the opening is resized per instance in apply_instance.
154
+ cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H,
155
+ wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA,
156
+ density=3000))
157
+ for c in "ABCDE"]
158
+ objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))]
159
+ slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)]
160
+ for i, (x, y) in enumerate(slots):
161
+ objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)))
162
+ return write_bddl(self.name, self.instruction, objs)
163
+
164
+ def sample_instance(self, seed):
165
+ rng = np.random.default_rng(seed)
166
+ j = np.radians(JITTER_DEG)
167
+ for _ in range(500):
168
+ col = int(rng.integers(3))
169
+ phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)]
170
+ phone_yaw = float(rng.uniform(-j, j))
171
+ slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])]
172
+ kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)]
173
+ cap = float(rng.uniform(*CAP_RANGE))
174
+ boxes = []
175
+ for i, (kind, (x, y)) in enumerate(zip(kinds, slots)):
176
+ lo, hi = INNER_RANGES[kind]
177
+ a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1])
178
+ assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap)
179
+ assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b)
180
+ crossed = bool(rng.random() < 0.5)
181
+ yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j))
182
+ boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed,
183
+ xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))],
184
+ yaw=yaw, inner=[float(a), float(b)]))
185
+ rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007))
186
+ for b in boxes]
187
+ rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01)))
188
+ if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)):
189
+ break
190
+ else:
191
+ raise RuntimeError("could not sample a non-overlapping layout")
192
+ prng = np.random.default_rng(seed + 7919)
193
+ perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))]
194
+ for b in boxes]
195
+ return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes,
196
+ fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc)
197
+
198
+ def _reshape_box(self, name, a, b):
199
+ ix, iy, H = a / 2, b / 2, BOX_HALF_H
200
+ parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
201
+ ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
202
+ ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
203
+ ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
204
+ ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
205
+ m = self.env.sim.model
206
+ o = self.env.objects_dict[name]
207
+ for names in (o.contact_geoms, o.visual_geoms):
208
+ assert len(names) == len(parts), names
209
+ for k, n in enumerate(names):
210
+ g = m.geom_name2id(n)
211
+ pos, size = parts[k]
212
+ m.geom_pos[g] = pos
213
+ m.geom_size[g] = size
214
+ m.geom_rbound[g] = float(np.linalg.norm(size))
215
+ m.geom_aabb[g] = [0, 0, 0, *size]
216
+
217
+ def _set_caps(self, cap):
218
+ """resize the two hidden bumper caps to `cap` (m) per end"""
219
+ m = self.env.sim.model
220
+ if not hasattr(self, "_cap_ids"):
221
+ self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1")
222
+ if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]]
223
+ assert len(self._cap_ids) == 2, self._cap_ids
224
+ for g in self._cap_ids:
225
+ sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0
226
+ size = (cap / 2, PW / 2 - 0.001, PT / 2)
227
+ m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0)
228
+ m.geom_size[g] = size
229
+ m.geom_rbound[g] = float(np.linalg.norm(size))
230
+ m.geom_aabb[g] = [0, 0, 0, *size]
231
+
232
+ def apply_instance(self, inst):
233
+ # walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision
234
+ # mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07).
235
+ # Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below.
236
+ import mujoco
237
+ self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
238
+ self._set_caps(inst["cap"])
239
+ for b in inst["boxes"]:
240
+ self._reshape_box(b["name"], *b["inner"])
241
+ envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"])
242
+ envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005],
243
+ yaw=inst["phone_yaw"])
244
+
245
+ # ------------------------------------------------------------ outcome
246
+ def _pose2d(self, name):
247
+ bid = envs.body_id(self.env, name)
248
+ R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
249
+ p = self.env.sim.data.body_xpos[bid].copy()
250
+ return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
251
+
252
+ def outcome(self, inst):
253
+ envs.settle(self.env, 40)
254
+ p, yaw, tilt = self._pose2d("phone_1")
255
+ held = bool(self.sk is not None and self.sk.holding("phone_1"))
256
+ # which box is the phone in / on: smallest distance of the phone centre outside a box opening
257
+ best = None
258
+ for j, b in enumerate(inst["boxes"]):
259
+ c, byaw, btilt = self._pose2d(b["name"])
260
+ d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2])
261
+ out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0)
262
+ dist = float(np.linalg.norm(out))
263
+ if best is None or dist < best[0]:
264
+ best = (dist, j, c, byaw, btilt)
265
+ dist, j, c, byaw, btilt = best
266
+ b = inst["boxes"][j]
267
+ a_in, b_in = b["inner"]
268
+ floor_top = c[2] - BOX_HALF_H + FLOOR_T
269
+ height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor
270
+ in_opening = dist < 1e-9
271
+ on_floor = height < 0.004 and tilt < 5.0
272
+ success = bool(in_opening and on_floor and not held and btilt < 10.0)
273
+ where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback
274
+ # footprint of the phone (as it lies now) against the opening of that box
275
+ dl = yaw - byaw
276
+ cs, sn = abs(np.cos(dl)), abs(np.sin(dl))
277
+ L = PL + 2 * inst.get("cap", 0.0) # the capped phone
278
+ over_long = L * cs + PW * sn - a_in
279
+ over_short = L * sn + PW * cs - b_in
280
+ along_long = "length" if cs >= sn else "width"
281
+ fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long,
282
+ over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None,
283
+ over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None)
284
+ res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2),
285
+ tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb)
286
+ if held:
287
+ res["detail"] = "The phone is still in the gripper."
288
+ res["failure"] = "held"
289
+ return res
290
+ if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006):
291
+ res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm "
292
+ f"outside the opening of {where}.")
293
+ res["failure"] = "table"
294
+ return res
295
+ if success:
296
+ res["detail"] = f"The phone is lying flat on the bottom of {where}."
297
+ res["failure"] = None
298
+ return res
299
+ pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else
300
+ f"tilted about {tilt:.0f} degrees with one end down inside the box")
301
+ txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}."
302
+ dim_l = "long" if along_long == "length" else "wide"
303
+ dim_s = "wide" if along_long == "length" else "long"
304
+ if fb["over_long_cm"]:
305
+ txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side."
306
+ if fb["over_short_cm"]:
307
+ txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side."
308
+ if not fb["over_long_cm"] and not fb["over_short_cm"]:
309
+ txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim."
310
+ res["detail"] = txt
311
+ res["failure"] = "rim"
312
+ return res
313
+
314
+ @staticmethod
315
+ def box_label(inst, j):
316
+ """Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left)."""
317
+ ys = [b["xy"][1] for b in inst["boxes"]]
318
+ xs = [b["xy"][0] for b in inst["boxes"]]
319
+ n = len(ys)
320
+ order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first
321
+ r = order.index(j)
322
+ close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04]
323
+ if close: # boxes side by side in y: tell them apart by distance from the robot
324
+ nearer = all(xs[j] < xs[i] for i in close)
325
+ return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position"
326
+ if r == 0:
327
+ return "the box furthest to the robot's left (+y)"
328
+ if r == n - 1:
329
+ return "the box furthest to the robot's right (-y)"
330
+ return "the middle box (between the others, left to right)"
331
+
332
+ # ------------------------------------------------------------ execution
333
+ def execute(self, inst, params):
334
+ """params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released).
335
+ Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre
336
+ along the box's long / short axis (m), drop = height of the phone bottom above the rim (m)."""
337
+ sk, env = self.sk, self.env
338
+ px, py = inst["phone_xy"]
339
+ zc = envs.TABLE_Z + PT / 2
340
+ g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width
341
+ sk.set_gripper(False, steps=5)
342
+ sk.move_to([px, py, zc + 0.10], yaw=g0)
343
+ sk.move_to([px, py, zc + 0.001], tol=0.003)
344
+ sk.set_gripper(True, steps=15)
345
+ sk.move_to([px, py, Z_CARRY], speed=0.25)
346
+ b = inst["boxes"][int(params["box"])]
347
+ c, s = np.cos(b["yaw"]), np.sin(b["yaw"])
348
+ dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
349
+ bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy
350
+ sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"]))
351
+ # put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip
352
+ off = envs.obj_pos(env, "phone_1") - sk.eef_pos()
353
+ drop = params.get("drop", DROP)
354
+ sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003)
355
+ tgt = self._servo_phone([bx, by], RIM_Z + drop)
356
+ sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts)
357
+ self._hold_at(tgt, 12)
358
+ sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
359
+ sk.move_to(list(PARK), yaw=0.0)
360
+
361
+ def _hold_at(self, target, steps):
362
+ sk = self.sk
363
+ R = sk._R()
364
+ for _ in range(steps):
365
+ sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
366
+
367
+ def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015):
368
+ """Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom.
369
+ Returns the final gripper target."""
370
+ sk = self.sk
371
+ R = sk._R()
372
+ goal = np.array([xy[0], xy[1], z_bottom + PT / 2])
373
+ tgt = e_prev = sk.eef_pos()
374
+ for i in range(max_steps):
375
+ ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos()
376
+ if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
377
+ break
378
+ tgt = goal - (ph - e)
379
+ sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
380
+ e_prev = e
381
+ return tgt
382
+
383
+ # ------------------------------------------------------------ scripted policies
384
+ def _naive_yaw(self, inst, j):
385
+ """keep the phone's orientation, only snap it to the nearest axis of box j"""
386
+ p = inst["phone_yaw"]
387
+ return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p))
388
+
389
+ def default_params(self, inst):
390
+ """v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the
391
+ trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its
392
+ tighter direction, i.e. "snug" by construction; phone's long side along the box's long side"""
393
+ marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]]
394
+ j = int(np.argmax(marg))
395
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
396
+
397
+ def nearest_params(self, inst):
398
+ """v2 prior (kept for reference): nearest box, lined up"""
399
+ d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
400
+ j = int(np.argmin(d))
401
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
402
+
403
+ def oracle_params(self, inst):
404
+ j = inst["fit"]
405
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
406
+
407
+ def blind_params(self, inst, attempt, rng):
408
+ """no history: a random box (may repeat), lined up like the prior"""
409
+ j = int(rng.integers(N_BOXES))
410
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
411
+
412
+ def naive_keep_yaw_params(self, inst):
413
+ """old prior (kept for reference): nearest box, keep the phone's orientation"""
414
+ d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
415
+ j = int(np.argmin(d))
416
+ return dict(box=j, place_yaw=self._naive_yaw(inst, j))
417
+
418
+ def adapt_params(self, inst, history):
419
+ """Scripted learner on F2 feedback.
420
+
421
+ Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the
422
+ phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an
423
+ estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box
424
+ that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and
425
+ lines the phone's long side up with the box's long side.
426
+ """
427
+ perc = inst["_perc"]
428
+ L_est = W_est = None
429
+ tried_aligned = set()
430
+ for h in history:
431
+ o = h["outcome"]
432
+ fb = o.get("feedback") or {}
433
+ if o.get("failure") != "rim":
434
+ continue
435
+ j = fb["box"]
436
+ a, b = perc[j]
437
+ if fb["along_long"] == "length":
438
+ if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box
439
+ tried_aligned.add(j)
440
+ if fb["over_long_cm"]:
441
+ L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100)
442
+ if fb["over_short_cm"]:
443
+ W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100)
444
+ else:
445
+ if fb["over_short_cm"]:
446
+ L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100)
447
+ if fb["over_long_cm"]:
448
+ W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100)
449
+ thr = 0.002
450
+ cands = []
451
+ for j, (a, b) in enumerate(perc):
452
+ if j in tried_aligned:
453
+ continue
454
+ mL = None if L_est is None else a - L_est
455
+ mW = None if W_est is None else b - W_est
456
+ feasible = (mL is None or mL > thr) and (mW is None or mW > thr)
457
+ if mL is not None and mW is not None:
458
+ key = min(mL, mW)
459
+ elif mL is not None:
460
+ key = b
461
+ elif mW is not None:
462
+ key = a
463
+ else:
464
+ key = a * b
465
+ cands.append((feasible, key, j))
466
+ if not cands:
467
+ j = int(np.argmax([a * b for a, b in perc]))
468
+ else:
469
+ j = max(cands)[2]
470
+ return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"]))
471
+
472
+ def elim_params(self, inst, history, rng):
473
+ """sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up
474
+ after the first attempt) and to never retry a box that got a size verdict; picks among the remaining
475
+ boxes at random, i.e. no size reasoning / perception."""
476
+ bad = set()
477
+ for h in history:
478
+ fb = h["outcome"].get("feedback") or {}
479
+ if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and (
480
+ fb.get("over_long_cm") or fb.get("over_short_cm")):
481
+ bad.add(int(fb["box"]))
482
+ left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES))
483
+ j = int(rng.choice(left))
484
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
485
+
486
+ EXTRA_KINDS = ("elim",)
487
+
488
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
489
+ if kind not in self.EXTRA_KINDS:
490
+ return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
491
+ k = k or self.max_attempts
492
+ rng = np.random.default_rng(seed)
493
+ history = []
494
+ for a in range(k):
495
+ self.reset_instance(inst)
496
+ if a == 0:
497
+ params = self.default_params(inst)
498
+ else:
499
+ params = self.elim_params(inst, history, rng)
500
+ self.execute(inst, params)
501
+ out = self.outcome(inst)
502
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
503
+ if on_attempt:
504
+ on_attempt(a, params, out)
505
+ if out["success"]:
506
+ break
507
+ return history
508
+
509
+
510
+ # ---------------------------------------------------------------- physical validity checks
511
+ def physics_check(seed0=1000, n=20, out=None):
512
+ """Every (box, orientation) pair on each instance, released centred from DROP above the rim.
513
+ Expect success iff the box is the fitting one and the phone's long side is along the box's long side."""
514
+ import json
515
+ task = FitContainer()
516
+ rows = []
517
+ for seed in range(seed0, seed0 + n):
518
+ inst = task.sample_instance(seed)
519
+ for j, b in enumerate(inst["boxes"]):
520
+ for orient in ("aligned", "crossed"):
521
+ task.reset_instance(inst)
522
+ task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2))))
523
+ o = task.outcome(inst)
524
+ rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]],
525
+ orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"),
526
+ failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
527
+ r = rows[-1]
528
+ print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} "
529
+ f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True)
530
+ if out:
531
+ with open(out, "w") as f:
532
+ json.dump(rows, f, indent=1)
533
+ print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
534
+ return rows
535
+
536
+
537
+ def stress_check(seed=1002, out=None):
538
+ """Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box
539
+ (+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow."""
540
+ import copy
541
+ import json
542
+ task = FitContainer()
543
+ base = task.sample_instance(seed)
544
+ j = base["fit"]
545
+ rows = []
546
+ for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010),
547
+ ("narrow_0.5", PL + 0.010, PW - 0.005)]:
548
+ for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP),
549
+ (0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]:
550
+ inst = copy.deepcopy(base)
551
+ inst["boxes"][j]["inner"] = [a, b]
552
+ task.reset_instance(inst)
553
+ task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)),
554
+ dx=dx, dy=dy, drop=drop))
555
+ o = task.outcome(inst)
556
+ rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000,
557
+ dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"],
558
+ height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
559
+ print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> "
560
+ f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True)
561
+ if out:
562
+ with open(out, "w") as f:
563
+ json.dump(rows, f, indent=1)
564
+ return rows
565
+
566
+
567
+ if __name__ == "__main__":
568
+ # python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json
569
+ # python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json
570
+ import sys
571
+ if sys.argv[1] == "physics":
572
+ physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
573
+ elif sys.argv[1] == "stress":
574
+ stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/scripts/agent_viewer/viewer.html ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <title>Agent Viewer · 历史回放</title>
6
+ <style>
7
+ :root{color-scheme:light;--bg:#f6f7f6;--paper:#fff;--text:#192b31;--muted:#62747a;--border:#dfe7e6;--teal:#087f79;--soft:#e9f5f1;--orange:#b56624;--red:#af4545;--mono:ui-monospace,SFMono-Regular,Consolas,monospace;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:var(--text);background:var(--bg)}
8
+ *{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,select{cursor:pointer}button{border:1px solid var(--border);background:var(--paper);color:var(--text);border-radius:7px;padding:9px 13px;font-size:13px}button:hover{background:var(--soft)}button:disabled{opacity:.4;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #55bbb1;outline-offset:2px}button.active,button[aria-pressed="true"]{border-color:var(--teal);color:var(--teal);background:var(--soft)}.primary{background:var(--teal);border-color:var(--teal);color:white}.primary:hover{background:#076762}.muted{color:var(--muted)}.mono,code{font-family:var(--mono)}.eyebrow{font-size:10px;text-transform:uppercase;letter-spacing:1.7px;font-weight:700;color:var(--muted)}
9
+ header{height:72px;padding:0 28px;display:flex;align-items:center;gap:18px;border-bottom:1px solid var(--border);background:var(--paper)}.brand{font-size:21px;font-weight:750;letter-spacing:-.6px;display:flex;align-items:center;gap:11px}.brandmark{background:var(--teal);color:#fff;border-radius:9px;padding:4px 8px;font-size:20px}.divider{height:23px;width:1px;background:var(--border)}.mode{margin-left:auto;font-size:12px;color:var(--teal);background:var(--soft);padding:7px 12px;border-radius:6px}.shell{display:grid;grid-template-columns:235px minmax(0,1fr);min-height:calc(100vh - 72px)}aside{padding:27px 18px;border-right:1px solid var(--border);background:#f9faf9}.aside-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:21px;font-size:13px}.run{display:block;text-align:left;width:100%;padding:15px 13px;border-radius:9px;margin-bottom:9px}.run strong{display:block;font-size:13px;line-height:1.6;overflow-wrap:anywhere}.run small{display:block;line-height:1.9;color:var(--muted);font-size:11px}.run .state{font-size:11px;color:var(--teal);margin-bottom:9px;display:block}.aside-section{border-top:1px solid var(--border);margin-top:27px;padding-top:22px}.attempt{display:block;width:100%;text-align:left;margin-top:9px;font-size:12px}.attempt span{float:right}.success{color:var(--teal)}.failed{color:var(--red)}.aside-note{font-size:11px;line-height:1.9;margin-top:25px;color:var(--muted)}
10
+ main{min-width:0;padding:28px 30px}.heading{display:flex;justify-content:space-between;gap:20px;align-items:flex-start;margin-bottom:22px}h1{font-size:26px;letter-spacing:-.8px;line-height:1.3;margin:7px 0 9px}h2{font-size:15px;margin:0}h3{font-size:13px;margin:0}.subtitle{font-size:12px;line-height:1.8;color:var(--muted)}.pill{display:inline-block;white-space:nowrap;font-size:11px;padding:6px 10px;border-radius:20px;background:var(--soft);color:var(--teal)}.workspace{display:grid;grid-template-columns:minmax(320px,1.5fr) minmax(280px,1fr);gap:22px}.panel{background:var(--paper);border:1px solid var(--border);border-radius:12px;overflow:hidden}.panel-top{display:flex;align-items:center;justify-content:space-between;padding:17px 19px;border-bottom:1px solid var(--border);gap:10px}.panel-top small{font-size:11px;color:var(--muted)}.switches{padding:14px 18px;display:flex;gap:7px;flex-wrap:wrap}.switches button{font-size:11px;padding:7px 10px}.image-stage{background:#e9eeec;margin:0 18px;min-height:230px;display:grid;place-items:center;position:relative;border-radius:7px;overflow:hidden}.image-stage img{display:block;width:100%;height:clamp(290px,36vw,480px);object-fit:contain}.image-stage .empty{padding:45px;text-align:center;color:var(--muted);line-height:1.8}.caption{padding:12px 19px;font-size:11px;color:var(--muted);line-height:1.7;overflow-wrap:anywhere}.camera-strip{display:flex;gap:12px;padding:0 18px 18px;flex-wrap:wrap}.camera{display:grid;grid-template-columns:58px 1fr;align-items:center;gap:9px;text-align:left;padding:5px 10px 5px 5px;min-width:140px}.camera img{width:58px;height:46px;object-fit:contain;background:#e9eeec;border-radius:4px}.camera span{font-size:11px}.task{margin:0 18px 18px;padding:14px 0 0;border-top:1px solid var(--border);font-size:12px;line-height:1.8}.task p{margin:6px 0 0}.step-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.step-title small{font-size:11px;color:var(--muted)}.flowcard{background:var(--paper);border:1px solid var(--border);border-radius:10px;margin-bottom:12px;padding:16px}.cardtitle{display:flex;align-items:center;gap:9px;margin-bottom:12px;font-size:12px;font-weight:650}.number{color:var(--muted);background:var(--bg);border:1px solid var(--border);border-radius:5px;padding:4px;font:10px var(--mono)}.flowcard p{font-size:12px;line-height:1.8;margin:7px 0;color:var(--muted)}pre{margin:9px 0 0;font:11px/1.7 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere;background:var(--bg);border:1px solid var(--border);padding:12px;border-radius:6px;max-height:230px;overflow:auto}details{margin-top:9px}summary{font-size:11px;color:var(--muted);cursor:pointer;padding:5px 0}.result-message{font-size:13px;line-height:1.8}.notice{border:1px solid #e9cfab;background:#fff8ec;color:#89541d;padding:10px 12px;border-radius:7px;margin-top:10px;font-size:11px;line-height:1.8}.statement{border-left:2px solid var(--teal);padding-left:10px;font-size:12px;line-height:1.8;margin:12px 0}.subtle{font-size:11px;line-height:1.8;color:var(--muted)}
11
+ .timeline{margin-top:22px;padding:18px 20px}.controls{display:flex;align-items:center;gap:9px;flex-wrap:wrap}.controls .count{font:12px var(--mono);margin:0 8px}.controls select{padding:7px;border:1px solid var(--border);background:var(--paper);border-radius:6px;font-size:11px}.controls small{margin-left:auto;font-size:11px;color:var(--muted)}input[type=range]{width:100%;accent-color:var(--teal);margin:18px 0 10px;cursor:pointer}.filmstrip{display:flex;gap:9px;overflow-x:auto;padding:3px 0 7px;scroll-behavior:smooth}.frame{flex:0 0 95px;padding:4px;position:relative}.frame img,.frame .placeholder{display:block;width:85px;height:64px;object-fit:contain;background:#e9eeec;border-radius:4px}.frame .label{display:block;font-size:10px;margin:7px 0 3px}.frame .dot{position:absolute;top:8px;right:8px;border:2px solid white;width:10px;height:10px;border-radius:50%;background:var(--teal)}.frame .dot.bad{background:var(--orange)}.timeline-foot{display:flex;justify-content:space-between;gap:15px;font-size:10px;color:var(--muted);margin-top:10px;line-height:1.8}footer{display:flex;justify-content:space-between;font-size:10px;color:var(--muted);margin-top:18px;gap:15px;line-height:1.8}.warning-list{font-size:11px;color:var(--orange)}
12
+ @media(min-width:1600px){main{max-width:1600px;width:100%;margin:auto}}@media(max-width:1100px){.shell{grid-template-columns:185px minmax(0,1fr)}main{padding:23px 20px}.workspace{gap:15px;grid-template-columns:minmax(250px,1.2fr) minmax(250px,1fr)}aside{padding:25px 12px}.image-stage img{height:320px}}@media(max-width:850px){.shell{display:block}aside{border-right:0;border-bottom:1px solid var(--border);padding:15px 20px}.aside-title,.aside-note,.aside-section .eyebrow{display:none}#runs{display:flex;gap:10px}.run{width:auto;min-width:190px;margin:0}.aside-section{margin:12px 0 0;padding:0;border:0;display:flex;gap:8px}.attempt{width:auto}.attempt span{float:none;margin-left:10px}.workspace{grid-template-columns:minmax(0,1fr)}.image-stage img{height:400px}header{padding:0 18px;height:63px}.heading{margin-bottom:17px}main{padding:22px 18px}.details-col{display:grid;grid-template-columns:1fr 1fr;gap:12px}.step-title{grid-column:1/-1;margin-bottom:0}.flowcard{margin:0}.flowcard:last-child{grid-column:1/-1}}@media(max-width:480px){header .divider,header>.muted{display:none}header{gap:8px}.brand{font-size:18px}.mode{font-size:10px;padding:6px 8px}.heading{display:block}h1{font-size:23px}.heading>.pill{margin-top:9px}.details-col{display:block}.flowcard{margin-top:12px}.image-stage{margin:0 10px}.image-stage img{height:280px}.panel-top{padding:14px}.camera-strip{padding:0 10px 12px;gap:6px}.camera{min-width:120px;padding-right:6px;grid-template-columns:42px 1fr}.camera img{width:42px;height:38px}.timeline{padding:14px 10px}.controls{gap:5px}.controls .count{margin:0 3px;font-size:10px}.controls small{display:none}.controls button{padding:9px 10px}.timeline-foot,footer{flex-direction:column;gap:3px}}
13
+ [hidden]{display:none!important}.view-tabs{display:flex;gap:8px;margin-bottom:18px}.video-panel{margin-bottom:22px}.video-stage{background:#101817;padding:16px;text-align:center}.video-stage video{display:block;width:100%;max-height:68vh;min-height:200px;margin:auto;aspect-ratio:640/376;background:#101817}.video-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:14px 19px}.video-toolbar label{font-size:12px}.video-toolbar select{padding:6px;border:1px solid var(--border);border-radius:6px;background:var(--paper);color:var(--text)}.video-toolbar .subtle{margin-left:auto}.video-note{padding:0 19px 16px;font-size:12px;line-height:1.8;color:var(--muted)}
14
+ .reason-copy{white-space:pre-wrap;font-size:12px;line-height:1.8;background:var(--soft);border-radius:7px;padding:12px;margin:9px 0}.reason-empty{background:none;color:var(--muted);padding:0}.reason-public{white-space:pre-wrap;font-size:12px;line-height:1.8;border-left:2px solid var(--teal);padding-left:10px;margin:9px 0}.view-tabs{flex-wrap:wrap}
15
+ </style>
16
+ </head>
17
+ <body>
18
+ <header><div class="brand"><span class="brandmark">⌘</span>Agent Viewer</div><span class="divider"></span><span class="muted" style="font-size:12px">LFF-Bench</span><span class="mode">◷ 历史回放</span></header>
19
+ <div class="shell">
20
+ <aside><div class="aside-title"><strong>运行记录</strong><span id="run-count" class="muted"></span></div><nav id="runs" aria-label="运行记录"></nav><div class="aside-section" id="attempts"></div><div class="aside-note">回放已保存的观察与工具记录。<br>画面来自模型输入的历史图片文件。<br>视频支持连续播放与全屏。<br>逐步视图:← → 切换,空格播放。</div></aside>
21
+ <main>
22
+ <div class="heading"><div><div class="eyebrow">OBSERVE / ACT / REVIEW</div><h1 id="title"></h1><div class="subtitle" id="subtitle"></div></div><span id="status" class="pill"></span></div>
23
+ <div class="view-tabs" aria-label="回放视图"><button id="video-tab" aria-pressed="false">▶ 完整执行视频</button><button id="steps-tab" aria-pressed="false">逐步输入与日志</button></div>
24
+ <section id="video-view" class="panel video-panel" hidden><div class="panel-top"><h2>完整执行录像</h2><small>主相机 + 腕部相机</small></div><div class="video-stage"><video id="execution-video" controls playsinline preload="metadata" aria-label="任务完整执行录像">浏览器不支持视频播放。</video></div><div class="video-toolbar"><label for="video-rate">播放速度</label><select id="video-rate"><option value="0.3333333333333333">⅓×</option><option value="0.5">0.5×</option><option value="1" selected>1× 原录像</option><option value="2">2×</option></select><span class="subtle">连续播放 · 拖动进度 · 全屏查看</span></div><div class="video-note">播放原始执行录像,保留尝试切换与结果画面。录像时间不等于日志中的等待时间;查看单步输入与工具返回可切换到“逐步输入与日志”。</div><div id="video-error" class="notice" hidden role="alert"></div></section>
25
+ <div id="step-view"><div class="workspace">
26
+ <section class="panel"><div class="panel-top"><h2>Agent 看到的画面</h2><small id="attempt-label"></small></div><div class="switches"><button id="before" aria-pressed="true">决策前 · 最近观察</button><button id="after" aria-pressed="false">执行后 · 返回图片</button></div><div class="image-stage" id="stage"></div><div class="caption" id="caption"></div><div class="camera-strip" id="cameras"></div><div class="task"><span class="eyebrow">TASK</span><p id="task"></p></div></section>
27
+ <section class="details-col" aria-label="当前步骤"><div class="step-title"><h2 id="step-title"></h2><small id="time"></small></div><div class="flowcard"><div class="cardtitle"><span class="number">01</span>观察输入</div><div id="observation-note" class="subtle"></div><details><summary>查看最近输入文本</summary><pre id="input-text"></pre></details></div><div class="flowcard"><div class="cardtitle"><span class="number">02</span>步骤间思考</div><div id="reason-transition" class="subtle"></div><div id="reason-summary" class="reason-copy"></div><div id="reason-public-wrap"><span class="subtle">Agent 文字说明</span><div id="reason-public" class="reason-public"></div></div><details><summary>前一步反馈与记录来源</summary><pre id="reason-feedback"></pre><p id="reason-source" class="subtle"></p><p class="subtle">显示已记录的模型摘要与文字回复,不代表完整内部 CoT。</p></details></div><div class="flowcard"><div class="cardtitle"><span class="number">03</span>执行动作</div><div id="actions"></div></div><div class="flowcard"><div class="cardtitle"><span class="number">04</span>执行反馈</div><div id="results"></div><div id="notices"></div></div></section>
28
+ </div>
29
+ <section class="panel timeline" aria-label="回放时间轴"><div class="controls"><button id="prev" aria-label="上一步">←</button><button id="play" class="primary" aria-label="播放回放">▶ 播放</button><button id="next" aria-label="下一步">→</button><span class="count" id="count" aria-live="polite"></span><select id="speed" aria-label="每步播放时长"><option value="2000">2 秒 / 步</option><option value="1000">1 秒 / 步</option><option value="4000">4 秒 / 步</option></select><small>按步骤播放 · 不按实际等待时间</small></div><input id="scrubber" type="range" min="0" value="0" aria-label="选择回放步骤"><div class="filmstrip" id="filmstrip"></div><div class="timeline-foot"><span>● 绿色:尝试成功 ● 橙色:失败 / API 重试</span><span id="step-meta"></span></div></section>
30
+ </div>
31
+ <div id="warnings" class="warning-list"></div><footer><span>真实历史记录 · 原始执行录像与输入图片 · 离线可用</span><span>逐步视图展示最近观察;模型上下文可能包含更早图片。</span></footer>
32
+ </main></div>
33
+ <script id="viewer-data" type="application/json">/*__PAYLOAD__*/null</script>
34
+ <script>
35
+ 'use strict';
36
+ const DATA=JSON.parse(document.getElementById('viewer-data').textContent);
37
+ const $=id=>document.getElementById(id);
38
+ const names={l5_slide_to_target:'把红色方块滑入目标区',l1_bias_place:'校准偏差下的抓取放置'};
39
+ let runIndex=0, index=0, phase='before', camera='agentview', selectedFrameKey=null, timer=null, viewMode='steps';
40
+ const run=()=>DATA.runs[runIndex];
41
+ const step=()=>run().steps[index];
42
+ function el(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
43
+ function fmt(value){return typeof value==='string'?value:JSON.stringify(value,null,2);}
44
+ function clock(seconds){const s=Math.max(0,Math.round(seconds||0));return `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;}
45
+ function cameraName(name){return name==='agentview'?'主相机':name==='wrist'?'腕部相机':name;}
46
+ function stop(){if(timer)clearInterval(timer);timer=null;$('play').textContent='▶ 播放';$('play').setAttribute('aria-label','播放回放');}
47
+ function setMode(mode){stop();viewMode=mode==='video'&&run().video?'video':'steps';$('video-view').hidden=viewMode!=='video';$('step-view').hidden=viewMode!=='steps';$('video-tab').setAttribute('aria-pressed',String(viewMode==='video'));$('steps-tab').setAttribute('aria-pressed',String(viewMode==='steps'));if(viewMode!=='video')$('execution-video').pause();}
48
+ function setupVideo(){const v=$('execution-video');v.pause();v.removeAttribute('src');$('video-error').hidden=true;$('video-tab').disabled=!run().video;if(run().video)v.src=DATA.assets[run().video.asset];v.load();$('video-rate').value='1';v.playbackRate=1;setMode(run().video?'video':'steps');}
49
+ function move(value,manual=true){if(manual)stop();index=Math.max(0,Math.min(run().steps.length-1,value));render();}
50
+ function img(frame){const image=el('img');image.alt=`${cameraName(frame.camera)} · ${frame.path}`;image.src=DATA.assets[frame.asset];return image;}
51
+ function allAfter(s){return s.actions.flatMap(a=>a.after||[]);}
52
+ function renderRun(){
53
+ const r=run();$('title').textContent=names[r.task]||r.task;$('subtitle').textContent=`${r.model} / seed ${r.seed??'—'} / ${r.actionCount} 次工具调用 / ${r.feedback} · ${r.perception}`;
54
+ $('task').textContent=r.taskText;$('status').textContent=r.status==='success'?'● 最终成功':r.status==='failed'?'● 尝试未成功':'◌ 记录未完成';
55
+ $('status').style.color=r.status==='failed'?'var(--red)':'';$('run-count').textContent=DATA.runs.length;
56
+ $('runs').replaceChildren(...DATA.runs.map((item,n)=>{const b=el('button',undefined,'run'+(n===runIndex?' active':''));b.setAttribute('aria-pressed',String(n===runIndex));b.append(el('span',item.status==='success'?'● 已完成 · 成功':'◌ '+(item.status==='failed'?'未成功':'未完成'),'state'),el('strong',names[item.task]||item.task),el('small',`${item.model} · seed ${item.seed??'—'}`),el('small',`${item.steps.length} 步决策 · ${item.outcomes.length} 次提交`));b.onclick=()=>{stop();runIndex=n;index=0;phase='before';renderRun();render();};return b;}));
57
+ $('attempts').replaceChildren(el('div','ATTEMPTS','eyebrow'),...r.outcomes.map(o=>{const b=el('button',`第 ${o.attempt} 次尝试`,'attempt');b.append(el('span',o.success?'成功 ↗':'失败 ↗',o.success?'success':'failed'));b.title=o.feedback;b.onclick=()=>{setMode('steps');phase='before';move(r.steps.findIndex(s=>s.verdict?.attempt===o.attempt));};return b;}));
58
+ $('scrubber').max=r.steps.length-1;
59
+ $('warnings').replaceChildren(...r.warnings.map(w=>el('p',w)));
60
+ $('filmstrip').replaceChildren(...r.steps.map((s,n)=>{const b=el('button',undefined,'frame');b.setAttribute('aria-label',`第 ${n+1} 步,尝试 ${s.attempt}`);const f=s.before.find(f=>f.camera==='agentview')||s.before[0];b.append(f?.asset?img(f):el('span','无图片','placeholder'));b.append(el('span',`${String(n+1).padStart(2,'0')} · 尝试 ${s.attempt}`,'label'));if(s.verdict||s.notices.length)b.append(el('span',undefined,'dot'+(s.verdict?.success?'':' bad')));b.onclick=()=>move(n);return b;}));
61
+ setupVideo();
62
+ }
63
+ function renderReason(){
64
+ const s=step(),previous=run().steps[index-1];
65
+ $('reason-transition').textContent=index===0?'任务输入 → 第 1 步':`第 ${index} 步反馈 → 第 ${index+1} 步决策`;
66
+ $('reason-feedback').textContent=previous?previous.actions.map(a=>a.result===null?'结果未记录':fmt(a.result)).join('\n\n')||previous.text||'没有工具反馈':s.inputText||'初始输入未记录';
67
+ $('reason-summary').textContent=s.decisionSummary||(s.decisionSummaryStatus==='not_returned'?'模型未返回摘要。':'本步未记录摘要。');
68
+ $('reason-summary').classList.toggle('reason-empty',!s.decisionSummary);
69
+ $('reason-public-wrap').hidden=!s.text;$('reason-public').textContent=s.text||'';
70
+ $('reason-source').textContent=`来源:${run().source} 第 ${s.decisionSourceLine} 行 · turn ${s.turn??'—'}`;
71
+ }
72
+ function render(){
73
+ renderReason();
74
+ const r=run(),s=step(),after=allAfter(s),frames=phase==='before'?s.before:after;
75
+ const selected=frames.find(f=>`${f.path}@${f.source}`===selectedFrameKey)||frames.find(f=>f.camera===camera)||frames[0];if(selected)camera=selected.camera;
76
+ $('before').setAttribute('aria-pressed',String(phase==='before'));$('after').setAttribute('aria-pressed',String(phase==='after'));
77
+ $('attempt-label').textContent=`尝试 ${s.attempt} · 步骤 ${index+1}`;$('step-title').textContent=`Step ${String(index+1).padStart(2,'0')}`;
78
+ $('time').textContent=`+${clock(s.elapsed)}${s.latency==null?'':` · 模型耗时 ${s.latency.toFixed(1)}s`}`;
79
+ $('stage').replaceChildren(selected?.asset?img(selected):el('div',selected?'该图片文件缺失':'此步骤没有返回新图片','empty'));
80
+ const reset=s.actions.find(a=>a.resetToAttempt);
81
+ $('caption').textContent=selected?`${cameraName(selected.camera)} · ${selected.path} · 来源:transcript 第 ${selected.source} 行${phase==='after'&&reset?` · 已重置为尝试 ${reset.resetToAttempt}`:''}`:'日志未记录新图片;切换“决策前”查看最近观察。';
82
+ $('cameras').replaceChildren(...frames.map((f,n)=>{const b=el('button',undefined,'camera');b.setAttribute('aria-pressed',String(f===selected));if(f.asset)b.append(img(f));b.append(el('span',cameraName(f.camera)));b.onclick=()=>{camera=f.camera;selectedFrameKey=`${f.path}@${f.source}`;render();};return b;}));
83
+ $('observation-note').textContent=`最近一次收到 ${s.before.length} 张图片${s.requestImages==null?'':`;本次请求记录共 ${s.requestImages} 张图片(含历史)`}。`;
84
+ $('input-text').textContent=s.inputText||'没有记录输入文本。';
85
+ $('actions').replaceChildren(...s.actions.map(a=>{const box=el('div');box.append(el('div',a.name,'subtle'),el('pre',fmt(a.arguments)));return box;}));
86
+ if(!s.actions.length)$('actions').append(el('p','本步没有工具调用,Agent 输出最终报告。'));
87
+ $('results').replaceChildren();
88
+ if(s.verdict){$('results').append(el('div',s.verdict.success?'✓ 本次尝试成功':'↻ 本次尝试失败',`result-message ${s.verdict.success?'success':'failed'}`),el('p',s.verdict.feedback));}
89
+ for(const a of s.actions){
90
+ if(!s.verdict)$('results').append(el('div',a.result===null?'等待结果 / 日志缺失':a.ok===false?'工具返回错误':'工具已返回',`result-message ${a.ok===false?'failed':''}`));
91
+ if(a.resetToAttempt)$('results').append(el('div',`场景已重置:返回图片属于第 ${a.resetToAttempt} 次尝试。`,'notice'));
92
+ const d=el('details');d.append(el('summary',`${a.name} · 完整返回`),el('pre',a.result===null?'未记录':fmt(a.result)));$('results').append(d);
93
+ }
94
+ if(!s.actions.length)$('results').append(el('p','最终文字报告;结果以尝试判定为准。'));
95
+ const notices=[...s.notices,...(s.noticesAfter||[])];$('notices').replaceChildren(...notices.map(n=>el('div',`${n.kind==='api_error'?'API 重试':'运行中断'} · ${n.text}`,'notice')));
96
+ $('count').textContent=`${String(index+1).padStart(2,'0')} / ${r.steps.length}`;$('scrubber').value=index;$('prev').disabled=index===0;$('next').disabled=index===r.steps.length-1;
97
+ $('step-meta').textContent=`turn ${s.turn??'—'} · ${s.actions.length} 次工具调用${s.incomplete?' · 结果不完整':''}`;
98
+ [...$('filmstrip').children].forEach((b,n)=>b.setAttribute('aria-pressed',String(n===index)));
99
+ const selectedButton=$('filmstrip').children[index];if(selectedButton){const strip=$('filmstrip'),a=selectedButton.getBoundingClientRect(),b=strip.getBoundingClientRect();if(a.left<b.left||a.right>b.right)strip.scrollLeft+=a.left-b.left-strip.clientWidth/2+selectedButton.offsetWidth/2;}
100
+ }
101
+ $('prev').onclick=()=>move(index-1);$('next').onclick=()=>move(index+1);$('scrubber').oninput=e=>move(Number(e.target.value));
102
+ $('before').onclick=()=>{phase='before';render();};$('after').onclick=()=>{phase='after';render();};
103
+ $('play').onclick=()=>{if(timer){stop();return;}if(index===run().steps.length-1)move(0);$('play').textContent='Ⅱ 暂停';$('play').setAttribute('aria-label','暂停回放');timer=setInterval(()=>{if(index>=run().steps.length-1){stop();return;}move(index+1,false);if(index===run().steps.length-1)stop();},Number($('speed').value));};
104
+ $('speed').onchange=()=>{if(timer){stop();$('play').click();}};
105
+ $('video-tab').onclick=()=>setMode('video');$('steps-tab').onclick=()=>setMode('steps');
106
+ $('video-rate').onchange=e=>{$('execution-video').playbackRate=Number(e.target.value);};
107
+ $('execution-video').onerror=()=>{if(!run().video)return;$('video-error').textContent='视频加载失败,请刷新重试;仍可查看逐步输入与日志。';$('video-error').hidden=false;};
108
+ document.addEventListener('keydown',e=>{if(viewMode==='video')return;if(e.target.closest('input,select,textarea,button,summary'))return;if(e.key==='ArrowLeft'){e.preventDefault();move(index-1);}if(e.key==='ArrowRight'){e.preventDefault();move(index+1);}if(e.code==='Space'&&viewMode==='steps'){e.preventDefault();$('play').click();}});
109
+ renderRun();render();
110
+ </script>
111
+ </body></html>
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/sensenova.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant."""
2
+ from .framework_codex import RobotFrameworkCodex
3
+
4
+ class SenseNovaCodex(RobotFrameworkCodex):
5
+ name = "sensenova_codex"
6
+ runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi"
7
+
8
+ def __init__(self, **kwargs):
9
+ kwargs.setdefault("sessions", 1)
10
+ kwargs.setdefault("attempts_per_session", 0)
11
+ if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0:
12
+ raise ValueError("SenseNova controlled variant uses one persistent session for all attempts")
13
+ super().__init__(**kwargs)
14
+
15
+ def env(self, state, ep, base_url, work):
16
+ env = super().env(state, ep, base_url, work)
17
+ env["LFF_CONTROLLED_CODEX"] = "1"
18
+ return env
19
+
20
+ def config_info(self):
21
+ info = super().config_info()
22
+ info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns,
23
+ history="same-thread", cross_episode_memory=False)
24
+ return info
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/api_batch.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch of runs with a concurrency limit: the runner for the paper's main table (reference driver scripts/api_player.py)
2
+ and, with --harness, for native agent harnesses (side table, docs/15).
3
+
4
+ start python scripts/api_batch.py start --batch m1_opus --provider anthropic --model claude-opus-5-5 --effort high \
5
+ --tasks l1_height_bias:3000,3001 lh_bridge:3000 --k 3 --concurrency 6 --video
6
+ -> writes runs/api/<batch>/manifest.json (one entry per run, status "pending") and starts a background
7
+ runner that keeps at most --concurrency runs going (robot server + api_player each) and stops each
8
+ server when its player exits.
9
+ status python scripts/api_batch.py status --batch m1_opus
10
+ table python scripts/api_batch.py table --batch m1_opus [--batch ...] (same table as claude_batch + tokens)
11
+ stop python scripts/api_batch.py stop --batch m1_opus (runner, players, servers; runs -> "stopped")
12
+ retry python scripts/api_batch.py retry --batch m1_opus [--runs <run> ...] (default: every failed / stopped / timeout run;
13
+ old logs stay, listed under "superseded"; starts the runner again)
14
+ followup python scripts/api_batch.py followup --batch m1_opus (switch a batch started before 2026-10-19 to
15
+ --memfree followup: plans the memory-free retries due for its finished history runs; then `retry` starts them)
16
+ contract python scripts/api_batch.py contract --batch b1 [--batch b2 ...] (contract_sha256 per instance and condition;
17
+ flags instances whose hash differs between batches: those cells must not share a table)
18
+ pause touch runs/api/<batch>/PAUSE: the runner launches no new run while the file exists; the runs going on finish
19
+ and are recorded as usual (rm the file to go on). Used by quota watchers to stay below a usage window.
20
+
21
+ --harness (default ours): which agent harness drives each run, through scripts/harness_run.py (lffbench/harnesses):
22
+ ours scripts/api_player.py, unchanged (--provider as before)
23
+ claude_code Claude Code CLI --bare, only our MCP tools, one-time config dirs (arm B; provider anthropic)
24
+ claude_code_full Claude Code CLI without --bare (full system prompt), otherwise the same (arm B');
25
+ --claude-auth oauth (default): the subscription token of `claude setup-token` (LFF_CLAUDE_OAUTH_FILE),
26
+ apikey: ANTHROPIC_API_KEY (claude_code takes only apikey)
27
+ codex Codex CLI exec --ephemeral, empty CODEX_HOME, only our MCP tools reachable (arm F; provider openai);
28
+ --codex-auth chatgpt (default): the ChatGPT subscription login, apikey: OPENAI_API_KEY
29
+ dsh DeepSeek Harness headless, only our MCP tools, one-time dirs (lffbench/harnesses/dsh.py; provider
30
+ deepseek, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)
31
+ Native harnesses are refused at launch (status "refused") unless their preset prompt / tool list matches the pin
32
+ written by tests/harness_selfcheck (--allow-unpinned to launch anyway; the preflight still runs). Every run gets
33
+ harness.json, contract.json, trajectory.jsonl and harness_audit.json in its log dir.
34
+
35
+ Conditions (same as claude_batch): harness = memory full, k attempts in one agent; noharness = independent single-attempt
36
+ agents (memory none, k=1). History runs use --hide-k (README and status say 1 attempt, byte-identical to an independent
37
+ run; more attempts are announced only after a failure; --no-hide-k to show k).
38
+ --memfree, how the memory-free retries (pass@k without history) are run:
39
+ followup (default, 2026-10-19): one history run per instance. Its attempt 1 is also the first memory-free attempt,
40
+ since under --hide-k it sees exactly what a fresh agent sees. Only if attempt 1 fails does the runner add a
41
+ fresh single-attempt agent (noharness rep 1, "chain" = the history run's id); if that one fails too, the
42
+ next (rep 2), up to k-1 of them; the first success ends the chain. An instance solved on attempt 1 thus
43
+ costs one attempt in all. Not for tasks whose scene persists between attempts (task protocol "within"):
44
+ a fresh agent would start from the initial scene, the history run's attempt 2 from the failed one, so the
45
+ two conditions would differ; these tasks are reported without memory-free retries (user 2026-10-20).
46
+ upfront the 2026-10-11 protocol: --indep-reps independent runs per instance (default k, all of them run), all
47
+ before the history runs (--conds order; --no-barrier to mix the phases).
48
+ none history runs only.
49
+ --seeds-per-task N keeps the first N seeds of each task:seeds (e.g. 1 = one instance per task).
50
+ API keys come from LFF_ENV_FILE (default <repo>/.env, KEY=value lines) or the environment.
51
+ """
52
+ import argparse
53
+ import json
54
+ import os
55
+ import re
56
+ import shlex
57
+ import signal
58
+ import subprocess
59
+ import sys
60
+ import threading
61
+ import time
62
+
63
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
64
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
65
+ import claude_batch # noqa: E402
66
+
67
+ RUNS = os.path.join(ROOT, "runs", "api")
68
+ ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
69
+ ACTIVE = ("starting", "running")
70
+ RETRYABLE = ("failed", "stopped", "timeout", "server_failed")
71
+ sys.path.insert(0, ROOT)
72
+ from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER as HARNESS_PROVIDER
73
+
74
+
75
+
76
+ def bdir(batch):
77
+ return os.path.join(RUNS, batch)
78
+
79
+
80
+ def mpath(batch):
81
+ return os.path.join(bdir(batch), "manifest.json")
82
+
83
+
84
+ def load(batch):
85
+ with open(mpath(batch)) as f:
86
+ return json.load(f)
87
+
88
+
89
+ def save(batch, m):
90
+ os.makedirs(bdir(batch), exist_ok=True)
91
+ tmp = mpath(batch) + ".tmp"
92
+ with open(tmp, "w") as f:
93
+ json.dump(m, f, indent=1)
94
+ os.replace(tmp, mpath(batch))
95
+
96
+
97
+ def alive(pid):
98
+ try:
99
+ os.kill(int(pid), 0)
100
+ return True
101
+ except (ProcessLookupError, PermissionError, TypeError, ValueError):
102
+ return False
103
+
104
+
105
+ def runner_alive(batch):
106
+ p = os.path.join(bdir(batch), "runner.pid")
107
+ return os.path.exists(p) and alive(open(p).read().strip())
108
+
109
+
110
+ def launch_runner(batch):
111
+ log = open(os.path.join(bdir(batch), "runner.log"), "a")
112
+ p = subprocess.Popen([sys.executable, os.path.abspath(__file__), "_runner", "--batch", batch], cwd=ROOT,
113
+ start_new_session=True, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
114
+ with open(os.path.join(bdir(batch), "runner.pid"), "w") as f:
115
+ f.write(str(p.pid))
116
+ return p.pid
117
+
118
+
119
+ def next_id(m):
120
+ return f"{max((int(r['id']) for r in m['runs']), default=-1) + 1:04d}"
121
+
122
+
123
+ # ------------------------------------------------------------------------------------------------- memory-free chains
124
+ # --memfree followup: per instance, history run (cond harness, followup=True) -> noharness rep 1 -> ... -> rep k-1,
125
+ # each link planned only after the previous attempts all failed. Attempt 1 of the history run is the chain's first
126
+ # attempt (--hide-k makes it identical to a fresh agent's), so the memory-free pass@k of an instance is: attempt 1 of
127
+ # the history run, or any of its chain runs, succeeded.
128
+ PLAN_KEYS = ("task", "seed", "provider", "agent_harness", "api_base_url", "max_budget_usd", "allow_unpinned", "jail",
129
+ "codex_auth", "claude_auth", "codex_catalog", "codex_provider",
130
+ "rpent_sessions", "rpent_attempts_per_session", "rpent_max_turns",
131
+ "model", "effort", "perception", "video", "style", "feedback", "phase", "nominal", "red_team")
132
+
133
+
134
+ def attempt_results(log):
135
+ """[success of attempt 1, of attempt 2, ...] from the robot server log ([] if there is none)."""
136
+ p = os.path.join(log or "", "events.jsonl")
137
+ if not os.path.exists(p):
138
+ return []
139
+ res = {}
140
+ for line in open(p):
141
+ e = json.loads(line)
142
+ if e.get("ev") == "done":
143
+ res[e["attempt"]] = bool(e["success"])
144
+ return [res[i] for i in sorted(res)]
145
+
146
+
147
+ def episode_protocol(log):
148
+ """The task's attempt protocol ("cross": reset between attempts, "within": the scene persists) from the robot
149
+ server log's session_start line; None if unknown."""
150
+ p = os.path.join(log or "", "events.jsonl")
151
+ if os.path.exists(p):
152
+ for line in open(p):
153
+ e = json.loads(line)
154
+ if e.get("ev") == "session_start":
155
+ return e.get("protocol")
156
+ return None
157
+
158
+
159
+ def plan_followup(m, r):
160
+ """Run r has finished: append the next memory-free retry of its instance if one is due; returns it or None."""
161
+ if r["status"] != "done":
162
+ return None
163
+ if r["cond"] == "harness" and r.get("followup"):
164
+ if episode_protocol(r.get("log")) == "within": # no like-for-like fresh agent (module docstring)
165
+ return None
166
+ root, nxt, res = r, 1, attempt_results(r.get("log"))[:1]
167
+ elif r.get("chain"):
168
+ root = next((x for x in m["runs"] if x["id"] == r["chain"]), None)
169
+ nxt, res = r["rep"] + 1, attempt_results(r.get("log"))
170
+ else:
171
+ return None
172
+ if root is None or not res or any(res) or nxt >= root["k"]:
173
+ return None
174
+ if any(x.get("chain") == root["id"] and x["rep"] == nxt for x in m["runs"]):
175
+ return None
176
+ new = {k: root.get(k) for k in PLAN_KEYS}
177
+ new.update(id=next_id(m), cond="noharness", rep=nxt, k=1, mem="none", hide_k=False, chain=root["id"],
178
+ status="pending")
179
+ m["runs"].append(new)
180
+ return new
181
+
182
+
183
+ def memfree_chain(m, root):
184
+ """Table rows for the memory-free retries of root's instance: its attempt 1 (rep 0, only_attempt=1) and the chain
185
+ runs after it. [] while the chain has not ended (a success, or k attempts)."""
186
+ first = attempt_results(root.get("log"))[:1]
187
+ if not first:
188
+ return []
189
+ rows = [dict(root, cond="noharness", rep=0, k=1, only_attempt=1)]
190
+ if first[0]:
191
+ return rows
192
+ chain = {x["rep"]: x for x in m["runs"] if x.get("chain") == root["id"] and x["status"] == "done" and x.get("log")}
193
+ for rep in range(1, root["k"]):
194
+ if rep not in chain:
195
+ return []
196
+ rows.append(dict(chain[rep]))
197
+ if any(attempt_results(chain[rep]["log"])):
198
+ break
199
+ return rows
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------------------ start
203
+ def cmd_start(a):
204
+ a.codex_auth = a.codex_auth or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
205
+ if a.harness == "rpent_codex" and a.codex_auth != "apikey":
206
+ sys.exit("Historical RPent adapter supports apikey only")
207
+ if runner_alive(a.batch):
208
+ sys.exit(f"batch {a.batch}: runner already running; stop it first or use another batch name")
209
+ m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[], superseded=[])
210
+ m.update(concurrency=a.concurrency, barrier=not a.no_barrier, port0=a.port0, run_timeout_s=a.run_timeout)
211
+ reps = a.k if a.indep_reps is None else a.indep_reps
212
+ if a.harness != "ours":
213
+ need = HARNESS_PROVIDER[a.harness]
214
+ if a.provider and a.provider != need:
215
+ sys.exit(f"--harness {a.harness} drives {need} models only (got --provider {a.provider})")
216
+ a.provider = need
217
+ elif not a.provider:
218
+ sys.exit("--provider is required with --harness ours")
219
+ claude_auth = None
220
+ if a.harness.startswith("claude_code"):
221
+ claude_auth = a.claude_auth or ("apikey" if a.harness == "claude_code" else "oauth")
222
+ if claude_auth == "oauth" and a.harness == "claude_code":
223
+ sys.exit("--harness claude_code (--bare) takes only an API key; use claude_code_full for a subscription")
224
+ elif a.claude_auth:
225
+ sys.exit("--claude-auth is for --harness claude_code / claude_code_full")
226
+ if a.jail and a.harness == "ours":
227
+ sys.exit("--jail is for native harnesses (the reference driver runs our own code)")
228
+ if a.red_team and a.harness == "ours":
229
+ sys.exit("--red-team is for native harnesses (lffbench/harnesses/redteam.py)")
230
+ if a.memfree == "upfront":
231
+ conds = [c.strip() for c in (a.conds or "noharness,harness").split(",") if c.strip()]
232
+ else:
233
+ if a.conds and a.conds.replace(" ", "") != "harness":
234
+ sys.exit(f"--conds is for --memfree upfront (--memfree {a.memfree} plans history runs only)")
235
+ if a.memfree == "followup" and a.no_hide_k:
236
+ sys.exit("--memfree followup shares attempt 1 of the history run with the memory-free retries: needs --hide-k")
237
+ conds = ["harness"]
238
+ dossiers = json.load(open(a.dossiers)) if a.dossiers else None
239
+ if dossiers is not None: # task:seed -> record dir (scripts/make_dossier.py); every planned instance needs one
240
+ miss = [f"{spec.split(':')[0]}:{sd}" for spec in a.tasks for sd in spec.split(":")[1].split(",")[:a.seeds_per_task]
241
+ if f"{spec.split(':')[0]}:{sd}" not in dossiers]
242
+ if miss:
243
+ sys.exit(f"--dossiers has no record for {miss}")
244
+ bad = [d for d in dossiers.values() if not os.path.isfile(os.path.join(d, "README.md")) or any(c.isspace() for c in d)]
245
+ if bad:
246
+ sys.exit(f"--dossiers: not a record dir (or path with spaces): {bad}")
247
+ n0 = len(m["runs"])
248
+ for cond in conds: # the order of --conds is the order of the phases
249
+ for spec in a.tasks:
250
+ task, seeds = spec.split(":")
251
+ for seed in seeds.split(",")[:a.seeds_per_task]:
252
+ plan = [("harness", "full", a.k, 0)] if cond == "harness" else \
253
+ [("noharness", "none", 1, i) for i in range(reps)]
254
+ for c, mem, k, rep in plan:
255
+ m["runs"].append(dict(id=next_id(m), task=task, seed=int(seed), provider=a.provider,
256
+ agent_harness=a.harness, api_base_url=a.api_base_url,
257
+ max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
258
+ jail=a.jail, codex_auth=(("apikey" if a.codex_provider in ("deepseek", "opencode") else a.codex_auth)
259
+ if a.harness in ("codex", *ROBOT_HARNESSES) else None),
260
+ claude_auth=claude_auth,
261
+ codex_catalog=(a.codex_catalog if a.harness in ("codex", *ROBOT_HARNESSES)
262
+ else None),
263
+ **(dict(rpent_sessions=a.rpent_sessions,
264
+ rpent_attempts_per_session=a.rpent_attempts_per_session,
265
+ rpent_max_turns=a.rpent_max_turns)
266
+ if a.harness == "rpent_codex" else {}),
267
+ codex_provider=(a.codex_provider if a.harness == "codex" else None),
268
+ model=a.model, effort=a.effort, cond=c, rep=rep, k=k, mem=mem,
269
+ hide_k=(c == "harness" and not a.no_hide_k), perception=a.perception,
270
+ video=a.video, style="la", feedback=a.feedback, phase=conds.index(cond),
271
+ nominal=a.nominal, followup=(c == "harness" and a.memfree == "followup"),
272
+ arm=a.arm, red_team=a.red_team, dossier=(os.path.abspath(dossiers[f"{task}:{seed}"]) if dossiers else None),
273
+ status="pending"))
274
+ save(a.batch, m)
275
+ print(f"{len(m['runs']) - n0} runs planned ({', '.join(conds)}, --memfree {a.memfree}); manifest {mpath(a.batch)}")
276
+ if a.memfree == "followup":
277
+ print("memory-free retries are added while the batch runs, for instances whose attempt 1 failed")
278
+ print("runner pid", launch_runner(a.batch))
279
+
280
+
281
+ # ------------------------------------------------------------------------------------------------------------ runner
282
+ class Runner:
283
+ def __init__(self, batch):
284
+ self.batch = batch
285
+ self.lock = threading.Lock()
286
+ self.m = load(batch)
287
+ self.used_ports = set()
288
+ self.stop = False
289
+
290
+ def update(self, r, **kw):
291
+ with self.lock:
292
+ r.update(kw)
293
+ save(self.batch, self.m)
294
+
295
+ def next_run(self):
296
+ with self.lock:
297
+ runs = self.m["runs"]
298
+ pending = [r for r in runs if r["status"] == "pending"]
299
+ if not pending:
300
+ # a run still going may yet add a memory-free retry (--memfree followup)
301
+ if any(r["status"] in ACTIVE and (r.get("followup") or r.get("chain")) for r in runs):
302
+ return "wait"
303
+ return None
304
+ if self.m.get("barrier", True):
305
+ phase = min(r["phase"] for r in pending)
306
+ if any(r["status"] in ACTIVE and r["phase"] < phase for r in runs):
307
+ return "wait"
308
+ pending = [r for r in pending if r["phase"] == phase]
309
+ if os.path.exists(os.path.join(bdir(self.batch), "PAUSE")):
310
+ return "wait"
311
+ r = pending[0]
312
+ r["status"] = "starting"
313
+ save(self.batch, self.m)
314
+ return r
315
+
316
+ def port(self):
317
+ with self.lock:
318
+ p = int(self.m.get("port0", 14000))
319
+ while p in self.used_ports or not claude_batch.port_free(p):
320
+ p += 1
321
+ self.used_ports.add(p)
322
+ return p
323
+
324
+ def run_one(self, r):
325
+ port = self.port()
326
+ model_tag = re.sub(r"[^A-Za-z0-9.-]+", "-", r["model"])[:40]
327
+ ah = r.get("agent_harness", "ours")
328
+ if ah != "ours":
329
+ model_tag += "-" + ah.replace("_", "")
330
+ tag = (f"{self.batch}-{model_tag}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
331
+ + ("-hidek" if r["hide_k"] else "") + ("-nominal" if r.get("nominal") else "")
332
+ + (f"-{r['arm']}" if r.get("arm", "none") != "none" else "") + ("-dossier" if r.get("dossier") else "")
333
+ + ("-redteam" if r.get("red_team") else ""))
334
+ extra = (" --hide-k" if r["hide_k"] else "") + (" --nominal" if r.get("nominal") else "")
335
+ # docs/14 §6 arms (robot_server --arm / --dossier); LFF_EXTRA_ARGS is word-split, so no spaces in the path
336
+ extra += (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + (f" --dossier {r['dossier']}" if r.get("dossier") else "")
337
+ t0 = time.time()
338
+ try:
339
+ sb, log = claude_batch.start_one(r["task"], r["seed"], r["mem"], r["k"], port, tag, r["perception"],
340
+ r["video"], r["style"], extra.strip(), r["feedback"])
341
+ except Exception as e: # server did not come up
342
+ self.update(r, status="server_failed", error=str(e)[-500:], port=port)
343
+ with self.lock:
344
+ self.used_ports.discard(port)
345
+ return
346
+ self.update(r, status="running", port=port, sandbox=sb, log=log, run=os.path.basename(log), t_start=t0)
347
+ opts = ""
348
+ if r.get("api_base_url"):
349
+ opts += f" --api-base-url {shlex.quote(r['api_base_url'])}"
350
+ if r.get("max_budget_usd"):
351
+ opts += f" --max-budget-usd {r['max_budget_usd']}"
352
+ if r.get("allow_unpinned"):
353
+ opts += " --allow-unpinned"
354
+ if r.get("jail"):
355
+ opts += " --jail"
356
+ if r.get("red_team"):
357
+ opts += " --red-team"
358
+ if r.get("codex_auth"):
359
+ opts += f" --codex-auth {r['codex_auth']}"
360
+ if r.get("claude_auth"):
361
+ opts += f" --claude-auth {r['claude_auth']}"
362
+ if r.get("agent_harness") in ("codex", *ROBOT_HARNESSES) and r.get("agent_harness") != "rpent_codex": # runs planned before 10-20 have no catalog: Codex's native one
363
+ opts += f" --codex-catalog {r.get('codex_catalog') or 'native'}"
364
+ if r.get("codex_provider") in ("deepseek", "opencode"):
365
+ opts += f" --codex-provider {r['codex_provider']}"
366
+ if r.get("agent_harness") == "rpent_codex":
367
+ opts += (f" --codex-catalog {r.get('codex_catalog') or 'generic'}"
368
+ f" --rpent-sessions {r.get('rpent_sessions') or 5}"
369
+ f" --rpent-attempts-per-session {r.get('rpent_attempts_per_session', 1)}"
370
+ f" --rpent-max-turns {r.get('rpent_max_turns') or 100}")
371
+ # every harness (also ours: api_player.py with the same arguments as before, its output still in
372
+ # api_player.log) goes through the adapter layer, which adds harness.json / contract.json / trajectory.jsonl
373
+ player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
374
+ f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
375
+ f"exec python scripts/harness_run.py --harness {ah} --session {log}/session.json "
376
+ f"--provider {r['provider']} --model {shlex.quote(r['model'])} --effort {r['effort']} "
377
+ f"--timeout {int(self.m.get('run_timeout_s', 28800))}{opts} > {log}/harness_run.log 2>&1")
378
+ p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
379
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
380
+ self.update(r, player_pid=p.pid)
381
+ status = None
382
+ try:
383
+ code = p.wait(timeout=self.m.get("run_timeout_s", 28800))
384
+ except subprocess.TimeoutExpired:
385
+ os.killpg(p.pid, signal.SIGTERM)
386
+ code, status = p.wait(), "timeout"
387
+ self.stop_server(log)
388
+ if status is None:
389
+ status = "stopped" if self.stop else ("done" if code == 0 else "refused" if code == 2 else "failed")
390
+ self.update(r, status=status, exit_code=code, t_end=time.time(), wall_s=round(time.time() - t0, 1))
391
+ with self.lock:
392
+ self.used_ports.discard(port)
393
+ if plan_followup(self.m, r):
394
+ save(self.batch, self.m)
395
+
396
+ @staticmethod
397
+ def stop_server(log):
398
+ pf = os.path.join(log, "server.pid")
399
+ if not os.path.exists(pf):
400
+ return
401
+ pid = int(open(pf).read())
402
+ try:
403
+ os.kill(pid, signal.SIGTERM) # the server closes rollout.mp4 first
404
+ except ProcessLookupError:
405
+ return
406
+ for _ in range(120):
407
+ if not alive(pid):
408
+ return
409
+ time.sleep(0.5)
410
+
411
+ def worker(self):
412
+ while not self.stop:
413
+ r = self.next_run()
414
+ if r is None:
415
+ return
416
+ if r == "wait":
417
+ time.sleep(5)
418
+ continue
419
+ try:
420
+ self.run_one(r)
421
+ except Exception as e: # keep the other workers going
422
+ self.update(r, status="failed", error=f"runner: {type(e).__name__}: {e}"[:500])
423
+
424
+ def main(self):
425
+ os.environ["LFF_RUNS_DIR"] = bdir(self.batch) # claude_batch.start_one puts the run logs here
426
+ for r in self.m["runs"]: # a previous runner died: its half-started runs go back to pending
427
+ if r["status"] in ACTIVE:
428
+ r["status"] = "pending"
429
+ for r in list(self.m["runs"]): # memory-free retries due but not yet planned (runner died, `followup`)
430
+ plan_followup(self.m, r)
431
+ save(self.batch, self.m)
432
+
433
+ def on_term(*_):
434
+ self.stop = True
435
+ with self.lock:
436
+ for r in self.m["runs"]:
437
+ if r["status"] == "running" and r.get("player_pid"):
438
+ try:
439
+ os.killpg(r["player_pid"], signal.SIGTERM)
440
+ except ProcessLookupError:
441
+ pass
442
+ signal.signal(signal.SIGTERM, on_term)
443
+ ths = [threading.Thread(target=self.worker, daemon=True) for _ in range(int(self.m.get("concurrency", 4)))]
444
+ for t in ths:
445
+ t.start()
446
+ time.sleep(2) # stagger server start-ups
447
+ for t in ths:
448
+ t.join()
449
+ print(time.strftime("%F %T"), "runner finished", flush=True)
450
+
451
+
452
+ def cmd_runner(a):
453
+ Runner(a.batch).main()
454
+
455
+
456
+ # ------------------------------------------------------------------------------------------------------------ views
457
+ def transcript_usage(log):
458
+ tot = dict(calls=0, input_tokens=0, cached_tokens=0, output_tokens=0, api_errors=0, end=None)
459
+ p = os.path.join(log or "", "transcript.jsonl")
460
+ if not os.path.exists(p): # native harness: totals from the unified trajectory
461
+ sys.path.insert(0, ROOT)
462
+ from lffbench.harnesses.trajectory import usage_summary
463
+ u = usage_summary(log)
464
+ if u:
465
+ tot.update(calls=u.get("calls", 0), input_tokens=u.get("total_prompt_tokens") or 0,
466
+ cached_tokens=u.get("total_cached_tokens") or 0,
467
+ output_tokens=u.get("total_completion_tokens") or 0, end=u.get("exit_reason"),
468
+ cost_usd=u.get("total_cost_usd"))
469
+ return tot
470
+ for line in open(p):
471
+ d = json.loads(line)
472
+ if d["ev"] == "assistant":
473
+ tot["calls"] += 1
474
+ for k in ("input_tokens", "cached_tokens", "output_tokens"):
475
+ tot[k] += (d.get("usage") or {}).get(k, 0)
476
+ elif d["ev"] == "api_error":
477
+ tot["api_errors"] += 1
478
+ elif d["ev"] in ("end", "abort"):
479
+ tot["end"] = d["ev"] if d["ev"] == "end" else "abort: " + d.get("reason", "")
480
+ return tot
481
+
482
+
483
+ def cmd_status(a):
484
+ m = load(a.batch)
485
+ counts = {}
486
+ for r in m["runs"]:
487
+ counts[r["status"]] = counts.get(r["status"], 0) + 1
488
+ att = ""
489
+ if r.get("log") and os.path.exists(os.path.join(r["log"], "events.jsonl")):
490
+ ev = [json.loads(line) for line in open(os.path.join(r["log"], "events.jsonl"))]
491
+ att = "".join("S" if e["success"] else "F" for e in ev if e["ev"] == "done")
492
+ u = transcript_usage(r.get("log"))
493
+ print(f"{r['id']} {r['status']:13s} {r.get('agent_harness', 'ours'):16s} "
494
+ f"{r['cond']:9s}{r['rep'] if r['cond'] == 'noharness' else '':1} "
495
+ f"{r['task']:24s} s{r['seed']} {att:4s} calls={u['calls']:3d} api_err={u['api_errors']} "
496
+ f"in={u['input_tokens'] / 1e6:.2f}M out={u['output_tokens'] / 1e3:.0f}k {u['end'] or ''}"
497
+ + (f" (memory-free attempt {r['rep'] + 1} after {r['chain']})" if r.get("chain") else ""))
498
+ print("runner", "alive" if runner_alive(a.batch) else "not running", "|", counts)
499
+
500
+
501
+ def cmd_table(a):
502
+ def done_runs(b):
503
+ m = load(b)
504
+ runs = []
505
+ for r in m["runs"]:
506
+ if not (r.get("log") and r["status"] == "done") or r.get("chain"):
507
+ continue
508
+ runs.append(dict(r))
509
+ if r["cond"] == "harness" and r.get("followup"): # its memory-free chain, once finished
510
+ runs += memfree_chain(m, r)
511
+ for r in runs: # the harness is part of the table's "model" column (claude_batch groups by task, model)
512
+ if r.get("agent_harness", "ours") != "ours":
513
+ r["model"] = f"{r['model']} @ {r['agent_harness']}"
514
+ return dict(m, runs=runs)
515
+ claude_batch.load = done_runs # same manifest fields (task, seed, model, cond, rep, k, log): reuse its table
516
+ # token totals: every run once (the rep-0 row of a chain is attempt 1 of a history run, already counted)
517
+ rows = [r for b in a.batch for r in done_runs(b)["runs"] if not r.get("only_attempt")]
518
+ claude_batch.cmd_table(argparse.Namespace(batch=a.batch))
519
+ by = {}
520
+ for r in rows:
521
+ u = transcript_usage(r["log"])
522
+ t = by.setdefault((r.get("agent_harness", "ours"), r["provider"], r["model"], r["effort"]), [0, 0, 0, 0, 0])
523
+ t[0] += 1
524
+ t[1] += u["calls"]
525
+ t[2] += u["input_tokens"]
526
+ t[3] += u["cached_tokens"]
527
+ t[4] += u["output_tokens"]
528
+ print("\n| harness | provider | model | effort | runs done | model calls | input tokens (M) | of which cached (M) | output tokens (M) |")
529
+ print("|---|---|---|---|---|---|---|---|---|")
530
+ for (h, p, mo, e), t in sorted(by.items()):
531
+ print(f"| {h} | {p} | {mo} | {e} | {t[0]} | {t[1]} | {t[2] / 1e6:.1f} | {t[3] / 1e6:.1f} | {t[4] / 1e6:.2f} |")
532
+
533
+
534
+ def cmd_contract(a):
535
+ """contract_sha256 per (task, seed, cond) and batch; an instance whose hash differs between batches is flagged."""
536
+ import collections
537
+ seen = collections.defaultdict(dict)
538
+ for b in a.batch:
539
+ for r in load(b)["runs"]:
540
+ p = os.path.join(r.get("log") or "", "contract.json")
541
+ if r.get("log") and os.path.exists(p):
542
+ sha = json.load(open(p))["contract_sha256"]
543
+ seen[(r["task"], r["seed"], r["cond"])].setdefault(b, set()).add(sha)
544
+ bad = 0
545
+ print("| task | seed | cond | " + " | ".join(a.batch) + " | same |")
546
+ print("|---|---|---|" + "---|" * len(a.batch) + "---|")
547
+ for (task, seed, cond), per in sorted(seen.items()):
548
+ shas = set().union(*per.values())
549
+ same = len(shas) == 1
550
+ bad += not same
551
+ cells = [",".join(sorted(x[:12] for x in per.get(b, []))) or "-" for b in a.batch]
552
+ print(f"| {task} | {seed} | {cond} | " + " | ".join(cells) + f" | {'yes' if same else '**NO**'} |")
553
+ print(f"\n{len(seen)} instance/condition rows, {bad} with differing contracts")
554
+
555
+
556
+ def cmd_stop(a):
557
+ pf = os.path.join(bdir(a.batch), "runner.pid")
558
+ if os.path.exists(pf) and alive(open(pf).read().strip()):
559
+ os.kill(int(open(pf).read().strip()), signal.SIGTERM) # the runner stops its players and servers
560
+ for _ in range(240):
561
+ if not runner_alive(a.batch):
562
+ break
563
+ time.sleep(0.5)
564
+ m = load(a.batch)
565
+ for r in m["runs"]: # anything left over (runner killed hard)
566
+ if r["status"] in ACTIVE:
567
+ if r.get("player_pid"):
568
+ try:
569
+ os.killpg(r["player_pid"], signal.SIGTERM)
570
+ except ProcessLookupError:
571
+ pass
572
+ if r.get("log"):
573
+ Runner.stop_server(r["log"])
574
+ r["status"] = "stopped"
575
+ save(a.batch, m)
576
+ print("stopped")
577
+
578
+
579
+ def cmd_retry(a):
580
+ if runner_alive(a.batch):
581
+ sys.exit("runner still running: stop it first")
582
+ m = load(a.batch)
583
+ reset = []
584
+ for r in m["runs"]:
585
+ if (a.runs and (r.get("run") in a.runs or r["id"] in a.runs)) or (not a.runs and r["status"] in RETRYABLE):
586
+ if r.get("log"):
587
+ m.setdefault("superseded", []).append(dict(r))
588
+ for k in ("port", "sandbox", "log", "run", "player_pid", "exit_code", "t_start", "t_end", "wall_s", "error"):
589
+ r.pop(k, None)
590
+ r["status"] = "pending"
591
+ reset.append(r)
592
+ # memory-free retries planned after a run that is now re-run were based on attempts that no longer count
593
+ stale = [x for x in m["runs"] if x.get("chain") and all(x is not y for y in reset) and any(
594
+ x["chain"] == y["id"] or (x["chain"] == y.get("chain") and x["rep"] > y["rep"]) for y in reset)]
595
+ for x in stale:
596
+ m["runs"].remove(x)
597
+ if x.get("log"):
598
+ m.setdefault("superseded", []).append(dict(x, superseded_because="earlier attempt of its chain re-run"))
599
+ save(a.batch, m)
600
+ print(len(reset), "runs reset to pending" + (f", {len(stale)} memory-free retries after them dropped" if stale else "")
601
+ + "; runner pid", launch_runner(a.batch))
602
+
603
+
604
+ def cmd_followup(a):
605
+ """Switch a batch to --memfree followup: mark its --hide-k history runs and plan the memory-free retries due for
606
+ those already done. `retry` then starts the runner (and re-runs failed / stopped runs)."""
607
+ if runner_alive(a.batch):
608
+ sys.exit("runner still running: stop it first")
609
+ m = load(a.batch)
610
+ marked = left = 0
611
+ for r in m["runs"]:
612
+ if r["cond"] == "harness" and not r.get("followup"):
613
+ if r.get("hide_k"):
614
+ r["followup"] = True
615
+ marked += 1
616
+ else:
617
+ left += 1
618
+ new = [x for r in list(m["runs"]) for x in [plan_followup(m, r)] if x]
619
+ save(a.batch, m)
620
+ print(f"{marked} history runs switched to --memfree followup"
621
+ + (f" ({left} without --hide-k left out: their attempt 1 is not a fresh agent's)" if left else "")
622
+ + f"; {len(new)} memory-free retries planned")
623
+ print(f"start the runner with: python scripts/api_batch.py retry --batch {a.batch}")
624
+
625
+
626
+ def main():
627
+ ap = argparse.ArgumentParser()
628
+ sub = ap.add_subparsers(dest="cmd", required=True)
629
+ s = sub.add_parser("start")
630
+ s.add_argument("--batch", required=True)
631
+ s.add_argument("--harness", default="ours", choices=NAMES,
632
+ help="agent harness (docs/15); native harnesses imply the provider; rpent_codex = RPent on Codex "
633
+ "(docs/18), OpenAI API key only (LFF_OPENAI_API_KEY)")
634
+ s.add_argument("--provider", default=None, choices=["openai", "anthropic", "gemini", "chat"],
635
+ help="required for --harness ours")
636
+ s.add_argument("--api-base-url", default=None, help="native harnesses: model API endpoint (see harness_run.py)")
637
+ s.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: per-run dollar cap")
638
+ s.add_argument("--allow-unpinned", action="store_true", help="native harnesses: launch without a pin")
639
+ s.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
640
+ help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
641
+ "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
642
+ s.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
643
+ help="claude_code*: subscription token (default for claude_code_full) or ANTHROPIC_API_KEY "
644
+ "(claude_code, --bare: apikey only)")
645
+ s.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
646
+ help="codex: model provider; deepseek / opencode (OpenCode Go) imply --codex-auth apikey "
647
+ "(see harness_run.py)")
648
+ s.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
649
+ help="codex: model configuration, the main table's shared one (default) or Codex's native one "
650
+ "(control; see lffbench/harnesses/codex.py)")
651
+ s.add_argument("--rpent-sessions", type=int, default=5, help="rpent_codex: planner sessions per episode")
652
+ s.add_argument("--rpent-attempts-per-session", type=int, default=1,
653
+ help="rpent_codex: attempts one session may use (1 = variant H, default; 0 = no limit)")
654
+ s.add_argument("--rpent-max-turns", type=int, default=100, help="rpent_codex: model responses per session")
655
+ s.add_argument("--jail", action="store_true",
656
+ help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4, lffbench/harnesses/jail.py)")
657
+ s.add_argument("--model", required=True)
658
+ s.add_argument("--effort", default="high")
659
+ s.add_argument("--tasks", nargs="+", required=True, help="task:seed,seed ...")
660
+ s.add_argument("--k", type=int, default=3)
661
+ s.add_argument("--seeds-per-task", type=int, default=None, help="only the first N seeds of each task:seeds")
662
+ s.add_argument("--memfree", default="followup", choices=["followup", "upfront", "none"],
663
+ help="memory-free retries: followup (default) = fresh single-attempt agents only after the history "
664
+ "run's attempt 1 failed, one at a time, up to k attempts in all, stop at the first success; "
665
+ "upfront = --indep-reps independent runs per instance before the history runs; none = no "
666
+ "memory-free retries (see the module docstring)")
667
+ s.add_argument("--indep-reps", type=int, default=None, help="--memfree upfront: independent runs per instance (default k)")
668
+ s.add_argument("--conds", default=None, help="--memfree upfront: conditions in phase order (default noharness,harness)")
669
+ s.add_argument("--no-barrier", action="store_true", help="do not wait for one phase to finish before the next")
670
+ s.add_argument("--no-hide-k", action="store_true", help="history runs: README / status show all k attempts")
671
+ s.add_argument("--concurrency", type=int, default=4)
672
+ s.add_argument("--port0", type=int, default=14000)
673
+ s.add_argument("--run-timeout", type=int, default=28800,
674
+ help="seconds per run before the player is killed (default 8 h: a long-horizon history run can need 300+ model calls)")
675
+ s.add_argument("--perception", default="rgb", choices=["rgb", "rgbd"])
676
+ s.add_argument("--video", action="store_true")
677
+ s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
678
+ s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
679
+ s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
680
+ help="docs/14 §6 controlled arm for every run: twin = same layout, other value of the hidden variable")
681
+ s.add_argument("--red-team", action="store_true",
682
+ help="adversarial acceptance runs (lffbench/harnesses/redteam.py): the agent is told to get a success "
683
+ "without doing the task; own contract; read with scripts/redteam_report.py")
684
+ s.add_argument("--dossiers", default=None,
685
+ help="JSON {\"task:seed\": record dir from scripts/make_dossier.py}: each run gets that record in "
686
+ "history/ and a README section saying an earlier attempt failed (own vs mismatched history)")
687
+ r = sub.add_parser("_runner")
688
+ r.add_argument("--batch", required=True)
689
+ for name in ("status", "stop", "followup"):
690
+ sub.add_parser(name).add_argument("--batch", required=True)
691
+ t = sub.add_parser("table")
692
+ t.add_argument("--batch", nargs="+", required=True)
693
+ ct = sub.add_parser("contract")
694
+ ct.add_argument("--batch", nargs="+", required=True)
695
+ rt = sub.add_parser("retry")
696
+ rt.add_argument("--batch", required=True)
697
+ rt.add_argument("--runs", nargs="*", default=[])
698
+ a = ap.parse_args()
699
+ dict(start=cmd_start, _runner=cmd_runner, status=cmd_status, table=cmd_table, stop=cmd_stop, retry=cmd_retry,
700
+ contract=cmd_contract, followup=cmd_followup)[a.cmd](a)
701
+
702
+
703
+ if __name__ == "__main__":
704
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_breakfast_geometry.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V2 physical height/orientation controls. Initialization interventions are diagnostics only."""
2
+ import json
3
+ from pathlib import Path
4
+ from PIL import Image
5
+ from lffbench import envs
6
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
7
+
8
+ def main():
9
+ out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls'
10
+ out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService()
11
+ for seed in range(1000,1003):
12
+ inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
13
+ # Move bread clear only at diagnostic initialization, so the obstacle is unambiguous.
14
+ envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward()
15
+ def state(stage):
16
+ r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(),
17
+ butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(),
18
+ applied_torque=float(t.env.sim.data.qfrc_applied[t.dof]))
19
+ assert r['applied_torque']==0.,r
20
+ rows.append(r);print(json.dumps(r),flush=True)
21
+ Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png')
22
+ (out/'progress.json').write_text(json.dumps(rows,indent=2))
23
+ return r
24
+ # Two empty-box closes prove that the removed closure-count mechanism does not reappear.
25
+ for cycle in range(2):
26
+ # Let the freely swinging open lid settle before targeting its knob again.
27
+ t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80)
28
+ r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4
29
+ t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
30
+ r=state('upright_blocked')
31
+ assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r
32
+ # Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged.
33
+ t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003)
34
+ t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4
35
+ assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9
36
+ t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
37
+ r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r
38
+ (out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2))
39
+ t.env.close()
40
+
41
+ if __name__=='__main__':main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_breakfast_tool_interface.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute the reference through the real public ToolExecutor, including default motion limits.
2
+ Privileged reference observations remain allowed; all actuation goes through public tools.
3
+ """
4
+ import argparse, json, math
5
+ from pathlib import Path
6
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
7
+ from lffbench.agent.tools import ToolExecutor
8
+
9
+ class PublicSkills:
10
+ def __init__(self,base,executor):
11
+ object.__setattr__(self,'base',base);object.__setattr__(self,'executor',executor)
12
+ object.__setattr__(self,'calls',[])
13
+ # Learned compensation belongs in the caller's command coordinates, not the environment.
14
+ object.__setattr__(self,'correction',base.correction.copy());base.correction[:]=0
15
+ def __getattr__(self,name):return getattr(self.base,name)
16
+ def __setattr__(self,name,value):
17
+ if name=='correction':object.__setattr__(self,name,value)
18
+ else:setattr(self.base,name,value)
19
+ def call(self,name,args):
20
+ result=self.executor.call(name,args)
21
+ self.calls.append(dict(name=name,args=args,ok=result.ok,report=result.report))
22
+ if not result.ok:raise RuntimeError(result.report)
23
+ return result.report
24
+ def move_to(self,target,yaw=None,speed=None,**kwargs):
25
+ target=target-self.correction
26
+ return self.call('move_to',dict(x=float(target[0]),y=float(target[1]),z=float(target[2]),
27
+ yaw=math.degrees(self.base.yaw if yaw is None else yaw),speed=speed))
28
+ def set_gripper(self,close,steps=15):
29
+ result=self.call('close_gripper' if close else 'open_gripper',{})
30
+ if steps>15:self.hold(steps-15)
31
+ return result
32
+ def hold(self,steps=10):
33
+ for _ in range(steps//15):self.call('close_gripper' if self.base.grip>0 else 'open_gripper',{})
34
+ for _ in range(steps%15):
35
+ self.move_to(self.base.eef_pos()-self.base.bias+self.correction)
36
+
37
+ def main():
38
+ p=argparse.ArgumentParser();p.add_argument('--out');p.add_argument('--seed',type=int,default=1000);args=p.parse_args()
39
+ root=Path(__file__).resolve().parents[1]
40
+ out=Path(args.out) if args.out else root/'results/lh_breakfast_service/geometry_v2/tool_interface'
41
+ out.mkdir(parents=True,exist_ok=True)
42
+ t=BreakfastService();inst=t.sample_instance(args.seed);t.reset_instance(inst)
43
+ executor=ToolExecutor(t,inst,image_res=128)
44
+ proxy=PublicSkills(t.sk,executor);t.sk=proxy
45
+ t.phase_hook=lambda text,state:print(json.dumps(state),flush=True)
46
+ t.execute(inst,{'mode':'adaptive'})
47
+ # The final judge's mandatory settle is environment work, not additional agent tool calls.
48
+ t.sk=proxy.base
49
+ result=t.outcome(inst)
50
+ data=dict(outcome=result,calls=proxy.calls,call_count=len(proxy.calls),trace=t.trace,
51
+ environment_correction=proxy.base.correction.tolist(),compensation_in_tool_arguments=True,
52
+ scope='Reference with privileged observations; actual public ToolExecutor actuation, not an LLM evaluation')
53
+ (out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
54
+ print('OUTCOME',result,flush=True)
55
+ assert result['success'] and all(result['traps'].values()) and len(proxy.calls)<=t.agent_max_steps,dict(outcome=result,call_count=len(proxy.calls))
56
+
57
+ if __name__=='__main__':main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_compound_public.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public actuator-boundary replay of a privileged reference, never a model eval."""
2
+ import argparse,importlib,json
3
+ from pathlib import Path
4
+ from lffbench.task_base import TASKS
5
+ from lffbench.agent.tools import ToolExecutor
6
+ from check_breakfast_tool_interface import PublicSkills
7
+ from check_compound_remaining import plain
8
+
9
+ p=argparse.ArgumentParser();p.add_argument('--task',required=True);p.add_argument('--seed',type=int,default=1000);p.add_argument('--out',required=True);a=p.parse_args()
10
+ importlib.import_module('lffbench.tasks.'+a.task);out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
11
+ t=TASKS[a.task]()
12
+ # Same reference plan is now used for every public replay.
13
+ i=t.sample_instance(a.seed);t.reset_instance(i);e=ToolExecutor(t,i,image_res=128);proxy=PublicSkills(t.sk,e);t.sk=proxy
14
+ t.phase_hook=lambda text,row:print(json.dumps(row,default=plain),flush=True)
15
+ t.execute(i,{'mode':'adaptive'});t.sk=proxy.base;o=t.outcome(i)
16
+ r=dict(seed=a.seed,outcome=o,trace=t.trace,calls=proxy.calls,robot_tool_calls=len(proxy.calls),robot_call_budget=t.agent_max_steps,
17
+ environment_correction=proxy.base.correction.tolist(),scope='Privileged reference observations, actual public ToolExecutor actuation. Not a model evaluation.')
18
+ (out/'result.json').write_text(json.dumps(r,indent=2,default=plain));print(json.dumps(dict(outcome=o,calls=len(proxy.calls)),default=plain),flush=True);t.env.close()
19
+ assert o['success'] and all(o['traps'].values()) and all(o['recovered'].values()) and len(proxy.calls)<=t.agent_max_steps,dict(outcome=o,calls=len(proxy.calls),budget=t.agent_max_steps)
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_desk_mechanisms.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Physical controls for offset, covered access, and loss of support."""
2
+ import argparse,copy,json
3
+ from pathlib import Path
4
+ from lffbench.tasks.lh_desk_organizer import DeskOrganizer,JARS
5
+ from check_compound_remaining import plain
6
+ p=argparse.ArgumentParser();p.add_argument('--n',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True);t=DeskOrganizer();rows=[]
7
+ for seed in range(1000,1000+a.n):
8
+ i=t.sample_instance(seed);r=dict(seed=seed)
9
+ t.reset_instance(i);r['biased_grasp']=t.pick(JARS[0],tries=1,v=.15)
10
+ z=copy.deepcopy(i);z['bias']=[0,0,0];t.reset_instance(z);r['unbiased_grasp']=t.pick(JARS[0],tries=1,v=.15)
11
+ t.reset_instance(i);t.sk.correction=t.sk.bias.copy();r['covered_top_grasp']=t.top_book_probe()
12
+ z=copy.deepcopy(i);z['start']['green']=[-.20,.05];t.reset_instance(z);t.sk.correction=t.sk.bias.copy();r['uncovered_top_grasp']=t.top_book_probe()
13
+ for remove in (False,True):
14
+ t.reset_instance(i);t.sk.correction=t.sk.bias.copy();assert t.pick(JARS[0]);t.put(JARS[0],-.09,.14);assert t.pick(JARS[2]);t.put(JARS[2],.055,.13);t.sk.hold(80);t.top_book_probe();before=t.on_board(2)
15
+ if remove:t.move_book_out()
16
+ else:t.sk.hold(400)
17
+ t.sk.hold(150);r['removed_support' if remove else 'retained_support']=dict(mug_before=before,mug_after=t.on_board(2),tray_degrees=float(__import__('numpy').degrees(t.angle())),cause=t.mon['lost_cause'][2])
18
+ r['pass']=bool(not r['biased_grasp'] and r['unbiased_grasp'] and not r['covered_top_grasp'] and r['uncovered_top_grasp'] and r['retained_support']['mug_before'] and r['retained_support']['mug_after'] and r['removed_support']['mug_before'] and not r['removed_support']['mug_after'] and r['removed_support']['cause']=='slid_off')
19
+ rows.append(r);(out/'progress.json').write_text(json.dumps(rows,indent=2,default=plain));print(json.dumps(r,default=plain),flush=True)
20
+ (out/'summary.json').write_text(json.dumps(dict(rows=rows,pass_count=sum(x['pass'] for x in rows)),indent=2,default=plain));t.env.close();assert all(x['pass'] for x in rows)
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/check_lh_pantry_relatch.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Physical checks for lh_pantry_relatch: confirm the latch-fatigue mechanism actually behaves as designed before
2
+ any acceptance validation. Not the formal n>=20 k=5 headroom run (see scripts/validate.py for that).
3
+
4
+ Usage:
5
+ cd lffbench && source run_env.sh && OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py mechanism
6
+ OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py seeds --seeds 1000,1001,1002 --out <path>
7
+ """
8
+ import argparse
9
+ import copy
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
16
+
17
+ import numpy as np
18
+
19
+ from lffbench import envs
20
+ from lffbench.tasks.lh_pantry_relatch import PantryRelatch
21
+
22
+
23
+ def source_hash():
24
+ path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "lffbench", "tasks",
25
+ "lh_pantry_relatch.py")
26
+ return hashlib.sha256(open(path, "rb").read()).hexdigest()
27
+
28
+
29
+ def mechanism_check(seed=1000, out=None):
30
+ """Isolate the latch mechanism: close 1 (quick) should hold; close 2 (quick) should drift open on its own
31
+ during the settle window; close 2 (dwell) should hold. No bread/butter picking involved -- just the lid."""
32
+ task = PantryRelatch()
33
+ rows = []
34
+ for label, dwell1, dwell2 in [("quick_quick", False, False), ("quick_dwell", False, True)]:
35
+ inst = task.sample_instance(seed)
36
+ task.reset_instance(inst)
37
+ task.open_lid()
38
+ task.close_lid(dwell=dwell1)
39
+ after_close1 = task.lid_deg()
40
+ n = 0
41
+ while n < 300:
42
+ task.sk.hold(10)
43
+ n += 10
44
+ settled1 = task.lid_deg()
45
+ task.open_lid()
46
+ task.close_lid(dwell=dwell2)
47
+ after_close2 = task.lid_deg()
48
+ n = 0
49
+ while n < 500:
50
+ task.sk.hold(10)
51
+ n += 10
52
+ settled2 = task.lid_deg()
53
+ row = dict(label=label, dwell1=dwell1, dwell2=dwell2, after_close1_deg=round(after_close1, 2),
54
+ settled1_deg=round(settled1, 2), after_close2_deg=round(after_close2, 2),
55
+ settled2_deg=round(settled2, 2), closes_done=task.closes_done,
56
+ active_latch_final=round(task.active_latch, 4))
57
+ rows.append(row)
58
+ print(row, flush=True)
59
+ print("expect: quick_quick settled2_deg clearly > quick_dwell settled2_deg (fatigue visible without dwell)")
60
+ if out:
61
+ with open(out, "w") as f:
62
+ json.dump(dict(rows=rows, source_sha256=source_hash()), f, indent=1)
63
+ return rows
64
+
65
+
66
+ def ablation_no_decay(seed=1000, out=None):
67
+ """Ablation: force DECAY=1.0 (no fatigue). Quick-release close 2 should then also hold."""
68
+ import lffbench.tasks.lh_pantry_relatch as mod
69
+ orig = mod.DECAY
70
+ mod.DECAY = 1.0
71
+ try:
72
+ task = PantryRelatch()
73
+ inst = task.sample_instance(seed)
74
+ task.reset_instance(inst)
75
+ task.open_lid()
76
+ task.close_lid(dwell=False)
77
+ task.open_lid()
78
+ task.close_lid(dwell=False)
79
+ n = 0
80
+ while n < 500:
81
+ task.sk.hold(10)
82
+ n += 10
83
+ settled2 = task.lid_deg()
84
+ row = dict(decay_forced=1.0, settled2_deg=round(settled2, 2), closes_done=task.closes_done)
85
+ print(row, flush=True)
86
+ finally:
87
+ mod.DECAY = orig
88
+ if out:
89
+ with open(out, "w") as f:
90
+ json.dump(row, f, indent=1)
91
+ return row
92
+
93
+
94
+ def full_episode(seed, kind, out_dir=None):
95
+ """Full pick-bread / put-butter episode with a given scripted policy kind."""
96
+ task = PantryRelatch()
97
+ inst = task.sample_instance(seed)
98
+ hist = task.run_scripted(kind, inst, k=task.max_attempts, seed=seed)
99
+ for h in hist:
100
+ o = h["outcome"]
101
+ print(f"seed={seed} kind={kind} attempt={h['attempt']} success={o['success']} failure={o['failure']} "
102
+ f"closes_done={o['closes_done']} lid_final={o['lid_final_deg']} detail={o['detail']}", flush=True)
103
+ return hist
104
+
105
+
106
+ def seeds_check(seeds, out=None):
107
+ task_rows = {}
108
+ for seed in seeds:
109
+ rows = {}
110
+ for kind in ("oracle", "naive", "adaptive"):
111
+ hist = full_episode(seed, kind)
112
+ rows[kind] = [dict(attempt=h["attempt"], success=h["outcome"]["success"],
113
+ failure=h["outcome"]["failure"], closes_done=h["outcome"]["closes_done"],
114
+ lid_final_deg=h["outcome"]["lid_final_deg"]) for h in hist]
115
+ task_rows[seed] = rows
116
+ result = dict(seeds=seeds, rows=task_rows, source_sha256=source_hash())
117
+ if out:
118
+ with open(out, "w") as f:
119
+ json.dump(result, f, indent=1)
120
+ return result
121
+
122
+
123
+ if __name__ == "__main__":
124
+ ap = argparse.ArgumentParser()
125
+ ap.add_argument("mode", choices=["mechanism", "ablation", "seeds", "episode"])
126
+ ap.add_argument("--seed", type=int, default=1000)
127
+ ap.add_argument("--seeds", type=str, default="1000,1001,1002")
128
+ ap.add_argument("--kind", type=str, default="oracle")
129
+ ap.add_argument("--out", type=str, default=None)
130
+ args = ap.parse_args()
131
+ if args.mode == "mechanism":
132
+ mechanism_check(args.seed, args.out)
133
+ elif args.mode == "ablation":
134
+ ablation_no_decay(args.seed, args.out)
135
+ elif args.mode == "episode":
136
+ full_episode(args.seed, args.kind)
137
+ elif args.mode == "seeds":
138
+ seeds_check([int(s) for s in args.seeds.split(",")], args.out)
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/compound_thumbnails.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Initial and naive-end camera images for the three new task cards."""
2
+ import importlib,json
3
+ from pathlib import Path
4
+ from PIL import Image
5
+ from lffbench import envs
6
+ from lffbench.task_base import TASKS
7
+ from check_compound_remaining import plain
8
+ for name in ('lh_desk_organizer','lh_split_calibration','lh_shim_relay'):
9
+ importlib.import_module('lffbench.tasks.'+name);t=TASKS[name]();i=t.sample_instance(1000);t.reset_instance(i);out=Path('results')/name/'thumbnails';out.mkdir(parents=True,exist_ok=True)
10
+ Image.fromarray(envs.render(t.env,res=640)).save(out/'initial.png');t.execute(i,{'mode':'naive'});o=t.outcome(i);Image.fromarray(envs.render(t.env,res=640)).save(out/'naive_end.png');(out/'result.json').write_text(json.dumps(dict(seed=1000,outcome=o),indent=2,default=plain));t.env.close();print(name,o['success'],flush=True)
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/feedback_ladder.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen first-failure record experiment. No native-session-continuation claim.
2
+
3
+ prepare creates a host-only manifest plus agent-visible, identical history records.
4
+ run starts the serial, resumable controller; player wraps the unchanged native harness.
5
+ """
6
+ import argparse
7
+ import collections
8
+ import datetime as dt
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import random
14
+ import shutil
15
+ import signal
16
+ import socket
17
+ import subprocess
18
+ import sys
19
+ import time
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ sys.path.insert(0, str(ROOT))
23
+ sys.path.insert(0, str(ROOT / 'scripts'))
24
+ SOURCE = ROOT.parents[1] / 'lffbench'
25
+ REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027'
26
+ BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3')
27
+ TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush',
28
+ 'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam')
29
+ ARMS = ('F1', 'F2', 'cause', 'fix')
30
+ ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env')
31
+ PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001')
32
+
33
+
34
+ def now():
35
+ return dt.datetime.now(dt.timezone.utc).isoformat()
36
+
37
+
38
+ def sha(p):
39
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()
40
+
41
+
42
+ def digest(d):
43
+ return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
44
+
45
+
46
+ def read(p):
47
+ return json.loads(Path(p).read_text())
48
+
49
+
50
+ def write(p,d):
51
+ p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
52
+ tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p)
53
+
54
+
55
+ def jsonl(p):
56
+ return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()]
57
+
58
+
59
+ def tree_hash(p):
60
+ return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()})
61
+
62
+
63
+ def intervention(a,arm):
64
+ parts=['The earlier attempt failed.']
65
+ if arm not in ARMS:raise ValueError(arm)
66
+ for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]:
67
+ if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key])
68
+ return '\n'.join(parts)
69
+
70
+
71
+ def annotations(task,seed,out,inst):
72
+ """Manual mechanism families, checked against each observed first-attempt outcome.
73
+ F2 contains observations only; privileged mechanism and strategy are separate.
74
+ Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause.
75
+ """
76
+ if task=='l3_wall_flush' and out.get('mode')=='placed_off':
77
+ return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.')
78
+ if task=='l3_under_table_tool':
79
+ return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.')
80
+ if task=='l5_slide_to_target':
81
+ assert out['failure']=='position' and out['along_err']>0 and out['at_rest']
82
+ return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.',
83
+ cause='The cube keeps moving after release: its surface friction is low, so the launch imparted more sliding distance than the remaining distance to the target.',
84
+ fix='Use the previous strike and observed travel as a calibration. Align a short strike toward the square, launch more gently for the remaining distance, withdraw the gripper, and wait for the cube to stop before checking both edges. Preserve a free slide; do not carry or continuously push it into place.',
85
+ basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release')
86
+ if task=='l5_tablecloth_pull':
87
+ assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0
88
+ return dict(eligible=True,phenomenon='The board came out and the cube stayed upright, but the cube stopped short of the green band in the direction of the pull.',
89
+ cause='Friction transfers motion from the board to the cube while they remain in contact. The pull was too fast to move the cube far enough toward the band before the board escaped.',
90
+ fix='On the reset scene, grasp only the handle and use one straight, somewhat slower pull than before, then release. A slower pull carries the cube farther before the board escapes; avoid making it so slow that the cube rides on the board. Check the whole cube against the band after it settles.',
91
+ basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement')
92
+ if task=='l3_wall_flush':
93
+ assert out['mode']=='wall_blocked' and not out['lifted']
94
+ return dict(eligible=True,phenomenon='The box was not lifted. During grasp attempts, the wall-side finger came down on the top of the wall.',
95
+ cause='The clearance between box and wall is too small for that finger, and the wall is higher than the box. At the attempted grasp locations the finger still overlapped the wall.',
96
+ fix='With the gripper closed, slide the box along the wall toward an accessible wall end. Move it far enough past that end for both fingers to descend clear of the wall, then open, grasp the box, lift, and place it centered on the plate.',
97
+ basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger')
98
+ if task=='l4_fit_container':
99
+ assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small')
100
+ return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.',
101
+ cause='The selected box is shorter internally than the phone along its long dimension. The phone bridges the rims even when its long axis is aligned with that box.',
102
+ fix='Choose a different box whose internal length and width both clear the phone. Compare the inside edges, orient the phone along the chosen box, lower it through the opening, release it, then withdraw and verify that it lies flat below the rims.',
103
+ basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short')
104
+ if task=='l3_card_shelf':
105
+ assert out['failure']=='fell_off' and out['tip']['part']=='heavy'
106
+ side=out['tip']['edge'];assert side==inst['heavy_edge']
107
+ return dict(eligible=True,phenomenon=f'The card tipped over the shelf\'s {side} edge and fell flat onto the table before it was lifted.',
108
+ cause=f'The card has a hidden weight toward the end that went over the {side} edge. Its center of mass passed outside the shelf support even with only a small overhang.',
109
+ fix='On the reset shelf, slide the opposite, lighter end toward the opposite shelf edge in small checked moves. Keep the weighted end supported, expose enough of the light end for the fingers to pass the shelf edge, pinch the exposed end across its width, then lift and transfer the card into the bin.',
110
+ basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge')
111
+ if task=='l5_loaded_beam':
112
+ assert out['failure']=='load_off' and out['n_load_falls']>0
113
+ return dict(eligible=True,phenomenon='The beam tilted during lifting and the blocks slid away from their end positions. At the end, the beam was held up but one block was still displaced inward from its end position.',
114
+ cause='The beam has an off-center hidden weight. The initial grip was away from the loaded balance point, so the beam tilted and displaced its blocks; later leveling did not itself restore their required end positions.',
115
+ fix='First restore both blocks to their original end positions while the beam is supported. Make a low test lift, adjust the grip toward the lower, heavier end until the loaded beam stays level, and only then raise it fully. Recheck both blocks after the lift; if either shifts, set down and restore it before trying again.',
116
+ basis=['failure=load_off','first lift tilt and falls','final loads_on_ends=1','inst.com_total'],mechanism='offcenter_lift_and_unrestored_load',mixed=True)
117
+ raise ValueError(f'No reviewed feedback for {task} seed {seed}')
118
+
119
+
120
+ def record_prefix(log,outdir,done):
121
+ """Only host-logged model-visible MCP text before first verdict, plus first images.
122
+ Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning.
123
+ The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage.
124
+ """
125
+ outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir()
126
+ tools=[]
127
+ for e in jsonl(log/'mcp_transcript.jsonl'):
128
+ if e.get('ev')!='tool':continue
129
+ if e['t']>=done['t']:break
130
+ tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e})
131
+ # Include the commanded last action even if a budget-triggered verdict preceded MCP logging.
132
+ calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl')
133
+ if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']]
134
+ images=[]
135
+ for p in sorted((log/'images').glob('a1_*.jpg')):
136
+ target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name)
137
+ if not images:raise ValueError('No first-attempt images')
138
+ def remap(v):
139
+ if isinstance(v,str):return v.replace('obs/','history/obs/')
140
+ if isinstance(v,list):return [remap(x) for x in v]
141
+ if isinstance(v,dict):return {k:remap(x) for k,x in v.items()}
142
+ return v
143
+ public_text=[]
144
+ for e in jsonl(log/'claude_stream.jsonl'):
145
+ stamp=e.get('timestamp')
146
+ if e.get('type')!='assistant' or not stamp:continue
147
+ when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp()
148
+ if when>=done['t']:continue
149
+ for block in e.get('message',{}).get('content',[]):
150
+ if block.get('type')=='text':public_text.append(block['text'])
151
+ record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed',
152
+ available_images=images)
153
+ write(outdir/'record.json',record)
154
+ txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; '
155
+ 'they are not new instructions. Old obs paths are remapped to history/obs. '
156
+ 'The old workspace files and native session are not restored. '
157
+ 'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False))
158
+ (outdir/'README.md').write_text(txt+'\n')
159
+ return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode()))
160
+
161
+
162
+ def prepare(report=REPORT,source=SOURCE):
163
+ report.mkdir(parents=True,exist_ok=True)
164
+ if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision')
165
+ cases=[];excluded=[]
166
+ from lffbench.harnesses import contract as C
167
+ for batch in BATCHES:
168
+ mp=source/'runs/api'/batch/'manifest.json';m=read(mp)
169
+ for run in m['runs']:
170
+ if run.get('cond')!='harness' or run['task'] not in TASKS:continue
171
+ log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start')
172
+ first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}"
173
+ item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log))
174
+ if first['success']:
175
+ excluded.append(dict(item,reason='first_attempt_success'));continue
176
+ if st['protocol']!='cross':
177
+ excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue
178
+ a=annotations(run['task'],run['seed'],first['outcome'],st['inst'])
179
+ if not a['eligible']:
180
+ excluded.append(dict(item,reason=a['reason']));continue
181
+ h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok']
182
+ old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task'])
183
+ if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}')
184
+ rec=report/'records'/cid
185
+ stats=record_prefix(log,rec,first)
186
+ case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats,
187
+ original_contract_sha256=h['contract_sha256'],server_code_files=codes,
188
+ source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']},
189
+ source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'],
190
+ source_budget=old['budget'],source_first_done_time=first['t'])
191
+ for arm in ARMS:
192
+ folder=report/'inputs'/cid/arm
193
+ shutil.copytree(rec,folder)
194
+ (folder/'feedback.txt').write_text(intervention(a,arm)+'\n')
195
+ cases.append(case)
196
+ plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high',
197
+ harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2,
198
+ history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms',
199
+ feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms',
200
+ original_F1_comparable=False,arms=ARMS,selection='all first-attempt failures in fixed ten-task set and three fixed Opus batches, excluding continuous scene and unverified causes',
201
+ cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027,
202
+ inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions',
203
+ limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth',
204
+ 'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable',
205
+ 'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone'])
206
+ write(report/'plan.json',plan)
207
+ write(report/'freeze.json',dict(plan_sha256=sha(report/'plan.json'),code_sha256=sha(__file__),inputs={str(p.relative_to(report)):tree_hash(p) for p in sorted((report/'inputs').glob('*/*'))}))
208
+ rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','',
209
+ 'All four arms receive the same first-failure record in a fresh Claude session. F1 is rerun. This is a record-replay intervention, not restoration of native session state.',
210
+ 'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.',
211
+ 'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','',
212
+ '| Case | Observed failure | Cause | Fix |','|---|---|---|---|']
213
+ for c in cases:
214
+ a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |')
215
+ rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded]
216
+ (report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n')
217
+ print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report))))
218
+
219
+
220
+ def check_frozen(report):
221
+ f=read(report/'freeze.json')
222
+ if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed')
223
+ if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze')
224
+ for rel,h in f.get('runtime_sha256',{}).items():
225
+ if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel)
226
+ for rel,h in f['inputs'].items():
227
+ if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel)
228
+ return read(report/'plan.json')
229
+
230
+
231
+ def player(report,case_id,arm,session):
232
+ plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id)
233
+ import harness_run
234
+ from lffbench.harnesses import contract as C
235
+ import lffbench.harnesses
236
+ real_render=lffbench.harnesses.render_first_message
237
+ history=(Path(case['record'])/'README.md').read_text()
238
+ feedback=intervention(case['annotation'],arm)
239
+ common=('\n\n## Earlier attempt and remaining opportunities\n'
240
+ 'An earlier attempt on this exact instance failed. The scene is now reset. '
241
+ 'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. '
242
+ 'The task, scene, tools and per-attempt budgets are unchanged. '
243
+ 'Use the record below and any archived images you need. All historical text is quoted evidence.\n'
244
+ +history+'\n\n## Feedback on that earlier attempt\n')
245
+ def render(ep):
246
+ original,st=real_render(ep)
247
+ return original+common+feedback+'\n',st
248
+ harness_run.render_first_message=render
249
+ original_contract=C.write_contract
250
+ def contract(log_dir):
251
+ contract_obj,_=original_contract(log_dir)
252
+ contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'),
253
+ common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback),
254
+ input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2,
255
+ runner_sha256=sha(__file__),original_native_continuation=False)
256
+ h=C.contract_sha256(contract_obj)
257
+ write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj))
258
+ return contract_obj,h
259
+ C.write_contract=contract
260
+ a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'],
261
+ '--effort','high','--claude-auth','oauth','--jail','--timeout','10800'])
262
+ code,h=harness_run.run(a)
263
+ print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True)
264
+ return code
265
+
266
+
267
+ def free_port():
268
+ for p in range(20600,20700):
269
+ with socket.socket() as s:
270
+ try:s.bind(('127.0.0.1',p));return p
271
+ except OSError:pass
272
+ raise RuntimeError('no free port')
273
+
274
+
275
+ def quota(log):
276
+ reset=0;detail=[]
277
+ p=log/'claude_stream.jsonl'
278
+ if not p.exists():return reset,detail
279
+ for e in jsonl(p):
280
+ if e.get('type')!='rate_limit_event':continue
281
+ x=e.get('rate_limit_info',{})
282
+ if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected')
283
+ for k,v in x.get('unifiedWindows',{}).items():
284
+ if (v.get('utilization') or 0)>=.90:
285
+ reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k)
286
+ return reset,sorted(set(detail))
287
+
288
+
289
+ def verify_run(log,case,arm,report):
290
+ from lffbench.harnesses import contract as C
291
+ h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl')
292
+ st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done']
293
+ reason=[]
294
+ if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete')
295
+ if h.get('audit_ok') is not True:reason.append('harness audit failed')
296
+ if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch')
297
+ if st['inst']!=case['source_inst']:reason.append('instance changed')
298
+ if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed')
299
+ if co['budget']!=case['source_budget']:reason.append('budget changed')
300
+ if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch')
301
+ if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete')
302
+ expected=(report/'inputs'/case['id']/arm)
303
+ # sandbox survives server exit; ensure agent was handed the exact predeclared bundle.
304
+ sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history'
305
+ if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered')
306
+ first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else ''
307
+ if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history')
308
+ if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch')
309
+ for source,hsh in case['source_hashes'].items():
310
+ if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed')
311
+ return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done),
312
+ success=any(x['success'] for x in done),attempts=len(done),audit_ok=h.get('audit_ok'),pin_status=h.get('preflight',{}).get('pin_status'))
313
+
314
+
315
+ def run_one(report,case,arm,index):
316
+ port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}'
317
+ folder.mkdir(parents=True,exist_ok=False)
318
+ env=dict(os.environ,LFF_RUNS_DIR=str(folder),LFF_STYLE='la',LFF_EXTRA_ARGS='--agent-iface tools --dossier '+str(report/'inputs'/case['id']/arm))
319
+ start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'],
320
+ cwd=ROOT,env=env,capture_output=True,text=True,timeout=660)
321
+ (folder/'server_start.log').write_text(start.stdout+start.stderr)
322
+ logs=list(folder.glob('*/session.json'))
323
+ if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:])
324
+ log=logs[0].parent
325
+ result=dict(status='running',log=str(log),started_utc=now())
326
+ write(report/'active.json',dict(case=case['id'],arm=arm,**result))
327
+ try:
328
+ # Positional shell parameters avoid interpolating commands or credentials.
329
+ command='source run_env.sh >/dev/null 2>&1 && set -a && source "$1" && set +a && exec python scripts/feedback_ladder.py player --report "$2" --case "$3" --arm "$4" --session "$5"'
330
+ with (log/'player.log').open('w') as out:
331
+ proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')],
332
+ cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True)
333
+ write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result))
334
+ try:code=proc.wait(timeout=11000)
335
+ except subprocess.TimeoutExpired:
336
+ os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60)
337
+ result.update(exit_code=code,ended_utc=now())
338
+ if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report))
339
+ else:result.update(valid=False,invalid_reasons=['harness metadata missing'])
340
+ result['status']='done' if result.get('valid') and code==0 else 'invalid'
341
+ reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why)
342
+ return result
343
+ finally:
344
+ try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM)
345
+ except (OSError,ValueError):pass
346
+
347
+
348
+ def summarize(report,state):
349
+ plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'}
350
+ complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)]
351
+ counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS}
352
+ paired=[]
353
+ for a,b in zip(ARMS,ARMS[1:]):
354
+ transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete)
355
+ paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False],
356
+ net=transitions[False,True]-transitions[True,False]))
357
+ summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete),
358
+ counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'],
359
+ outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']])
360
+ write(report/'summary.json',summary)
361
+ lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'',
362
+ 'Recovery success conditional on the same earlier failure and record replay. Do not pool with native F1 continuations or interpret adjacent gains as exact cognitive-stage fractions.','',
363
+ '| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|']
364
+ for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |')
365
+ lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|']
366
+ for x in paired:lines.append(f"| {x['lower']} → {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |")
367
+ (report/'RESULTS.md').write_text('\n'.join(lines)+'\n')
368
+ if complete:
369
+ import matplotlib
370
+ matplotlib.use('Agg')
371
+ import matplotlib.pyplot as plt
372
+ fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340'])
373
+ ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}')
374
+ for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center')
375
+ fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig)
376
+ return summary
377
+
378
+
379
+ def controller(report,pilot_only=False):
380
+ import fcntl
381
+ lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
382
+ plan=check_frozen(report)
383
+ if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed')
384
+ state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now())
385
+ write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only))
386
+ cases={c['id']:c for c in plan['cases']}
387
+ rng=random.Random(plan['randomization_seed']);queue=[]
388
+ for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]:
389
+ arms=list(ARMS);rng.shuffle(arms)
390
+ queue.extend((cid,a) for a in arms)
391
+ for cid,arm in queue:
392
+ if pilot_only and cid not in plan['pilot_cases']:break
393
+ if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue
394
+ # Any operational failure stops progression; quota-only retry is bounded and waits for the real window.
395
+ state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running'
396
+ state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state)
397
+ while (report/'PAUSE').exists():time.sleep(30)
398
+ check_frozen(report)
399
+ try:
400
+ result=run_one(report,cases[cid],arm,len(state['runs']))
401
+ except Exception as e:
402
+ result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False)
403
+ state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state)
404
+ print(now(),cid,arm,result['status'],result.get('history'),flush=True)
405
+ if result['status']!='done':
406
+ state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2
407
+ if result.get('quota_reset',0)>time.time():
408
+ state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat())
409
+ write(report/'status.json',state);summarize(report,state)
410
+ while time.time()<result['quota_reset']+120:time.sleep(30)
411
+ # Pilot gate depends on protocol validity, never success rate.
412
+ if all(any(r['case']==p and r['arm']==a and r['status']=='done' for r in state['runs']) for p in plan['pilot_cases'] for a in ARMS):
413
+ write(report/'pilot_gate.json',dict(passed=True,validated_utc=now(),criterion='all eight pilot runs complete; source, input, code, budget, model pin and harness audits pass; independent of outcomes'))
414
+ state['state']='pilot_complete' if pilot_only else 'complete';state.pop('active',None)
415
+ write(report/'status.json',state);summarize(report,state);return 0
416
+
417
+
418
+ def main():
419
+ ap=argparse.ArgumentParser();ap.add_argument('command',choices=['prepare','player','run','report','check']);ap.add_argument('--report',type=Path,default=REPORT)
420
+ ap.add_argument('--case');ap.add_argument('--arm',choices=ARMS);ap.add_argument('--session',type=Path);ap.add_argument('--pilot-only',action='store_true');a=ap.parse_args()
421
+ if a.command=='prepare':prepare(a.report)
422
+ elif a.command=='check':p=check_frozen(a.report);print(json.dumps({'frozen':True,'cases':len(p['cases'])}))
423
+ elif a.command=='player':return player(a.report,a.case,a.arm,a.session)
424
+ elif a.command=='run':return controller(a.report,a.pilot_only)
425
+ else:print(json.dumps(summarize(a.report,read(a.report/'status.json'))))
426
+ return 0
427
+
428
+ if __name__=='__main__':sys.exit(main())
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/gpt_batch.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch of GPT-player runs on robot_server sessions (same sessions / README / images as the Claude players).
2
+
3
+ start python scripts/gpt_batch.py start --batch exp2 --model gpt-6-astra --perception rgb --video \
4
+ --tasks l1_bias_place:1000,1001 l5_slide_to_target:1000,1001 --port0 9710
5
+ -> one server + one gpt_player process per (task, seed); manifest at runs/gpt/<batch>/manifest.json
6
+ status python scripts/gpt_batch.py status --batch exp2
7
+ table python scripts/gpt_batch.py table --batch exp2
8
+ stop python scripts/gpt_batch.py stop --batch exp2 (stops the robot servers and any player still running)
9
+ """
10
+ import argparse
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+
16
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
18
+ from claude_batch import run_stats # noqa: E402
19
+
20
+ RUNS = os.path.join(ROOT, "runs", "gpt")
21
+ # OPENAI_API_KEY / OPENAI_BASE_URL: taken from this file if it exists (KEY=value lines), else from the environment
22
+ ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
23
+
24
+
25
+ def mpath(batch):
26
+ return os.path.join(RUNS, batch, "manifest.json")
27
+
28
+
29
+ def load(batch):
30
+ return json.load(open(mpath(batch)))
31
+
32
+
33
+ def save(batch, m):
34
+ os.makedirs(os.path.dirname(mpath(batch)), exist_ok=True)
35
+ json.dump(m, open(mpath(batch), "w"), indent=1)
36
+
37
+
38
+ def port_free(port):
39
+ import socket
40
+ with socket.socket() as so:
41
+ try:
42
+ so.bind(("127.0.0.1", port))
43
+ return True
44
+ except OSError:
45
+ return False
46
+
47
+
48
+ def cmd_start(a):
49
+ m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[])
50
+ used = {r["port"] for r in m["runs"]}
51
+ port = a.port0
52
+ env = dict(os.environ, LFF_RUNS_DIR=os.path.join(RUNS, a.batch), LFF_STYLE=a.style,
53
+ LFF_EXTRA_ARGS="--nominal" if a.nominal else "")
54
+ for spec in a.tasks:
55
+ task, seeds = spec.split(":")
56
+ for seed in seeds.split(","):
57
+ while port in used or not port_free(port):
58
+ port += 1
59
+ out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, seed, "full", a.feedback,
60
+ str(port), "direct", str(a.k), f"{a.batch}-{a.harness}" + ("-nominal" if a.nominal else ""), a.perception,
61
+ "1" if a.video else "0"], capture_output=True, text=True, env=env)
62
+ kv = dict(l.split("=", 1) for l in out.stdout.splitlines() if l.startswith(("SANDBOX=", "LOG=")))
63
+ if "LOG" not in kv:
64
+ print("server failed", task, seed, out.stdout[-500:], out.stderr[-500:])
65
+ continue
66
+ used.add(port)
67
+ log = kv["LOG"]
68
+ if a.harness == "gpt_player":
69
+ player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
70
+ f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
71
+ f"exec python scripts/gpt_player.py --session {log}/session.json --model {a.model} "
72
+ f"--effort {a.effort} --style {a.style} > {log}/gpt_player.log 2>&1")
73
+ elif a.harness == "rpent":
74
+ player = (f"bash {ROOT}/scripts/rpent_player.sh {log}/session.json --model {a.model} --effort {a.effort} "
75
+ f"> {log}/rpent_player.out 2>&1")
76
+ else: # gptpolicy
77
+ player = (f"GPTPOLICY_MODEL={a.model} GPTPOLICY_EFFORT={a.effort} GPTPOLICY_KEEP_SERVER=1 "
78
+ f"bash {ROOT}/scripts/gptpolicy_player.sh {log}/session.json > {log}/gptpolicy_player.out 2>&1")
79
+ # detach stdio: otherwise a player that does not exec keeps the caller's stdout pipe open and the
80
+ # caller (e.g. `gpt_batch.py start ... | grep`) blocks until the run ends
81
+ p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
82
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
83
+ r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, effort=a.effort, cond="harness",
84
+ rep=0, k=a.k, port=port, sandbox=kv["SANDBOX"], log=log, perception=a.perception, player_pid=p.pid,
85
+ harness=a.harness, style=a.style, nominal=a.nominal)
86
+ m["runs"].append(r)
87
+ print(json.dumps(dict(run=r["run"], pid=p.pid)), flush=True)
88
+ save(a.batch, m)
89
+
90
+
91
+ def cmd_status(a):
92
+ for r in load(a.batch)["runs"]:
93
+ tr = os.path.join(r["log"], "gpt_transcript.jsonl")
94
+ errs = 0
95
+ end = None
96
+ if os.path.exists(tr):
97
+ for l in open(tr):
98
+ d = json.loads(l)
99
+ errs += d["ev"] == "api_error"
100
+ if d["ev"] in ("end", "abort"):
101
+ end = d
102
+ ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
103
+ n = sum(1 for e in ev if e["ev"] == "call")
104
+ dones = [e for e in ev if e["ev"] == "done"]
105
+ alive = True
106
+ try:
107
+ os.kill(r["player_pid"], 0)
108
+ except (ProcessLookupError, KeyError, PermissionError):
109
+ alive = False
110
+ if end:
111
+ state = "END" if end["ev"] == "end" else "ABORT " + end.get("reason", "")
112
+ else:
113
+ state = "running" if alive else ("END" if dones and (dones[-1]["success"] or len(dones) >= r["k"]) else "ABORT player exited")
114
+ print(f"{r.get('harness', 'gpt_player'):10s} {r['task']:24s} s{r['seed']} cmds={n:3d} api_err={errs} "
115
+ f"attempts={[('S' if d['success'] else 'F') for d in dones]} {state}")
116
+
117
+
118
+ def cmd_table(a):
119
+ import collections
120
+ rows = []
121
+ for b in a.batch:
122
+ for r in load(b)["runs"]:
123
+ try:
124
+ st = run_stats(r)
125
+ except FileNotFoundError:
126
+ continue
127
+ rows.append(dict(r, **st, first_grasp=first_grasp(r), harness=r.get("harness", "gpt_player")))
128
+ lines = ["| harness | task | seed | attempts | first success | cmds | close_gripper (held / total) | think s/cmd | wall min |",
129
+ "|---|---|---|---|---|---|---|---|---|"]
130
+ for x in sorted(rows, key=lambda x: (x["task"], x["harness"], x["seed"])):
131
+ lines.append(f"| {x['harness']} | {x['task']} | {x['seed']} | {x['attempts']} | {x['first_success'] or '—'} | "
132
+ f"{x['n_calls']} | {x['first_grasp'][1]}/{x['first_grasp'][0]} | "
133
+ f"{(x['think_per_cmd'] or 0):.1f} | {(x['wall_s'] or 0) / 60:.1f} |")
134
+ by = collections.defaultdict(list)
135
+ for x in rows:
136
+ by[x["harness"]].append(x)
137
+ lines.append("")
138
+ for h, xs in sorted(by.items()):
139
+ n = len(xs)
140
+ g = [sum(x["first_grasp"][i] for x in xs) for i in (0, 1)]
141
+ lines.append(f"{h}: @1 = {sum(1 for x in xs if x['first_success'] == 1)}/{n}, "
142
+ f"@k = {sum(1 for x in xs if x['first_success'])}/{n}, close_gripper held {g[1]}/{g[0]}")
143
+ print("\n".join(lines))
144
+
145
+
146
+ def cmd_stop(a):
147
+ for r in load(a.batch)["runs"]:
148
+ pids = [r.get("player_pid")]
149
+ pf = os.path.join(r["log"], "server.pid")
150
+ if os.path.exists(pf):
151
+ pids.append(int(open(pf).read()))
152
+ for pid in pids:
153
+ if pid:
154
+ try:
155
+ os.kill(pid, 15) # SIGTERM: the server closes rollout.mp4 first
156
+ except (ProcessLookupError, PermissionError):
157
+ pass
158
+
159
+
160
+ def first_grasp(r):
161
+ """(close_gripper calls, of which ended holding an object) over the whole run."""
162
+ tot = held = 0
163
+ for l in open(os.path.join(r["log"], "events.jsonl")):
164
+ d = json.loads(l)
165
+ if d.get("ev") == "call" and d.get("cmd") == "close_gripper":
166
+ tot += 1
167
+ held += bool(d.get("report", {}).get("holding_object"))
168
+ return tot, held
169
+
170
+
171
+ def main():
172
+ ap = argparse.ArgumentParser()
173
+ sub = ap.add_subparsers(dest="cmd")
174
+ s = sub.add_parser("start")
175
+ s.add_argument("--batch", required=True); s.add_argument("--model", default="gpt-6-astra")
176
+ s.add_argument("--effort", default="medium"); s.add_argument("--tasks", nargs="+", required=True)
177
+ s.add_argument("--k", type=int, default=3); s.add_argument("--port0", type=int, default=9710)
178
+ s.add_argument("--perception", default="rgb", choices=["rgb", "depth", "rgbd"]); s.add_argument("--video", action="store_true")
179
+ s.add_argument("--harness", default="gpt_player", choices=["gpt_player", "rpent", "gptpolicy"])
180
+ s.add_argument("--style", default="v1", choices=["v1", "v2", "la"])
181
+ s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
182
+ s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"],
183
+ help="F1 = success/failure only (default since 2026-10-08); F2 = measured error, ablation only")
184
+ st = sub.add_parser("status"); st.add_argument("--batch", required=True)
185
+ t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True)
186
+ sp = sub.add_parser("stop"); sp.add_argument("--batch", required=True)
187
+ a = ap.parse_args()
188
+ dict(start=cmd_start, status=cmd_status, table=cmd_table, stop=cmd_stop)[a.cmd](a)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/gpt_player.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Old entry point of the GPT player, kept so existing commands keep working: the code now lives in api_player.py
2
+ (the unified harness for every provider). This runs it with --provider openai and the old transcript name.
3
+
4
+ python scripts/gpt_player.py --session runs/claude/<run>/session.json --model gpt-6-astra --effort medium [--style la]
5
+ """
6
+ import os
7
+ import sys
8
+ import traceback
9
+
10
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
+ from api_player import main # noqa: E402
12
+
13
+ if __name__ == "__main__":
14
+ try:
15
+ main(default_provider="openai", transcript_name="gpt_transcript.jsonl")
16
+ except SystemExit:
17
+ raise
18
+ except Exception:
19
+ traceback.print_exc()
20
+ sys.exit(1)
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/gptpolicy_player.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated
3
+ # lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium).
4
+ #
5
+ # usage: scripts/gptpolicy_player.sh <LOG>/session.json [extra gpt-policy-lffbench options]
6
+ # e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1
7
+ # scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json
8
+ # The robot_server interface (v1 / v2) is detected from the first status reply.
9
+ #
10
+ # Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response,
11
+ # images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and
12
+ # GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4.
13
+ # The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then).
14
+ set -uo pipefail
15
+ [ $# -ge 1 ] || { echo "usage: $0 <LOG>/session.json [options]"; exit 2; }
16
+ SESSION=$(readlink -f "$1"); shift
17
+ LOG=$(dirname "$SESSION")
18
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
19
+ [ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh"
20
+ # GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV)
21
+ VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv}
22
+ ENVF=${LFF_ENV_FILE:-$ROOT/.env}
23
+ [ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed)
24
+ export PYTHONUNBUFFERED=1
25
+ stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first
26
+ if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then
27
+ kill "$(cat "$LOG/server.pid")" 2>/dev/null || true
28
+ fi
29
+ }
30
+ trap stop_server EXIT
31
+ trap 'exit 143' TERM INT HUP
32
+ cd /tmp # neutral working directory; the model has no file access anyway
33
+ "$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \
34
+ --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log"
35
+ RC=${PIPESTATUS[0]}
36
+ echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log"
37
+ exit $RC
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/ladder_plan.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history
2
+ control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose
3
+ attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm;
4
+ only the Result section of history/README.md grows, one rung at a time:
5
+
6
+ F1 "The environment judged that attempt: failed." = the Do arm (do_<m>), not re-run
7
+ F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_<m>
8
+ hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_<m>
9
+ fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_<m>
10
+
11
+ python scripts/ladder_plan.py build records -> runs/api/ladder_20261027/<m>/<rung>.json (+ tasks_<m>.txt)
12
+ python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts
13
+ -> runs/api/ladder_20261027/report.json + markdown on stdout
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ SRC = os.path.join(API, "mismatch_20261027")
24
+ OUT = os.path.join(API, "ladder_20261027")
25
+ FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json")
26
+ MODELS = ("opus", "sonnet")
27
+ RUNGS = ("F2", "hplus", "fix")
28
+ BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"}
29
+ WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 §2)
30
+
31
+
32
+ def events(log):
33
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()]
34
+
35
+
36
+ def texts(src, fixes):
37
+ """rung -> result_extra for one record source (the logged attempt 1)"""
38
+ from lffbench import arm_specs
39
+ from lffbench.agent.robot_server import strip_axes
40
+ ev = events(src["log"])
41
+ start = next(e for e in ev if e["ev"] == "session_start")
42
+ done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1)
43
+ detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip()
44
+ if not detail:
45
+ raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2")
46
+ cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip())
47
+ fx = fixes.get(f"{start['task']}:{start['seed']}")
48
+ if fx is None or not fx["ok"]:
49
+ raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}")
50
+ return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]}
51
+
52
+
53
+ def cmd_build():
54
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
55
+ for m in MODELS:
56
+ own = json.load(open(os.path.join(SRC, m, "own.json")))
57
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
58
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n")
59
+ out = {r: {} for r in RUNGS}
60
+ for key, d in own.items():
61
+ src = json.load(open(d + ".source.json"))
62
+ tx = texts(src, fixes)
63
+ for r in RUNGS:
64
+ dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}")
65
+ if not os.path.isdir(dst):
66
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"],
67
+ dst, "--result-extra", tx[r]], check=True, capture_output=True)
68
+ out[r][key] = dst
69
+ for r in RUNGS:
70
+ json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1)
71
+ print(m, len(own), "instances x", len(RUNGS), "rungs")
72
+
73
+
74
+ def single(batch):
75
+ """task:seed -> True / False (attempt 1 of the batch's done run)"""
76
+ out = {}
77
+ p = os.path.join(API, batch, "manifest.json")
78
+ if not os.path.exists(p):
79
+ return out
80
+ for r in json.load(open(p))["runs"]:
81
+ if r["status"] != "done":
82
+ continue
83
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
84
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
85
+ return out
86
+
87
+
88
+ def cmd_report():
89
+ rep, md = {}, []
90
+ order = ("F1", "F2", "hplus", "fix")
91
+ f = lambda v: "-" if v is None else ("S" if v else "F")
92
+ for m in MODELS:
93
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
94
+ res = {r: single(f"{BATCH[r]}_{m}") for r in order}
95
+ rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want]
96
+ tot = {}
97
+ for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]),
98
+ ("within", [r for r in rows if r["within"]])):
99
+ tot[part] = {r: [sum(x[r] for x in sub if x[r] is not None), sum(x[r] is not None for x in sub)] for r in order}
100
+ steps = {}
101
+ cross = [r for r in rows if not r["within"]]
102
+ for lo, hi in zip(order, order[1:]):
103
+ both = [r for r in cross if r[lo] is not None and r[hi] is not None]
104
+ steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both),
105
+ down=sum(r[lo] and not r[hi] for r in both))
106
+ rep[m] = dict(rows=rows, totals=tot, steps=steps)
107
+ md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"]
108
+ md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |"
109
+ for r in rows]
110
+ for part in ("cross", "within"):
111
+ md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order))
112
+ md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}"
113
+ for k, v in steps.items()))
114
+ md.append("")
115
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
116
+ print("\n".join(md))
117
+
118
+
119
+ if __name__ == "__main__":
120
+ {"build": cmd_build, "report": cmd_report}[sys.argv[1]]()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/layer4_plan.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-4 minimal intervention (user 2026-10-30: 先用 opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the
2
+ two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh
3
+ single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs:
4
+
5
+ f1 "The environment judged that attempt: failed."
6
+ v + a generic reminder to check the goal before ending; no cause
7
+ hp + "Cause: " the hidden variable (arm_specs reveal)
8
+ fx + cause + how to succeed (arm_specs fix, validated below)
9
+
10
+ python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json
11
+ python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/<cond>.json + tasks.txt
12
+ python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds)
13
+ python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ OUT = os.path.join(API, "layer4i_20261030")
24
+ FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json")
25
+ CONDS = ("f1", "v", "hp", "fx")
26
+ DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"},
27
+ "lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}}
28
+ # frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10;
29
+ # tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3)
30
+ TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]}
31
+ REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; "
32
+ "if it is not, keep working.")
33
+
34
+
35
+ def events(log):
36
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line]
37
+
38
+
39
+ def batch_log(batch, task, seed):
40
+ runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
41
+ return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done"
42
+ and r.get("cond") == "harness")
43
+
44
+
45
+ def la_push(task, inst):
46
+ """the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)"""
47
+ import numpy as np
48
+ from lffbench.agent.tools import ToolExecutor
49
+ from lffbench.tasks import lh_clear_cover as cc
50
+ from scripts.validate_ladder_fix import la_move
51
+ task.reset_instance(inst)
52
+ sim = task.env.sim
53
+ off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
54
+ ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
55
+ cov = task.covering()
56
+ lp = task.lid_pos()
57
+ b = np.asarray(inst["boxes"][cov], float)
58
+ o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float)
59
+ d = np.array((0.0, float(np.sign(b[1] - o[1]))))
60
+ back = cc.LID_HALF + 0.03
61
+ s = lp[:2] - d * back
62
+ z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP
63
+ need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03
64
+ e = s + d * need
65
+ sb, eb, zb = s - off[:2], e - off[:2], z - off[2]
66
+ la_move(task, ex, off, gripper="close")
67
+ la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0)
68
+ la_move(task, ex, off, x=sb[0], y=sb[1], z=zb)
69
+ la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED)
70
+ la_move(task, ex, off, z=zb + 0.10, speed=0.2)
71
+ return float(zb), float(need), task.covering() is None
72
+
73
+
74
+ def cmd_validate():
75
+ import importlib
76
+ import pkgutil
77
+ from lffbench import arm_specs
78
+ from lffbench import tasks as task_pkg
79
+ from lffbench.agent.robot_server import strip_axes
80
+ from lffbench.task_base import TASKS
81
+ for m in pkgutil.iter_modules(task_pkg.__path__):
82
+ importlib.import_module(f"lffbench.tasks.{m.name}")
83
+ rows = []
84
+ for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG):
85
+ task = TASKS[name](cam_res=64)
86
+ for seed in seeds:
87
+ inst = task.sample_instance(seed)
88
+ clean = {k: v for k, v in inst.items() if not k.startswith("_")}
89
+ params = dict(task.oracle_params(inst))
90
+ row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour"))
91
+ row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"])
92
+ row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"])
93
+ if name == "lh_clear_cover":
94
+ params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst)
95
+ task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push
96
+ row["la_then_place_success"] = bool(task.outcome(inst)["success"])
97
+ cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params)
98
+ row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx)
99
+ row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"]
100
+ and row.get("la_lid_off", True) and row.get("la_then_place_success", True))
101
+ rows.append(row)
102
+ print("OK " if row["ok"] else "BAD", json.dumps({k: v for k, v in row.items() if k not in ("cause", "fix")}), flush=True)
103
+ os.makedirs(os.path.dirname(FIXV), exist_ok=True)
104
+ json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1)
105
+ print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}")
106
+
107
+
108
+ def sources(stage):
109
+ if stage == "debug":
110
+ return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())]
111
+ out = []
112
+ for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]:
113
+ if r["status"] == "done":
114
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
115
+ if d is not None and not d["success"]:
116
+ out.append((r["task"], r["seed"], r["log"]))
117
+ return out
118
+
119
+
120
+ def cmd_build(stage):
121
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
122
+ base = os.path.join(OUT, stage)
123
+ os.makedirs(base, exist_ok=True)
124
+ maps, tasks = {c: {} for c in CONDS}, []
125
+ for task, seed, log in sources(stage):
126
+ key = f"{task}:{seed}"
127
+ if not fixes[key]["ok"]:
128
+ raise SystemExit(f"{key}: fix text not validated")
129
+ tasks.append(key)
130
+ cause = "Cause: " + fixes[key]["cause"]
131
+ extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"])
132
+ for c in CONDS:
133
+ dst = os.path.join(base, c, f"{task}_s{seed}")
134
+ if not os.path.isdir(dst):
135
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst,
136
+ "--result-extra", extra[c]], check=True, capture_output=True)
137
+ maps[c][key] = dst
138
+ for c in CONDS:
139
+ json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1)
140
+ open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n")
141
+ print(stage, len(tasks), "instances x", len(CONDS), "conditions")
142
+
143
+
144
+ def cmd_report(stage):
145
+ rows = {}
146
+ for c in CONDS:
147
+ p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json")
148
+ if not os.path.exists(p):
149
+ continue
150
+ for r in json.load(open(p))["runs"]:
151
+ key = f"{r['task']}:{r['seed']}"
152
+ cell = dict(status=r["status"])
153
+ if r["status"] == "done":
154
+ ev = events(r["log"])
155
+ d = next((e for e in ev if e["ev"] == "done"), {})
156
+ o = d.get("outcome") or {}
157
+ cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300],
158
+ failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"],
159
+ events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40],
160
+ cover_removed=o.get("cover_removed"))
161
+ rows.setdefault(key, {})[c] = cell
162
+ print("| instance | " + " | ".join(CONDS) + " |")
163
+ print("|---|" + "---|" * len(CONDS))
164
+ f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status")))
165
+ for k, v in sorted(rows.items()):
166
+ print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |")
167
+ for c in CONDS:
168
+ xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"]
169
+ print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}")
170
+ json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1)
171
+
172
+
173
+ if __name__ == "__main__":
174
+ {"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/make_dossier.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6).
2
+
3
+ python scripts/make_dossier.py <run log dir> <out dir> [--attempt 1] [--allow-success]
4
+
5
+ The record contains only what the agent of that attempt saw: the starting images, every robot command with the
6
+ robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the
7
+ F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history
8
+ arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the
9
+ twin instance: same layout, different hidden variable), so the two dossiers differ only in content.
10
+ """
11
+ import argparse
12
+ import json
13
+ import os
14
+ import shutil
15
+
16
+ DROP = ("state_file", "attempt_ended", "camera_file")
17
+
18
+
19
+ def shell_args(args):
20
+ out = []
21
+ for k, v in args.items():
22
+ v = json.dumps(v) if not isinstance(v, str) else v
23
+ out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}")
24
+ return " ".join(out)
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("log")
30
+ ap.add_argument("out")
31
+ ap.add_argument("--attempt", type=int, default=1)
32
+ ap.add_argument("--allow-success", action="store_true")
33
+ ap.add_argument("--result-extra", default="",
34
+ help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs "
35
+ "separated by blank lines; the first one continues the verdict line). Empty = F1 record, "
36
+ "byte-identical to the record built without this option.")
37
+ a = ap.parse_args()
38
+ evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()]
39
+ start = next(e for e in evs if e["ev"] == "session_start")
40
+ if start.get("style", "la") not in ("la", None) and "style" in start:
41
+ raise SystemExit("only la-style runs are supported")
42
+ calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt]
43
+ done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt]
44
+ if not done:
45
+ raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)")
46
+ done = done[0]
47
+ if done["success"] and not a.allow_success:
48
+ raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)")
49
+ imgs = os.path.join(a.log, "images")
50
+ # commands as that agent issued them: `./robot <cmd>` in a CLI workspace, the `robot` tool's argument otherwise
51
+ try:
52
+ iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli")
53
+ except OSError:
54
+ iface = "cli"
55
+ pre = "./robot " if iface == "cli" else ""
56
+ os.makedirs(os.path.join(a.out, "obs"), exist_ok=False)
57
+
58
+ def copy(rel):
59
+ base = os.path.basename(rel)
60
+ src = os.path.join(imgs, f"a{a.attempt}_{base}")
61
+ if not os.path.exists(src):
62
+ return None
63
+ shutil.copy(src, os.path.join(a.out, "obs", base))
64
+ return f"obs/{base}"
65
+
66
+ # starting images: the first images the agent saw (status at step 0)
67
+ first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f)
68
+ start_imgs = [copy(f.split("_", 1)[1]) for f in first]
69
+ lines = ["# Record of the earlier attempt", "",
70
+ "Starting scene: " + ", ".join(p for p in start_imgs if p), "",
71
+ "## Robot commands and replies", ""]
72
+ rec = []
73
+ for i, e in enumerate(calls, 1):
74
+ rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP}
75
+ if "images" in rep:
76
+ rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2]
77
+ cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip()
78
+ lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""]
79
+ rec.append(dict(n=i, command=cmd, reply=rep))
80
+ lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "",
81
+ "## Closing remark of that attempt", "", str(done.get("reason", "")), "",
82
+ "## Result", ""]
83
+ verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.")
84
+ extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()]
85
+ if extra:
86
+ verdict += " " + extra[0]
87
+ lines += [verdict, ""]
88
+ for x in extra[1:]:
89
+ lines += [x, ""]
90
+ with open(os.path.join(a.out, "README.md"), "w") as f:
91
+ f.write("\n".join(lines))
92
+ with open(os.path.join(a.out, "record.jsonl"), "w") as f:
93
+ for r in rec:
94
+ f.write(json.dumps(r) + "\n")
95
+ with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f:
96
+ json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"),
97
+ arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"],
98
+ result_extra=a.result_extra), f)
99
+ print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs"))))))
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/make_video.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Record a scripted rollout of a task as an mp4 (agentview | wrist), with title cards between attempts.
2
+
3
+ python scripts/make_video.py --task l1_bias_place --kind adaptive --seed 1000
4
+ """
5
+ import argparse
6
+ import importlib
7
+ import os
8
+ import pkgutil
9
+ import sys
10
+ import textwrap
11
+
12
+ import numpy as np
13
+
14
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
+ sys.path.insert(0, ROOT)
16
+
17
+ import imageio # noqa: E402
18
+ from PIL import Image, ImageDraw, ImageFont # noqa: E402
19
+
20
+ import lffbench.tasks as task_pkg # noqa: E402
21
+ from lffbench import envs # noqa: E402
22
+ from lffbench.task_base import TASKS # noqa: E402
23
+
24
+ for m in pkgutil.iter_modules(task_pkg.__path__):
25
+ importlib.import_module(f"lffbench.tasks.{m.name}")
26
+
27
+ RES = 320
28
+ FPS = 15
29
+
30
+
31
+ def font(size):
32
+ try:
33
+ return ImageFont.load_default(size=size)
34
+ except TypeError:
35
+ return ImageFont.load_default()
36
+
37
+
38
+ def header(img, lines):
39
+ im = Image.fromarray(img)
40
+ d = ImageDraw.Draw(im)
41
+ d.rectangle([0, 0, im.width, 18 * len(lines) + 6], fill=(0, 0, 0))
42
+ for i, s in enumerate(lines):
43
+ d.text((6, 3 + 18 * i), s, fill=(255, 255, 255), font=font(15))
44
+ return np.asarray(im)
45
+
46
+
47
+ def card(lines, w, h, color=(20, 20, 20)):
48
+ im = Image.new("RGB", (w, h), color)
49
+ d = ImageDraw.Draw(im)
50
+ y = 20
51
+ for s in lines:
52
+ for part in textwrap.wrap(s, 70) or [""]:
53
+ d.text((20, y), part, fill=(255, 255, 255), font=font(18))
54
+ y += 24
55
+ y += 6
56
+ return np.asarray(im)
57
+
58
+
59
+ def main():
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--task", required=True)
62
+ ap.add_argument("--kind", default="adaptive")
63
+ ap.add_argument("--seed", type=int, default=1000)
64
+ ap.add_argument("--k", type=int, default=5)
65
+ ap.add_argument("--every", type=int, default=3, help="record one frame every N control steps")
66
+ ap.add_argument("--out", default=None)
67
+ args = ap.parse_args()
68
+
69
+ task = TASKS[args.task]()
70
+ env = task.env
71
+ inst = task.sample_instance(args.seed)
72
+ frames = []
73
+ state = dict(n=0, attempt=1)
74
+ W = 2 * RES
75
+
76
+ def grab():
77
+ a = envs.render(env, "agentview", RES)
78
+ w = envs.render(env, "robot0_eye_in_hand", RES)
79
+ img = np.concatenate([a, w], axis=1)
80
+ return header(img, [f"{args.task} [{task.level}] policy={args.kind} seed={args.seed}",
81
+ f"attempt {state['attempt']} t={state['n'] * 0.05:5.1f}s (sim) left: agentview right: wrist"])
82
+
83
+ orig_step = env.step
84
+
85
+ def step(a):
86
+ out = orig_step(a)
87
+ state["n"] += 1
88
+ if state["n"] % args.every == 0:
89
+ frames.append(grab())
90
+ return out
91
+
92
+ env.step = step
93
+
94
+ def on_attempt(a, params, out):
95
+ txt = [f"Attempt {a + 1}: {'SUCCESS' if out['success'] else 'FAILED'}"]
96
+ if out.get("detail"):
97
+ txt.append("Feedback (F2): " + out["detail"])
98
+ p = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in (params or {}).items()
99
+ if not isinstance(v, (list, dict)) or len(str(v)) < 120}
100
+ if p:
101
+ txt.append(f"params: {p}")
102
+ if not out["success"]:
103
+ txt.append(f"-> attempt {a + 2}")
104
+ frames.extend([card(txt, W, RES, (40, 20, 20) if not out["success"] else (20, 50, 20))] * (FPS * 3))
105
+ state["attempt"] = a + 2
106
+
107
+ intro = card([f"Task: {args.task} (level {task.level}; capabilities: {', '.join(task.capabilities)})",
108
+ f"Instruction: {task.instruction}",
109
+ f"Policy: {args.kind} (scripted reference)",
110
+ "Hidden variables are not visible to the policy."], W, RES)
111
+ frames.extend([intro] * (FPS * 3))
112
+ task.reset_instance(inst)
113
+ frames.append(grab())
114
+ n_cards_before = len(frames)
115
+ hist = task.run_scripted(args.kind, inst, k=args.k, seed=args.seed, on_attempt=on_attempt)
116
+ # tasks whose run_scripted does not call on_attempt: summarise at the end
117
+ if not any(f is not None and f.shape[0] == RES and (f[5, 5] == np.array([40, 20, 20])).all() for f in frames[n_cards_before:]) \
118
+ and not any((f[5, 5] == np.array([20, 50, 20])).all() for f in frames[n_cards_before:]):
119
+ lines = []
120
+ for h in hist:
121
+ o = h["outcome"]
122
+ lines.append(f"Attempt {h['attempt']}: {'SUCCESS' if o['success'] else 'FAILED'} — {o.get('detail', '')}")
123
+ frames.extend([card(lines[-6:], W, RES)] * (FPS * 4))
124
+ out = args.out or os.path.join(ROOT, "videos", f"{args.task}_{args.kind}_s{args.seed}.mp4")
125
+ os.makedirs(os.path.dirname(out), exist_ok=True)
126
+ imageio.mimwrite(out, frames, fps=FPS, quality=7, macro_block_size=8)
127
+ first = next((h["attempt"] for h in hist if h["outcome"]["success"]), None)
128
+ print(f"wrote {out} frames={len(frames)} attempts={len(hist)} first_success={first}")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/qwen_vl_server.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL.
3
+
4
+ Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one
5
+ CUDA-compatible device (here: Alibaba PPU) and exposes:
6
+
7
+ POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true
8
+ is emulated: the full answer is generated first
9
+ and then sent as SSE chunks)
10
+ GET /v1/models lists the single served model
11
+ GET /health liveness + device memory
12
+
13
+ Request format accepted (subset of OpenAI):
14
+ messages: system / developer / user / assistant (with tool_calls) / tool
15
+ user/tool content may be a string or a list of
16
+ {"type":"text","text":...} and
17
+ {"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}}
18
+ tools: [{"type":"function","function":{"name","description","parameters"}}]
19
+ tool_choice: "auto" (default) | "none" (tools hidden from the prompt) |
20
+ "required" (generation is prefixed with "<tool_call>\n") |
21
+ {"type":"function","function":{"name":X}} (prefixed with the call header for X)
22
+ parallel_tool_calls: false -> only the first parsed tool call is returned
23
+ max_tokens / max_completion_tokens (default --default-max-tokens, 1024)
24
+ temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list)
25
+ Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user.
26
+
27
+ The model emits Hermes-style <tool_call>{"name":..., "arguments":{...}}</tool_call>
28
+ blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON
29
+ string, and the remaining text (if any) becomes message.content (else null).
30
+
31
+ Generation is serialised with a lock (one request on the device at a time); the
32
+ HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import argparse
37
+ import base64
38
+ import io
39
+ import json
40
+ import logging
41
+ import os
42
+ import re
43
+ import sys
44
+ import threading
45
+ import time
46
+ import traceback
47
+ import urllib.request
48
+ import uuid
49
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
50
+
51
+ LOG = logging.getLogger("qwen_vl_server")
52
+
53
+ TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
54
+ END_MARKERS = ("<|im_end|>", "<|endoftext|>")
55
+
56
+
57
+ # ----------------------------------------------------------------------------
58
+ # Request conversion
59
+ # ----------------------------------------------------------------------------
60
+ class BadRequest(Exception):
61
+ pass
62
+
63
+
64
+ def load_image(url: str):
65
+ from PIL import Image
66
+
67
+ if url.startswith("data:"):
68
+ try:
69
+ _, b64 = url.split(",", 1)
70
+ except ValueError as e:
71
+ raise BadRequest("malformed data URL") from e
72
+ raw = base64.b64decode(b64)
73
+ elif url.startswith("http://") or url.startswith("https://"):
74
+ with urllib.request.urlopen(url, timeout=30) as r:
75
+ raw = r.read()
76
+ else:
77
+ path = url[len("file://"):] if url.startswith("file://") else url
78
+ with open(path, "rb") as f:
79
+ raw = f.read()
80
+ img = Image.open(io.BytesIO(raw))
81
+ img.load()
82
+ return img.convert("RGB")
83
+
84
+
85
+ def convert_content(content, images: list):
86
+ """OpenAI content (str | list[part] | None) -> Qwen template content.
87
+
88
+ Images are replaced by {"type": "image"} placeholders and the decoded PIL images
89
+ are appended to `images` in prompt order (the chat template emits one
90
+ <|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order).
91
+ """
92
+ if content is None:
93
+ return ""
94
+ if isinstance(content, str):
95
+ return content
96
+ if not isinstance(content, list):
97
+ raise BadRequest(f"unsupported content type: {type(content).__name__}")
98
+ out = []
99
+ for part in content:
100
+ if isinstance(part, str):
101
+ out.append({"type": "text", "text": part})
102
+ continue
103
+ ptype = part.get("type")
104
+ if ptype in ("text", "input_text"):
105
+ out.append({"type": "text", "text": part.get("text", "")})
106
+ elif ptype in ("image_url", "input_image", "image"):
107
+ iu = part.get("image_url", part.get("image"))
108
+ url = iu.get("url") if isinstance(iu, dict) else iu
109
+ if not isinstance(url, str):
110
+ raise BadRequest("image part without url")
111
+ try:
112
+ images.append(load_image(url))
113
+ except BadRequest:
114
+ raise
115
+ except Exception as e: # noqa: BLE001
116
+ raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e
117
+ out.append({"type": "image"})
118
+ else:
119
+ raise BadRequest(f"unsupported content part type: {ptype}")
120
+ return out
121
+
122
+
123
+ def text_only(content) -> str:
124
+ if content is None:
125
+ return ""
126
+ if isinstance(content, str):
127
+ return content
128
+ return "".join(p.get("text", "") for p in content if isinstance(p, dict))
129
+
130
+
131
+ def convert_messages(messages: list):
132
+ if not isinstance(messages, list) or not messages:
133
+ raise BadRequest("messages must be a non-empty list")
134
+ images: list = []
135
+ system_texts = []
136
+ conv = []
137
+ for m in messages:
138
+ role = m.get("role")
139
+ if role in ("system", "developer"):
140
+ # The Qwen template only renders a leading system message; merge all of them.
141
+ system_texts.append(text_only(m.get("content")))
142
+ elif role == "user":
143
+ conv.append({"role": "user", "content": convert_content(m.get("content"), images)})
144
+ elif role == "assistant":
145
+ c = m.get("content")
146
+ msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c}
147
+ tcs = m.get("tool_calls") or []
148
+ if tcs:
149
+ norm = []
150
+ for tc in tcs:
151
+ fn = tc.get("function", tc)
152
+ args = fn.get("arguments", {})
153
+ if not isinstance(args, str):
154
+ args = json.dumps(args, ensure_ascii=False)
155
+ norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}})
156
+ msg["tool_calls"] = norm
157
+ conv.append(msg)
158
+ elif role in ("tool", "function"):
159
+ conv.append({"role": "tool", "content": convert_content(m.get("content"), images)})
160
+ else:
161
+ raise BadRequest(f"unsupported role: {role}")
162
+ if system_texts:
163
+ conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)})
164
+ return conv, images
165
+
166
+
167
+ # ----------------------------------------------------------------------------
168
+ # Output parsing
169
+ # ----------------------------------------------------------------------------
170
+ def _loads_lenient(s: str):
171
+ s = s.strip()
172
+ try:
173
+ return json.loads(s)
174
+ except json.JSONDecodeError:
175
+ pass
176
+ # common slips: trailing garbage after the object, missing final brace
177
+ start = s.find("{")
178
+ if start >= 0:
179
+ dec = json.JSONDecoder()
180
+ try:
181
+ obj, _ = dec.raw_decode(s[start:])
182
+ return obj
183
+ except json.JSONDecodeError:
184
+ pass
185
+ for extra in ("}", "}}", "\"}}"):
186
+ try:
187
+ return json.loads(s[start:] + extra)
188
+ except json.JSONDecodeError:
189
+ continue
190
+ return None
191
+
192
+
193
+ def parse_tool_calls(text: str):
194
+ """Return (content_or_None, tool_calls_list)."""
195
+ calls = []
196
+ spans = []
197
+ for mt in TOOL_CALL_RE.finditer(text):
198
+ spans.append(mt.span())
199
+ calls.append(mt.group(1))
200
+ # an unterminated trailing <tool_call> (e.g. hit max_tokens / model forgot the tag)
201
+ last_end = spans[-1][1] if spans else 0
202
+ tail_idx = text.find("<tool_call>", last_end)
203
+ if tail_idx >= 0:
204
+ spans.append((tail_idx, len(text)))
205
+ calls.append(text[tail_idx + len("<tool_call>"):])
206
+
207
+ tool_calls = []
208
+ keep_raw = [] # unparsable blocks stay in content
209
+ for (a, b), body in zip(spans, calls):
210
+ obj = _loads_lenient(body)
211
+ if not isinstance(obj, dict) or "name" not in obj:
212
+ keep_raw.append((a, b))
213
+ continue
214
+ args = obj.get("arguments", obj.get("parameters", {}))
215
+ if isinstance(args, str):
216
+ parsed = _loads_lenient(args)
217
+ args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args
218
+ else:
219
+ args_str = json.dumps(args, ensure_ascii=False)
220
+ tool_calls.append({
221
+ "id": "call_" + uuid.uuid4().hex[:24],
222
+ "type": "function",
223
+ "function": {"name": str(obj["name"]), "arguments": args_str},
224
+ })
225
+
226
+ # content = text with successfully parsed blocks removed
227
+ parsed_spans = [s for s in spans if s not in keep_raw]
228
+ pieces, pos = [], 0
229
+ for a, b in sorted(parsed_spans):
230
+ pieces.append(text[pos:a])
231
+ pos = b
232
+ pieces.append(text[pos:])
233
+ content = "".join(pieces).strip()
234
+ return (content if content else None), tool_calls
235
+
236
+
237
+ # ----------------------------------------------------------------------------
238
+ # Model wrapper
239
+ # ----------------------------------------------------------------------------
240
+ class Engine:
241
+ def __init__(self, args):
242
+ import torch
243
+ from transformers import AutoModelForImageTextToText, AutoProcessor
244
+
245
+ self.torch = torch
246
+ self.args = args
247
+ self.device = args.device
248
+ t0 = time.time()
249
+ proc_kwargs = {}
250
+ if args.min_pixels:
251
+ proc_kwargs["min_pixels"] = args.min_pixels
252
+ if args.max_pixels:
253
+ proc_kwargs["max_pixels"] = args.max_pixels
254
+ if args.attn == "sdpa" and not args.sdpa_native_gqa:
255
+ # PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps
256
+ # (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads,
257
+ # head_size_og)". Make transformers repeat K/V heads itself instead.
258
+ import transformers.integrations.sdpa_attention as _sdpa
259
+
260
+ _sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False
261
+ self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs)
262
+ self.tokenizer = self.processor.tokenizer
263
+ self.model = AutoModelForImageTextToText.from_pretrained(
264
+ args.model,
265
+ dtype=torch.bfloat16,
266
+ attn_implementation=args.attn,
267
+ device_map={"": self.device},
268
+ ).eval()
269
+ self.load_time = time.time() - t0
270
+ self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS]
271
+ self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0]
272
+ self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1]
273
+ self.lock = threading.Lock()
274
+ LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB",
275
+ self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30)
276
+
277
+ def mem(self):
278
+ t = self.torch
279
+ return {
280
+ "allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2),
281
+ "reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2),
282
+ "max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2),
283
+ }
284
+
285
+ def chat(self, req: dict):
286
+ torch = self.torch
287
+ a = self.args
288
+ messages, images = convert_messages(req.get("messages"))
289
+ tools = req.get("tools") or None
290
+ tool_choice = req.get("tool_choice", "auto")
291
+ prefix = ""
292
+ if tools:
293
+ if tool_choice == "none":
294
+ tools = None
295
+ elif tool_choice == "required":
296
+ prefix = "<tool_call>\n"
297
+ elif isinstance(tool_choice, dict):
298
+ fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name")
299
+ if fname:
300
+ prefix = '<tool_call>\n{"name": "' + fname + '", "arguments": '
301
+ tmpl_tools = None
302
+ if tools:
303
+ tmpl_tools = []
304
+ for t in tools:
305
+ if isinstance(t, dict) and "function" not in t and "name" in t:
306
+ t = {"type": "function", "function": t}
307
+ tmpl_tools.append(t)
308
+
309
+ prompt = self.processor.apply_chat_template(
310
+ messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True
311
+ ) + prefix
312
+ inputs = self.processor(
313
+ text=[prompt], images=images if images else None, return_tensors="pt"
314
+ ).to(self.device)
315
+ n_prompt = int(inputs["input_ids"].shape[1])
316
+ if n_prompt > a.max_prompt_tokens:
317
+ raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}")
318
+
319
+ max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens
320
+ max_new = int(min(max_new, a.max_tokens_cap))
321
+ temperature = req.get("temperature")
322
+ if temperature is None:
323
+ temperature = a.default_temperature
324
+ gen_kwargs = dict(
325
+ max_new_tokens=max_new,
326
+ eos_token_id=self.eos_ids,
327
+ pad_token_id=self.pad_id,
328
+ use_cache=True,
329
+ )
330
+ if temperature and float(temperature) > 0:
331
+ gen_kwargs.update(do_sample=True, temperature=float(temperature),
332
+ top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20))
333
+ else:
334
+ gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None)
335
+ if req.get("seed") is not None:
336
+ torch.manual_seed(int(req["seed"]))
337
+
338
+ with torch.inference_mode():
339
+ out = self.model.generate(**inputs, **gen_kwargs)
340
+ new_ids = out[0, n_prompt:].tolist()
341
+ # count tokens up to and including the first EOS
342
+ n_completion = len(new_ids)
343
+ hit_eos = False
344
+ for i, tid in enumerate(new_ids):
345
+ if tid in self.eos_ids:
346
+ n_completion = i + 1
347
+ hit_eos = True
348
+ break
349
+ text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False)
350
+ for mk in END_MARKERS:
351
+ text = text.replace(mk, "")
352
+ text = prefix + text
353
+
354
+ stop = req.get("stop")
355
+ stopped_by_str = False
356
+ if stop:
357
+ for s in ([stop] if isinstance(stop, str) else stop):
358
+ k = text.find(s, len(prefix))
359
+ if k >= 0:
360
+ text = text[:k]
361
+ stopped_by_str = True
362
+
363
+ if tools:
364
+ content, tool_calls = parse_tool_calls(text)
365
+ if tool_calls and req.get("parallel_tool_calls") is False:
366
+ tool_calls = tool_calls[:1]
367
+ else:
368
+ content, tool_calls = (text.strip() or None), []
369
+
370
+ if tool_calls:
371
+ finish = "tool_calls"
372
+ elif hit_eos or stopped_by_str:
373
+ finish = "stop"
374
+ else:
375
+ finish = "length"
376
+ message = {"role": "assistant", "content": content}
377
+ if tool_calls:
378
+ message["tool_calls"] = tool_calls
379
+ usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion,
380
+ "total_tokens": n_prompt + n_completion}
381
+ return message, finish, usage, len(images), text
382
+
383
+
384
+ # ----------------------------------------------------------------------------
385
+ # HTTP
386
+ # ----------------------------------------------------------------------------
387
+ ENGINE: Engine | None = None
388
+ ARGS = None
389
+
390
+
391
+ class Handler(BaseHTTPRequestHandler):
392
+ protocol_version = "HTTP/1.1"
393
+
394
+ def log_message(self, fmt, *args): # route http.server logs through logging
395
+ LOG.debug("%s - %s", self.address_string(), fmt % args)
396
+
397
+ def _send_json(self, code: int, obj):
398
+ body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
399
+ self.send_response(code)
400
+ self.send_header("Content-Type", "application/json")
401
+ self.send_header("Content-Length", str(len(body)))
402
+ self.end_headers()
403
+ self.wfile.write(body)
404
+
405
+ def _error(self, code: int, msg: str, etype: str):
406
+ self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}})
407
+
408
+ def do_GET(self):
409
+ if self.path.rstrip("/") in ("/health", "/v1/health"):
410
+ self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(),
411
+ "load_time_s": round(ENGINE.load_time, 1)})
412
+ elif self.path.rstrip("/") == "/v1/models":
413
+ self._send_json(200, {"object": "list", "data": [
414
+ {"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]})
415
+ else:
416
+ self._error(404, f"no route {self.path}", "not_found")
417
+
418
+ def do_POST(self):
419
+ if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"):
420
+ self._error(404, f"no route {self.path}", "not_found")
421
+ return
422
+ try:
423
+ n = int(self.headers.get("Content-Length", "0"))
424
+ req = json.loads(self.rfile.read(n).decode("utf-8"))
425
+ except Exception as e: # noqa: BLE001
426
+ self._error(400, f"invalid JSON body: {e}", "invalid_request_error")
427
+ return
428
+ t0 = time.time()
429
+ try:
430
+ with ENGINE.lock:
431
+ t_lock = time.time()
432
+ message, finish, usage, n_img, raw = ENGINE.chat(req)
433
+ except BadRequest as e:
434
+ self._error(400, str(e), "invalid_request_error")
435
+ return
436
+ except Exception as e: # noqa: BLE001
437
+ LOG.error("generation failed: %s\n%s", e, traceback.format_exc())
438
+ if "out of memory" in str(e).lower():
439
+ try:
440
+ ENGINE.torch.cuda.empty_cache()
441
+ except Exception: # noqa: BLE001
442
+ pass
443
+ self._error(500, f"{type(e).__name__}: {e}", "server_error")
444
+ return
445
+ dt = time.time() - t0
446
+ LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s",
447
+ n_img, usage["prompt_tokens"], usage["completion_tokens"], finish,
448
+ len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem())
449
+ if ARGS.log_outputs:
450
+ LOG.info("raw output: %r", raw)
451
+ cid = "chatcmpl-" + uuid.uuid4().hex[:24]
452
+ created = int(time.time())
453
+ model_name = req.get("model") or ARGS.served_name
454
+ if req.get("stream"):
455
+ self._send_stream(cid, created, model_name, message, finish, usage, req)
456
+ return
457
+ self._send_json(200, {
458
+ "id": cid,
459
+ "object": "chat.completion",
460
+ "created": created,
461
+ "model": model_name,
462
+ "choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}],
463
+ "usage": usage,
464
+ "server_timing": {"latency_s": round(dt, 3)},
465
+ })
466
+
467
+ def _send_stream(self, cid, created, model_name, message, finish, usage, req):
468
+ self.send_response(200)
469
+ self.send_header("Content-Type", "text/event-stream")
470
+ self.send_header("Cache-Control", "no-cache")
471
+ self.send_header("Connection", "close")
472
+ self.end_headers()
473
+ self.close_connection = True
474
+
475
+ def chunk(delta, fr=None, with_usage=False):
476
+ obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name,
477
+ "choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]}
478
+ if with_usage:
479
+ obj["usage"] = usage
480
+ self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n")
481
+
482
+ chunk({"role": "assistant", "content": message.get("content") or ""})
483
+ for i, tc in enumerate(message.get("tool_calls", [])):
484
+ chunk({"tool_calls": [dict(tc, index=i)]})
485
+ include_usage = bool((req.get("stream_options") or {}).get("include_usage"))
486
+ chunk({}, finish, with_usage=include_usage)
487
+ self.wfile.write(b"data: [DONE]\n\n")
488
+ self.wfile.flush()
489
+
490
+
491
+ def main():
492
+ global ENGINE, ARGS
493
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
494
+ p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct"))
495
+ p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct")
496
+ p.add_argument("--host", default="127.0.0.1")
497
+ p.add_argument("--port", type=int, default=8765)
498
+ p.add_argument("--device", default="cuda:0")
499
+ p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"])
500
+ p.add_argument("--sdpa-native-gqa", action="store_true",
501
+ help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default")
502
+ p.add_argument("--default-max-tokens", type=int, default=1024)
503
+ p.add_argument("--max-tokens-cap", type=int, default=8192)
504
+ p.add_argument("--max-prompt-tokens", type=int, default=65536)
505
+ p.add_argument("--default-temperature", type=float, default=0.0,
506
+ help="used when the request has no temperature; 0 = greedy")
507
+ p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels")
508
+ p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels")
509
+ p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request")
510
+ p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving")
511
+ ARGS = p.parse_args()
512
+
513
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout)
514
+ import transformers
515
+
516
+ LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__))
517
+ ENGINE = Engine(ARGS)
518
+ if ARGS.warmup:
519
+ t = time.time()
520
+ with ENGINE.lock:
521
+ ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4})
522
+ LOG.info("warmup done in %.1fs", time.time() - t)
523
+ srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler)
524
+ srv.daemon_threads = True
525
+ LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port)
526
+ try:
527
+ srv.serve_forever()
528
+ except KeyboardInterrupt:
529
+ pass
530
+ finally:
531
+ srv.server_close()
532
+
533
+
534
+ if __name__ == "__main__":
535
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/real_check_driver.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Conformance check of a robot driver (lffbench/real/protocol.py, spec lffbench/real/DRIVER.md). Run it on the robot PC
3
+ (or through the SSH tunnel) before the first real run, and again after any change to the driver.
4
+
5
+ python scripts/real_check_driver.py --driver http://127.0.0.1:9900 --token <token> [--yes] [--operator] [--json]
6
+
7
+ The arm moves a little: 3 cm up and back, a 30 deg turn and back, the gripper closes and opens, all at 5 cm/s from
8
+ the current pose. Keep a hand on the e-stop. --yes skips the confirmation; --operator also tests the operator
9
+ prompts (you answer them on the driver's terminal). Needs only Python 3 + numpy + Pillow.
10
+ Exit code 0 = every check PASS (WARN does not fail).
11
+ """
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+ import time
17
+
18
+ HERE = os.path.dirname(os.path.abspath(__file__))
19
+ sys.path[:0] = [HERE, os.path.join(os.path.dirname(HERE), "lffbench", "real")] # protocol.py next to it, or the repo copy
20
+ import numpy as np # noqa: E402
21
+
22
+ from protocol import (CAMERAS, DriverClient, DriverError, info_problems, state_problems) # noqa: E402
23
+
24
+
25
+ class Checks:
26
+ def __init__(self):
27
+ self.rows = []
28
+
29
+ def add(self, name, status, detail=""):
30
+ self.rows.append(dict(name=name, status=status, detail=str(detail)))
31
+ print(f"[{status}] {name} {detail}", file=sys.stderr, flush=True)
32
+ return status == "PASS"
33
+
34
+ def ok(self, name, cond, detail="", warn=False):
35
+ return self.add(name, "PASS" if cond else ("WARN" if warn else "FAIL"), detail)
36
+
37
+
38
+ def yaw_diff(a, b):
39
+ return abs((a - b + 90.0) % 180.0 - 90.0)
40
+
41
+
42
+ def main():
43
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
44
+ ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"))
45
+ ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
46
+ ap.add_argument("--yes", action="store_true", help="do not ask before moving the arm")
47
+ ap.add_argument("--operator", action="store_true", help="also test the operator prompts (reset, judge)")
48
+ ap.add_argument("--json", action="store_true", help="print a JSON summary as the last line of stdout")
49
+ ap.add_argument("--yaw-tol", type=float, default=2.0, help="degrees (keep 2 for a real arm)")
50
+ a = ap.parse_args()
51
+ C = Checks()
52
+ d = DriverClient(a.driver, a.token, timeout=120)
53
+ try:
54
+ run(C, d, a)
55
+ except DriverError as e:
56
+ C.add("driver answered every request", "FAIL", e)
57
+ n_fail = sum(r["status"] == "FAIL" for r in C.rows)
58
+ print(f"\n{len(C.rows) - n_fail} ok / {n_fail} FAIL", file=sys.stderr)
59
+ if a.json:
60
+ print(json.dumps(dict(checks=C.rows, n_fail=n_fail)))
61
+ sys.exit(1 if n_fail else 0)
62
+
63
+
64
+ def run(C, d, a):
65
+ # ---- no motion
66
+ bad = DriverClient(d.url, d.token + "-wrong")
67
+ try:
68
+ rep = bad.call("state", allow_not_ok=True)
69
+ C.ok("wrong token is refused", rep.get("ok") is False, rep.get("error", ""))
70
+ except DriverError as e:
71
+ C.add("wrong token is refused", "FAIL", e)
72
+ info = d.call("info")
73
+ prob = info_problems(info)
74
+ if not C.ok("/info has every field", not prob, "; ".join(prob) or {k: info[k] for k in ("robot", "n_joints", "workspace")}):
75
+ return
76
+ n = int(info["n_joints"])
77
+ st = d.state()
78
+ prob = state_problems(st, n)
79
+ if not C.ok("/state has every field", not prob, "; ".join(prob) or st):
80
+ return
81
+ lo, hi = np.array(info["workspace"]["lo"]), np.array(info["workspace"]["hi"])
82
+ p0 = np.array(st["eef_pos"])
83
+ C.ok("current grasp point inside the declared workspace", bool(np.all(p0 >= lo) and np.all(p0 <= hi)), p0.round(4).tolist())
84
+ t0 = time.time()
85
+ frames, st2 = d.observe()
86
+ dt = time.time() - t0
87
+ for c in CAMERAS:
88
+ f = frames[c]
89
+ C.ok(f"/observe {c}: RGB image", f.ndim == 3 and f.shape[2] == 3 and min(f.shape[:2]) >= 256,
90
+ f"{f.shape[1]}x{f.shape[0]}")
91
+ C.ok(f"/observe {c}: not blank", float(f.std()) > 5.0, f"pixel std {f.std():.1f}")
92
+ h, w = f.shape[:2]
93
+ C.ok(f"/observe {c}: square or close to it (the benchmark centre-crops to a square)", 0.75 <= w / h <= 1.34,
94
+ f"{w}x{h}: {abs(w - h) // 2} px cut on each side", warn=True)
95
+ C.ok("/observe also returns the state", not state_problems(st2, n))
96
+ C.ok("/observe latency", dt < 2.0, f"{dt:.2f} s", warn=True)
97
+ rep = d.call("event", dict(ev="session_start", run="check_driver", task="check", seed=0))
98
+ C.ok("/event answers", rep["ok"])
99
+ rep = d.operator("notice", run="check_driver", attempt=0, text="real_check_driver.py: conformance check running")
100
+ C.ok("/operator notice answers", rep["ok"])
101
+ if info["ik"]:
102
+ q = d.ik(st["eef_pos"], st["eef_yaw_deg"])
103
+ err = float(np.max(np.abs(np.array(q) - np.array(st["joint_pos_rad"])))) if len(q) == n else None
104
+ C.ok("/ik of the current pose = current joint angles (within 0.05 rad)", err is not None and err < 0.05,
105
+ f"max |dq| = {err}")
106
+ # ---- rejected targets: must not move
107
+ for name, tgt in (("far outside the workspace (x + 1 m)", [hi[0] + 1.0, p0[1], p0[2]]),
108
+ ("below the workspace floor (z - 5 cm)", [p0[0], p0[1], lo[2] - 0.05])):
109
+ rep = d.move(*tgt, st["eef_yaw_deg"], 0.05)
110
+ moved = float(np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0))
111
+ C.ok(f"/move {name} is rejected and the arm does not move", rep["ok"] is False and moved < 0.005,
112
+ f"ok={rep['ok']} error={rep.get('error')!r} moved {moved * 100:.1f} cm")
113
+ # ---- motion
114
+ if not a.yes:
115
+ input("\nThe arm will now move 3 cm up and back, turn 30 deg and back, close and open the gripper, at 5 cm/s.\n"
116
+ "Keep a hand on the e-stop and press Enter... ")
117
+ up = p0 + [0.0, 0.0, 0.03]
118
+ if up[2] > hi[2]:
119
+ up = p0 - [0.0, 0.0, 0.03]
120
+ y0 = float(st["eef_yaw_deg"])
121
+ rep = d.move(*up, y0, 0.05)
122
+ p = np.array(rep["state"]["eef_pos"])
123
+ C.ok("/move 3 cm vertical: ok", rep["ok"], rep.get("error", ""))
124
+ C.ok("/move 3 cm vertical: reached within 5 mm", np.linalg.norm(p - up) < 0.005, f"error {np.linalg.norm(p - up) * 1000:.1f} mm")
125
+ C.ok("/move 3 cm vertical: blocking, motion_s plausible at 5 cm/s", 0.3 <= rep["motion_s"] <= 5.0, f"motion_s={rep['motion_s']}")
126
+ C.ok("/move keeps the yaw (within 2 deg)", yaw_diff(rep["state"]["eef_yaw_deg"], y0) < 2.0,
127
+ f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}")
128
+ y1 = y0 + 30.0 if y0 + 30.0 <= info["yaw_range_deg"][1] else y0 - 30.0
129
+ rep = d.move(*up, y1, 0.05)
130
+ C.ok(f"/move turn 30 deg: reached within {a.yaw_tol:g} deg", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y1) < a.yaw_tol,
131
+ f"{rep['state']['eef_yaw_deg']:.1f} vs {y1:.1f}")
132
+ C.ok("/move turn 30 deg: position kept (within 5 mm)", np.linalg.norm(np.array(rep["state"]["eef_pos"]) - up) < 0.005)
133
+ sign = 1.0 if y1 > y0 else -1.0
134
+ C.add("yaw sign (look at the arm)", "NOTE",
135
+ f"it just turned {sign * 30:+.0f} deg: + must be counter-clockwise seen from above (DRIVER.md §3)")
136
+ rep = d.move(*up, y0, 0.05)
137
+ C.ok("/move turn back", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y0) < a.yaw_tol,
138
+ f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}")
139
+ rep = d.gripper(True)
140
+ w_closed = rep["state"]["gripper_width_m"]
141
+ C.ok("/gripper close: width < 1 cm when closed on nothing", w_closed < 0.01, f"{w_closed:.4f} m, motion_s={rep['motion_s']}")
142
+ rep = d.gripper(False)
143
+ w_open = rep["state"]["gripper_width_m"]
144
+ C.ok("/gripper open: width > 3 cm", w_open > 0.03, f"{w_open:.4f} m")
145
+ rep = d.move(*p0, y0, 0.05)
146
+ C.ok("/move back to the start pose", rep["ok"] and np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0) < 0.005)
147
+ rep = d.home()
148
+ C.ok("/home answers with the state", rep["ok"] and not state_problems(rep["state"], n))
149
+ rep = d.call("event", dict(ev="attempt_start", run="check_driver", attempt=1)) # starts the driver's recorder
150
+ time.sleep(2.0)
151
+ rep2 = d.call("event", dict(ev="attempt_end", run="check_driver", attempt=1))
152
+ C.ok("/event attempt_start / attempt_end answer (recording)", rep["ok"] and rep2["ok"],
153
+ "check that the driver wrote a short video (driver_template: <log>/check_driver_a1.mp4)")
154
+ if a.operator:
155
+ rep = d.operator("reset", run="check_driver", attempt=1, setup="(test) nothing to change, just press Enter")
156
+ C.ok("/operator reset returns after Enter", rep["ok"])
157
+ rep = d.operator("judge", run="check_driver", attempt=1, checklist=["(test) answer y"])
158
+ C.ok("/operator judge returns success", rep.get("success") is True, rep)
159
+ d.call("event", dict(ev="session_end", run="check_driver"))
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/record_compound_remaining.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Uncut simulation and annotated synchronized views of one reference attempt."""
2
+ import argparse,hashlib,importlib,json,textwrap
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import imageio.v2 as imageio
6
+ from PIL import Image,ImageDraw,ImageFont
7
+ import robosuite.utils.transform_utils as T
8
+ from lffbench import envs
9
+ from lffbench.task_base import TASKS
10
+ from check_compound_remaining import plain
11
+ FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
12
+ TITLES={'lh_desk_organizer':'CLEAR THE DESK','lh_split_calibration':'TWO WORKSTATIONS','lh_shim_relay':'ONE SUPPORT, TWO TRAYS'}
13
+ class Recorder:
14
+ def __init__(self,t,out):
15
+ self.t=t;self.out=out;self.n=0;self.frames=0;self.raw_n=0;self.timeline=[];self.phase='Initial scene'
16
+ self.raw=imageio.get_writer(str(out/'full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1)
17
+ self.preview=imageio.get_writer(str(out/'recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1)
18
+ self.original=t.env.step;t.env.step=self.step
19
+ m=t.env.sim.model;c=m.camera_name2id('sideview')
20
+ pos,target=({'lh_desk_organizer':([-.62,-.46,1.20],[-.26,-.08,.98]),'lh_split_calibration':([-.48,-.48,1.17],[-.22,-.18,.94]),'lh_shim_relay':([-.58,-.56,1.30],[-.04,0,.99])})[t.name]
21
+ pos=np.array(pos);z=pos-np.array(target);z/=np.linalg.norm(z);x=np.cross([0,0,1],z);x/=np.linalg.norm(x);y=np.cross(z,x);q=T.mat2quat(np.column_stack([x,y,z]))
22
+ m.cam_pos[c]=pos;m.cam_quat[c]=q[[3,0,1,2]];m.cam_fovy[c]=48;t.env.sim.forward()
23
+ def step(self,a):
24
+ r=self.original(a);self.n+=1
25
+ if self.n%4==0:self.capture()
26
+ return r
27
+ def main(self):return Image.fromarray(envs.render(self.t.env,res=768))
28
+ def decorate(self,im):
29
+ c=Image.new('RGB',(1280,928),(19,26,36));c.paste(im,(0,48));c.paste(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)),(768,80))
30
+ d=ImageDraw.Draw(c);f=ImageFont.truetype(FONT,23);sm=ImageFont.truetype(FONT,19)
31
+ d.text((18,10),TITLES[self.t.name]+' | scripted reference | one continuous attempt | 2x',font=f,fill='white')
32
+ d.text((785,52),'Synchronized side view',font=sm,fill='#b5ccdf')
33
+ d.text((790,615),f'Simulation time: {self.n*.05:.1f} s',font=f,fill='white')
34
+ for k,key in enumerate(self.t.failure_causes):
35
+ a=self.t.traps[key];b=self.t.recovered[key]
36
+ d.text((790,660+40*k),f'{key}: '+('recovered' if a and b else 'triggered' if a else 'not yet triggered'),font=f,fill='#93e7a8' if a and b else '#ffe0a2' if a else '#b5ccdf')
37
+ for k,line in enumerate(textwrap.wrap(self.phase,width=95)[:2]):d.text((18,826+30*k),line,font=f,fill='#ffe0a2')
38
+ d.text((18,897),'Rigid-body contacts; no scene reset or object teleport during this attempt.',font=sm,fill='#b5ccdf')
39
+ return np.asarray(c)
40
+ def capture(self):
41
+ im=self.main();self.raw.append_data(np.asarray(im));self.raw_n+=1;self.preview.append_data(self.decorate(im));self.frames+=1
42
+ def phase_hook(self,text,state):
43
+ self.phase=text;row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames);self.timeline.append(row)
44
+ im=self.main();im.save(self.out/f'checkpoint_{len(self.timeline):02d}.png')
45
+ for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1
46
+ print(json.dumps(row,default=plain),flush=True)
47
+ def close(self):self.t.env.step=self.original;self.raw.close();self.preview.close()
48
+ def main():
49
+ p=argparse.ArgumentParser();p.add_argument('--task',required=True);p.add_argument('--seed',type=int,default=1000);p.add_argument('--out',required=True);a=p.parse_args()
50
+ importlib.import_module('lffbench.tasks.'+a.task);out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
51
+ t=TASKS[a.task]();i=t.sample_instance(a.seed);t.reset_instance(i);r=Recorder(t,out);t.phase_hook=r.phase_hook
52
+ root=Path(__file__).resolve().parents[1];paths=[root/'lffbench'/n for n in ['envs.py','skills.py','task_base.py','objects.py','bddl.py','tasks/'+a.task+'.py','tasks/lh_shelf_droop.py','tasks/lh_lid_box.py']]
53
+ hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in paths}
54
+ try:
55
+ t.execute(i,{'mode':'adaptive'});result=t.outcome(i);r.phase_hook('FINAL: all goals verified' if result['success'] else 'FINAL: verification failed',dict(step=t.sk.n_steps,outcome=result))
56
+ finally:r.close()
57
+ meta=dict(task=a.task,seed=a.seed,instance=i,outcome=result,scope='Scripted reference with privileged observations, not a model evaluation',continuous_attempt=True,resets_during_recording=0,source_hashes=hashes,
58
+ source_unchanged=all(hashlib.sha256(Path(f).read_bytes()).hexdigest()==h for f,h in hashes.items()),sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline,
59
+ presentation='2x with 1-second labeled presentation freezes. Full 1x is uncut with no freezes.',video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')})
60
+ (out/'recording.json').write_text(json.dumps(meta,indent=2,default=plain));t.env.close()
61
+ assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()) and meta['source_unchanged'],result
62
+ if __name__=='__main__':main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/summarize.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Aggregate results/<task>/validate.json into results/SUMMARY.md (headroom table)."""
2
+ import glob
3
+ import json
4
+ import os
5
+
6
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+
8
+
9
+ def main():
10
+ rows = []
11
+ for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))):
12
+ r = json.load(open(p))
13
+ s = r["succ_at_k"]
14
+
15
+ def g(kind, j):
16
+ v = s.get(kind)
17
+ return "—" if v is None else f"{100 * v[j - 1]:.0f}"
18
+
19
+ k = r["k"]
20
+ rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | "
21
+ f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | "
22
+ f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |")
23
+ head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n"
24
+ "|---|---|---|---|---|---|---|---|---|")
25
+ text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n"
26
+ out = os.path.join(ROOT, "results", "SUMMARY.md")
27
+ with open(out, "w") as f:
28
+ f.write(text)
29
+ print(text)
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/validate.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Headroom validation of LFF-Bench tasks with scripted reference policies.
2
+
3
+ python scripts/validate.py --task l5_slide_to_target --n 20 --k 5
4
+ Writes results/<task>/validate.json and thumbnails.
5
+ """
6
+ import argparse
7
+ import importlib
8
+ import json
9
+ import os
10
+ import pkgutil
11
+ import sys
12
+ import time
13
+
14
+ import numpy as np
15
+
16
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ sys.path.insert(0, ROOT)
18
+
19
+ import imageio # noqa: E402
20
+
21
+ import lffbench.tasks as task_pkg # noqa: E402
22
+ from lffbench.task_base import TASKS # noqa: E402
23
+
24
+ for m in pkgutil.iter_modules(task_pkg.__path__):
25
+ importlib.import_module(f"lffbench.tasks.{m.name}")
26
+
27
+
28
+ def succ_curve(results, k):
29
+ """run-level succ@j for j = 1..k (a run = one instance, attempts share the run's state)."""
30
+ out = []
31
+ for j in range(1, k + 1):
32
+ out.append(float(np.mean([r is not None and r <= j for r in results])))
33
+ return out
34
+
35
+
36
+ def main():
37
+ ap = argparse.ArgumentParser()
38
+ ap.add_argument("--task", required=True)
39
+ ap.add_argument("--n", type=int, default=20)
40
+ ap.add_argument("--k", type=int, default=5)
41
+ ap.add_argument("--seed0", type=int, default=1000)
42
+ ap.add_argument("--kinds", default="oracle,naive,adaptive,blind")
43
+ ap.add_argument("--thumbs", type=int, default=3)
44
+ args = ap.parse_args()
45
+
46
+ task = TASKS[args.task]()
47
+ outdir = os.path.join(ROOT, "results", args.task)
48
+ os.makedirs(outdir, exist_ok=True)
49
+ kinds = args.kinds.split(",")
50
+ first_success = {k: [] for k in kinds}
51
+ runs = []
52
+ t0 = time.time()
53
+ for i in range(args.n):
54
+ seed = args.seed0 + i
55
+ inst = task.sample_instance(seed)
56
+ if i < args.thumbs:
57
+ task.reset_instance(inst)
58
+ imageio.imwrite(os.path.join(outdir, f"init_{seed}.png"), task.snapshot(res=384))
59
+ for kind in kinds:
60
+ hist = task.run_scripted(kind, inst, k=args.k, seed=seed)
61
+ s = next((h["attempt"] for h in hist if h["outcome"]["success"]), None)
62
+ first_success[kind].append(s)
63
+ runs.append(dict(seed=seed, kind=kind, inst={k: v for k, v in inst.items() if not k.startswith("_")},
64
+ history=hist))
65
+ if i < args.thumbs and kind == "naive":
66
+ imageio.imwrite(os.path.join(outdir, f"naive_end_{seed}.png"), task.snapshot(res=384))
67
+ print(f"[{i + 1}/{args.n}] seed={seed} " + " ".join(f"{k}={first_success[k][-1]}" for k in kinds)
68
+ + f" ({time.time() - t0:.0f}s)", flush=True)
69
+
70
+ summary = {k: succ_curve(v, args.k) for k, v in first_success.items()}
71
+ res = dict(task=args.task, level=task.level, capabilities=list(task.capabilities), n=args.n, k=args.k,
72
+ succ_at_k=summary, runs=runs, seconds=time.time() - t0)
73
+ with open(os.path.join(outdir, "validate.json"), "w") as f:
74
+ json.dump(res, f, indent=1, default=float)
75
+ print(json.dumps({k: [round(x, 2) for x in v] for k, v in summary.items()}))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/release/image_stats.json ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "pass",
3
+ "created": "2026-11-06T15:33:02.982962+00:00",
4
+ "method": "Full RGB pixel histograms from distinct floor(n/4), floor(n/2), floor(3n/4) frames per episode; float64 moments and exact histogram quantiles. Samples are stratified by episode, not a full-frame census.",
5
+ "sample_frames_per_camera": {
6
+ "observation.images.image": 123,
7
+ "observation.images.wrist_image": 123
8
+ },
9
+ "old_zero_std_episode_camera_pairs": 82,
10
+ "old_global_image_stats": {
11
+ "observation.images.image": {
12
+ "min": [
13
+ [
14
+ [
15
+ 0.0
16
+ ]
17
+ ],
18
+ [
19
+ [
20
+ 0.0
21
+ ]
22
+ ],
23
+ [
24
+ [
25
+ 0.0
26
+ ]
27
+ ]
28
+ ],
29
+ "max": [
30
+ [
31
+ [
32
+ 1.0
33
+ ]
34
+ ],
35
+ [
36
+ [
37
+ 1.0
38
+ ]
39
+ ],
40
+ [
41
+ [
42
+ 1.0
43
+ ]
44
+ ]
45
+ ],
46
+ "mean": [
47
+ [
48
+ [
49
+ 0.5568382349550881
50
+ ]
51
+ ],
52
+ [
53
+ [
54
+ 0.5169564268987544
55
+ ]
56
+ ],
57
+ [
58
+ [
59
+ 0.47270913066691733
60
+ ]
61
+ ]
62
+ ],
63
+ "std": [
64
+ [
65
+ [
66
+ 0.011156032243561901
67
+ ]
68
+ ],
69
+ [
70
+ [
71
+ 0.01106973955252011
72
+ ]
73
+ ],
74
+ [
75
+ [
76
+ 0.012984140373567328
77
+ ]
78
+ ]
79
+ ],
80
+ "count": [
81
+ 37912
82
+ ],
83
+ "q01": [
84
+ [
85
+ [
86
+ 0.09321265999066689
87
+ ]
88
+ ],
89
+ [
90
+ [
91
+ 0.09432396444890886
92
+ ]
93
+ ],
94
+ [
95
+ [
96
+ 0.08553305654884547
97
+ ]
98
+ ]
99
+ ],
100
+ "q10": [
101
+ [
102
+ [
103
+ 0.38254107921858377
104
+ ]
105
+ ],
106
+ [
107
+ [
108
+ 0.3548048559834867
109
+ ]
110
+ ],
111
+ [
112
+ [
113
+ 0.27105549107349963
114
+ ]
115
+ ]
116
+ ],
117
+ "q50": [
118
+ [
119
+ [
120
+ 0.5763788236172425
121
+ ]
122
+ ],
123
+ [
124
+ [
125
+ 0.5327155834513468
126
+ ]
127
+ ],
128
+ [
129
+ [
130
+ 0.48903387051069475
131
+ ]
132
+ ]
133
+ ],
134
+ "q90": [
135
+ [
136
+ [
137
+ 0.752934972106522
138
+ ]
139
+ ],
140
+ [
141
+ [
142
+ 0.6880672902308267
143
+ ]
144
+ ],
145
+ [
146
+ [
147
+ 0.6208822543172496
148
+ ]
149
+ ]
150
+ ],
151
+ "q99": [
152
+ [
153
+ [
154
+ 0.7878534591967343
155
+ ]
156
+ ],
157
+ [
158
+ [
159
+ 0.7309064303265345
160
+ ]
161
+ ],
162
+ [
163
+ [
164
+ 0.6949545352957096
165
+ ]
166
+ ]
167
+ ]
168
+ },
169
+ "observation.images.wrist_image": {
170
+ "min": [
171
+ [
172
+ [
173
+ 0.0
174
+ ]
175
+ ],
176
+ [
177
+ [
178
+ 0.0
179
+ ]
180
+ ],
181
+ [
182
+ [
183
+ 0.0
184
+ ]
185
+ ]
186
+ ],
187
+ "max": [
188
+ [
189
+ [
190
+ 1.0
191
+ ]
192
+ ],
193
+ [
194
+ [
195
+ 1.0
196
+ ]
197
+ ],
198
+ [
199
+ [
200
+ 1.0
201
+ ]
202
+ ]
203
+ ],
204
+ "mean": [
205
+ [
206
+ [
207
+ 0.5916322109927509
208
+ ]
209
+ ],
210
+ [
211
+ [
212
+ 0.534439166068293
213
+ ]
214
+ ],
215
+ [
216
+ [
217
+ 0.4752197202980305
218
+ ]
219
+ ]
220
+ ],
221
+ "std": [
222
+ [
223
+ [
224
+ 0.025923648086762403
225
+ ]
226
+ ],
227
+ [
228
+ [
229
+ 0.026521139585646968
230
+ ]
231
+ ],
232
+ [
233
+ [
234
+ 0.03338285372448509
235
+ ]
236
+ ]
237
+ ],
238
+ "count": [
239
+ 37912
240
+ ],
241
+ "q01": [
242
+ [
243
+ [
244
+ 0.06152575978820971
245
+ ]
246
+ ],
247
+ [
248
+ [
249
+ 0.05909590704190847
250
+ ]
251
+ ],
252
+ [
253
+ [
254
+ 0.0516897406064225
255
+ ]
256
+ ]
257
+ ],
258
+ "q10": [
259
+ [
260
+ [
261
+ 0.18780954288962132
262
+ ]
263
+ ],
264
+ [
265
+ [
266
+ 0.18815108399527786
267
+ ]
268
+ ],
269
+ [
270
+ [
271
+ 0.17944534931291906
272
+ ]
273
+ ]
274
+ ],
275
+ "q50": [
276
+ [
277
+ [
278
+ 0.7126266579172164
279
+ ]
280
+ ],
281
+ [
282
+ [
283
+ 0.6406999389233642
284
+ ]
285
+ ],
286
+ [
287
+ [
288
+ 0.5662896578919809
289
+ ]
290
+ ]
291
+ ],
292
+ "q90": [
293
+ [
294
+ [
295
+ 0.7753744232458472
296
+ ]
297
+ ],
298
+ [
299
+ [
300
+ 0.7079467945393821
301
+ ]
302
+ ],
303
+ [
304
+ [
305
+ 0.6390325655923946
306
+ ]
307
+ ]
308
+ ],
309
+ "q99": [
310
+ [
311
+ [
312
+ 0.8243606480386086
313
+ ]
314
+ ],
315
+ [
316
+ [
317
+ 0.7675141532462598
318
+ ]
319
+ ],
320
+ [
321
+ [
322
+ 0.7487936296667783
323
+ ]
324
+ ]
325
+ ]
326
+ }
327
+ },
328
+ "new_global_image_stats": {
329
+ "observation.images.image": {
330
+ "count": [
331
+ 123
332
+ ],
333
+ "mean": [
334
+ [
335
+ [
336
+ 0.5600752857414403
337
+ ]
338
+ ],
339
+ [
340
+ [
341
+ 0.5203577120376701
342
+ ]
343
+ ],
344
+ [
345
+ [
346
+ 0.4768471317543627
347
+ ]
348
+ ]
349
+ ],
350
+ "std": [
351
+ [
352
+ [
353
+ 0.16554352479006743
354
+ ]
355
+ ],
356
+ [
357
+ [
358
+ 0.146233931474151
359
+ ]
360
+ ],
361
+ [
362
+ [
363
+ 0.13259858327658017
364
+ ]
365
+ ]
366
+ ],
367
+ "min": [
368
+ [
369
+ [
370
+ 0.00784313725490196
371
+ ]
372
+ ],
373
+ [
374
+ [
375
+ 0.011764705882352941
376
+ ]
377
+ ],
378
+ [
379
+ [
380
+ 0.00784313725490196
381
+ ]
382
+ ]
383
+ ],
384
+ "max": [
385
+ [
386
+ [
387
+ 1.0
388
+ ]
389
+ ],
390
+ [
391
+ [
392
+ 1.0
393
+ ]
394
+ ],
395
+ [
396
+ [
397
+ 1.0
398
+ ]
399
+ ]
400
+ ],
401
+ "q01": [
402
+ [
403
+ [
404
+ 0.09411764705882353
405
+ ]
406
+ ],
407
+ [
408
+ [
409
+ 0.09803921568627451
410
+ ]
411
+ ],
412
+ [
413
+ [
414
+ 0.09019607843137255
415
+ ]
416
+ ]
417
+ ],
418
+ "q10": [
419
+ [
420
+ [
421
+ 0.40784313725490196
422
+ ]
423
+ ],
424
+ [
425
+ [
426
+ 0.3568627450980392
427
+ ]
428
+ ],
429
+ [
430
+ [
431
+ 0.27450980392156865
432
+ ]
433
+ ]
434
+ ],
435
+ "q50": [
436
+ [
437
+ [
438
+ 0.5882352941176471
439
+ ]
440
+ ],
441
+ [
442
+ [
443
+ 0.5411764705882353
444
+ ]
445
+ ],
446
+ [
447
+ [
448
+ 0.4980392156862745
449
+ ]
450
+ ]
451
+ ],
452
+ "q90": [
453
+ [
454
+ [
455
+ 0.7529411764705882
456
+ ]
457
+ ],
458
+ [
459
+ [
460
+ 0.6862745098039216
461
+ ]
462
+ ],
463
+ [
464
+ [
465
+ 0.6196078431372549
466
+ ]
467
+ ]
468
+ ],
469
+ "q99": [
470
+ [
471
+ [
472
+ 0.788235294117647
473
+ ]
474
+ ],
475
+ [
476
+ [
477
+ 0.7254901960784313
478
+ ]
479
+ ],
480
+ [
481
+ [
482
+ 0.6901960784313725
483
+ ]
484
+ ]
485
+ ]
486
+ },
487
+ "observation.images.wrist_image": {
488
+ "count": [
489
+ 123
490
+ ],
491
+ "mean": [
492
+ [
493
+ [
494
+ 0.5939303470649884
495
+ ]
496
+ ],
497
+ [
498
+ [
499
+ 0.5384182735852376
500
+ ]
501
+ ],
502
+ [
503
+ [
504
+ 0.48487998248476855
505
+ ]
506
+ ]
507
+ ],
508
+ "std": [
509
+ [
510
+ [
511
+ 0.23704162843118068
512
+ ]
513
+ ],
514
+ [
515
+ [
516
+ 0.21186236737316416
517
+ ]
518
+ ],
519
+ [
520
+ [
521
+ 0.193684994527939
522
+ ]
523
+ ]
524
+ ],
525
+ "min": [
526
+ [
527
+ [
528
+ 0.00784313725490196
529
+ ]
530
+ ],
531
+ [
532
+ [
533
+ 0.00784313725490196
534
+ ]
535
+ ],
536
+ [
537
+ [
538
+ 0.00392156862745098
539
+ ]
540
+ ]
541
+ ],
542
+ "max": [
543
+ [
544
+ [
545
+ 1.0
546
+ ]
547
+ ],
548
+ [
549
+ [
550
+ 1.0
551
+ ]
552
+ ],
553
+ [
554
+ [
555
+ 1.0
556
+ ]
557
+ ]
558
+ ],
559
+ "q01": [
560
+ [
561
+ [
562
+ 0.058823529411764705
563
+ ]
564
+ ],
565
+ [
566
+ [
567
+ 0.058823529411764705
568
+ ]
569
+ ],
570
+ [
571
+ [
572
+ 0.050980392156862744
573
+ ]
574
+ ]
575
+ ],
576
+ "q10": [
577
+ [
578
+ [
579
+ 0.19215686274509805
580
+ ]
581
+ ],
582
+ [
583
+ [
584
+ 0.19215686274509805
585
+ ]
586
+ ],
587
+ [
588
+ [
589
+ 0.19215686274509805
590
+ ]
591
+ ]
592
+ ],
593
+ "q50": [
594
+ [
595
+ [
596
+ 0.7215686274509804
597
+ ]
598
+ ],
599
+ [
600
+ [
601
+ 0.6549019607843137
602
+ ]
603
+ ],
604
+ [
605
+ [
606
+ 0.5882352941176471
607
+ ]
608
+ ]
609
+ ],
610
+ "q90": [
611
+ [
612
+ [
613
+ 0.7764705882352941
614
+ ]
615
+ ],
616
+ [
617
+ [
618
+ 0.7098039215686275
619
+ ]
620
+ ],
621
+ [
622
+ [
623
+ 0.6431372549019608
624
+ ]
625
+ ]
626
+ ],
627
+ "q99": [
628
+ [
629
+ [
630
+ 0.807843137254902
631
+ ]
632
+ ],
633
+ [
634
+ [
635
+ 0.7411764705882353
636
+ ]
637
+ ],
638
+ [
639
+ [
640
+ 0.7607843137254902
641
+ ]
642
+ ]
643
+ ]
644
+ }
645
+ },
646
+ "samples": [
647
+ {
648
+ "camera": "observation.images.image",
649
+ "episode_index": 0,
650
+ "frame_indices": [
651
+ 3569,
652
+ 7139,
653
+ 10709
654
+ ]
655
+ },
656
+ {
657
+ "camera": "observation.images.wrist_image",
658
+ "episode_index": 0,
659
+ "frame_indices": [
660
+ 3569,
661
+ 7139,
662
+ 10709
663
+ ]
664
+ },
665
+ {
666
+ "camera": "observation.images.image",
667
+ "episode_index": 1,
668
+ "frame_indices": [
669
+ 1544,
670
+ 3089,
671
+ 4633
672
+ ]
673
+ },
674
+ {
675
+ "camera": "observation.images.wrist_image",
676
+ "episode_index": 1,
677
+ "frame_indices": [
678
+ 1544,
679
+ 3089,
680
+ 4633
681
+ ]
682
+ },
683
+ {
684
+ "camera": "observation.images.image",
685
+ "episode_index": 2,
686
+ "frame_indices": [
687
+ 677,
688
+ 1355,
689
+ 2032
690
+ ]
691
+ },
692
+ {
693
+ "camera": "observation.images.wrist_image",
694
+ "episode_index": 2,
695
+ "frame_indices": [
696
+ 677,
697
+ 1355,
698
+ 2032
699
+ ]
700
+ },
701
+ {
702
+ "camera": "observation.images.image",
703
+ "episode_index": 3,
704
+ "frame_indices": [
705
+ 4177,
706
+ 8355,
707
+ 12532
708
+ ]
709
+ },
710
+ {
711
+ "camera": "observation.images.wrist_image",
712
+ "episode_index": 3,
713
+ "frame_indices": [
714
+ 4177,
715
+ 8355,
716
+ 12532
717
+ ]
718
+ },
719
+ {
720
+ "camera": "observation.images.image",
721
+ "episode_index": 4,
722
+ "frame_indices": [
723
+ 2902,
724
+ 5805,
725
+ 8708
726
+ ]
727
+ },
728
+ {
729
+ "camera": "observation.images.wrist_image",
730
+ "episode_index": 4,
731
+ "frame_indices": [
732
+ 2902,
733
+ 5805,
734
+ 8708
735
+ ]
736
+ },
737
+ {
738
+ "camera": "observation.images.image",
739
+ "episode_index": 5,
740
+ "frame_indices": [
741
+ 4248,
742
+ 8496,
743
+ 12744
744
+ ]
745
+ },
746
+ {
747
+ "camera": "observation.images.wrist_image",
748
+ "episode_index": 5,
749
+ "frame_indices": [
750
+ 4248,
751
+ 8496,
752
+ 12744
753
+ ]
754
+ },
755
+ {
756
+ "camera": "observation.images.image",
757
+ "episode_index": 6,
758
+ "frame_indices": [
759
+ 3463,
760
+ 6926,
761
+ 10389
762
+ ]
763
+ },
764
+ {
765
+ "camera": "observation.images.wrist_image",
766
+ "episode_index": 6,
767
+ "frame_indices": [
768
+ 3463,
769
+ 6926,
770
+ 10389
771
+ ]
772
+ },
773
+ {
774
+ "camera": "observation.images.image",
775
+ "episode_index": 7,
776
+ "frame_indices": [
777
+ 3867,
778
+ 7735,
779
+ 11602
780
+ ]
781
+ },
782
+ {
783
+ "camera": "observation.images.wrist_image",
784
+ "episode_index": 7,
785
+ "frame_indices": [
786
+ 3867,
787
+ 7735,
788
+ 11602
789
+ ]
790
+ },
791
+ {
792
+ "camera": "observation.images.image",
793
+ "episode_index": 8,
794
+ "frame_indices": [
795
+ 547,
796
+ 1095,
797
+ 1642
798
+ ]
799
+ },
800
+ {
801
+ "camera": "observation.images.wrist_image",
802
+ "episode_index": 8,
803
+ "frame_indices": [
804
+ 547,
805
+ 1095,
806
+ 1642
807
+ ]
808
+ },
809
+ {
810
+ "camera": "observation.images.image",
811
+ "episode_index": 9,
812
+ "frame_indices": [
813
+ 1826,
814
+ 3653,
815
+ 5480
816
+ ]
817
+ },
818
+ {
819
+ "camera": "observation.images.wrist_image",
820
+ "episode_index": 9,
821
+ "frame_indices": [
822
+ 1826,
823
+ 3653,
824
+ 5480
825
+ ]
826
+ },
827
+ {
828
+ "camera": "observation.images.image",
829
+ "episode_index": 10,
830
+ "frame_indices": [
831
+ 2650,
832
+ 5301,
833
+ 7952
834
+ ]
835
+ },
836
+ {
837
+ "camera": "observation.images.wrist_image",
838
+ "episode_index": 10,
839
+ "frame_indices": [
840
+ 2650,
841
+ 5301,
842
+ 7952
843
+ ]
844
+ },
845
+ {
846
+ "camera": "observation.images.image",
847
+ "episode_index": 11,
848
+ "frame_indices": [
849
+ 3990,
850
+ 7980,
851
+ 11970
852
+ ]
853
+ },
854
+ {
855
+ "camera": "observation.images.wrist_image",
856
+ "episode_index": 11,
857
+ "frame_indices": [
858
+ 3990,
859
+ 7980,
860
+ 11970
861
+ ]
862
+ },
863
+ {
864
+ "camera": "observation.images.image",
865
+ "episode_index": 12,
866
+ "frame_indices": [
867
+ 893,
868
+ 1787,
869
+ 2680
870
+ ]
871
+ },
872
+ {
873
+ "camera": "observation.images.wrist_image",
874
+ "episode_index": 12,
875
+ "frame_indices": [
876
+ 893,
877
+ 1787,
878
+ 2680
879
+ ]
880
+ },
881
+ {
882
+ "camera": "observation.images.image",
883
+ "episode_index": 13,
884
+ "frame_indices": [
885
+ 4792,
886
+ 9584,
887
+ 14376
888
+ ]
889
+ },
890
+ {
891
+ "camera": "observation.images.wrist_image",
892
+ "episode_index": 13,
893
+ "frame_indices": [
894
+ 4792,
895
+ 9584,
896
+ 14376
897
+ ]
898
+ },
899
+ {
900
+ "camera": "observation.images.image",
901
+ "episode_index": 14,
902
+ "frame_indices": [
903
+ 2592,
904
+ 5185,
905
+ 7778
906
+ ]
907
+ },
908
+ {
909
+ "camera": "observation.images.wrist_image",
910
+ "episode_index": 14,
911
+ "frame_indices": [
912
+ 2592,
913
+ 5185,
914
+ 7778
915
+ ]
916
+ },
917
+ {
918
+ "camera": "observation.images.image",
919
+ "episode_index": 15,
920
+ "frame_indices": [
921
+ 1612,
922
+ 3225,
923
+ 4838
924
+ ]
925
+ },
926
+ {
927
+ "camera": "observation.images.wrist_image",
928
+ "episode_index": 15,
929
+ "frame_indices": [
930
+ 1612,
931
+ 3225,
932
+ 4838
933
+ ]
934
+ },
935
+ {
936
+ "camera": "observation.images.image",
937
+ "episode_index": 16,
938
+ "frame_indices": [
939
+ 992,
940
+ 1984,
941
+ 2976
942
+ ]
943
+ },
944
+ {
945
+ "camera": "observation.images.wrist_image",
946
+ "episode_index": 16,
947
+ "frame_indices": [
948
+ 992,
949
+ 1984,
950
+ 2976
951
+ ]
952
+ },
953
+ {
954
+ "camera": "observation.images.image",
955
+ "episode_index": 17,
956
+ "frame_indices": [
957
+ 2123,
958
+ 4247,
959
+ 6370
960
+ ]
961
+ },
962
+ {
963
+ "camera": "observation.images.wrist_image",
964
+ "episode_index": 17,
965
+ "frame_indices": [
966
+ 2123,
967
+ 4247,
968
+ 6370
969
+ ]
970
+ },
971
+ {
972
+ "camera": "observation.images.image",
973
+ "episode_index": 18,
974
+ "frame_indices": [
975
+ 327,
976
+ 655,
977
+ 982
978
+ ]
979
+ },
980
+ {
981
+ "camera": "observation.images.wrist_image",
982
+ "episode_index": 18,
983
+ "frame_indices": [
984
+ 327,
985
+ 655,
986
+ 982
987
+ ]
988
+ },
989
+ {
990
+ "camera": "observation.images.image",
991
+ "episode_index": 19,
992
+ "frame_indices": [
993
+ 147,
994
+ 295,
995
+ 443
996
+ ]
997
+ },
998
+ {
999
+ "camera": "observation.images.wrist_image",
1000
+ "episode_index": 19,
1001
+ "frame_indices": [
1002
+ 147,
1003
+ 295,
1004
+ 443
1005
+ ]
1006
+ },
1007
+ {
1008
+ "camera": "observation.images.image",
1009
+ "episode_index": 20,
1010
+ "frame_indices": [
1011
+ 2271,
1012
+ 4542,
1013
+ 6813
1014
+ ]
1015
+ },
1016
+ {
1017
+ "camera": "observation.images.wrist_image",
1018
+ "episode_index": 20,
1019
+ "frame_indices": [
1020
+ 2271,
1021
+ 4542,
1022
+ 6813
1023
+ ]
1024
+ },
1025
+ {
1026
+ "camera": "observation.images.image",
1027
+ "episode_index": 21,
1028
+ "frame_indices": [
1029
+ 651,
1030
+ 1303,
1031
+ 1955
1032
+ ]
1033
+ },
1034
+ {
1035
+ "camera": "observation.images.wrist_image",
1036
+ "episode_index": 21,
1037
+ "frame_indices": [
1038
+ 651,
1039
+ 1303,
1040
+ 1955
1041
+ ]
1042
+ },
1043
+ {
1044
+ "camera": "observation.images.image",
1045
+ "episode_index": 22,
1046
+ "frame_indices": [
1047
+ 338,
1048
+ 677,
1049
+ 1015
1050
+ ]
1051
+ },
1052
+ {
1053
+ "camera": "observation.images.wrist_image",
1054
+ "episode_index": 22,
1055
+ "frame_indices": [
1056
+ 338,
1057
+ 677,
1058
+ 1015
1059
+ ]
1060
+ },
1061
+ {
1062
+ "camera": "observation.images.image",
1063
+ "episode_index": 23,
1064
+ "frame_indices": [
1065
+ 1450,
1066
+ 2900,
1067
+ 4350
1068
+ ]
1069
+ },
1070
+ {
1071
+ "camera": "observation.images.wrist_image",
1072
+ "episode_index": 23,
1073
+ "frame_indices": [
1074
+ 1450,
1075
+ 2900,
1076
+ 4350
1077
+ ]
1078
+ },
1079
+ {
1080
+ "camera": "observation.images.image",
1081
+ "episode_index": 24,
1082
+ "frame_indices": [
1083
+ 1215,
1084
+ 2431,
1085
+ 3647
1086
+ ]
1087
+ },
1088
+ {
1089
+ "camera": "observation.images.wrist_image",
1090
+ "episode_index": 24,
1091
+ "frame_indices": [
1092
+ 1215,
1093
+ 2431,
1094
+ 3647
1095
+ ]
1096
+ },
1097
+ {
1098
+ "camera": "observation.images.image",
1099
+ "episode_index": 25,
1100
+ "frame_indices": [
1101
+ 809,
1102
+ 1618,
1103
+ 2427
1104
+ ]
1105
+ },
1106
+ {
1107
+ "camera": "observation.images.wrist_image",
1108
+ "episode_index": 25,
1109
+ "frame_indices": [
1110
+ 809,
1111
+ 1618,
1112
+ 2427
1113
+ ]
1114
+ },
1115
+ {
1116
+ "camera": "observation.images.image",
1117
+ "episode_index": 26,
1118
+ "frame_indices": [
1119
+ 2153,
1120
+ 4307,
1121
+ 6460
1122
+ ]
1123
+ },
1124
+ {
1125
+ "camera": "observation.images.wrist_image",
1126
+ "episode_index": 26,
1127
+ "frame_indices": [
1128
+ 2153,
1129
+ 4307,
1130
+ 6460
1131
+ ]
1132
+ },
1133
+ {
1134
+ "camera": "observation.images.image",
1135
+ "episode_index": 27,
1136
+ "frame_indices": [
1137
+ 1731,
1138
+ 3462,
1139
+ 5193
1140
+ ]
1141
+ },
1142
+ {
1143
+ "camera": "observation.images.wrist_image",
1144
+ "episode_index": 27,
1145
+ "frame_indices": [
1146
+ 1731,
1147
+ 3462,
1148
+ 5193
1149
+ ]
1150
+ },
1151
+ {
1152
+ "camera": "observation.images.image",
1153
+ "episode_index": 28,
1154
+ "frame_indices": [
1155
+ 1431,
1156
+ 2862,
1157
+ 4293
1158
+ ]
1159
+ },
1160
+ {
1161
+ "camera": "observation.images.wrist_image",
1162
+ "episode_index": 28,
1163
+ "frame_indices": [
1164
+ 1431,
1165
+ 2862,
1166
+ 4293
1167
+ ]
1168
+ },
1169
+ {
1170
+ "camera": "observation.images.image",
1171
+ "episode_index": 29,
1172
+ "frame_indices": [
1173
+ 1672,
1174
+ 3345,
1175
+ 5018
1176
+ ]
1177
+ },
1178
+ {
1179
+ "camera": "observation.images.wrist_image",
1180
+ "episode_index": 29,
1181
+ "frame_indices": [
1182
+ 1672,
1183
+ 3345,
1184
+ 5018
1185
+ ]
1186
+ },
1187
+ {
1188
+ "camera": "observation.images.image",
1189
+ "episode_index": 30,
1190
+ "frame_indices": [
1191
+ 7340,
1192
+ 14681,
1193
+ 22021
1194
+ ]
1195
+ },
1196
+ {
1197
+ "camera": "observation.images.wrist_image",
1198
+ "episode_index": 30,
1199
+ "frame_indices": [
1200
+ 7340,
1201
+ 14681,
1202
+ 22021
1203
+ ]
1204
+ },
1205
+ {
1206
+ "camera": "observation.images.image",
1207
+ "episode_index": 31,
1208
+ "frame_indices": [
1209
+ 3426,
1210
+ 6853,
1211
+ 10280
1212
+ ]
1213
+ },
1214
+ {
1215
+ "camera": "observation.images.wrist_image",
1216
+ "episode_index": 31,
1217
+ "frame_indices": [
1218
+ 3426,
1219
+ 6853,
1220
+ 10280
1221
+ ]
1222
+ },
1223
+ {
1224
+ "camera": "observation.images.image",
1225
+ "episode_index": 32,
1226
+ "frame_indices": [
1227
+ 6983,
1228
+ 13967,
1229
+ 20950
1230
+ ]
1231
+ },
1232
+ {
1233
+ "camera": "observation.images.wrist_image",
1234
+ "episode_index": 32,
1235
+ "frame_indices": [
1236
+ 6983,
1237
+ 13967,
1238
+ 20950
1239
+ ]
1240
+ },
1241
+ {
1242
+ "camera": "observation.images.image",
1243
+ "episode_index": 33,
1244
+ "frame_indices": [
1245
+ 742,
1246
+ 1484,
1247
+ 2226
1248
+ ]
1249
+ },
1250
+ {
1251
+ "camera": "observation.images.wrist_image",
1252
+ "episode_index": 33,
1253
+ "frame_indices": [
1254
+ 742,
1255
+ 1484,
1256
+ 2226
1257
+ ]
1258
+ },
1259
+ {
1260
+ "camera": "observation.images.image",
1261
+ "episode_index": 34,
1262
+ "frame_indices": [
1263
+ 2788,
1264
+ 5577,
1265
+ 8366
1266
+ ]
1267
+ },
1268
+ {
1269
+ "camera": "observation.images.wrist_image",
1270
+ "episode_index": 34,
1271
+ "frame_indices": [
1272
+ 2788,
1273
+ 5577,
1274
+ 8366
1275
+ ]
1276
+ },
1277
+ {
1278
+ "camera": "observation.images.image",
1279
+ "episode_index": 35,
1280
+ "frame_indices": [
1281
+ 1689,
1282
+ 3379,
1283
+ 5068
1284
+ ]
1285
+ },
1286
+ {
1287
+ "camera": "observation.images.wrist_image",
1288
+ "episode_index": 35,
1289
+ "frame_indices": [
1290
+ 1689,
1291
+ 3379,
1292
+ 5068
1293
+ ]
1294
+ },
1295
+ {
1296
+ "camera": "observation.images.image",
1297
+ "episode_index": 36,
1298
+ "frame_indices": [
1299
+ 1495,
1300
+ 2990,
1301
+ 4485
1302
+ ]
1303
+ },
1304
+ {
1305
+ "camera": "observation.images.wrist_image",
1306
+ "episode_index": 36,
1307
+ "frame_indices": [
1308
+ 1495,
1309
+ 2990,
1310
+ 4485
1311
+ ]
1312
+ },
1313
+ {
1314
+ "camera": "observation.images.image",
1315
+ "episode_index": 37,
1316
+ "frame_indices": [
1317
+ 3828,
1318
+ 7657,
1319
+ 11485
1320
+ ]
1321
+ },
1322
+ {
1323
+ "camera": "observation.images.wrist_image",
1324
+ "episode_index": 37,
1325
+ "frame_indices": [
1326
+ 3828,
1327
+ 7657,
1328
+ 11485
1329
+ ]
1330
+ },
1331
+ {
1332
+ "camera": "observation.images.image",
1333
+ "episode_index": 38,
1334
+ "frame_indices": [
1335
+ 2092,
1336
+ 4184,
1337
+ 6276
1338
+ ]
1339
+ },
1340
+ {
1341
+ "camera": "observation.images.wrist_image",
1342
+ "episode_index": 38,
1343
+ "frame_indices": [
1344
+ 2092,
1345
+ 4184,
1346
+ 6276
1347
+ ]
1348
+ },
1349
+ {
1350
+ "camera": "observation.images.image",
1351
+ "episode_index": 39,
1352
+ "frame_indices": [
1353
+ 7552,
1354
+ 15104,
1355
+ 22656
1356
+ ]
1357
+ },
1358
+ {
1359
+ "camera": "observation.images.wrist_image",
1360
+ "episode_index": 39,
1361
+ "frame_indices": [
1362
+ 7552,
1363
+ 15104,
1364
+ 22656
1365
+ ]
1366
+ },
1367
+ {
1368
+ "camera": "observation.images.image",
1369
+ "episode_index": 40,
1370
+ "frame_indices": [
1371
+ 509,
1372
+ 1019,
1373
+ 1529
1374
+ ]
1375
+ },
1376
+ {
1377
+ "camera": "observation.images.wrist_image",
1378
+ "episode_index": 40,
1379
+ "frame_indices": [
1380
+ 509,
1381
+ 1019,
1382
+ 1529
1383
+ ]
1384
+ }
1385
+ ],
1386
+ "wall_seconds": 15.528291940689087
1387
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/evaluation_tool_caps.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "lh_desk_organizer": 460,
3
+ "lh_split_calibration": 340,
4
+ "lh_shim_relay": 600
5
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/framework_codex.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared launcher for robot frameworks using a native Codex backend.
2
+
3
+ The external integration contract is Session.first_message(), Session.tool_specs(),
4
+ and Session.call(name, arguments). This launcher owns isolation, model configuration,
5
+ pins, trajectory collection and audits; framework plugins own their native loop.
6
+ Based on the validated RPent launcher; RPent's historical launcher remains frozen.
7
+ """
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import time
14
+
15
+ from . import contract as C
16
+ from . import pins
17
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
18
+ gateway_env, new_run_dir, proxy_env, snapshot_tree)
19
+ from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
20
+ request_fingerprint, toml_str)
21
+ from .fakeapi import FakeResponses
22
+ from .trajectory import TrajWriter
23
+
24
+ ROOT = C.ROOT
25
+ JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework"
26
+ BASE_PATH = "/usr/bin:/bin"
27
+ MCP_SERVER = "lff"
28
+ MCP_TOOLS = ["robot", "shell", "view_images"]
29
+ TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"}
30
+
31
+
32
+
33
+ def tree_sha256(root, skip=TREE_SKIP):
34
+ """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
35
+ h = hashlib.sha256()
36
+ for dp, dn, fn in os.walk(root):
37
+ dn[:] = sorted(d for d in dn if d not in skip)
38
+ for f in sorted(fn):
39
+ if f.endswith(".pyc"):
40
+ continue
41
+ p = os.path.join(dp, f)
42
+ rel = os.path.relpath(p, root)
43
+ if os.path.islink(p):
44
+ h.update(f"L {rel} {os.readlink(p)}\n".encode())
45
+ else:
46
+ h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
47
+ return h.hexdigest()
48
+
49
+
50
+ def runtime_info(home):
51
+ """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
52
+ src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
53
+ for d in (src, venv):
54
+ if not os.path.isdir(d):
55
+ raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)")
56
+
57
+ def git(*a):
58
+ r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
59
+ return r.stdout.strip() if r.returncode == 0 else None
60
+ commit = git("rev-parse", "HEAD")
61
+ patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
62
+ untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
63
+ return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
64
+ untracked=sorted(u for u in untracked if "__pycache__" not in u),
65
+ tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
66
+
67
+
68
+ def jail_runtime_copy(home, tree):
69
+ """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not)."""
70
+ dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}")
71
+ stamp = os.path.join(dst, ".tree_sha256")
72
+ if os.path.exists(stamp) and open(stamp).read().strip() == tree:
73
+ return dst
74
+ os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True)
75
+ tmp = dst + ".tmp-" + os.urandom(3).hex()
76
+ shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
77
+ ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
78
+ shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
79
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
80
+ got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
81
+ ).hexdigest()
82
+ if got != tree:
83
+ shutil.rmtree(tmp, ignore_errors=True)
84
+ raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
85
+ for dp, dn, fn in os.walk(tmp):
86
+ os.chmod(dp, 0o755)
87
+ for f in fn:
88
+ p = os.path.join(dp, f)
89
+ if not os.path.islink(p):
90
+ os.chmod(p, os.stat(p).st_mode | 0o444)
91
+ with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
92
+ f.write(tree)
93
+ if os.path.exists(dst):
94
+ shutil.rmtree(dst)
95
+ os.rename(tmp, dst)
96
+ return dst
97
+
98
+
99
+ def codex_overrides(effort, catalog_path):
100
+ """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
101
+ overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process)."""
102
+ return (["model_reasoning_effort=" + toml_str(effort),
103
+ "include_permissions_instructions=false", "include_environment_context=false",
104
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
105
+ "skills.bundled.enabled=false", 'web_search="disabled"',
106
+ f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
107
+ f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
108
+ f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
109
+ f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
110
+ "model_catalog_json=" + toml_str(catalog_path)]
111
+ + [f"features.{f}=false" for f in DISABLE])
112
+
113
+
114
+ def _items(stream_path):
115
+ """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL)."""
116
+ out = []
117
+ if not os.path.exists(stream_path):
118
+ return out
119
+ for line in open(stream_path, encoding="utf-8", errors="replace"):
120
+ try:
121
+ out.append(json.loads(line))
122
+ except ValueError:
123
+ continue
124
+ return out
125
+
126
+
127
+ def _item_of(ev):
128
+ it = (ev.get("payload") or {}).get("item") or {}
129
+ return it.get("root", it) if isinstance(it, dict) else {}
130
+
131
+
132
+ class RobotFrameworkCodex(HarnessAdapter):
133
+ name = "framework_codex"
134
+ runtime_home = "/nonexistent"
135
+ runtime_module = "lff_integration.run"
136
+ default_steps = 500
137
+ uses_mcp = False
138
+ uses_gateway = True
139
+ can_resume = False
140
+ clean_dirs = ("home", "codex_home", "tmp", "out")
141
+ clean_allowed = {"codex_home": (CATALOG_FILE,)}
142
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
143
+ capabilities = dict(
144
+ only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
145
+ "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers "
146
+ "no tool of its own (no file tools, no finish)"),
147
+ images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, "
148
+ "JPEG with its own MIME type"),
149
+ non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the "
150
+ "run; no preloaded or cross-episode framework memory"),
151
+ pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in "
152
+ "harness.json; pin per version and tree"),
153
+ machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session "
154
+ "(codex.out.stream.jsonl) + robot framework run.json"),
155
+ tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"),
156
+ model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
157
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not "
158
+ "constructed"),
159
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
160
+ web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
161
+ host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
162
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
163
+ subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
164
+ background_execution=Cap("absent", "preflight", "no background tool in the request"),
165
+ )
166
+
167
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
168
+ jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500,
169
+ home=None, provider=None, auth_home=None):
170
+ """Common controlled Codex SDK launcher.
171
+
172
+ The plugin entrypoint interprets its declared loop options. For SenseNova,
173
+ max_turns is the upstream SDK-step limit, not a provider-response count.
174
+ Robot commands, simulation time and tool budgets are always server-owned.
175
+ """
176
+ if auth not in ("apikey", "chatgpt"):
177
+ raise ValueError("framework_codex auth must be apikey or chatgpt")
178
+ if catalog not in CATALOGS:
179
+ raise ValueError(f"catalog must be one of {CATALOGS}")
180
+ self.auth, self.catalog = auth, catalog
181
+ self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog)
182
+ self.api_env = self._auth_manager.api_env
183
+ self.base_url = self._auth_manager.base_url
184
+ self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
185
+ self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
186
+ self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
187
+ int(max_turns)
188
+ self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home
189
+ self.proxy = proxy_env()
190
+ self._version = None
191
+ self._runtime = None
192
+ self.runtime_dir = self.home
193
+ if jail:
194
+ from .jail import HarnessJail
195
+ self.jail = HarnessJail(codex_bin(), proc="static")
196
+
197
+ # ------------------------------------------------------------------------------------------------ identity
198
+ def runtime(self):
199
+ if self._runtime is None:
200
+ self._runtime = runtime_info(self.home)
201
+ if self.jail is not None:
202
+ self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
203
+ return self._runtime
204
+
205
+ def version(self):
206
+ if self._version is None:
207
+ b = codex_bin()
208
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
209
+ CODEX_HOME="/nonexistent"),
210
+ capture_output=True, text=True, timeout=60)
211
+ v = (out.stdout.strip().split() or ["?"])[-1]
212
+ rt = self.runtime()
213
+ self._version = dict(version=v, binary=binary_info(b),
214
+ framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
215
+ tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
216
+ return self._version
217
+
218
+ def pin_key(self, ep):
219
+ v = self.version()
220
+ mode = "" if self.auth == "apikey" else "-chatgpt"
221
+ name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}"
222
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
223
+
224
+ def anchor_pin_key(self, ep):
225
+ """The main table's codex pin for the same model / effort (apikey, same catalog)."""
226
+ v = self.version()
227
+ name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}")
228
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
229
+
230
+ def auth_info(self):
231
+ if self.auth == "chatgpt":
232
+ return self._auth_manager.auth_info()
233
+ return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
234
+ "OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
235
+
236
+ def config_info(self):
237
+ return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
238
+ max_turns=self.max_turns, framework=self.version()["framework"])
239
+
240
+ # ------------------------------------------------------------------------------------------------ prepare
241
+ def _state_dirs(self, hexname=None):
242
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
243
+ os.makedirs(root, exist_ok=True)
244
+ state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
245
+ for k in ("home", "codex_home", "tmp", "out"):
246
+ os.makedirs(state[k], exist_ok=True)
247
+ return state
248
+
249
+ def _install_catalog(self, codex_home, ep):
250
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
251
+ path = os.path.join(codex_home, CATALOG_FILE)
252
+ with open(path, "w") as f:
253
+ json.dump(cat, f)
254
+ return path, C.sha256_file(path), os.path.relpath(src, ROOT)
255
+
256
+ def argv(self, ep, out_dir, sessions=None, preflight=False):
257
+ py = os.path.join(self.runtime_dir, "venv", "bin", "python")
258
+ return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
259
+ "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
260
+ "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
261
+ + (["--no-continue"] if preflight else [])
262
+
263
+ def env(self, state, ep, base_url, work):
264
+ e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
265
+ CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
266
+ CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER,
267
+ FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
268
+ ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
269
+ FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
270
+ PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
271
+ if self.auth == "chatgpt":
272
+ # The native API provider declares env_key. Codex app-server still requires that
273
+ # variable even with requires_openai_auth=true, so select a separate provider
274
+ # with no env_key. Do not inject a dummy key or modify the upstream runtime.
275
+ provider_id = "lffsubscription"
276
+ overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"])
277
+ overrides += ["model_provider=" + toml_str(provider_id),
278
+ f"model_providers.{provider_id}.name=" + toml_str(provider_id),
279
+ f"model_providers.{provider_id}.wire_api=\"responses\"",
280
+ f"model_providers.{provider_id}.base_url=" + toml_str(base_url),
281
+ f"model_providers.{provider_id}.requires_openai_auth=true"]
282
+ e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides)
283
+ e.update(self.proxy)
284
+ if self.api_env.get("OPENAI_API_KEY"):
285
+ e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
286
+ return e
287
+
288
+ def prepare(self, ep, first_message, reuse_state=None):
289
+ self.version()
290
+ work = new_run_dir("/tmp/lffrun")
291
+ state = reuse_state or self._state_dirs(os.path.basename(work))
292
+ if self.jail is not None:
293
+ self.jail.stderr_dir = ep.log_dir
294
+ if not reuse_state and os.listdir(state["codex_home"]):
295
+ raise HarnessRefused("CODEX_HOME is not empty")
296
+ cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
297
+ return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
298
+ run_dir=work, state_dirs=state, first_message=first_message,
299
+ stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"),
300
+ stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"),
301
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
302
+ catalog=self.catalog, code_mode=False)),
303
+ timeout_s=self.timeout_s)
304
+
305
+ def config_sha256(self, spec, ep):
306
+ argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<FRAMEWORK>")
307
+ for a in spec.argv]
308
+ hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH",
309
+ "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
310
+ env = {k: v for k, v in spec.env.items() if k not in hidden}
311
+ env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace(
312
+ spec.state_dirs["codex_home"], "<CODEX_HOME>")
313
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
314
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
315
+ framework_tree_sha256=self.version()["framework"]["tree_sha256"]))
316
+
317
+ # ------------------------------------------------------------------------------------------------ launch
318
+ def launch(self, spec, ep, skip_preflight=False):
319
+ """harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
320
+ self._auth_manager._install_auth(spec.state_dirs["codex_home"])
321
+ spec.env.update(gateway_env(ep.log_dir))
322
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
323
+
324
+ def cleanup(self, spec):
325
+ self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", ""))
326
+ super().cleanup(spec)
327
+
328
+ def preflight(self, spec, ep, record_dir=None):
329
+ """The same framework process, one session, against a local fake Responses server that answers with text
330
+ only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
331
+ sandbox, robot framework's prefix + our first message) against the pins."""
332
+ t0 = time.time()
333
+ fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
334
+ pre = self._state_dirs()
335
+ try:
336
+ self._auth_manager._install_auth(pre["codex_home"])
337
+ self._install_catalog(pre["codex_home"], ep)
338
+ env = self.env(pre, ep, fake.base_url, spec.cwd)
339
+ if self.auth == "apikey":
340
+ env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
341
+ env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
342
+ argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
343
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
344
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
345
+ reqs = fake.model_requests()
346
+ if not reqs:
347
+ # Native planners may record failures only in run.json, with empty stdout/stderr.
348
+ record = os.path.join(pre["out"], "run.json")
349
+ detail = ""
350
+ if os.path.isfile(record):
351
+ with open(record) as f:
352
+ failed_run = json.load(f)
353
+ detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error"))
354
+ raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
355
+ f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}")
356
+ body = reqs[0][1]
357
+ fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
358
+ problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
359
+ users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
360
+ and it.get("role") == "user" for c in it.get("content") or []]
361
+ prefix = None
362
+ if len(users) != 1 or not users[0].endswith(spec.first_message):
363
+ problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
364
+ else:
365
+ prefix = users[0][:-len(spec.first_message)]
366
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
367
+ if effort != ep.effort:
368
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
369
+ if fp["params"].get("model") != ep.model:
370
+ problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
371
+ if os.listdir(spec.cwd):
372
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
373
+ mid_sha = C.sha256_json(fp)
374
+ full = dict(middle=fp, framework_prefix=prefix)
375
+ fp_sha = C.sha256_json(full)
376
+ anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
377
+ out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
378
+ framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
379
+ framework_prefix_chars=len(prefix) if prefix is not None else None,
380
+ developer_chars=fp["developer_chars"], n_requests=len(reqs),
381
+ top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
382
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
383
+ dt_s=round(time.time() - t0, 1), problems=problems,
384
+ anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
385
+ if anchor is None:
386
+ out["anchor_status"] = "no main-table pin for this model / effort"
387
+ elif anchor["fingerprint_sha256"] != mid_sha:
388
+ problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
389
+ f"({anchor['key']}): the middle layer is not the main table's")
390
+ else:
391
+ out["anchor_status"] = "match"
392
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
393
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
394
+ out["fingerprint"] = full
395
+ if problems:
396
+ raise HarnessRefused("preflight: " + "; ".join(problems))
397
+ if pin is None:
398
+ if not self.allow_unpinned:
399
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
400
+ f"with --write-pins after the self-check passes)")
401
+ out["pin_status"] = "unpinned (allowed)"
402
+ elif pin["fingerprint_sha256"] != fp_sha:
403
+ raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
404
+ f"({pin['key']})")
405
+ else:
406
+ out["pin_status"] = "match"
407
+ return out
408
+ finally:
409
+ fake.stop()
410
+ self._auth_manager._sync_auth_back(pre["codex_home"])
411
+ shutil.rmtree(pre["state"], ignore_errors=True)
412
+
413
+ # ------------------------------------------------------------------------------------------------ collect
414
+ def collect(self, h):
415
+ spec, ep = h.spec, h.ep
416
+ dst = os.path.join(ep.log_dir, "framework")
417
+ if os.path.isdir(spec.state_dirs["out"]):
418
+ shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
419
+ run = {}
420
+ if os.path.exists(os.path.join(dst, "run.json")):
421
+ run = json.load(open(os.path.join(dst, "run.json")))
422
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
423
+ usage = dict(input=0, cached=0, output=0, reasoning=0)
424
+ items, threads, errors = [], [], []
425
+ for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
426
+ else []:
427
+ last = None
428
+ for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
429
+ m = ev.get("method") or ev.get("type")
430
+ p = ev.get("payload") or {}
431
+ if m == "thread/tokenUsage/updated":
432
+ last = (p.get("token_usage") or {}).get("total") or last
433
+ if p.get("thread_id") and p["thread_id"] not in threads:
434
+ threads.append(p["thread_id"])
435
+ elif m in ("error", "fatal", "timeout"):
436
+ errors.append(ev)
437
+ elif m == "item/completed":
438
+ it = _item_of(ev)
439
+ t = it.get("type")
440
+ items.append(t)
441
+ if t == "agentMessage":
442
+ tw.add_step("agent", message=it.get("text", ""))
443
+ elif t == "reasoning":
444
+ tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
445
+ elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
446
+ name = it.get("tool") or t
447
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
448
+ native_name=f"{it.get('server', '')}.{name}",
449
+ item_type=t, arguments=it.get("arguments"),
450
+ session=sdir)])
451
+ res = it.get("result") or {}
452
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
453
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
454
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
455
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
456
+ if last:
457
+ usage["input"] += last.get("input_tokens") or 0
458
+ usage["cached"] += last.get("cached_input_tokens") or 0
459
+ usage["output"] += last.get("output_tokens") or 0
460
+ usage["reasoning"] += last.get("reasoning_output_tokens") or 0
461
+ # Framework close-out uses the same counted gateway shell, outside
462
+ # the model stream. Keep it visible in trajectories and tool totals.
463
+ session_record = next((s for s in run.get("sessions", [])
464
+ if sdir == f"session_{s['number']:03d}"), {})
465
+ handoff = session_record.get("handoff") or {}
466
+ if handoff:
467
+ call_id = f"framework-handoff-{sdir}"
468
+ tw.add_step("framework", tool_calls=[dict(
469
+ tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
470
+ item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
471
+ tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
472
+ if c.get("type") == "text"))
473
+ v = self.version()
474
+ tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl",
475
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
476
+ framework=v["framework"]), tools=EXPECTED_TOP_GENERIC)
477
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
478
+ run={k: run.get(k) for k in ("stop", "finished",
479
+ "attempts_failed", "tool_calls")},
480
+ sessions=len(run.get("sessions") or [])),
481
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
482
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
483
+ tw.write()
484
+ h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
485
+ return tw
486
+
487
+ # ------------------------------------------------------------------------------------------------ audit
488
+ def audit(self, h):
489
+ spec, ep = h.spec, h.ep
490
+ v, notes = [], []
491
+ items = h.info.get("items") or []
492
+ bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
493
+ "plan", "hookPrompt")})
494
+ if bad:
495
+ v.append(f"items other than messages / reasoning / MCP calls: {bad}")
496
+ residual = []
497
+ tw = h.info.get("traj")
498
+ for st in (tw.steps if tw else []):
499
+ for tc in st["tool_calls"]:
500
+ if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
501
+ continue
502
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
503
+ residual.append(tc["function_name"])
504
+ else:
505
+ v.append(f"unexpected tool call {tc['native_name']}")
506
+ if residual:
507
+ notes.append(f"residual MCP-resource tool calls (empty): {residual}")
508
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
509
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
510
+ run = h.info.get("run") or {}
511
+ nsess = len(run.get("sessions") or [])
512
+ if len(h.info.get("threads") or []) > max(1, nsess):
513
+ v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions")
514
+ if nsess > 1:
515
+ notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)")
516
+ if run.get("stop") not in (None, "episode over"):
517
+ notes.append(f"robot framework stopped: {run.get('stop')}")
518
+ left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
519
+ work=snapshot_tree(spec.cwd))
520
+ if left["work"]:
521
+ v.append(f"files in the work dir: {left['work']}")
522
+ foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
523
+ and not any(t in f for t in (h.info.get("threads") or []))]
524
+ if foreign:
525
+ v.append(f"session files other than this run's threads: {foreign}")
526
+ gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
527
+ faces = set()
528
+ if os.path.exists(gt):
529
+ for line in open(gt):
530
+ try:
531
+ d = json.loads(line)
532
+ except ValueError:
533
+ continue
534
+ if d.get("ev") == "tool" and d.get("face"):
535
+ faces.add(d["face"])
536
+ if faces - {self.name}:
537
+ v.append(f"gateway calls from other access paths: {sorted(faces)}")
538
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
539
+ item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
540
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
541
+ json.dump(out, f, indent=1)
542
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
3
+ "fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
4
+ "written": "2026-10-20 02:16:14",
5
+ "summary": {
6
+ "system_chars": 26736,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-sonnet-5-5"
14
+ }
15
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
4
+ "written": "2026-10-21 04:17:19",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6.1-sol",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }