standards-sync 0.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ Metadata-Version: 2.5
2
+ Name: standards-sync
3
+ Version: 0.0.8
4
+ Summary: Keep the canonical code standards in sync with the workspace root and dotfiles copies.
5
+ Project-URL: Homepage, https://github.com/sebastienrousseau/standards
6
+ Project-URL: Documentation, https://sebastienrousseau.com/standards/
7
+ Project-URL: Changelog, https://github.com/sebastienrousseau/standards/blob/main/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/sebastienrousseau/standards/issues
9
+ Author-email: Sebastien Rousseau <sebastian.rousseau@gmail.com>
10
+ License-Expression: Apache-2.0 OR MIT
11
+ License-File: LICENSE-APACHE
12
+ License-File: LICENSE-MIT
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Software Development :: Quality Assurance
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+
23
+ <!-- SPDX-FileCopyrightText: 2026 Sebastien Rousseau -->
24
+ <!-- SPDX-License-Identifier: Apache-2.0 OR MIT -->
25
+
26
+ <p align="center">
27
+ <img src="https://raw.githubusercontent.com/sebastienrousseau/standards/main/.github/logo.svg" alt="standards logo" width="128" />
28
+ </p>
29
+
30
+ <h1 align="center">standards</h1>
31
+
32
+ <p align="center">
33
+ The rules every repository by Sebastien Rousseau follows, and the command that keeps every copy of them identical.
34
+ </p>
35
+
36
+ <p align="center">
37
+ <a href="https://github.com/sebastienrousseau/standards/actions"><img src="https://img.shields.io/github/actions/workflow/status/sebastienrousseau/standards/ci.yml?style=for-the-badge&logo=github" alt="Build" height="28" /></a>
38
+ <a href="https://github.com/sebastienrousseau/standards/releases"><img src="https://img.shields.io/github/v/release/sebastienrousseau/standards?style=for-the-badge&color=fc8d62&logo=github" alt="Release" height="28" /></a>
39
+ <a href="https://sebastienrousseau.com/standards/"><img src="https://img.shields.io/badge/docs-manual-blue?style=for-the-badge&labelColor=555555&logo=materialformkdocs" alt="Docs" height="28" /></a>
40
+ <a href="https://scorecard.dev/viewer/?uri=github.com/sebastienrousseau/standards"><img src="https://img.shields.io/ossf-scorecard/github.com/sebastienrousseau/standards?style=for-the-badge&label=OpenSSF%20Scorecard&logo=openssf" alt="OpenSSF Scorecard" height="28" /></a>
41
+ <a href="#license"><img src="https://img.shields.io/badge/license-Apache--2.0%20OR%20MIT-blue.svg?style=for-the-badge" alt="License: Apache-2.0 OR MIT" height="28" /></a>
42
+ <a href="https://github.com/sebastienrousseau/standards/blob/main/docs/POLICIES.md"><img src="https://img.shields.io/badge/Python-3.9%2B-93450a.svg?style=for-the-badge&logo=python" alt="Python 3.9 or later" height="28" /></a>
43
+ </p>
44
+
45
+ <p align="center">
46
+ <img src="https://raw.githubusercontent.com/sebastienrousseau/standards/main/.github/demo.gif" alt="standards-sync pushing the five standards to a target, keeping a file edited there instead of overwriting it, and showing the drift with --check" width="100%" />
47
+ </p>
48
+
49
+ ---
50
+
51
+ ## Contents
52
+
53
+ **Getting started**
54
+
55
+ - [Install](#install): `uv tool install`, `make install`, or the dotfiles
56
+ - [Requirements](#requirements): toolchain floor, platforms
57
+ - [Quick Start](#quick-start): push the standards to a scratch directory and check them
58
+
59
+ **The standards ecosystem**
60
+
61
+ - [The standards ecosystem](#the-standards-ecosystem): the five standards, standards-sync, the dotfiles, the compliance audit
62
+
63
+ **Library reference**
64
+
65
+ - [Capabilities at a glance](#capabilities-at-a-glance): the current surface by theme
66
+ - [Ecosystem comparison](#ecosystem-comparison): why there is none
67
+ - [Benchmarks](#benchmarks): why there are none
68
+ - [Features](#features): what each part does
69
+ - [Configuration](#configuration): environment variables
70
+ - [Examples](#examples): common tasks
71
+
72
+ **Operational**
73
+
74
+ - [When not to use standards](#when-not-to-use-standards): limitations
75
+ - [Development](#development): make targets, fuzzing, CI
76
+ - [Security](#security): guarantees and compliance
77
+ - [Documentation](#documentation): all reference docs
78
+ - [Stability guarantees](#stability-guarantees): SemVer axis, output stability, minimum toolchain discipline
79
+ - [License](#license)
80
+
81
+ ---
82
+
83
+ ## Install
84
+
85
+ ### As a Python library
86
+
87
+ ```bash
88
+ uv tool install git+https://github.com/sebastienrousseau/standards
89
+ ```
90
+
91
+ This installs the `standards-sync` command; its functions are importable
92
+ as `standards_sync`.
93
+
94
+ From a clone, with the manpage and bash, zsh and fish completions:
95
+
96
+ ```bash
97
+ make PREFIX="$HOME/.local" install
98
+ ```
99
+
100
+ The [dotfiles](https://github.com/sebastienrousseau/dotfiles) also install
101
+ it as `~/.local/bin/standards-sync`, and link `~/Code`'s standards to a
102
+ clone of this repository.
103
+
104
+ ---
105
+
106
+ ## Requirements
107
+
108
+ | Requirement | Version | Why |
109
+ | :--- | :--- | :--- |
110
+ | Python | 3.9 or later | the minimum toolchain is the macOS system `python3`; see the policy in [docs/POLICIES.md](docs/POLICIES.md) |
111
+ | git | any | to tell a published version of a file from an edit |
112
+ | OS | macOS, Linux | tested on both in CI |
113
+
114
+ ---
115
+
116
+ ## Quick Start
117
+
118
+ ```bash
119
+ make PREFIX="$HOME/.local" install
120
+ export PATH="$HOME/.local/bin:$PATH"
121
+ export STANDARDS_REPO="$PWD" STANDARDS_TARGETS="$PWD/build/quickstart"
122
+ standards-sync --push # copy the five standards to the scratch directory
123
+ standards-sync --check # every file [OK]
124
+ ```
125
+
126
+ Run from a clone, this installs the command and tries it on a scratch
127
+ directory, leaving `~/Code` and the dotfiles alone. Unset
128
+ `STANDARDS_TARGETS` to work on the real targets. CI runs this block as
129
+ written.
130
+
131
+ ---
132
+
133
+ ## The standards ecosystem
134
+
135
+ The standards are edited here, carried to every machine by the dotfiles,
136
+ and measured across the portfolio by the compliance audit.
137
+
138
+ | Component | Purpose | Use case |
139
+ | :--- | :--- | :--- |
140
+ | [`AGENTS.md`](AGENTS.md) | Invariants for AI-assisted and human work | Read before changing any repository |
141
+ | [`GEMINI.md`](GEMINI.md) | Pointer file for Gemini and other agents | Loaded at the start of an agent session |
142
+ | [`REPO-STANDARD.md`](REPO-STANDARD.md) | The eight-category scorecard and its phases | Rating and raising a repository |
143
+ | [`README-TEMPLATE.md`](README-TEMPLATE.md) | The layout of every primary README | Writing or checking a README |
144
+ | [`PR-TEMPLATE.md`](PR-TEMPLATE.md) | The shape of every pull request description | Opening a pull request |
145
+ | `standards-sync` | Keeps every copy identical without losing an edit | `~/Code` and dotfiles upkeep |
146
+ | [dotfiles](https://github.com/sebastienrousseau/dotfiles) | Installs the command, links `~/Code` here | A new machine |
147
+
148
+ ---
149
+
150
+ ## Capabilities at a glance
151
+
152
+ | Area | Capability | Status |
153
+ | :--- | :--- | :--- |
154
+ | Standards | Five canonical files, released together | Stable |
155
+ | Sync | Drift check with diffs | Stable |
156
+ | Sync | Push that keeps edits made in place | Stable |
157
+ | Sync | Pull that adopts a `~/Code` edit | Stable |
158
+ | Sync | Git hooks that push on commit and merge | Stable |
159
+ | Tooling | Manpage and completions from the parser | Stable |
160
+
161
+ ---
162
+
163
+ ## Ecosystem comparison
164
+
165
+ This section does not apply: the repository is one portfolio's
166
+ governance, not a product with alternatives, and no comparison is claimed.
167
+
168
+ ---
169
+
170
+ ## Benchmarks
171
+
172
+ This section does not apply: `standards-sync` hashes and copies five
173
+ small text files, and no performance claim is made.
174
+
175
+ ---
176
+
177
+ ## Features
178
+
179
+ - **One source.** A rule changes here, in a pull request, and nowhere else.
180
+ - **Safe push.** A target file is overwritten only if it is missing,
181
+ identical, or a version this repository committed. An edit made in
182
+ place is kept and named, and the push exits 1.
183
+ - **Links respected.** A target that links to the source is left alone.
184
+ - **Pull.** An edit made in `~/Code` is adopted, then pushed to the
185
+ dotfiles copies.
186
+ - **Checks that bind this repository too.** CI holds the README to
187
+ `README-TEMPLATE.md`, the GitHub PR template to `PR-TEMPLATE.md`, and
188
+ every function to the complexity ceilings of `AGENTS.md`.
189
+
190
+ ---
191
+
192
+ ## Configuration
193
+
194
+ | Variable | Effect |
195
+ | :--- | :--- |
196
+ | `STANDARDS_REPO` | The source directory, tried before any other |
197
+ | `STANDARDS_TARGETS` | Target directories, separated by `:`, replacing the defaults |
198
+
199
+ Without them, the source is found from the script's location or under
200
+ `~/Code`, and the targets are `~/Code` and the dotfiles copies that exist.
201
+ [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) lists the exact order.
202
+
203
+ ---
204
+
205
+ ## Examples
206
+
207
+ ```bash
208
+ standards-sync --check # what differs, with diffs; changes nothing
209
+ standards-sync --check -q # one warning line, or silence
210
+ standards-sync --push # bring every copy up to date
211
+ standards-sync --push --force # also overwrite files edited in place
212
+ standards-sync --pull # adopt an edit made in ~/Code
213
+ standards-sync --install-hooks # push after every commit and merge here
214
+ ```
215
+
216
+ ---
217
+
218
+ ## When not to use standards
219
+
220
+ - The default targets are one workspace's layout (`~/Code`, chezmoi
221
+ dotfiles). Elsewhere, set `STANDARDS_TARGETS`.
222
+ - It syncs exactly five files. It is not a general file synchroniser.
223
+ - The rules are opinionated (`0.0.x` versioning, one release pull
224
+ request, signed-off commits). Adopt them knowingly.
225
+ - Windows is not tested.
226
+
227
+ ---
228
+
229
+ ## Development
230
+
231
+ ```bash
232
+ uv sync --frozen
233
+ make check # every gate CI runs
234
+ make help # every task
235
+ ```
236
+
237
+ `make check` runs ruff, the complexity ceilings, codespell, REUSE,
238
+ markdownlint, actionlint, the tests at 95 percent branch coverage, the
239
+ property-based fuzz corpus, the strict manual build, the API breakage
240
+ check, pip-audit and a reproducible-build comparison. See
241
+ [DEVELOPMENT.md](DEVELOPMENT.md).
242
+
243
+ ---
244
+
245
+ ## Security
246
+
247
+ `standards-sync` writes only the five standard files, into the targets it
248
+ lists, and git hooks into this checkout. Commits and tags are signed
249
+ (`KEYS.asc`), every Action is pinned by SHA, dependencies are locked and
250
+ audited on every push, and releases carry checksums, an SBOM and build
251
+ provenance. CodeQL, secret scanning and the OpenSSF Scorecard run on
252
+ `main`.
253
+
254
+ The project holds the
255
+ [OpenSSF Best Practices passing badge](https://www.bestpractices.dev/projects/17104).
256
+
257
+ Report vulnerabilities according to [`SECURITY.md`](SECURITY.md).
258
+
259
+ ---
260
+
261
+ ## Documentation
262
+
263
+ - [User manual](https://sebastienrousseau.com/standards/): the standards and `standards-sync`
264
+ - `man standards-sync`, after `make install`
265
+ - [DEVELOPMENT.md](DEVELOPMENT.md): tools, the gate, tests, releases
266
+ - [ROADMAP.md](ROADMAP.md) and [GOVERNANCE.md](GOVERNANCE.md): plans, roles and decisions
267
+ - [docs/ASSURANCE.md](docs/ASSURANCE.md): the security assurance case
268
+ - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) and the [decision records](docs/adr/index.md)
269
+ - [CHANGELOG.md](CHANGELOG.md)
270
+
271
+ ---
272
+
273
+ ## Stability guarantees
274
+
275
+ Versions rise by `0.0.1` per release ([`AGENTS.md`](AGENTS.md) section 3).
276
+ For `standards-sync`, the options, exit status, status words and
277
+ environment variables are the contract, and a push never overwrites an
278
+ edit made in place without `--force`: changing any of these is breaking,
279
+ even with no option renamed. The public Python API is checked against the
280
+ last release in CI. The minimum toolchain is Python 3.9 and rises only
281
+ with the macOS system Python. Details in
282
+ [docs/POLICIES.md](docs/POLICIES.md).
283
+
284
+ ---
285
+
286
+ ## License
287
+
288
+ Dual-licensed under either:
289
+
290
+ - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
291
+ - MIT License ([LICENSE-MIT](LICENSE-MIT) or <https://opensource.org/licenses/MIT>)
292
+
293
+ at your option.
294
+
295
+ Copyright &copy; 2026 <a href="https://sebastienrousseau.com/" rel="author">Sebastien Rousseau</a>.
@@ -0,0 +1,7 @@
1
+ standards_sync.py,sha256=fHoy2iPzaZR5zZrG7f0IvWmmhIGgRsZET7tnMilPAGg,15528
2
+ standards_sync-0.0.8.dist-info/METADATA,sha256=E8XTtZH7T8htEx0TdxPyzY2KhAYRJ4c6bFvSRobMzh4,11650
3
+ standards_sync-0.0.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ standards_sync-0.0.8.dist-info/entry_points.txt,sha256=d_ojfLtRXuOQSPUucx8iqobOCJzGBsJlRXfYB2vmYzs,55
5
+ standards_sync-0.0.8.dist-info/licenses/LICENSE-APACHE,sha256=lr2GZssZHYbkEI1nQSA5EUjQUK-q7Tc9vMop1BrzEOQ,10287
6
+ standards_sync-0.0.8.dist-info/licenses/LICENSE-MIT,sha256=C7vUXDiQo9vcRhTx2sBd4pBTFlA5rt9x_8etuF4q2BA,1075
7
+ standards_sync-0.0.8.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ standards-sync = standards_sync:main
@@ -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 the 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.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding 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 Sebastien Rousseau
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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sebastien Rousseau
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.
standards_sync.py ADDED
@@ -0,0 +1,430 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-FileCopyrightText: 2026 Sebastien Rousseau
3
+ # SPDX-License-Identifier: Apache-2.0 OR MIT
4
+ """Standards synchronization and integrity verification utility.
5
+
6
+ Maintains strict synchronization between the canonical standards repository,
7
+ the active workspace root (~/Code), and dotfiles (chezmoi distribution).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import difflib
14
+ import filecmp
15
+ import hashlib
16
+ import os
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ from collections.abc import Iterator
21
+ from pathlib import Path
22
+
23
+ STANDARD_FILES = (
24
+ "AGENTS.md",
25
+ "GEMINI.md",
26
+ "PR-TEMPLATE.md",
27
+ "README-TEMPLATE.md",
28
+ "REPO-STANDARD.md",
29
+ )
30
+
31
+
32
+ def _holds_standards(directory: Path, readable: bool = True) -> bool:
33
+ """Whether `directory` holds AGENTS.md (and, if `readable`, can read it)."""
34
+ agents = directory / "AGENTS.md"
35
+ try:
36
+ if not (directory.is_dir() and agents.is_file()):
37
+ return False
38
+ if readable:
39
+ with agents.open("rb") as f:
40
+ f.read(1)
41
+ except OSError:
42
+ return False
43
+ return True
44
+
45
+
46
+ def _source_candidates() -> Iterator[tuple[Path, bool]]:
47
+ """Directories that may hold the standards, in order, with whether to test a read."""
48
+ if "STANDARDS_REPO" in os.environ:
49
+ yield Path(os.environ["STANDARDS_REPO"]), False
50
+ # First check if invoked from within a dotfiles or standards git checkout
51
+ for parent in Path(__file__).resolve().parents:
52
+ yield parent / "defaults" / "Code", True
53
+ yield parent, True
54
+ home = Path.home()
55
+ for candidate in (
56
+ home / "Code" / "Public" / "Other" / "standards",
57
+ home / "Code",
58
+ home / ".dotfiles" / "defaults" / "Code",
59
+ home / ".local" / "share" / "chezmoi" / "defaults" / "Code",
60
+ ):
61
+ yield candidate, True
62
+
63
+
64
+ def find_canonical_source() -> Path | None:
65
+ """Locate the canonical source directory containing the standard files."""
66
+ return next((c for c, readable in _source_candidates() if _holds_standards(c, readable)), None)
67
+
68
+
69
+ def _env_targets(value: str) -> list[tuple[str, Path]]:
70
+ """Targets named in STANDARDS_TARGETS, separated by os.pathsep."""
71
+ targets: list[tuple[str, Path]] = []
72
+ for item in value.split(os.pathsep):
73
+ p = Path(item.strip())
74
+ # Blank after Path normalises it ("./ /" is Path(" ")): ignore it too.
75
+ if item.strip() and str(p).strip():
76
+ targets.append((p.name or "Custom Target", p))
77
+ return targets
78
+
79
+
80
+ def _resolved(path: Path) -> Path:
81
+ """`path` resolved, or as given when it cannot be (a symlink loop)."""
82
+ try:
83
+ return path.resolve()
84
+ except (OSError, RuntimeError):
85
+ return path
86
+
87
+
88
+ def _is_target(path: Path) -> bool:
89
+ """Whether `path` exists, or is a ~/Code that a push may create."""
90
+ try:
91
+ return path.exists() or (path.parent.exists() and path.name == "Code")
92
+ except OSError:
93
+ return False
94
+
95
+
96
+ def get_target_dirs(src_dir: Path) -> list[tuple[str, Path]]:
97
+ """Return configured sync target directories with descriptive labels."""
98
+ if "STANDARDS_TARGETS" in os.environ:
99
+ return _env_targets(os.environ["STANDARDS_TARGETS"])
100
+
101
+ home = Path.home()
102
+ code_dir = home / "Code"
103
+ all_targets: list[tuple[str, Path]] = [
104
+ ("Workspace Root", code_dir),
105
+ ("Chezmoi Dotfiles", home / ".dotfiles" / "defaults" / "Code"),
106
+ ("Dotfiles Workspace", code_dir / "Public" / "Shell" / "dotfiles" / "defaults" / "Code"),
107
+ ("Chezmoi Local Share", home / ".local" / "share" / "chezmoi" / "defaults" / "Code"),
108
+ ]
109
+
110
+ targets: list[tuple[str, Path]] = []
111
+ seen: set[Path] = {_resolved(src_dir)}
112
+ for label, p in all_targets:
113
+ p_resolved = _resolved(p)
114
+ if p_resolved in seen or not _is_target(p):
115
+ continue
116
+ seen.add(p_resolved)
117
+ targets.append((label, p))
118
+ return targets
119
+
120
+
121
+ def compute_hash(path: Path) -> str:
122
+ """Compute SHA-256 digest of a file."""
123
+ try:
124
+ if not path.is_file():
125
+ return ""
126
+ h = hashlib.sha256()
127
+ with path.open("rb") as f:
128
+ while chunk := f.read(65536):
129
+ h.update(chunk)
130
+ return h.hexdigest()
131
+ except (OSError, PermissionError):
132
+ return ""
133
+
134
+
135
+ def _say(quiet: bool, *lines: str) -> None:
136
+ """Print `lines` unless `quiet`."""
137
+ if not quiet:
138
+ print(*lines, sep="\n")
139
+
140
+
141
+ _STATE_LINE = {"missing": " [MISSING] {}", "drifted": " [DRIFTED] {}", "ok": " [OK] {}"}
142
+
143
+
144
+ def _file_state(src: Path, dst: Path) -> str:
145
+ """Compare `dst` with `src`: "skip", "missing", "drifted" or "ok"."""
146
+ try:
147
+ src_hash = compute_hash(src) if src.is_file() else ""
148
+ if src_hash and not dst.exists():
149
+ return "missing"
150
+ except OSError:
151
+ return "skip"
152
+ dst_hash = compute_hash(dst) if src_hash else ""
153
+ if not dst_hash:
154
+ return "skip"
155
+ return "ok" if src_hash == dst_hash else "drifted"
156
+
157
+
158
+ def _print_diff(src: Path, dst: Path, fname: str, label: str) -> None:
159
+ """Print the first lines of a unified diff from `src` to `dst`."""
160
+ try:
161
+ src_lines = src.read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
162
+ dst_lines = dst.read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
163
+ except OSError:
164
+ return
165
+ diff = difflib.unified_diff(
166
+ src_lines,
167
+ dst_lines,
168
+ fromfile=f"standards/{fname}",
169
+ tofile=f"{label}/{fname}",
170
+ n=2,
171
+ )
172
+ print("".join(list(diff)[:15]))
173
+
174
+
175
+ def check_target_file(src: Path, dst: Path, fname: str, label: str, quiet: bool) -> bool:
176
+ """Check a single target file against source. Return True if drifted."""
177
+ state = _file_state(src, dst)
178
+ if state == "skip":
179
+ return False
180
+ _say(quiet, _STATE_LINE[state].format(fname))
181
+ if state == "drifted" and not quiet:
182
+ _print_diff(src, dst, fname, label)
183
+ return state != "ok"
184
+
185
+
186
+ def _check_target(src_dir: Path, label: str, target_dir: Path, quiet: bool) -> int:
187
+ """Check every standard file in one target; return its drift count."""
188
+ _say(quiet, f"Target: {label} ({target_dir})")
189
+ try:
190
+ if not target_dir.exists():
191
+ _say(quiet, f" [MISSING] Target directory does not exist: {target_dir}\n")
192
+ return 1
193
+ except OSError:
194
+ return 0
195
+ drift = sum(check_target_file(src_dir / f, target_dir / f, f, label, quiet) for f in STANDARD_FILES)
196
+ _say(quiet, "")
197
+ return drift
198
+
199
+
200
+ def _report_drift(drift_count: int, quiet: bool) -> int:
201
+ """Print the outcome of a check and return its exit status."""
202
+ if drift_count == 0:
203
+ _say(quiet, "All standards are synchronized.")
204
+ return 0
205
+ if quiet:
206
+ print(f"\033[0;33m⚠️ [standards] Drift detected across ~/Code or dotfiles ({drift_count} discrepancy).\033[0m")
207
+ print(" Run 'standards-sync' to auto-heal or 'standards-sync --check' to inspect diffs.")
208
+ else:
209
+ print(f"Synchronization check failed with {drift_count} drift(s).")
210
+ return 1
211
+
212
+
213
+ def check_sync(src_dir: Path | None, targets: list[tuple[str, Path]], quiet: bool = False) -> int:
214
+ """Verify all targets match source files byte-for-byte. Return 0 if in sync, 1 if drifted."""
215
+ if src_dir is None:
216
+ _say(quiet, "No standards source directory located.")
217
+ return 0
218
+ _say(
219
+ quiet,
220
+ f"Checking synchronization for {len(STANDARD_FILES)} standard files across {len(targets)} targets...\n",
221
+ )
222
+ drift_count = sum(_check_target(src_dir, label, target_dir, quiet) for label, target_dir in targets)
223
+ return _report_drift(drift_count, quiet)
224
+
225
+
226
+ def published_blobs(src_dir: Path, fname: str) -> set[str]:
227
+ """Every version of `fname` this repository has committed, as git blob ids."""
228
+ git = shutil.which("git")
229
+ if git is None:
230
+ return set()
231
+ # The argv is fixed apart from paths this script chose; no shell is involved.
232
+ log = subprocess.run( # noqa: S603
233
+ [git, "-C", str(src_dir), "log", "--raw", "--no-abbrev", "--format=", "--", fname],
234
+ capture_output=True,
235
+ text=True,
236
+ check=False,
237
+ ).stdout
238
+ return {line.split()[3] for line in log.splitlines() if line.startswith(":")}
239
+
240
+
241
+ def blob_of(path: Path) -> str:
242
+ """The git blob id of a file's current content, as `git hash-object` gives it."""
243
+ data = path.read_bytes()
244
+ return hashlib.sha1(b"blob %d\0" % len(data) + data, usedforsecurity=False).hexdigest()
245
+
246
+
247
+ def safe_to_overwrite(src_dir: Path, src: Path, dst: Path) -> bool:
248
+ """Whether pushing `src` over `dst` loses nothing.
249
+
250
+ It does not when `dst` is missing, already matches, or holds a version
251
+ this repository once published. Any other content was edited in place
252
+ (in ~/Code or a dotfiles copy) and is newer than the canonical source as
253
+ far as anyone can tell: a push that overwrote it once replaced the
254
+ workspace's AGENTS.md with an October copy. Such a file is kept.
255
+ """
256
+ if not dst.exists() or filecmp.cmp(src, dst, shallow=False):
257
+ return True
258
+ return blob_of(dst) in published_blobs(src_dir, src.name)
259
+
260
+
261
+ def is_same_file(a: Path, b: Path) -> bool:
262
+ """Whether `a` and `b` are one file, as when a target links to the source.
263
+
264
+ Copying a file onto itself fails (shutil.SameFileError), and there is
265
+ nothing to copy: a linked target is always in sync.
266
+ """
267
+ try:
268
+ return a.exists() and b.exists() and os.path.samefile(a, b)
269
+ except OSError:
270
+ return False
271
+
272
+
273
+ def push_file(src_dir: Path, fname: str, dst: Path, force: bool) -> bool:
274
+ """Push one standard file to `dst`; return True when an edit was kept."""
275
+ src = src_dir / fname
276
+ try:
277
+ if not src.is_file():
278
+ return False
279
+ if is_same_file(src, dst):
280
+ print(f" [LINKED] {fname}")
281
+ return False
282
+ if not force and not safe_to_overwrite(src_dir, src, dst):
283
+ print(
284
+ f" [KEPT] {fname}: edited here, not a published version; "
285
+ "--pull to adopt it, --push --force to overwrite"
286
+ )
287
+ return True
288
+ shutil.copy2(src, dst)
289
+ print(f" [COPIED] {fname}")
290
+ except (OSError, PermissionError) as e:
291
+ print(f" [ERROR] {fname}: {e}")
292
+ return False
293
+
294
+
295
+ def push_sync(src_dir: Path | None, targets: list[tuple[str, Path]], force: bool = False) -> int:
296
+ """Propagate canonical repo files to all target destinations.
297
+
298
+ A target file edited in place is kept and reported, unless `force`:
299
+ adopt it with --pull, or overwrite it with --push --force. A target
300
+ that links to the source is reported as linked and left alone.
301
+ """
302
+ if src_dir is None:
303
+ print("Cannot push: no standards source directory located.")
304
+ return 1
305
+ kept = 0
306
+
307
+ print(f"Synchronizing {len(STANDARD_FILES)} standard files to {len(targets)} targets...\n")
308
+ for label, target_dir in targets:
309
+ try:
310
+ target_dir.mkdir(parents=True, exist_ok=True)
311
+ except (OSError, PermissionError) as e:
312
+ print(f"Cannot update {label} ({target_dir}): {e}")
313
+ continue
314
+
315
+ print(f"Updating: {label} ({target_dir})")
316
+ for fname in STANDARD_FILES:
317
+ kept += push_file(src_dir, fname, target_dir / fname, force)
318
+ print()
319
+ if kept:
320
+ print(f"Push synchronization kept {kept} file(s) edited in place; nothing of them was overwritten.")
321
+ return 1
322
+ print("Push synchronization complete.")
323
+ return 0
324
+
325
+
326
+ def pull_sync(src_dir: Path | None) -> int:
327
+ """Pull edited files from workspace root (~/Code) into canonical repo."""
328
+ if src_dir is None:
329
+ print("Cannot pull: no standards destination directory located.")
330
+ return 1
331
+
332
+ code_dir = Path.home() / "Code"
333
+ if not code_dir.exists():
334
+ print(f"Workspace root not found: {code_dir}")
335
+ return 1
336
+
337
+ print(f"Pulling standards from workspace root ({code_dir}) into repo...\n")
338
+ for fname in STANDARD_FILES:
339
+ src = code_dir / fname
340
+ dst = src_dir / fname
341
+ try:
342
+ if not src.is_file():
343
+ continue
344
+ if is_same_file(src, dst):
345
+ print(f" [LINKED] {fname}")
346
+ continue
347
+ shutil.copy2(src, dst)
348
+ print(f" [PULLED] {fname}")
349
+ except (OSError, PermissionError) as e:
350
+ print(f" [ERROR] {fname}: {e}")
351
+ print("\nPull complete. Running push to update dotfiles mirrors...")
352
+ targets = [t for t in get_target_dirs(src_dir) if t[0] != "Workspace Root"]
353
+ return push_sync(src_dir, targets)
354
+
355
+
356
+ def install_hooks(src_dir: Path | None) -> int:
357
+ """Install git post-commit and post-merge hooks to auto-sync on commit/pull."""
358
+ if src_dir is None:
359
+ print("Cannot install hooks: no standards directory located.")
360
+ return 1
361
+
362
+ hooks_dir = src_dir / ".git" / "hooks"
363
+ if not hooks_dir.exists():
364
+ print(f"Git hooks directory not found at {hooks_dir}")
365
+ return 1
366
+
367
+ hook_content = "#!/bin/sh\n# Auto-sync standards to workspace root and dotfiles\nstandards-sync --push\n"
368
+
369
+ for hook_name in ("post-commit", "post-merge"):
370
+ hook_path = hooks_dir / hook_name
371
+ try:
372
+ hook_path.write_text(hook_content, encoding="utf-8")
373
+ hook_path.chmod(0o755)
374
+ print(f"Installed hook: {hook_path}")
375
+ except (OSError, PermissionError) as e:
376
+ print(f"Cannot install hook {hook_name}: {e}")
377
+ return 1
378
+
379
+ return 0
380
+
381
+
382
+ EPILOG = """\
383
+ environment:
384
+ STANDARDS_REPO the canonical source directory, tried first
385
+ STANDARDS_TARGETS target directories separated by the path separator (:),
386
+ replacing the default ~/Code and dotfiles targets
387
+
388
+ exit status:
389
+ 0 in sync (or, for --check, no source found), or every file pushed or pulled
390
+ 1 drift found, a file edited in place was kept, or a push, pull or hook
391
+ install could not run
392
+ """
393
+
394
+
395
+ def build_parser() -> argparse.ArgumentParser:
396
+ """The command-line interface; also the source of the manpage and completions."""
397
+ parser = argparse.ArgumentParser(
398
+ prog="standards-sync",
399
+ description=__doc__,
400
+ epilog=EPILOG,
401
+ formatter_class=argparse.RawDescriptionHelpFormatter,
402
+ )
403
+ parser.add_argument("--check", action="store_true", help="Check for drift without modifying files")
404
+ parser.add_argument("-q", "--quiet", action="store_true", help="Quiet mode: suppress output unless drift detected")
405
+ parser.add_argument("--push", action="store_true", help="Push canonical repo standards to all targets")
406
+ parser.add_argument("--force", action="store_true", help="With --push, also overwrite files edited in place")
407
+ parser.add_argument("--pull", action="store_true", help="Pull standards from workspace root into repo")
408
+ parser.add_argument("--install-hooks", action="store_true", help="Install git post-commit and post-merge hooks")
409
+ return parser
410
+
411
+
412
+ def main() -> int:
413
+ """Run the command named on the command line; push when none is."""
414
+ args = build_parser().parse_args()
415
+
416
+ src_dir = find_canonical_source()
417
+ targets = get_target_dirs(src_dir) if src_dir else []
418
+
419
+ if args.install_hooks:
420
+ return install_hooks(src_dir)
421
+ if args.pull:
422
+ return pull_sync(src_dir)
423
+ if args.check:
424
+ return check_sync(src_dir, targets, quiet=args.quiet)
425
+
426
+ return push_sync(src_dir, targets, force=args.force)
427
+
428
+
429
+ if __name__ == "__main__":
430
+ sys.exit(main())