Repository navigation
Expand file tree
/
Copy pathguardrails.py
More file actions
166 lines (145 loc) · 6.84 KB
/
Copy pathguardrails.py
File metadata and controls
166 lines (145 loc) · 6.84 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
"""Progress guardrails — catch the agent thrashing on unproductive actions and
drifting from the request, then intervene (soft re-ground first, hard stop
second). Complements loop.py's exact-repeat breaker, which only catches
byte-identical calls; this catches the *class* of "no progress" failures:
reworded dead ends, confabulated targets, and general spinning.
Design (see the guardrails discussion / LAB_NOTEBOOK):
- Detect LACK OF PROGRESS, not specific bad paths (no overfitting to one trace).
- Enforce in the harness, not the prompt (Exp 3: this model ignores prompt-only
behavioral nudges).
- Soft-correct before hard-stop (legit debugging also fails commands; a blunt
kill is a false-positive machine).
One class: ProgressMonitor. One method the loop calls: record(name, raw_args,
result) -> None | "reground" | "stop". When it returns non-None, .message holds
the text to inject (reground) or return to the user (stop).
"""
import os
import re
REGROUND_AT = 4 # weighted stall score that triggers the first nudge
HARD_UNPRODUCTIVE = 12 # absolute backstop: this many dead steps total -> stop
# result looks like a dead end
_NOTFOUND = re.compile(
r"no such file|cannot find|does not exist|not found|is not recognized|"
r"command not found|\[exit [1-9]|\bfalse\b\s*$", re.IGNORECASE)
# filesystem-ish path tokens inside a raw args string (drive paths + unix paths)
_PATH = re.compile(
r"[A-Za-z]:[\\/][^\s\"'<>|]+|(?:\.{1,2}|~)?[\\/][A-Za-z0-9._\-][^\s\"'<>|]*")
_PATH_NOISE = {"/dev/null", "/dev/stdout", "/dev/stderr", "2>&1"}
# path components too generic to count as "provenance"
_COMMON = {"users", "home", "appdata", "local", "roaming", "documents",
"desktop", "program files", "programdata", "temp", "tmp", "windows",
"system32", "dev", "null", "usr", "bin", "etc", "var", "content"}
def _fs_paths(raw):
out = []
for m in _PATH.findall(raw or ""):
t = m.strip().strip("\"'")
if len(t) < 4 or t.lower() in _PATH_NOISE or t.startswith("http"):
continue
# driveless token must have real path structure (>=2 separators) or a file
# extension — otherwise it's a command flag like /nologo or /ipk, not a path.
if not re.match(r"[A-Za-z]:", t):
seps = t.count("/") + t.count("\\")
if seps < 2 and not re.search(r"\.[A-Za-z0-9]{1,5}$", t):
continue
out.append(t)
return out
def _canon(raw, paths):
"""Canonical target for near-repeat matching: the longest fs-path with digits
collapsed, else a normalized command string."""
base = max(paths, key=len) if paths else (raw or "")
base = base.lower().replace("\\", "/")
base = re.sub(r"\d+", "#", base)
base = re.sub(r"\s+", " ", base).strip()
return base
def _similar(a, b):
if not a or not b:
return False
if len(a) >= 6 and len(b) >= 6 and (a in b or b in a):
return True
ca = {c for c in re.split(r"[/ ]", a) if len(c) > 2}
cb = {c for c in re.split(r"[/ ]", b) if len(c) > 2}
if not ca or not cb:
return False
return len(ca & cb) / len(ca | cb) >= 0.6
class ProgressMonitor:
def __init__(self, user_request, cwd=None):
self.user_request = (user_request or "").strip()
self.grounded_text = (self.user_request + " " + str(cwd or os.getcwd())).lower()
self.score = 0
self.unproductive_total = 0
self.reground_count = 0
self.recent_canons = [] # last few targets, for near-repeat
self.last_offender = ""
self.message = ""
# --- classification ------------------------------------------------------
def _productive(self, name, result):
r = result or ""
if name in ("write_file", "edit_file") and not r.startswith("[error]"):
return True
if (r.startswith("[error]") or r.startswith("[harness]")
or not r.strip() or len(r.strip()) < 24):
return False
if _NOTFOUND.search(r[:400]):
return False
return True
def _grounded(self, path):
try:
if os.path.exists(path):
return True
except (OSError, ValueError):
pass
pl = path.lower().replace("\\", "/")
for c in re.split(r"[/\\]", pl):
if len(c) > 2 and c not in _COMMON and c in self.grounded_text:
return True
return False
# --- the one entry point the loop calls ----------------------------------
def record(self, name, raw_args, result):
paths = _fs_paths(raw_args)
if self._productive(name, result):
# progress erases suspicion: learn the new grounded tokens, reset.
self.grounded_text += " " + (raw_args or "").lower() \
+ " " + (result or "")[:2000].lower()
self.score = 0
self.recent_canons.clear()
return None
# unproductive step — weight it
self.unproductive_total += 1
weight = 1
ungrounded = [p for p in paths if not self._grounded(p)]
if ungrounded: # acting on a target from nowhere = confab
weight += 2
self.last_offender = max(ungrounded, key=len)
canon = _canon(raw_args, paths)
if any(_similar(canon, c) for c in self.recent_canons):
weight += 1 # reworded dead end
self.recent_canons = (self.recent_canons + [canon])[-8:]
self.score += weight
if self.unproductive_total >= HARD_UNPRODUCTIVE:
return self._stop()
if self.score >= REGROUND_AT:
return self._stop() if self.reground_count else self._reground()
return None
# --- interventions -------------------------------------------------------
def _reground(self):
self.reground_count += 1
self.score = 0
off = self.last_offender
self.message = (
"[harness — STOP AND RE-READ] Your last several tool calls failed and "
"produced nothing useful"
+ (f", and the path `{off}` does not exist and was not part of the "
"request" if off else "")
+ f'. The user actually asked: "{self.user_request[:300]}". Abandon this '
"line of action. Either answer the user directly now, or take a "
"genuinely DIFFERENT approach. Do not repeat that path or search again.")
return "reground"
def _stop(self):
off = self.last_offender
self.message = (
"[pit stopped] The model stalled — it kept chasing a dead end"
+ (f" (`{off}`)" if off else "")
+ " and did not recover after a correction. This is almost certainly a "
"model confabulation, not a problem with your request. Try `/model qwen` "
"(a steadier finetune) or rephrase. Nothing was modified.")
return "stop"