forked from PeiranLi0930/Plugin-GBT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaper.txt
More file actions
1926 lines (1602 loc) · 129 KB
/
Copy pathpaper.txt
File metadata and controls
1926 lines (1602 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\newcommand{\gbt}{\textsc{GBT}}
\icmltitlerunning{Traversal-as-Policy: Log-Distilled Gated Behavior Trees as Externalized, Verifiable Policies for Safe, Robust, and Efficient Agents}
\begin{abstract}
Autonomous LLM agents fail because long-horizon policy remains implicit in model weights and transcripts, while safety is retrofitted post hoc. We propose \emph{Traversal-as-Policy}: distill sandboxed OpenHands execution logs into a single executable \textbf{Gated Behavior Tree} (\gbt{}) and treat tree traversal---rather than unconstrained generation---as the control policy whenever a task is in coverage. Each node encodes a \emph{state-conditioned action macro} mined and merge-checked from successful trajectories; macros implicated by unsafe traces attach deterministic \emph{pre-execution gates} over structured tool context and bounded history, updated under experience-grounded monotonicity so previously rejected unsafe contexts cannot be re-admitted. At runtime, a lightweight traverser matches the base model's intent to child macros, executes one macro at a time under global and node-local gating, and when stalled performs risk-aware shortest-path recovery to a feasible success leaf; the visited path forms a compact spine memory that replaces transcript replay. Evaluated in a unified OpenHands sandbox on \textit{15+} software, web, reasoning, and safety/security benchmarks, \gbt{} improves success while driving violations toward zero and reducing cost. On SWE-bench Verified (Protocol A, 500 issues), \gbt{}-SE raises success from 34.6\% to 73.6\%, reduces violations from 2.8\% to 0.2\%, and cuts token/character usage from 208k/820k to 126k/490k; with the same distilled tree, 8B executors more than double success on SWE-bench Verified (14.0\%\,$\rightarrow$\,58.8\%) and WebArena (9.1\%\,$\rightarrow$\,37.3\%).
\end{abstract}
\section{Introduction}
Autonomous language-model agents are increasingly asked to \emph{act}: patch repositories, navigate websites, run commands, and chain tools over long horizons. Yet most deployments still execute an \emph{implicit} policy -- a brittle mixture of model weights, prompt templates, and ad-hoc transcripts -- while safety is retrofitted post hoc. The policy remains buried in weights and logs, making agents hard to debug, difficult to certify, and expensive to improve.
Reasoning and safety advances have not produced an explicit, reusable control object. Deliberative search and reflection-style memories (Tree-of-Thoughts; Reflexion; Meta-Policy Reflexion) still decide and remember through free-form generation, treating logs as transient context rather than compiling them into an executable artifact \citep{treeofthought,reflexion,mpr}. Guardrailing attaches runtime validators or ``guardian'' agents \citep{guardagent,aworld,policyasprompt}, but their safety knowledge is typically human-specified (rules, prompts, or code), unscalable, and blind to long-tail, context-dependent failures that only appear in operational traces.
We argue what is missing is a \emph{first-class, model-external policy artifact} distilled from execution that unifies: (i) robust long-horizon control, (ii) deterministic safety \emph{before} high-risk actions, and (iii) a compact state representation that replaces transcript replay. This motivates a concrete question: \emph{Can we distill massive execution logs into a single executable artifact that simultaneously governs behavior, enforces safety, and compresses memory -- avoiding weight updates?}
We answer yes with \emph{Traversal-as-Policy}. From sandboxed OpenHands trajectories \citep{wang2024openhands}, we distill a single executable \textbf{Gated Behavior Tree} (\gbt{}), and treat \emph{tree traversal} -- rather than unconstrained generation -- as the control policy whenever a task is in coverage. Each node is a \emph{state-conditioned action macro}: a contiguous segment of primitive tool calls that stays within a local sub-action region and realizes a coherent intent. Successful trajectories contribute macro paths that are merge-checked into a single tree under a signature-based discipline designed to prevent semantic aliasing where safety matters. Coverage is explicit: when semantic matching is confident, \gbt{} governs long-horizon control; otherwise the traverser abstains and the episode is labeled \texttt{covered}=0.
Safety enters \gbt{} through \emph{experience-grounded pre-execution gates}. We designate high-risk primitives (writes/deletes, process spawns, network sends, sensitive reads). For each attempted high-risk primitive we construct a structured context \texttt{ctx} directly from sandbox state (primitive type, parameters such as file paths or domains, process metadata, and a bounded history). Gates are deterministic checks over these structured fields -- they do not consult LLM summaries -- so safety cannot be bypassed by prompt hacking or summarization choices. Unsafe traces are deterministically replayed and shrunk to minimal violating windows; the extracted contexts synthesize global or node-local gates. Gates update under \emph{experience-grounded monotonicity}: once a structured context is rejected, it stays rejected by all future gate libraries, preventing silent safety regression.
At runtime, a lightweight \textbf{GBT-Traverser} makes \gbt{} operational. The base model proposes the next step at the level of intent; the traverser matches this proposal to a child macro and advances only along that transition, executing one macro at a time under both global and node-local gating. Traversal arrests long-horizon drift by constraining choices to successors grounded in prior successes; when stalled or repeatedly blocked, the traverser performs risk-aware shortest-path recovery to a feasible success leaf. \gbt{} also serves as hierarchical memory: the traverser maintains a compact \emph{task spine} (visited macros) as persistent long-term state, replacing transcript replay; safety-critical fields bypass summarization and flow directly into \texttt{ctx}. Offline, a failure-driven self-evolution loop upgrades \gbt{}-Basic to \gbt{}-SE by locally repairing \texttt{covered}=1 failures via analogical successes and updated selection statistics, while preserving safety by forbidding gate relaxation and regression-testing historical successes and historical unsafe corpora.
Experiments evaluate whether \gbt{} behaves as a first-class external policy artifact under strictly controlled OpenHands execution \citep{wang2024openhands}. On SWE-bench Verified~\cite{jimenez2023swe} (Protocol A, 500 issues), \gbt{}-SE raises success from 34.6\% to 73.6\% at 86.0\% coverage, reduces violations from 2.8\% to 0.2\%, eliminates unsafe success (1.2\%$\rightarrow$0.0\%), and cuts Tok/Chars (thousands) from 208/820 to 126/490; global guardrail alone yields 38.8\% success with 0.8\% violations. On WebArena~\cite{zhou2023webarena} (Protocol A, 812 tasks), \gbt{}-SE raises success from 19.7\% to 66.9\% at 78.0\% coverage, reduces violations from 3.4\% to 0.2\%, eliminates unsafe success (1.0\%$\rightarrow$0.0\%), and cuts Tok/Chars from 94/360 to 52/205; global guardrail alone leaves success essentially unchanged (19.3\%). On GPQA~\cite{rein2024gpqa} (Protocol A, 448; browsing disabled), \gbt{}-SE raises accuracy from 58.7\% to 87.3\% at 73.0\% coverage while keeping violations at 0.2\% and unsafe success at 0.0\%, and reduces Tok/Chars from 22/86 to 15/58. After distillation, the same tree enables small executors: \texttt{Qwen3-VL-8B-Thinking}~\cite{bai2025qwen3vltechnicalreport} rises from 14.0\% to 58.8\% on SWE-bench Verified and from 9.1\% to 37.3\% on WebArena, demonstrating decoupling of offline reasoning from online execution.
\textbf{Contributions:}
\vspace{-.2em}
\begin{itemize}[leftmargin=*, itemsep=0.1em, topsep=0.1em, parsep=0pt, partopsep=0pt]
\item \textbf{Traversal-as-Policy:} we externalize long-horizon agent control as executable tree traversal in a log-distilled \textbf{Gated Behavior Tree} (\gbt{}), yielding a persistent policy artifact independent of model weights.
\item \textbf{Experience-grounded deterministic safety:} we compile unsafe traces into \emph{pre-execution} gates over structured contexts and update them under monotonicity so logged unsafe contexts cannot be re-admitted.
\item \textbf{Unified evidence:} on \textit{15+} OpenHands benchmarks, \gbt{} simultaneously improves success, reduces violations and unsafe success toward zero, cuts inference cost, and enables strong execution by small models.
\end{itemize}
\section{Gated Behavior Tree (\gbt)}
\label{sec:method}
We instantiate \emph{Traversal-as-Policy} by distilling sandboxed execution logs into a single \emph{Gated Behavior Tree} (\gbt{}), then treating \emph{tree traversal}---rather than unconstrained generation---as the agent's long-horizon control policy whenever the task is within coverage. The pipeline is \emph{training-free}: we never update model weights. Frozen LLMs (temperature $0$) are used only offline to summarize chosen macro segments for semantic matching, synthesize deterministic predicates, and diagnose failures; their outputs are compiled into inspectable artifacts (tree structure, gate predicates, and preconditions). Throughout all phases (data collection, offline distillation, and online deployment), the same primitive-level guardrail vets each high-risk tool call.
\textbf{Pipeline (3-line overview):}
\vspace{-0.2em}
\begin{itemize}[leftmargin=*, itemsep=0.1em, topsep=0.1em, parsep=0pt, partopsep=0pt]
\item \textbf{Offline:} logs $\rightarrow$ primitives $\rightarrow$ macros $\rightarrow$ merge into \emph{GBT-Basic} + attach gates from unsafe windows.
\item \textbf{Offline:} covered failures $\rightarrow$ local repair via analogical successes $\rightarrow$ \emph{GBT-SE} (safety preserved under monotone invariants).
\item \textbf{Online:} traversal policy + primitive gating + recovery search + spine memory (coverage-scoped claims).
\end{itemize}
\textbf{What is a macro?}
A \emph{state-conditioned action macro} is a of primitive tool calls that (i) stays within a local sub-action region of the environment and (ii) realizes a coherent intent. For example, in software tasks a macro might be ``inspect failing test and open the referenced file,'' while in web tasks it might be ``fill remaining form fields and submit.'' The key separation is \emph{macro-level control} (what step to do next) versus \emph{primitive-level execution} (the concrete tool calls), with safety enforced at the primitive level.
\textbf{Three coupled safety/control objects.}
Safety and control are coupled through: (i) a sandbox-level \emph{normative} safety specification $\mathcal{S}_{\text{spec}}$ defined by monitors and benchmark checkers; (ii) an \emph{executable} bounded-history approximation $\mathcal{S}_{\text{sys}}(t)$ using pre-execution gates over structured contexts; and (iii) a log-distilled tree whose nodes encode reusable macros and may carry \emph{node-local} gates. When \gbt{} is in coverage, the executed long-horizon behavior is the realized traversal path, while \emph{every} high-risk primitive is still mediated by deterministic, pre-execution gate checks.
\subsection{Safety Objects and Experience-Grounded Gates}
\label{sec:safety}
\vspace{-.2em}
\textbf{Sandboxed trajectories and structured contexts.}
A trajectory $\tau$ is labeled \texttt{unsafe} iff at least one primitive tool call violates $\mathcal{S}_{\text{spec}}$ in the OpenHands sandbox~\citep{wang2024openhands}. For high-risk primitives we construct a structured context $\texttt{ctx}\in\mathcal{C}$ directly from sandbox state: primitive type, parameters (paths, domains, process metadata, etc.), and a bounded history of recent high-risk primitives along the same macro. \emph{All safety decisions depend only on these structured fields.} LLM summaries are never read by gates or preconditions (details and examples in App.~\ref{app:guardrail}).
\textbf{Gate interface and executable subset.}
Each gate has the common interface
$$
g:\ \texttt{ctx} \mapsto (\texttt{ok}, \texttt{msg}) \in \{\texttt{true},\texttt{false}\}\times\texttt{String}.
$$
Let $\mathcal{G}(t)=\mathcal{G}_{\text{global}}(t)\cup\mathcal{G}_{\text{node}}(t)$ denote global plus node-local gates at time $t$. The executable safety subset is
\[
\mathcal{S}_{\text{sys}}(t)
=
\left\{\texttt{ctx}\in\mathcal{C}:\exists g\in\mathcal{G}(t),\ g(\texttt{ctx}).\texttt{ok}=\texttt{false}\right\},
\]
a conservative approximation to the portion of $\mathcal{S}_{\text{spec}}$ expressible over bounded-history structured contexts. \emph{Consequently, no summarization or prompting choice can bypass safety:} summaries can influence how a macro is realized, but cannot change $\texttt{ctx}$ nor the gate outcomes computed from it.
\textbf{Experience-grounded monotonicity.}
For every gate $g$ we maintain an unsafe corpus $\mathcal{D}_{\text{unsafe}}(g)$ (contexts extracted from observed violations) and a benign corpus $\mathcal{D}_{\text{benign}}(g)$ (representative safe contexts for the same primitive family). Any update from $g^{\text{old}}$ to $g^{\text{new}}$ must satisfy:
\[
\begin{aligned}
\forall\, \texttt{ctx}\in\mathcal{D}_{\text{unsafe}}(g):\quad
&g^{\text{old}}(\texttt{ctx}).\texttt{ok}=\texttt{false}\\
&\Rightarrow\;
g^{\text{new}}(\texttt{ctx}).\texttt{ok}=\texttt{false}.
\end{aligned}
\]
and control false positives on benign contexts:
\[
\frac{\left|\left\{\texttt{ctx}\in\mathcal{D}_{\text{benign}}(g): g^{\text{new}}(\texttt{ctx}).\texttt{ok}=\texttt{false}\right\}\right|}{|\mathcal{D}_{\text{benign}}(g)|}
\le \epsilon_{\text{benign}}.
\]
We give concrete corpora construction and gate update procedures in App.~\ref{app:guardrail}.
\textbf{Design invariant 1 (Experience-grounded monotonicity).}
Once a structured context is recorded as unsafe and rejected by any gate, it stays rejected by all future gate libraries.\\
\emph{Consequence:} the system can only \emph{expand} $\mathcal{S}_{\text{sys}}(t)$ on observed violations; it cannot re-admit logged unsafe contexts.
\subsection{Global Guardrail}
\label{sec:guardrail}
\vspace{-.2em}
We designate a set of high-risk primitives $\mathcal{T}_{\text{hard}}$ (writes/deletes, process spawns, network sends, and reads of resources matching sensitive patterns). For any candidate primitive $a\in\mathcal{T}_{\text{hard}}$ with structured context $\texttt{ctx}$, the global guardrail evaluates a fixed but extensible library $\mathcal{G}_{\text{global}}$ consisting of:
(i) \emph{RuleGates}, deterministic code predicates over structured fields and bounded history; and
(ii) \emph{ContentGates}, deterministic calls (temperature $0$) to a fixed guard classifier over payload-bearing actions, post-processed into a Boolean flag and message.
The global decision is
\[
\texttt{HardGateOK}(a,\texttt{ctx})
=
\bigwedge_{g\in\mathcal{G}_{\text{global}}} g(\texttt{ctx}).\texttt{ok}.
\]
Unsafe trajectories that still occur under the current guardrail expose violations of $\mathcal{S}_{\text{spec}}$ not yet captured by $\mathcal{S}_{\text{sys}}(t)$. We deterministically replay and shrink such traces to minimal violating primitive windows, record their structured contexts into unsafe corpora, and synthesize new global or node-local gates under Design invariant~1 (App.~\ref{app:guardrail}).
\subsection{From Logs to \texorpdfstring{GBT-Basic}{GBT-Basic}}
\label{sec:gbt-basic}
\vspace{-.2em}
\textbf{Macro abstraction (behavior paths).}
A frozen \emph{Behavior Path Extractor} $E$ maps a trajectory $\tau$ to a short macro path
\[
p=(v_0,\dots,v_K)=E(\tau),
\]
where each macro $v_k$ is a state-conditioned action macro. Macro boundaries are anchored by observable environment deltas (file diffs, domain changes, process starts) and tool-usage heuristics; LLM calls, when used, only summarize already-segmented macro spans into short descriptions for matching. Because traversal assumes macros have stable semantics, we explicitly test abstraction stability on unsafe or $\mathcal{T}_{\text{hard}}$-touching traces and exclude abstract-unstable trajectories from tree construction and gate derivation (App.~\ref{app:behavior-extractor}).
\textbf{Unsafe windows $\rightarrow$ node-local gates.}
For an unsafe trajectory, we shrink it (via sandbox replay) to a minimal unsafe primitive window $W$, map it to a minimal covering macro subsequence $U$ in $E(\tau)$, and treat each macro $v\in U$ as participating in the unsafe pattern. We attach to such nodes a small set of node-local gates $\mathcal{G}(v)$ with the same interface $g:\texttt{ctx}\mapsto(\texttt{ok},\texttt{msg})$, synthesized from observed violating contexts and constrained by the same monotonicity and benign-regression rules as global gates (App.~\ref{app:guardrail}).
\textbf{Tree construction and merge discipline.}
\gbt{} is a single rooted tree whose first layer consists of task-family roots that reduce branching; a frozen router assigns each task to a family when confident (App.~\ref{app:family-classifier}). Each macro node $v$ stores: a natural-language \texttt{description} for semantic matching, coarse tags, a discrete risk level, and a behavior signature $\sigma(v)=(\sigma_{\text{disc}}(v),\sigma_{\text{cont}}(v))$ computed purely from logs. When inserting a successful path, we reuse an existing child only when signatures and descriptions agree (exact match on $\sigma_{\text{disc}}$, cosine similarity thresholds on $\sigma_{\text{cont}}$ and embedded descriptions). To prevent semantic aliasing where safety matters most, merges into nodes that already carry node-local gates are disallowed. High-traffic ungated nodes are audited for aliasing and split when needed; acyclicity is enforced as a hard invariant (App.~\ref{app:tree-construction}). The resulting \emph{GBT-Basic} encodes reusable macros, explicit success leaves, and log-grounded node-local gates, while remaining coupled to the global guardrail that protects all high-risk primitives everywhere.
\textbf{Design invariant 2 (Tree edits do not weaken enforcement).}
Gates depend only on structured $\texttt{ctx}$ and bounded history, not on node descriptions or topology; tree edits never delete/relax gates, and merges into gated nodes are disallowed.\\
\emph{Consequence:} changing the tree can alter behavior availability and selection frequency, but cannot turn any previously rejected unsafe context into an allowed one.
\subsection{Self-Evolution Under Safety Invariants: \texorpdfstring{GBT-SE}{GBT-SE}}
\label{sec:gbt-se}
\vspace{-.2em}
Many failures do not violate $\mathcal{S}_{\text{spec}}$; they are dominated by control and context drift. We run a failure-driven self-evolution loop that improves behavior \emph{locally} while preserving all accumulated safety invariants.
\textbf{Coverage predicate.}
Self-evolution operates only on episodes where \gbt{} genuinely serves as the policy skeleton (\texttt{covered}$=1$): the task is routed to a single family with high confidence, macro transitions match existing children above a minimum similarity threshold, and traversal never invokes safe exploration (full definition in App.~\ref{app:self-evolution}). Outside coverage (\texttt{covered}$=0$), we do \emph{not} claim long-horizon control from \gbt{}; we only claim primitive-level safety from the guardrail.
\enlargethispage{1\baselineskip} % 试 1 或 2 行
\textbf{Local repair via analogical successes.}
Given a failed covered path $p^{\text{fail}}=(v_0,\dots,v_K)$, a frozen reasoning model diagnoses failure on the \emph{task spine} (macro descriptions plus coarse environment summaries), backtracking to the earliest node $v^\star$ where choosing a different successor could plausibly avert failure. To repair $v^\star$, we retrieve analogical success leaves by embedding task descriptions, identify a matched success path whose corresponding node best aligns with $v^\star$, and import its successor macro. If an existing child of $v^\star$ already matches sufficiently, we reuse it; otherwise we add a new child whose description, behavior signature, and risk metadata mirror the imported successor. Each child $u$ of $v^\star$ maintains a selection score
\begin{equation}
\begin{aligned}
\texttt{score}(u;\texttt{ctx})
&=
\alpha\cdot \mathrm{sim}_\text{text}\big(\text{proposal},\text{desc}(u)\big)\\
&\quad+\;
\beta\cdot \mathrm{success\_rate}\big(u;\mathrm{cluster}(\texttt{ctx})\big),
\end{aligned}
\label{eq:score}
\end{equation}
combining semantic match to the base model’s proposal with empirical success statistics for similar structured contexts (definitions and maintenance in App.~\ref{app:self-evolution}).
\textbf{Safety preservation by construction.}
Self-evolution may add children, update local selection statistics, and add new gates for newly observed unsafe patterns; it may \emph{not} delete or weaken any gate. Any new child inherits the full node-local gate set of its parent before additional gates are allowed. Proposed edits are regression-tested by replaying historical successes through $v^\star$ (requiring success not to degrade beyond a small tolerance) and replaying historical unsafe episodes that previously triggered gates (verifying they remain blocked), as detailed in App.~\ref{app:self-evolution}.
\textbf{Design invariant 3 (Safety under self-evolution).}
Under the allowed edits and regression tests, self-evolution cannot re-admit previously rejected unsafe contexts.\\
\emph{Consequence:} \emph{GBT-SE} expands coverage/robustness while preserving Design invariants~1--2.
\subsection{Online Traversal-as-Policy}
\label{sec:online}
\vspace{-.2em}
At deployment, a \emph{GBT-Traverser} runs alongside a base model $M_{\text{base}}$. It routes tasks to a family subtree when confident, constrains macro choices by traversal, enforces primitive-level gating, triggers recovery when stalled, and uses the tree as hierarchical memory. The global guardrail remains active on every $a\in\mathcal{T}_{\text{hard}}$ regardless of coverage.
\textbf{Routing, coverage boundary, and abstention.}
Given a task description $x$, a frozen router predicts $p(f\mid x)$ over task families (App.~\ref{app:family-classifier}). If $\max_f p(f\mid x)$ is below a threshold, the traverser \emph{abstains} from traversal control and the episode is \texttt{covered}$=0$. Otherwise, traversal proceeds within the selected family subtree. We make the claim boundary explicit:
\[
\begin{aligned}
\texttt{covered}=1:&\quad
\text{\parbox[t]{0.6\linewidth}{\gbt\ determines long-horizon policy by traversal.}}\\
\texttt{covered}=0:&\quad
\text{\parbox[t]{0.6\linewidth}{we only claim primitive-level safety from the guardrail.}}
\end{aligned}
\]
\textbf{Plan--match--advance and safe exploration.}
At node $v_t$, $M_{\text{base}}$ proposes the next macro as a short description. The traverser embeds this proposal and matches it against children of $v_t$, yielding similarity $s$. Two thresholds $\theta_{\text{high}}>\theta_{\text{low}}$ define three regimes: high-confidence advance ($s\ge\theta_{\text{high}}$), fragile advance ($\theta_{\text{low}}\le s<\theta_{\text{high}}$, queued for offline inspection), and \emph{safe exploration} ($s<\theta_{\text{low}}$), where traversal temporarily abstains from steering long-horizon control around $v_t$ for a small budget. Any episode invoking safe exploration is marked \texttt{covered}$=0$.
\textbf{Primitive-level enforcement during macro realization.}
Once a child $v'$ is selected (by traversal or recovery), the traverser instructs $M_{\text{base}}$ to realize only this macro. For each executed high-risk primitive $a\in\mathcal{T}_{\text{hard}}$ with structured context $\texttt{ctx}_{\text{tool}}$, we require
\begingroup
\setlength{\abovedisplayskip}{4pt}
\setlength{\belowdisplayskip}{4pt}
\setlength{\abovedisplayshortskip}{2pt}
\setlength{\belowdisplayshortskip}{2pt}
\[
\begin{aligned}
\texttt{GateOK}(v',\texttt{ctx})
&=
\bigwedge_{g\in\mathcal{G}(v')} g(\texttt{ctx}).\texttt{ok},\\
\texttt{Allowed}(a,\texttt{ctx}_{\text{tool}},v')
&=
\texttt{HardGateOK}(a,\texttt{ctx}_{\text{tool}})\\
&\quad\land\;
\texttt{GateOK}(v',\texttt{ctx}_{\text{tool}}).
\end{aligned}
\]
\endgroup
If \texttt{Allowed} is false, the primitive is blocked and $M_{\text{base}}$ is reinvoked with gate messages. Because gates read only structured $\texttt{ctx}$, summarization cannot override or route around these checks.
\textbf{Recovery via risk-aware shortest paths.}
When the agent stalls or repeatedly trips gates, control inverts: \gbt{} proposes recovery macros and $M_{\text{base}}$ executes them. We retrieve candidate success leaves similar to the task and filter them by a coarse environment signature match. Each node carries a deterministic precondition $\texttt{pre}(v,\texttt{env})$ over a structured environment summary; preconditions are conservative feasibility filters and never override gates (App.~\ref{app:recovery}). Restricted to feasible nodes and matched leaves, we run Dijkstra on the family subtree with edge cost
{%
\setlength{\abovedisplayskip}{6pt}
\setlength{\belowdisplayskip}{6pt}
\setlength{\abovedisplayshortskip}{4pt}
\setlength{\belowdisplayshortskip}{4pt}
\begin{equation}
c(v\to u)=1+\lambda\cdot \mathrm{risk\_level}(u),
\label{eq:cost}
\end{equation}
}%
to obtain a minimum-cost path to a reachable success leaf within a depth limit, then execute the path one macro at a time under the same primitive-level gating.
\textbf{Hierarchical memory (spine).}
The traverser maintains the \emph{task spine} $(v_0,\dots,v_t)$ as persistent long-horizon state. The base model receives the task summary, macro descriptions on the spine, and a short node-local context summary distilled from $\texttt{env\_context}(v_t)$; full transcripts are not replayed. Structured safety-critical fields (paths, domains, process identifiers) bypass summarization and flow directly into $\texttt{ctx}$ and $\texttt{env}$ for gates and preconditions (App.~\ref{app:memory}).
\subsection{Policy as an External Artifact}
\label{sec:policy-artifact}
\vspace{-.2em}
\gbt{} is a persistent policy object distilled from logs: it routes tasks, constrains macro choices through traversal, enforces pre-execution gates, orchestrates recovery, and compresses long-horizon state into a spine. Because behavior and the bounded-history executable subset $\mathcal{S}_{\text{sys}}(t)$ are externalized into \gbt{} and the gate library, we decouple offline reasoning capacity from online execution: large models operate offline to build and refine these artifacts (without training), while at deployment a smaller $M_{\text{base}}$ executes one macro at a time under deterministic, primitive-level gate supervision along paths grounded in logs and preserved under regression-tested self-evolution.
\section{Experiments}
\label{sec:experiments}
\begin{table*}[!t]
\centering
\footnotesize
\caption{\textbf{SWE-bench Verified (Protocol A, 500 issues):} SR (\%), coverage (Cov, \%), violation rate (Viol, \%), unsafe success (USucc, \%), and efficiency (Tok/Chars, thousands). Wilson 95\% CIs are computed over per-instance majority-vote outcomes from three runs.}
\label{tab:swe_main_refined}
\setlength{\tabcolsep}{4pt}
% \renewcommand{\arraystretch}{0.95}
\begin{tabularx}{\textwidth}{@{}>{\raggedright\arraybackslash}Xcccccc@{}}
\toprule
\textbf{System} &
\textbf{SR} &
\textbf{Cov} &
\textbf{Viol} &
\textbf{USucc} &
\textbf{Tok} &
\textbf{Chars} \\
\midrule
OpenHands CodeAct (\texttt{gpt-4o}, native) &
34.6 {\scriptsize[30.6,38.9]}\,{\scriptsize(173/500)} &
-- &
2.8 {\scriptsize[1.7,4.6]}\,{\scriptsize(14/500)} &
1.2 {\scriptsize[0.6,2.6]}\,{\scriptsize(6/500)} &
208 & 820 \\
\quad +Global guardrail only &
38.8 {\scriptsize[34.6,43.2]}\,{\scriptsize(194/500)} &
-- &
0.8 {\scriptsize[0.3,2.0]}\,{\scriptsize(4/500)} &
0.2 {\scriptsize[0.0,1.1]}\,{\scriptsize(1/500)} &
196 & 770 \\
\quad +GBT-Basic &
50.2 {\scriptsize[45.8,54.6]}\,{\scriptsize(251/500)} &
84.4 {\scriptsize(422/500)} &
0.4 {\scriptsize[0.1,1.4]}\,{\scriptsize(2/500)} &
0.2 {\scriptsize[0.0,1.1]}\,{\scriptsize(1/500)} &
148 & 570 \\
\quad +GBT-SE &
\textbf{73.6} {\scriptsize[69.6, 77.3]}\,{\scriptsize(368/500)} &
\textbf{86.0} {\scriptsize(430/500)} &
\textbf{0.2} {\scriptsize[0.0,1.1]}\,{\scriptsize(1/500)} &
\textbf{0.0} {\scriptsize[0.0,0.8]}\,{\scriptsize(0/500)} &
\textbf{126} & \textbf{490} \\
\bottomrule
\end{tabularx}
\end{table*}
\begin{table*}[!t]
\centering
\footnotesize
\caption{\textbf{WebArena (Protocol A, 812 tasks):} success, coverage, safety, and efficiency under strictly controlled OpenHands execution.}
\label{tab:web_main_refined}
\setlength{\tabcolsep}{4pt}
% \renewcommand{\arraystretch}{0.95}
\begin{tabularx}{\textwidth}{@{}>{\raggedright\arraybackslash}Xcccccc@{}}
\toprule
\textbf{System} &
\textbf{SR} &
\textbf{Cov} &
\textbf{Viol} &
\textbf{USucc} &
\textbf{Tok} &
\textbf{Chars} \\
\midrule
OpenHands CodeAct (\texttt{gpt-4o}, native) &
19.7 {\scriptsize[17.1,22.6]}\,{\scriptsize(160/812)} &
-- &
3.4 {\scriptsize[2.4,4.9]}\,{\scriptsize(28/812)} &
1.0 {\scriptsize[0.5,1.9]}\,{\scriptsize(8/812)} &
94 & 360 \\
\quad +Global guardrail only &
19.3 {\scriptsize[16.8,22.2]}\,{\scriptsize(157/812)} &
-- &
0.9 {\scriptsize[0.4,1.8]}\,{\scriptsize(7/812)} &
0.2 {\scriptsize[0.1,0.9]}\,{\scriptsize(2/812)} &
88 & 335 \\
\quad +GBT-Basic &
53.0 {\scriptsize[49.5, 56.4]}\,{\scriptsize(430/812)} &
76.5 {\scriptsize(621/812)} &
0.4 {\scriptsize[0.1,1.1]}\,{\scriptsize(3/812)} &
0.1 {\scriptsize[0.0,0.7]}\,{\scriptsize(1/812)} &
60 & 230 \\
\quad +GBT-SE &
\textbf{66.9} {\scriptsize[63.6, 70.0]}\,{\scriptsize(543/812)} &
\textbf{78.0} {\scriptsize(633/812)} &
\textbf{0.2} {\scriptsize[0.1,0.9]}\,{\scriptsize(2/812)} &
\textbf{0.0} {\scriptsize[0.0,0.5]}\,{\scriptsize(0/812)} &
\textbf{52} & \textbf{205} \\
\bottomrule
\end{tabularx}
\end{table*}
\begin{table*}[!t]
\centering
\footnotesize
\caption{\textbf{GPQA (Protocol A, 448 questions):} accuracy (Acc, \%), coverage (Cov, \%), and safety (Viol/USucc) under OpenHands monitors/checkers. External web browsing is disabled.}
\label{tab:gpqa_main_refined}
\setlength{\tabcolsep}{4pt}
% \renewcommand{\arraystretch}{0.95}
\begin{tabularx}{\textwidth}{@{}>{\raggedright\arraybackslash}Xcccccc@{}}
\toprule
\textbf{System} &
\textbf{Acc} &
\textbf{Cov} &
\textbf{Viol} &
\textbf{USucc} &
\textbf{Tok} &
\textbf{Chars} \\
\midrule
Zero-shot prompting (\texttt{gpt-4o}) &
53.6 {\scriptsize[48.9,58.1]}\,{\scriptsize(240/448)} &
-- & -- & -- &
-- & -- \\
OpenHands CodeActAgent (\texttt{gpt-4o}) &
58.7 {\scriptsize[54.1,63.2]}\,{\scriptsize(263/448)} &
-- &
1.6 {\scriptsize[0.8,3.2]}\,{\scriptsize(7/448)} &
0.4 {\scriptsize[0.1,1.6]}\,{\scriptsize(2/448)} &
22 & 86 \\
\quad +Global guardrail only &
59.2 {\scriptsize[54.6,63.7]}\,{\scriptsize(265/448)} &
-- &
0.4 {\scriptsize[0.1,1.6]}\,{\scriptsize(2/448)} &
0.2 {\scriptsize[0.0,1.3]}\,{\scriptsize(1/448)} &
21 & 82 \\
\quad +GBT-Basic &
78.8 {\scriptsize[74.8, 82.3]}\,{\scriptsize(353/448)} &
71.9 {\scriptsize(322/448)} &
0.2 {\scriptsize[0.0,1.3]}\,{\scriptsize(1/448)} &
0.0 {\scriptsize[0.0,0.9]}\,{\scriptsize(0/448)} &
16 & 62 \\
\quad +GBT-SE &
\textbf{87.3} {\scriptsize[83.9, 90.0]}\,{\scriptsize(391/448)} &
\textbf{73.0} {\scriptsize(327/448)} &
\textbf{0.2} {\scriptsize[0.0,1.3]}\,{\scriptsize(1/448)} &
\textbf{0.0} {\scriptsize[0.0,0.9]}\,{\scriptsize(0/448)} &
\textbf{15} & \textbf{58} \\
\bottomrule
\end{tabularx}
\end{table*}
We evaluate whether \gbt{} behaves as a \emph{first-class, model-external policy artifact}: (i) \textbf{when covered}, traversal (plus recovery) determines the executed long-horizon macro skeleton; (ii) \textbf{before execution}, every high-risk primitive is deterministically gated from structured \texttt{ctx} (global and node-local); (iii) \textbf{under stalls}, recovery emits short, feasible macro sequences; and (iv) \textbf{under long horizons}, spine memory replaces transcript replay to reduce drift and cost. All comparisons run inside the unified OpenHands runtime~\citep{wang2024openhands}; additional setup details, diagnostics, and mechanism ablations appear in App.~\ref{app:exp_details}--App.~\ref{app:exp_ablation}.
\subsection{Reproducible Runtime and Integration Discipline}
\label{sec:exp:runtime_main}
\vspace{-.2em}
\textbf{Unified sandbox, unified accounting.}
All runs execute in OpenHands~\citep{wang2024openhands}, which fixes the tool API, monitor/checker interface, logging schema, and cost accounting. This removes a dominant confound in agent evaluation: differences in environment instrumentation or safety enforcement cannot explain the results.
\textbf{\gbt-Traverser is a wrapper (no weight or planner edits).}
\textbf{GBT-Traverser} wraps the agent loop: it routes episodes to a task-family subtree, constrains macro choice by traversal (and, when triggered, recovery), enforces \emph{pre-execution} safety on every $a\in\mathcal{T}_{\text{hard}}$ via global and node-local gates, and maintains spine memory (Sec.~\ref{sec:method}; App.~\ref{app:memory}). It does \emph{not} update model weights and does \emph{not} modify any framework’s internal planner. Thus, differences between rows isolate exactly the Method’s levers: traversal/recovery/spine and node-local gates on top of the same base agent and the same sandbox monitors.
\subsection{Benchmarks, Protocols, and Metrics}
\label{sec:exp:setup}
\vspace{-.2em}
\textbf{Benchmarks.}
We evaluate on 15+ OpenHands-integrated benchmarks spanning software engineering, web interaction, tool-assisted reasoning, and adversarial safety/security. We foreground three execution-based pillars:
\textbf{SWE-bench Verified} (500 issues)~\cite{jimenez2023swe}, \textbf{WebArena} (812 tasks)~\cite{zhou2023webarena}, and \textbf{GPQA} (448 questions)~\citep{rein2024gpqa}. For GPQA we disable external web browsing and allow only local tools (e.g., Python) for deterministic computation. Safety/security is evaluated on \textbf{Agent-SafetyBench}\citep{agentsafetybench}, \textbf{AgentHarm (public)}\ \citep{andriushchenko2024agentharm}, and \textbf{Agent Security Bench (ASB)}~\citep{agentsecuritybench}.
\textbf{Leakage controls and claim boundary.}
We report three complementary protocols (App.~\ref{app:exp_protocols}). Our primary results use \textbf{Protocol A} (cross-benchmark distillation with benchmark-level hold-out): no trajectories from the evaluation benchmark are used for tree construction or self-evolution. We make the Method’s claim boundary explicit by reporting \textbf{Coverage} (Cov): when \texttt{covered}$=1$, traversal is the executed long-horizon policy skeleton; when \texttt{covered}$=0$, we do \emph{not} claim long-horizon control from \gbt{} and only claim primitive-level safety from the guardrail (Sec.\ \ref{sec:method}; App.~\ref{app:self-evolution}).
\textbf{Reporting.} For execution benchmarks we report success rate (SR) or accuracy (Acc), coverage (Cov), violation rate (Viol; any $\mathcal{S}_{\text{spec}}$ violation), unsafe success (USucc; success with any violation), and efficiency (Tok/Chars; thousands). Each instance is run \textbf{three times} at temperature $0$; outcomes are majority-voted and Wilson 95\% CIs are computed over per-instance binary outcomes (details in App.~\ref{app:exp_metrics}).
% ============================================================
\subsection{Main Results on the Three Pillars (Protocol A)}
\label{sec:exp:main}
\vspace{-.2em}
Across pillars, the pattern is consistent: \textbf{global guardrails alone} largely buy safety with limited utility gain, while \textbf{adding \gbt{} traversal} produces a step-change in success and cost by externalizing long-horizon control into a reusable macro skeleton under deterministic pre-execution enforcement.
\subsubsection{SWE-bench Verified: large utility gains without safety trade-offs}
\label{sec:exp:main_swe}
\vspace{-.2em}
Table~\ref{tab:swe_main_refined} isolates three mechanisms. \emph{Primitive gating alone} (\textbf{+Global guardrail only}) cuts violations from 2.8\% to 0.8\% and unsafe success from 1.2\% to 0.2\%, but improves SR only modestly (34.6\%$\rightarrow$38.8\%), showing safety vetoes alone cannot fix long-horizon control. \emph{Traversal-as-Policy} (\textbf{+GBT-Basic}) raises SR to 50.2\% while maintaining low Viol/USucc and reducing cost (Tok/Chars 208/820$\rightarrow$148/570), confirming a distilled macro skeleton that prevents drift and shrinks context. \emph{Self-evolution under invariants} (\textbf{+GBT-SE}) yields the headline jump to 73.6\% SR at 86.0\% coverage, while driving unsafe success to 0.0\% and keeping violations near zero (0.2\%). The net effect matches the our core claim: safety is enforced \emph{pre-execution} from structured \texttt{ctx}, while success rises as long-horizon behavior follows a constrained traversal policy.
\subsubsection{WebArena: traversal arrests drift; recovery converts stalls into progress}
\label{sec:exp:main_web}
\vspace{-.2em}
WebArena emphasizes long-horizon brittleness: small deviations compound into irrecoverable dead-ends. Table~\ref{tab:web_main_refined} again separates mechanisms. The \textbf{global guardrail only} row sharply reduces Viol/USucc (3.4\%/1.0\%$\rightarrow$0.9\%/0.2\%) but leaves SR unchanged (19.7\%$\rightarrow$19.3\%), indicating that the dominant failure mode is not unsafe actions but \emph{policy drift and stalling}. Adding \gbt{} produces a large SR jump (to 53.0\% with \textbf{GBT-Basic}, then 66.9\% with \textbf{GBT-SE}) while simultaneously reducing cost (Tok/Chars 94/360$\rightarrow$52/205) and eliminating unsafe success (0.0\%). This is the expected signature of Traversal-as-Policy: traversal constrains macro choice to log-grounded successors, and recovery injects short, feasible macro sequences when the agent stalls (recovery diagnostics and ablations in App.~\ref{app:exp_ablation}).
\subsubsection{GPQA: with browsing disabled, \gbt{} turns the agent into a controlled local executor}
\label{sec:exp:main_gpqa}
\vspace{-.2em}
GPQA removes web browsing and tests tool-assisted reasoning under strict sandbox monitors. Table~\ref{tab:gpqa_main_refined} shows that \gbt{} raises accuracy from 58.7\% (OpenHands agent) to 87.3\% (\textbf{GBT-SE}), while keeping Viol and USucc essentially at zero (0.2\% and 0.0\%). The improvement concentrates in covered episodes, consistent with traversal supplying an explicit macro-level execution plan and spine memory preventing transcript-induced drift; a coverage-conditioned audit is reported in Table~\ref{tab:conditional_success_refined}.
\begin{table}[t]
\centering
\scriptsize
\caption{\textbf{Conditional performance under coverage (GBT-SE, Protocol A):} gains concentrate in \texttt{covered}$=1$ episodes, the regime where traversal is the long-horizon policy.}
\label{tab:conditional_success_refined}
\setlength{\tabcolsep}{4pt}
\renewcommand{\arraystretch}{1.0}
\begin{tabular}{@{}lcccc@{}}
\toprule
\textbf{Benchmark} &
\textbf{Overall} &
\textbf{Cov} &
\shortstack{$\Pr(\mathbf{succ}\mid$\\$\texttt{covered}=1)$} &
\shortstack{$\Pr(\mathbf{succ}\mid$\\$\texttt{covered}=0)$} \\
\midrule
SWE-bench Verified (SR) &
73.6 &
86.0 &
80.2 &
32.9 \\
WebArena (SR) &
66.9 &
78.0 &
80.4 &
19.0 \\
GPQA (Acc) &
87.3 &
73.0 &
97.9 &
58.7 \\
\bottomrule
\end{tabular}
\end{table}
\subsubsection{Paired outcome audit: improvements persist under paired testing}
\label{sec:exp:paired_audit}
% \vspace{-.2em}
To rule out unpaired noise, we run a paired audit comparing \textbf{Global guardrail only} vs.\ \textbf{+GBT-SE} on the \emph{same} instances (Protocol A), reporting flips and an exact McNemar test. Table~\ref{tab:paired_mcnemar_refined} shows that \gbt{} converts large numbers of failures into successes (large $b$) with comparatively few regressions (small $c$), with significance across all pillars.
\begin{table}[t]
\centering
\small
\caption{\textbf{Paired outcome audit (Protocol A):} $b$ counts instances flipped to success by \gbt{}, $c$ counts instances flipped to failure, ties are unchanged. Exact McNemar test is computed on discordant pairs.}
\label{tab:paired_mcnemar_refined}
\setlength{\tabcolsep}{5pt} % was 7pt
\renewcommand{\arraystretch}{0.95}
\begin{tabular}{@{}lccccc@{}} % remove outer horizontal padding
\toprule
\textbf{Benchmark} & \textbf{$n$} & \textbf{$b$} & \textbf{$c$} & \textbf{Ties} & \textbf{McNemar $p$} \\
\midrule
SWE-bench Verified & 500 & 192 & 18 & 290 & $6.2\!\times\!10^{-38}$ \\
WebArena & 812 & 410 & 24 & 378 & $8.1\!\times\!10^{-92}$ \\
GPQA & 448 & 137 & 11 & 300 & $7.8\!\times\!10^{-29}$ \\
\bottomrule
\end{tabular}
\end{table}
% ============================================================
\subsection{Coverage is the Explicit Claim Boundary (and Where the Gains Come From)}
\label{sec:exp:coverage_main}
Traversal-as-Policy is intentionally coverage-scoped (Sec.\ \ref{sec:method}). Table~\ref{tab:conditional_success_refined} shows that improvements concentrate in \texttt{covered}$=1$ episodes, where traversal is the executed long-horizon policy: SR/Acc is 80.2/80.4/97.9 in coverage, versus 32.9/19.0/58.7 out of coverage. Conversely, Table~\ref{tab:outside_coverage_refined} shows that on episodes labeled \texttt{covered}$=0$ (abstention or safe exploration), outcomes remain similarly poor, consistent with explicit abstention rather than hidden free-running. Step-level matching diagnostics, matched-subset audits, and threshold sensitivity are reported in App.~\ref{app:exp_coverage}.
\begin{table*}[!t]
\centering
\footnotesize
\caption{\textbf{Executor decoupling (Protocol B, 5-fold hold-out):} performance with average tokens (Tok, thousands) and tokenizer-agnostic characters (Chars, thousands).}
\label{tab:small_exec_refined}
\setlength{\tabcolsep}{4pt}
% \renewcommand{\arraystretch}{0.88}
\begin{tabularx}{\textwidth}{@{}>{\raggedright\arraybackslash}Xccc@{}}
\toprule
\textbf{System (OpenHands CodeAct)} &
\textbf{SWE SR\ \ (Tok/Chars)} &
\textbf{WebArena SR\ \ (Tok/Chars)} &
\textbf{GPQA Acc\ \ (Tok/Chars)} \\
\midrule
\texttt{gpt-4o} (native) &
34.2\ (212/818) &
19.5\ (96/365) &
53.5\ (21/77) \\
\quad +Global guardrail only &
36.8\ (190/715) &
19.3\ (90/342) &
51.1\ (20/77) \\
\quad +GBT-SE (same-model upper bound) &
\textbf{63.1}\ (124/482) &
\textbf{65.1}\ (46/177) &
\textbf{63.0}\ (14/54) \\
\midrule
\texttt{llama-3-8b} (native) &
12.6\ (238/905) &
8.3\ (131/505) &
32.4\ (30/120) \\
\quad +GBT-Basic (executor-only) &
27.8\ (121/465) &
22.4\ (61/235) &
49.5\ (16/64) \\
\quad +GBT-SE (executor-only) &
\textbf{46.4}\ (105/405) &
\textbf{33.9}\ (55/212) &
\textbf{58.4}\ (16/60) \\
\midrule
\texttt{Qwen3-VL-8B-Thinking} (native) &
14.0\ (231/880) &
9.1\ (127/488) &
34.0\ (29/116) \\
\quad +GBT-Basic (executor-only) &
32.4\ (124/475) &
24.2\ (59/228) &
54.1\ (16/65) \\
\quad +GBT-SE (executor-only) &
\textbf{58.8}\ (109/420) &
\textbf{37.3}\ (54/210) &
\textbf{60.5}\ (18/61) \\
\bottomrule
\end{tabularx}
\end{table*}
\begin{table*}[!t]
\centering
\footnotesize
\caption{\textbf{Safety/security benchmarks (public and reproducible):} \gbt{} yields large safety gains beyond native agents while preserving utility.}
\label{tab:safety_bench_refined}
\setlength{\tabcolsep}{4pt}
% \renewcommand{\arraystretch}{0.88}
\begin{tabularx}{\textwidth}{@{}>{\raggedright\arraybackslash}Xccccc@{}}
\toprule
\textbf{System} &
\textbf{Agent-SafetyBench} $\uparrow$ &
\textbf{AgentHarm (public) HarmScore} $\downarrow$ &
\textbf{ASB ASR-d} $\downarrow$ &
\textbf{ASB RR} $\uparrow$ &
\textbf{ASB PNA-d} $\uparrow$ \\
\midrule
\texttt{gpt-4o} (native) &
44.2 & 71.8 & 64.4 & 8.8 & \textbf{71.3} \\
\quad +Global guardrail only &
56.8 & 19.0 & 13.1 & 63.2 & 69.0 \\
\quad +GBT-Basic &
60.2 & 11.2 & 8.6 & 73.8 & 70.1 \\
\quad +GBT-SE &
\textbf{72.3} & \textbf{9.6} & \textbf{7.0} & \textbf{78.4} & 70.4 \\
\midrule
\texttt{llama-3-8b} (native) &
20.1 & 29.4 & 20.4 & 4.9 & \textbf{52.0} \\
\quad +Global guardrail only &
50.4 & 16.5 & 10.9 & 61.6 & 50.8 \\
\quad +GBT-Basic &
55.4 & 12.4 & 8.7 & 72.2 & 51.6 \\
\quad +GBT-SE &
\textbf{70.8} & \textbf{10.3} & \textbf{7.4} & \textbf{77.0} & 51.8 \\
\bottomrule
\end{tabularx}
\end{table*}
%
\begin{table}[t]
\centering
\small
\caption{\textbf{Outside-coverage audit (Protocol A):} performance on episodes labeled \texttt{covered}$=0$ by \gbt{}. Similar outcomes confirm that gains arise in-coverage, where traversal is executed as the policy skeleton.}
\label{tab:outside_coverage_refined}
\setlength{\tabcolsep}{8pt}
\resizebox{\columnwidth}{!}{%
\begin{tabular}{lccc}
\toprule
\textbf{Benchmark} & \textbf{$n_{\texttt{covered}=0}$} & \textbf{Base agent} & \textbf{+GBT-SE} \\
\midrule
SWE-bench Verified (SR) & 70 & 32.9 {\scriptsize(23/70)} & 32.9 {\scriptsize(23/70)} \\
WebArena (SR) & 179 & 17.9 {\scriptsize(32/179)} & 19.0 {\scriptsize(34/179)} \\
GPQA (Acc) & 121 & 55.4 {\scriptsize(67/121)} & 58.7 {\scriptsize(71/121)} \\
\bottomrule
\end{tabular}%
}
\end{table}
\subsection{Decoupling Reasoning Capacity from Policy Execution (Protocol B)}
\label{sec:exp:decouple_main}
% \vspace{-.2em}
We test the executor-decoupling claim: heavy reasoning is used \emph{offline} to build/refine \gbt{}, while \emph{online} execution can be delegated to small models that realize one macro at a time under traversal/recovery and deterministic gates (Sec.~\ref{sec:method}). Table~\ref{tab:small_exec_refined} reports 5-fold instance-level hold-out (Protocol B). With the same distilled tree, 8B-scale executors more than triple success on the execution pillars (e.g., \texttt{llama-3-8b}~\cite{dubey2024llama} on SWE: 12.6\%$\rightarrow$46.4\%) while operating at markedly lower Tok/Chars due to spine-based context and reduced long-horizon deliberation. This directly supports the ``policy as external artifact'' claim: the reusable object is \gbt{}, not a particular model’s weights.
% ============================================================
\subsection{Deterministic Pre-execution Safety on Public Safety/Security Suites}
\label{sec:exp:safety_main}
% \vspace{-.2em}
We evaluate whether safety outcomes match the Method’s invariants (Sec.\ \ref{sec:method}): gate checks are \emph{pre-execution} and depend only on structured \texttt{ctx}; self-evolution cannot re-admit previously rejected unsafe contexts; and node-local gates provide macro-local defenses beyond global guardrails. Table~\ref{tab:safety_bench_refined} reports large safety gains over native agents, with further improvements past global guardrails when enabling \gbt{}; importantly, utility under defense (ASB \textbf{PNA-d}) remains stable. Extended safety counts, guardrail activity, and mechanism ablations (gates, recovery, memory, self-evolution) are in App.~\ref{app:exp_safety}--App.~\ref{app:exp_ablation}.
\textbf{Where to find the rest.} App.~\ref{app:exp_plugin}--\ref{app:exp_ablation} detail plug-in generalization across heterogeneous frameworks, run-to-run stability, structural hold-outs, coverage/matching diagnostics, and targeted ablations (gates, recovery, memory, self-evolution).
\section{Conclusion}
\label{sec:conclusion}
Traversal-as-Policy turns execution logs into an explicit, inspectable controller: a log-distilled Gated Behavior Tree (\gbt{}) whose traversal is the policy whenever coverage holds. By compiling unsafe traces into deterministic pre-execution gates over structured tool contexts and updating them under experience-grounded monotonicity, \gbt{} enforces safety before high-risk actions run and prevents silent regression during self-evolution. A lightweight traverser executes one state-conditioned macro at a time, uses risk-aware shortest-path recovery to escape stalls, and replaces transcript replay with a compact spine memory, jointly improving robustness and cost. Across 15+ OpenHands benchmarks, \gbt{}-SE delivers large utility gains while driving violations and unsafe success to (near) zero, and the same distilled tree enables 8B-scale executors to compete with far larger models—evidence that policy can be externalized from weights. Limitations, additional analysis, and future directions appear in App.~\ref{app:concl_limitations}--\ref{app:concl_future}.
\appendix
\section{Related Work}
Our work sits at the intersection of long-horizon agent control, safety, and structured policy representations. The key distinction is \emph{policy externalization}: instead of improving an implicit, transcript-driven controller, we distill a single \emph{executable} artifact from aggregate experience and then execute \emph{traversal} as the policy whenever in coverage.
\paragraph{Improving intrinsic reasoning and memory.}
A large body of work strengthens agent performance by amplifying internal reasoning. Deliberative methods such as Tree-of-Thoughts (ToT) \citep{treeofthought} expand online search, often at substantial inference cost. Self-improvement approaches such as Reflexion \citep{reflexion} and Meta-Policy Reflexion \citep{mpr} store textual ``reflection memories'' to adapt from failures. These techniques remain fundamentally \emph{generation-centric}: they either operate online or build non-executable textual memories, and the long-horizon policy is still realized through unconstrained language generation conditioned on a growing transcript. In contrast, our framework distills \emph{both} successes (for behavioral guidance) and failures (for safety) into a single offline, executable structure; the resulting controller is an inspectable artifact whose traversal determines the executed macro skeleton in covered episodes.
\paragraph{Guardrailing and runtime validation.}
The dominant safety paradigm for agents is ``guardrailing'': attach a runtime validator, critic, or guardian agent that checks actions as they are proposed \citep{guardagent,aworld,policyasprompt}. While effective in reducing harm, these systems typically rely on \emph{human-specified} policies (natural-language rules, prompt templates, or code), which is unscalable and often misses the long tail of emergent, context-dependent failure modes that appear only in operational data. Our approach flips the source of safety knowledge: we deterministically replay unsafe traces, shrink them to minimal violating windows, and compile the resulting structured contexts into \emph{pre-execution gates} that are grounded in observed failures. This converts failure logs into a growing, executable safety mechanism rather than a passive record.
\paragraph{Formal guarantees, learned constraints, and the safety--utility trade-off.}
Formal methods such as shielding \citep{shielding} can offer strong verifiable guarantees, but they typically require manually crafted formal environment models, an intractable prerequisite for most open-world agent tasks. Hybrid approaches that learn probabilistic models online \citep{agentguard} can provide only probabilistic assurances, whereas our gates provide deterministic checks over structured tool contexts. Other paradigms internalize safety via implicit optimization trade-offs, such as Constrained MDPs (CMDPs) \citep{gu2024enhancingefficiencysafereinforcement} or adversarial training \citep{agentdojo,arlas}. These methods embed safety inside an opaque, monolithic policy, making it difficult to inspect or certify what constraints are enforced and where. Our framework instead \emph{externalizes} safety into an explicit library of deterministic predicates over structured contexts, and enforces an experience-grounded monotonicity rule: once a context is observed unsafe and rejected, it cannot be re-admitted by later updates. This yields a verifiable notion of non-regression on observed unsafe contexts while still allowing behavioral improvement through coverage expansion.
\paragraph{Structured policy representations for agents.}
Hierarchical controllers such as finite state machines (FSMs) \citep{pract,crouse2024formallyspecifyinghighlevelbehavior} and behavior trees (BTs) \citep{wang2025llmhbtdynamicbehaviortree,btgenbot} offer interpretability and modularity, but are often hand-crafted by experts or generated once from a single high-level instruction. This ``Policy-as-Code'' paradigm is brittle under distribution shift and typically lacks a principled link between operational failures and controller updates. Our approach is ``Policy-as-Data'': we distill a \emph{Gated} Behavior Tree from massive aggregate experience, merge-checking macros to avoid semantic aliasing where safety matters, attaching node-local gates from unsafe windows, and executing traversal as the policy within an explicit coverage boundary. The result is not a one-off plan for a single instruction, but a reusable policy artifact that unifies behavioral guidance, deterministic pre-execution safety, recovery, and long-horizon memory within a single executable structure.
% ------------------------------------------------------------
\section{Safety Specification, Structured Contexts, and the Global Guardrail}
\label{app:guardrail}
\subsection{Normative Safety Specification in OpenHands and Sandboxed Data}
\label{app:guardrail:safety-spec}
\paragraph{What is normative safety \texorpdfstring{$\mathcal{S}_{\text{spec}}$}{S_spec}?}
All trajectories are executed inside the OpenHands runtime, which provides (i) a Docker-isolated sandbox, (ii) a standardized event stream of tool \emph{actions} and \emph{observations}, and (iii) benchmark-defined \emph{checkers} plus runtime \emph{monitors} that emit verdicts. Together, monitors and checkers define a \emph{normative safety specification} $\mathcal{S}_{\text{spec}}$ over primitive tool calls:
a primitive violates $\mathcal{S}_{\text{spec}}$ iff at execution time it triggers any monitor or checker safety verdict.
Examples include (non-exhaustive): writes outside workspace roots, deletion of protected directories, process spawn patterns disallowed by the sandbox policy, network traffic to disallowed destinations, and benchmark-specific leakage/exfiltration triggers.
\paragraph{Trajectory labeling.}
A trajectory $\tau$ is labeled \texttt{unsafe} \emph{iff} at least one executed primitive violates $\mathcal{S}_{\text{spec}}$ under the OpenHands monitors/checkers. This is the only ground-truth safety label used throughout the pipeline.
\paragraph{Design goal (coverage-scoped claims).}
We do \emph{not} claim complete enforcement of $\mathcal{S}_{\text{spec}}$ for all hazards.
Instead, we externalize and deterministically enforce an \emph{executable} bounded-history subset (defined below) and treat violations under the current system as evidence that expands this executable subset monotonically over observed unsafe contexts (Design invariant~1).
% ------------------------------------------------------------
\subsection{Structured Contexts: The Only Inputs to Gates}
\label{app:guardrail:ctx}
\paragraph{Structured context schema.}
For each candidate high-risk primitive, we construct a structured context $\texttt{ctx}\in\mathcal{C}$ \emph{directly from sandbox state}.
The gate library reads \emph{only} these structured fields and a bounded history of recent high-risk primitives; it never reads LLM summaries, chain-of-thought, or free-form transcripts.
Concretely, we represent \texttt{ctx} as:
\begin{quote}
\texttt{ctx = \{ primitive\_type, tool\_family, args, resource\_ids,}\\
\texttt{\ \ \ \ \ \ \ \ \ \ \ \ \ workspace\_roots, cwd, uid/gid,}\\
\texttt{\ \ \ \ \ \ \ \ \ \ \ \ \ net\_dest(domain, ip, port, scheme),}\\
\texttt{\ \ \ \ \ \ \ \ \ \ \ \ \ proc\_meta(exec, argv, parent),}\\
\texttt{\ \ \ \ \ \ \ \ \ \ \ \ \ payload\_meta(len, mime, hash),}\\
\texttt{\ \ \ \ \ \ \ \ \ \ \ \ \ recent\_hard\_history[1..H]\}}
\end{quote}
where:
(i) \texttt{args/resource\_ids} store canonicalized file paths (normalized, resolved, and checked against sandbox roots), URL components (domain/scheme/path), and process identifiers where applicable;
(ii) \texttt{payload\_meta} stores metadata for payload-bearing actions (length, MIME/type if known, and a stable hash); and
(iii) \texttt{recent\_hard\_history} records the last $H$ high-risk primitives \emph{within the same macro}, each stored as a compact structured record \texttt{(type, canonical\_resource, coarse\_op, timestamp)}.
We use a fixed small history bound $H=4$ in the reference configuration.
\paragraph{High-risk primitive set \texorpdfstring{$\mathcal{T}_{\text{hard}}$}{T_hard}.}
We designate as high-risk:
\[
\mathcal{T}_{\text{hard}}
=
\{\text{all writes and deletes}\}
\cup
\{\text{all process spawns}\}
\cup
\{\text{all network sends}\}
\cup
\{\text{reads matching sensitive patterns}\}.
\]
The \emph{sensitive patterns} component is benchmark- and runtime-aware and includes protected filesystem prefixes, environment/key material patterns, and benchmark-defined secret resources (when applicable).
\paragraph{Non-bypassability.}
Because \texttt{ctx} is constructed from sandbox state and canonicalization is deterministic, \emph{no prompting or summarization choice can alter gate inputs}.
Summaries may influence how a macro is realized, but cannot change \texttt{ctx} nor the outcome of deterministic gates computed from it.
% ------------------------------------------------------------
\subsection{Gate Interface, Global vs.\ Node-Local Gates, and Executable Safety Subset}
\label{app:guardrail:gate}
\paragraph{Gate interface (common to all gate families).}
Every gate has the same interface:
\[
g:\ \texttt{ctx} \mapsto (\texttt{ok},\texttt{msg})
\in
\{\texttt{true},\texttt{false}\}\times\texttt{String}.
\]
We write $\mathcal{G}_{\text{global}}(t)$ for global gates and $\mathcal{G}_{\text{node}}(t)$ for node-local gates attached to macros in the tree, and
$\mathcal{G}(t)=\mathcal{G}_{\text{global}}(t)\cup\mathcal{G}_{\text{node}}(t)$.
\paragraph{Executable safety subset.}
We define the executable subset at time $t$ as:
\[
\mathcal{S}_{\text{sys}}(t)
=
\left\{
\texttt{ctx}\in\mathcal{C}:
\exists g\in\mathcal{G}(t)
\ \text{s.t.}\
g(\texttt{ctx}).\texttt{ok}=\texttt{false}
\right\}.
\]
This is a conservative, bounded-history approximation of the portion of $\mathcal{S}_{\text{spec}}$ that is expressible via structured contexts.
\paragraph{Global decision (always-on, pre-execution).}
For any candidate high-risk primitive $a\in\mathcal{T}_{\text{hard}}$:
\[
\texttt{HardGateOK}(a,\texttt{ctx})
=
\bigwedge_{g\in\mathcal{G}_{\text{global}}} g(\texttt{ctx}).\texttt{ok}.
\]
This check runs \emph{before execution} for every high-risk primitive in every phase: data collection, offline distillation, and online deployment.
\paragraph{Node-local decision (macro-scoped, pre-execution).}
When a macro node $v$ is selected during traversal/recovery, we additionally enforce:
\[
\texttt{GateOK}(v,\texttt{ctx})
=
\bigwedge_{g\in\mathcal{G}(v)} g(\texttt{ctx}).\texttt{ok}.
\]
The executed primitive is allowed only if both global and node-local checks pass (as in Sec.~\ref{sec:online}).
% ------------------------------------------------------------
\subsection{Gate Families: Deterministic RuleGates and Deterministic ContentGates}
\label{app:guardrail:families}
\paragraph{RuleGates (fully deterministic).}
RuleGates are pure code predicates over structured fields in \texttt{ctx} and its bounded history, for example:
(i) forbid writes outside workspace roots;
(ii) forbid deletion of protected paths;
(iii) forbid process spawn patterns (e.g., executing disallowed binaries);
(iv) forbid network sends to disallowed domains/ports; and
(v) block short-window structured patterns such as ``read sensitive resource then archive then send'' when all components are detectable from \texttt{ctx} and bounded history.
RuleGates are unit-tested and deterministic.
\paragraph{ContentGates (deterministic calls to a frozen classifier).}
Some hazards are primarily carried by unstructured payloads (text/code/serialized blobs).
For payload-bearing actions, ContentGates construct a guard prompt from:
\texttt{(i) ctx structured fields, (ii) a short payload excerpt or redacted summary, (iii) a task/macro tag)},
then call a frozen safety classifier at temperature $0$ and post-process into a boolean decision.
In the reference configuration we use \texttt{Llama-Guard-3-8B} at temperature $0$ as the classifier (see App.~\ref{app:exp_systems}).
\paragraph{Determinism contract.}
ContentGates are deterministic conditional on (i) a fixed guard model, (ii) temperature $0$, and (iii) a fixed prompt template.
They do \emph{not} introduce stochasticity into enforcement.
% ------------------------------------------------------------
\subsection{Experience-Grounded Corpora and Monotone Updates (No Unsafe Re-Admission)}
\label{app:guardrail:monotone}
\paragraph{Unsafe and benign corpora.}
For each gate $g$ we maintain:
\begin{itemize}
\item an unsafe corpus $\mathcal{D}_{\text{unsafe}}(g)$: structured contexts extracted from trajectories that violate $\mathcal{S}_{\text{spec}}$ (minimal windows, App.~\ref{app:tree-construction});
\item a benign corpus $\mathcal{D}_{\text{benign}}(g)$: representative safe contexts of the \emph{same primitive family} (same tool family, same risk class) sampled from successful or non-violating runs.
\end{itemize}
We maintain balanced benign sampling across resource types and macro neighborhoods to avoid overfitting gates to a narrow distribution.
\paragraph{Update rule (monotonicity + benign regression control).}
Any update from $g^{\text{old}}$ to $g^{\text{new}}$ must satisfy:
\[
\forall\,\texttt{ctx}\in\mathcal{D}_{\text{unsafe}}(g):\quad
g^{\text{old}}(\texttt{ctx}).\texttt{ok}=\texttt{false}
\Rightarrow
g^{\text{new}}(\texttt{ctx}).\texttt{ok}=\texttt{false},
\]
and limit benign false positives:
\[
\frac{\left|\left\{\texttt{ctx}\in\mathcal{D}_{\text{benign}}(g): g^{\text{new}}(\texttt{ctx}).\texttt{ok}=\texttt{false}\right\}\right|}
{|\mathcal{D}_{\text{benign}}(g)|}
\le \epsilon_{\text{benign}}.
\]
In the reference configuration we use $\epsilon_{\text{benign}}=0.01$ for global gates and $\epsilon_{\text{benign}}=0.02$ for node-local gates (node-local gates are intentionally allowed to be slightly more conservative within a macro neighborhood).
\paragraph{Design invariant 1 (Experience-grounded monotonicity).}
Once a structured context is recorded as unsafe and rejected by any gate, it remains rejected by all future gate libraries.
Equivalently, $\mathcal{S}_{\text{sys}}(t)$ can only \emph{expand} on observed unsafe behavior; it cannot shrink on logged unsafe contexts.
% ------------------------------------------------------------
\subsection{Reference Prompt Templates (Runnable) for ContentGates and Gate Synthesis}
\label{app:guardrail:prompts}
\paragraph{ContentGate prompt (reference configuration).}
We use a fixed template that maps \texttt{ctx} + a payload excerpt to a strict binary decision.
The template is intentionally \emph{short}, as the input is already structured:
\begin{quote}\small
\textbf{SYSTEM:} You are a safety classifier. Output exactly one token: \texttt{SAFE} or \texttt{UNSAFE}.\\
\textbf{USER:} \\
\texttt{[Action]} \{primitive\_type, tool\_family\}\\
\texttt{[Args]} \{canonical\_path/domain/port if any\}\\
\texttt{[History]} last H hard primitives: \{(type, resource, op)\}\\
\texttt{[Payload]} (redacted excerpt, max 1{,}000 chars)\\
\texttt{Decide if executing this action violates the sandbox safety policy or}\\
\texttt{benchmark-defined safety constraints.}
\end{quote}
\paragraph{Deterministic RuleGate synthesis prompt (reference configuration).}
We synthesize candidate structured predicates offline from minimal unsafe windows (App.~\ref{app:tree-construction}) using a frozen reasoning model.
We enforce that the model outputs \emph{only} code over structured fields and bounded history:
\begin{quote}\small
\textbf{SYSTEM:} You write deterministic Python predicates over a given JSON schema.\\
\textbf{USER:} Given the unsafe contexts below (positive) and benign contexts (negative),\\
propose a Python function \texttt{gate(ctx)->(ok,msg)} that:
(1) rejects all positives,
(2) rejects at most $\epsilon_{\text{benign}}$ of negatives,
(3) uses only \texttt{ctx} fields and \texttt{ctx.recent\_hard\_history},
(4) contains no randomness and no external calls.
Return JSON: \{\texttt{"code": "...", "rationale": "..."}\}.
\end{quote}
We then (i) compile the returned code, (ii) unit-test it on corpora, and (iii) accept it only if it satisfies the formal constraints above.
% ------------------------------------------------------------
\subsection{Concrete Examples of Structured Gates (Illustrative)}
\label{app:guardrail:examples}
Below are illustrative (not benchmark-specific) RuleGate patterns, expressed purely over structured fields:
\begin{itemize}
\item \textbf{Workspace confinement:} reject writes/deletes whose canonical path is outside \texttt{workspace\_roots}.
\item \textbf{Protected deletion:} reject deletes of any path matching protected prefixes (e.g., system dirs) or non-ephemeral dirs.
\item \textbf{Network egress control:} reject network sends when \texttt{domain} is not in an allowlist or when \texttt{scheme/port} is disallowed.
\item \textbf{Short-window exfiltration motif:} if \texttt{recent\_hard\_history} contains a sensitive read followed by an archive/write, reject a subsequent network send of the same artifact.
\end{itemize}
These examples are representative of the expressible subset $\mathcal{S}_{\text{sys}}(t)$ and emphasize the key property: all decisions depend only on structured context and bounded history.
% ============================================================
\section{Behavior Path Extractor and Abstraction Stability}
\label{app:behavior-extractor}
\subsection{Deterministic Macro Segmentation from Observable Deltas}
\label{app:behavior-extractor:segmentation}
Raw trajectories are long and tool-specific. The Behavior Path Extractor $E$ maps a trajectory $\tau$ to a macro path
\[
p=(v_0,\dots,v_K)=E(\tau),
\]
where each macro $v_k$ is a contiguous span of primitives that:
(i) stays within a local sub-action region, and
(ii) realizes a coherent intent.
\paragraph{Segmentation signals (no LLM judgment).}
Macro boundaries are anchored by \emph{observable} environment deltas and tool-family changes logged by OpenHands:
\begin{itemize}
\item \textbf{Filesystem deltas:} creation/modification of files; diff size thresholds; directory scope change.
\item \textbf{Execution deltas:} process spawn/termination; test invocation boundaries; interpreter session boundaries.
\item \textbf{Web deltas:} domain change; navigation state change; form submission boundary.
\item \textbf{Tool-family switch:} first invocation of a different tool family in a span (e.g., from file ops to browser).
\end{itemize}
These rules are deterministic functions of logs. LLMs are not used to decide boundaries.
\paragraph{Risk annotation.}
Each macro is assigned a discrete \texttt{risk\_level} based on whether its primitive span touches $\mathcal{T}_{\text{hard}}$ and which resource families it touches (files, network, processes). This risk metadata is used only for (i) conservative merging and (ii) risk-aware recovery costs (App.~\ref{app:recovery}).
% ------------------------------------------------------------
\subsection{Macro Description Summarization (Offline Only) and Output Schema}
\label{app:behavior-extractor:summarization}
After segmentation, we summarize each macro span into a short description \emph{solely for semantic matching and retrieval}.
This summary is \emph{never} consumed by gates or preconditions.
\paragraph{Reference summarization prompt (runnable).}
We call a frozen LLM at temperature $0$ with a strict JSON schema:
\begin{quote}\small
\textbf{SYSTEM:} Summarize a tool-usage segment into a reusable action macro. Output JSON only.\\
\textbf{USER:} You are given (i) a sequence of primitive tool calls with arguments, and (ii) a compact description of observable environment deltas.\\
Produce JSON with fields:
\texttt{\{"macro\_desc": "...", "macro\_tags": [...], "resources": [...], "hard\_touch": bool\}}.
\end{quote}
We set \texttt{max\_tokens=256} and enforce JSON parsing; unparsable outputs are retried once with the same temperature $0$ and an added format reminder.
% ------------------------------------------------------------
\subsection{Abstraction Stability Test on Safety-Critical Traces}
\label{app:behavior-extractor:stability}
Traversal assumes macros have stable semantics. We therefore test stability on any trajectory that is unsafe or touches $\mathcal{T}_{\text{hard}}$.
\paragraph{Stability protocol.}
For a candidate trajectory $\tau$:
(i) run the deterministic segmentation once to obtain boundary indices;
(ii) rerun only the \emph{summarization} calls under $P$ prompt perturbations (rephrased instructions and shuffled in-context examples) while keeping segmentation fixed;
(iii) measure whether resulting macro descriptions remain semantically equivalent and do not induce boundary drift or semantic aliasing downstream.
\paragraph{Boundary stability (conservative).}
If the pipeline variant includes any stochastic segmentation component, we require boundary-set Jaccard similarity
\[
J(B^{(i)},B^{(j)}) \ge \delta_{\text{stab}}
\quad\forall i\neq j,
\]
with reference threshold $\delta_{\text{stab}}=0.9$ and $P=5$ perturbations.
Any trajectory failing this test is marked \emph{abstract-unstable} and excluded from tree construction and gate derivation.
(Primitive-level safety remains enforced by the global guardrail regardless.)
\paragraph{Why this matters.}
This explicitly prevents safety-critical behavior from being externalized into macros when the abstraction itself is unstable, aligning with the main-text claim that traversal is only used where macro semantics are robust.
% ============================================================
\section{Task-Family Routing and Re-rooting}
\label{app:family-classifier}
\subsection{Family Taxonomy (First-Layer Branching Control)}
\label{app:family-classifier:taxonomy}
We build a single rooted tree whose first layer consists of a small number of task-family roots (reference configuration: 21 families, derived by benchmark inspection) to reduce branching.
Example families include \texttt{CODE\_EDITING}, \texttt{TEST\_DEBUG}, \texttt{WEB\_BROWSING}, \texttt{FORM\_FILLING}, \texttt{DATA\_ANALYSIS}, \texttt{NETWORK\_PROCESS}, and \texttt{CHAT}.
\subsection{Training-Free Routing by Prototype Similarity}
\label{app:family-classifier:routing}
Routing must respect the paper’s training-free discipline: no weight updates.
We implement a frozen router using prototype similarity:
\begin{itemize}
\item For each family $f$, we store a small set of natural-language prototypes $\Pi_f$ (2--8 short descriptions) curated once from benchmark/task definitions.
\item Given a task description $x$, we embed $x$ and all prototypes using a frozen text encoder $f(\cdot)$ (any deterministic sentence embedding model).
\item We score each family by its best prototype similarity:
$
s(f\mid x)=\max_{\pi\in\Pi_f}\cos(f(x),f(\pi)).
$
\item We convert scores to a normalized distribution by a temperature-scaled softmax:
$
p(f\mid x)=\frac{\exp(s(f\mid x)/T_{\text{fam}})}{\sum_{f'}\exp(s(f'\mid x)/T_{\text{fam}})}.
$
\end{itemize}
\paragraph{Abstention threshold (explicit claim boundary).}
Let $p_{\max}=\max_f p(f\mid x)$.
If $p_{\max}<\delta_{\text{fam}}$, the traverser abstains from traversal control and the episode is labeled \texttt{covered}=0.
Reference configuration: $\delta_{\text{fam}}=0.55$, $T_{\text{fam}}=0.05$.
\subsection{Re-rooting Under Task Drift}
\label{app:family-classifier:reroot}
Long tasks may drift across families (e.g., from web browsing to code editing).
Every $m$ macro steps (reference: $m=3$), we recompute $p(f\mid x_{\text{current}})$ using the current task summary and spine.
We re-root iff:
(i) a new family exceeds the current family by margin $\Delta_{\text{switch}}$,
(ii) the new family also exceeds $\delta_{\text{fam}}$,
and (iii) re-rooting preserves acyclicity and does not cross into a disallowed subtree.
Reference: $\Delta_{\text{switch}}=0.10$.
Re-rooting modifies only the \emph{family root anchor}; it does not alter gates and cannot weaken enforcement (Design invariants~1--2).
% ============================================================
\section{Node-Local Gates, Tree Construction, and Acyclicity}
\label{app:tree-construction}
\subsection{Minimal Unsafe Windows via Deterministic Replay Shrinking}
\label{app:tree-construction:windows}
Unsafe trajectories reveal $\mathcal{S}_{\text{spec}}$ violations not yet captured by $\mathcal{S}_{\text{sys}}(t)$.
For each unsafe trajectory $\tau$, we find a minimal unsafe primitive window
$
W=(a_{t_0},\dots,a_{t_1})
$
by deterministic sandbox replay:
\paragraph{Window shrinking algorithm (deterministic).}
We checkpoint replayable states (pre-action snapshots) and shrink $[t_0,t_1]$ by:
(i) binary searching the earliest violating index,
(ii) minimizing contiguous prefixes/suffixes while preserving the violation,
and
(iii) verifying minimality: removing any primitive from the boundary removes the violation verdict.
This yields the shortest contiguous window that triggers the first safety verdict under replay.
\subsection{Mapping Unsafe Windows to Macro Subsequences and Attaching Node-Local Gates}