de-censor 0.7.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.
censor/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Censor — audits a DE Arsenal project and grades it."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("de-censor")
censor/audit.py ADDED
@@ -0,0 +1,36 @@
1
+ """Load -> check -> score. The one entry point the CLI calls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from pathlib import Path
7
+
8
+ from censor import __version__
9
+ from censor.checks import QUICK_CHECKS
10
+ from censor.context import load_context
11
+ from censor.model import AuditReport
12
+ from censor.runner import run_checks
13
+ from censor.scoring import score_checks
14
+
15
+
16
+ def new_run_id(tier: str, now: datetime | None = None) -> str:
17
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
18
+ return f"{moment:%Y%m%d-%H%M%S}-{tier}"
19
+
20
+
21
+ def audit_project(root: Path, *, now: datetime | None = None) -> AuditReport:
22
+ ctx = load_context(root)
23
+ checks = run_checks(ctx, QUICK_CHECKS)
24
+ scored = score_checks(checks)
25
+ return AuditReport(
26
+ run_id=new_run_id("quick", now),
27
+ tier="quick",
28
+ target=str(ctx.root),
29
+ target_kind="project",
30
+ censor_version=__version__,
31
+ score=scored.score,
32
+ grade=scored.grade,
33
+ capped_by_blocker=scored.capped_by_blocker,
34
+ dimensions=scored.dimensions,
35
+ checks=checks,
36
+ )
@@ -0,0 +1,17 @@
1
+ """The Quick tier: checks that read files only, never data or the network."""
2
+
3
+ from censor.checks.agent import check_agent_readiness
4
+ from censor.checks.correctness import check_correctness
5
+ from censor.checks.guards import check_guards
6
+ from censor.checks.operability import check_operability
7
+ from censor.checks.security import check_security
8
+ from censor.model import Dimension
9
+ from censor.runner import CheckGroup
10
+
11
+ QUICK_CHECKS: tuple[CheckGroup, ...] = (
12
+ CheckGroup("correctness", Dimension.CORRECTNESS, check_correctness),
13
+ CheckGroup("guards", Dimension.GUARDS, check_guards),
14
+ CheckGroup("security", Dimension.SECURITY, check_security),
15
+ CheckGroup("operability", Dimension.OPERABILITY, check_operability),
16
+ CheckGroup("agent", Dimension.AGENT_READINESS, check_agent_readiness),
17
+ )
censor/checks/agent.py ADDED
@@ -0,0 +1,137 @@
1
+ """Can a coding agent operate this pipeline safely?
2
+
3
+ DE-specific harness checks only; generic harness quality is harness-eval's job.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+ from typing import Any, Final, cast
11
+
12
+ from censor.context import ProjectContext
13
+ from censor.model import CheckResult, Dimension, Status
14
+
15
+ PLUGIN_PREFIX: Final = "de-arsenal@"
16
+ REQUIRED_COMMANDS: Final = ("arsenal check", "arsenal run")
17
+ _STATE_DIR: Final = ".arsenal"
18
+
19
+
20
+ def _r(
21
+ check_id: str, weight: int, status: Status, subject: str, evidence: str, fix: str
22
+ ) -> CheckResult:
23
+ return CheckResult(
24
+ id=check_id,
25
+ dimension=Dimension.AGENT_READINESS,
26
+ weight=weight,
27
+ status=status,
28
+ subject=subject,
29
+ evidence=evidence,
30
+ fix=fix if status != Status.PASS else "",
31
+ )
32
+
33
+
34
+ def _settings(root: Path) -> tuple[dict[str, Any], str | None]:
35
+ path = root / ".claude" / "settings.json"
36
+ if not path.is_file():
37
+ return {}, None
38
+ try:
39
+ loaded: object = json.loads(path.read_text(encoding="utf-8"))
40
+ except OSError:
41
+ return {}, ".claude/settings.json is unreadable"
42
+ except (UnicodeDecodeError, json.JSONDecodeError):
43
+ return {}, ".claude/settings.json is not valid JSON"
44
+ return (cast(dict[str, Any], loaded), None) if isinstance(loaded, dict) else ({}, None)
45
+
46
+
47
+ def _claude_md(root: Path) -> CheckResult:
48
+ path = root / "CLAUDE.md"
49
+ fix = "add a CLAUDE.md that says to run `arsenal check` before and `arsenal run` after edits"
50
+ if not path.is_file():
51
+ return _r("agent.claude_md", 2, Status.FAIL, "CLAUDE.md", "no CLAUDE.md", fix)
52
+ try:
53
+ text = path.read_text(encoding="utf-8", errors="replace")
54
+ except OSError:
55
+ return _r("agent.claude_md", 2, Status.WARN, "CLAUDE.md", "CLAUDE.md is unreadable", fix)
56
+ missing = [c for c in REQUIRED_COMMANDS if c not in text]
57
+ if missing:
58
+ evidence = "CLAUDE.md does not mention " + ", ".join(f"`{c}`" for c in missing)
59
+ return _r("agent.claude_md", 2, Status.WARN, "CLAUDE.md", evidence, fix)
60
+ return _r("agent.claude_md", 2, Status.PASS, "CLAUDE.md", "names arsenal check and run", fix)
61
+
62
+
63
+ def _plugin(settings: dict[str, Any], problem: str | None) -> CheckResult:
64
+ enabled: object = settings.get("enabledPlugins", {})
65
+ entries = cast(dict[str, object], enabled) if isinstance(enabled, dict) else {}
66
+ named = {name: value for name, value in entries.items() if name.startswith(PLUGIN_PREFIX)}
67
+ ok = any(value is True for value in named.values())
68
+ if ok:
69
+ detail = "de-arsenal plugin enabled for this project"
70
+ elif named:
71
+ detail = "de-arsenal plugin is disabled in .claude/settings.json"
72
+ else:
73
+ detail = "de-arsenal plugin not enabled in .claude/settings.json"
74
+ evidence = problem or detail
75
+ return _r(
76
+ "agent.plugin",
77
+ 1,
78
+ Status.PASS if ok else Status.WARN,
79
+ ".claude/settings.json",
80
+ evidence,
81
+ "/plugin install de-arsenal@de-arsenal, then enable it for the project",
82
+ )
83
+
84
+
85
+ def _deny_rules(settings: dict[str, Any]) -> list[str]:
86
+ permissions: object = settings.get("permissions", {})
87
+ if not isinstance(permissions, dict):
88
+ return []
89
+ deny: object = cast(dict[str, object], permissions).get("deny", [])
90
+ if not isinstance(deny, list):
91
+ return []
92
+ return [r for r in cast(list[object], deny) if isinstance(r, str)]
93
+
94
+
95
+ def _deny_state(settings: dict[str, Any]) -> CheckResult:
96
+ ok = any(_STATE_DIR in rule for rule in _deny_rules(settings))
97
+ return _r(
98
+ "agent.deny_state",
99
+ 1,
100
+ Status.PASS if ok else Status.WARN,
101
+ ".claude/settings.json",
102
+ "a deny rule protects .arsenal/" if ok else "nothing stops an agent deleting .arsenal/",
103
+ 'add "Bash(rm -rf .arsenal*)" to permissions.deny: .arsenal/ holds run state',
104
+ )
105
+
106
+
107
+ def _secret_hook(root: Path) -> CheckResult:
108
+ hooks = root / ".claude" / "hooks"
109
+ found = False
110
+ for path in sorted(hooks.glob("*")) if hooks.is_dir() else []:
111
+ try:
112
+ text = (
113
+ path.read_text(encoding="utf-8", errors="replace").lower() if path.is_file() else ""
114
+ )
115
+ except OSError:
116
+ continue
117
+ if "secret" in text and ("yaml" in text or "yml" in text):
118
+ found = True
119
+ break
120
+ return _r(
121
+ "agent.secret_hook",
122
+ 1,
123
+ Status.PASS if found else Status.WARN,
124
+ ".claude/hooks",
125
+ "a secret-scan hook covers YAML" if found else "no secret-scan hook that covers YAML specs",
126
+ "add a PreToolUse hook that scans *.yaml for secrets before commit",
127
+ )
128
+
129
+
130
+ def check_agent_readiness(ctx: ProjectContext) -> list[CheckResult]:
131
+ settings, problem = _settings(ctx.root)
132
+ return [
133
+ _claude_md(ctx.root),
134
+ _plugin(settings, problem),
135
+ _deny_state(settings),
136
+ _secret_hook(ctx.root),
137
+ ]
@@ -0,0 +1,97 @@
1
+ """Do the manifest and every spec load and compile? Same rules as `arsenal check`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ from pathlib import Path
7
+ from typing import Final
8
+
9
+ from arsenal.project import DbtProjectRef
10
+
11
+ from arsenal_core.errors import ArsenalError
12
+ from arsenal_core.spec import load_pipeline
13
+ from censor.context import ProjectContext
14
+ from censor.model import CheckResult, Dimension, Status
15
+ from gladius.compile import compile_sql
16
+ from gladius.loader import load_transform
17
+
18
+ _DIM: Final = Dimension.CORRECTNESS
19
+ _ENV_NOT_SET: Final = "environment variable not set"
20
+
21
+
22
+ def _result(
23
+ check_id: str, weight: int, status: Status, subject: str, evidence: str, fix: str = ""
24
+ ) -> CheckResult:
25
+ return CheckResult(
26
+ id=check_id,
27
+ dimension=_DIM,
28
+ weight=weight,
29
+ status=status,
30
+ blocker=status == Status.FAIL,
31
+ subject=subject,
32
+ evidence=evidence,
33
+ fix=fix,
34
+ )
35
+
36
+
37
+ def _name(ctx: ProjectContext, path: Path) -> str:
38
+ try:
39
+ return str(path.relative_to(ctx.root))
40
+ except ValueError:
41
+ return str(path)
42
+
43
+
44
+ def _pipeline(ctx: ProjectContext, path: Path) -> CheckResult:
45
+ name = _name(ctx, path)
46
+ check_id = f"correctness.pipeline:{name}"
47
+ try:
48
+ load_pipeline(path)
49
+ except ArsenalError as e:
50
+ message = str(e)
51
+ if message.startswith(_ENV_NOT_SET):
52
+ return _result(
53
+ check_id,
54
+ 2,
55
+ Status.WARN,
56
+ name,
57
+ f"could not fully validate: {message}",
58
+ "set the variable in this shell to validate the whole spec",
59
+ )
60
+ return _result(check_id, 2, Status.FAIL, name, message, "fix the field the message names")
61
+ return _result(check_id, 2, Status.PASS, name, "spec is valid")
62
+
63
+
64
+ def _transform(ctx: ProjectContext, ref: Path | DbtProjectRef) -> CheckResult:
65
+ if isinstance(ref, DbtProjectRef):
66
+ name = _name(ctx, ref.dbt)
67
+ return _result(
68
+ f"correctness.transform:{name}", 2, Status.NA, name, "dbt projects are not checked"
69
+ )
70
+ name = _name(ctx, ref)
71
+ check_id = f"correctness.transform:{name}"
72
+ try:
73
+ compile_sql(load_transform(ref))
74
+ except ArsenalError as e:
75
+ return _result(check_id, 2, Status.FAIL, name, str(e), "fix the step the message names")
76
+ return _result(check_id, 2, Status.PASS, name, "compiles")
77
+
78
+
79
+ def check_correctness(ctx: ProjectContext) -> list[CheckResult]:
80
+ if ctx.manifest is None:
81
+ return [
82
+ _result(
83
+ "correctness.manifest",
84
+ 3,
85
+ Status.FAIL,
86
+ "arsenal.yaml",
87
+ ctx.manifest_error or "invalid manifest",
88
+ "fix arsenal.yaml, then run `arsenal check`",
89
+ )
90
+ ]
91
+ results = [_result("correctness.manifest", 3, Status.PASS, "arsenal.yaml", "manifest is valid")]
92
+ with contextlib.chdir(
93
+ ctx.root
94
+ ): # specs use paths relative to the project, like `arsenal check`
95
+ results.extend(_pipeline(ctx, p.path) for p in ctx.pipelines)
96
+ results.extend(_transform(ctx, t) for t in ctx.transforms)
97
+ return results
@@ -0,0 +1,111 @@
1
+ """Does each pipeline keep bad data out? Reads raw YAML so unset env vars do not matter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final, cast
6
+
7
+ from censor.context import ProjectContext, SpecFile
8
+ from censor.model import CheckResult, Dimension, Status
9
+
10
+ _DIM: Final = Dimension.GUARDS
11
+
12
+
13
+ def _r(
14
+ kind: str, spec: SpecFile, weight: int, status: Status, evidence: str, fix: str
15
+ ) -> CheckResult:
16
+ return CheckResult(
17
+ id=f"guards.{kind}:{spec.name}",
18
+ dimension=_DIM,
19
+ weight=weight,
20
+ status=status,
21
+ subject=spec.name,
22
+ evidence=evidence,
23
+ fix=fix if status != Status.PASS else "",
24
+ )
25
+
26
+
27
+ def _rules(validate: dict[str, Any]) -> list[dict[str, Any]]:
28
+ rules: object = validate.get("rules", [])
29
+ if not isinstance(rules, list):
30
+ return []
31
+ return [cast(dict[str, Any], r) for r in cast(list[object], rules) if isinstance(r, dict)]
32
+
33
+
34
+ def _pipeline_guards(spec: SpecFile, raw: dict[str, Any]) -> list[CheckResult]:
35
+ validate_raw: object = raw.get("validate")
36
+ validate = cast(dict[str, Any], validate_raw) if isinstance(validate_raw, dict) else None
37
+ if not validate: # an empty or non-mapping block guards nothing
38
+ validate = None
39
+ results = [
40
+ _r(
41
+ "validate",
42
+ spec,
43
+ 3,
44
+ Status.PASS if validate else Status.FAIL,
45
+ "validate block present"
46
+ if validate
47
+ else "no validate block: bad values load unchecked",
48
+ "add `validate.rules` from what the first clean run showed (trust skill)",
49
+ ),
50
+ ]
51
+ if validate is None:
52
+ results.append(_r("on_violation", spec, 2, Status.NA, "no validate block", ""))
53
+ results.append(_r("key_rules", spec, 2, Status.NA, "no validate block", ""))
54
+ else:
55
+ explicit = "on_violation" in validate
56
+ results.append(
57
+ _r(
58
+ "on_violation",
59
+ spec,
60
+ 2,
61
+ Status.PASS if explicit else Status.WARN,
62
+ f"on_violation: {validate['on_violation']}"
63
+ if explicit
64
+ else "on_violation omitted: defaults to quarantine, which sets whole files aside",
65
+ "write `on_violation: split` unless one bad row must reject the file",
66
+ )
67
+ )
68
+ keyed = any(r.get("not_null") or r.get("unique") for r in _rules(validate))
69
+ results.append(
70
+ _r(
71
+ "key_rules",
72
+ spec,
73
+ 2,
74
+ Status.PASS if keyed else Status.WARN,
75
+ "a rule checks not_null or unique"
76
+ if keyed
77
+ else "no not_null/unique rule on any field",
78
+ "add `{ field: <key>, not_null: true, unique: true }` for the row key",
79
+ )
80
+ )
81
+ drift = raw.get("schema_drift", "allow")
82
+ results.append(
83
+ _r(
84
+ "schema_drift",
85
+ spec,
86
+ 2,
87
+ Status.PASS if drift in ("warn", "block") else Status.WARN,
88
+ f"schema_drift: {drift}",
89
+ "set `schema_drift: block` (or `warn`) so changed source columns are noticed",
90
+ )
91
+ )
92
+ has_contract = isinstance(raw.get("contract"), dict)
93
+ results.append(
94
+ _r(
95
+ "contract",
96
+ spec,
97
+ 1,
98
+ Status.PASS if has_contract else Status.WARN,
99
+ "contract declared" if has_contract else "no contract on the output shape",
100
+ "declare `contract.columns` when someone downstream depends on exact columns",
101
+ )
102
+ )
103
+ return results
104
+
105
+
106
+ def check_guards(ctx: ProjectContext) -> list[CheckResult]:
107
+ results: list[CheckResult] = []
108
+ for spec in ctx.pipelines:
109
+ if spec.raw is not None:
110
+ results.extend(_pipeline_guards(spec, spec.raw))
111
+ return results
@@ -0,0 +1,116 @@
1
+ """Can someone else run, schedule and trace this project?"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Final
8
+
9
+ from censor.context import ProjectContext
10
+ from censor.model import CheckResult, Dimension, Status
11
+
12
+ # Fixed locations only: globbing the whole tree would walk data/ and .venv/.
13
+ SCHEDULE_GLOBS: Final[tuple[str, ...]] = (
14
+ "dags/*.py",
15
+ "airflow/dags/*.py",
16
+ ".github/workflows/*.yml",
17
+ ".github/workflows/*.yaml",
18
+ "crontab",
19
+ )
20
+ _SCHEDULE_MARKERS: Final = ("arsenal", "pugio", "gladius")
21
+ # A file is a schedule only if it names the project's tools AND declares a trigger.
22
+ _WORKFLOW_TRIGGER: Final = "schedule:" # GitHub `on: schedule: - cron:`
23
+ _DAG_TRIGGER: Final = "schedule" # `schedule=` and `schedule_interval=`
24
+ _NO_SCHEDULE: Final = "no schedule found in dags/, airflow/dags/, .github/workflows/ or crontab"
25
+
26
+
27
+ # Aquila's default catalog file (aquila.service.DEFAULT_DB), relative to the project root.
28
+ AQUILA_CATALOG: Final = Path(".arsenal") / "aquila.db"
29
+ _DEPENDENCY_FILES: Final = ("pyproject.toml", "requirements*.txt")
30
+ _AQUILA_DEPENDENCY: Final = re.compile(
31
+ r"\bde-aquila\b|\bde-arsenal\[[^\]]*\bcatalog\b", re.IGNORECASE
32
+ )
33
+
34
+
35
+ def _lineage_evidence(root: Path) -> str | None:
36
+ """The project's own sign of a catalog: never the auditor's installed packages."""
37
+ if (root / AQUILA_CATALOG).is_file():
38
+ return f"aquila catalog at {AQUILA_CATALOG.as_posix()}"
39
+ for pattern in _DEPENDENCY_FILES:
40
+ for path in sorted(root.glob(pattern)):
41
+ try:
42
+ text = path.read_text(encoding="utf-8")
43
+ except (OSError, UnicodeDecodeError):
44
+ continue
45
+ lines = (ln for ln in text.splitlines() if not ln.lstrip().startswith("#"))
46
+ if any(_AQUILA_DEPENDENCY.search(ln) for ln in lines):
47
+ return f"{path.name} depends on aquila"
48
+ return None
49
+
50
+
51
+ def _r(
52
+ check_id: str, weight: int, status: Status, subject: str, evidence: str, fix: str
53
+ ) -> CheckResult:
54
+ return CheckResult(
55
+ id=check_id,
56
+ dimension=Dimension.OPERABILITY,
57
+ weight=weight,
58
+ status=status,
59
+ subject=subject,
60
+ evidence=evidence,
61
+ fix=fix if status != Status.PASS else "",
62
+ )
63
+
64
+
65
+ def _declares_schedule(path: Path, text: str) -> bool:
66
+ if path.name == "crontab":
67
+ lines = (ln for ln in text.splitlines() if not ln.lstrip().startswith("#"))
68
+ return any(m in ln for ln in lines for m in _SCHEDULE_MARKERS)
69
+ if not any(marker in text for marker in _SCHEDULE_MARKERS):
70
+ return False
71
+ trigger = _DAG_TRIGGER if path.suffix == ".py" else _WORKFLOW_TRIGGER
72
+ return trigger in text
73
+
74
+
75
+ def _schedule_file(root: Path) -> Path | None:
76
+ for pattern in SCHEDULE_GLOBS:
77
+ for path in sorted(root.glob(pattern)):
78
+ try:
79
+ text = path.read_text(encoding="utf-8").lower()
80
+ except (OSError, UnicodeDecodeError):
81
+ continue
82
+ if _declares_schedule(path, text):
83
+ return path
84
+ return None
85
+
86
+
87
+ def check_operability(ctx: ProjectContext) -> list[CheckResult]:
88
+ has_readme = (ctx.root / "README.md").is_file()
89
+ schedule = _schedule_file(ctx.root)
90
+ lineage = _lineage_evidence(ctx.root)
91
+ return [
92
+ _r(
93
+ "operability.readme",
94
+ 1,
95
+ Status.PASS if has_readme else Status.FAIL,
96
+ "README.md",
97
+ "README.md present" if has_readme else "no README.md",
98
+ "add a README saying what the pipeline loads and who uses it",
99
+ ),
100
+ _r(
101
+ "operability.schedule",
102
+ 2,
103
+ Status.PASS if schedule else Status.WARN,
104
+ str(schedule.relative_to(ctx.root)) if schedule else "project",
105
+ "runs on a schedule" if schedule else _NO_SCHEDULE,
106
+ "schedule `arsenal run` (see examples/transfer/airflow)",
107
+ ),
108
+ _r(
109
+ "operability.lineage",
110
+ 1,
111
+ Status.PASS if lineage else Status.WARN,
112
+ "aquila",
113
+ lineage or "no aquila catalog or dependency in the project: no lineage",
114
+ "pip install 'de-arsenal[catalog]', then `aquila scan`",
115
+ ),
116
+ ]