skill-drift 0.1.0__py3-none-any.whl

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,2 @@
1
+ """Offline skill package drift auditing."""
2
+ __version__ = '0.1.0'
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
skill_drift/audit.py ADDED
@@ -0,0 +1,89 @@
1
+ """Offline heuristic checks; never executes package code."""
2
+ from collections import Counter
3
+ from dataclasses import asdict, dataclass
4
+ from fnmatch import fnmatchcase
5
+ from pathlib import Path
6
+ import re
7
+ from .skills import discover, read_skill
8
+
9
+ @dataclass
10
+ class Finding:
11
+ skill: str
12
+ file: str
13
+ line: int
14
+ kind: str
15
+ claim: str
16
+ severity: str
17
+ detail: str
18
+
19
+ TOKEN = re.compile(r'`([^`\n]+)`|([^\s`<>"\']+)')
20
+ EXT = re.compile(r'\.(py|js|ts|md|json|yaml|yml|toml|sh|go|rs|txt)$')
21
+ DIR = re.compile(r'^(?:\./)?(?:scripts|references|examples|tests|docs|bin)/')
22
+
23
+
24
+ def claims(line):
25
+ for match in TOKEN.finditer(line):
26
+ token = (match[1] or match[2]).strip('()[]{}.,;:!?')
27
+ if token.startswith(('http://', 'https://', '/', '~/', '\\')) or '*' in token or re.match(r'^[A-Za-z]:[/\\]', token):
28
+ continue
29
+ if '/' in token and (EXT.search(token) or DIR.match(token)):
30
+ yield token
31
+
32
+
33
+ def audit(root, fail_on='high', ignore=(), limit=500):
34
+ root = Path(root).resolve()
35
+ packages = [read_skill(p) for p in discover(root)]
36
+ findings = []
37
+ errors = []
38
+ names = Counter(s.metadata.get('name') for s in packages if s.metadata.get('name'))
39
+ ignored = 0
40
+ seen = set()
41
+ for skill in packages:
42
+ relative = skill.directory.relative_to(root).as_posix()
43
+ if skill.error:
44
+ errors.append({'skill': relative, 'file': 'SKILL.md', 'line': 1, 'detail': skill.error})
45
+ continue
46
+ def add(line, kind, claim, severity, detail):
47
+ nonlocal ignored
48
+ key = (relative, line, kind, claim)
49
+ if key in seen:
50
+ return
51
+ seen.add(key)
52
+ if any(fnmatchcase(claim, pattern) for pattern in ignore):
53
+ ignored += 1
54
+ return
55
+ findings.append(Finding(relative, 'SKILL.md', line, kind, claim, severity, detail))
56
+ if skill.missing_frontmatter:
57
+ add(1, 'missing-frontmatter', 'frontmatter', 'HIGH', 'Expected opening --- frontmatter line')
58
+ else:
59
+ for key in ('name', 'description'):
60
+ if not skill.metadata.get(key, '').strip():
61
+ add(1, 'missing-' + key, key, 'HIGH', 'Required nonempty frontmatter field')
62
+ name = skill.metadata.get('name')
63
+ if name and name != skill.directory.name:
64
+ add(2, 'name-mismatch', name, 'MEDIUM', 'Directory name is ' + skill.directory.name)
65
+ if name and names[name] > 1:
66
+ add(2, 'duplicate-skill-name', name, 'MEDIUM', 'Name occurs in multiple skill packages')
67
+ if len(skill.body.strip()) < 50:
68
+ add(skill.body_line, 'empty-body', 'body', 'MEDIUM', 'Body is shorter than 50 characters')
69
+ for number, line in enumerate(skill.body.splitlines(), skill.body_line):
70
+ for claim in claims(line):
71
+ local = skill.directory / claim
72
+ target = local if local.exists() else root / claim
73
+ exists = target.is_dir() if claim.endswith('/') else target.exists()
74
+ if not exists:
75
+ add(number, 'referenced-file', claim, 'HIGH', 'Referenced path does not exist')
76
+ elif re.match(r'^(?:\./)?scripts/', claim) and target.is_file():
77
+ try:
78
+ shebang = target.open('rb')
79
+ with shebang:
80
+ starts = shebang.read(2) == b'#!'
81
+ if not target.stat().st_mode & 0o111 and not starts:
82
+ add(number, 'script-not-executable', claim, 'MEDIUM', 'No executable bit and no shebang')
83
+ except OSError as error:
84
+ errors.append({'skill': relative, 'file': claim, 'line': number, 'detail': str(error)})
85
+ findings.sort(key=lambda f: (f.skill, f.line, f.kind, f.claim))
86
+ # Verdict considers all findings, including those beyond the display cap.
87
+ failed = bool(errors) or any(f.severity == 'HIGH' or fail_on == 'medium' for f in findings)
88
+ code = 2 if failed else (1 if findings else 0)
89
+ return {'skills_found': len(packages), 'totals': {'kind': dict(sorted(Counter(f.kind for f in findings).items())), 'severity': dict(sorted(Counter(f.severity for f in findings).items()))}, 'findings': [asdict(f) for f in findings[:limit]], 'ignored_count': ignored, 'parse_error_count': len(errors), 'parse_errors': errors, 'truncated': len(findings) > limit, 'omitted_count': max(0, len(findings)-limit), 'verdict': ('FAIL' if code == 2 else 'WARN' if code == 1 else 'PASS'), 'exit_code': code, 'note': 'no skills found' if not packages else ''}
skill_drift/cli.py ADDED
@@ -0,0 +1,34 @@
1
+ """Command line interface."""
2
+ import argparse
3
+ import json
4
+ from . import __version__
5
+ from .audit import audit
6
+
7
+
8
+ def main(argv=None):
9
+ parser = argparse.ArgumentParser(prog='skill-drift', description='Audit skill package claims offline')
10
+ parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
11
+ commands = parser.add_subparsers(dest='command', required=True)
12
+ command = commands.add_parser('audit')
13
+ command.add_argument('path', nargs='?', default='.')
14
+ command.add_argument('--json', action='store_true')
15
+ command.add_argument('--fail-on', choices=('high', 'medium'), default='high')
16
+ command.add_argument('--ignore', action='append', default=[], metavar='G')
17
+ args = parser.parse_args(argv)
18
+ try:
19
+ report = audit(args.path, args.fail_on, args.ignore)
20
+ except (ValueError, OSError) as error:
21
+ report = {'skills_found': 0, 'totals': {'kind': {}, 'severity': {}}, 'findings': [], 'ignored_count': 0, 'parse_error_count': 1, 'parse_errors': [{'skill': '.', 'file': 'SKILL.md', 'line': 1, 'detail': str(error)}], 'truncated': False, 'omitted_count': 0, 'verdict': 'FAIL', 'exit_code': 2, 'note': ''}
22
+ if args.json:
23
+ print(json.dumps(report, sort_keys=True))
24
+ else:
25
+ print('%s: %s skills found' % (report['verdict'], report['skills_found']))
26
+ if report['note']:
27
+ print(report['note'])
28
+ for finding in report['findings']:
29
+ print('{skill}:{file}:{line}: {severity} {kind}: {claim} — {detail}'.format(**finding))
30
+ for error in report['parse_errors']:
31
+ print('{skill}:{file}:{line}: parse error: {detail}'.format(**error))
32
+ print('Totals: ' + json.dumps(report['totals'], sort_keys=True))
33
+ print('Ignored: %s; parse errors: %s; truncated: %s (omitted %s)' % (report['ignored_count'], report['parse_error_count'], report['truncated'], report['omitted_count']))
34
+ return report['exit_code']
skill_drift/skills.py ADDED
@@ -0,0 +1,81 @@
1
+ """Deterministic discovery and deliberately small frontmatter parser."""
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ import os
5
+ import re
6
+
7
+ SKIP = {'.git', 'node_modules', 'dist', '__pycache__', '.venv', 'venv'}
8
+
9
+ @dataclass
10
+ class Skill:
11
+ directory: Path
12
+ metadata: dict
13
+ body: str
14
+ body_line: int
15
+ error: str = ''
16
+ missing_frontmatter: bool = False
17
+
18
+
19
+ def discover(root):
20
+ root = Path(root)
21
+ if not root.is_dir():
22
+ raise ValueError('audit path must be an existing directory')
23
+ found = []
24
+ def walk_error(error):
25
+ raise ValueError(str(error))
26
+ for directory, dirs, files in os.walk(root, onerror=walk_error):
27
+ dirs[:] = sorted(d for d in dirs if d not in SKIP)
28
+ if 'SKILL.md' in files:
29
+ found.append(Path(directory))
30
+ return sorted(found, key=lambda p: p.relative_to(root).as_posix())
31
+
32
+
33
+ def scalar(value):
34
+ value = value.strip()
35
+ if not value:
36
+ return ''
37
+ if value[0] in "\"'":
38
+ if len(value) < 2 or value[-1] != value[0]:
39
+ raise ValueError('unterminated quoted scalar')
40
+ return value[1:-1]
41
+ if re.search(r'(^|\s)[&*!]|:\s|^[>|\[\]{}]|^[-?]\s', value):
42
+ raise ValueError('unsupported complex YAML scalar')
43
+ return value
44
+
45
+
46
+ def read_skill(directory):
47
+ directory = Path(directory)
48
+ try:
49
+ lines = (directory / 'SKILL.md').read_text(encoding='utf-8').splitlines()
50
+ if not lines or lines[0] != '---':
51
+ return Skill(directory, {}, '\n'.join(lines), 1, missing_frontmatter=True)
52
+ try:
53
+ end = lines.index('---', 1)
54
+ except ValueError:
55
+ raise ValueError('frontmatter has no closing --- line')
56
+ metadata = {}
57
+ current = None
58
+ for number, line in enumerate(lines[1:end], 2):
59
+ if not line.strip() or line.lstrip().startswith('#'):
60
+ continue
61
+ item = re.fullmatch(r'\s+-\s+(.+)', line)
62
+ if item and current:
63
+ if metadata[current] == '':
64
+ metadata[current] = []
65
+ if not isinstance(metadata[current], list):
66
+ raise ValueError('list under nonempty scalar')
67
+ metadata[current].append(scalar(item[1]))
68
+ continue
69
+ match = re.fullmatch(r'([A-Za-z_][\w-]*):\s*(.*)', line)
70
+ if not match:
71
+ raise ValueError('unsupported YAML at line %s' % number)
72
+ current = match[1]
73
+ if current in metadata:
74
+ raise ValueError('duplicate frontmatter key: ' + current)
75
+ metadata[current] = scalar(match[2])
76
+ for key in ('name', 'description'):
77
+ if key in metadata and not isinstance(metadata[key], str):
78
+ raise ValueError(key + ' must be a scalar')
79
+ return Skill(directory, metadata, '\n'.join(lines[end+1:]), end+2)
80
+ except (OSError, UnicodeError, ValueError) as error:
81
+ return Skill(directory, {}, '', 1, error=str(error))
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: skill-drift
3
+ Version: 0.1.0
4
+ Summary: Offline heuristic auditing of skill package claims
5
+ Author: skill-drift contributors
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # skill-drift
13
+
14
+ `skill-drift` 0.1.0 checks whether an agent skill package's stated paths and
15
+ basic metadata still match the disk. It is deterministic, offline, and uses
16
+ only the Python standard library at runtime: no daemon, LLM, network, or keys.
17
+ A finding means **check this claim**.
18
+
19
+ Requires Python 3.9+. Install with `pip install .`, or install a built wheel.
20
+
21
+ ```sh
22
+ skill-drift audit [path] [--json] [--fail-on high|medium] [--ignore G]
23
+ skill-drift --version
24
+ skill-drift --help
25
+ python -m skill_drift audit .
26
+ ```
27
+
28
+ Path defaults to the current directory. Repeat `--ignore` for multiple glob
29
+ patterns; patterns match the claim text, apply to all checks, and excluded
30
+ unique findings are counted as ignored.
31
+
32
+ ## Discovery and parsing
33
+
34
+ A package is any directory containing a file named exactly `SKILL.md`.
35
+ Discovery recursively includes the supplied directory itself and hidden
36
+ folders such as `.claude/skills` and `.cursor/skills`. It skips `.git`,
37
+ `node_modules`, `dist`, `__pycache__`, `.venv`, and `venv`; directory symlinks
38
+ are not traversed. No packages gives PASS, exit 0, and `no skills found`.
39
+ Unreadable or invalid UTF-8 SKILL.md files produce parse errors.
40
+
41
+ The file must begin with an exact `---` line and close its frontmatter with
42
+ another `---` line. Supported YAML is a subset: `key: value`, quoted or
43
+ unquoted scalar values, and block lists under a key. Blank lines and full-line
44
+ comments are accepted. Nested maps, anchors, tags, flow collections, multiline
45
+ scalars, duplicate keys, and malformed blocks are parse errors. Name and
46
+ description must be scalars. Quoted values are treated literally, without
47
+ YAML escape processing; inline comments are not interpreted.
48
+
49
+ ## Checks and severities
50
+
51
+ | Kind | Severity | Trigger |
52
+ | --- | --- | --- |
53
+ | missing-frontmatter | HIGH | No opening frontmatter delimiter |
54
+ | missing-name | HIGH | Missing or empty name |
55
+ | missing-description | HIGH | Missing or empty description |
56
+ | name-mismatch | MEDIUM | Name differs from package directory name |
57
+ | referenced-file | HIGH | Referenced path does not exist |
58
+ | script-not-executable | MEDIUM | Referenced scripts/ file has neither any executable bit nor a shebang |
59
+ | duplicate-skill-name | MEDIUM | Same nonempty name appears in multiple packages; each package is flagged |
60
+ | empty-body | MEDIUM | Stripped body has fewer than 50 characters |
61
+
62
+ Name and description are HIGH by design because they make a skill loadable
63
+ and discoverable. Name matching is a convention, not universal across hosts.
64
+
65
+ Path checks inspect the body after frontmatter, using backticked or bare
66
+ tokens containing `/` and ending in `.py`, `.js`, `.ts`, `.md`, `.json`,
67
+ `.yaml`, `.yml`, `.toml`, `.sh`, `.go`, `.rs`, or `.txt`, plus references
68
+ under `scripts/`, `references/`, `examples/`, `tests/`, `docs/`, and `bin/`.
69
+ URLs beginning http:// or https://, absolute paths, and tokens containing `*`
70
+ are skipped. Paths resolve against the skill directory first, then the audit
71
+ root. A trailing slash requires a directory. Shebang detection checks the
72
+ first two bytes for `#!`; permission checks inspect mode bits.
73
+
74
+ Findings include skill directory relative to the root, file, 1-based line,
75
+ kind, claim, severity, and detail. Metadata diagnostics use the opening lines;
76
+ body path diagnostics use their actual line. Findings deduplicate by
77
+ (skill, line, kind, claim). At most 500 are displayed, ordered by skill then
78
+ line (then kind and claim); truncation and omitted count are explicit.
79
+ Totals and verdict include all unignored findings, including omitted ones.
80
+ Human and JSON reports contain the same counts, per-kind and per-severity
81
+ totals, ignored count, parse-error count, and verdict.
82
+
83
+ ## Exit codes
84
+
85
+ | Code | Verdict | Meaning |
86
+ | --- | --- | --- |
87
+ | 0 | PASS | No unignored findings or parse errors |
88
+ | 1 | WARN | Findings exist, all below the threshold |
89
+ | 2 | FAIL | Any finding reaches the threshold, or any parse error |
90
+
91
+ Default threshold is HIGH. With `--fail-on medium`, every finding fails.
92
+ An invalid audit path also produces exit 2. CLI argument errors use argparse's
93
+ exit 2. The warn-only case uses exit 1 even though no finding reaches the
94
+ threshold.
95
+
96
+ ## Examples
97
+
98
+ All included examples are synthetic and need no credentials or services.
99
+
100
+ ```sh
101
+ skill-drift audit examples/sample-skills/good-skill
102
+ # PASS: 1 skills found; no findings; exit 0
103
+ skill-drift audit examples/sample-skills/broken-skill
104
+ # FAIL: 1 skills found; exit 2
105
+ # HIGH missing-description: description
106
+ # MEDIUM name-mismatch: outdated-skill
107
+ # HIGH referenced-file: scripts/renamed.sh
108
+ # HIGH referenced-file: references/moved.md
109
+ skill-drift audit examples/sample-skills/broken-skill --json
110
+ # Valid JSON: HIGH=3, MEDIUM=1, verdict=FAIL, exit_code=2
111
+ ```
112
+
113
+ The good package references an executable `scripts/check.sh`. The broken
114
+ package demonstrates a missing description, mismatched name, missing script,
115
+ and missing reference. The actual report also includes locations and details.
116
+
117
+ ## Limitations
118
+
119
+ Checks are heuristic pattern matching, not semantic judgement. Paraphrased
120
+ claims are not checked. Commands are never executed; only their path tokens
121
+ are checked. Paths with spaces and unusual punctuation may be missed or
122
+ misidentified. Existence says nothing about correctness, safety, importability,
123
+ or successful execution. External targets and glob expansions are not checked.
124
+ The YAML subset rejects complex YAML instead of guessing. Filesystem changes
125
+ during a run can affect results; this is a snapshot-style audit, not a monitor.
126
+
127
+ ## Differentiation
128
+
129
+ - **instruction-drift** audits instruction files (AGENTS.md, CLAUDE.md,
130
+ MUSE.md, CONTRIBUTING.md) against a repository. This audits skill packages:
131
+ SKILL.md, frontmatter, scripts, and references against the disk.
132
+ - **skill-tax** audits what a SKILL.md costs in tokens. This audits whether
133
+ the skill still works through its checkable package claims.
134
+ - **skill-pin-verify** audits pinning/signatures. This audits the truth of
135
+ package contents through offline heuristics.
136
+ - **frontmatter-guard** audits plugin.json manifests. This audits SKILL.md
137
+ frontmatter.
138
+ - **Heavy runtimes** require more infrastructure. This is an offline stdlib
139
+ CLI with no daemon, no LLM, and no network.
140
+
141
+ ## Development
142
+
143
+ ```sh
144
+ PYTHONPATH=src python -m unittest discover -s tests -v
145
+ python -m build
146
+ python -m venv /tmp/skill-drift-smoke
147
+ /tmp/skill-drift-smoke/bin/pip install dist/skill_drift-0.1.0-py3-none-any.whl
148
+ /tmp/skill-drift-smoke/bin/skill-drift audit examples/sample-skills/good-skill
149
+ ```
150
+
151
+ Tests use unittest, temporary synthetic fixtures, and no network. Setuptools
152
+ and wheel are build-time dependencies; `build` is the development frontend.
153
+ Build artifacts are local only and should be removed before sharing a tree.
154
+
155
+ MIT licensed. See LICENSE.
@@ -0,0 +1,11 @@
1
+ skill_drift/__init__.py,sha256=tlreCNmeuLuObBv65Yy4Z3mq_UtdNz9oSt3dK0ByKGw,66
2
+ skill_drift/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ skill_drift/audit.py,sha256=EvgDX-YFlpE95w98MWdBatYLPyCP5n5OMABCgDk6MH0,4657
4
+ skill_drift/cli.py,sha256=2_5ikg5D2YsCqnkapQ_MDh7kqZy_1mvt4EWyEywyIQM,1949
5
+ skill_drift/skills.py,sha256=c8AbYAXs5Nkdk3znLfxCEK4mErnxQaeqDoISOZM64l8,2992
6
+ skill_drift-0.1.0.dist-info/licenses/LICENSE,sha256=BY32OKHQwPwe_UT_YvyEpQOiKWFIyUZHQ7yXG4iWt-c,1081
7
+ skill_drift-0.1.0.dist-info/METADATA,sha256=hEE2ABUvZcXgP6GkKvhIPQtCsKEJfVsuY85VBFm8_Nk,7031
8
+ skill_drift-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ skill_drift-0.1.0.dist-info/entry_points.txt,sha256=eDM-LCBeV1WO8M2TAo4Vl-cXKT03MF9QEebLYQMoPt0,53
10
+ skill_drift-0.1.0.dist-info/top_level.txt,sha256=BtvcRxlm-UvndS0_1uZeli_k9XObfb2uGNt0VI5jrHA,12
11
+ skill_drift-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ skill-drift = skill_drift.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 skill-drift contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ skill_drift