assurance-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.
- assurance_cli-0.1.0/LICENSE +190 -0
- assurance_cli-0.1.0/PKG-INFO +39 -0
- assurance_cli-0.1.0/README.md +12 -0
- assurance_cli-0.1.0/assurance_cli/__init__.py +8 -0
- assurance_cli-0.1.0/assurance_cli/__main__.py +4 -0
- assurance_cli-0.1.0/assurance_cli/baseline.py +120 -0
- assurance_cli-0.1.0/assurance_cli/cli.py +106 -0
- assurance_cli-0.1.0/assurance_cli/gather.py +328 -0
- assurance_cli-0.1.0/assurance_cli/paths.py +42 -0
- assurance_cli-0.1.0/assurance_cli/profile.py +95 -0
- assurance_cli-0.1.0/assurance_cli.egg-info/PKG-INFO +39 -0
- assurance_cli-0.1.0/assurance_cli.egg-info/SOURCES.txt +18 -0
- assurance_cli-0.1.0/assurance_cli.egg-info/dependency_links.txt +1 -0
- assurance_cli-0.1.0/assurance_cli.egg-info/entry_points.txt +2 -0
- assurance_cli-0.1.0/assurance_cli.egg-info/requires.txt +5 -0
- assurance_cli-0.1.0/assurance_cli.egg-info/top_level.txt +1 -0
- assurance_cli-0.1.0/pyproject.toml +46 -0
- assurance_cli-0.1.0/setup.cfg +4 -0
- assurance_cli-0.1.0/tests/test_cli.py +125 -0
- assurance_cli-0.1.0/tests/test_read_only.py +34 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions. Notwithstanding
|
|
134
|
+
the above, nothing herein shall supersede or modify the terms of any
|
|
135
|
+
separate license agreement you may have executed with Licensor regarding
|
|
136
|
+
such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 I-Ops Operations Intelligence, LLC
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: assurance-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI for folder assurance checks — coverage, staleness, and baselines.
|
|
5
|
+
Author-email: "I-Ops Operations Intelligence, LLC" <hello@i-ops.dev>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://i-ops.dev
|
|
8
|
+
Project-URL: Source, https://github.com/i-ops-hq/assurance-cli
|
|
9
|
+
Keywords: cli,ai-agents,governance,auditing,assurance,reproducibility
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: assurance-core>=0.2
|
|
23
|
+
Requires-Dist: openpyxl>=3.1
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# assurance-cli
|
|
29
|
+
|
|
30
|
+
Command-line assurance checks over a folder — coverage gaps, baseline staleness, and machine-readable output for CI.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install assurance-cli
|
|
34
|
+
assurance check ~/data
|
|
35
|
+
assurance init ~/thesis-data
|
|
36
|
+
assurance check ~/thesis-data --against-baseline
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
See `assurance_core` for the pure arithmetic; this package owns all filesystem I/O.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# assurance-cli
|
|
2
|
+
|
|
3
|
+
Command-line assurance checks over a folder — coverage gaps, baseline staleness, and machine-readable output for CI.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install assurance-cli
|
|
7
|
+
assurance check ~/data
|
|
8
|
+
assurance init ~/thesis-data
|
|
9
|
+
assurance check ~/thesis-data --against-baseline
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
See `assurance_core` for the pure arithmetic; this package owns all filesystem I/O.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""assurance-cli — folder checks anyone can run without I-Ops.
|
|
2
|
+
|
|
3
|
+
Shared filesystem I/O (`paths`, `profile`, `gather`) lives in this package so `assurance-mcp` can
|
|
4
|
+
import it instead of duplicating the profiler. MCP depends on this package for gathering only; the
|
|
5
|
+
CLI does not depend on MCP. Two copies of the profiler is how they disagree.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Baseline file — the only thing this tool may write."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from assurance_cli.paths import resolve_folder, resolve_inside
|
|
11
|
+
from assurance_cli.profile import TABULAR_SUFFIXES, file_sha256, profile_file
|
|
12
|
+
|
|
13
|
+
BASELINE_NAME = ".assurance.json"
|
|
14
|
+
BASELINE_VERSION = 1
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def init_baseline(folder: str, *, update: bool = False) -> dict[str, Any]:
|
|
18
|
+
"""Write `.assurance.json` with hashes, sizes, mtimes, and computed totals."""
|
|
19
|
+
root = resolve_folder(folder)
|
|
20
|
+
path = root / BASELINE_NAME
|
|
21
|
+
if path.exists() and not update:
|
|
22
|
+
return {"written": False, "path": str(path), "reason": "baseline already exists; use --update"}
|
|
23
|
+
|
|
24
|
+
entries: dict[str, Any] = {}
|
|
25
|
+
for file_path in sorted(root.rglob("*")):
|
|
26
|
+
if not file_path.is_file():
|
|
27
|
+
continue
|
|
28
|
+
if file_path.name == BASELINE_NAME:
|
|
29
|
+
continue
|
|
30
|
+
if file_path.suffix.lower() not in TABULAR_SUFFIXES:
|
|
31
|
+
continue
|
|
32
|
+
try:
|
|
33
|
+
rel = str(file_path.relative_to(root))
|
|
34
|
+
resolve_inside(root, rel)
|
|
35
|
+
except Exception:
|
|
36
|
+
continue
|
|
37
|
+
stat = file_path.stat()
|
|
38
|
+
profile = profile_file(file_path)
|
|
39
|
+
entries[rel] = {
|
|
40
|
+
"sha256": file_sha256(file_path),
|
|
41
|
+
"size": stat.st_size,
|
|
42
|
+
"mtime": stat.st_mtime,
|
|
43
|
+
"profile": profile,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
payload = {
|
|
47
|
+
"version": BASELINE_VERSION,
|
|
48
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
49
|
+
"folder": str(root),
|
|
50
|
+
"files": entries,
|
|
51
|
+
}
|
|
52
|
+
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
53
|
+
return {"written": True, "path": str(path), "file_count": len(entries)}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def check_against_baseline(folder: str) -> dict[str, Any]:
|
|
57
|
+
"""Compare the folder to its baseline — each file against its own entry only."""
|
|
58
|
+
root = resolve_folder(folder)
|
|
59
|
+
path = root / BASELINE_NAME
|
|
60
|
+
if not path.is_file():
|
|
61
|
+
return {
|
|
62
|
+
"ok": False,
|
|
63
|
+
"summary": f"No baseline at {BASELINE_NAME}. Run `assurance init` first.",
|
|
64
|
+
"changed": [],
|
|
65
|
+
"vanished": [],
|
|
66
|
+
"new": [],
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
baseline = json.loads(path.read_text(encoding="utf-8"))
|
|
70
|
+
recorded: dict[str, Any] = baseline.get("files") or {}
|
|
71
|
+
findings: list[dict[str, Any]] = []
|
|
72
|
+
changed: list[str] = []
|
|
73
|
+
vanished: list[str] = []
|
|
74
|
+
new_files: list[str] = []
|
|
75
|
+
|
|
76
|
+
for rel, entry in sorted(recorded.items()):
|
|
77
|
+
file_path = root / rel
|
|
78
|
+
if not file_path.is_file():
|
|
79
|
+
vanished.append(rel)
|
|
80
|
+
findings.append({"file": rel, "status": "vanished"})
|
|
81
|
+
continue
|
|
82
|
+
stat = file_path.stat()
|
|
83
|
+
current_hash = file_sha256(file_path)
|
|
84
|
+
current_profile = profile_file(file_path)
|
|
85
|
+
if (
|
|
86
|
+
current_hash != entry.get("sha256")
|
|
87
|
+
or stat.st_size != entry.get("size")
|
|
88
|
+
or abs(stat.st_mtime - float(entry.get("mtime", 0))) > 0.001
|
|
89
|
+
or current_profile != entry.get("profile")
|
|
90
|
+
):
|
|
91
|
+
changed.append(rel)
|
|
92
|
+
findings.append({"file": rel, "status": "changed"})
|
|
93
|
+
|
|
94
|
+
for file_path in sorted(root.rglob("*")):
|
|
95
|
+
if not file_path.is_file() or file_path.name == BASELINE_NAME:
|
|
96
|
+
continue
|
|
97
|
+
if file_path.suffix.lower() not in TABULAR_SUFFIXES:
|
|
98
|
+
continue
|
|
99
|
+
rel = str(file_path.relative_to(root))
|
|
100
|
+
if rel not in recorded:
|
|
101
|
+
new_files.append(rel)
|
|
102
|
+
findings.append({"file": rel, "status": "new"})
|
|
103
|
+
|
|
104
|
+
parts: list[str] = []
|
|
105
|
+
if changed:
|
|
106
|
+
parts.append(f"{len(changed)} file(s) changed since the baseline")
|
|
107
|
+
if vanished:
|
|
108
|
+
parts.append(f"{len(vanished)} vanished")
|
|
109
|
+
if new_files:
|
|
110
|
+
parts.append(f"{len(new_files)} new (not in baseline)")
|
|
111
|
+
summary = "; ".join(parts) if parts else "All baseline files match."
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
"ok": not findings,
|
|
115
|
+
"summary": summary,
|
|
116
|
+
"changed": changed,
|
|
117
|
+
"vanished": vanished,
|
|
118
|
+
"new": new_files,
|
|
119
|
+
"findings": findings,
|
|
120
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Command-line entry for assurance checks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from assurance_cli.baseline import check_against_baseline, init_baseline
|
|
11
|
+
from assurance_cli.gather import check_coverage
|
|
12
|
+
from assurance_cli.paths import PathEscapeError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv: list[str] | None = None) -> int:
|
|
16
|
+
parser = argparse.ArgumentParser(prog="assurance", description="Folder assurance checks — arithmetic, not models.")
|
|
17
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
18
|
+
|
|
19
|
+
init_parser = sub.add_parser("init", help="Write .assurance.json baseline")
|
|
20
|
+
init_parser.add_argument("folder", help="Folder to baseline")
|
|
21
|
+
init_parser.add_argument("--update", action="store_true", help="Overwrite an existing baseline")
|
|
22
|
+
|
|
23
|
+
check_parser = sub.add_parser("check", help="Check a folder for coverage or staleness")
|
|
24
|
+
check_parser.add_argument("folder", help="Folder to check")
|
|
25
|
+
check_parser.add_argument("--expect", choices=["monthly", "quarterly", "weekly", "daily", "numbered"])
|
|
26
|
+
check_parser.add_argument("--from", dest="from_point", metavar="FROM")
|
|
27
|
+
check_parser.add_argument("--to", dest="to_point", metavar="TO")
|
|
28
|
+
check_parser.add_argument("--against-baseline", action="store_true")
|
|
29
|
+
check_parser.add_argument("--json", action="store_true", dest="as_json")
|
|
30
|
+
check_parser.add_argument("--fail-on-gap", action="store_true")
|
|
31
|
+
check_parser.add_argument("period_range", nargs="?", help="Optional period range (monthly)")
|
|
32
|
+
|
|
33
|
+
args = parser.parse_args(argv)
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
if args.command == "init":
|
|
37
|
+
result = init_baseline(args.folder, update=args.update)
|
|
38
|
+
return _emit(result, args, finding=not result.get("written") and not args.update)
|
|
39
|
+
return _run_check(args)
|
|
40
|
+
except (PathEscapeError, FileNotFoundError, NotADirectoryError) as exc:
|
|
41
|
+
return _emit({"error": str(exc)}, args if args.command == "check" else argparse.Namespace(as_json=False), code=2)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _run_check(args: argparse.Namespace) -> int:
|
|
45
|
+
output: dict[str, Any] = {}
|
|
46
|
+
findings = False
|
|
47
|
+
|
|
48
|
+
if args.against_baseline:
|
|
49
|
+
baseline = check_against_baseline(args.folder)
|
|
50
|
+
output["baseline"] = baseline
|
|
51
|
+
findings = findings or not baseline.get("ok", True)
|
|
52
|
+
|
|
53
|
+
coverage = check_coverage(
|
|
54
|
+
args.folder,
|
|
55
|
+
getattr(args, "period_range", None),
|
|
56
|
+
expect=args.expect,
|
|
57
|
+
from_point=args.from_point,
|
|
58
|
+
to_point=args.to_point,
|
|
59
|
+
)
|
|
60
|
+
output["coverage"] = coverage
|
|
61
|
+
if coverage.get("error"):
|
|
62
|
+
return _emit(output, args, code=2)
|
|
63
|
+
|
|
64
|
+
if args.against_baseline and not output.get("baseline", {}).get("ok", True):
|
|
65
|
+
findings = True
|
|
66
|
+
if not coverage.get("complete", False) and args.fail_on_gap:
|
|
67
|
+
findings = True
|
|
68
|
+
|
|
69
|
+
return _emit(output, args, finding=findings)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _emit(payload: dict[str, Any], args: argparse.Namespace, *, code: int = 0, finding: bool = False) -> int:
|
|
73
|
+
if getattr(args, "as_json", False):
|
|
74
|
+
print(json.dumps(payload, indent=2))
|
|
75
|
+
else:
|
|
76
|
+
print(_format_text(payload))
|
|
77
|
+
if code:
|
|
78
|
+
return code
|
|
79
|
+
if finding:
|
|
80
|
+
return 1
|
|
81
|
+
if _has_findings(payload):
|
|
82
|
+
return 1
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _has_findings(payload: dict[str, Any]) -> bool:
|
|
87
|
+
if payload.get("baseline") and not payload["baseline"].get("ok", True):
|
|
88
|
+
return True
|
|
89
|
+
coverage = payload.get("coverage") or payload
|
|
90
|
+
return bool(coverage.get("error"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _format_text(payload: dict[str, Any]) -> str:
|
|
94
|
+
lines: list[str] = []
|
|
95
|
+
if "baseline" in payload:
|
|
96
|
+
lines.append(payload["baseline"].get("summary", ""))
|
|
97
|
+
coverage = payload.get("coverage") or payload
|
|
98
|
+
if coverage.get("summary"):
|
|
99
|
+
lines.append(coverage["summary"])
|
|
100
|
+
if coverage.get("derivation") and coverage["derivation"] not in (coverage.get("summary") or ""):
|
|
101
|
+
lines.append(coverage["derivation"])
|
|
102
|
+
return "\n".join(line for line in lines if line)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""Gather facts from a folder, then hand them to assurance-core for verdicts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from assurance_core.coverage import Coverage, EvidenceRef, Expectation
|
|
9
|
+
from assurance_core.report_period import Period, parse_period_range
|
|
10
|
+
from assurance_core.sequence import (
|
|
11
|
+
DetectedSeries,
|
|
12
|
+
SeriesKind,
|
|
13
|
+
detect_series,
|
|
14
|
+
enumerate_between,
|
|
15
|
+
explicit_derivation,
|
|
16
|
+
inference_derivation,
|
|
17
|
+
parse_point,
|
|
18
|
+
point_from_filename,
|
|
19
|
+
point_key,
|
|
20
|
+
)
|
|
21
|
+
from assurance_core.staleness import Finding, Verdict, compare
|
|
22
|
+
|
|
23
|
+
from assurance_cli.paths import PathEscapeError, resolve_folder, resolve_inside
|
|
24
|
+
from assurance_cli.profile import TABULAR_SUFFIXES, profile_file
|
|
25
|
+
|
|
26
|
+
MAX_PERIODS = 36
|
|
27
|
+
MAX_NUMBERED = 500
|
|
28
|
+
MIN_FILES_TO_INFER = 3
|
|
29
|
+
|
|
30
|
+
_KIND_FROM_NAME = {
|
|
31
|
+
"monthly": SeriesKind.MONTHLY,
|
|
32
|
+
"quarterly": SeriesKind.QUARTERLY,
|
|
33
|
+
"weekly": SeriesKind.WEEKLY,
|
|
34
|
+
"daily": SeriesKind.DAILY,
|
|
35
|
+
"numbered": SeriesKind.NUMBERED,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def list_dated_files(folder: str) -> dict[str, Any]:
|
|
40
|
+
"""List sequence points present in a folder from dated tabular filenames."""
|
|
41
|
+
root = resolve_folder(folder)
|
|
42
|
+
by_key = _indexed_files(root)
|
|
43
|
+
keys = sorted(by_key)
|
|
44
|
+
return {
|
|
45
|
+
"folder": str(root),
|
|
46
|
+
"periods": [
|
|
47
|
+
{
|
|
48
|
+
"key": key,
|
|
49
|
+
"label": _label_for_key(key, by_key[key][0].name),
|
|
50
|
+
"files": [str(path) for path in by_key[key]],
|
|
51
|
+
}
|
|
52
|
+
for key in keys
|
|
53
|
+
],
|
|
54
|
+
"count": len(keys),
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def check_coverage(
|
|
59
|
+
folder: str,
|
|
60
|
+
period_range: str | None = None,
|
|
61
|
+
*,
|
|
62
|
+
expect: str | None = None,
|
|
63
|
+
from_point: str | None = None,
|
|
64
|
+
to_point: str | None = None,
|
|
65
|
+
) -> dict[str, Any]:
|
|
66
|
+
"""Check whether every step in the span is present — cold start, no prior state."""
|
|
67
|
+
root = resolve_folder(folder)
|
|
68
|
+
by_key = _indexed_files(root)
|
|
69
|
+
if not by_key:
|
|
70
|
+
return {
|
|
71
|
+
"folder": str(root),
|
|
72
|
+
"summary": f"Nothing in {root.name} has a recognisable sequence in its name.",
|
|
73
|
+
"complete": False,
|
|
74
|
+
"derivation": "",
|
|
75
|
+
"coverage": _coverage_to_dict(
|
|
76
|
+
Coverage(scope_label=f"items in {root.name}", expected=[])
|
|
77
|
+
),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
filenames = [path.name for paths in by_key.values() for path in paths]
|
|
81
|
+
detected = detect_series(filenames)
|
|
82
|
+
kind = _resolve_kind(expect, detected)
|
|
83
|
+
|
|
84
|
+
if kind is None:
|
|
85
|
+
return {
|
|
86
|
+
"folder": str(root),
|
|
87
|
+
"summary": "No dated or numbered series detected.",
|
|
88
|
+
"complete": False,
|
|
89
|
+
"derivation": "",
|
|
90
|
+
"coverage": _coverage_to_dict(
|
|
91
|
+
Coverage(scope_label=f"items in {root.name}", expected=[])
|
|
92
|
+
),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
unit = _unit_for_kind(kind)
|
|
96
|
+
derivation = ""
|
|
97
|
+
|
|
98
|
+
if from_point and to_point:
|
|
99
|
+
start = parse_point(from_point, kind)
|
|
100
|
+
end = parse_point(to_point, kind)
|
|
101
|
+
if start is None or end is None:
|
|
102
|
+
return _error_result(root, "Could not parse --from / --to for the detected series kind.")
|
|
103
|
+
expected_keys = enumerate_between(start, end)
|
|
104
|
+
derivation = explicit_derivation(kind, point_key(start), point_key(end)) # type: ignore[arg-type]
|
|
105
|
+
scope = f"{unit} from {point_key(start)} to {point_key(end)} in {root.name}" # type: ignore[arg-type]
|
|
106
|
+
elif period_range and kind is SeriesKind.MONTHLY:
|
|
107
|
+
available = sorted(p for p in (point_from_filename(n) for n in filenames) if isinstance(p, Period))
|
|
108
|
+
window = parse_period_range(period_range, available) # type: ignore[arg-type]
|
|
109
|
+
if window is None:
|
|
110
|
+
return _error_result(root, f"Could not parse period range: {period_range!r}")
|
|
111
|
+
expected_keys = enumerate_between(window[0], window[1])
|
|
112
|
+
derivation = f"Range set by request: {period_range!r}."
|
|
113
|
+
scope = f"months from {window[0].label} to {window[1].label} in {root.name}"
|
|
114
|
+
elif detected is not None and len(detected.points) >= MIN_FILES_TO_INFER:
|
|
115
|
+
expected_keys = enumerate_between(detected.earliest, detected.latest) # type: ignore[arg-type]
|
|
116
|
+
derivation = inference_derivation(detected)
|
|
117
|
+
scope = f"{unit} from {point_key(detected.earliest)} to {point_key(detected.latest)} in {root.name}" # type: ignore[arg-type]
|
|
118
|
+
else:
|
|
119
|
+
return {
|
|
120
|
+
"folder": str(root),
|
|
121
|
+
"summary": "No dated or numbered series detected.",
|
|
122
|
+
"complete": False,
|
|
123
|
+
"derivation": "",
|
|
124
|
+
"coverage": _coverage_to_dict(
|
|
125
|
+
Coverage(scope_label=f"items in {root.name}", expected=[])
|
|
126
|
+
),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
truncated = ""
|
|
130
|
+
cap = MAX_NUMBERED if kind is SeriesKind.NUMBERED else MAX_PERIODS
|
|
131
|
+
if len(expected_keys) > cap:
|
|
132
|
+
truncated = f"stopped at {cap} {unit}"
|
|
133
|
+
expected_keys = expected_keys[-cap:]
|
|
134
|
+
|
|
135
|
+
cov = Coverage(scope_label=scope, truncated=truncated, derivation=derivation)
|
|
136
|
+
for key, label in expected_keys:
|
|
137
|
+
expectation = Expectation(key=key, label=label, why=derivation or f"in {scope}")
|
|
138
|
+
cov.expected.append(expectation)
|
|
139
|
+
candidates = by_key.get(key, [])
|
|
140
|
+
|
|
141
|
+
if not candidates:
|
|
142
|
+
cov.missing.append(expectation)
|
|
143
|
+
continue
|
|
144
|
+
if len(candidates) > 1:
|
|
145
|
+
cov.ambiguous[key] = [str(path) for path in candidates]
|
|
146
|
+
continue
|
|
147
|
+
|
|
148
|
+
path = candidates[0]
|
|
149
|
+
facts = profile_file(path)
|
|
150
|
+
if facts is None or facts.get("rows", 0) == 0:
|
|
151
|
+
cov.unreadable[key] = "could not be read as a table"
|
|
152
|
+
continue
|
|
153
|
+
|
|
154
|
+
cov.found[key] = EvidenceRef(key=key, path=str(path), reader="assurance-cli")
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
"folder": str(root),
|
|
158
|
+
"summary": cov.summary(),
|
|
159
|
+
"complete": cov.complete,
|
|
160
|
+
"derivation": cov.derivation,
|
|
161
|
+
"coverage": _coverage_to_dict(cov),
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def check_staleness(
|
|
166
|
+
folder: str,
|
|
167
|
+
document: str,
|
|
168
|
+
source: str,
|
|
169
|
+
*,
|
|
170
|
+
recorded_facts: dict[str, Any] | None = None,
|
|
171
|
+
) -> dict[str, Any]:
|
|
172
|
+
"""Compare recorded figures to a freshly profiled source the caller names."""
|
|
173
|
+
root = resolve_folder(folder)
|
|
174
|
+
document_path = resolve_inside(root, document)
|
|
175
|
+
source_path = resolve_inside(root, source)
|
|
176
|
+
|
|
177
|
+
if not document_path.is_file():
|
|
178
|
+
return _finding_to_dict(
|
|
179
|
+
compare(
|
|
180
|
+
artifact_name=document_path.name,
|
|
181
|
+
artifact_path=str(document_path),
|
|
182
|
+
generated_at="",
|
|
183
|
+
source_name=source_path.name,
|
|
184
|
+
source_mtime=None,
|
|
185
|
+
recorded_facts=None,
|
|
186
|
+
current_facts=None,
|
|
187
|
+
uncheckable_reason=document_path.name,
|
|
188
|
+
)
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
if not source_path.is_file():
|
|
192
|
+
return _finding_to_dict(
|
|
193
|
+
compare(
|
|
194
|
+
artifact_name=document_path.name,
|
|
195
|
+
artifact_path=str(document_path),
|
|
196
|
+
generated_at="",
|
|
197
|
+
source_name=source_path.name,
|
|
198
|
+
source_mtime=None,
|
|
199
|
+
recorded_facts=recorded_facts,
|
|
200
|
+
current_facts=None,
|
|
201
|
+
source_gone=True,
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
recorded = recorded_facts if recorded_facts is not None else profile_file(document_path)
|
|
206
|
+
current = profile_file(source_path)
|
|
207
|
+
source_mtime = source_path.stat().st_mtime if source_path.exists() else None
|
|
208
|
+
|
|
209
|
+
finding = compare(
|
|
210
|
+
artifact_name=document_path.name,
|
|
211
|
+
artifact_path=str(document_path),
|
|
212
|
+
generated_at="",
|
|
213
|
+
source_name=source_path.name,
|
|
214
|
+
source_mtime=source_mtime,
|
|
215
|
+
recorded_facts=recorded,
|
|
216
|
+
current_facts=current,
|
|
217
|
+
)
|
|
218
|
+
return _finding_to_dict(finding)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _indexed_files(root: Path) -> dict[str, list[Path]]:
|
|
222
|
+
found: dict[str, list[Path]] = {}
|
|
223
|
+
for path in sorted(root.rglob("*")):
|
|
224
|
+
if not path.is_file() or path.suffix.lower() not in TABULAR_SUFFIXES:
|
|
225
|
+
continue
|
|
226
|
+
if path.name == ".assurance.json":
|
|
227
|
+
continue
|
|
228
|
+
try:
|
|
229
|
+
resolve_inside(root, str(path.relative_to(root)))
|
|
230
|
+
except PathEscapeError:
|
|
231
|
+
continue
|
|
232
|
+
point = point_from_filename(path.name)
|
|
233
|
+
if point is None:
|
|
234
|
+
continue
|
|
235
|
+
key = point_key(point) # type: ignore[arg-type]
|
|
236
|
+
found.setdefault(key, []).append(path)
|
|
237
|
+
return found
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _label_for_key(key: str, filename: str) -> str:
|
|
241
|
+
point = point_from_filename(filename)
|
|
242
|
+
if point is None:
|
|
243
|
+
return key
|
|
244
|
+
if isinstance(point, Period):
|
|
245
|
+
return point.label
|
|
246
|
+
return point.label
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _resolve_kind(expect: str | None, detected: DetectedSeries | None) -> SeriesKind | None:
|
|
250
|
+
if expect:
|
|
251
|
+
return _KIND_FROM_NAME.get(expect.lower())
|
|
252
|
+
if detected is not None:
|
|
253
|
+
return detected.kind
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _unit_for_kind(kind: SeriesKind) -> str:
|
|
258
|
+
return {
|
|
259
|
+
SeriesKind.MONTHLY: "months",
|
|
260
|
+
SeriesKind.QUARTERLY: "quarters",
|
|
261
|
+
SeriesKind.WEEKLY: "weeks",
|
|
262
|
+
SeriesKind.DAILY: "days",
|
|
263
|
+
SeriesKind.NUMBERED: "runs",
|
|
264
|
+
}[kind]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _error_result(root: Path, message: str) -> dict[str, Any]:
|
|
268
|
+
return {
|
|
269
|
+
"folder": str(root),
|
|
270
|
+
"summary": message,
|
|
271
|
+
"complete": False,
|
|
272
|
+
"derivation": "",
|
|
273
|
+
"coverage": _coverage_to_dict(Coverage(scope_label=f"items in {root.name}", expected=[])),
|
|
274
|
+
"error": message,
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _coverage_to_dict(cov: Coverage) -> dict[str, Any]:
|
|
279
|
+
return {
|
|
280
|
+
"scope_label": cov.scope_label,
|
|
281
|
+
"read": cov.read,
|
|
282
|
+
"required": cov.required,
|
|
283
|
+
"complete": cov.complete,
|
|
284
|
+
"derivation": cov.derivation,
|
|
285
|
+
"expected": [_expectation(e) for e in cov.expected],
|
|
286
|
+
"found": {key: _evidence(ref) for key, ref in cov.found.items()},
|
|
287
|
+
"missing": [_expectation(e) for e in cov.missing],
|
|
288
|
+
"gone": dict(cov.gone),
|
|
289
|
+
"ambiguous": dict(cov.ambiguous),
|
|
290
|
+
"unreadable": dict(cov.unreadable),
|
|
291
|
+
"unauthorized": dict(cov.unauthorized),
|
|
292
|
+
"truncated": cov.truncated,
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _expectation(exp: Expectation) -> dict[str, str]:
|
|
297
|
+
return {"key": exp.key, "label": exp.label, "why": exp.why}
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _evidence(ref: EvidenceRef) -> dict[str, Any]:
|
|
301
|
+
return {
|
|
302
|
+
"key": ref.key,
|
|
303
|
+
"path": ref.path,
|
|
304
|
+
"reader": ref.reader,
|
|
305
|
+
"bytes": ref.bytes,
|
|
306
|
+
"sha256": ref.sha256,
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _finding_to_dict(finding: Finding) -> dict[str, Any]:
|
|
311
|
+
return {
|
|
312
|
+
"verdict": finding.verdict.value,
|
|
313
|
+
"sentence": finding.sentence(),
|
|
314
|
+
"artifact_name": finding.artifact_name,
|
|
315
|
+
"artifact_path": finding.artifact_path,
|
|
316
|
+
"source_name": finding.source_name,
|
|
317
|
+
"source_modified_at": finding.source_modified_at,
|
|
318
|
+
"divergences": [
|
|
319
|
+
{
|
|
320
|
+
"measure": div.measure,
|
|
321
|
+
"claimed": div.claimed,
|
|
322
|
+
"current": div.current,
|
|
323
|
+
"delta": div.delta,
|
|
324
|
+
}
|
|
325
|
+
for div in finding.divergences
|
|
326
|
+
],
|
|
327
|
+
"uncheckable": finding.verdict is Verdict.UNCHECKABLE,
|
|
328
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Resolve caller paths and refuse escapes outside the named folder."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PathEscapeError(ValueError):
|
|
9
|
+
"""A path would read outside the folder the caller named."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def resolve_folder(folder: str) -> Path:
|
|
13
|
+
"""Resolve and validate a folder the caller named."""
|
|
14
|
+
if not folder or not str(folder).strip():
|
|
15
|
+
raise PathEscapeError("folder is required")
|
|
16
|
+
root = Path(folder).expanduser()
|
|
17
|
+
if not root.exists():
|
|
18
|
+
raise FileNotFoundError(f"folder does not exist: {folder}")
|
|
19
|
+
if not root.is_dir():
|
|
20
|
+
raise NotADirectoryError(f"not a directory: {folder}")
|
|
21
|
+
return _real(root)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def resolve_inside(root: Path, path: str) -> Path:
|
|
25
|
+
"""Resolve `path` and require it stays inside `root`."""
|
|
26
|
+
if not path or not str(path).strip():
|
|
27
|
+
raise PathEscapeError("path is required")
|
|
28
|
+
root = _real(root)
|
|
29
|
+
candidate = Path(path).expanduser()
|
|
30
|
+
if not candidate.is_absolute():
|
|
31
|
+
candidate = root / candidate
|
|
32
|
+
resolved = _real(candidate)
|
|
33
|
+
if resolved != root and root not in resolved.parents:
|
|
34
|
+
raise PathEscapeError(f"path escapes the named folder: {path}")
|
|
35
|
+
return resolved
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _real(path: Path) -> Path:
|
|
39
|
+
try:
|
|
40
|
+
return path.resolve(strict=False)
|
|
41
|
+
except OSError as exc:
|
|
42
|
+
raise PathEscapeError(f"cannot resolve path: {path}") from exc
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Tabular profiling for coverage and staleness — CSV, TSV, and XLSX."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import hashlib
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
TABULAR_SUFFIXES = {".csv", ".tsv", ".xlsx"}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def profile_file(path: Path) -> dict | None:
|
|
13
|
+
"""Return a facts-shaped dict compatible with `staleness.extract_measures`, or None."""
|
|
14
|
+
suffix = path.suffix.lower()
|
|
15
|
+
if suffix == ".xlsx":
|
|
16
|
+
return _profile_xlsx(path)
|
|
17
|
+
if suffix in {".csv", ".tsv"}:
|
|
18
|
+
return _profile_csv(path, delimiter="\t" if suffix == ".tsv" else ",")
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def file_sha256(path: Path) -> str:
|
|
23
|
+
"""Hash file contents, or empty string on failure."""
|
|
24
|
+
try:
|
|
25
|
+
digest = hashlib.sha256()
|
|
26
|
+
with path.open("rb") as handle:
|
|
27
|
+
for chunk in iter(lambda: handle.read(65536), b""):
|
|
28
|
+
digest.update(chunk)
|
|
29
|
+
return digest.hexdigest()
|
|
30
|
+
except OSError:
|
|
31
|
+
return ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _profile_csv(path: Path, *, delimiter: str) -> dict | None:
|
|
35
|
+
try:
|
|
36
|
+
with path.open(newline="", encoding="utf-8") as handle:
|
|
37
|
+
reader = csv.DictReader(handle, delimiter=delimiter)
|
|
38
|
+
fieldnames = reader.fieldnames or []
|
|
39
|
+
rows = list(reader)
|
|
40
|
+
except (OSError, UnicodeDecodeError, csv.Error):
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
if not fieldnames:
|
|
44
|
+
return {"rows": 0, "numeric": []}
|
|
45
|
+
|
|
46
|
+
return _facts_from_rows(fieldnames, rows)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _profile_xlsx(path: Path) -> dict | None:
|
|
50
|
+
try:
|
|
51
|
+
from openpyxl import load_workbook
|
|
52
|
+
except ImportError:
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
workbook = load_workbook(path, read_only=True, data_only=True)
|
|
57
|
+
sheet = workbook.active
|
|
58
|
+
rows_iter = sheet.iter_rows(values_only=True)
|
|
59
|
+
header = next(rows_iter, None)
|
|
60
|
+
if not header:
|
|
61
|
+
workbook.close()
|
|
62
|
+
return {"rows": 0, "numeric": []}
|
|
63
|
+
fieldnames = [str(cell) if cell is not None else "" for cell in header]
|
|
64
|
+
rows = [
|
|
65
|
+
{fieldnames[i]: ("" if value is None else value) for i, value in enumerate(row)}
|
|
66
|
+
for row in rows_iter
|
|
67
|
+
]
|
|
68
|
+
workbook.close()
|
|
69
|
+
except (OSError, ValueError):
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
return _facts_from_rows(fieldnames, rows)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _facts_from_rows(fieldnames: list[str], rows: list[dict]) -> dict:
|
|
76
|
+
numeric: list[dict[str, object]] = []
|
|
77
|
+
row_count = len(rows)
|
|
78
|
+
for column in fieldnames:
|
|
79
|
+
values: list[float] = []
|
|
80
|
+
for row in rows:
|
|
81
|
+
raw = str(row.get(column) or "").strip()
|
|
82
|
+
if not raw:
|
|
83
|
+
continue
|
|
84
|
+
cleaned = raw.replace(",", "").replace("$", "").replace("£", "").replace("€", "")
|
|
85
|
+
if cleaned.endswith("%"):
|
|
86
|
+
cleaned = cleaned[:-1]
|
|
87
|
+
try:
|
|
88
|
+
values.append(float(cleaned))
|
|
89
|
+
except ValueError:
|
|
90
|
+
values = []
|
|
91
|
+
break
|
|
92
|
+
if values and len(values) >= max(1, int(row_count * 0.8)):
|
|
93
|
+
numeric.append({"name": column, "total": sum(values)})
|
|
94
|
+
|
|
95
|
+
return {"rows": row_count, "numeric": numeric}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: assurance-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI for folder assurance checks — coverage, staleness, and baselines.
|
|
5
|
+
Author-email: "I-Ops Operations Intelligence, LLC" <hello@i-ops.dev>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://i-ops.dev
|
|
8
|
+
Project-URL: Source, https://github.com/i-ops-hq/assurance-cli
|
|
9
|
+
Keywords: cli,ai-agents,governance,auditing,assurance,reproducibility
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: assurance-core>=0.2
|
|
23
|
+
Requires-Dist: openpyxl>=3.1
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# assurance-cli
|
|
29
|
+
|
|
30
|
+
Command-line assurance checks over a folder — coverage gaps, baseline staleness, and machine-readable output for CI.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install assurance-cli
|
|
34
|
+
assurance check ~/data
|
|
35
|
+
assurance init ~/thesis-data
|
|
36
|
+
assurance check ~/thesis-data --against-baseline
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
See `assurance_core` for the pure arithmetic; this package owns all filesystem I/O.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
assurance_cli/__init__.py
|
|
5
|
+
assurance_cli/__main__.py
|
|
6
|
+
assurance_cli/baseline.py
|
|
7
|
+
assurance_cli/cli.py
|
|
8
|
+
assurance_cli/gather.py
|
|
9
|
+
assurance_cli/paths.py
|
|
10
|
+
assurance_cli/profile.py
|
|
11
|
+
assurance_cli.egg-info/PKG-INFO
|
|
12
|
+
assurance_cli.egg-info/SOURCES.txt
|
|
13
|
+
assurance_cli.egg-info/dependency_links.txt
|
|
14
|
+
assurance_cli.egg-info/entry_points.txt
|
|
15
|
+
assurance_cli.egg-info/requires.txt
|
|
16
|
+
assurance_cli.egg-info/top_level.txt
|
|
17
|
+
tests/test_cli.py
|
|
18
|
+
tests/test_read_only.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
assurance_cli
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "assurance-cli"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "CLI for folder assurance checks — coverage, staleness, and baselines."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "Apache-2.0" }
|
|
11
|
+
authors = [{ name = "I-Ops Operations Intelligence, LLC", email = "hello@i-ops.dev" }]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"assurance-core>=0.2",
|
|
15
|
+
"openpyxl>=3.1",
|
|
16
|
+
]
|
|
17
|
+
keywords = ["cli", "ai-agents", "governance", "auditing", "assurance", "reproducibility"]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"License :: OSI Approved :: Apache Software License",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://i-ops.dev"
|
|
32
|
+
Source = "https://github.com/i-ops-hq/assurance-cli"
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
dev = ["pytest>=8.0"]
|
|
36
|
+
|
|
37
|
+
[project.scripts]
|
|
38
|
+
assurance = "assurance_cli.cli:main"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.packages.find]
|
|
41
|
+
where = ["."]
|
|
42
|
+
include = ["assurance_cli*"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
testpaths = ["tests"]
|
|
46
|
+
pythonpath = ["."]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""CLI and gather tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from assurance_cli.baseline import BASELINE_NAME, check_against_baseline, init_baseline
|
|
12
|
+
from assurance_cli.cli import main
|
|
13
|
+
from assurance_cli.gather import check_coverage
|
|
14
|
+
from assurance_cli.paths import PathEscapeError, resolve_inside
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.fixture
|
|
18
|
+
def monthly_folder(tmp_path: Path) -> Path:
|
|
19
|
+
root = tmp_path / "reports"
|
|
20
|
+
root.mkdir()
|
|
21
|
+
for year in (2024, 2025):
|
|
22
|
+
for month in range(1, 13):
|
|
23
|
+
if (year, month) in {(2024, 3), (2025, 7)}:
|
|
24
|
+
continue
|
|
25
|
+
path = root / f"billing_{year}-{month:02d}.csv"
|
|
26
|
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
|
27
|
+
writer = csv.writer(handle)
|
|
28
|
+
writer.writerow(["amount"])
|
|
29
|
+
writer.writerow([100 * month])
|
|
30
|
+
return root
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.fixture
|
|
34
|
+
def numbered_folder(tmp_path: Path) -> Path:
|
|
35
|
+
root = tmp_path / "runs"
|
|
36
|
+
root.mkdir()
|
|
37
|
+
for n in range(1, 201):
|
|
38
|
+
if n in (47, 82):
|
|
39
|
+
continue
|
|
40
|
+
path = root / f"run_{n:03d}.csv"
|
|
41
|
+
path.write_text("value\n1\n", encoding="utf-8")
|
|
42
|
+
return root
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_check_coverage_reports_missing_months(monthly_folder: Path):
|
|
46
|
+
result = check_coverage(str(monthly_folder))
|
|
47
|
+
assert result["complete"] is False
|
|
48
|
+
assert "22 of 24" in result["summary"]
|
|
49
|
+
assert "March 2024" in result["summary"]
|
|
50
|
+
assert "July 2025" in result["summary"]
|
|
51
|
+
assert "Range inferred from filenames" in result["derivation"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_check_coverage_numbered_runs(numbered_folder: Path):
|
|
55
|
+
result = check_coverage(str(numbered_folder))
|
|
56
|
+
assert result["complete"] is False
|
|
57
|
+
assert "198 of 200" in result["summary"]
|
|
58
|
+
missing_keys = {item["key"] for item in result["coverage"]["missing"]}
|
|
59
|
+
assert missing_keys == {"run_047", "run_082"}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_explicit_range(monthly_folder: Path):
|
|
63
|
+
result = check_coverage(
|
|
64
|
+
str(monthly_folder),
|
|
65
|
+
expect="monthly",
|
|
66
|
+
from_point="2024-04",
|
|
67
|
+
to_point="2024-06",
|
|
68
|
+
)
|
|
69
|
+
assert result["coverage"]["required"] == 3
|
|
70
|
+
assert result["complete"] is True
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_path_escape_refuses_parent_traversal(monthly_folder: Path):
|
|
74
|
+
with pytest.raises(PathEscapeError):
|
|
75
|
+
resolve_inside(monthly_folder, "../outside.csv")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_baseline_init_and_detect_change(monthly_folder: Path):
|
|
79
|
+
init = init_baseline(str(monthly_folder))
|
|
80
|
+
assert init["written"] is True
|
|
81
|
+
assert (monthly_folder / BASELINE_NAME).is_file()
|
|
82
|
+
|
|
83
|
+
check = check_against_baseline(str(monthly_folder))
|
|
84
|
+
assert check["ok"] is True
|
|
85
|
+
|
|
86
|
+
target = next(monthly_folder.glob("billing_2024-01.csv"))
|
|
87
|
+
target.write_text("amount\n999\n", encoding="utf-8")
|
|
88
|
+
changed = check_against_baseline(str(monthly_folder))
|
|
89
|
+
assert changed["ok"] is False
|
|
90
|
+
assert "billing_2024-01.csv" in changed["changed"]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_cli_exit_codes(monthly_folder: Path, numbered_folder: Path):
|
|
94
|
+
assert main(["check", str(monthly_folder)]) == 0
|
|
95
|
+
assert main(["check", str(monthly_folder), "--fail-on-gap"]) == 1
|
|
96
|
+
assert main(["check", "/no/such/folder"]) == 2
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_cli_json_output(monthly_folder: Path, capsys):
|
|
100
|
+
code = main(["check", str(monthly_folder), "--json"])
|
|
101
|
+
assert code == 0
|
|
102
|
+
payload = json.loads(capsys.readouterr().out)
|
|
103
|
+
assert "coverage" in payload
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_counterfactual_complete_span_fails_when_month_removed(monthly_folder: Path, tmp_path: Path):
|
|
107
|
+
complete = tmp_path / "complete"
|
|
108
|
+
complete.mkdir()
|
|
109
|
+
for path in monthly_folder.glob("*.csv"):
|
|
110
|
+
(complete / path.name).write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
|
|
111
|
+
(complete / "billing_2024-03.csv").write_text("amount\n300\n", encoding="utf-8")
|
|
112
|
+
(complete / "billing_2025-07.csv").write_text("amount\n700\n", encoding="utf-8")
|
|
113
|
+
|
|
114
|
+
assert check_coverage(str(complete))["complete"] is True
|
|
115
|
+
(complete / "billing_2024-03.csv").unlink()
|
|
116
|
+
assert check_coverage(str(complete))["complete"] is False
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_mixed_series_folder_reports_none(tmp_path: Path):
|
|
120
|
+
root = tmp_path / "mixed"
|
|
121
|
+
root.mkdir()
|
|
122
|
+
for name in ("2024-01.csv", "2024-02.csv", "2024-03.csv", "run_001.csv"):
|
|
123
|
+
(root / name).write_text("v\n1\n", encoding="utf-8")
|
|
124
|
+
result = check_coverage(str(root))
|
|
125
|
+
assert "No dated or numbered series detected" in result["summary"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""CLI write gate — baseline is the only permitted write."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
PACKAGE = Path(__file__).resolve().parents[1] / "assurance_cli"
|
|
9
|
+
BASELINE_MODULE = "baseline.py"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_only_baseline_writes():
|
|
13
|
+
offenders: list[str] = []
|
|
14
|
+
for path in sorted(PACKAGE.glob("*.py")):
|
|
15
|
+
if path.name == BASELINE_MODULE:
|
|
16
|
+
continue
|
|
17
|
+
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
18
|
+
offenders.extend(_forbidden_writes(path, tree))
|
|
19
|
+
assert not offenders, "unexpected writes outside baseline.py:\n" + "\n".join(offenders)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _forbidden_writes(path: Path, tree: ast.AST) -> list[str]:
|
|
23
|
+
hits: list[str] = []
|
|
24
|
+
for node in ast.walk(tree):
|
|
25
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
|
26
|
+
if node.func.attr in {"write_text", "write_bytes"}:
|
|
27
|
+
hits.append(f"{path.name}: calls .{node.func.attr}()")
|
|
28
|
+
return hits
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_baseline_write_counterfactual():
|
|
32
|
+
sample = 'path.write_text("x")\n'
|
|
33
|
+
tree = ast.parse(sample)
|
|
34
|
+
assert _forbidden_writes(Path("cli.py"), tree)
|