@mokuyoaxis/agent-guard 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +101 -0
- package/LICENSE +21 -0
- package/README.md +558 -0
- package/README.zh-CN.md +488 -0
- package/adapters/INTEGRATION.md +94 -0
- package/adapters/claude/README.md +141 -0
- package/adapters/claude/compatibility.json +17 -0
- package/adapters/claude/harness/README.md +59 -0
- package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
- package/adapters/claude/harness/run_scenario.sh +79 -0
- package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
- package/adapters/claude/hook_bridge.sh +33 -0
- package/adapters/claude/pre_tool_use.py +264 -0
- package/adapters/claude/settings.example.json +16 -0
- package/adapters/codex/harness/README.md +53 -0
- package/adapters/codex/harness/acceptance.py +226 -0
- package/adapters/dsh/README.md +62 -0
- package/adapters/dsh/cordis.patch.yml +30 -0
- package/adapters/dsh/lib/index.js +500 -0
- package/adapters/kimi-code/README.md +169 -0
- package/adapters/kimi-code/compatibility.json +17 -0
- package/adapters/kimi-code/config.example.toml +26 -0
- package/adapters/kimi-code/hook_bridge.sh +32 -0
- package/adapters/kimi-code/pre_tool_use.py +72 -0
- package/core/__init__.py +47 -0
- package/core/audit.py +86 -0
- package/core/classifier.py +1175 -0
- package/core/dialects.py +898 -0
- package/core/policy.py +817 -0
- package/core/recovery.py +700 -0
- package/core/redaction.py +1096 -0
- package/core/safe_view.py +212 -0
- package/docs/architecture.md +223 -0
- package/docs/compatibility.md +142 -0
- package/docs/development-note-unguarded-deletion.md +187 -0
- package/docs/friction.md +266 -0
- package/docs/harness-capabilities.md +72 -0
- package/docs/host-drift.md +142 -0
- package/docs/publishing-from-ephemeral-environments.md +104 -0
- package/docs/release-notes-0.2.0-rc1.md +46 -0
- package/docs/release-notes-0.2.0.md +72 -0
- package/docs/release-notes-0.2.1.md +78 -0
- package/docs/release-notes-0.2.2.md +120 -0
- package/docs/secret-guard-analysis.md +416 -0
- package/docs/secret-guard-architecture.md +93 -0
- package/docs/secret-guard-design.md +649 -0
- package/docs/test-report-claude-code-harness.md +462 -0
- package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
- package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
- package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
- package/docs/test-report-dsh-v0.1.1.md +126 -0
- package/docs/test-report-kimi-code-block.md +198 -0
- package/docs/test-report-zcode-glm-flash.md +241 -0
- package/docs/threat-model.md +44 -0
- package/doctor.py +756 -0
- package/live_sentinel.py +339 -0
- package/package.json +69 -0
- package/skills/delete-guard/SKILL.md +109 -0
- package/skills/delete-guard/agents/openai.yaml +4 -0
- package/skills/delete-guard/references/policy.md +161 -0
- package/skills/delete-guard/scripts/_bootstrap.py +8 -0
- package/skills/delete-guard/scripts/check.py +370 -0
- package/skills/delete-guard/scripts/gc.py +103 -0
- package/skills/delete-guard/scripts/restore.py +98 -0
- package/skills/delete-guard/scripts/safe_delete.py +256 -0
- package/skills/delete-guard/scripts/status.py +130 -0
- package/skills/exfil-guard/SKILL.md +143 -0
- package/skills/exfil-guard/agents/openai.yaml +4 -0
- package/skills/exfil-guard/references/channels.md +58 -0
- package/skills/exfil-guard/references/rules.md +194 -0
- package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
- package/skills/exfil-guard/scripts/check_span.py +250 -0
- package/skills/exfil-guard/scripts/sanitize.py +155 -0
- package/skills/exfil-guard/scripts/view.py +44 -0
- package/skills/recovery-audit/SKILL.md +283 -0
- package/skills/recovery-audit/agents/openai.yaml +4 -0
- package/skills/recovery-audit/references/evidence-records.md +85 -0
|
@@ -0,0 +1,1175 @@
|
|
|
1
|
+
"""Effect-oriented classifier for potentially destructive operations.
|
|
2
|
+
|
|
3
|
+
The classifier turns raw input (a shell command string, or an explicit list
|
|
4
|
+
of paths handed to the safe_delete tool) into structured *facts*:
|
|
5
|
+
|
|
6
|
+
OpSpec - one destructive operation found in a command line
|
|
7
|
+
PathSpec - one deletion target with resolved boundary facts
|
|
8
|
+
|
|
9
|
+
It deliberately does NOT decide what to do - that is policy.py's job.
|
|
10
|
+
Design rules:
|
|
11
|
+
|
|
12
|
+
* Classify by effect, dialect only as a front end. The POSIX vocabulary
|
|
13
|
+
(rm/rmdir/unlink/shred, find -delete, git clean/reset/restore/checkout/
|
|
14
|
+
push) covers the overwhelming majority of real agent accidents on
|
|
15
|
+
Linux/macOS. Native Windows shells express the same effects with other
|
|
16
|
+
programs and other lexical rules; those live in `dialects.py` and are
|
|
17
|
+
dispatched by `classify_command(dialect=...)`. The default dialect is
|
|
18
|
+
POSIX, so the pre-dialect behaviour is unchanged for every existing
|
|
19
|
+
caller.
|
|
20
|
+
* Fail closed. Unbalanced quotes, shell variables, command substitution,
|
|
21
|
+
unknown flags, stdin-fed target lists, indirect shells (bash -c) - all
|
|
22
|
+
become `undeterminable` facts. The policy layer restricts those.
|
|
23
|
+
* Lexical boundary analysis. Workspace containment is decided on the
|
|
24
|
+
lexically normalized path (so deleting a symlink that points outside is
|
|
25
|
+
deleting the *link*, not the target, and stays inside the boundary);
|
|
26
|
+
symlink facts are still recorded for audit and for restore.
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import os
|
|
31
|
+
import re
|
|
32
|
+
import shlex
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from typing import List, Optional, Tuple
|
|
35
|
+
|
|
36
|
+
from . import dialects
|
|
37
|
+
|
|
38
|
+
# ---------------------------------------------------------------- vocabulary
|
|
39
|
+
|
|
40
|
+
FS_DELETE_CMDS = {"rm", "rmdir", "unlink", "shred"}
|
|
41
|
+
# Windows-native delete verbs. Recognised on EVERY dialect: a harness that
|
|
42
|
+
# never configured `AGENT_GUARD_DIALECT` still defaults to posix, and a
|
|
43
|
+
# posix-lexed `del /s /q build` must not be treated as an unknown verb.
|
|
44
|
+
# See docs/development-note-unguarded-deletion.md (lesson: the normalized
|
|
45
|
+
# target decides, not the spelling).
|
|
46
|
+
WINDOWS_DELETE_CMDS = {"del", "erase", "rd", "rmdir", "ri"}
|
|
47
|
+
SHELL_PREFIXES = {
|
|
48
|
+
"sudo", "env", "nice", "nohup", "command", "time", "stdbuf",
|
|
49
|
+
"xargs", "exec",
|
|
50
|
+
}
|
|
51
|
+
INTERPRETER_CMDS = {"sh", "bash", "zsh", "ksh", "eval", "source", "."}
|
|
52
|
+
SEPARATORS = {";", "&", "&&", "|", "||", "\n"}
|
|
53
|
+
GLOB_CHARS = ("*", "?", "[")
|
|
54
|
+
INDETERMINACY_CHARS = ("$", "`")
|
|
55
|
+
|
|
56
|
+
# Filesystem roots that must never be a deletion target, whatever the
|
|
57
|
+
# workspace setting says. `rm -rf /home` blocks today only because /home
|
|
58
|
+
# happens to sit outside the workspace root - an accident of configuration,
|
|
59
|
+
# not a policy (see docs/development-note-unguarded-deletion.md).
|
|
60
|
+
#
|
|
61
|
+
# Matching is EXACT: the rule fires when a target *is* one of these roots,
|
|
62
|
+
# never when it merely lives under one, so `rm -rf /home/alice/build` stays
|
|
63
|
+
# an ordinary (out-of-workspace) target and `rm -rf /tmp/work` is untouched.
|
|
64
|
+
PROTECTED_ANCESTOR_ROOTS = frozenset({
|
|
65
|
+
"/", "/home", "/root", "/Users", "/Volumes", "/tmp", "/var", "/usr",
|
|
66
|
+
"/etc", "/opt", "/srv", "/bin", "/sbin", "/lib", "/lib64", "/boot",
|
|
67
|
+
"/proc", "/sys", "/dev", "/mnt", "/media", "/Applications", "/System",
|
|
68
|
+
"/Library", "/private",
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
# Windows drive root (`C:\`, `D:`), which has no POSIX spelling.
|
|
72
|
+
_DRIVE_ROOT_RE = re.compile(r"[A-Za-z]:[\\/]?")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def protected_ancestor_root(path: Optional[str]) -> Optional[str]:
|
|
76
|
+
"""The protected root this path *is*, or None.
|
|
77
|
+
|
|
78
|
+
Exact-match on purpose: `rm -rf /home` is a catastrophe while
|
|
79
|
+
`rm -rf /home/alice/build` is an ordinary target the boundary rules
|
|
80
|
+
already handle. `$HOME` is matched dynamically because it is the one
|
|
81
|
+
root whose location is per-user.
|
|
82
|
+
"""
|
|
83
|
+
if not path:
|
|
84
|
+
return None
|
|
85
|
+
try:
|
|
86
|
+
norm = os.path.normpath(path)
|
|
87
|
+
except (TypeError, ValueError):
|
|
88
|
+
return None
|
|
89
|
+
if norm in PROTECTED_ANCESTOR_ROOTS:
|
|
90
|
+
return norm
|
|
91
|
+
try:
|
|
92
|
+
home = os.path.expanduser("~")
|
|
93
|
+
except Exception: # pragma: no cover - exotic passwd setups
|
|
94
|
+
home = None
|
|
95
|
+
if home and home != "~" and os.path.normpath(home) == norm:
|
|
96
|
+
return norm
|
|
97
|
+
if _DRIVE_ROOT_RE.fullmatch(norm):
|
|
98
|
+
return norm
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
# Single-source keyword prefilter: harness adapters use it to skip
|
|
102
|
+
# non-destructive traffic at regex cost before invoking check.py.
|
|
103
|
+
DESTRUCTIVE_PREFILTER_RE = re.compile(
|
|
104
|
+
r"\b(rm|rmdir|unlink|shred)\b"
|
|
105
|
+
r"|\bfind\b[^\n|;&]*-delete\b"
|
|
106
|
+
r"|\bgit\b[^\n|;&]*\b(clean|reset|restore|checkout|push)\b")
|
|
107
|
+
|
|
108
|
+
# Windows-native prefilter vocabulary. The POSIX regex above never matches
|
|
109
|
+
# `ri build -r -fo`/`rd /s /q build`, so a Windows-native harness would hand
|
|
110
|
+
# the cheap regex a line it cannot see and skip the guard entirely. Adapters
|
|
111
|
+
# only consult this when the *requested* dialect is non-POSIX, so the POSIX
|
|
112
|
+
# fast path keeps its exact historical cost and behaviour.
|
|
113
|
+
DESTRUCTIVE_PREFILTER_RE_WINDOWS = re.compile(
|
|
114
|
+
r"\b(rm|ri|rd|rmdir|del|erase|remove-item)\b"
|
|
115
|
+
r"|-\s?(recurse|force|whatif|literalpath)\b"
|
|
116
|
+
r"|\bgit\b[^\n|;&]*\b(clean|reset|restore|checkout|push)\b",
|
|
117
|
+
re.IGNORECASE)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Rough prefilter for "does this opaque string smell destructive at all".
|
|
121
|
+
# Only used for indirect execution (bash -c '...'), where the guard cannot
|
|
122
|
+
# parse structure and therefore only needs a yes/no smell test.
|
|
123
|
+
DESTRUCTIVE_SMELL_RE = re.compile(
|
|
124
|
+
r"\b(rm|rmdir|unlink|shred|del|erase|remove-item)\b|"
|
|
125
|
+
r"find\s+\S.*-delete|"
|
|
126
|
+
r"git\b[^\n|;&]*\b(clean|reset|restore|checkout|push)\b|mkfs\b",
|
|
127
|
+
re.IGNORECASE,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
# --------------------------------------------------------------------- types
|
|
131
|
+
|
|
132
|
+
KIND_OTHER = "other" # not destructive (or not recognized)
|
|
133
|
+
KIND_FS_DELETE = "fs-delete" # rm family
|
|
134
|
+
KIND_GIT_CLEAN = "git-clean" # git clean -f...
|
|
135
|
+
KIND_GIT_RESET_HARD = "git-reset-hard" # git reset --hard
|
|
136
|
+
KIND_GIT_DISCARD = "git-discard" # git restore <path> / git checkout -- <path>
|
|
137
|
+
KIND_GIT_PUSH_FORCE = "git-push-force" # force / mirror / ref-deletion push
|
|
138
|
+
KIND_UNKNOWN = "unknown" # destructive smell, no parseable shape
|
|
139
|
+
|
|
140
|
+
# Whole-command-line shape facts (docs/friction.md F1/F2).
|
|
141
|
+
CREATION_CMDS = {"touch", "mkdir", "cp", "mv", "install", "ln", "tee"}
|
|
142
|
+
# cmd builtins with the same shape (F2 is about "created then destroyed",
|
|
143
|
+
# which `copy x a.tmp && del a.tmp` expresses just as literally).
|
|
144
|
+
CMD_CREATION_CMDS = {"copy", "xcopy", "robocopy", "mkdir", "md", "mklink",
|
|
145
|
+
"type", "echo", "ren", "rename", "move"}
|
|
146
|
+
REDIRECT_CREATE_TOKENS = {">", ">>"}
|
|
147
|
+
# Kinds whose compensation depends on enumerating concrete targets; a target
|
|
148
|
+
# created earlier in the same line is invisible to pre-execution compensation.
|
|
149
|
+
TARGET_DEPENDENT_KINDS = {KIND_FS_DELETE, KIND_GIT_CLEAN, KIND_GIT_DISCARD}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@dataclass
|
|
153
|
+
class OpSpec:
|
|
154
|
+
"""One potentially destructive operation extracted from a command line."""
|
|
155
|
+
|
|
156
|
+
op: str # program name, e.g. 'rm', 'git'
|
|
157
|
+
kind: str # KIND_* constant
|
|
158
|
+
sub: Optional[str] = None # git subcommand when op == 'git'
|
|
159
|
+
targets: List[str] = field(default_factory=list) # raw target tokens
|
|
160
|
+
recursive: bool = False
|
|
161
|
+
force: bool = False
|
|
162
|
+
dry_run: bool = False
|
|
163
|
+
extra_flags: List[str] = field(default_factory=list) # scope letters for git clean
|
|
164
|
+
segment_index: int = 0 # position of this op within the command line
|
|
165
|
+
dialect: str = "posix" # lexical front end that produced this fact
|
|
166
|
+
wildcard: bool = False # any target contains glob syntax
|
|
167
|
+
undeterminable: bool = False # effect cannot be determined statically
|
|
168
|
+
shape: Optional[str] = None # 'F1' | 'F2': compound-command shape facts
|
|
169
|
+
notes: List[str] = field(default_factory=list)
|
|
170
|
+
|
|
171
|
+
def note(self, text: str) -> None:
|
|
172
|
+
if text not in self.notes:
|
|
173
|
+
self.notes.append(text)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass
|
|
177
|
+
class PathSpec:
|
|
178
|
+
"""One explicit deletion target with resolved boundary facts."""
|
|
179
|
+
|
|
180
|
+
raw: str
|
|
181
|
+
resolved: Optional[str] = None # lexically normalized absolute path
|
|
182
|
+
wildcard: bool = False
|
|
183
|
+
indeterminable: bool = False # contains $, `, ( in direct API
|
|
184
|
+
exists: bool = False
|
|
185
|
+
is_symlink: bool = False
|
|
186
|
+
is_dir: bool = False
|
|
187
|
+
is_file: bool = False
|
|
188
|
+
link_target: Optional[str] = None # realpath when is_symlink
|
|
189
|
+
inside_workspace: bool = False
|
|
190
|
+
inside_trash: bool = False
|
|
191
|
+
protected: Optional[str] = None # None | ancestor-root | workspace-root
|
|
192
|
+
# | outside-workspace | git-metadata
|
|
193
|
+
error: Optional[str] = None
|
|
194
|
+
|
|
195
|
+
# ------------------------------------------------------------- path analysis
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _has_glob(text: str) -> bool:
|
|
199
|
+
return any(c in text for c in GLOB_CHARS)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _has_indeterminacy(text: str) -> bool:
|
|
203
|
+
return any(c in text for c in INDETERMINACY_CHARS) or "(" in text
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def inside_path(path: str, root: str) -> bool:
|
|
207
|
+
"""True when path is root or lies under root (both absolute, same form).
|
|
208
|
+
|
|
209
|
+
Lexical by design - the caller decides whether the two sides are
|
|
210
|
+
lexical or physical. Comparing a lexical path against a physical root
|
|
211
|
+
(or vice versa) is the F9 macOS bug; see `_physical`.
|
|
212
|
+
"""
|
|
213
|
+
try:
|
|
214
|
+
return os.path.commonpath([path, root]) == root
|
|
215
|
+
except ValueError: # pragma: no cover - mixed abs/rel or exotic roots
|
|
216
|
+
return False
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _physical(path: str) -> str:
|
|
220
|
+
"""``realpath``-normalized comparison form of a path (F8/F9).
|
|
221
|
+
|
|
222
|
+
Boundary analysis puts BOTH sides through this one function so they can
|
|
223
|
+
never diverge again: realpath resolves symlinks and ``..`` segments (an
|
|
224
|
+
unresolved ``/a/link/../b`` does not even mean what its own prefix
|
|
225
|
+
says), and normpath canonicalizes the result the way the workspace root
|
|
226
|
+
already was.
|
|
227
|
+
|
|
228
|
+
`PathSpec.resolved` deliberately stays lexical for every other use
|
|
229
|
+
(relocation, restore, messages).
|
|
230
|
+
"""
|
|
231
|
+
return os.path.normpath(os.path.realpath(path))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _physical_keep_final(path: str) -> str:
|
|
235
|
+
"""Physical form of a path whose FINAL component must not be resolved.
|
|
236
|
+
|
|
237
|
+
`_physical` resolves every symlink, which is right for boundary
|
|
238
|
+
questions ("does this path live under the workspace?") but wrong for
|
|
239
|
+
LAYOUT reconstruction: a target that IS a symlink would otherwise be
|
|
240
|
+
stored under its link target's position, so `restore` could no longer
|
|
241
|
+
put the link itself back. Resolve the parent chain - that is where the
|
|
242
|
+
macOS spelling divergence lives - and keep the last name verbatim.
|
|
243
|
+
"""
|
|
244
|
+
abspath = os.path.normpath(os.path.abspath(path))
|
|
245
|
+
parent, name = os.path.split(abspath)
|
|
246
|
+
if not name: # filesystem root
|
|
247
|
+
return abspath
|
|
248
|
+
return os.path.join(os.path.realpath(parent), name)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def workspace_boundary_root(workspace: str) -> str:
|
|
252
|
+
"""Physical form of a workspace root, for callers that compare roots."""
|
|
253
|
+
return _physical(os.path.normpath(os.path.abspath(workspace)))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def discover_workspace(start_dir: str) -> str:
|
|
257
|
+
"""Nearest ancestor (or start itself) containing .git; else start_dir.
|
|
258
|
+
|
|
259
|
+
AGENT_GUARD_WORKSPACE overrides discovery entirely - harness adapters
|
|
260
|
+
that already know the workspace should set it.
|
|
261
|
+
|
|
262
|
+
The result is realpath-resolved (F8): on macOS, /var is a symlink to
|
|
263
|
+
/private/var, so an unresolved root string never matches the physical
|
|
264
|
+
cwd that child processes report - every target would look out of
|
|
265
|
+
bounds. Target paths stay LEXICAL by design; only the boundary root
|
|
266
|
+
gets physicalized.
|
|
267
|
+
"""
|
|
268
|
+
resolve = lambda pth: os.path.realpath(os.path.normpath(os.path.abspath(pth)))
|
|
269
|
+
env = os.environ.get("AGENT_GUARD_WORKSPACE")
|
|
270
|
+
if env:
|
|
271
|
+
return resolve(env)
|
|
272
|
+
cur = os.path.normpath(os.path.abspath(start_dir))
|
|
273
|
+
while True:
|
|
274
|
+
marker = os.path.join(cur, ".git")
|
|
275
|
+
if os.path.exists(marker): # dir (normal repo) or file (worktree)
|
|
276
|
+
return resolve(cur)
|
|
277
|
+
parent = os.path.dirname(cur)
|
|
278
|
+
if parent == cur:
|
|
279
|
+
return resolve(start_dir)
|
|
280
|
+
cur = parent
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def classify_paths(
|
|
284
|
+
raw_paths: List[str],
|
|
285
|
+
base_dir: str,
|
|
286
|
+
workspace: str,
|
|
287
|
+
trash_root: Optional[str] = None,
|
|
288
|
+
) -> List[PathSpec]:
|
|
289
|
+
"""Resolve explicit deletion targets into boundary facts (safe_delete path).
|
|
290
|
+
|
|
291
|
+
Boundary checks are lexical: `..` escapes are caught, and a symlink is
|
|
292
|
+
judged by the location of the link itself, never by its target - deleting
|
|
293
|
+
a link does not touch what it points to.
|
|
294
|
+
"""
|
|
295
|
+
workspace = _physical(os.path.normpath(os.path.abspath(workspace)))
|
|
296
|
+
specs: List[PathSpec] = []
|
|
297
|
+
for raw in raw_paths:
|
|
298
|
+
spec = PathSpec(raw=raw)
|
|
299
|
+
text = raw.strip()
|
|
300
|
+
if not text:
|
|
301
|
+
spec.error = "empty path"
|
|
302
|
+
specs.append(spec)
|
|
303
|
+
continue
|
|
304
|
+
spec.wildcard = _has_glob(text)
|
|
305
|
+
if _is_windows_absolute(text):
|
|
306
|
+
# NOT host-relative and NOT resolvable here: mapping `C:/x` onto
|
|
307
|
+
# the POSIX workspace would invent a containment fact. The
|
|
308
|
+
# dialect layer reports an absolute Windows path as outside the
|
|
309
|
+
# POSIX workspace boundary - fail closed, never a false ALLOW.
|
|
310
|
+
spec.resolved = text
|
|
311
|
+
spec.protected = "outside-workspace"
|
|
312
|
+
specs.append(spec)
|
|
313
|
+
continue
|
|
314
|
+
if _has_indeterminacy(text):
|
|
315
|
+
spec.indeterminable = True
|
|
316
|
+
spec.error = "variables/substitution are not allowed in the direct path API"
|
|
317
|
+
specs.append(spec)
|
|
318
|
+
continue
|
|
319
|
+
expanded = os.path.expanduser(text)
|
|
320
|
+
absolute = (
|
|
321
|
+
os.path.normpath(os.path.abspath(expanded))
|
|
322
|
+
if os.path.isabs(expanded)
|
|
323
|
+
else os.path.normpath(os.path.abspath(os.path.join(base_dir, expanded)))
|
|
324
|
+
)
|
|
325
|
+
spec.resolved = absolute
|
|
326
|
+
spec.exists = os.path.lexists(absolute)
|
|
327
|
+
spec.is_symlink = os.path.islink(absolute)
|
|
328
|
+
if spec.is_symlink:
|
|
329
|
+
spec.link_target = os.path.realpath(absolute)
|
|
330
|
+
elif os.path.isdir(absolute):
|
|
331
|
+
spec.is_dir = True
|
|
332
|
+
elif os.path.isfile(absolute):
|
|
333
|
+
spec.is_file = True
|
|
334
|
+
# Boundary facts are resolved PHYSICALLY on BOTH sides (F9): the
|
|
335
|
+
# target is physicalized for the containment comparison only, while
|
|
336
|
+
# `spec.resolved` keeps the caller's LEXICAL path - compensation
|
|
337
|
+
# budget and error messages depend on the path the caller gave us.
|
|
338
|
+
# Normalizing one side alone is the macOS bug: a fixture that runs
|
|
339
|
+
# under a symlinked directory (/tmp -> /private/tmp, /var/folders
|
|
340
|
+
# -> /private/var/folders) lexically shares no prefix with the
|
|
341
|
+
# physicalized workspace root, so every in-workspace target was
|
|
342
|
+
# reported BLOCK_OUT_OF_WORKSPACE. Symbolic links the target *ends*
|
|
343
|
+
# at are physicalized too, exactly as the workspace root already was
|
|
344
|
+
# (F8): the old comparison was asymmetrically physical anyway.
|
|
345
|
+
physical = _physical(absolute)
|
|
346
|
+
spec.inside_workspace = inside_path(physical, workspace)
|
|
347
|
+
trash_physical = None
|
|
348
|
+
if trash_root:
|
|
349
|
+
trash_physical = _physical(os.path.normpath(trash_root))
|
|
350
|
+
spec.inside_trash = inside_path(physical, trash_physical)
|
|
351
|
+
# Both spellings are checked: the caller's lexical path and the
|
|
352
|
+
# physicalized one. On macOS `/tmp` resolves to `/private/tmp`, so a
|
|
353
|
+
# physical-only test would miss the root the user actually named.
|
|
354
|
+
if (protected_ancestor_root(absolute)
|
|
355
|
+
or protected_ancestor_root(physical)):
|
|
356
|
+
# Before every other boundary rule: a system root is refused
|
|
357
|
+
# because of what it *is*, not because of where the workspace
|
|
358
|
+
# happens to sit. Hard boundary - never askable.
|
|
359
|
+
spec.protected = "ancestor-root"
|
|
360
|
+
elif physical == workspace or physical == trash_physical:
|
|
361
|
+
# Anchored at a boundary root itself: a workspace root and the
|
|
362
|
+
# quarantine centre are both "the root of their tree", never
|
|
363
|
+
# content. `rm -rf .` stays a hard BLOCK. (When no trash_root is
|
|
364
|
+
# given, trash_physical is None and cannot match a real path.)
|
|
365
|
+
spec.protected = "workspace-root"
|
|
366
|
+
elif not spec.inside_workspace:
|
|
367
|
+
spec.protected = "outside-workspace"
|
|
368
|
+
else:
|
|
369
|
+
rel = os.path.relpath(physical, workspace)
|
|
370
|
+
if any(part == ".git" for part in rel.split(os.sep)):
|
|
371
|
+
spec.protected = "git-metadata"
|
|
372
|
+
specs.append(spec)
|
|
373
|
+
return specs
|
|
374
|
+
|
|
375
|
+
# ----------------------------------------------------------- shell parsing
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _split_segments(tokens: List[str]) -> List[List[str]]:
|
|
379
|
+
segments: List[List[str]] = [[]]
|
|
380
|
+
for tok in tokens:
|
|
381
|
+
if tok in SEPARATORS:
|
|
382
|
+
segments.append([])
|
|
383
|
+
else:
|
|
384
|
+
segments[-1].append(tok)
|
|
385
|
+
out: List[List[str]] = []
|
|
386
|
+
for seg in segments:
|
|
387
|
+
# Subshell/grouping parens attach to adjacent words under shlex
|
|
388
|
+
# ((rm -rf x) tokenizes as ['(rm', '-rf', 'x)']); strip them from
|
|
389
|
+
# segment edges so the dispatcher sees the real command head.
|
|
390
|
+
while seg and seg[0][:1] in ("(", "{"):
|
|
391
|
+
seg[0] = seg[0][1:]
|
|
392
|
+
if not seg[0]:
|
|
393
|
+
seg.pop(0)
|
|
394
|
+
while seg and seg[-1][-1:] in (")", "}"):
|
|
395
|
+
seg[-1] = seg[-1][:-1]
|
|
396
|
+
if not seg[-1]:
|
|
397
|
+
seg.pop()
|
|
398
|
+
if seg:
|
|
399
|
+
out.append(seg)
|
|
400
|
+
return out
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _basename(path: str) -> str:
|
|
404
|
+
return os.path.basename(path)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
_ENV_ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*\Z", re.DOTALL)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _unknown_op(note: str, target: str = "") -> OpSpec:
|
|
411
|
+
"""Return a redacted, fail-closed fact for an opaque shell effect."""
|
|
412
|
+
spec = OpSpec(op="<opaque>", kind=KIND_UNKNOWN, undeterminable=True)
|
|
413
|
+
if target:
|
|
414
|
+
spec.targets = [target[:200]]
|
|
415
|
+
spec.note(note)
|
|
416
|
+
return spec
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _has_active_shell_substitution(text: str) -> bool:
|
|
420
|
+
"""Detect executable substitution while respecting POSIX quoting."""
|
|
421
|
+
quote = None
|
|
422
|
+
escaped = False
|
|
423
|
+
for index, char in enumerate(text):
|
|
424
|
+
if escaped:
|
|
425
|
+
escaped = False
|
|
426
|
+
continue
|
|
427
|
+
if char == "\\" and quote != "'":
|
|
428
|
+
escaped = True
|
|
429
|
+
continue
|
|
430
|
+
if quote == "'":
|
|
431
|
+
if char == "'":
|
|
432
|
+
quote = None
|
|
433
|
+
continue
|
|
434
|
+
if char == "'" and quote is None:
|
|
435
|
+
quote = "'"
|
|
436
|
+
continue
|
|
437
|
+
if char == '"':
|
|
438
|
+
quote = None if quote == '"' else '"'
|
|
439
|
+
continue
|
|
440
|
+
following = text[index + 1:index + 2]
|
|
441
|
+
if char == "`" or (char == "$" and following == "(") or \
|
|
442
|
+
(char in "<>" and following == "("):
|
|
443
|
+
return True
|
|
444
|
+
return False
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _consume_prefix_options(tokens: List[str], no_arg: set,
|
|
448
|
+
with_arg: set,
|
|
449
|
+
attached: Tuple[str, ...] = (),
|
|
450
|
+
long_equals: Tuple[str, ...] = (),
|
|
451
|
+
assignments: bool = False,
|
|
452
|
+
stop_options: Tuple[str, ...] = (),
|
|
453
|
+
) -> Tuple[List[str], bool, bool]:
|
|
454
|
+
"""Consume wrapper options without guessing unknown option arity."""
|
|
455
|
+
rest = list(tokens)
|
|
456
|
+
while rest:
|
|
457
|
+
tok = rest[0]
|
|
458
|
+
if tok == "--":
|
|
459
|
+
return rest[1:], False, False
|
|
460
|
+
if assignments and _ENV_ASSIGNMENT_RE.fullmatch(tok):
|
|
461
|
+
rest.pop(0)
|
|
462
|
+
continue
|
|
463
|
+
if tok in stop_options:
|
|
464
|
+
return [], False, True
|
|
465
|
+
if tok in no_arg:
|
|
466
|
+
rest.pop(0)
|
|
467
|
+
continue
|
|
468
|
+
if tok in with_arg:
|
|
469
|
+
if len(rest) < 2:
|
|
470
|
+
return [], True, False
|
|
471
|
+
rest = rest[2:]
|
|
472
|
+
continue
|
|
473
|
+
if any(tok.startswith(prefix) and len(tok) > len(prefix)
|
|
474
|
+
for prefix in attached):
|
|
475
|
+
rest.pop(0)
|
|
476
|
+
continue
|
|
477
|
+
if any(tok.startswith(prefix + "=") for prefix in long_equals):
|
|
478
|
+
rest.pop(0)
|
|
479
|
+
continue
|
|
480
|
+
if tok.startswith("-") and tok != "-":
|
|
481
|
+
return rest, True, False
|
|
482
|
+
return rest, False, False
|
|
483
|
+
return rest, False, False
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _unwrap_shell_prefixes(segment: List[str]
|
|
487
|
+
) -> Tuple[List[str], bool, bool]:
|
|
488
|
+
"""Strip supported wrappers; return (command, from_xargs, ambiguous)."""
|
|
489
|
+
seg = list(segment)
|
|
490
|
+
from_xargs = False
|
|
491
|
+
while seg and _ENV_ASSIGNMENT_RE.fullmatch(seg[0]):
|
|
492
|
+
seg.pop(0)
|
|
493
|
+
|
|
494
|
+
while seg and _basename(seg[0]) in SHELL_PREFIXES:
|
|
495
|
+
head = _basename(seg.pop(0))
|
|
496
|
+
uncertain = False
|
|
497
|
+
stop_execution = False
|
|
498
|
+
if head == "env":
|
|
499
|
+
if any(tok in ("-S", "--split-string") or
|
|
500
|
+
tok.startswith("-S") or
|
|
501
|
+
tok.startswith("--split-string=") for tok in seg):
|
|
502
|
+
return seg, from_xargs, True
|
|
503
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
504
|
+
seg,
|
|
505
|
+
{"-i", "--ignore-environment", "-0", "--null"},
|
|
506
|
+
{"-u", "--unset", "-C", "--chdir", "-S", "--split-string"},
|
|
507
|
+
attached=("-u", "-C", "-S"),
|
|
508
|
+
long_equals=("--unset", "--chdir", "--split-string"),
|
|
509
|
+
assignments=True,
|
|
510
|
+
stop_options=("--help", "--version"),
|
|
511
|
+
)
|
|
512
|
+
elif head == "sudo":
|
|
513
|
+
if any(tok in ("-s", "--shell", "-i", "--login")
|
|
514
|
+
for tok in seg):
|
|
515
|
+
return seg, from_xargs, True
|
|
516
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
517
|
+
seg,
|
|
518
|
+
{"-A", "-b", "-E", "-H", "-k", "-n",
|
|
519
|
+
"-P", "-S", "--background", "--non-interactive",
|
|
520
|
+
"--preserve-env", "--remove-timestamp", "--reset-timestamp",
|
|
521
|
+
"--stdin"},
|
|
522
|
+
{"-C", "-D", "-g", "-h", "-p", "-R", "-r", "-T", "-t", "-u",
|
|
523
|
+
"--chdir", "--close-from", "--group", "--host", "--prompt",
|
|
524
|
+
"--role", "--type", "--user"},
|
|
525
|
+
attached=("-C", "-D", "-g", "-h", "-p", "-R", "-r", "-T", "-t", "-u"),
|
|
526
|
+
long_equals=("--chdir", "--close-from", "--group", "--host",
|
|
527
|
+
"--prompt", "--role", "--type", "--user"),
|
|
528
|
+
stop_options=("-e", "--edit", "-K", "-V", "-v",
|
|
529
|
+
"--help", "--validate", "--version"),
|
|
530
|
+
)
|
|
531
|
+
elif head == "nice":
|
|
532
|
+
if seg and re.fullmatch(r"-[0-9]+", seg[0]):
|
|
533
|
+
seg.pop(0)
|
|
534
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
535
|
+
seg, set(), {"-n", "--adjustment"}, attached=("-n",),
|
|
536
|
+
long_equals=("--adjustment",),
|
|
537
|
+
stop_options=("--help", "--version"))
|
|
538
|
+
elif head == "nohup":
|
|
539
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
540
|
+
seg, set(), set(), stop_options=("--help", "--version"))
|
|
541
|
+
elif head == "command":
|
|
542
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
543
|
+
seg, {"-p"}, set(), stop_options=("-v", "-V"))
|
|
544
|
+
elif head == "time":
|
|
545
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
546
|
+
seg,
|
|
547
|
+
{"-a", "-p", "-v", "--append", "--portability", "--verbose"},
|
|
548
|
+
{"-f", "-o", "--format", "--output"},
|
|
549
|
+
attached=("-f", "-o"), long_equals=("--format", "--output"),
|
|
550
|
+
stop_options=("--help", "--version"))
|
|
551
|
+
elif head == "stdbuf":
|
|
552
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
553
|
+
seg, set(),
|
|
554
|
+
{"-i", "-o", "-e", "--input", "--output", "--error"},
|
|
555
|
+
attached=("-i", "-o", "-e"),
|
|
556
|
+
long_equals=("--input", "--output", "--error"),
|
|
557
|
+
stop_options=("--help", "--version"))
|
|
558
|
+
elif head == "xargs":
|
|
559
|
+
from_xargs = True
|
|
560
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
561
|
+
seg,
|
|
562
|
+
{"-0", "-p", "-r", "-t", "-x", "--null", "--interactive",
|
|
563
|
+
"--no-run-if-empty", "--verbose", "--exit"},
|
|
564
|
+
{"-a", "-d", "-E", "-I", "-L", "-n", "-P", "-s",
|
|
565
|
+
"--arg-file", "--delimiter", "--eof", "--replace",
|
|
566
|
+
"--max-lines", "--max-args", "--max-procs", "--max-chars"},
|
|
567
|
+
attached=("-a", "-d", "-E", "-I", "-L", "-n", "-P", "-s"),
|
|
568
|
+
long_equals=("--arg-file", "--delimiter", "--eof", "--replace",
|
|
569
|
+
"--max-lines", "--max-args", "--max-procs",
|
|
570
|
+
"--max-chars"),
|
|
571
|
+
stop_options=("--help", "--show-limits", "--version"))
|
|
572
|
+
else: # exec
|
|
573
|
+
seg, uncertain, stop_execution = _consume_prefix_options(
|
|
574
|
+
seg, {"-c", "-l"}, {"-a"}, attached=("-a",))
|
|
575
|
+
if uncertain:
|
|
576
|
+
return seg, from_xargs, True
|
|
577
|
+
if stop_execution:
|
|
578
|
+
return [], from_xargs, False
|
|
579
|
+
while seg and _ENV_ASSIGNMENT_RE.fullmatch(seg[0]):
|
|
580
|
+
seg.pop(0)
|
|
581
|
+
return seg, from_xargs, False
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
# Windows path shapes, meaningful to the dialect layer on ANY host (a
|
|
585
|
+
# Linux CI run must still reason about `C:/Windows` and `/etc`-style
|
|
586
|
+
# targets arriving in a cmd line).
|
|
587
|
+
_WIN_DRIVE_RE = re.compile(r"^[A-Za-z]:")
|
|
588
|
+
_WIN_UNC_RE = re.compile(r"^(?:\\\\|//)[^/\\]+[/\\][^/\\]+")
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _is_windows_absolute(target: str) -> bool:
|
|
592
|
+
"""True for `C:/x`, `C:\\x`, UNC `\\\\server\\share\\x`, `//server/share`."""
|
|
593
|
+
return bool(_WIN_DRIVE_RE.match(target) or _WIN_UNC_RE.match(target))
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _scan_targets(spec: OpSpec) -> None:
|
|
597
|
+
for target in spec.targets:
|
|
598
|
+
if _has_glob(target):
|
|
599
|
+
spec.wildcard = True
|
|
600
|
+
if _has_indeterminacy(target):
|
|
601
|
+
spec.undeterminable = True
|
|
602
|
+
spec.note(f"target '{target}' contains variable/substitution")
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _parse_fs_delete(head: str, segment: List[str], from_xargs: bool) -> OpSpec:
|
|
606
|
+
spec = OpSpec(op=head, kind=KIND_FS_DELETE)
|
|
607
|
+
after_dd = False
|
|
608
|
+
for tok in segment[1:]:
|
|
609
|
+
if not after_dd and tok == "--":
|
|
610
|
+
after_dd = True
|
|
611
|
+
continue
|
|
612
|
+
if not after_dd and tok.startswith("-") and len(tok) > 1:
|
|
613
|
+
if tok.startswith("--"):
|
|
614
|
+
name = tok[2:]
|
|
615
|
+
if name == "recursive":
|
|
616
|
+
spec.recursive = True
|
|
617
|
+
elif name == "force":
|
|
618
|
+
spec.force = True
|
|
619
|
+
elif name in ("interactive", "verbose", "one-file-system",
|
|
620
|
+
"preserve-root", "prompt"):
|
|
621
|
+
pass # semantics-neutral for classification
|
|
622
|
+
elif name == "no-preserve-root":
|
|
623
|
+
spec.note("no-preserve-root requested")
|
|
624
|
+
else:
|
|
625
|
+
spec.undeterminable = True
|
|
626
|
+
spec.note(f"unknown flag --{name}")
|
|
627
|
+
else:
|
|
628
|
+
for ch in tok[1:]:
|
|
629
|
+
if ch in "rR":
|
|
630
|
+
spec.recursive = True
|
|
631
|
+
elif ch == "f":
|
|
632
|
+
spec.force = True
|
|
633
|
+
elif ch in "vidI":
|
|
634
|
+
pass
|
|
635
|
+
else:
|
|
636
|
+
spec.undeterminable = True
|
|
637
|
+
spec.note(f"unknown flag -{ch}")
|
|
638
|
+
continue
|
|
639
|
+
spec.targets.append(tok)
|
|
640
|
+
if from_xargs:
|
|
641
|
+
spec.undeterminable = True
|
|
642
|
+
spec.note("target list arrives via stdin (xargs)")
|
|
643
|
+
_scan_targets(spec)
|
|
644
|
+
return spec
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _parse_windows_delete(head: str, segment: List[str]) -> OpSpec:
|
|
648
|
+
"""A Windows delete verb seen on a non-Windows dialect.
|
|
649
|
+
|
|
650
|
+
`del /s /q build` lexed by the POSIX lexer yields `/s` and `/q` as
|
|
651
|
+
ordinary words; treating them as filenames would relocate two files
|
|
652
|
+
that do not exist and let `build` through unguarded. cmd spells its
|
|
653
|
+
switches with `/`, so they are recognised here, and `rd`/`rmdir`
|
|
654
|
+
remove a tree the way `rm -r` does.
|
|
655
|
+
|
|
656
|
+
This exists because the default dialect is posix: a harness that never
|
|
657
|
+
set AGENT_GUARD_DIALECT would otherwise hand every `del`/`rd`/`erase`
|
|
658
|
+
through untouched - no verdict, no audit record.
|
|
659
|
+
"""
|
|
660
|
+
spec = OpSpec(op=head, kind=KIND_FS_DELETE)
|
|
661
|
+
for tok in segment[1:]:
|
|
662
|
+
low = tok.lower()
|
|
663
|
+
if low in ("/s", "/q", "/f", "/a", "/p"):
|
|
664
|
+
if low == "/s":
|
|
665
|
+
spec.recursive = True
|
|
666
|
+
elif low == "/q":
|
|
667
|
+
spec.force = True
|
|
668
|
+
continue
|
|
669
|
+
if tok == "--":
|
|
670
|
+
continue
|
|
671
|
+
if tok.startswith("-") and len(tok) > 1:
|
|
672
|
+
for ch in tok[1:]:
|
|
673
|
+
if ch in "rR":
|
|
674
|
+
spec.recursive = True
|
|
675
|
+
elif ch == "f":
|
|
676
|
+
spec.force = True
|
|
677
|
+
else:
|
|
678
|
+
spec.undeterminable = True
|
|
679
|
+
spec.note(f"unknown flag -{ch}")
|
|
680
|
+
continue
|
|
681
|
+
spec.targets.append(tok)
|
|
682
|
+
if head in ("rd", "rmdir", "ri"):
|
|
683
|
+
# `rd`/`rmdir` only ever remove directories; on cmd a bare
|
|
684
|
+
# `rd build` is already a tree removal. `ri` is the PowerShell
|
|
685
|
+
# alias for Remove-Item.
|
|
686
|
+
spec.recursive = True
|
|
687
|
+
spec.note("windows delete verb on %s dialect" % (spec.dialect or "posix"))
|
|
688
|
+
_scan_targets(spec)
|
|
689
|
+
return spec
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _normalize_windows_separators(cmd: str) -> str:
|
|
693
|
+
r"""Turn a backslash into a slash so `del build\o.js` survives POSIX.
|
|
694
|
+
|
|
695
|
+
`shlex.split(..., posix=True)` treats `\` as an escape and silently
|
|
696
|
+
yields `buildo.js` - one wrong filename instead of a path. Only the
|
|
697
|
+
segment following a Windows delete verb is rewritten, and only on a
|
|
698
|
+
non-Windows host, matching `_classify_windows_dialect`: separation is a
|
|
699
|
+
host concern, not a dialect concern.
|
|
700
|
+
"""
|
|
701
|
+
if os.name == "nt":
|
|
702
|
+
return cmd
|
|
703
|
+
return cmd.replace("\\", "/")
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _parse_find(segment: List[str]) -> OpSpec:
|
|
707
|
+
rest = segment[1:]
|
|
708
|
+
spec = OpSpec(op="find", kind=KIND_OTHER, targets=rest[:1])
|
|
709
|
+
for i, tok in enumerate(rest):
|
|
710
|
+
if tok == "-delete":
|
|
711
|
+
spec.kind = KIND_FS_DELETE
|
|
712
|
+
spec.recursive = True
|
|
713
|
+
spec.undeterminable = True
|
|
714
|
+
spec.note("find -delete: matched set depends on predicates")
|
|
715
|
+
break
|
|
716
|
+
if tok in ("-exec", "-execdir"):
|
|
717
|
+
nxt = rest[i + 1] if i + 1 < len(rest) else ""
|
|
718
|
+
if _basename(nxt) in {"rm", "sh", "bash", "xargs"}:
|
|
719
|
+
spec.kind = KIND_FS_DELETE
|
|
720
|
+
spec.recursive = True
|
|
721
|
+
spec.undeterminable = True
|
|
722
|
+
spec.note("find -exec rm: matched set depends on predicates")
|
|
723
|
+
break
|
|
724
|
+
return spec
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _parse_git(segment: List[str]) -> OpSpec:
|
|
728
|
+
tokens = segment[1:]
|
|
729
|
+
global_uncertainty: List[str] = []
|
|
730
|
+
while tokens and tokens[0].startswith("-"):
|
|
731
|
+
tok = tokens.pop(0)
|
|
732
|
+
if tok in ("--no-pager", "--paginate", "-P"):
|
|
733
|
+
continue
|
|
734
|
+
if tok in ("-C", "-c", "--git-dir", "--work-tree", "--namespace",
|
|
735
|
+
"--config-env", "--exec-path"):
|
|
736
|
+
if tokens:
|
|
737
|
+
tokens.pop(0)
|
|
738
|
+
global_uncertainty.append(tok)
|
|
739
|
+
continue
|
|
740
|
+
if (tok.startswith("-C") and tok != "-C") or \
|
|
741
|
+
(tok.startswith("-c") and tok != "-c"):
|
|
742
|
+
global_uncertainty.append(tok[:2])
|
|
743
|
+
continue
|
|
744
|
+
if any(tok.startswith(name + "=") for name in
|
|
745
|
+
("--git-dir", "--work-tree", "--namespace", "--config-env",
|
|
746
|
+
"--exec-path")):
|
|
747
|
+
global_uncertainty.append(tok.split("=", 1)[0])
|
|
748
|
+
continue
|
|
749
|
+
global_uncertainty.append("unknown global option")
|
|
750
|
+
break
|
|
751
|
+
destructive_subcommands = {"clean", "reset", "restore", "checkout", "push"}
|
|
752
|
+
if global_uncertainty and (not tokens or
|
|
753
|
+
tokens[0] not in destructive_subcommands):
|
|
754
|
+
for offset, token in enumerate(tokens):
|
|
755
|
+
if token in destructive_subcommands:
|
|
756
|
+
tokens = tokens[offset:]
|
|
757
|
+
break
|
|
758
|
+
sub = tokens[0] if tokens else ""
|
|
759
|
+
rest = tokens[1:]
|
|
760
|
+
spec = OpSpec(op="git", kind=KIND_OTHER, sub=sub)
|
|
761
|
+
|
|
762
|
+
def apply_global_uncertainty() -> None:
|
|
763
|
+
if global_uncertainty:
|
|
764
|
+
spec.undeterminable = True
|
|
765
|
+
spec.note("git global options may change repository context: " +
|
|
766
|
+
", ".join(global_uncertainty[:4]))
|
|
767
|
+
|
|
768
|
+
if sub == "clean":
|
|
769
|
+
spec.kind = KIND_GIT_CLEAN
|
|
770
|
+
dry = False
|
|
771
|
+
force = False
|
|
772
|
+
force_count = 0
|
|
773
|
+
after_dd = False
|
|
774
|
+
idx = 0
|
|
775
|
+
while idx < len(rest):
|
|
776
|
+
tok = rest[idx]
|
|
777
|
+
idx += 1
|
|
778
|
+
if not after_dd and tok == "--":
|
|
779
|
+
after_dd = True
|
|
780
|
+
continue
|
|
781
|
+
if not after_dd and tok.startswith("--"):
|
|
782
|
+
name = tok[2:].split("=")[0]
|
|
783
|
+
if name == "force":
|
|
784
|
+
force = True
|
|
785
|
+
force_count += 1
|
|
786
|
+
elif name == "dry-run":
|
|
787
|
+
dry = True
|
|
788
|
+
elif name == "directory":
|
|
789
|
+
spec.extra_flags.append("-d")
|
|
790
|
+
elif name == "ignored":
|
|
791
|
+
spec.extra_flags.append("-x")
|
|
792
|
+
elif name == "quiet":
|
|
793
|
+
pass
|
|
794
|
+
elif name == "exclude":
|
|
795
|
+
spec.undeterminable = True
|
|
796
|
+
spec.note("git clean exclude patterns are not safely mirrored")
|
|
797
|
+
if "=" not in tok:
|
|
798
|
+
idx += 1 # --exclude <pattern> consumes an argument
|
|
799
|
+
else:
|
|
800
|
+
spec.undeterminable = True
|
|
801
|
+
spec.note(f"unknown git clean flag --{name}")
|
|
802
|
+
continue
|
|
803
|
+
if not after_dd and tok.startswith("-") and len(tok) > 1:
|
|
804
|
+
for ch in tok[1:]:
|
|
805
|
+
if ch == "n":
|
|
806
|
+
dry = True
|
|
807
|
+
elif ch == "f":
|
|
808
|
+
force = True
|
|
809
|
+
force_count += 1
|
|
810
|
+
elif ch == "d":
|
|
811
|
+
spec.extra_flags.append("-d")
|
|
812
|
+
elif ch == "x":
|
|
813
|
+
spec.extra_flags.append("-x")
|
|
814
|
+
elif ch == "X":
|
|
815
|
+
spec.extra_flags.append("-X")
|
|
816
|
+
elif ch == "q":
|
|
817
|
+
pass
|
|
818
|
+
elif ch == "i":
|
|
819
|
+
spec.undeterminable = True
|
|
820
|
+
spec.note("interactive git clean selection")
|
|
821
|
+
elif ch == "e":
|
|
822
|
+
spec.undeterminable = True
|
|
823
|
+
spec.note("git clean exclude patterns are not safely mirrored")
|
|
824
|
+
else:
|
|
825
|
+
spec.undeterminable = True
|
|
826
|
+
spec.note(f"unknown git clean flag -{ch}")
|
|
827
|
+
continue
|
|
828
|
+
spec.targets.append(tok)
|
|
829
|
+
spec.dry_run = dry
|
|
830
|
+
spec.force = force and not dry
|
|
831
|
+
if force_count > 1:
|
|
832
|
+
spec.undeterminable = True
|
|
833
|
+
spec.note("double-force git clean may remove nested repositories")
|
|
834
|
+
if not spec.targets and not spec.force and not dry:
|
|
835
|
+
spec.dry_run = True # git clean without -f is a dry run anyway
|
|
836
|
+
_scan_targets(spec)
|
|
837
|
+
apply_global_uncertainty()
|
|
838
|
+
return spec
|
|
839
|
+
|
|
840
|
+
if sub == "reset":
|
|
841
|
+
if "--hard" in rest:
|
|
842
|
+
spec.kind = KIND_GIT_RESET_HARD
|
|
843
|
+
spec.force = True
|
|
844
|
+
spec.targets = [
|
|
845
|
+
t for t in rest if t != "--hard" and not t.startswith("-")
|
|
846
|
+
]
|
|
847
|
+
if not spec.targets:
|
|
848
|
+
spec.note("whole-tree reset (no path limit)")
|
|
849
|
+
apply_global_uncertainty()
|
|
850
|
+
return spec
|
|
851
|
+
|
|
852
|
+
if sub == "restore":
|
|
853
|
+
staged_only = ("--staged" in rest or "-S" in rest) and (
|
|
854
|
+
"--worktree" not in rest and "-W" not in rest
|
|
855
|
+
)
|
|
856
|
+
if staged_only:
|
|
857
|
+
spec.note("staged-only restore does not touch working tree files")
|
|
858
|
+
apply_global_uncertainty()
|
|
859
|
+
return spec # kind stays OTHER
|
|
860
|
+
if "-p" in rest or "--patch" in rest:
|
|
861
|
+
spec.kind = KIND_GIT_DISCARD
|
|
862
|
+
spec.undeterminable = True
|
|
863
|
+
spec.note("interactive patch selection")
|
|
864
|
+
apply_global_uncertainty()
|
|
865
|
+
return spec
|
|
866
|
+
spec.kind = KIND_GIT_DISCARD
|
|
867
|
+
spec.targets = [t for t in rest if not t.startswith("-") or t == "--"]
|
|
868
|
+
spec.targets = [t for t in spec.targets if t != "--"]
|
|
869
|
+
_scan_targets(spec)
|
|
870
|
+
apply_global_uncertainty()
|
|
871
|
+
return spec
|
|
872
|
+
|
|
873
|
+
if sub == "checkout":
|
|
874
|
+
if "--" in rest:
|
|
875
|
+
spec.kind = KIND_GIT_DISCARD
|
|
876
|
+
spec.targets = rest[rest.index("--") + 1:]
|
|
877
|
+
_scan_targets(spec)
|
|
878
|
+
elif "-p" in rest or "--patch" in rest:
|
|
879
|
+
spec.kind = KIND_GIT_DISCARD
|
|
880
|
+
spec.undeterminable = True
|
|
881
|
+
spec.note("interactive patch selection")
|
|
882
|
+
apply_global_uncertainty()
|
|
883
|
+
return spec
|
|
884
|
+
|
|
885
|
+
if sub == "push":
|
|
886
|
+
destructive: List[str] = []
|
|
887
|
+
for tok in rest:
|
|
888
|
+
if not tok.startswith("-"):
|
|
889
|
+
if tok.startswith(":"):
|
|
890
|
+
destructive.append(f"ref-deletion {tok}")
|
|
891
|
+
elif tok.startswith("+"):
|
|
892
|
+
destructive.append(f"force-refspec {tok}")
|
|
893
|
+
elif tok in ("--force", "-f", "--mirror", "--delete", "-d"):
|
|
894
|
+
destructive.append(tok)
|
|
895
|
+
elif tok.startswith("--force-with-lease"):
|
|
896
|
+
destructive.append("--force-with-lease")
|
|
897
|
+
if destructive:
|
|
898
|
+
spec.kind = KIND_GIT_PUSH_FORCE
|
|
899
|
+
spec.force = True
|
|
900
|
+
spec.note("remote mutation: " + ", ".join(destructive[:4]))
|
|
901
|
+
apply_global_uncertainty()
|
|
902
|
+
return spec
|
|
903
|
+
|
|
904
|
+
return spec # other git subcommands are out of V1 scope
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
HEREDOC_OP_RE = re.compile(r"<<-?\s*([\"']?)([A-Za-z_][A-Za-z0-9_-]*)\1")
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
def strip_heredocs(cmd: str) -> str:
|
|
911
|
+
"""Remove heredoc bodies before classification (F5/F6).
|
|
912
|
+
|
|
913
|
+
A redirection like cat-over-heredoc writes a FILE; its body is payload
|
|
914
|
+
text, not executable syntax. Two rules keep this safe and terminating:
|
|
915
|
+
|
|
916
|
+
* the operator token is REPLACED (not retained) so the scan can never
|
|
917
|
+
re-match the same heredoc;
|
|
918
|
+
* an unterminated heredoc removes only its own operator line - later
|
|
919
|
+
command lines survive intact (the old truncating fallback once cut a
|
|
920
|
+
sed line mid-quote and manufactured the very danger it guarded
|
|
921
|
+
against).
|
|
922
|
+
"""
|
|
923
|
+
out = cmd
|
|
924
|
+
while True:
|
|
925
|
+
m = HEREDOC_OP_RE.search(out)
|
|
926
|
+
if not m:
|
|
927
|
+
return out
|
|
928
|
+
tag = m.group(2)
|
|
929
|
+
start = m.start() # cut from the operator itself
|
|
930
|
+
after = m.end()
|
|
931
|
+
nl = out.find("\n", after)
|
|
932
|
+
if nl == -1:
|
|
933
|
+
out = out[:start] + " " + out[after:]
|
|
934
|
+
continue # operator gone: no re-match possible
|
|
935
|
+
terminator = re.compile(r"^\s*" + re.escape(tag) + r"\s*$",
|
|
936
|
+
re.MULTILINE)
|
|
937
|
+
end_m = terminator.search(out, nl + 1)
|
|
938
|
+
if end_m:
|
|
939
|
+
# end_m was searched from nl+1, so end_m.end() is ALREADY an
|
|
940
|
+
# absolute index in out. Adding nl+1 again double-offsets the
|
|
941
|
+
# cut deep into the following command (friction F7).
|
|
942
|
+
out = out[:start] + " " + out[end_m.end():]
|
|
943
|
+
else:
|
|
944
|
+
out = out[:start] + " " + out[nl + 1:]
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _has_create_redirect(segment: List[str]) -> bool:
|
|
948
|
+
return any(tok in REDIRECT_CREATE_TOKENS for tok in segment)
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
def _apply_shape_rules(specs: List[OpSpec], cd_positions: List[int],
|
|
952
|
+
creation_positions: List[int]) -> None:
|
|
953
|
+
"""Whole-command-line restrictions (docs/friction.md F1/F2).
|
|
954
|
+
|
|
955
|
+
F1: a destructive op preceded by cd resolves against the wrong working
|
|
956
|
+
directory - compensation would enumerate/snapshot the wrong tree.
|
|
957
|
+
Applies to every destructive kind.
|
|
958
|
+
F2: a target created earlier in the same line does not exist yet at
|
|
959
|
+
interception time, so target-dependent compensation cannot cover it.
|
|
960
|
+
Position-independent compensations (reset --hard whole-tree stash,
|
|
961
|
+
force-push which is blocked anyway) are exempt.
|
|
962
|
+
Shapes are DECISION-CLASS facts, not effect-uncertainty: the operation
|
|
963
|
+
itself is well understood, only its safe automatic compensation is not.
|
|
964
|
+
Policy maps them to ASK (single-execution authorization), keeping true
|
|
965
|
+
effect-undeterminable cases on the BLOCK path.
|
|
966
|
+
"""
|
|
967
|
+
for spec in specs:
|
|
968
|
+
if spec.kind in (KIND_OTHER, KIND_UNKNOWN):
|
|
969
|
+
continue
|
|
970
|
+
idx = spec.segment_index
|
|
971
|
+
if any(pos < idx for pos in cd_positions):
|
|
972
|
+
spec.shape = "F1"
|
|
973
|
+
spec.note(
|
|
974
|
+
"destructive operation follows 'cd' within the same "
|
|
975
|
+
"command line; targets cannot be resolved against the "
|
|
976
|
+
"declared working directory")
|
|
977
|
+
if spec.kind in TARGET_DEPENDENT_KINDS and any(
|
|
978
|
+
pos < idx for pos in creation_positions):
|
|
979
|
+
spec.shape = "F2"
|
|
980
|
+
spec.note(
|
|
981
|
+
"this command line creates files before destroying "
|
|
982
|
+
"them; pre-execution compensation cannot see targets that "
|
|
983
|
+
"do not exist yet")
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def _parse_error_spec(exc: str,
|
|
987
|
+
dialect: str = dialects.DIALECT_POSIX) -> OpSpec:
|
|
988
|
+
"""One undeterminable UNKNOWN spec for an unparseable command line."""
|
|
989
|
+
spec = OpSpec(op="<unparseable>", kind=KIND_UNKNOWN, undeterminable=True,
|
|
990
|
+
dialect=dialect)
|
|
991
|
+
spec.note(f"shell parse error: {exc}")
|
|
992
|
+
return spec
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
_WINDOWS_PREFIX_RE = "|".join(sorted(SHELL_PREFIXES - {"xargs"}))
|
|
996
|
+
_WINDOWS_COMMAND_RE = re.compile(
|
|
997
|
+
r"(^|[;&|\n])\s*(?:(?:" + _WINDOWS_PREFIX_RE + r")\s+)*"
|
|
998
|
+
r"(?:del|erase|rd|ri)\b", re.IGNORECASE)
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def _posix_tokens(cmd: str) -> List[str]:
|
|
1002
|
+
"""Preserve unquoted command separators, including attached ones.
|
|
1003
|
+
|
|
1004
|
+
`shlex.split` treats newlines as whitespace and `x;rm` as one word,
|
|
1005
|
+
although Bash executes a second command. Punctuation-aware shlex keeps
|
|
1006
|
+
quoted punctuation in filenames while exposing actual operators.
|
|
1007
|
+
"""
|
|
1008
|
+
lexer = shlex.shlex(cmd, posix=True, punctuation_chars=";&|\n")
|
|
1009
|
+
lexer.whitespace_split = True
|
|
1010
|
+
lexer.whitespace = " \t\r"
|
|
1011
|
+
lexer.commenters = ""
|
|
1012
|
+
return list(lexer)
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def _classify_posix(cmd: str) -> Tuple[List[OpSpec], Optional[str]]:
|
|
1016
|
+
"""POSIX lexer with explicit shell command boundaries."""
|
|
1017
|
+
text = strip_heredocs(cmd)
|
|
1018
|
+
if "\\" in text and _WINDOWS_COMMAND_RE.search(text):
|
|
1019
|
+
# The cmd-style backslash rewrite is safe only for a standalone
|
|
1020
|
+
# Windows verb. Rewriting a compound line changes POSIX `rm a\ b`
|
|
1021
|
+
# into a different target. Refuse mixed syntax rather than inspect
|
|
1022
|
+
# bytes different from those the host shell will execute.
|
|
1023
|
+
if re.search(r"[;&|\n]", text):
|
|
1024
|
+
reason = "mixed Windows delete and POSIX command separators"
|
|
1025
|
+
return [_parse_error_spec(reason)], reason
|
|
1026
|
+
text = _normalize_windows_separators(text)
|
|
1027
|
+
try:
|
|
1028
|
+
tokens = _posix_tokens(text)
|
|
1029
|
+
except ValueError as exc:
|
|
1030
|
+
return [_parse_error_spec(str(exc))], str(exc)
|
|
1031
|
+
if not tokens:
|
|
1032
|
+
return [], None
|
|
1033
|
+
|
|
1034
|
+
# The lexer deliberately does not execute nested shell programs. A
|
|
1035
|
+
# destructive command hidden in substitution, or piped as program text
|
|
1036
|
+
# to an interpreter, has no safely enumerable target set.
|
|
1037
|
+
if (_has_active_shell_substitution(text)
|
|
1038
|
+
and DESTRUCTIVE_SMELL_RE.search(text)):
|
|
1039
|
+
return [_unknown_op(
|
|
1040
|
+
"destructive command inside shell substitution")], None
|
|
1041
|
+
if (re.search(r"\|\s*(?:/[^\s|;&]+/)?(?:sh|bash|zsh|ksh)\b", text)
|
|
1042
|
+
and DESTRUCTIVE_SMELL_RE.search(text)):
|
|
1043
|
+
return [_unknown_op("shell program arrives via stdin")], None
|
|
1044
|
+
|
|
1045
|
+
specs: List[OpSpec] = []
|
|
1046
|
+
cd_positions: List[int] = []
|
|
1047
|
+
creation_positions: List[int] = []
|
|
1048
|
+
|
|
1049
|
+
def emit(spec: OpSpec, index: int) -> None:
|
|
1050
|
+
spec.segment_index = index
|
|
1051
|
+
specs.append(spec)
|
|
1052
|
+
|
|
1053
|
+
for index, segment in enumerate(_split_segments(tokens)):
|
|
1054
|
+
seg, from_xargs, prefix_uncertain = _unwrap_shell_prefixes(segment)
|
|
1055
|
+
if prefix_uncertain:
|
|
1056
|
+
opaque = " ".join(segment)
|
|
1057
|
+
if (DESTRUCTIVE_PREFILTER_RE.search(opaque) or
|
|
1058
|
+
DESTRUCTIVE_PREFILTER_RE_WINDOWS.search(opaque)):
|
|
1059
|
+
emit(_unknown_op(
|
|
1060
|
+
"command wrapper options have ambiguous arity"), index)
|
|
1061
|
+
continue
|
|
1062
|
+
if not seg:
|
|
1063
|
+
continue
|
|
1064
|
+
head = _basename(seg[0])
|
|
1065
|
+
|
|
1066
|
+
if head == "cd":
|
|
1067
|
+
cd_positions.append(index)
|
|
1068
|
+
elif head in CREATION_CMDS or _has_create_redirect(seg):
|
|
1069
|
+
creation_positions.append(index)
|
|
1070
|
+
|
|
1071
|
+
if head in INTERPRETER_CMDS:
|
|
1072
|
+
inner = " ".join(seg[1:])
|
|
1073
|
+
if DESTRUCTIVE_SMELL_RE.search(inner):
|
|
1074
|
+
spec = OpSpec(op=head, kind=KIND_UNKNOWN, undeterminable=True,
|
|
1075
|
+
targets=[inner[:200]])
|
|
1076
|
+
spec.note("indirect shell execution with destructive smell")
|
|
1077
|
+
emit(spec, index)
|
|
1078
|
+
continue
|
|
1079
|
+
|
|
1080
|
+
if head in FS_DELETE_CMDS:
|
|
1081
|
+
emit(_parse_fs_delete(head, seg, from_xargs), index)
|
|
1082
|
+
elif head in WINDOWS_DELETE_CMDS:
|
|
1083
|
+
emit(_parse_windows_delete(head, seg), index)
|
|
1084
|
+
elif head == "find":
|
|
1085
|
+
emit(_parse_find(seg), index)
|
|
1086
|
+
elif head == "git":
|
|
1087
|
+
emit(_parse_git(seg), index)
|
|
1088
|
+
# anything else: kind OTHER, intentionally ignored by policy
|
|
1089
|
+
|
|
1090
|
+
for spec in specs:
|
|
1091
|
+
spec.dialect = dialects.DIALECT_POSIX
|
|
1092
|
+
_apply_shape_rules(specs, cd_positions, creation_positions)
|
|
1093
|
+
return [s for s in specs if s.kind != KIND_OTHER], None
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
def _attribute_targets(spec: OpSpec) -> None:
|
|
1097
|
+
"""Per-target facts (wildcard / interpolation) for a dialect op.
|
|
1098
|
+
|
|
1099
|
+
The POSIX path did this inside `_parse_fs_delete`; dialect classifiers
|
|
1100
|
+
only enumerate targets, so the shared attribution lives here. A target
|
|
1101
|
+
like `%BUILD_DIR%/x` or `$env:TEMP` is not a path the guard may
|
|
1102
|
+
resolve, and a target like `*.log` is a set the *tool* expands - both
|
|
1103
|
+
must reach policy as uncertainty, never as a filename.
|
|
1104
|
+
"""
|
|
1105
|
+
for target in spec.targets:
|
|
1106
|
+
if _has_glob(target):
|
|
1107
|
+
spec.wildcard = True
|
|
1108
|
+
if dialects.has_interpolation(target):
|
|
1109
|
+
spec.undeterminable = True
|
|
1110
|
+
spec.note(f"target '{target}' contains variable/substitution")
|
|
1111
|
+
|
|
1112
|
+
|
|
1113
|
+
def _classify_windows_dialect(cmd: str, dialect: str
|
|
1114
|
+
) -> Tuple[List[OpSpec], Optional[str]]:
|
|
1115
|
+
"""Native Windows dialects: lex, map effects, then shared annotations.
|
|
1116
|
+
|
|
1117
|
+
Rewriting the path separators before classification is what makes the
|
|
1118
|
+
existing POSIX boundary/glob machinery work unchanged: on Linux a naive
|
|
1119
|
+
`deploy\build` is one filename, so the boundary check would silently
|
|
1120
|
+
treat a Windows tree as a file inside the workspace. Host-native
|
|
1121
|
+
commands keep their separators - the running host already resolves
|
|
1122
|
+
them.
|
|
1123
|
+
|
|
1124
|
+
Shape rules (docs/friction.md F1/F2) apply to Windows lines too: `cd`
|
|
1125
|
+
and the interpreter prefix set are shared shell concepts, so F1 means
|
|
1126
|
+
the same thing in cmd and PowerShell.
|
|
1127
|
+
"""
|
|
1128
|
+
stream = dialects.tokenize(cmd, dialect)
|
|
1129
|
+
if not stream.ok:
|
|
1130
|
+
return [_parse_error_spec(stream.error or "parse error", dialect)], \
|
|
1131
|
+
stream.error
|
|
1132
|
+
specs = dialects.classify_stream(stream)
|
|
1133
|
+
cd_positions: List[int] = []
|
|
1134
|
+
creation_positions: List[int] = []
|
|
1135
|
+
for index, segment in enumerate(stream.segments):
|
|
1136
|
+
head = _basename(segment[0]).lower()
|
|
1137
|
+
if head in ("cd", "chdir", "set-location", "sl", "pushd", "popd"):
|
|
1138
|
+
cd_positions.append(index)
|
|
1139
|
+
elif (head.lower() in CREATION_CMDS
|
|
1140
|
+
or head.lower() in CMD_CREATION_CMDS
|
|
1141
|
+
or _has_create_redirect(segment)):
|
|
1142
|
+
creation_positions.append(index)
|
|
1143
|
+
for spec in specs:
|
|
1144
|
+
spec.dialect = dialect
|
|
1145
|
+
if os.name != "nt":
|
|
1146
|
+
# Path separation is a host concern, not a dialect concern:
|
|
1147
|
+
# only rewrite on a non-Windows host, where `\` is an ordinary
|
|
1148
|
+
# filename character and would defeat boundary analysis.
|
|
1149
|
+
spec.targets = [t.replace("\\", "/") for t in spec.targets]
|
|
1150
|
+
_attribute_targets(spec)
|
|
1151
|
+
_apply_shape_rules(specs, cd_positions, creation_positions)
|
|
1152
|
+
return [s for s in specs if s.kind != KIND_OTHER], None
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
def classify_command(cmd: str, dialect: str = dialects.DEFAULT_DIALECT
|
|
1156
|
+
) -> Tuple[List[OpSpec], Optional[str]]:
|
|
1157
|
+
"""Parse one shell command line into destructive OpSpecs.
|
|
1158
|
+
|
|
1159
|
+
`dialect` selects the lexical front end: `posix` (default, identical to
|
|
1160
|
+
pre-dialect behaviour), `cmd`, or `powershell`. Unknown dialect names
|
|
1161
|
+
raise ValueError rather than silently falling back to POSIX - parsing a
|
|
1162
|
+
Windows command line with the POSIX lexer is the exact failure the
|
|
1163
|
+
dialect layer exists to prevent.
|
|
1164
|
+
|
|
1165
|
+
Heredoc bodies are stripped before POSIX parsing (they are written
|
|
1166
|
+
payload, not commands - see docs/friction.md F5).
|
|
1167
|
+
|
|
1168
|
+
Returns (specs, parse_error). Segments that are not destructive are
|
|
1169
|
+
returned as kind=OTHER and ignored by policy. A parse_error (unbalanced
|
|
1170
|
+
quoting) yields one undeterminable UNKNOWN spec - fail closed.
|
|
1171
|
+
"""
|
|
1172
|
+
resolved = dialects.normalize_dialect(dialect)
|
|
1173
|
+
if resolved == dialects.DIALECT_POSIX:
|
|
1174
|
+
return _classify_posix(cmd)
|
|
1175
|
+
return _classify_windows_dialect(cmd, resolved)
|