shipwright-kit 0.6.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.
Files changed (37) hide show
  1. shipwright_kit-0.6.0/LICENSE +21 -0
  2. shipwright_kit-0.6.0/PKG-INFO +164 -0
  3. shipwright_kit-0.6.0/README.md +135 -0
  4. shipwright_kit-0.6.0/pyproject.toml +81 -0
  5. shipwright_kit-0.6.0/setup.cfg +4 -0
  6. shipwright_kit-0.6.0/shipwright_kit/__init__.py +3 -0
  7. shipwright_kit-0.6.0/shipwright_kit/cli.py +36 -0
  8. shipwright_kit-0.6.0/shipwright_kit/config.py +53 -0
  9. shipwright_kit-0.6.0/shipwright_kit/design/__init__.py +24 -0
  10. shipwright_kit-0.6.0/shipwright_kit/design/banner.py +21 -0
  11. shipwright_kit-0.6.0/shipwright_kit/design/console.py +33 -0
  12. shipwright_kit-0.6.0/shipwright_kit/design/glyphs.py +30 -0
  13. shipwright_kit-0.6.0/shipwright_kit/design/output.py +60 -0
  14. shipwright_kit-0.6.0/shipwright_kit/design/palette.py +46 -0
  15. shipwright_kit-0.6.0/shipwright_kit/design/tiers.py +33 -0
  16. shipwright_kit-0.6.0/shipwright_kit/eval/__init__.py +7 -0
  17. shipwright_kit-0.6.0/shipwright_kit/eval/corpus.py +34 -0
  18. shipwright_kit-0.6.0/shipwright_kit/eval/harness.py +50 -0
  19. shipwright_kit-0.6.0/shipwright_kit/eval/metrics.py +66 -0
  20. shipwright_kit-0.6.0/shipwright_kit/py.typed +0 -0
  21. shipwright_kit-0.6.0/shipwright_kit/security/__init__.py +17 -0
  22. shipwright_kit-0.6.0/shipwright_kit/security/eval.py +26 -0
  23. shipwright_kit-0.6.0/shipwright_kit/security/injection.py +206 -0
  24. shipwright_kit-0.6.0/shipwright_kit/security/theme.py +34 -0
  25. shipwright_kit-0.6.0/shipwright_kit.egg-info/PKG-INFO +164 -0
  26. shipwright_kit-0.6.0/shipwright_kit.egg-info/SOURCES.txt +35 -0
  27. shipwright_kit-0.6.0/shipwright_kit.egg-info/dependency_links.txt +1 -0
  28. shipwright_kit-0.6.0/shipwright_kit.egg-info/entry_points.txt +2 -0
  29. shipwright_kit-0.6.0/shipwright_kit.egg-info/requires.txt +6 -0
  30. shipwright_kit-0.6.0/shipwright_kit.egg-info/top_level.txt +1 -0
  31. shipwright_kit-0.6.0/tests/test_cli.py +64 -0
  32. shipwright_kit-0.6.0/tests/test_config.py +67 -0
  33. shipwright_kit-0.6.0/tests/test_packaging.py +24 -0
  34. shipwright_kit-0.6.0/tests/test_packs_entrypoint.py +12 -0
  35. shipwright_kit-0.6.0/tests/test_release_config.py +18 -0
  36. shipwright_kit-0.6.0/tests/test_template_wiring.py +72 -0
  37. shipwright_kit-0.6.0/tests/test_tooling.py +15 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Christian Huhn
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,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: shipwright-kit
3
+ Version: 0.6.0
4
+ Summary: Shipwright — AI-agent dev framework + import-light design/eval/security library
5
+ Author: Christian Huhn
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/duathron/shipwright
8
+ Project-URL: Repository, https://github.com/duathron/shipwright
9
+ Project-URL: Documentation, https://github.com/duathron/shipwright/blob/main/docs/library.md
10
+ Project-URL: Changelog, https://github.com/duathron/shipwright/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/duathron/shipwright/issues
12
+ Keywords: ci,dev-tooling,eval,design-tokens,severity,quality-gates
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
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
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: rich
25
+ Requires-Dist: rich>=13.7; extra == "rich"
26
+ Provides-Extra: banner
27
+ Requires-Dist: pyfiglet>=1.0; extra == "banner"
28
+ Dynamic: license-file
29
+
30
+ # Shipwright
31
+
32
+ ![CI](https://github.com/duathron/shipwright/actions/workflows/ci.yml/badge.svg)
33
+ ![CodeQL](https://github.com/duathron/shipwright/actions/workflows/codeql.yml/badge.svg)
34
+ ![Coverage](https://img.shields.io/badge/coverage-%E2%89%A590%25-brightgreen.svg)
35
+ ![Types](https://img.shields.io/badge/types-mypy-blue.svg)
36
+ ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
37
+ ![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)
38
+
39
+ Shipwright is two things that share one repo:
40
+
41
+ - an installable, **import-light Python library** of shared dev-tooling runtime —
42
+ `shipwright_kit.design` (severity tiers + accessible output), `shipwright_kit.eval`
43
+ (detection-quality eval harness), `shipwright_kit.security` (a security pack);
44
+ - an **AI-agent-operated development framework** — reusable CI/CD, a Copier
45
+ scaffolder, quality gates, and bundled agent skills + personas — that **dogfoods**
46
+ the library and the gates it hands to the projects built with it.
47
+
48
+ The library is consumed today by two real tools: **barb** and **sift** both import
49
+ `shipwright_kit.eval` to run their detection-quality gates.
50
+
51
+ ## Install
52
+
53
+ The library is **not on PyPI** — the bare name `shipwright` belongs to an unrelated
54
+ project, so the published distribution is **`shipwright-kit`** and the import name is
55
+ **`shipwright_kit`**. For now, install from git:
56
+
57
+ ```bash
58
+ uv pip install "git+https://github.com/duathron/shipwright@main"
59
+ # then: import shipwright_kit
60
+ ```
61
+
62
+ > [!NOTE]
63
+ > Pin a release tag instead of `@main` for reproducible builds once a tagged
64
+ > release of the `shipwright-kit` distribution is cut. Do **not** `pip install
65
+ > shipwright` from PyPI — that is a different, unrelated package.
66
+
67
+ The security pack needs no extra — it ships with the base install and registers
68
+ through the `shipwright_kit.packs` entry point.
69
+
70
+ ## Library quickstart
71
+
72
+ **Run an eval gate** — score a classifier against a labeled corpus and fail if it
73
+ misses a floor (the exact pattern barb and sift use):
74
+
75
+ ```python
76
+ from shipwright_kit.eval import Sample, evaluate, gate
77
+
78
+ corpus = [Sample("phish-login", "phishing"),
79
+ Sample("example.com", "benign"),
80
+ Sample("secure-phish", "phishing")]
81
+
82
+ result = evaluate(
83
+ lambda text: "phishing" if "phish" in text else "benign",
84
+ corpus,
85
+ positive_pred=lambda pred: pred == "phishing",
86
+ positive_expected=lambda label: label == "phishing",
87
+ )
88
+ print(result.precision, result.recall) # 1.0 1.0
89
+ gate(result, min_precision=1.0, min_recall=0.9) # raises EvalGateError if below
90
+ ```
91
+
92
+ **Use the shared severity tiers** — one generic scale tools map their own verdicts
93
+ onto, with accessible (Unicode-or-ASCII) labels:
94
+
95
+ ```python
96
+ from shipwright_kit.design import Severity, tier_label
97
+
98
+ Severity.OK, Severity.INFO, Severity.NOTICE, Severity.WARN, Severity.CRITICAL # IntEnum 0..4
99
+ print(tier_label(Severity.CRITICAL)) # ✗ CRITICAL
100
+ print(tier_label(Severity.OK)) # ✓ OK
101
+ ```
102
+
103
+ `import shipwright_kit` pulls in no `rich` or `pyfiglet` — the heavy deps load lazily only
104
+ when you actually render. Full API: **[docs/library.md](docs/library.md)**.
105
+
106
+ ## The framework
107
+
108
+ The repo contains **no project code**. Projects stay their own Git repositories and
109
+ their own packages; locally you clone each into the **gitignored** `projects/`
110
+ directory, where a [uv](https://docs.astral.sh/uv/) workspace ties them together for
111
+ development:
112
+
113
+ ```
114
+ shipwright/
115
+ ├─ shipwright_kit/ # the importable library (design / eval / security)
116
+ ├─ tooling/ruff-base.toml # single source of truth for lint rules
117
+ ├─ templates/ # Copier scaffolder (python-cli) + release config
118
+ ├─ skills/ · personas/ # the agent operating layer (scaffold, onboard, review …)
119
+ ├─ .github/workflows/ # reusable python-ci.yml + python-release.yml (SHA-pinned)
120
+ └─ projects/ # GITIGNORED, local-only — your projects plug in here
121
+ ```
122
+
123
+ Work is promoted through gates; failing a rung blocks promotion:
124
+
125
+ ```
126
+ commit → lint + unit (auto) → build → dogfood + eval (auto) →
127
+ QM gate (manual) → beta sign-off (manual) → release
128
+ ```
129
+
130
+ The reusable CI/CD that wires these gates, the Copier scaffolder (`templates/`), and
131
+ the agent skills (`skills/`) and personas (`personas/`) all ship now. This repo runs
132
+ the exact gates it gives the projects built with it.
133
+
134
+ ## Framework quickstart
135
+
136
+ Requires Python 3.11+, [uv](https://docs.astral.sh/uv/), and
137
+ [just](https://github.com/casey/just).
138
+
139
+ ```bash
140
+ uv sync --dev # create the dev environment
141
+ uv run pre-commit install # install the local gate
142
+ just lint # ruff check + format-check
143
+ just test # pytest
144
+ ```
145
+
146
+ The local `pre-commit` gate runs the same lint/format/secret checks as CI; add
147
+ `just test` (and `uv build`) for the test and build rungs CI also enforces.
148
+
149
+ ## Docs
150
+
151
+ - **[docs/library.md](docs/library.md)** — per-module API reference (design / eval / security)
152
+ - **[docs/release-policy.md](docs/release-policy.md)** — SemVer + release policy
153
+ - **[docs/ci-cd.md](docs/ci-cd.md)** — the reusable CI/CD workflows
154
+ - **[CHANGELOG.md](CHANGELOG.md)**
155
+
156
+ ## Security
157
+
158
+ Report vulnerabilities privately via GitHub's
159
+ [private vulnerability reporting](https://github.com/duathron/shipwright/security/advisories/new)
160
+ (repo **Security** tab → **Report a vulnerability**). See [SECURITY.md](SECURITY.md).
161
+
162
+ ## License
163
+
164
+ [MIT](LICENSE) © 2026 Christian Huhn
@@ -0,0 +1,135 @@
1
+ # Shipwright
2
+
3
+ ![CI](https://github.com/duathron/shipwright/actions/workflows/ci.yml/badge.svg)
4
+ ![CodeQL](https://github.com/duathron/shipwright/actions/workflows/codeql.yml/badge.svg)
5
+ ![Coverage](https://img.shields.io/badge/coverage-%E2%89%A590%25-brightgreen.svg)
6
+ ![Types](https://img.shields.io/badge/types-mypy-blue.svg)
7
+ ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
8
+ ![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)
9
+
10
+ Shipwright is two things that share one repo:
11
+
12
+ - an installable, **import-light Python library** of shared dev-tooling runtime —
13
+ `shipwright_kit.design` (severity tiers + accessible output), `shipwright_kit.eval`
14
+ (detection-quality eval harness), `shipwright_kit.security` (a security pack);
15
+ - an **AI-agent-operated development framework** — reusable CI/CD, a Copier
16
+ scaffolder, quality gates, and bundled agent skills + personas — that **dogfoods**
17
+ the library and the gates it hands to the projects built with it.
18
+
19
+ The library is consumed today by two real tools: **barb** and **sift** both import
20
+ `shipwright_kit.eval` to run their detection-quality gates.
21
+
22
+ ## Install
23
+
24
+ The library is **not on PyPI** — the bare name `shipwright` belongs to an unrelated
25
+ project, so the published distribution is **`shipwright-kit`** and the import name is
26
+ **`shipwright_kit`**. For now, install from git:
27
+
28
+ ```bash
29
+ uv pip install "git+https://github.com/duathron/shipwright@main"
30
+ # then: import shipwright_kit
31
+ ```
32
+
33
+ > [!NOTE]
34
+ > Pin a release tag instead of `@main` for reproducible builds once a tagged
35
+ > release of the `shipwright-kit` distribution is cut. Do **not** `pip install
36
+ > shipwright` from PyPI — that is a different, unrelated package.
37
+
38
+ The security pack needs no extra — it ships with the base install and registers
39
+ through the `shipwright_kit.packs` entry point.
40
+
41
+ ## Library quickstart
42
+
43
+ **Run an eval gate** — score a classifier against a labeled corpus and fail if it
44
+ misses a floor (the exact pattern barb and sift use):
45
+
46
+ ```python
47
+ from shipwright_kit.eval import Sample, evaluate, gate
48
+
49
+ corpus = [Sample("phish-login", "phishing"),
50
+ Sample("example.com", "benign"),
51
+ Sample("secure-phish", "phishing")]
52
+
53
+ result = evaluate(
54
+ lambda text: "phishing" if "phish" in text else "benign",
55
+ corpus,
56
+ positive_pred=lambda pred: pred == "phishing",
57
+ positive_expected=lambda label: label == "phishing",
58
+ )
59
+ print(result.precision, result.recall) # 1.0 1.0
60
+ gate(result, min_precision=1.0, min_recall=0.9) # raises EvalGateError if below
61
+ ```
62
+
63
+ **Use the shared severity tiers** — one generic scale tools map their own verdicts
64
+ onto, with accessible (Unicode-or-ASCII) labels:
65
+
66
+ ```python
67
+ from shipwright_kit.design import Severity, tier_label
68
+
69
+ Severity.OK, Severity.INFO, Severity.NOTICE, Severity.WARN, Severity.CRITICAL # IntEnum 0..4
70
+ print(tier_label(Severity.CRITICAL)) # ✗ CRITICAL
71
+ print(tier_label(Severity.OK)) # ✓ OK
72
+ ```
73
+
74
+ `import shipwright_kit` pulls in no `rich` or `pyfiglet` — the heavy deps load lazily only
75
+ when you actually render. Full API: **[docs/library.md](docs/library.md)**.
76
+
77
+ ## The framework
78
+
79
+ The repo contains **no project code**. Projects stay their own Git repositories and
80
+ their own packages; locally you clone each into the **gitignored** `projects/`
81
+ directory, where a [uv](https://docs.astral.sh/uv/) workspace ties them together for
82
+ development:
83
+
84
+ ```
85
+ shipwright/
86
+ ├─ shipwright_kit/ # the importable library (design / eval / security)
87
+ ├─ tooling/ruff-base.toml # single source of truth for lint rules
88
+ ├─ templates/ # Copier scaffolder (python-cli) + release config
89
+ ├─ skills/ · personas/ # the agent operating layer (scaffold, onboard, review …)
90
+ ├─ .github/workflows/ # reusable python-ci.yml + python-release.yml (SHA-pinned)
91
+ └─ projects/ # GITIGNORED, local-only — your projects plug in here
92
+ ```
93
+
94
+ Work is promoted through gates; failing a rung blocks promotion:
95
+
96
+ ```
97
+ commit → lint + unit (auto) → build → dogfood + eval (auto) →
98
+ QM gate (manual) → beta sign-off (manual) → release
99
+ ```
100
+
101
+ The reusable CI/CD that wires these gates, the Copier scaffolder (`templates/`), and
102
+ the agent skills (`skills/`) and personas (`personas/`) all ship now. This repo runs
103
+ the exact gates it gives the projects built with it.
104
+
105
+ ## Framework quickstart
106
+
107
+ Requires Python 3.11+, [uv](https://docs.astral.sh/uv/), and
108
+ [just](https://github.com/casey/just).
109
+
110
+ ```bash
111
+ uv sync --dev # create the dev environment
112
+ uv run pre-commit install # install the local gate
113
+ just lint # ruff check + format-check
114
+ just test # pytest
115
+ ```
116
+
117
+ The local `pre-commit` gate runs the same lint/format/secret checks as CI; add
118
+ `just test` (and `uv build`) for the test and build rungs CI also enforces.
119
+
120
+ ## Docs
121
+
122
+ - **[docs/library.md](docs/library.md)** — per-module API reference (design / eval / security)
123
+ - **[docs/release-policy.md](docs/release-policy.md)** — SemVer + release policy
124
+ - **[docs/ci-cd.md](docs/ci-cd.md)** — the reusable CI/CD workflows
125
+ - **[CHANGELOG.md](CHANGELOG.md)**
126
+
127
+ ## Security
128
+
129
+ Report vulnerabilities privately via GitHub's
130
+ [private vulnerability reporting](https://github.com/duathron/shipwright/security/advisories/new)
131
+ (repo **Security** tab → **Report a vulnerability**). See [SECURITY.md](SECURITY.md).
132
+
133
+ ## License
134
+
135
+ [MIT](LICENSE) © 2026 Christian Huhn
@@ -0,0 +1,81 @@
1
+ [build-system]
2
+ # setuptools>=77 is required for the SPDX string-form `license = "MIT"` (PEP 639).
3
+ requires = ["setuptools>=77.0", "wheel"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ # PyPI distribution name. The bare `shipwright` is taken on PyPI (unrelated 6si
8
+ # tool), so the dist is `shipwright-kit`; the IMPORT name is `shipwright_kit`.
9
+ name = "shipwright-kit"
10
+ version = "0.6.0"
11
+ description = "Shipwright — AI-agent dev framework + import-light design/eval/security library"
12
+ readme = "README.md"
13
+ requires-python = ">=3.11"
14
+ license = "MIT"
15
+ license-files = ["LICENSE"]
16
+ authors = [{ name = "Christian Huhn" }]
17
+ keywords = ["ci", "dev-tooling", "eval", "design-tokens", "severity", "quality-gates"]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Software Development :: Quality Assurance",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = []
29
+
30
+ [project.optional-dependencies]
31
+ rich = ["rich>=13.7"]
32
+ banner = ["pyfiglet>=1.0"]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/duathron/shipwright"
36
+ Repository = "https://github.com/duathron/shipwright"
37
+ Documentation = "https://github.com/duathron/shipwright/blob/main/docs/library.md"
38
+ Changelog = "https://github.com/duathron/shipwright/blob/main/CHANGELOG.md"
39
+ Issues = "https://github.com/duathron/shipwright/issues"
40
+
41
+ [project.entry-points."shipwright_kit.packs"]
42
+ security = "shipwright_kit.security.theme:SecurityTheme"
43
+
44
+ [dependency-groups]
45
+ dev = [
46
+ "pytest>=8.0",
47
+ "pytest-cov>=5.0",
48
+ "mypy>=1.10",
49
+ "ruff>=0.8",
50
+ "pre-commit>=4.0",
51
+ "hypothesis>=6.0",
52
+ "rich>=13.7",
53
+ "copier>=9",
54
+ "packaging",
55
+ "typer>=0.9",
56
+ ]
57
+
58
+ [tool.setuptools.packages.find]
59
+ include = ["shipwright_kit*"]
60
+
61
+ [tool.setuptools.package-data]
62
+ shipwright_kit = ["py.typed"]
63
+
64
+ [tool.uv.workspace]
65
+ members = ["projects/*"]
66
+
67
+ [tool.ruff]
68
+ extend = "tooling/ruff-base.toml"
69
+
70
+ [tool.pytest.ini_options]
71
+ testpaths = ["tests"]
72
+ addopts = "--cov=shipwright_kit --cov-report=term-missing --cov-fail-under=90"
73
+
74
+ [tool.coverage.run]
75
+ source = ["shipwright_kit"]
76
+ branch = true
77
+
78
+ [tool.mypy]
79
+ python_version = "3.11"
80
+ files = ["shipwright_kit"]
81
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Shipwright — design-token + tooling library."""
2
+
3
+ __version__ = "0.6.0"
@@ -0,0 +1,36 @@
1
+ """Typer application factory for Shipwright CLI tools.
2
+
3
+ Thin, opinionated defaults so every scaffolded CLI is consistent
4
+ (``add_completion=False``, ``no_args_is_help=True``) plus an optional
5
+ ``version`` command. Imports Typer at module load, so this submodule is NOT
6
+ imported by ``shipwright_kit/__init__`` — ``import shipwright_kit`` stays
7
+ typer-free (import-light). Consumers that import ``shipwright_kit.cli`` already
8
+ depend on Typer.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import typer
14
+
15
+ __all__ = ["build_typer"]
16
+
17
+
18
+ def build_typer(name: str, help: str, *, version: str | None = None) -> typer.Typer:
19
+ """Return a Typer app with Shipwright's standard defaults. If ``version`` is
20
+ given, register a ``version`` command that prints it."""
21
+ app = typer.Typer(
22
+ name=name,
23
+ help=help,
24
+ add_completion=False,
25
+ no_args_is_help=True,
26
+ )
27
+ if version is not None:
28
+
29
+ @app.command()
30
+ def version_() -> None: # registered as "version"
31
+ """Print the version."""
32
+ typer.echo(version)
33
+
34
+ version_.__name__ = "version"
35
+
36
+ return app
@@ -0,0 +1,53 @@
1
+ """Import-light config mechanism shared by Shipwright CLI tools.
2
+
3
+ Owns the *mechanism* only — a secure per-tool app directory, ordered-candidate
4
+ config-file resolution, and a resolve->load->validate skeleton. The consumer
5
+ injects its own yaml ``loader`` and (pydantic) ``validator`` callables, so this
6
+ module stays stdlib-only and ``import shipwright_kit.config`` pulls no
7
+ pyyaml/pydantic/typer. Each tool keeps its own config *schema*, env-override
8
+ step, ``save_config`` and ``.env`` handling.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable, Iterable
14
+ from pathlib import Path
15
+ from typing import TypeVar
16
+
17
+ __all__ = ["app_dir", "load_config", "resolve_config_file"]
18
+
19
+ T = TypeVar("T")
20
+
21
+ _OWNER_ONLY = 0o700
22
+
23
+
24
+ def app_dir(name: str, *, create: bool = False, mode: int = _OWNER_ONLY) -> Path:
25
+ """Return ``~/.{name}``. With ``create=True`` make it owner-only (mkdir + chmod,
26
+ so a pre-existing loose-permission dir is hardened too)."""
27
+ d = Path.home() / f".{name}"
28
+ if create:
29
+ d.mkdir(mode=mode, parents=True, exist_ok=True)
30
+ d.chmod(mode)
31
+ return d
32
+
33
+
34
+ def resolve_config_file(candidates: Iterable[Path | None]) -> Path | None:
35
+ """Return the first candidate that exists (``None`` entries skipped)."""
36
+ for c in candidates:
37
+ if c is not None and c.exists():
38
+ return c
39
+ return None
40
+
41
+
42
+ def load_config(
43
+ candidates: Iterable[Path | None],
44
+ *,
45
+ loader: Callable[[Path], dict],
46
+ validator: Callable[[dict], T],
47
+ ) -> T:
48
+ """Resolve the first existing candidate, ``loader`` it to a dict, and
49
+ ``validator`` that dict into a config object. If no candidate exists, the
50
+ loader is NOT called and ``validator({})`` is returned."""
51
+ path = resolve_config_file(candidates)
52
+ data = loader(path) if path is not None else {}
53
+ return validator(data)
@@ -0,0 +1,24 @@
1
+ """Design tokens: tiers, glyphs, palette, console, output."""
2
+
3
+ from .console import get_console, supports_color, supports_unicode
4
+ from .glyphs import glyph, tier_label
5
+ from .output import OUTPUT_SCHEMA_VERSION, VALID_FORMATS, Renderable, render
6
+ from .palette import ColorblindTheme, DefaultTheme, Theme
7
+ from .tiers import Severity, TierMappable
8
+
9
+ __all__ = [
10
+ "Severity",
11
+ "TierMappable",
12
+ "glyph",
13
+ "tier_label",
14
+ "Theme",
15
+ "DefaultTheme",
16
+ "ColorblindTheme",
17
+ "get_console",
18
+ "supports_color",
19
+ "supports_unicode",
20
+ "VALID_FORMATS",
21
+ "Renderable",
22
+ "render",
23
+ "OUTPUT_SCHEMA_VERSION",
24
+ ]
@@ -0,0 +1,21 @@
1
+ """Plain ASCII banner generator (dep-free). Optional figlet via the `banner`
2
+ extra is imported lazily, with a plain fallback if it is absent."""
3
+
4
+ from __future__ import annotations
5
+
6
+
7
+ def _figlet(name: str) -> str:
8
+ try:
9
+ from pyfiglet import figlet_format
10
+ except (ModuleNotFoundError, ImportError, TypeError):
11
+ return name.upper()
12
+ return figlet_format(name).rstrip("\n")
13
+
14
+
15
+ def make_banner(name: str, version: str, tagline: str = "", *, figlet: bool = False, ascii_only: bool = False) -> str:
16
+ """Return a banner string. Caller decides where to print it (typically stderr)."""
17
+ title = _figlet(name) if figlet else name.upper()
18
+ info = f"v{version}" + (f" | {tagline}" if tagline else "")
19
+ width = max([len(line) for line in title.splitlines()] + [len(info), 12])
20
+ rule = ("-" if ascii_only else "─") * width
21
+ return "\n".join([title, rule, info])
@@ -0,0 +1,33 @@
1
+ """Accessibility-aware console helpers. Rich is imported lazily inside
2
+ `get_console` so `import shipwright_kit` stays light."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import sys
8
+
9
+
10
+ def supports_color(stream=None) -> bool:
11
+ stream = stream if stream is not None else sys.stdout
12
+ if os.environ.get("NO_COLOR"):
13
+ return False
14
+ isatty = getattr(stream, "isatty", None)
15
+ return bool(isatty and isatty())
16
+
17
+
18
+ def supports_unicode(stream=None) -> bool:
19
+ stream = stream if stream is not None else sys.stdout
20
+ enc = (getattr(stream, "encoding", "") or "").lower()
21
+ if "utf" in enc:
22
+ return True
23
+ return bool(os.environ.get("WT_SESSION") or os.environ.get("ANSICON"))
24
+
25
+
26
+ def get_console(*, no_color: bool = False, force_terminal: bool | None = None):
27
+ """Return a configured Rich Console (lazy import). Requires the `rich` extra."""
28
+ try:
29
+ from rich.console import Console
30
+ except ModuleNotFoundError as exc: # pragma: no cover
31
+ raise RuntimeError("rich output requires `pip install shipwright-kit[rich]`") from exc
32
+ use_color = supports_color() and not no_color
33
+ return Console(no_color=not use_color, force_terminal=force_terminal, safe_box=not supports_unicode())
@@ -0,0 +1,30 @@
1
+ """Per-tier glyphs with an ASCII fallback. Rule: a tier indicator always
2
+ renders symbol + label, never color alone (the #1 colorblind fix)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from .tiers import Severity
7
+
8
+ _UNICODE: dict[Severity, str] = {
9
+ Severity.OK: "✓",
10
+ Severity.INFO: "ℹ",
11
+ Severity.NOTICE: "•",
12
+ Severity.WARN: "⚠",
13
+ Severity.CRITICAL: "✗",
14
+ }
15
+ _ASCII: dict[Severity, str] = {
16
+ Severity.OK: "OK",
17
+ Severity.INFO: "i",
18
+ Severity.NOTICE: "*",
19
+ Severity.WARN: "!",
20
+ Severity.CRITICAL: "XX",
21
+ }
22
+
23
+
24
+ def glyph(tier: Severity, *, ascii_only: bool = False) -> str:
25
+ return (_ASCII if ascii_only else _UNICODE)[tier]
26
+
27
+
28
+ def tier_label(tier: Severity, *, ascii_only: bool = False) -> str:
29
+ """Symbol + label — never color/symbol alone."""
30
+ return f"{glyph(tier, ascii_only=ascii_only)} {tier.label}"
@@ -0,0 +1,60 @@
1
+ """Output-format contract. Core formats are stdlib-only; `rich` is lazy.
2
+ `console` is a distinct reduced-density plain formatter (not Rich-no-color)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import csv as _csv
7
+ import io
8
+ import json
9
+ from typing import Protocol, runtime_checkable
10
+
11
+ from .glyphs import tier_label
12
+ from .tiers import Severity
13
+
14
+ VALID_FORMATS = ("rich", "console", "json", "ndjson", "csv")
15
+
16
+ # render(fmt="json") envelope contract version (G10). Bump = structural break;
17
+ # update the golden test + a migration note (docs/release-policy.md).
18
+ OUTPUT_SCHEMA_VERSION = 1
19
+
20
+
21
+ @runtime_checkable
22
+ class Renderable(Protocol):
23
+ def rows(self) -> list[dict]: ...
24
+
25
+ def tier(self) -> Severity: ...
26
+
27
+
28
+ def render(obj: Renderable, fmt: str = "console", *, ascii_only: bool = False) -> str:
29
+ if fmt not in VALID_FORMATS:
30
+ raise ValueError(f"unknown format {fmt!r}; valid: {', '.join(VALID_FORMATS)}")
31
+ rows = list(obj.rows())
32
+ if fmt == "json":
33
+ return json.dumps({"schema_version": OUTPUT_SCHEMA_VERSION, "tier": obj.tier().label, "rows": rows}, indent=2)
34
+ if fmt == "ndjson":
35
+ return "\n".join(json.dumps(r) for r in rows)
36
+ if fmt == "csv":
37
+ if not rows:
38
+ return ""
39
+ buf = io.StringIO()
40
+ writer = _csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
41
+ writer.writeheader()
42
+ writer.writerows(rows)
43
+ return buf.getvalue()
44
+ if fmt == "console":
45
+ head = tier_label(obj.tier(), ascii_only=ascii_only)
46
+ body = [" " + " ".join(f"{k}={v}" for k, v in r.items()) for r in rows]
47
+ return "\n".join([head, *body])
48
+ # fmt == "rich" — lazy import
49
+ from rich.console import Console
50
+ from rich.table import Table
51
+
52
+ table = Table()
53
+ if rows:
54
+ for key in rows[0]:
55
+ table.add_column(str(key))
56
+ for r in rows:
57
+ table.add_row(*[str(v) for v in r.values()])
58
+ buf = io.StringIO()
59
+ Console(file=buf, force_terminal=False, no_color=True).print(table)
60
+ return buf.getvalue()