foldscan 0.1.0__tar.gz

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.
@@ -0,0 +1,13 @@
1
+ bench/quarantine/
2
+ bench/private/
3
+ .env*
4
+ node_modules/
5
+ dist/
6
+ .venv/
7
+ __pycache__/
8
+ *.age
9
+ *.key
10
+ .pytest_cache/
11
+ .mypy_cache/
12
+ .ruff_cache/
13
+ !scanner/tests/fixtures/**/__pycache__/
foldscan-0.1.0/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.5
2
+ Name: foldscan
3
+ Version: 0.1.0
4
+ Summary: Scan what the agent will run, not what the file shows. A scanner for malicious AI-agent skills.
5
+ Project-URL: Homepage, https://site-ashy-two-46.vercel.app
6
+ Project-URL: Documentation, https://site-ashy-two-46.vercel.app/docs/
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: ai-agents,malware,sarif,scanner,security,skills
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Security
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: pydantic>=2.8
18
+ Requires-Dist: regex>=2024.7.24
19
+ Requires-Dist: rich>=13.7
20
+ Requires-Dist: ruamel-yaml>=0.18
21
+ Requires-Dist: typer>=0.12
22
+ Provides-Extra: judge
23
+ Requires-Dist: anthropic>=1.0; extra == 'judge'
24
+ Provides-Extra: ocr
25
+ Requires-Dist: pillow>=11.0; extra == 'ocr'
26
+ Requires-Dist: pytesseract>=0.3.13; extra == 'ocr'
27
+ Provides-Extra: yara
28
+ Requires-Dist: yara-python>=4.5; extra == 'yara'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # foldscan
32
+
33
+ Scan what the agent will run, not what the file shows.
34
+
35
+ foldscan is an open-source scanner for malicious AI-agent skills. Before any rule runs, it unpacks archives, removes padding, decodes layered encodings and maps look-alike letters to Latin, so a hidden command is matched the same way as a plain one.
36
+
37
+ Site and docs: https://site-ashy-two-46.vercel.app
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pipx install foldscan
43
+ ```
44
+
45
+ Optional extras: `foldscan[yara]` for YARA signatures, `foldscan[judge]` for the optional model judge, `foldscan[ocr]` for text in images.
46
+
47
+ ## Use
48
+
49
+ ```bash
50
+ foldscan scan ./my-skill --format table
51
+ foldscan scan skill.zip --format sarif --output foldscan.sarif
52
+ foldscan rules
53
+ foldscan explain FS-UNI-CONFUSABLE
54
+ ```
55
+
56
+ The target can be a skill directory, an archive or a single SKILL.md. Output formats: table, json, markdown, sarif.
57
+
58
+ Exit codes: `0` clean, `1` findings at or above `--fail-on` (default high), `2` coverage incomplete, `3` usage error, `4` feature not available, `70` internal error.
59
+
60
+ ## How it decides
61
+
62
+ - Seven stages: inventory, unpack, normalize, analyze, prose, optional judge, verdict.
63
+ - Every rule maps to an OWASP Agentic Skills Top 10 ID.
64
+ - Rules set the minimum severity. The optional model judge can raise a finding and can never lower or remove one. It is off by default, and foldscan sends nothing anywhere unless you turn it on.
65
+ - Anything that could not be analyzed is reported as incomplete coverage, never as clean.
66
+
67
+ ## What it does not claim
68
+
69
+ - Static analysis cannot prove what a remote URL serves at run time. foldscan flags the fetch.
70
+ - Heavy packing and obfuscation can defeat static analysis. Sandboxed detonation is on the roadmap.
71
+ - No findings means nothing was found in what foldscan analyzed. The coverage report lists what that was.
72
+
73
+ ## License
74
+
75
+ Apache-2.0.
@@ -0,0 +1,45 @@
1
+ # foldscan
2
+
3
+ Scan what the agent will run, not what the file shows.
4
+
5
+ foldscan is an open-source scanner for malicious AI-agent skills. Before any rule runs, it unpacks archives, removes padding, decodes layered encodings and maps look-alike letters to Latin, so a hidden command is matched the same way as a plain one.
6
+
7
+ Site and docs: https://site-ashy-two-46.vercel.app
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pipx install foldscan
13
+ ```
14
+
15
+ Optional extras: `foldscan[yara]` for YARA signatures, `foldscan[judge]` for the optional model judge, `foldscan[ocr]` for text in images.
16
+
17
+ ## Use
18
+
19
+ ```bash
20
+ foldscan scan ./my-skill --format table
21
+ foldscan scan skill.zip --format sarif --output foldscan.sarif
22
+ foldscan rules
23
+ foldscan explain FS-UNI-CONFUSABLE
24
+ ```
25
+
26
+ The target can be a skill directory, an archive or a single SKILL.md. Output formats: table, json, markdown, sarif.
27
+
28
+ Exit codes: `0` clean, `1` findings at or above `--fail-on` (default high), `2` coverage incomplete, `3` usage error, `4` feature not available, `70` internal error.
29
+
30
+ ## How it decides
31
+
32
+ - Seven stages: inventory, unpack, normalize, analyze, prose, optional judge, verdict.
33
+ - Every rule maps to an OWASP Agentic Skills Top 10 ID.
34
+ - Rules set the minimum severity. The optional model judge can raise a finding and can never lower or remove one. It is off by default, and foldscan sends nothing anywhere unless you turn it on.
35
+ - Anything that could not be analyzed is reported as incomplete coverage, never as clean.
36
+
37
+ ## What it does not claim
38
+
39
+ - Static analysis cannot prove what a remote URL serves at run time. foldscan flags the fetch.
40
+ - Heavy packing and obfuscation can defeat static analysis. Sandboxed detonation is on the roadmap.
41
+ - No findings means nothing was found in what foldscan analyzed. The coverage report lists what that was.
42
+
43
+ ## License
44
+
45
+ Apache-2.0.
@@ -0,0 +1,73 @@
1
+ [project]
2
+ name = "foldscan"
3
+ version = "0.1.0"
4
+ description = "Scan what the agent will run, not what the file shows. A scanner for malicious AI-agent skills."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ keywords = ["security", "scanner", "ai-agents", "skills", "sarif", "malware"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Environment :: Console",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Topic :: Security",
17
+ ]
18
+ dependencies = [
19
+ "pydantic>=2.8",
20
+ "typer>=0.12",
21
+ "rich>=13.7",
22
+ "ruamel.yaml>=0.18",
23
+ "regex>=2024.7.24",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ ocr = ["pytesseract>=0.3.13", "pillow>=11.0"]
28
+ judge = ["anthropic>=1.0"]
29
+ yara = [
30
+ "yara-python>=4.5",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://site-ashy-two-46.vercel.app"
35
+ Documentation = "https://site-ashy-two-46.vercel.app/docs/"
36
+
37
+ [project.scripts]
38
+ foldscan = "foldscan.cli:app"
39
+
40
+ [dependency-groups]
41
+ dev = ["pytest>=8.3", "hypothesis>=6.112", "ruff>=0.6", "mypy>=1.11"]
42
+
43
+ [build-system]
44
+ requires = ["hatchling"]
45
+ build-backend = "hatchling.build"
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ # Tests and fixtures stay out of the published archive (honeytokens, defanged payload samples).
49
+ include = ["src/foldscan", "README.md", "LICENSE", "pyproject.toml"]
50
+
51
+ [tool.hatch.build.targets.wheel]
52
+ packages = ["src/foldscan"]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
56
+
57
+ [tool.mypy]
58
+ python_version = "3.12"
59
+
60
+ [[tool.mypy.overrides]]
61
+ module = ["anthropic", "anthropic.*", "yara", "regex"]
62
+ ignore_missing_imports = true
63
+
64
+ [tool.ruff]
65
+ line-length = 120
66
+ target-version = "py312"
67
+
68
+ [tool.ruff.lint]
69
+ select = ["E", "F", "I", "B", "S", "UP"]
70
+ ignore = ["S101", "S603"]
71
+
72
+ [tool.ruff.lint.per-file-ignores]
73
+ "src/foldscan/cli.py" = ["B008"] # typer idiom
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,284 @@
1
+ """SKILL.md frontmatter and prose-structure rules. Owned by the prose rule-author (S3).
2
+
3
+ Interface: analyze_skill_md(path: str, text: str) -> list[Finding]
4
+
5
+ The frontmatter is screened for YAML tags and alias bombs before ruamel's SAFE loader sees it, and every
6
+ parser failure degrades to a finding instead of an exception. Heuristics here are raise-only or
7
+ conservative: when in doubt, a rule stays silent rather than flagging ordinary prose.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ from ruamel.yaml import YAML
15
+
16
+ from foldscan.analyze.registry import emit
17
+ from foldscan.model import Finding, Layer
18
+
19
+ MAX_FRONTMATTER_BYTES = 64 * 1024
20
+ MAX_ANCHORS_AND_ALIASES = 10
21
+
22
+ BUILTIN_COMMANDS = frozenset({
23
+ "init", "commit", "review", "compact", "clear", "config", "help", "login", "logout", "memory", "model",
24
+ "permissions", "plan", "mcp", "agents", "hooks", "doctor", "cost", "status", "resume", "bug",
25
+ "terminal-setup", "security-review",
26
+ })
27
+
28
+ # Description phrasing that claims every request or overrides other skills and built-ins.
29
+ _SHADOW_DESC = re.compile(
30
+ r"\b(?:for|on)\s+(?:every|all)\s+(?:\w+\s+)?(?:tasks?|requests?)\b"
31
+ r"|\balways\s+(?:use|invoke|run|trigger|activate)\s+(?:this|it|the\s+skill)\b"
32
+ r"|\bbefore\s+(?:any|all)\s+other\s+skills?\b"
33
+ r"|\binstead\s+of\s+(?:the\s+)?built[- ]?in\b",
34
+ re.IGNORECASE,
35
+ )
36
+ _UNRESTRICTED_BASH = frozenset({"Bash", "Bash(*)", "Bash(*:*)"})
37
+ _PERMISSION_KEYS = ("allowed-tools", "allowed_tools", "tools")
38
+ _NARROW_TASK = re.compile(r"\b(?:summari[sz]e|format|convert|lint|csv|markdown)\b", re.IGNORECASE)
39
+ _NETWORK_CMD = re.compile(r"\b(?:curl|wget)\b", re.IGNORECASE)
40
+ _URL = re.compile(r"https?://([^/\s\"'<>)`]+)", re.IGNORECASE)
41
+ _CREDENTIAL_OR_REGISTRY = re.compile(
42
+ r"~/\.(?:ssh|aws|npmrc|pypirc|netrc|git-credentials|docker/config\.json|kube/config|config/gcloud)"
43
+ r"|\.npmrc\b|\.pypirc\b|\bpip\.conf\b|\.yarnrc\b|PIP_INDEX_URL|UV_INDEX_URL|\bregistry\s*=",
44
+ re.IGNORECASE,
45
+ )
46
+ # Hosts that count as documentation for the mismatch heuristic. Matched by exact domain or subdomain only,
47
+ # so a name like docs.attacker.example does not pass.
48
+ _DOC_DOMAINS = ("python.org", "readthedocs.io", "readthedocs.org", "mozilla.org", "anthropic.com", "claude.com")
49
+ _BOUNDARY = frozenset(" \t[{,:-?")
50
+ _ANCHOR_NAME = re.compile(r"[A-Za-z0-9_-]")
51
+ _TOP_KEY = re.compile(r"^([A-Za-z_][\w-]*)[ \t]*:(.*)$")
52
+
53
+
54
+ def _is_boundary(line: str, i: int) -> bool:
55
+ return i == 0 or line[i - 1] in _BOUNDARY
56
+
57
+
58
+ def _mask_quotes(line: str) -> list[bool]:
59
+ """Mark characters that sit inside a quoted scalar or a comment.
60
+
61
+ Quotes open only at a token boundary, so an apostrophe in "don't" does not hide later text. State resets
62
+ per line, which can only over-flag, never hide a tag.
63
+ """
64
+ masked = [False] * len(line)
65
+ quote: str | None = None
66
+ i = 0
67
+ while i < len(line):
68
+ ch = line[i]
69
+ if quote is not None:
70
+ masked[i] = True
71
+ if quote == '"' and ch == "\\" and i + 1 < len(line):
72
+ masked[i + 1] = True
73
+ i += 2
74
+ continue
75
+ if ch == quote:
76
+ if quote == "'" and i + 1 < len(line) and line[i + 1] == "'":
77
+ masked[i + 1] = True
78
+ i += 2
79
+ continue
80
+ quote = None
81
+ i += 1
82
+ continue
83
+ if ch in "\"'" and _is_boundary(line, i):
84
+ quote = ch
85
+ masked[i] = True
86
+ elif ch == "#" and _is_boundary(line, i):
87
+ break
88
+ i += 1
89
+ return masked
90
+
91
+
92
+ def _line_specials(line: str) -> tuple[bool, int]:
93
+ """Return (has_tag, anchor_or_alias_count) for the unquoted part of one frontmatter line."""
94
+ masked = _mask_quotes(line)
95
+ tag = False
96
+ refs = 0
97
+ for i, ch in enumerate(line):
98
+ if masked[i] or ch not in "!&*" or not _is_boundary(line, i):
99
+ continue
100
+ if ch == "!":
101
+ before = line[:i].rstrip()
102
+ # A tag starts a node: after line start, a key colon, a sequence dash, a flow opener or an anchor.
103
+ # "Wow !" is prose, not a tag.
104
+ if not before or before[-1] in ":-[{,?" or re.search(r"&\S*$", before):
105
+ tag = True
106
+ elif i + 1 < len(line) and _ANCHOR_NAME.match(line[i + 1]):
107
+ refs += 1
108
+ return tag, refs
109
+
110
+
111
+ def _parse(fm_text: str) -> dict | None:
112
+ try:
113
+ data = YAML(typ="safe", pure=True).load(fm_text)
114
+ except Exception: # any parser failure is a finding, never a crash
115
+ return None
116
+ return data if isinstance(data, dict) else None
117
+
118
+
119
+ def _fallback_fields(fm_lines: list[str]) -> dict[str, str]:
120
+ """Top-level `key: value` pairs read line by line, used only when the YAML parse failed."""
121
+ fields: dict[str, str] = {}
122
+ for line in fm_lines:
123
+ m = _TOP_KEY.match(line)
124
+ if m and m.group(1) not in fields:
125
+ fields[m.group(1)] = m.group(2).strip().strip("\"'")
126
+ return fields
127
+
128
+
129
+ def _text(value: object) -> str:
130
+ return value.strip() if isinstance(value, str) else ""
131
+
132
+
133
+ def _key_line(fm_lines: list[str], keys: tuple[str, ...]) -> int:
134
+ """1-based line in the original file of the first top-level key, or 1 when not found."""
135
+ rx = re.compile("^(?:" + "|".join(re.escape(k) for k in keys) + r")\s*:")
136
+ for idx, line in enumerate(fm_lines):
137
+ if rx.match(line):
138
+ return idx + 2 # fm_lines[0] is file line 2
139
+ return 1
140
+
141
+
142
+ def _tool_tokens(value: object) -> list[str]:
143
+ """Split an allowed-tools value into entries, keeping commas and spaces inside parentheses."""
144
+ if isinstance(value, list):
145
+ return [str(v).strip() for v in value if str(v).strip()]
146
+ if not isinstance(value, str):
147
+ return []
148
+ tokens: list[str] = []
149
+ buf: list[str] = []
150
+ depth = 0
151
+ for ch in value.strip().strip("[]"):
152
+ if ch == "(":
153
+ depth += 1
154
+ elif ch == ")":
155
+ depth = max(0, depth - 1)
156
+ if depth == 0 and (ch == "," or ch.isspace()):
157
+ if buf:
158
+ tokens.append("".join(buf))
159
+ buf = []
160
+ else:
161
+ buf.append(ch)
162
+ if buf:
163
+ tokens.append("".join(buf))
164
+ return tokens
165
+
166
+
167
+ def _permission_reason(value: object) -> str | None:
168
+ tokens = _tool_tokens(value)
169
+ unrestricted = [t for t in tokens if t in _UNRESTRICTED_BASH]
170
+ if unrestricted:
171
+ return f"grants unrestricted shell access ({unrestricted[0]})"
172
+ if "*" in tokens:
173
+ return "grants every tool (*)"
174
+ if "WebFetch" in tokens and any(t == "Bash" or t.startswith("Bash(") for t in tokens):
175
+ return "combines WebFetch with Bash"
176
+ for t in tokens:
177
+ m = re.fullmatch(r"Write\((.*)\)", t)
178
+ if m and (m.group(1).startswith(("~", "/")) or ".." in m.group(1)):
179
+ return f"allows writes outside the skill ({t})"
180
+ return None
181
+
182
+
183
+ def _body_hit(body: list[str], first_line: int) -> tuple[int, str] | None:
184
+ """First body line that fetches from the network to a non-doc host, or reads credential/registry config."""
185
+ for idx, line in enumerate(body):
186
+ hit = bool(_NETWORK_CMD.search(line)) or _CREDENTIAL_OR_REGISTRY.search(line) is not None
187
+ for m in _URL.finditer(line):
188
+ host = m.group(1).split("@")[-1].split(":")[0].lower()
189
+ if not any(host == d or host.endswith("." + d) for d in _DOC_DOMAINS):
190
+ hit = True
191
+ if hit:
192
+ return first_line + idx, line.strip()[:160]
193
+ return None
194
+
195
+
196
+ def _missing(path: str, reason: str, line: int) -> Finding:
197
+ return emit("FS-META-MISSING", f"SKILL.md metadata problem: {reason}.", path=path, layer=Layer.META,
198
+ line=line)
199
+
200
+
201
+ def analyze_skill_md(path: str, text: str) -> list[Finding]:
202
+ out: list[Finding] = []
203
+ lines = text.lstrip("").split("\n")
204
+ if not lines or lines[0].rstrip("\r") != "---":
205
+ return [_missing(path, "no YAML frontmatter at the top of the file", 1)]
206
+ close = next((i for i in range(1, len(lines)) if lines[i].rstrip() == "---"), None)
207
+ if close is None:
208
+ return [_missing(path, "frontmatter is not closed by a '---' line", 1)]
209
+
210
+ fm_lines = lines[1:close]
211
+ fm_text = "\n".join(fm_lines)
212
+ body = lines[close + 1:]
213
+ body_first_line = close + 2 # 1-based line of body[0]
214
+
215
+ if len(fm_text.encode("utf-8", "replace")) > MAX_FRONTMATTER_BYTES:
216
+ return [emit("FS-META-UNSAFE-YAML", "Frontmatter exceeds 64 KB and was not parsed.", path=path,
217
+ layer=Layer.META, line=1)]
218
+
219
+ tag_lines: list[int] = []
220
+ ref_lines: list[int] = []
221
+ total_refs = 0
222
+ for idx, line in enumerate(fm_lines):
223
+ tag, refs = _line_specials(line)
224
+ if tag:
225
+ tag_lines.append(idx + 2)
226
+ if refs:
227
+ ref_lines.append(idx + 2)
228
+ total_refs += refs
229
+ if tag_lines or total_refs > MAX_ANCHORS_AND_ALIASES:
230
+ if tag_lines:
231
+ reason = "uses YAML tags (language-specific tags are never allowed in SKILL.md)"
232
+ at = tag_lines[0]
233
+ evidence = fm_lines[tag_lines[0] - 2].strip()
234
+ else:
235
+ reason = f"uses {total_refs} anchors and aliases (limit {MAX_ANCHORS_AND_ALIASES})"
236
+ at = ref_lines[0]
237
+ evidence = fm_lines[ref_lines[0] - 2].strip()
238
+ return [emit("FS-META-UNSAFE-YAML", f"Frontmatter {reason}. Parsing was refused.", path=path,
239
+ layer=Layer.META, line=at, evidence=evidence)]
240
+
241
+ data = _parse(fm_text)
242
+ fields: dict[str, object] = dict(data) if data is not None else dict(_fallback_fields(fm_lines))
243
+ name = _text(fields.get("name"))
244
+ desc = _text(fields.get("description"))
245
+
246
+ problems = []
247
+ if data is None:
248
+ problems.append("frontmatter could not be parsed as YAML")
249
+ missing = [k for k, v in (("name", name), ("description", desc)) if not v]
250
+ if missing:
251
+ problems.append(f"lacks {' and '.join(missing)}")
252
+ if problems:
253
+ out.append(_missing(path, "; ".join(problems), 1))
254
+
255
+ if name:
256
+ if name.lstrip("/").strip().lower() in BUILTIN_COMMANDS:
257
+ out.append(emit("FS-META-SHADOW", f"Skill name '{name}' claims a built-in Claude Code command.",
258
+ path=path, layer=Layer.META, line=_key_line(fm_lines, ("name",)), evidence=name))
259
+ if desc:
260
+ m = _SHADOW_DESC.search(desc)
261
+ if m:
262
+ out.append(emit("FS-META-SHADOW",
263
+ "Description asks to run for every request, ahead of other skills, or in place of "
264
+ "a built-in.", path=path, layer=Layer.META,
265
+ line=_key_line(fm_lines, ("description",)), evidence=desc))
266
+
267
+ for key in _PERMISSION_KEYS:
268
+ if key not in fields:
269
+ continue
270
+ why = _permission_reason(fields[key])
271
+ if why:
272
+ out.append(emit("FS-META-PERMS", f"'{key}' {why}.", path=path, layer=Layer.META,
273
+ line=_key_line(fm_lines, (key,)), evidence=str(fields[key])))
274
+
275
+ if desc and _NARROW_TASK.search(desc):
276
+ hit = _body_hit(body, body_first_line)
277
+ if hit:
278
+ at, snippet = hit
279
+ out.append(emit("FS-META-MISMATCH",
280
+ "Description claims a narrow local task, but the body fetches from the network, "
281
+ "reads credential paths or changes registry config.", path=path, layer=Layer.META,
282
+ line=at, confidence="low",
283
+ evidence=f'description: "{desc[:160]}" | body line {at}: {snippet}'))
284
+ return out