trustline-cli 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.
- trustline_cli-0.1.0/LICENSE +21 -0
- trustline_cli-0.1.0/PKG-INFO +146 -0
- trustline_cli-0.1.0/README.md +123 -0
- trustline_cli-0.1.0/pyproject.toml +41 -0
- trustline_cli-0.1.0/setup.cfg +4 -0
- trustline_cli-0.1.0/src/trustline/__init__.py +3 -0
- trustline_cli-0.1.0/src/trustline/baseline.py +126 -0
- trustline_cli-0.1.0/src/trustline/cli.py +280 -0
- trustline_cli-0.1.0/src/trustline/config.py +116 -0
- trustline_cli-0.1.0/src/trustline/discovery.py +36 -0
- trustline_cli-0.1.0/src/trustline/heuristics.py +282 -0
- trustline_cli-0.1.0/src/trustline/hooks.py +290 -0
- trustline_cli-0.1.0/src/trustline/rollback.py +119 -0
- trustline_cli-0.1.0/src/trustline/sarif.py +49 -0
- trustline_cli-0.1.0/src/trustline/scanner.py +33 -0
- trustline_cli-0.1.0/src/trustline_cli.egg-info/PKG-INFO +146 -0
- trustline_cli-0.1.0/src/trustline_cli.egg-info/SOURCES.txt +25 -0
- trustline_cli-0.1.0/src/trustline_cli.egg-info/dependency_links.txt +1 -0
- trustline_cli-0.1.0/src/trustline_cli.egg-info/entry_points.txt +2 -0
- trustline_cli-0.1.0/src/trustline_cli.egg-info/requires.txt +6 -0
- trustline_cli-0.1.0/src/trustline_cli.egg-info/top_level.txt +1 -0
- trustline_cli-0.1.0/tests/test_baseline.py +59 -0
- trustline_cli-0.1.0/tests/test_cli.py +117 -0
- trustline_cli-0.1.0/tests/test_config_glob.py +41 -0
- trustline_cli-0.1.0/tests/test_discovery.py +33 -0
- trustline_cli-0.1.0/tests/test_heuristics.py +63 -0
- trustline_cli-0.1.0/tests/test_rollback.py +77 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Terence Cai
|
|
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,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: trustline-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Trusted baseline + auto-rollback for AI agent configuration files (.claude/, AGENTS.md, .mcp.json, ...). Detects prompt-injection / supply-chain tampering of agent rules and rolls back to a trusted snapshot.
|
|
5
|
+
Author-email: Terence Cai <cys2193736202@163.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: security,ai-agents,claude-code,supply-chain,prompt-injection,baseline
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Security
|
|
14
|
+
Requires-Python: >=3.11
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: typer>=0.12
|
|
18
|
+
Requires-Dist: rich>=13.7
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Trustline
|
|
25
|
+
|
|
26
|
+
**Trusted baseline + auto-rollback for AI agent configuration files.**
|
|
27
|
+
|
|
28
|
+
[](https://github.com/LuckTerence/trustline/actions/workflows/ci.yml)
|
|
29
|
+
[](https://pypi.org/project/trustline-cli/)
|
|
30
|
+
[](LICENSE)
|
|
31
|
+
|
|
32
|
+
AI coding agents (Claude Code, Cursor, Codex, ...) load rules from files such as
|
|
33
|
+
`.claude/`, `AGENTS.md`, `.cursorrules` and `.mcp.json`. Those files are now a
|
|
34
|
+
supply-chain attack surface: cloning a repository or installing a third-party
|
|
35
|
+
MCP can silently inject instructions that tell your agent to exfiltrate
|
|
36
|
+
secrets, tamper with your shell, or hide its own actions.
|
|
37
|
+
|
|
38
|
+
Existing scanners (medusa, Snyk agent-scan, Cisco mcp-scanner, ...) **detect**
|
|
39
|
+
such tampering. Trustline is the missing **recovery layer**: it keeps a
|
|
40
|
+
trusted baseline of your agent configuration files and can roll them back —
|
|
41
|
+
and, through Claude Code hooks, block suspicious loads *before* they reach the
|
|
42
|
+
model.
|
|
43
|
+
|
|
44
|
+
## Why Trustline?
|
|
45
|
+
|
|
46
|
+
Detection is table stakes. Every scanner in this space answers one question:
|
|
47
|
+
*"has this rules file been poisoned?"* — and then leaves you to fix it by hand.
|
|
48
|
+
Trustline answers the two questions that come after:
|
|
49
|
+
|
|
50
|
+
1. **Did my agent config drift from a state I explicitly trusted?**
|
|
51
|
+
`status` diffs the working tree against a SHA-256 baseline *you* approved,
|
|
52
|
+
so a poisoned `.claude/settings.json` cloned from an untrusted repo shows up
|
|
53
|
+
as a concrete `modified`/`added` change — not a vague alert.
|
|
54
|
+
2. **How do I get back to the trusted state?**
|
|
55
|
+
`rollback` restores from git HEAD or from content snapshots taken at
|
|
56
|
+
baseline time, and preserves the tampered copy for forensics — no manual
|
|
57
|
+
surgery, no guessing which file was the original.
|
|
58
|
+
|
|
59
|
+
And because PreToolUse fires *before* a write lands, Trustline can refuse to
|
|
60
|
+
let an agent write a poisoned rules file into your tree in the first place —
|
|
61
|
+
the layer none of the scanners provide. This is deliberately defense-in-depth:
|
|
62
|
+
the model's own safety training is the first line, the hook is the second, and
|
|
63
|
+
the baseline + audit log is the third.
|
|
64
|
+
|
|
65
|
+
## What it does
|
|
66
|
+
|
|
67
|
+
- `trustline init` — establish a trusted baseline (SHA-256 snapshot) of managed agent files.
|
|
68
|
+
- `trustline status` — diff the working tree against the baseline (added / modified / deleted).
|
|
69
|
+
- `trustline scan` — static heuristic scan for prompt-injection / exfiltration / privilege-tampering signals (15 rules in v0.1).
|
|
70
|
+
- `trustline rollback [files...]` — restore files to the baseline (git HEAD first, then local snapshots; soft rollback keeps `.bak`).
|
|
71
|
+
- `trustline export-sarif` — emit scan findings as SARIF for CI / DefectDojo.
|
|
72
|
+
- `trustline hook install` — wire Claude Code hooks (SessionStart / file-load / PreToolUse) to verify before the agent trusts a rules file.
|
|
73
|
+
|
|
74
|
+
## Install
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install trustline-cli # or: uv tool install trustline-cli
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Quick start
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
cd ~/some-repo-you-cloned
|
|
84
|
+
trustline init # review listed files, press enter -> baseline saved
|
|
85
|
+
trustline status # nothing changed yet
|
|
86
|
+
trustline scan --sarif # heuristic scan of managed files
|
|
87
|
+
# ... after a suspicious change ...
|
|
88
|
+
trustline status # shows: MODIFIED .claude/settings.json
|
|
89
|
+
trustline scan .claude/settings.json
|
|
90
|
+
trustline rollback .claude/settings.json # back to trusted state
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Claude Code hooks
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
trustline hook install # writes .claude/settings.local.json (gitignored)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Hooks are executed with the project directory as cwd (no project-dir
|
|
100
|
+
placeholder is needed). What fires:
|
|
101
|
+
|
|
102
|
+
- **SessionStart** — warns on any managed file that differs from the trusted
|
|
103
|
+
baseline (verified in real Claude Code sessions).
|
|
104
|
+
- **PreToolUse** on `Write`/`Edit`/`NotebookEdit` of a managed file — inspects
|
|
105
|
+
the *incoming* content and blocks with `exit 2` when a high-severity tamper
|
|
106
|
+
signal is present (so the agent cannot write a poisoned rules file).
|
|
107
|
+
- **InstructionsLoaded** — best-effort block when a loaded rules file drifted
|
|
108
|
+
out of baseline; the event is not emitted in all Claude Code versions /
|
|
109
|
+
headless mode, so treat it as defense-in-depth, not the primary gate.
|
|
110
|
+
|
|
111
|
+
Every hook decision is appended to a per-project audit log under
|
|
112
|
+
`~/.config/trustline/projects/<root>/audit.jsonl`, so behaviour is observable
|
|
113
|
+
without trusting stderr alone.
|
|
114
|
+
|
|
115
|
+
## Real-world smoke scan
|
|
116
|
+
|
|
117
|
+
`trustline scan` run over three public repositories (2026-09-02, shallow clone,
|
|
118
|
+
default rules). Findings are static signals that require human review — the
|
|
119
|
+
point of the table is to show the tool runs cleanly on real trees and that
|
|
120
|
+
false-positive volume is low.
|
|
121
|
+
|
|
122
|
+
| Repository | Managed files scanned | Findings | Signal rules hit | Notes |
|
|
123
|
+
|---|---|---|---|---|
|
|
124
|
+
| [affaan-m/ECC](https://github.com/affaan-m/ECC) (ruleset, 245k★) | 65 | 3 | T010 · T007 · T012 | low hit-rate on a very large rules corpus |
|
|
125
|
+
| [yamadashy/repomix](https://github.com/yamadashy/repomix) (tool, 28k★) | 11 | 1 | T010 | unpinned `npx` MCP package (common, low-risk) |
|
|
126
|
+
| [Pantheon-Security/medusa](https://github.com/Pantheon-Security/medusa) (security scanner) | 3 | 2 | T013 · T004 | both hits are inside its own `tests/fixtures/malicious_repo/` samples — Trustline flags the same fixtures medusa ships |
|
|
127
|
+
|
|
128
|
+
Reproduce: `pip install trustline-cli && trustline scan --root <clone-dir> --sarif`.
|
|
129
|
+
|
|
130
|
+
## Managed files (default)
|
|
131
|
+
|
|
132
|
+
`.claude/**`, `CLAUDE.md`, `**/AGENTS.md`, `**/.cursorrules`, `**/.mcp.json`,
|
|
133
|
+
`**/.codex/**`, `**/.github/copilot-instructions.md` — override with
|
|
134
|
+
`trustline init --patterns ...` or a `trustline.toml`.
|
|
135
|
+
|
|
136
|
+
## Development
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
python -m venv .venv && . .venv/bin/activate
|
|
140
|
+
pip install -e ".[dev]"
|
|
141
|
+
pytest
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
MIT
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Trustline
|
|
2
|
+
|
|
3
|
+
**Trusted baseline + auto-rollback for AI agent configuration files.**
|
|
4
|
+
|
|
5
|
+
[](https://github.com/LuckTerence/trustline/actions/workflows/ci.yml)
|
|
6
|
+
[](https://pypi.org/project/trustline-cli/)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
|
|
9
|
+
AI coding agents (Claude Code, Cursor, Codex, ...) load rules from files such as
|
|
10
|
+
`.claude/`, `AGENTS.md`, `.cursorrules` and `.mcp.json`. Those files are now a
|
|
11
|
+
supply-chain attack surface: cloning a repository or installing a third-party
|
|
12
|
+
MCP can silently inject instructions that tell your agent to exfiltrate
|
|
13
|
+
secrets, tamper with your shell, or hide its own actions.
|
|
14
|
+
|
|
15
|
+
Existing scanners (medusa, Snyk agent-scan, Cisco mcp-scanner, ...) **detect**
|
|
16
|
+
such tampering. Trustline is the missing **recovery layer**: it keeps a
|
|
17
|
+
trusted baseline of your agent configuration files and can roll them back —
|
|
18
|
+
and, through Claude Code hooks, block suspicious loads *before* they reach the
|
|
19
|
+
model.
|
|
20
|
+
|
|
21
|
+
## Why Trustline?
|
|
22
|
+
|
|
23
|
+
Detection is table stakes. Every scanner in this space answers one question:
|
|
24
|
+
*"has this rules file been poisoned?"* — and then leaves you to fix it by hand.
|
|
25
|
+
Trustline answers the two questions that come after:
|
|
26
|
+
|
|
27
|
+
1. **Did my agent config drift from a state I explicitly trusted?**
|
|
28
|
+
`status` diffs the working tree against a SHA-256 baseline *you* approved,
|
|
29
|
+
so a poisoned `.claude/settings.json` cloned from an untrusted repo shows up
|
|
30
|
+
as a concrete `modified`/`added` change — not a vague alert.
|
|
31
|
+
2. **How do I get back to the trusted state?**
|
|
32
|
+
`rollback` restores from git HEAD or from content snapshots taken at
|
|
33
|
+
baseline time, and preserves the tampered copy for forensics — no manual
|
|
34
|
+
surgery, no guessing which file was the original.
|
|
35
|
+
|
|
36
|
+
And because PreToolUse fires *before* a write lands, Trustline can refuse to
|
|
37
|
+
let an agent write a poisoned rules file into your tree in the first place —
|
|
38
|
+
the layer none of the scanners provide. This is deliberately defense-in-depth:
|
|
39
|
+
the model's own safety training is the first line, the hook is the second, and
|
|
40
|
+
the baseline + audit log is the third.
|
|
41
|
+
|
|
42
|
+
## What it does
|
|
43
|
+
|
|
44
|
+
- `trustline init` — establish a trusted baseline (SHA-256 snapshot) of managed agent files.
|
|
45
|
+
- `trustline status` — diff the working tree against the baseline (added / modified / deleted).
|
|
46
|
+
- `trustline scan` — static heuristic scan for prompt-injection / exfiltration / privilege-tampering signals (15 rules in v0.1).
|
|
47
|
+
- `trustline rollback [files...]` — restore files to the baseline (git HEAD first, then local snapshots; soft rollback keeps `.bak`).
|
|
48
|
+
- `trustline export-sarif` — emit scan findings as SARIF for CI / DefectDojo.
|
|
49
|
+
- `trustline hook install` — wire Claude Code hooks (SessionStart / file-load / PreToolUse) to verify before the agent trusts a rules file.
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install trustline-cli # or: uv tool install trustline-cli
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
cd ~/some-repo-you-cloned
|
|
61
|
+
trustline init # review listed files, press enter -> baseline saved
|
|
62
|
+
trustline status # nothing changed yet
|
|
63
|
+
trustline scan --sarif # heuristic scan of managed files
|
|
64
|
+
# ... after a suspicious change ...
|
|
65
|
+
trustline status # shows: MODIFIED .claude/settings.json
|
|
66
|
+
trustline scan .claude/settings.json
|
|
67
|
+
trustline rollback .claude/settings.json # back to trusted state
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Claude Code hooks
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
trustline hook install # writes .claude/settings.local.json (gitignored)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Hooks are executed with the project directory as cwd (no project-dir
|
|
77
|
+
placeholder is needed). What fires:
|
|
78
|
+
|
|
79
|
+
- **SessionStart** — warns on any managed file that differs from the trusted
|
|
80
|
+
baseline (verified in real Claude Code sessions).
|
|
81
|
+
- **PreToolUse** on `Write`/`Edit`/`NotebookEdit` of a managed file — inspects
|
|
82
|
+
the *incoming* content and blocks with `exit 2` when a high-severity tamper
|
|
83
|
+
signal is present (so the agent cannot write a poisoned rules file).
|
|
84
|
+
- **InstructionsLoaded** — best-effort block when a loaded rules file drifted
|
|
85
|
+
out of baseline; the event is not emitted in all Claude Code versions /
|
|
86
|
+
headless mode, so treat it as defense-in-depth, not the primary gate.
|
|
87
|
+
|
|
88
|
+
Every hook decision is appended to a per-project audit log under
|
|
89
|
+
`~/.config/trustline/projects/<root>/audit.jsonl`, so behaviour is observable
|
|
90
|
+
without trusting stderr alone.
|
|
91
|
+
|
|
92
|
+
## Real-world smoke scan
|
|
93
|
+
|
|
94
|
+
`trustline scan` run over three public repositories (2026-09-02, shallow clone,
|
|
95
|
+
default rules). Findings are static signals that require human review — the
|
|
96
|
+
point of the table is to show the tool runs cleanly on real trees and that
|
|
97
|
+
false-positive volume is low.
|
|
98
|
+
|
|
99
|
+
| Repository | Managed files scanned | Findings | Signal rules hit | Notes |
|
|
100
|
+
|---|---|---|---|---|
|
|
101
|
+
| [affaan-m/ECC](https://github.com/affaan-m/ECC) (ruleset, 245k★) | 65 | 3 | T010 · T007 · T012 | low hit-rate on a very large rules corpus |
|
|
102
|
+
| [yamadashy/repomix](https://github.com/yamadashy/repomix) (tool, 28k★) | 11 | 1 | T010 | unpinned `npx` MCP package (common, low-risk) |
|
|
103
|
+
| [Pantheon-Security/medusa](https://github.com/Pantheon-Security/medusa) (security scanner) | 3 | 2 | T013 · T004 | both hits are inside its own `tests/fixtures/malicious_repo/` samples — Trustline flags the same fixtures medusa ships |
|
|
104
|
+
|
|
105
|
+
Reproduce: `pip install trustline-cli && trustline scan --root <clone-dir> --sarif`.
|
|
106
|
+
|
|
107
|
+
## Managed files (default)
|
|
108
|
+
|
|
109
|
+
`.claude/**`, `CLAUDE.md`, `**/AGENTS.md`, `**/.cursorrules`, `**/.mcp.json`,
|
|
110
|
+
`**/.codex/**`, `**/.github/copilot-instructions.md` — override with
|
|
111
|
+
`trustline init --patterns ...` or a `trustline.toml`.
|
|
112
|
+
|
|
113
|
+
## Development
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
python -m venv .venv && . .venv/bin/activate
|
|
117
|
+
pip install -e ".[dev]"
|
|
118
|
+
pytest
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "trustline-cli"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Trusted baseline + auto-rollback for AI agent configuration files (.claude/, AGENTS.md, .mcp.json, ...). Detects prompt-injection / supply-chain tampering of agent rules and rolls back to a trusted snapshot."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Terence Cai", email = "cys2193736202@163.com" }]
|
|
13
|
+
keywords = ["security", "ai-agents", "claude-code", "supply-chain", "prompt-injection", "baseline"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Security",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"typer>=0.12",
|
|
24
|
+
"rich>=13.7",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.optional-dependencies]
|
|
28
|
+
dev = [
|
|
29
|
+
"pytest>=8",
|
|
30
|
+
"pytest-cov>=5",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
trustline = "trustline.cli:app"
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.packages.find]
|
|
37
|
+
where = ["src"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
testpaths = ["tests"]
|
|
41
|
+
addopts = "-q"
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Trusted baseline: SHA-256 snapshot of managed files + content copies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import shutil
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .config import Config, normalize_relpath
|
|
13
|
+
|
|
14
|
+
BASELINE_VERSION = 1
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sha256_file(path: Path) -> str:
|
|
18
|
+
h = hashlib.sha256()
|
|
19
|
+
with path.open("rb") as f:
|
|
20
|
+
for chunk in iter(lambda: f.read(65536), b""):
|
|
21
|
+
h.update(chunk)
|
|
22
|
+
return h.hexdigest()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def sha256_bytes(data: bytes) -> str:
|
|
26
|
+
return hashlib.sha256(data).hexdigest()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class FileEntry:
|
|
31
|
+
sha256: str
|
|
32
|
+
copied: bool = False # a content snapshot exists under copies/<sha>/
|
|
33
|
+
size: int = 0
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Change:
|
|
38
|
+
relpath: str
|
|
39
|
+
change_type: str # "added" | "modified" | "deleted"
|
|
40
|
+
old_sha: str = ""
|
|
41
|
+
new_sha: str = ""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Baseline:
|
|
46
|
+
version: int = BASELINE_VERSION
|
|
47
|
+
created_at: str = ""
|
|
48
|
+
files: dict[str, FileEntry] = field(default_factory=dict)
|
|
49
|
+
|
|
50
|
+
def to_json(self) -> dict:
|
|
51
|
+
return {
|
|
52
|
+
"version": self.version,
|
|
53
|
+
"created_at": self.created_at,
|
|
54
|
+
"files": {k: {"sha256": v.sha256, "copied": v.copied, "size": v.size} for k, v in self.files.items()},
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_json(cls, data: dict) -> "Baseline":
|
|
59
|
+
b = cls(version=data.get("version", BASELINE_VERSION), created_at=data.get("created_at", ""))
|
|
60
|
+
for k, v in (data.get("files") or {}).items():
|
|
61
|
+
b.files[k] = FileEntry(sha256=v.get("sha256", ""), copied=bool(v.get("copied")), size=int(v.get("size", 0)))
|
|
62
|
+
return b
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def load(config: Config) -> Baseline | None:
|
|
66
|
+
p = config.baseline_path
|
|
67
|
+
if not p.exists():
|
|
68
|
+
return None
|
|
69
|
+
try:
|
|
70
|
+
return Baseline.from_json(json.loads(p.read_text(encoding="utf-8")))
|
|
71
|
+
except (json.JSONDecodeError, OSError):
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def save(config: Config, baseline: Baseline) -> Path:
|
|
76
|
+
config.ensure_dirs()
|
|
77
|
+
p = config.baseline_path
|
|
78
|
+
p.write_text(json.dumps(baseline.to_json(), indent=2, ensure_ascii=False), encoding="utf-8")
|
|
79
|
+
return p
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def snapshot(config: Config) -> Baseline:
|
|
83
|
+
"""Hash every managed file; store content copies under copies/<sha> when
|
|
84
|
+
config.with_copies is set so rollback works even outside a git repo."""
|
|
85
|
+
from .discovery import discover
|
|
86
|
+
|
|
87
|
+
baseline = Baseline(created_at=time.strftime("%Y-%m-%dT%H:%M:%S%z"))
|
|
88
|
+
for path in discover(config):
|
|
89
|
+
rel = normalize_relpath(config.root, path)
|
|
90
|
+
digest = sha256_file(path)
|
|
91
|
+
entry = FileEntry(sha256=digest, size=path.stat().st_size)
|
|
92
|
+
if config.with_copies:
|
|
93
|
+
dest = config.copies_dir / digest
|
|
94
|
+
if not dest.exists():
|
|
95
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
96
|
+
shutil.copy2(path, dest)
|
|
97
|
+
entry.copied = True
|
|
98
|
+
baseline.files[rel] = entry
|
|
99
|
+
return baseline
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def compare(config: Config, baseline: Baseline) -> list[Change]:
|
|
103
|
+
"""Diff current managed files against the baseline."""
|
|
104
|
+
from .discovery import discover
|
|
105
|
+
|
|
106
|
+
changes: list[Change] = []
|
|
107
|
+
current: dict[str, Path] = {}
|
|
108
|
+
for path in discover(config):
|
|
109
|
+
rel = normalize_relpath(config.root, path)
|
|
110
|
+
current[rel] = path
|
|
111
|
+
|
|
112
|
+
for rel, path in current.items():
|
|
113
|
+
entry = baseline.files.get(rel)
|
|
114
|
+
if entry is None:
|
|
115
|
+
changes.append(Change(relpath=rel, change_type="added", new_sha=sha256_file(path)))
|
|
116
|
+
else:
|
|
117
|
+
digest = sha256_file(path)
|
|
118
|
+
if digest != entry.sha256:
|
|
119
|
+
changes.append(Change(relpath=rel, change_type="modified", old_sha=entry.sha256, new_sha=digest))
|
|
120
|
+
|
|
121
|
+
for rel in baseline.files:
|
|
122
|
+
if rel not in current:
|
|
123
|
+
changes.append(Change(relpath=rel, change_type="deleted", old_sha=baseline.files[rel].sha256))
|
|
124
|
+
|
|
125
|
+
changes.sort(key=lambda c: (c.change_type, c.relpath))
|
|
126
|
+
return changes
|