@invariantly/cli 0.0.0-stage → 0.0.3
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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +93 -2
- package/dist/base.d.ts +35 -0
- package/dist/base.js +300 -0
- package/dist/check.d.ts +125 -0
- package/dist/check.js +1247 -0
- package/dist/git.d.ts +36 -0
- package/dist/git.js +765 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +154 -0
- package/dist/validate.d.ts +15 -0
- package/dist/validate.js +68 -0
- package/package.json +59 -4
- package/schema/invariants.v0.schema.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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.
|
|
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
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# invariantly
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Keep your app's promises.** invariantly turns the promises an application makes ("an order is never shipped before it is paid", "a refund never exceeds what was paid", "the audit log cannot be changed") into a registry of invariants, ties each one to the tests that check it, and makes sure that a change to a promise always reaches a human.
|
|
4
|
+
|
|
5
|
+
It is built for code written with AI coding agents: the agents may change *how* the app keeps its promises, but not *which* promises it makes without someone noticing.
|
|
6
|
+
|
|
7
|
+
> **Status: early (0.0.x).** Today invariantly validates the registry format and checks that every rule has a vitest or pytest test. Repository analysis with agents, test generation, the CI checker and the local panel are being built; see [Roadmap](#roadmap).
|
|
8
|
+
|
|
9
|
+
The idea comes from contracts in [Truss](https://github.com/finiteloop/truss): people read short, precise promises and machines check that the code keeps them. invariantly brings that way of working to existing Python and TypeScript projects, using ordinary tests.
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
Requires Node.js 22 or newer.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npx @invariantly/cli validate # checks ./invariants.yaml
|
|
17
|
+
npx @invariantly/cli validate path/to/invariants.yaml --json
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Exit codes: `0` valid, `1` invalid registry, `2` usage or file error.
|
|
21
|
+
|
|
22
|
+
### Check that every rule has a test
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npx @invariantly/cli check # validates ./invariants.yaml, then links tests to rules
|
|
26
|
+
npx @invariantly/cli check path/to/invariants.yaml --json
|
|
27
|
+
npx @invariantly/cli check --base main # also reports whether this branch changes a promise
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
A test guards a rule when its name, or the name of an enclosing `describe`, carries the rule id in brackets: `it("[INV-02] reports every missing field", …)`. `check` validates the registry first, then scans every `*.test.*` and `*.spec.*` file (`.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`) under the registry's directory, skipping `node_modules`, `dist`, `build`, `coverage` and dot-directories. It reports, in one run, every rule without an active test (a test that is skipped, todo, has no body or sits in a skipped `describe` does not count) and every marker that names a rule not in the registry.
|
|
31
|
+
|
|
32
|
+
pytest tests are found too (`test_*.py`, `*_test.py`) and marked with `@pytest.mark.invariant("INV-02")`. `check` reads the markers as text and combines them with vitest markers in one report. See [docs/format.md](docs/format.md#linking-tests-to-rules) for what is supported.
|
|
33
|
+
|
|
34
|
+
`check` only reads files as text: it never runs or imports your tests, writes no file and makes no network or AI call, so it is safe in CI.
|
|
35
|
+
|
|
36
|
+
Exit codes: `0` valid registry and every rule linked, `1` invalid registry, a rule without an active test or an unknown marker, `2` usage or file error. With `--json`, stdout carries one document: `schemaVersion` (`1`), the `validate` fields (`file`, `ok`, `ruleCount`, `problems`) plus `testFileCount`, `untested[]` (`id`, `path`, `skipped`), `unknownMarkers[]`, `links[]` (`id`, `file`, `line`, `test`, `active`) and `warnings[]` (`code`, `message`, `path`, `line?`). In `--json` mode warnings go into `warnings[]` and not to stderr. `validate --json` carries `schemaVersion` too.
|
|
37
|
+
|
|
38
|
+
### Report a contract change
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npx @invariantly/cli check --base main
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
With `--base <ref>`, `check` also compares the merge base of `<ref>` and `HEAD` with `HEAD` and reports whether the change is a contract change, one reason per finding:
|
|
45
|
+
|
|
46
|
+
- `contract-path`: a changed file matches a `contract_paths` glob (the human report names the glob);
|
|
47
|
+
- `registry`: a rule was added, removed, or had its `statement` or `status` changed, or the `contract_paths` list changed;
|
|
48
|
+
- `marker-removed`: a guarding test was deleted or renamed so it no longer carries the marker;
|
|
49
|
+
- `skip-added`: a guarding test was newly skipped.
|
|
50
|
+
|
|
51
|
+
The result is advisory: it never changes the exit code. `--base` compares commits only, not uncommitted edits. It reads git objects directly from `.git` without running `git`, so repository git configuration cannot run commands and no object is ever fetched. An unknown ref or a missing merge base (for example in a shallow CI checkout: fetch with `fetch-depth: 0`) exits `2`, as do reftable and SHA-256 repositories, which the reader does not support yet. With `--json` the document gains `contractChange` (`changed`, `reasons[]` of `{ kind, path, ruleId? }`). `reasons[].kind` and `warnings[].code` are open sets: ignore values you do not know.
|
|
52
|
+
|
|
53
|
+
## The registry
|
|
54
|
+
|
|
55
|
+
`invariants.yaml` lives in your repository and is the source of truth. Format version 0 ([JSON Schema](schema/invariants.v0.schema.json)):
|
|
56
|
+
|
|
57
|
+
```yaml
|
|
58
|
+
version: 0
|
|
59
|
+
rules:
|
|
60
|
+
- id: INV-02
|
|
61
|
+
statement: Every path through the order lifecycle to shipped passes through payment captured.
|
|
62
|
+
source: ADR-007, "no shipping on credit"
|
|
63
|
+
rationale: Someone adds a shortcut transition and goods leave the warehouse unpaid.
|
|
64
|
+
status: approved # approved | proposed | to-confirm
|
|
65
|
+
check: graph # example | integration | architecture | graph | property | stateful
|
|
66
|
+
components: [orders/lifecycle.ts]
|
|
67
|
+
|
|
68
|
+
contract_paths: # a change here needs a human (label: contract-change)
|
|
69
|
+
- orders/lifecycle.ts
|
|
70
|
+
- invariants.yaml
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Required for every rule: `id` (`INV-` plus at least two digits, unique), `statement`, `source`, `rationale`.
|
|
74
|
+
|
|
75
|
+
## What invariantly is not
|
|
76
|
+
|
|
77
|
+
- **Not an end-to-end UI testing tool.** Tools such as e2e or Playwright check what a user can do through the interface. invariantly guards domain and code-level promises, and gates changes to them. You can use both.
|
|
78
|
+
- **Not a hosted service.** It runs on your machine and in your CI.
|
|
79
|
+
|
|
80
|
+
## Roadmap
|
|
81
|
+
|
|
82
|
+
- A report of contract changes in a pull request.
|
|
83
|
+
- Adapters: pytest (with Hypothesis, on your consent) and vitest (with fast-check).
|
|
84
|
+
- `analyze` / `propose`: agents read the repository and propose rules for you to approve.
|
|
85
|
+
- `generate`: graph, architecture, property and stateful tests, each with a self-test that catches a planted violation.
|
|
86
|
+
- `serve`: a local panel on `127.0.0.1` to review rules, runs and pull requests.
|
|
87
|
+
- Agents run through the coding-agent CLI you already installed and signed in to (for example Claude Code or Codex), through your own API key, or through a local model. invariantly never handles your credentials.
|
|
88
|
+
- Repository code runs in a container by default.
|
|
89
|
+
|
|
90
|
+
## License
|
|
91
|
+
|
|
92
|
+
[Apache-2.0](LICENSE)
|
|
93
|
+
|
|
94
|
+
Trademarks: see [TRADEMARKS.md](TRADEMARKS.md) for how the invariantly name and logo may be used.
|
package/dist/base.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** One reason why a change is a contract change. `kind` is an open enum. */
|
|
2
|
+
export interface ContractReason {
|
|
3
|
+
kind: "contract-path" | "registry" | "marker-removed" | "skip-added";
|
|
4
|
+
/** Relative to the repository root, with `/` separators. */
|
|
5
|
+
path: string;
|
|
6
|
+
/** Present only when the reason concerns one rule. */
|
|
7
|
+
ruleId?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ContractChange {
|
|
10
|
+
changed: boolean;
|
|
11
|
+
reasons: ContractReason[];
|
|
12
|
+
}
|
|
13
|
+
/** The full comparison, with what the human output needs beyond the JSON shape. */
|
|
14
|
+
export interface BaseComparison {
|
|
15
|
+
ref: string;
|
|
16
|
+
mergeBase: string;
|
|
17
|
+
contractChange: ContractChange;
|
|
18
|
+
/** For each `contract-path` reason, the glob it matched (human output only; not in JSON). */
|
|
19
|
+
globs: Map<string, string>;
|
|
20
|
+
}
|
|
21
|
+
/** The base ref cannot be resolved, or has no merge base with HEAD: exit 2 with a fetch hint. */
|
|
22
|
+
export declare class BaseRefError extends Error {
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Compares the merge base of `ref` and HEAD with HEAD for the registry at `file`.
|
|
26
|
+
* Throws BaseRefError for an unknown ref or a missing merge base and GitError for a
|
|
27
|
+
* repository the reader cannot handle; the CLI turns both into exit 2.
|
|
28
|
+
*/
|
|
29
|
+
export declare function compareWithBase(file: string, schema: object, ref: string): Promise<BaseComparison>;
|
|
30
|
+
/**
|
|
31
|
+
* Matches a `contract_paths` glob against a path relative to the registry's directory.
|
|
32
|
+
* `*` and `?` match within one segment, `**` matches any number of segments, and a
|
|
33
|
+
* pattern without a glob character matches that exact path.
|
|
34
|
+
*/
|
|
35
|
+
export declare function matchContractPath(pattern: string, path: string): boolean;
|
package/dist/base.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { dirname, relative, resolve, sep } from "node:path";
|
|
2
|
+
import { parse } from "yaml";
|
|
3
|
+
import { findTests, isJsTestPath, isPythonTestCandidate, isTestDiscoveryDirectory, readRootPytestConfig, scanPytest, selectPythonFiles, } from "./check.js";
|
|
4
|
+
import { diffTrees, GitError, listTreePaths, mergeBase, openRepo, readBlob, readCommit, resolveRef } from "./git.js";
|
|
5
|
+
import { validateText } from "./validate.js";
|
|
6
|
+
/** The base ref cannot be resolved, or has no merge base with HEAD: exit 2 with a fetch hint. */
|
|
7
|
+
export class BaseRefError extends Error {
|
|
8
|
+
}
|
|
9
|
+
const KIND_ORDER = ["contract-path", "registry", "marker-removed", "skip-added"];
|
|
10
|
+
/**
|
|
11
|
+
* Compares the merge base of `ref` and HEAD with HEAD for the registry at `file`.
|
|
12
|
+
* Throws BaseRefError for an unknown ref or a missing merge base and GitError for a
|
|
13
|
+
* repository the reader cannot handle; the CLI turns both into exit 2.
|
|
14
|
+
*/
|
|
15
|
+
export async function compareWithBase(file, schema, ref) {
|
|
16
|
+
if (ref.startsWith("-"))
|
|
17
|
+
throw new BaseRefError(`invalid base ref: ${ref}`);
|
|
18
|
+
const registryDir = dirname(resolve(file));
|
|
19
|
+
const repo = await openRepo(registryDir);
|
|
20
|
+
const head = await resolveRef(repo, "HEAD");
|
|
21
|
+
let base;
|
|
22
|
+
try {
|
|
23
|
+
base = await mergeBase(repo, await resolveRef(repo, ref), head);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (!(error instanceof GitError))
|
|
27
|
+
throw error;
|
|
28
|
+
if (/^invalid ref name/.test(error.message)) {
|
|
29
|
+
throw new BaseRefError(`invalid base ref: ${ref} (use a branch, tag or remote ref name, or a full 40-character commit id)`);
|
|
30
|
+
}
|
|
31
|
+
// Only a ref or history that is not there locally gets the fetch hint; a corrupt or
|
|
32
|
+
// unsupported repository keeps its own message.
|
|
33
|
+
if (/^(ref not found|merge base not found|object not found)/.test(error.message)) {
|
|
34
|
+
throw new BaseRefError(missingRefMessage(ref, error.message));
|
|
35
|
+
}
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
const baseTree = (await readCommit(repo, base)).tree;
|
|
39
|
+
const headTree = (await readCommit(repo, head)).tree;
|
|
40
|
+
const changed = base === head ? [] : await diffTrees(repo, baseTree, headTree);
|
|
41
|
+
// Paths relative to the registry's directory, for globs and test discovery.
|
|
42
|
+
const prefix = toPosix(relative(repo.root, registryDir));
|
|
43
|
+
const local = (path) => prefix === "" ? path : path.startsWith(`${prefix}/`) ? path.slice(prefix.length + 1) : undefined;
|
|
44
|
+
const regRel = toPosix(relative(repo.root, resolve(file)));
|
|
45
|
+
const read = async (tree, path) => (await readBlob(repo, tree, path))?.toString("utf8");
|
|
46
|
+
const baseReg = loadRegistry(await read(baseTree, regRel), schema, regRel);
|
|
47
|
+
const headReg = loadRegistry(await read(headTree, regRel), schema, regRel);
|
|
48
|
+
const reasons = [];
|
|
49
|
+
const globs = new Map();
|
|
50
|
+
// 1. Contract paths: the union of the globs of every registry side that parses as YAML.
|
|
51
|
+
const patterns = [...new Set([...contractPaths(baseReg), ...contractPaths(headReg)])];
|
|
52
|
+
for (const path of changed) {
|
|
53
|
+
const rel = local(path);
|
|
54
|
+
if (rel === undefined)
|
|
55
|
+
continue;
|
|
56
|
+
const glob = patterns.find((p) => matchContractPath(p, rel));
|
|
57
|
+
if (glob !== undefined) {
|
|
58
|
+
reasons.push({ kind: "contract-path", path });
|
|
59
|
+
globs.set(path, glob);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// 2 and 3 run only when the HEAD registry is valid (OD-03).
|
|
63
|
+
if (headReg.valid) {
|
|
64
|
+
reasons.push(...registryReasons(baseReg, headReg, regRel));
|
|
65
|
+
const ids = new Set([...ruleIds(baseReg), ...ruleIds(headReg)]);
|
|
66
|
+
reasons.push(...(await markerReasons(repo, registryDir, prefix, changed, local, ids, baseTree, headTree)));
|
|
67
|
+
}
|
|
68
|
+
const sorted = dedupe(reasons).sort(compareReasons);
|
|
69
|
+
return { ref, mergeBase: base, contractChange: { changed: sorted.length > 0, reasons: sorted }, globs };
|
|
70
|
+
}
|
|
71
|
+
/** PA-11: name the ref and suggest a fetch, with any `origin/` prefix removed. */
|
|
72
|
+
function missingRefMessage(ref, detail) {
|
|
73
|
+
const name = ref.replace(/^(refs\/remotes\/)?origin\//, "");
|
|
74
|
+
return `base ref not found: ${ref} (${detail}); fetch it first, e.g. git fetch origin ${name}`;
|
|
75
|
+
}
|
|
76
|
+
function loadRegistry(text, schema, file) {
|
|
77
|
+
if (text === undefined)
|
|
78
|
+
return { doc: undefined, valid: false };
|
|
79
|
+
let doc;
|
|
80
|
+
try {
|
|
81
|
+
const parsed = parse(text);
|
|
82
|
+
doc = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
doc = null;
|
|
86
|
+
}
|
|
87
|
+
return { doc, valid: doc !== null && validateText(text, schema, file).ok };
|
|
88
|
+
}
|
|
89
|
+
function contractPaths(reg) {
|
|
90
|
+
const list = reg.doc?.contract_paths;
|
|
91
|
+
return Array.isArray(list) ? list.filter((p) => typeof p === "string") : [];
|
|
92
|
+
}
|
|
93
|
+
function rules(reg) {
|
|
94
|
+
const list = reg.doc?.rules;
|
|
95
|
+
if (!Array.isArray(list))
|
|
96
|
+
return [];
|
|
97
|
+
return list.filter((r) => r !== null && typeof r === "object" && typeof r.id === "string");
|
|
98
|
+
}
|
|
99
|
+
function ruleIds(reg) {
|
|
100
|
+
return rules(reg).map((r) => r.id);
|
|
101
|
+
}
|
|
102
|
+
function registryReasons(base, head, path) {
|
|
103
|
+
// A missing, unparsable or invalid base registry: one reason for the whole registry.
|
|
104
|
+
if (!base.valid)
|
|
105
|
+
return [{ kind: "registry", path }];
|
|
106
|
+
const reasons = [];
|
|
107
|
+
const before = new Map(rules(base).map((r) => [r.id, r]));
|
|
108
|
+
const after = new Map(rules(head).map((r) => [r.id, r]));
|
|
109
|
+
for (const id of new Set([...before.keys(), ...after.keys()])) {
|
|
110
|
+
const a = before.get(id);
|
|
111
|
+
const b = after.get(id);
|
|
112
|
+
if (!a || !b || a.statement !== b.statement || a.status !== b.status)
|
|
113
|
+
reasons.push({ kind: "registry", path, ruleId: id });
|
|
114
|
+
}
|
|
115
|
+
if (JSON.stringify(contractPaths(base)) !== JSON.stringify(contractPaths(head)))
|
|
116
|
+
reasons.push({ kind: "registry", path });
|
|
117
|
+
return reasons;
|
|
118
|
+
}
|
|
119
|
+
async function markerReasons(repo, registryDir, prefix, changed, local, ids, baseTree, headTree) {
|
|
120
|
+
// Which changed files are tests: today's discovery rules (as coverage applies them).
|
|
121
|
+
let config;
|
|
122
|
+
try {
|
|
123
|
+
config = await readRootPytestConfig(registryDir);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
config = undefined;
|
|
127
|
+
}
|
|
128
|
+
const candidates = changed.flatMap((path) => {
|
|
129
|
+
const rel = local(path);
|
|
130
|
+
return rel === undefined ? [] : [{ path, rel }];
|
|
131
|
+
});
|
|
132
|
+
const js = candidates.filter((c) => isJsTestPath(c.rel));
|
|
133
|
+
const pythonCandidates = candidates.map(({ rel }) => rel).filter(isPythonTestCandidate);
|
|
134
|
+
const selectChangedPythonPaths = async (tree) => {
|
|
135
|
+
if (!config || pythonCandidates.length === 0)
|
|
136
|
+
return new Set();
|
|
137
|
+
const seen = config.testpaths.length > 0
|
|
138
|
+
? await listTreePaths(repo, tree, prefix, isTestDiscoveryDirectory)
|
|
139
|
+
: new Set();
|
|
140
|
+
return new Set(selectPythonFiles({ py: pythonCandidates, seen }, config));
|
|
141
|
+
};
|
|
142
|
+
// A file with a lexical fault on either side is left out of both sides: no reason is
|
|
143
|
+
// invented from the fault (the fault itself is reported as a coverage warning).
|
|
144
|
+
const faulted = new Set();
|
|
145
|
+
const count = async (tree) => {
|
|
146
|
+
const perFile = new Map();
|
|
147
|
+
const pythonPaths = await selectChangedPythonPaths(tree);
|
|
148
|
+
const python = candidates.filter(({ rel }) => pythonPaths.has(rel));
|
|
149
|
+
for (const { path } of [...js, ...python]) {
|
|
150
|
+
const text = (await readBlob(repo, tree, path))?.toString("utf8");
|
|
151
|
+
const counts = new Map();
|
|
152
|
+
perFile.set(path, counts);
|
|
153
|
+
if (text === undefined)
|
|
154
|
+
continue;
|
|
155
|
+
const add = (id, active) => {
|
|
156
|
+
if (!ids.has(id))
|
|
157
|
+
return;
|
|
158
|
+
const c = counts.get(id) ?? { markers: 0, active: 0 };
|
|
159
|
+
c.markers += 1;
|
|
160
|
+
if (active)
|
|
161
|
+
c.active += 1;
|
|
162
|
+
counts.set(id, c);
|
|
163
|
+
};
|
|
164
|
+
if (js.some((c) => c.path === path)) {
|
|
165
|
+
for (const t of findTests(text))
|
|
166
|
+
if (t.kind === "test")
|
|
167
|
+
for (const id of t.markers)
|
|
168
|
+
add(id, t.active);
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
const scan = scanPytest(text);
|
|
172
|
+
if (scan.fault) {
|
|
173
|
+
faulted.add(path);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
for (const t of scan.tests) {
|
|
177
|
+
if (t.kind !== "test" || t.markers.length === 0)
|
|
178
|
+
continue;
|
|
179
|
+
if (config?.deselect !== undefined && t.marks.includes(config.deselect))
|
|
180
|
+
continue;
|
|
181
|
+
for (const id of t.markers)
|
|
182
|
+
add(id, t.active);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return perFile;
|
|
187
|
+
};
|
|
188
|
+
const before = await count(baseTree);
|
|
189
|
+
const after = await count(headTree);
|
|
190
|
+
for (const path of faulted) {
|
|
191
|
+
before.delete(path);
|
|
192
|
+
after.delete(path);
|
|
193
|
+
}
|
|
194
|
+
const paths = new Set([...before.keys(), ...after.keys()]);
|
|
195
|
+
const reasons = [];
|
|
196
|
+
const get = (m, path, id) => m.get(path)?.get(id) ?? { markers: 0, active: 0 };
|
|
197
|
+
for (const id of ids) {
|
|
198
|
+
let dm = 0;
|
|
199
|
+
let da = 0;
|
|
200
|
+
for (const path of paths) {
|
|
201
|
+
dm += get(before, path, id).markers - get(after, path, id).markers;
|
|
202
|
+
da += get(before, path, id).active - get(after, path, id).active;
|
|
203
|
+
}
|
|
204
|
+
// Summing over every changed file first: a test moved between files gives no reason.
|
|
205
|
+
if (dm > 0) {
|
|
206
|
+
for (const path of paths) {
|
|
207
|
+
if (get(after, path, id).markers < get(before, path, id).markers)
|
|
208
|
+
reasons.push({ kind: "marker-removed", path, ruleId: id });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
// Active tests fell by more than markers did: some guarding test was newly skipped.
|
|
212
|
+
// It is reported on every file whose own count of inactive markers rose, which also
|
|
213
|
+
// covers a test that was moved (or renamed) and skipped in the same change.
|
|
214
|
+
if (da > Math.max(dm, 0)) {
|
|
215
|
+
for (const path of paths) {
|
|
216
|
+
const b = get(before, path, id);
|
|
217
|
+
const a = get(after, path, id);
|
|
218
|
+
if (a.markers - a.active > b.markers - b.active)
|
|
219
|
+
reasons.push({ kind: "skip-added", path, ruleId: id });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return reasons;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Matches a `contract_paths` glob against a path relative to the registry's directory.
|
|
227
|
+
* `*` and `?` match within one segment, `**` matches any number of segments, and a
|
|
228
|
+
* pattern without a glob character matches that exact path.
|
|
229
|
+
*/
|
|
230
|
+
export function matchContractPath(pattern, path) {
|
|
231
|
+
const pat = pattern.replace(/^\.\//, "").split("/").filter((s) => s !== "");
|
|
232
|
+
const parts = path.split("/");
|
|
233
|
+
// Memoized over (pattern segment, path segment): at most pat.length × parts.length states.
|
|
234
|
+
const memo = new Map();
|
|
235
|
+
const match = (p, s) => {
|
|
236
|
+
if (p === pat.length)
|
|
237
|
+
return s === parts.length;
|
|
238
|
+
const key = p * (parts.length + 1) + s;
|
|
239
|
+
const hit = memo.get(key);
|
|
240
|
+
if (hit !== undefined)
|
|
241
|
+
return hit;
|
|
242
|
+
let result;
|
|
243
|
+
if (pat[p] === "**") {
|
|
244
|
+
result = false;
|
|
245
|
+
for (let k = s; k <= parts.length && !result; k++)
|
|
246
|
+
result = match(p + 1, k);
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
result = s < parts.length && wildcard(pat[p], parts[s]) && match(p + 1, s + 1);
|
|
250
|
+
}
|
|
251
|
+
memo.set(key, result);
|
|
252
|
+
return result;
|
|
253
|
+
};
|
|
254
|
+
return match(0, 0);
|
|
255
|
+
}
|
|
256
|
+
/** `*` and `?` within one segment, matched greedily with one backtrack point (linear time). */
|
|
257
|
+
function wildcard(glob, name) {
|
|
258
|
+
let g = 0;
|
|
259
|
+
let n = 0;
|
|
260
|
+
let star = -1;
|
|
261
|
+
let mark = 0;
|
|
262
|
+
while (n < name.length) {
|
|
263
|
+
if (g < glob.length && (glob[g] === "?" || glob[g] === name[n])) {
|
|
264
|
+
g++;
|
|
265
|
+
n++;
|
|
266
|
+
}
|
|
267
|
+
else if (g < glob.length && glob[g] === "*") {
|
|
268
|
+
star = g++;
|
|
269
|
+
mark = n;
|
|
270
|
+
}
|
|
271
|
+
else if (star >= 0) {
|
|
272
|
+
g = star + 1;
|
|
273
|
+
n = ++mark;
|
|
274
|
+
}
|
|
275
|
+
else
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
while (g < glob.length && glob[g] === "*")
|
|
279
|
+
g++;
|
|
280
|
+
return g === glob.length;
|
|
281
|
+
}
|
|
282
|
+
function dedupe(reasons) {
|
|
283
|
+
const seen = new Map();
|
|
284
|
+
for (const r of reasons)
|
|
285
|
+
seen.set(`${r.kind}\0${r.path}\0${r.ruleId ?? ""}`, r);
|
|
286
|
+
return [...seen.values()];
|
|
287
|
+
}
|
|
288
|
+
function compareReasons(a, b) {
|
|
289
|
+
const kind = KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind);
|
|
290
|
+
if (kind !== 0)
|
|
291
|
+
return kind;
|
|
292
|
+
if (a.path !== b.path)
|
|
293
|
+
return a.path < b.path ? -1 : 1;
|
|
294
|
+
const x = a.ruleId ?? "";
|
|
295
|
+
const y = b.ruleId ?? "";
|
|
296
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
297
|
+
}
|
|
298
|
+
function toPosix(path) {
|
|
299
|
+
return path.split(sep).join("/");
|
|
300
|
+
}
|