@descent-vtt/spec-graph 0.3.0 → 0.4.0
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/CHANGELOG.md +178 -5
- package/README.md +82 -1
- package/dist/baseline.d.ts +18 -4
- package/dist/baseline.js +14 -2
- package/dist/baseline.js.map +1 -1
- package/dist/cli.d.ts +3 -3
- package/dist/cli.js +97 -21
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +12 -2
- package/dist/config.js +21 -1
- package/dist/config.js.map +1 -1
- package/dist/extract.d.ts +0 -11
- package/dist/extract.js +19 -38
- package/dist/extract.js.map +1 -1
- package/dist/identity.d.ts +10 -0
- package/dist/identity.js +37 -0
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/project-rules.d.ts +92 -0
- package/dist/project-rules.js +201 -0
- package/dist/project-rules.js.map +1 -0
- package/dist/report.d.ts +15 -7
- package/dist/report.js +63 -5
- package/dist/report.js.map +1 -1
- package/dist/resolve.d.ts +8 -1
- package/dist/resolve.js +154 -30
- package/dist/resolve.js.map +1 -1
- package/dist/rules.d.ts +8 -5
- package/dist/rules.js +66 -5
- package/dist/rules.js.map +1 -1
- package/dist/runner.d.ts +5 -2
- package/dist/runner.js +1 -0
- package/dist/runner.js.map +1 -1
- package/dist/select.d.ts +11 -0
- package/dist/select.js +31 -0
- package/dist/select.js.map +1 -1
- package/dist/types.d.ts +36 -1
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,178 @@
|
|
|
3
3
|
Notable changes, newest first. Versions follow [semver](https://semver.org):
|
|
4
4
|
a patch fixes behaviour without asking anything of a repository that upgrades.
|
|
5
5
|
|
|
6
|
+
## 0.4.0
|
|
7
|
+
|
|
8
|
+
Ten open questions across the ADR suite, answered. Five shipped, three declined
|
|
9
|
+
with a reason, one settled by measuring it, and one withdrawn because it turned
|
|
10
|
+
out not to be true.
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
**A repository can write its own rules.** `rules` in `.spec-graph.json` takes a
|
|
15
|
+
selector, a message, a hint and a severity, and runs it beside the built-ins:
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
"rules": {
|
|
19
|
+
"no-draft-dependency": {
|
|
20
|
+
"query": "document[phase=active] -depends-on-> document[phase=draft]",
|
|
21
|
+
"message": "{0} depends on {1}, which is still a draft",
|
|
22
|
+
"hint": "wait for {1} to be accepted, or drop it from {0.path}",
|
|
23
|
+
"severity": "error"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
[ADR-0005](docs/adr/0005-rules-are-queries.md) claimed for three releases that
|
|
29
|
+
the selector language was expressive enough for a team to write the equivalent
|
|
30
|
+
of a built-in rule. It was only true at a prompt: `spec-graph query` could find
|
|
31
|
+
the thing, and nothing could make finding it fail. Three ADRs recorded the same
|
|
32
|
+
gap and stopped at the same sentence - a query needs a severity and a message
|
|
33
|
+
before it is a rule.
|
|
34
|
+
|
|
35
|
+
The id is the name with `project:` in front, and a built-in id can never contain
|
|
36
|
+
a colon. That one fact is why `--rule`, `--strict`, `--record-baseline`, the
|
|
37
|
+
severity table, the record exemption, the sort order and the SARIF `ruleId` all
|
|
38
|
+
carry a user-defined rule without being taught what one is.
|
|
39
|
+
|
|
40
|
+
Messages interpolate over the path the query already numbers: `{0}` and `{1}`
|
|
41
|
+
for node ids, `{1.phase}` and `{0.fm.owner}` for anything a selector can read. A
|
|
42
|
+
selector that does not parse, a `{2}` no query can reach, or an attribute
|
|
43
|
+
nothing answers to is reported when the file is read - a rule that cannot work
|
|
44
|
+
has to say so, because silence from a linter is indistinguishable from health.
|
|
45
|
+
`query` also takes a list, read as a union.
|
|
46
|
+
|
|
47
|
+
See [ADR-0016](docs/adr/0016-a-query-needs-a-sentence.md).
|
|
48
|
+
|
|
49
|
+
**A broken reference suggests the document it was probably meant to name.**
|
|
50
|
+
`ARD-0015` gets `did you mean ADR-0015?`; `0002-cacheing.md` gets its sibling
|
|
51
|
+
one letter away. `ADR-0003` in a repository of two ADRs gets nothing, and that
|
|
52
|
+
restraint is the design rather than a limitation of it: a family name is a word
|
|
53
|
+
people misremember, a number *is* the identity, and every number sits one edit
|
|
54
|
+
from its neighbours. Each gate ends the same way - exactly one candidate, or
|
|
55
|
+
silence. See [ADR-0004](docs/adr/0004-reference-resolution.md).
|
|
56
|
+
|
|
57
|
+
**A stale baseline entry says `paid` or `gone`.** `paid` is the ratchet working.
|
|
58
|
+
`gone` means the document was not in this corpus at all, so nothing is known
|
|
59
|
+
about the defect - and the ordinary way to produce one is to narrow an include
|
|
60
|
+
pattern. Both still trip `--ratchet`, but the verdict now says how many entries
|
|
61
|
+
name documents the run did not see and asks a team to check their patterns,
|
|
62
|
+
rather than congratulating them for losing sight of a problem.
|
|
63
|
+
|
|
64
|
+
**Stale entries are named in the JSON report**, under `baseline.entries`, each
|
|
65
|
+
with its label. A count is enough to know the file has slack and never enough to
|
|
66
|
+
strike it.
|
|
67
|
+
|
|
68
|
+
**`--verbose` lists what configuration silenced.** Every reference
|
|
69
|
+
`ignoreReferences` or `ignoreFamilies` suppressed, grouped by target and naming
|
|
70
|
+
which of the two did it; the JSON report carries every site under `suppressed`
|
|
71
|
+
without the flag. A single over-broad glob looks exactly like a clean repository
|
|
72
|
+
from the outside, and nothing said otherwise. Not listed: a bare identifier
|
|
73
|
+
spec-graph read as prose on its own - that was nobody's decision.
|
|
74
|
+
|
|
75
|
+
**A NUL byte is reported as a parse problem.** Not a finding: nothing about the
|
|
76
|
+
graph is wrong and it never fails a build. It earns the line because spec-graph
|
|
77
|
+
is likely the only tool that read the file at all - grep, diff and every review
|
|
78
|
+
interface treat it as binary - and the message names the usual cause, which is
|
|
79
|
+
UTF-16 read as UTF-8 rather than anybody's keystroke.
|
|
80
|
+
|
|
81
|
+
### Fixed
|
|
82
|
+
|
|
83
|
+
Nothing that a corpus had hit. Two findings came out of probing rather than out
|
|
84
|
+
of the suite, which is the practice [CLAUDE.md](CLAUDE.md) asks for:
|
|
85
|
+
|
|
86
|
+
- A near-miss gate that suggested a file which had moved **never fired**.
|
|
87
|
+
Resolution already binds a path by its basename, so the suggestion had nothing
|
|
88
|
+
left to suggest. Removed before it shipped rather than after.
|
|
89
|
+
- Hand-mutating each remaining gate found two that no test could kill. One was
|
|
90
|
+
genuinely equivalent code and is now one line shorter; the other was masked by
|
|
91
|
+
a length floor, and the test now writes a number long enough to clear it.
|
|
92
|
+
|
|
93
|
+
### Not added
|
|
94
|
+
|
|
95
|
+
- **SARIF `fixes`.** Counted the findings with a fix that is an edit rather than
|
|
96
|
+
a judgement, and there is one. Everything else has to be *inserted*, into front
|
|
97
|
+
matter that may not exist, at a position only a human can choose. The new
|
|
98
|
+
near-miss suggestions made the case weaker rather than stronger: they are
|
|
99
|
+
deliberately a guess, and promoting a guess to a machine-applicable edit throws
|
|
100
|
+
away the restraint that makes it worth printing.
|
|
101
|
+
- **Hybrid documents** - a specification with a changelog section. The premise
|
|
102
|
+
turned out to be wrong: regions cannot express it, because `record` is decided
|
|
103
|
+
once per file and inherited by everything in it. Making it work means a second
|
|
104
|
+
source of truth for `record`, traded against a free workaround - put the
|
|
105
|
+
changelog in its own file, which is where it belongs.
|
|
106
|
+
- **Cross-repository references.** Every way of doing it puts network or
|
|
107
|
+
discovery underneath a pipeline whose test strategy rests on being a pure
|
|
108
|
+
function of text.
|
|
109
|
+
- **A guard for `~=`.** Probing confirmed `[title~=(a+)+$]` never returns. The
|
|
110
|
+
hang has been reachable from `query` since 0.1.0; what 0.4.0 changes is that it
|
|
111
|
+
now lives in a file that runs on every build. Rejecting nested quantifiers
|
|
112
|
+
catches `(a+)+` and misses `(a|a)+`, and a guard that is incomplete and says it
|
|
113
|
+
is safe is worse than no guard. Documented instead, with the alternatives
|
|
114
|
+
weighed in ADR-0016.
|
|
115
|
+
|
|
116
|
+
### Measured
|
|
117
|
+
|
|
118
|
+
**The near-miss gate for front-matter keys stays at one edit**, and this is the
|
|
119
|
+
first time anybody checked. Across 73 keys that Jekyll, Hugo, Docusaurus, Astro,
|
|
120
|
+
MADR, KEP, the IETF datatracker and Obsidian actually write, one edit reads
|
|
121
|
+
*none* of them as a near-miss and two edits reads exactly one: `rfc`, which it
|
|
122
|
+
would tell an author to spell `refs`. [ADR-0014](docs/adr/0014-a-relation-is-spelled-both-ways.md)
|
|
123
|
+
said two edits would catch `dependancies`; one edit already did, along with
|
|
124
|
+
every other typo anybody produced to argue the case. Two buys nothing and costs
|
|
125
|
+
a false positive on a key that carries citations in exactly the corpora this
|
|
126
|
+
tool is pointed at.
|
|
127
|
+
|
|
128
|
+
### Verified
|
|
129
|
+
|
|
130
|
+
| | |
|
|
131
|
+
|---|---|
|
|
132
|
+
| `npm run lint` | pass |
|
|
133
|
+
| `npm test` | 754 passing, 20 files |
|
|
134
|
+
| `npm run selfcheck` | pass, over 19 documents and 124 relations |
|
|
135
|
+
| `npm run test:mutation` | 79.41% over 8,585 mutants, 64m30s |
|
|
136
|
+
| hosted full run, which governs | **75.40%**, 102m48s |
|
|
137
|
+
| `break` | unchanged at 70 |
|
|
138
|
+
|
|
139
|
+
79.69% over 8,126 mutants at 0.3.0 against 79.41% over 8,585 here, on the same
|
|
140
|
+
machine. The new code carries itself: `project-rules.ts` at **99.50%** with one
|
|
141
|
+
survivor - a genuinely equivalent `<` against `<=` in a comparator whose inputs
|
|
142
|
+
are object keys and therefore never equal.
|
|
143
|
+
|
|
144
|
+
That 99.50% is what reading the survivor list bought. The first full run put the
|
|
145
|
+
module at 86.89%, a targeted re-measurement with `coverageAnalysis all` agreed at
|
|
146
|
+
86.41% - so the gap was real and not `perTest` mis-attribution - and sixteen of
|
|
147
|
+
those survivors turned out to be tests nobody had written. The whole-corpus
|
|
148
|
+
figure moved 0.38 points for it.
|
|
149
|
+
|
|
150
|
+
The hosted number is the one that actually governs, because it is where the build
|
|
151
|
+
fails: **75.40%**, up from 75.14% at 0.3.0. Lose every timeout on a loaded runner
|
|
152
|
+
and it reads 71.76%, which is the most margin `break: 70` has ever had.
|
|
153
|
+
|
|
154
|
+
That run also caught the other half of a claim
|
|
155
|
+
[ADR-0007](docs/adr/0007-mutation-testing.md) narrowed at 0.3.0. The `main` push
|
|
156
|
+
and the `v0.4.0` tag were the same commit on the same runner, and the incremental
|
|
157
|
+
read **1.29 points low** against the rebuild - having read 3.18 points *high* at
|
|
158
|
+
0.3.0. Two observations, opposite signs. The direction is not a property, and the
|
|
159
|
+
incremental run took 110 minutes to the rebuild's 103, because a change this wide
|
|
160
|
+
leaves it nothing to reuse.
|
|
161
|
+
|
|
162
|
+
### Withdrawn
|
|
163
|
+
|
|
164
|
+
[ADR-0013](docs/adr/0013-the-scanner-hands-back-prose.md) said a lone `\r` was
|
|
165
|
+
not treated as a line ending. It always was - `createLineIndex` has recognised
|
|
166
|
+
all three terminators since 0.1.0 and says so in its own doc comment. The claim
|
|
167
|
+
came from reading the scanner and not the table underneath it, and nobody had
|
|
168
|
+
executed it. One corpus through `\n`, `\r\n` and `\r` now produces identical
|
|
169
|
+
items, findings and line numbers, as a test.
|
|
170
|
+
|
|
171
|
+
### Changed
|
|
172
|
+
|
|
173
|
+
For anyone using the programmatic API: `Diagnostic.rule` is now `AnyRuleId`,
|
|
174
|
+
which is `RuleId` plus the `project:` namespace. An exhaustive `switch` over the
|
|
175
|
+
built-ins needs a default arm. `BaselineOutcome.stale` carries `reason`, and
|
|
176
|
+
`ResolvedCorpus` carries `suppressed`.
|
|
177
|
+
|
|
6
178
|
## 0.3.0
|
|
7
179
|
|
|
8
180
|
Found by writing a corpus designed to break the scanner and reading the edges it
|
|
@@ -99,11 +271,12 @@ text. Reasoning in
|
|
|
99
271
|
|
|
100
272
|
### Measured
|
|
101
273
|
|
|
102
|
-
684 tests, and a mutation score of **
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
274
|
+
684 tests, and a mutation score of **75.14% on the hosted runner** - the figure
|
|
275
|
+
that governs, up from 73.32% at v0.2.0 - against 79.69% over 8,126 mutants on a
|
|
276
|
+
developer machine. The guard stays at `break: 70`. See
|
|
277
|
+
[ADR-0007](docs/adr/0007-mutation-testing.md), which 0.3.0 also amended: an
|
|
278
|
+
incremental run read 3.18 points *high* against a full rebuild of the same
|
|
279
|
+
commit, so the claim that incremental errs low was wrong.
|
|
107
280
|
|
|
108
281
|
## 0.2.3
|
|
109
282
|
|
package/README.md
CHANGED
|
@@ -363,6 +363,9 @@ gate without writing any code:
|
|
|
363
363
|
! npx spec-graph query 'document[path^=docs/prd] -depends-on-> document[phase=draft]'
|
|
364
364
|
```
|
|
365
365
|
|
|
366
|
+
That shell line is a rule wearing a disguise. Give it a name and a sentence and
|
|
367
|
+
it becomes one — see [your own rules](#your-own-rules) below.
|
|
368
|
+
|
|
366
369
|
**Grammar**
|
|
367
370
|
|
|
368
371
|
```text
|
|
@@ -383,6 +386,64 @@ Items inherit their document's lifecycle, so `item[phase=retired]` means what yo
|
|
|
383
386
|
expect. A query evaluates to **paths**, not endpoints, which is why a finding can
|
|
384
387
|
name both ends and the line that connects them.
|
|
385
388
|
|
|
389
|
+
## Your own rules
|
|
390
|
+
|
|
391
|
+
A convention spec-graph never anticipated is a selector plus a sentence. Write
|
|
392
|
+
both in the config file and it becomes a rule like any other:
|
|
393
|
+
|
|
394
|
+
```json
|
|
395
|
+
{
|
|
396
|
+
"rules": {
|
|
397
|
+
"no-draft-dependency": {
|
|
398
|
+
"query": "document[phase=active] -depends-on-> document[phase=draft]",
|
|
399
|
+
"message": "{0} depends on {1}, which is still a draft",
|
|
400
|
+
"hint": "wait for {1} to be accepted, or drop it from {0.path}",
|
|
401
|
+
"severity": "error"
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
```text
|
|
408
|
+
x docs/adr/0002-delivery.md:4:13 project:no-draft-dependency
|
|
409
|
+
ADR-0002 depends on ADR-0001, which is still a draft
|
|
410
|
+
> wait for ADR-0001 to be accepted, or drop it from docs/adr/0002-delivery.md
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
The finding points at the line that *declares* the relation, because that is
|
|
414
|
+
where a human goes to change the answer — the same discipline every built-in
|
|
415
|
+
follows.
|
|
416
|
+
|
|
417
|
+
| Field | |
|
|
418
|
+
|---|---|
|
|
419
|
+
| `query` | One selector, or a list of them read as a union. |
|
|
420
|
+
| `message` | The headline. `{0}` is the first node on the path, `{1}` the next; `{1.phase}` and `{0.fm.owner}` read any selector attribute. |
|
|
421
|
+
| `hint` | The next action. Optional, templated the same way. |
|
|
422
|
+
| `severity` | `error`, `warn`, `info` or `off`. Defaults to `warn`. |
|
|
423
|
+
|
|
424
|
+
It defaults to `warn` on purpose: a rule a team has just written has not yet
|
|
425
|
+
earned the right to fail their build, and the first run of a new convention is
|
|
426
|
+
when it is most likely to be wrong.
|
|
427
|
+
|
|
428
|
+
The id is the name with `project:` in front, which is why it can never collide
|
|
429
|
+
with a built-in — and why everything else already works. It is baselined by
|
|
430
|
+
`--record-baseline`, silenced by `--rule project:no-draft-dependency=off`,
|
|
431
|
+
escalated by `--strict`, listed by `spec-graph rules`, exempted on journals like
|
|
432
|
+
every other rule about obligations, and emitted as a first-class `ruleId` in
|
|
433
|
+
SARIF, where a project rule describes itself by the selector it is.
|
|
434
|
+
|
|
435
|
+
Mistakes are reported when the file is read, not discovered as a rule that
|
|
436
|
+
quietly finds nothing:
|
|
437
|
+
|
|
438
|
+
```text
|
|
439
|
+
spec-graph: .spec-graph.json: rules.no-drafts: mismatched arrow: use -kind-> for
|
|
440
|
+
one hop or =kind=> for transitive (at character 10)
|
|
441
|
+
spec-graph: .spec-graph.json: rules.owner: "{1.phse}" asks for an attribute
|
|
442
|
+
nothing has
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
See [ADR-0016](docs/adr/0016-a-query-needs-a-sentence.md).
|
|
446
|
+
|
|
386
447
|
## Directives
|
|
387
448
|
|
|
388
449
|
Inference covers almost everything, but inference you cannot override is a trap.
|
|
@@ -523,7 +584,13 @@ command. spec-graph reads the first of `.spec-graph.json`,
|
|
|
523
584
|
"baseline": ".spec-graph-baseline.json",
|
|
524
585
|
"ratchet": true,
|
|
525
586
|
"severities": { "self-reference": "off" },
|
|
526
|
-
"strict": true
|
|
587
|
+
"strict": true,
|
|
588
|
+
"rules": {
|
|
589
|
+
"no-draft-dependency": {
|
|
590
|
+
"query": "document[phase=active] -depends-on-> document[phase=draft]",
|
|
591
|
+
"message": "{0} depends on {1}, which is still a draft"
|
|
592
|
+
}
|
|
593
|
+
}
|
|
527
594
|
}
|
|
528
595
|
```
|
|
529
596
|
|
|
@@ -554,6 +621,20 @@ resolves to your local RFC-0001 with `RFC` on the ignore list. No configuration
|
|
|
554
621
|
can delete an edge. See
|
|
555
622
|
[ADR-0010](docs/adr/0010-configuration-belongs-to-the-repository.md).
|
|
556
623
|
|
|
624
|
+
`--verbose` lists everything they silenced, so one over-broad glob cannot quietly
|
|
625
|
+
turn the check off and look like a clean repository:
|
|
626
|
+
|
|
627
|
+
```text
|
|
628
|
+
i docs/adr/0001-traps.md:15:3 ignored reference: trap 55 (2 times)
|
|
629
|
+
i docs/rfcs/0002-transport.md:7:69 ignored family: RFC 2119
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
The JSON report carries the same rows under `suppressed`, without needing the
|
|
633
|
+
flag. What is deliberately *not* listed is a bare identifier spec-graph read as
|
|
634
|
+
prose on its own — `T-1000` was nobody's decision, and listing it would bury the
|
|
635
|
+
entries that were. See
|
|
636
|
+
[ADR-0008](docs/adr/0008-wiki-links-carry-no-path.md).
|
|
637
|
+
|
|
557
638
|
Prose like `Phase 1`, `R69`, `Q-120`, `Table 2` and `Step 4` has never needed
|
|
558
639
|
this: an identifier found in prose is only read as a citation when its family
|
|
559
640
|
already exists in the corpus.
|
package/dist/baseline.d.ts
CHANGED
|
@@ -14,12 +14,12 @@
|
|
|
14
14
|
* the same reason extraction never touches a disk.
|
|
15
15
|
*/
|
|
16
16
|
import type { SpecGraph } from './graph.js';
|
|
17
|
-
import type
|
|
17
|
+
import { type AnyRuleId, type Diagnostic } from './types.js';
|
|
18
18
|
/** The current file format. Bumped only for a change old files cannot survive. */
|
|
19
19
|
export declare const BASELINE_VERSION = 1;
|
|
20
20
|
/** One class of accepted finding, and how many of it there were. */
|
|
21
21
|
export interface BaselineEntry {
|
|
22
|
-
readonly rule:
|
|
22
|
+
readonly rule: AnyRuleId;
|
|
23
23
|
/** The specification the finding is about, not the file it was found in. */
|
|
24
24
|
readonly document: string;
|
|
25
25
|
/** What within it: a citation target, or the document at the other end. */
|
|
@@ -70,18 +70,32 @@ export interface ParsedBaseline {
|
|
|
70
70
|
}
|
|
71
71
|
/** Parses a baseline file. Never throws; an unusable file yields an empty one. */
|
|
72
72
|
export declare function parseBaseline(raw: string, source: string): ParsedBaseline;
|
|
73
|
+
/**
|
|
74
|
+
* An entry the run did not spend, and why.
|
|
75
|
+
*
|
|
76
|
+
* The distinction is the whole value of the label. `paid` is the ratchet
|
|
77
|
+
* working: the defect was fixed and the exemption can be struck. `gone` is not
|
|
78
|
+
* an achievement at all - the document the entry is about was not in this
|
|
79
|
+
* corpus, so nothing whatever is known about the defect. Both make the file
|
|
80
|
+
* stale and both need it re-recorded, but only one of them is good news, and a
|
|
81
|
+
* report that says "paid" over a narrowed `patterns` glob is congratulating a
|
|
82
|
+
* team for losing sight of the problem.
|
|
83
|
+
*/
|
|
84
|
+
export interface StaleEntry extends BaselineEntry {
|
|
85
|
+
readonly reason: 'paid' | 'gone';
|
|
86
|
+
}
|
|
73
87
|
export interface BaselineOutcome {
|
|
74
88
|
/** Findings the baseline does not account for. These are the report. */
|
|
75
89
|
readonly kept: readonly Diagnostic[];
|
|
76
90
|
/** How many were accounted for. Reported as a number, not as a list. */
|
|
77
91
|
readonly suppressed: number;
|
|
78
92
|
/**
|
|
79
|
-
* Entries whose debt
|
|
93
|
+
* Entries whose debt was not spent, wholly or partly.
|
|
80
94
|
*
|
|
81
95
|
* The ratchet: once a repository is clean of something, saying so in the file
|
|
82
96
|
* stops it coming back unnoticed.
|
|
83
97
|
*/
|
|
84
|
-
readonly stale: readonly
|
|
98
|
+
readonly stale: readonly StaleEntry[];
|
|
85
99
|
}
|
|
86
100
|
/**
|
|
87
101
|
* Removes the findings a baseline accounts for.
|
package/dist/baseline.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* the same reason extraction never touches a disk.
|
|
15
15
|
*/
|
|
16
16
|
import { RULE_IDS } from './rules.js';
|
|
17
|
+
import { isProjectRule } from './types.js';
|
|
17
18
|
/** The current file format. Bumped only for a change old files cannot survive. */
|
|
18
19
|
export const BASELINE_VERSION = 1;
|
|
19
20
|
export const EMPTY_BASELINE = Object.freeze({ version: BASELINE_VERSION, findings: [] });
|
|
@@ -128,7 +129,12 @@ function readEntry(row, where, problems) {
|
|
|
128
129
|
}
|
|
129
130
|
const fields = row;
|
|
130
131
|
const rule = fields['rule'];
|
|
131
|
-
|
|
132
|
+
// A project rule is accepted on its namespace alone, because the baseline is
|
|
133
|
+
// read before the configuration that defines it has any say - and an entry
|
|
134
|
+
// rejected here would silently un-accept debt a team had already signed off.
|
|
135
|
+
// A name nothing defines suppresses nothing and is reported as stale, which
|
|
136
|
+
// is the same answer by a route that keeps the file readable.
|
|
137
|
+
if (typeof rule !== 'string' || !(RULE_IDS.includes(rule) || isProjectRule(rule))) {
|
|
132
138
|
problems.push(`${where}: unknown rule ${JSON.stringify(rule)}`);
|
|
133
139
|
return null;
|
|
134
140
|
}
|
|
@@ -177,7 +183,13 @@ export function applyBaseline(graph, diagnostics, baseline) {
|
|
|
177
183
|
const unspent = budget.get(key) ?? 0;
|
|
178
184
|
if (unspent <= 0)
|
|
179
185
|
continue;
|
|
180
|
-
|
|
186
|
+
// Asked of the graph rather than of the filesystem, because the graph is
|
|
187
|
+
// what this run looked at. A document that still exists on disk and fell
|
|
188
|
+
// outside the include patterns is gone for the purposes of the answer, and
|
|
189
|
+
// that is the case worth telling apart - it is the one a team reaches by
|
|
190
|
+
// editing a glob rather than by fixing anything.
|
|
191
|
+
const reason = graph.document(entry.document) === undefined ? 'gone' : 'paid';
|
|
192
|
+
stale.push({ ...entry, count: Math.min(unspent, entry.count), reason });
|
|
181
193
|
// An entry counted once; a duplicate key in a hand-edited file must not
|
|
182
194
|
// claim the same surplus twice.
|
|
183
195
|
budget.set(key, 0);
|
package/dist/baseline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baseline.js","sourceRoot":"","sources":["../src/baseline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAGtC,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAiBlC,MAAM,CAAC,MAAM,cAAc,GAAa,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;AAEnG;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,aAAa,CAAC,KAAgB,EAAE,UAAsB;IACpE,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,MAAM,QAAQ,GAAG,KAAK,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,KAAK,CAAC;IAC1D,IAAI,UAAU,CAAC,MAAM,KAAK,IAAI;QAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IAEhF,MAAM,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnC,MAAM,OAAO,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,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AAG,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC7D,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,IAAI,OAAO,IAAI,CAAC;YAAE,SAAS;QAC3B,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAChE,wEAAwE;QACxE,gCAAgC;QAChC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IACrB,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC;AACjE,CAAC","sourcesContent":["/**\n * Accepted debt, and the ratchet that keeps it from growing.\n *\n * A linter introduced to a repository that predates it reports everything at\n * once. Fifty findings on day one is not a report, it is a decision to be\n * ignored: the team cannot stop to fix them, so they turn the tool off, or they\n * turn the rules off and the next specification rots unwatched.\n *\n * A baseline is the third answer. It records what was already wrong on the day\n * the tool arrived, and reports only what happened since. Debt can be paid down\n * whenever there is room, and in the meantime nothing new gets in.\n *\n * The whole module is pure. Reading and writing the file is the CLI's job, for\n * the same reason extraction never touches a disk.\n */\n\nimport type { SpecGraph } from './graph.js';\nimport { RULE_IDS } from './rules.js';\nimport type { Diagnostic, RuleId } from './types.js';\n\n/** The current file format. Bumped only for a change old files cannot survive. */\nexport const BASELINE_VERSION = 1;\n\n/** One class of accepted finding, and how many of it there were. */\nexport interface BaselineEntry {\n readonly rule: RuleId;\n /** The specification the finding is about, not the file it was found in. */\n readonly document: string;\n /** What within it: a citation target, or the document at the other end. */\n readonly subject: string;\n readonly count: number;\n}\n\nexport interface Baseline {\n readonly version: number;\n readonly findings: readonly BaselineEntry[];\n}\n\nexport const EMPTY_BASELINE: Baseline = Object.freeze({ version: BASELINE_VERSION, findings: [] });\n\n/**\n * What makes two findings the same finding.\n *\n * Not the line. A baseline keyed on line numbers is invalidated by any edit\n * above it, which turns every unrelated pull request into a wall of findings\n * nobody introduced. Not the message either: rewording a diagnostic would\n * silently expire every baseline in the world.\n *\n * What survives is the pair the finding is actually about - which specification,\n * and what within it. Both are ids that outlive a file being renamed, a section\n * being moved into its own file, or an obligation being reordered, because that\n * is exactly what identifiers were made stable for (ADR-0009).\n *\n * The cost is deliberate coarseness: two broken links from one document to the\n * same target are one entry with a count of two. Paying that buys a baseline\n * that does not lie the first time somebody reformats a paragraph.\n */\nexport function fingerprintOf(graph: SpecGraph, diagnostic: Diagnostic): { document: string; subject: string } {\n const first = diagnostic.nodes[0] ?? '';\n const document = graph.owningDocument(first)?.id ?? first;\n if (diagnostic.target !== null) return { document, subject: diagnostic.target };\n\n const second = diagnostic.nodes[1];\n const subject = second === undefined ? '' : (graph.owningDocument(second)?.id ?? second);\n // A document-level rule lists its own items as the rest of `nodes`, so the\n // other end resolves back to where it started. Saying so twice in the file\n // would only invite a reader to look for a distinction that is not there.\n return { document, subject: subject === document ? '' : subject };\n}\n\nfunction keyOf(rule: RuleId, document: string, subject: string): string {\n // Tab-joined: the three parts are ids and targets, and a tab is the one\n // character none of them can contain.\n return `${rule}\\t${document}\\t${subject}`;\n}\n\n/** Counts findings by fingerprint. */\nfunction tally(graph: SpecGraph, diagnostics: readonly Diagnostic[]): Map<string, BaselineEntry> {\n const out = new Map<string, BaselineEntry>();\n for (const diagnostic of diagnostics) {\n const { document, subject } = fingerprintOf(graph, diagnostic);\n const key = keyOf(diagnostic.rule, document, subject);\n const seen = out.get(key);\n out.set(key, {\n rule: diagnostic.rule,\n document,\n subject,\n count: (seen?.count ?? 0) + 1,\n });\n }\n return out;\n}\n\n/**\n * Renders a baseline for the findings given.\n *\n * Sorted by rule, then document, then subject, and written with two-space\n * indentation: the file lands in a repository and is read in diffs, so its byte\n * order has to be a function of its content and nothing else. No timestamp, for\n * the same reason - a generated date makes every re-record a change even when\n * nothing changed.\n */\nexport function formatBaseline(graph: SpecGraph, diagnostics: readonly Diagnostic[]): string {\n const findings = [...tally(graph, diagnostics).values()].sort(compareEntries);\n return `${JSON.stringify({ version: BASELINE_VERSION, findings }, null, 2)}\\n`;\n}\n\nfunction compareEntries(a: BaselineEntry, b: BaselineEntry): number {\n if (a.rule !== b.rule) return a.rule < b.rule ? -1 : 1;\n if (a.document !== b.document) return a.document < b.document ? -1 : 1;\n if (a.subject !== b.subject) return a.subject < b.subject ? -1 : 1;\n return 0;\n}\n\nexport interface ParsedBaseline {\n readonly baseline: Baseline;\n /** Reported, never silently dropped. A baseline nobody can read is worse\n * than none: it suppresses findings the reader cannot account for. */\n readonly problems: readonly string[];\n}\n\n/** Parses a baseline file. Never throws; an unusable file yields an empty one. */\nexport function parseBaseline(raw: string, source: string): ParsedBaseline {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw);\n } catch (error) {\n return { baseline: EMPTY_BASELINE, problems: [`${source} is not valid JSON: ${(error as Error).message}`] };\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { baseline: EMPTY_BASELINE, problems: [`${source} must contain a JSON object`] };\n }\n\n const record = parsed as Record<string, unknown>;\n const problems: string[] = [];\n if (record['version'] !== BASELINE_VERSION) {\n return {\n baseline: EMPTY_BASELINE,\n problems: [`${source} is version ${String(record['version'])}, and this build reads version ${BASELINE_VERSION}`],\n };\n }\n\n const rows = record['findings'];\n if (!Array.isArray(rows)) {\n return { baseline: EMPTY_BASELINE, problems: [`${source}: \"findings\" must be an array`] };\n }\n\n const findings: BaselineEntry[] = [];\n for (const [index, row] of rows.entries()) {\n const entry = readEntry(row, `${source}: findings[${index}]`, problems);\n if (entry !== null) findings.push(entry);\n }\n return { baseline: { version: BASELINE_VERSION, findings }, problems };\n}\n\nfunction readEntry(row: unknown, where: string, problems: string[]): BaselineEntry | null {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) {\n problems.push(`${where} must be an object`);\n return null;\n }\n const fields = row as Record<string, unknown>;\n const rule = fields['rule'];\n if (typeof rule !== 'string' || !RULE_IDS.includes(rule as RuleId)) {\n problems.push(`${where}: unknown rule ${JSON.stringify(rule)}`);\n return null;\n }\n const document = fields['document'];\n const subject = fields['subject'] ?? '';\n const count = fields['count'] ?? 1;\n if (typeof document !== 'string' || typeof subject !== 'string') {\n problems.push(`${where}: \"document\" and \"subject\" must be strings`);\n return null;\n }\n if (typeof count !== 'number' || !Number.isInteger(count) || count < 1) {\n problems.push(`${where}: \"count\" must be a whole number of at least 1`);\n return null;\n }\n return { rule: rule as RuleId, document, subject, count };\n}\n\nexport interface BaselineOutcome {\n /** Findings the baseline does not account for. These are the report. */\n readonly kept: readonly Diagnostic[];\n /** How many were accounted for. Reported as a number, not as a list. */\n readonly suppressed: number;\n /**\n * Entries whose debt has been paid, wholly or partly.\n *\n * The ratchet: once a repository is clean of something, saying so in the file\n * stops it coming back unnoticed.\n */\n readonly stale: readonly BaselineEntry[];\n}\n\n/**\n * Removes the findings a baseline accounts for.\n *\n * Where a baseline allows two of something and three exist, one is reported.\n * Which one is not a meaningful question - they share a fingerprint - so the\n * findings are taken in report order and the surplus is what is left.\n */\nexport function applyBaseline(\n graph: SpecGraph,\n diagnostics: readonly Diagnostic[],\n baseline: Baseline,\n): BaselineOutcome {\n const budget = new Map<string, number>();\n for (const entry of baseline.findings) {\n const key = keyOf(entry.rule, entry.document, entry.subject);\n budget.set(key, (budget.get(key) ?? 0) + entry.count);\n }\n\n const kept: Diagnostic[] = [];\n let suppressed = 0;\n for (const diagnostic of diagnostics) {\n const { document, subject } = fingerprintOf(graph, diagnostic);\n const key = keyOf(diagnostic.rule, document, subject);\n const left = budget.get(key) ?? 0;\n if (left <= 0) {\n kept.push(diagnostic);\n continue;\n }\n budget.set(key, left - 1);\n suppressed += 1;\n }\n\n const stale: BaselineEntry[] = [];\n for (const entry of baseline.findings) {\n const key = keyOf(entry.rule, entry.document, entry.subject);\n const unspent = budget.get(key) ?? 0;\n if (unspent <= 0) continue;\n stale.push({ ...entry, count: Math.min(unspent, entry.count) });\n // An entry counted once; a duplicate key in a hand-edited file must not\n // claim the same surplus twice.\n budget.set(key, 0);\n }\n\n return { kept, suppressed, stale: stale.sort(compareEntries) };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"baseline.js","sourceRoot":"","sources":["../src/baseline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,aAAa,EAAgD,MAAM,YAAY,CAAC;AAEzF,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAiBlC,MAAM,CAAC,MAAM,cAAc,GAAa,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;AAEnG;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,aAAa,CAAC,KAAgB,EAAE,UAAsB;IACpE,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,MAAM,QAAQ,GAAG,KAAK,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,KAAK,CAAC;IAC1D,IAAI,UAAU,CAAC,MAAM,KAAK,IAAI;QAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IAEhF,MAAM,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnC,MAAM,OAAO,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CA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AK,MAAM,KAAK,IAAI,QAAQ,CAAC,QAAQ,EAAE,CAAC;QACtC,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC7D,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACrC,IAAI,OAAO,IAAI,CAAC;YAAE,SAAS;QAC3B,yEAAyE;QACzE,yEAAyE;QACzE,2EAA2E;QAC3E,yEAAyE;QACzE,iDAAiD;QACjD,MAAM,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;QAC9E,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QACxE,wEAAwE;QACxE,gCAAgC;QAChC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IACrB,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC;AACjE,CAAC","sourcesContent":["/**\n * Accepted debt, and the ratchet that keeps it from growing.\n *\n * A linter introduced to a repository that predates it reports everything at\n * once. Fifty findings on day one is not a report, it is a decision to be\n * ignored: the team cannot stop to fix them, so they turn the tool off, or they\n * turn the rules off and the next specification rots unwatched.\n *\n * A baseline is the third answer. It records what was already wrong on the day\n * the tool arrived, and reports only what happened since. Debt can be paid down\n * whenever there is room, and in the meantime nothing new gets in.\n *\n * The whole module is pure. Reading and writing the file is the CLI's job, for\n * the same reason extraction never touches a disk.\n */\n\nimport type { SpecGraph } from './graph.js';\nimport { RULE_IDS } from './rules.js';\nimport { isProjectRule, type AnyRuleId, type Diagnostic, type RuleId } from './types.js';\n\n/** The current file format. Bumped only for a change old files cannot survive. */\nexport const BASELINE_VERSION = 1;\n\n/** One class of accepted finding, and how many of it there were. */\nexport interface BaselineEntry {\n readonly rule: AnyRuleId;\n /** The specification the finding is about, not the file it was found in. */\n readonly document: string;\n /** What within it: a citation target, or the document at the other end. */\n readonly subject: string;\n readonly count: number;\n}\n\nexport interface Baseline {\n readonly version: number;\n readonly findings: readonly BaselineEntry[];\n}\n\nexport const EMPTY_BASELINE: Baseline = Object.freeze({ version: BASELINE_VERSION, findings: [] });\n\n/**\n * What makes two findings the same finding.\n *\n * Not the line. A baseline keyed on line numbers is invalidated by any edit\n * above it, which turns every unrelated pull request into a wall of findings\n * nobody introduced. Not the message either: rewording a diagnostic would\n * silently expire every baseline in the world.\n *\n * What survives is the pair the finding is actually about - which specification,\n * and what within it. Both are ids that outlive a file being renamed, a section\n * being moved into its own file, or an obligation being reordered, because that\n * is exactly what identifiers were made stable for (ADR-0009).\n *\n * The cost is deliberate coarseness: two broken links from one document to the\n * same target are one entry with a count of two. Paying that buys a baseline\n * that does not lie the first time somebody reformats a paragraph.\n */\nexport function fingerprintOf(graph: SpecGraph, diagnostic: Diagnostic): { document: string; subject: string } {\n const first = diagnostic.nodes[0] ?? '';\n const document = graph.owningDocument(first)?.id ?? first;\n if (diagnostic.target !== null) return { document, subject: diagnostic.target };\n\n const second = diagnostic.nodes[1];\n const subject = second === undefined ? '' : (graph.owningDocument(second)?.id ?? second);\n // A document-level rule lists its own items as the rest of `nodes`, so the\n // other end resolves back to where it started. Saying so twice in the file\n // would only invite a reader to look for a distinction that is not there.\n return { document, subject: subject === document ? '' : subject };\n}\n\nfunction keyOf(rule: AnyRuleId, document: string, subject: string): string {\n // Tab-joined: the three parts are ids and targets, and a tab is the one\n // character none of them can contain.\n return `${rule}\\t${document}\\t${subject}`;\n}\n\n/** Counts findings by fingerprint. */\nfunction tally(graph: SpecGraph, diagnostics: readonly Diagnostic[]): Map<string, BaselineEntry> {\n const out = new Map<string, BaselineEntry>();\n for (const diagnostic of diagnostics) {\n const { document, subject } = fingerprintOf(graph, diagnostic);\n const key = keyOf(diagnostic.rule, document, subject);\n const seen = out.get(key);\n out.set(key, {\n rule: diagnostic.rule,\n document,\n subject,\n count: (seen?.count ?? 0) + 1,\n });\n }\n return out;\n}\n\n/**\n * Renders a baseline for the findings given.\n *\n * Sorted by rule, then document, then subject, and written with two-space\n * indentation: the file lands in a repository and is read in diffs, so its byte\n * order has to be a function of its content and nothing else. No timestamp, for\n * the same reason - a generated date makes every re-record a change even when\n * nothing changed.\n */\nexport function formatBaseline(graph: SpecGraph, diagnostics: readonly Diagnostic[]): string {\n const findings = [...tally(graph, diagnostics).values()].sort(compareEntries);\n return `${JSON.stringify({ version: BASELINE_VERSION, findings }, null, 2)}\\n`;\n}\n\nfunction compareEntries(a: BaselineEntry, b: BaselineEntry): number {\n if (a.rule !== b.rule) return a.rule < b.rule ? -1 : 1;\n if (a.document !== b.document) return a.document < b.document ? -1 : 1;\n if (a.subject !== b.subject) return a.subject < b.subject ? -1 : 1;\n return 0;\n}\n\nexport interface ParsedBaseline {\n readonly baseline: Baseline;\n /** Reported, never silently dropped. A baseline nobody can read is worse\n * than none: it suppresses findings the reader cannot account for. */\n readonly problems: readonly string[];\n}\n\n/** Parses a baseline file. Never throws; an unusable file yields an empty one. */\nexport function parseBaseline(raw: string, source: string): ParsedBaseline {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw);\n } catch (error) {\n return { baseline: EMPTY_BASELINE, problems: [`${source} is not valid JSON: ${(error as Error).message}`] };\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { baseline: EMPTY_BASELINE, problems: [`${source} must contain a JSON object`] };\n }\n\n const record = parsed as Record<string, unknown>;\n const problems: string[] = [];\n if (record['version'] !== BASELINE_VERSION) {\n return {\n baseline: EMPTY_BASELINE,\n problems: [`${source} is version ${String(record['version'])}, and this build reads version ${BASELINE_VERSION}`],\n };\n }\n\n const rows = record['findings'];\n if (!Array.isArray(rows)) {\n return { baseline: EMPTY_BASELINE, problems: [`${source}: \"findings\" must be an array`] };\n }\n\n const findings: BaselineEntry[] = [];\n for (const [index, row] of rows.entries()) {\n const entry = readEntry(row, `${source}: findings[${index}]`, problems);\n if (entry !== null) findings.push(entry);\n }\n return { baseline: { version: BASELINE_VERSION, findings }, problems };\n}\n\nfunction readEntry(row: unknown, where: string, problems: string[]): BaselineEntry | null {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) {\n problems.push(`${where} must be an object`);\n return null;\n }\n const fields = row as Record<string, unknown>;\n const rule = fields['rule'];\n // A project rule is accepted on its namespace alone, because the baseline is\n // read before the configuration that defines it has any say - and an entry\n // rejected here would silently un-accept debt a team had already signed off.\n // A name nothing defines suppresses nothing and is reported as stale, which\n // is the same answer by a route that keeps the file readable.\n if (typeof rule !== 'string' || !(RULE_IDS.includes(rule as RuleId) || isProjectRule(rule as AnyRuleId))) {\n problems.push(`${where}: unknown rule ${JSON.stringify(rule)}`);\n return null;\n }\n const document = fields['document'];\n const subject = fields['subject'] ?? '';\n const count = fields['count'] ?? 1;\n if (typeof document !== 'string' || typeof subject !== 'string') {\n problems.push(`${where}: \"document\" and \"subject\" must be strings`);\n return null;\n }\n if (typeof count !== 'number' || !Number.isInteger(count) || count < 1) {\n problems.push(`${where}: \"count\" must be a whole number of at least 1`);\n return null;\n }\n return { rule: rule as AnyRuleId, document, subject, count };\n}\n\n/**\n * An entry the run did not spend, and why.\n *\n * The distinction is the whole value of the label. `paid` is the ratchet\n * working: the defect was fixed and the exemption can be struck. `gone` is not\n * an achievement at all - the document the entry is about was not in this\n * corpus, so nothing whatever is known about the defect. Both make the file\n * stale and both need it re-recorded, but only one of them is good news, and a\n * report that says \"paid\" over a narrowed `patterns` glob is congratulating a\n * team for losing sight of the problem.\n */\nexport interface StaleEntry extends BaselineEntry {\n readonly reason: 'paid' | 'gone';\n}\n\nexport interface BaselineOutcome {\n /** Findings the baseline does not account for. These are the report. */\n readonly kept: readonly Diagnostic[];\n /** How many were accounted for. Reported as a number, not as a list. */\n readonly suppressed: number;\n /**\n * Entries whose debt was not spent, wholly or partly.\n *\n * The ratchet: once a repository is clean of something, saying so in the file\n * stops it coming back unnoticed.\n */\n readonly stale: readonly StaleEntry[];\n}\n\n/**\n * Removes the findings a baseline accounts for.\n *\n * Where a baseline allows two of something and three exist, one is reported.\n * Which one is not a meaningful question - they share a fingerprint - so the\n * findings are taken in report order and the surplus is what is left.\n */\nexport function applyBaseline(\n graph: SpecGraph,\n diagnostics: readonly Diagnostic[],\n baseline: Baseline,\n): BaselineOutcome {\n const budget = new Map<string, number>();\n for (const entry of baseline.findings) {\n const key = keyOf(entry.rule, entry.document, entry.subject);\n budget.set(key, (budget.get(key) ?? 0) + entry.count);\n }\n\n const kept: Diagnostic[] = [];\n let suppressed = 0;\n for (const diagnostic of diagnostics) {\n const { document, subject } = fingerprintOf(graph, diagnostic);\n const key = keyOf(diagnostic.rule, document, subject);\n const left = budget.get(key) ?? 0;\n if (left <= 0) {\n kept.push(diagnostic);\n continue;\n }\n budget.set(key, left - 1);\n suppressed += 1;\n }\n\n const stale: StaleEntry[] = [];\n for (const entry of baseline.findings) {\n const key = keyOf(entry.rule, entry.document, entry.subject);\n const unspent = budget.get(key) ?? 0;\n if (unspent <= 0) continue;\n // Asked of the graph rather than of the filesystem, because the graph is\n // what this run looked at. A document that still exists on disk and fell\n // outside the include patterns is gone for the purposes of the answer, and\n // that is the case worth telling apart - it is the one a team reaches by\n // editing a glob rather than by fixing anything.\n const reason = graph.document(entry.document) === undefined ? 'gone' : 'paid';\n stale.push({ ...entry, count: Math.min(unspent, entry.count), reason });\n // An entry counted once; a duplicate key in a hand-edited file must not\n // claim the same surplus twice.\n budget.set(key, 0);\n }\n\n return { kept, suppressed, stale: stale.sort(compareEntries) };\n}\n"]}
|
package/dist/cli.d.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* itself could not run. A usage mistake never masquerades as a passing build.
|
|
10
10
|
*/
|
|
11
11
|
import { type GraphFormat } from './report.js';
|
|
12
|
-
import type
|
|
12
|
+
import { type AnyRuleId, type Severity } from './types.js';
|
|
13
13
|
export declare const EXIT_OK = 0;
|
|
14
14
|
export declare const EXIT_FAILED = 1;
|
|
15
15
|
export declare const EXIT_ERROR = 2;
|
|
@@ -47,7 +47,7 @@ export interface CliOptions {
|
|
|
47
47
|
readonly noConfig: boolean;
|
|
48
48
|
readonly format: 'human' | 'json' | 'sarif';
|
|
49
49
|
readonly graphFormat: GraphFormat;
|
|
50
|
-
readonly severities: Partial<Record<
|
|
50
|
+
readonly severities: Partial<Record<AnyRuleId, Severity>>;
|
|
51
51
|
readonly color: boolean | null;
|
|
52
52
|
readonly ascii: boolean | null;
|
|
53
53
|
readonly verbose: boolean;
|
|
@@ -68,7 +68,7 @@ export interface CliIO {
|
|
|
68
68
|
readonly env?: Readonly<Record<string, string | undefined>> | undefined;
|
|
69
69
|
readonly isTTY?: boolean | undefined;
|
|
70
70
|
}
|
|
71
|
-
export declare const HELP = "spec-graph - turn Markdown specifications into a verifiable graph\n\nUSAGE\n spec-graph [check] [patterns...] [options]\n spec-graph query <selector> [patterns...] [options]\n spec-graph graph [patterns...] [--graph-format dot|mermaid|json]\n spec-graph rules [--explain]\n\nCOMMANDS\n check Validate the specification graph. The default.\n query Run a selector and print the matching paths.\n graph Export the graph for Graphviz, Mermaid, or another tool.\n rules List the built
|
|
71
|
+
export declare const HELP = "spec-graph - turn Markdown specifications into a verifiable graph\n\nUSAGE\n spec-graph [check] [patterns...] [options]\n spec-graph query <selector> [patterns...] [options]\n spec-graph graph [patterns...] [--graph-format dot|mermaid|json]\n spec-graph rules [--explain]\n\nCOMMANDS\n check Validate the specification graph. The default.\n query Run a selector and print the matching paths.\n graph Export the graph for Graphviz, Mermaid, or another tool.\n rules List the diagnostics that will run, built in and project.\n\nOPTIONS\n --root <dir> Directory the patterns resolve against (default: cwd)\n --ignore <glob> Skip paths. Repeatable.\n --ignore-ref <glob> Do not report these reference targets when they fail\n to resolve, for repositories where [[...]] tags a\n concept rather than naming a file. Repeatable.\n Suppresses findings only, never edges.\n --family <name> Families a bare identifier in prose may name. When\n given, everything else stays prose. Repeatable.\n --ignore-family <name> Families that are never citations - RFC when the repo\n cites RFC 2119 and keeps its own RFCs. Repeatable.\n --history <glob> Files that log what was decided rather than deciding\n it - journals, changelogs, minutes. Their links are\n still checked; their obligations are not. Repeatable.\n --baseline <file> Accept the findings recorded in this file and report\n only what is new since. Missing file = accept nothing.\n --record-baseline <f> Write today's findings to this file as accepted debt,\n and exit 0 without judging them.\n --ratchet Also fail when a baseline entry no longer occurs, so\n a paid-off exemption cannot outlive the defect.\n --no-config Ignore .spec-graph.json and the package.json key.\n --format <fmt> human, json, or sarif - the interchange format\n GitHub code scanning and editors already read\n (default: human)\n --graph-format <fmt> dot, mermaid or json (default: dot)\n --documents-only Leave items out of the exported graph\n --rule <id>=<severity> Override one rule: error, warn, info or off. A project\n rule is named in full: project:no-draft-dependency.\n Repeatable.\n --max <n> Show at most n findings (0 = no limit)\n --max-warnings <n> Fail when warnings exceed n (default: no limit)\n --strict Raise every warning to an error. An explicit --rule\n still wins, so --strict --rule x=warn exempts x.\n --color / --no-color Force colour on or off\n --ascii Use ASCII glyphs only\n --verbose Include parse problems, per-file detail, and every\n reference --ignore-ref or --ignore-family silenced\n -h, --help Show this help\n -v, --version Show the version\n\nSELECTORS\n A selector is a path through the graph.\n\n item[openness=open] -delegates-to-> document[phase=retired]\n document[phase=active] -assumes-> document[phase=retired]\n document =supersedes=> document\n *[path^=docs/adr] -contains-> item[state=accepted-debt]\n\n Node types: document, item, * (any)\n Attributes: id, kind, title, path, file, line, phase, status, receptivity,\n alias, document, state (or disposition), openness, section,\n text, body, evidence, conflicted, fm.<front-matter-key>\n Operators: = != ^= $= *= ~= and [attr] for \"is present\"\n ~= is a JavaScript regular expression, run once per node; ^= $=\n and *= cover most cases and cannot backtrack\n Relations: -kind-> <-kind- =kind=> <=kind= (= forms are transitive)\n\nEXIT CODES\n 0 clean\n 1 findings at error severity (or over --max-warnings)\n 2 the tool could not run\n\nCONFIGURATION\n Anything repeated on every run belongs in the repository rather than in the\n command. spec-graph reads the first of these that exists:\n\n .spec-graph.json, spec-graph.config.json, or a \"spec-graph\" key in\n package.json\n\n { \"patterns\": [\"docs/**/*.md\"],\n \"ignoreReferences\": [\"trap *\"],\n \"ignoreFamilies\": [\"RFC\"],\n \"historyPatterns\": [\"**/JOURNAL_*.md\", \"archive/**\"],\n \"baseline\": \".spec-graph-baseline.json\",\n \"severities\": { \"self-reference\": \"off\" },\n \"strict\": true }\n\n A flag always wins over the file, and list flags add to it rather than\n replacing it.\n\nPROJECT RULES\n A convention spec-graph never anticipated is a selector plus a sentence, and\n belongs in the same file. Every rule declared here runs beside the built-ins\n and is reported, baselined, escalated by --strict and silenced by --rule in\n exactly the same way.\n\n { \"rules\": {\n \"no-draft-dependency\": {\n \"query\": \"document[phase=active] -depends-on-> document[phase=draft]\",\n \"message\": \"{0} depends on {1}, which is still a draft\",\n \"hint\": \"wait for {1} to be accepted, or drop it from {0.path}\",\n \"severity\": \"error\" } } }\n\n query One selector, or a list of them read as a union.\n message The headline. {0} is the first node on the path, {1} the next;\n {1.phase} and {0.fm.owner} read any selector attribute.\n hint The next action. Optional, and templated the same way.\n severity error, warn, info or off. Defaults to warn - a rule a team has\n just written has not yet earned the right to fail their build.\n\n The id is the name with project: in front, which is why it can never collide\n with a built-in. A selector that does not parse, or a {2} the query can never\n reach, is reported when the file is read rather than found missing later.\n\nADOPTING THIS ON AN OLD REPOSITORY\n Record what is already wrong, then report only what happens next:\n\n spec-graph check --record-baseline .spec-graph-baseline.json\n git add .spec-graph-baseline.json\n\n The file is keyed by specification and citation, not by line number, so it\n survives edits, moves and renames. Findings that stop occurring are reported\n so the file can be tightened; nothing new gets in.\n\nEXAMPLES\n spec-graph \"docs/**/*.md\"\n spec-graph check --rule self-reference=off --format json\n spec-graph query 'item[openness=open] -delegates-to-> document[phase=retired]'\n spec-graph check --ignore-ref \"trap *\" # [[trap 55]] tags a concept, not a file\n spec-graph graph --documents-only --graph-format mermaid > graph.mmd\n spec-graph check --history \"**/JOURNAL_*.md\" # a log is not a specification\n spec-graph check --baseline .spec-graph-baseline.json\n spec-graph rules --explain # including this repository's own\n spec-graph check --rule project:no-draft-dependency=off\n";
|
|
72
72
|
/** Parses argv into options. Throws {@link UsageError} on anything malformed. */
|
|
73
73
|
export declare function parseArgs(argv: readonly string[], cwd: string): CliOptions;
|
|
74
74
|
/** Runs the CLI and returns the process exit code. Never throws. */
|