@hailstails/hone 0.1.0-pre.3 → 0.1.0-pre.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/ADOPTING.md +44 -19
  2. package/MIGRATING.md +5 -5
  3. package/README.md +89 -24
  4. package/api/audit.d.ts +11 -0
  5. package/api/audit.mjs +1 -0
  6. package/api/rule-set.d.ts +4 -0
  7. package/api/rule-set.mjs +1 -0
  8. package/chunks/chunk-3HFJHJDO.js +53 -0
  9. package/chunks/chunk-7OVV6NEU.js +22 -0
  10. package/chunks/chunk-7PVPPH4C.js +13 -0
  11. package/chunks/chunk-HVABJ7T4.js +361 -0
  12. package/chunks/{chunk-TRCB27ET.js → chunk-IIMK5BCL.js} +55 -14
  13. package/chunks/{chunk-7ZJZZBSS.js → chunk-SWPCKTJV.js} +87 -380
  14. package/chunks/{chunk-HBY4ZWSP.js → chunk-VUG3DJHN.js} +7 -13
  15. package/chunks/{chunk-233U4FBA.js → chunk-YBWVUDIG.js} +1 -1
  16. package/core/check/tool-command.js +422 -115
  17. package/core/mechanism-port/piece-failure-types.d.ts +14 -0
  18. package/core/mechanism-port/runner-module-types.d.ts +13 -0
  19. package/core/mechanism-port/runner-result-types.d.ts +9 -0
  20. package/core/rule-set-reader/authored-rule-set-types.d.ts +48 -0
  21. package/core/values/anchor.d.ts +10 -0
  22. package/core/values/branded.d.ts +5 -0
  23. package/core/values/clause-address-types.d.ts +9 -0
  24. package/core/values/identifier-types.d.ts +5 -0
  25. package/core/values/json-value.d.ts +6 -0
  26. package/core/values/repo-path-types.d.ts +2 -0
  27. package/core/values/result.d.ts +7 -0
  28. package/docs/adding-a-discipline-or-mechanism.md +8 -5
  29. package/docs/extending.md +357 -0
  30. package/mechanisms/audit/CD-1/any-cast.js +9 -37
  31. package/mechanisms/audit/CD-19/import-boundaries.js +82 -63
  32. package/mechanisms/audit/CD-19/piece.json +5 -0
  33. package/mechanisms/audit/CD-2/cast-expressions.js +14 -37
  34. package/mechanisms/audit/CD-5/comments-directives.js +137 -55
  35. package/mechanisms/audit/CD-5/piece.json +7 -0
  36. package/mechanisms/audit/runner/README.md +1 -0
  37. package/mechanisms/audit/runner/runner.js +39 -33
  38. package/mechanisms/audit/runner/typescript-parse.d.ts +26 -0
  39. package/mechanisms/audit/runner/walker-piece.d.ts +60 -0
  40. package/mechanisms/eslint/runner/README.md +1 -1
  41. package/mechanisms/eslint/runner/eslint-piece-settings-types.d.ts +8 -0
  42. package/mechanisms/eslint/runner/runner.js +137 -71
  43. package/package.json +20 -3
  44. package/rules/CD-1/README.md +5 -5
  45. package/rules/CD-1/discipline.json +16 -6
  46. package/rules/CD-19/README.md +13 -3
  47. package/rules/CD-19/discipline.json +6 -8
  48. package/rules/CD-2/README.md +8 -4
  49. package/rules/CD-2/discipline.json +25 -7
  50. package/rules/CD-5/README.md +17 -5
  51. package/rules/CD-5/discipline.json +66 -0
@@ -0,0 +1,14 @@
1
+ import type { RepoPath } from "../values/repo-path-types.js";
2
+ export type PieceFailure = {
3
+ readonly kind: "piece-invalid";
4
+ readonly pieceRoot: string;
5
+ readonly detail: string;
6
+ } | {
7
+ readonly kind: "file-unreadable";
8
+ readonly file: RepoPath;
9
+ readonly detail: string;
10
+ } | {
11
+ readonly kind: "file-unparseable";
12
+ readonly file: RepoPath;
13
+ readonly detail: string;
14
+ };
@@ -0,0 +1,13 @@
1
+ import type { AnchorKind } from "../values/anchor.js";
2
+ import type { ClauseAddress } from "../values/clause-address-types.js";
3
+ import type { ReadonlyJsonValue } from "../values/json-value.js";
4
+ export type ClauseSettingValues = {
5
+ readonly [key: string]: ReadonlyJsonValue;
6
+ };
7
+ export type RunnerClause = {
8
+ readonly address: ClauseAddress;
9
+ readonly anchor: AnchorKind;
10
+ readonly pieceRoot: string;
11
+ readonly settings: unknown;
12
+ readonly clauseSettings: ClauseSettingValues;
13
+ };
@@ -0,0 +1,9 @@
1
+ import type { Anchor } from "../values/anchor.js";
2
+ import type { ClauseAddress } from "../values/clause-address-types.js";
3
+ import type { RepoPath } from "../values/repo-path-types.js";
4
+ export type Hit = {
5
+ readonly clause: ClauseAddress;
6
+ readonly file: RepoPath;
7
+ readonly anchor: Anchor;
8
+ readonly snippet: string;
9
+ };
@@ -0,0 +1,48 @@
1
+ import type { AnchorKind } from "../values/anchor.js";
2
+ import type { ReadonlyJsonValue } from "../values/json-value.js";
3
+ export type ClauseExceptions = "allowed" | "refused";
4
+ export type AuthoredSourceCase = {
5
+ readonly name: string;
6
+ readonly fileName: string;
7
+ readonly source: string;
8
+ readonly expectedLines: readonly number[];
9
+ };
10
+ export type AuthoredClauseDefinition = {
11
+ readonly kind: "mechanical";
12
+ readonly id: string;
13
+ readonly summary: string;
14
+ readonly mechanisms: readonly string[];
15
+ readonly anchor: AnchorKind;
16
+ readonly exceptions?: ClauseExceptions;
17
+ readonly cases: {
18
+ readonly flag: readonly AuthoredSourceCase[];
19
+ readonly allow: readonly AuthoredSourceCase[];
20
+ };
21
+ } | {
22
+ readonly kind: "judgement";
23
+ readonly id: string;
24
+ readonly summary: string;
25
+ readonly enforcedBy: "review";
26
+ };
27
+ export type AuthoredDisciplineFile = {
28
+ readonly version: 1;
29
+ readonly id: string;
30
+ readonly clauses: readonly AuthoredClauseDefinition[];
31
+ };
32
+ export type ClauseSettingDeclaration = {
33
+ readonly default: ReadonlyJsonValue;
34
+ readonly choices?: readonly ReadonlyJsonValue[];
35
+ };
36
+ export type ClauseSettingDeclarations = {
37
+ readonly [key: string]: ClauseSettingDeclaration;
38
+ };
39
+ export type AuthoredPieceFile = {
40
+ readonly version: 1;
41
+ readonly discipline: string;
42
+ readonly mechanism: string;
43
+ readonly clauses: readonly {
44
+ readonly clause: string;
45
+ readonly settings: unknown;
46
+ readonly clauseSettings?: ClauseSettingDeclarations;
47
+ }[];
48
+ };
@@ -0,0 +1,10 @@
1
+ export type AnchorKind = {
2
+ readonly kind: "keyword";
3
+ readonly keyword: string;
4
+ } | {
5
+ readonly kind: "file";
6
+ };
7
+ export type Anchor = {
8
+ readonly line: number;
9
+ readonly column: number;
10
+ };
@@ -0,0 +1,5 @@
1
+ declare const brandName: unique symbol;
2
+ export type Branded<Base, Name extends string> = Base & {
3
+ readonly [brandName]: Name;
4
+ };
5
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { ClauseId, DisciplineId, RuleSetName } from "./identifier-types.js";
2
+ export type ToolRuleSet = "hone";
3
+ export type ClauseAddress = {
4
+ readonly ruleSet: ToolRuleSet | {
5
+ readonly name: RuleSetName;
6
+ };
7
+ readonly discipline: DisciplineId;
8
+ readonly clause: ClauseId;
9
+ };
@@ -0,0 +1,5 @@
1
+ import type { Branded } from "./branded.js";
2
+ export type RuleSetName = Branded<string, "RuleSetName">;
3
+ export type DisciplineId = Branded<string, "DisciplineId">;
4
+ export type ClauseId = Branded<string, "ClauseId">;
5
+ export type MechanismId = Branded<string, "MechanismId">;
@@ -0,0 +1,6 @@
1
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export type ReadonlyJsonValue = string | number | boolean | null | readonly ReadonlyJsonValue[] | {
5
+ readonly [key: string]: ReadonlyJsonValue;
6
+ };
@@ -0,0 +1,2 @@
1
+ import type { Branded } from "./branded.js";
2
+ export type RepoPath = Branded<string, "RepoPath">;
@@ -0,0 +1,7 @@
1
+ export type Result<T, E> = {
2
+ readonly outcome: "ok";
3
+ readonly value: T;
4
+ } | {
5
+ readonly outcome: "failed";
6
+ readonly error: E;
7
+ };
@@ -7,7 +7,7 @@ Terms used below:
7
7
  - A **discipline** is a rule a repository can adopt, with an id such as `CD-14`, made of one or more **clauses**.
8
8
  - A **mechanism** is a tool that checks clauses, such as the TypeScript `audit` or `eslint`. Each mechanism has one **runner**.
9
9
  - A **piece** is one discipline's code for one mechanism, written in that mechanism's own extension format.
10
- - A **rule set** is a directory holding `rules/` and `mechanisms/` folders. The rule set shipped with core is `shared`; a repository can add its own and name them in `disciplines.json`.
10
+ - A **rule set** is a directory holding `rules/` and `mechanisms/` folders. The rule set shipped with the tool is `hone`, which a bare address also names, so no rule-set name may be `hone` or start with `hone-`, and no declared name may be another declared name plus `-<suffix>`; a repository can add its own and name them in `disciplines.json`.
11
11
  - A **native channel** is a way the tool itself lets a team exempt or weaken a rule, outside core's exception records.
12
12
 
13
13
  ## Adding a discipline
@@ -53,7 +53,9 @@ For each mechanism in a clause's `mechanisms` list, add a piece folder `mechanis
53
53
  `discipline` and `mechanism` must match the folder names, every `clause` must exist in the discipline, and no clause may appear twice. Core reads only this envelope. `settings` belongs to the runner, which parses it with its own schema:
54
54
 
55
55
  - **audit:** `{ "module": "<file>.ts" }`, a path inside the piece folder; a `.js` module is accepted too, which is what the built package's pieces name. The module exports `check`, typed with `import type { WalkerPiece }` from `mechanisms/audit/runner/walker-piece.ts`. See `mechanisms/audit/runner/README.md`.
56
- - **eslint:** `{ "pluginNamespace", "pluginModule", "rule" }`. `pluginModule` is a `.ts` or `.js` path inside the piece folder whose default export is an ESLint plugin; `rule` must be a key of its `rules`. The rule id is `<pluginNamespace>/<rule>`. The namespace `hone-core` is reserved for Hone's own machinery, and two selected clauses may not share a rule id, or a namespace with different plugin modules. CD-14's piece is `mechanisms/eslint/CD-14/piece.json`, pointing at the rule `no-class-authoring` in `cd14/cd14.eslint-plugin.ts` under the namespace `hone`.
56
+ - **eslint:** `{ "pluginNamespace", "pluginModule", "rule" }`. `pluginModule` is a `.ts` or `.js` path inside the piece folder whose default export is an ESLint plugin; `rule` must be a key of its `rules`. The rule id is `<pluginNamespace>/<rule>`. The namespace `hone-core` is reserved for Hone's own machinery. The namespaces `hone` and `hone-*` belong to Hone's own rule set. A team rule set's pieces must use its rule-set name or `<ruleSet>-<name>`. Two selected clauses may not share a rule id, or a namespace with different plugin modules. CD-14's piece is `mechanisms/eslint/CD-14/piece.json`, pointing at the rule `no-class-authoring` in `cd14/cd14.eslint-plugin.ts` under the namespace `hone`.
57
+
58
+ A clause entry may also declare the settings a repository may tune, beside `settings`: `"clauseSettings": { "<key>": { "default": <JSON>, "choices": [<JSON>, ...] } }`. `choices` is optional; when given, every choice is the default's JSON kind and the default is one of them. Core reads these declarations itself, checks a repository's values from its `disciplines.json` against them when the check loads, and hands the piece the settled values, defaults included, as `clauseSettings` on each clause, typed `ClauseSettingValues`, apart from the mechanism's own `settings`. The `audit` and `rule-set` type entries carry no code, so a team's piece checks the shape of its `clauseSettings` itself, for example with its own schema, and returns `piece-invalid` when they do not match. No eslint piece declares `clauseSettings` yet, so a repository's settings for an eslint clause are refused when the check loads.
57
59
 
58
60
  A runner reports a bad `settings` value, a module that fails to load or does not match its schema, or a missing rule as `piece-invalid`.
59
61
 
@@ -152,6 +154,7 @@ An embedded runner has the same `run` and `conform` as a standalone one, plus:
152
154
 
153
155
  - `projectedKinds`: the native exception kinds its own projection writes. Only these kinds can be matched by a record.
154
156
  - `run` also receives the repository's exception records for that mechanism, so it can regenerate the projection and compare it. It returns hits, the native exceptions it found, and the projection's state: `current`, `out-of-date`, `missing` or `not-included`. A projection that is missing or not included means the mechanism did not run: core lists `mechanism-not-run` and the check fails. An out-of-date one is a projection problem and also fails.
157
+ - `run` also receives `projectedClauses`: every selected clause of the mechanism, while `clauses` holds only the clauses to run. The two differ only when `waivedClauses` is `not-run` and a waived clause shares its mechanism with a clause still to run. Judge the projection, its effect and every native exception against `projectedClauses`; run, and report hits for, `clauses` only. Core refuses a hit on a clause outside `clauses`, and a native exception on a clause outside `projectedClauses`, as `runner-invalid-output`. The ESLint runner registers every projected plugin and watches every projected rule for inline comments, but switches on only the rules in `clauses`, so ESLint never creates a waived rule.
155
158
  - `project`: writes the projection file and returns its path with `written` or `unchanged`. `hone project` calls it.
156
159
 
157
160
  Core passes every record for the mechanism to both calls, forfeited or not, and never passes the touched set. A forfeited file carve-out therefore stays in the projection and still matches its native exception; core's check reports it as `forfeited` and fails the run. Keep it that way: a runner must not compute forfeiture or read the touched set itself, so that whether a forfeited carve-out stays pushed down remains core's decision. No test checks this; it is a rule for review.
@@ -180,16 +183,16 @@ How the runner finds each channel (`mechanisms/eslint/runner/`):
180
183
  - `suppression-entry` comes from `suppressions-scanner.ts`. Keys in a tracked `eslint-suppressions.json` are read relative to its folder; keys in a file named by `--suppressions-location` are read relative to the `package.json` that names it.
181
184
  - `command-line-option` comes from `package-script-scanner.ts`, which parses every tracked `package.json` and splits each script into commands. A command is an ESLint invocation when a token is `eslint`, starts `eslint@`, or ends `/eslint` or `/eslint.js`. A script with an unterminated quote is `tool-failed`.
182
185
 
183
- Hits come from a separate governance instance that uses only the runner's configuration: the selected rules and the inline-config rule at `"error"` on `**/*.{ts,tsx,mts,cts}`, parsed with `@typescript-eslint/parser`, with the team's configuration file, ignores, suppressions and inline configuration all off. No native channel can change core's findings.
186
+ Hits come from a separate governance instance that uses only the runner's configuration: the rules of the clauses to run and the inline-config rule at `"error"` on `**/*.{ts,tsx,mts,cts}`, with every selected plugin registered and every selected rule watched by the inline-config rule, parsed with `@typescript-eslint/parser`, with the team's configuration file, ignores, suppressions and inline configuration all off. No native channel can change core's findings.
184
187
 
185
188
  Options passed outside a `package.json` script (a CI step, an editor setting, a wrapper script) are not found. They cannot change core's verdict, but core cannot check whether such a run honours the records.
186
189
 
187
190
  ### The ESLint projection
188
191
 
189
- `projection.ts` writes `disciplines.eslint.mjs` at the repository root. It imports each piece's plugin module by a path relative to the repository root, then exports, in order: one block per plugin namespace enabling its selected rules at `"error"` on `**/*.{ts,tsx,mts,cts}`; one block per authorised location or file carve-out turning those rules `"off"` for that file (the path escaped as a glob); and one block per clause-wide carve-out turning them `"off"` everywhere. Block names start with `reservedNamespace` (currently `hone-core/`). The output is sorted, so the same selection and records always produce the same text.
192
+ `projection.ts` writes `disciplines.eslint.mjs` at the repository root. It imports each piece's plugin module by a path relative to the repository root, then exports, in order: one block per plugin namespace enabling its selected rules at `"error"` on `**/*.{ts,tsx,mts,cts}`; one block per distinct set of clauses that authorised locations and file carve-outs except files from, listing those files (each path escaped as a glob) and turning the set's rules `"off"` for them, so the block count follows the clause combinations in use rather than the number of records; and one block per clause-wide carve-out turning them `"off"` everywhere. Block names start with `reservedNamespace` (currently `hone-core/`). The output is sorted, so the same selection and records always produce the same text.
190
193
 
191
194
  The team spreads its default export last in its flat config; the projection is the only supported way to adopt the rules. On each check the runner first compares the file with what it would write now (`missing`, or `out-of-date` if it differs). It then checks the projection's effect through the query instance, in two directions. Every selected rule must be set, at any severity, on at least one checked file that is not ignored, when there is one. Every record whose file is checked must leave its rules at severity `0` on that file, or on every checked file for a clause-wide carve-out. If either fails, the result is `not-included` with no hits. The second direction catches a team that enables a rule another way, for example through a piece's own fragment such as `mechanisms/eslint/CD-14/cd14.eslint.ts`, without importing the projection.
192
195
 
193
196
  ### Runtime
194
197
 
195
- The ESLint mechanism runs on the repository's own toolchain, declared as optional peers: `eslint` `^9.12.0 || ^10.0.0`, and `@typescript-eslint/parser` and `@typescript-eslint/eslint-plugin` `^8.56.0` (the latter for the pieces that reuse its rules). TypeScript is the parser's peer and the audit mechanism's, at `>=4.8.4 <7.0.0`. `@eslint/plugin-kit` is core's own dependency, imported directly because a transitive copy does not resolve under strict package managers. The development pins are `eslint` 10.11.0 and, as `eslint-9`, 9.39.5, with typescript-eslint 8.71.2, and each range's floor under a `-floor` alias; the integration suite runs on all four lines, against the consumer repositories in `mechanisms/eslint/runner/test-fixtures/`.
198
+ The ESLint mechanism runs on the repository's own toolchain, declared as optional peers: `eslint` `^9.28.0 || ^10.0.0`, and `@typescript-eslint/parser` and `@typescript-eslint/eslint-plugin` `^8.56.0` (the latter for the pieces that reuse its rules). TypeScript is the parser's peer and the audit mechanism's, at `>=4.8.4 <7.0.0`. `@eslint/plugin-kit` is core's own dependency, imported directly because a transitive copy does not resolve under strict package managers. The development pins are `eslint` 10.11.0 and, as `eslint-9`, 9.39.5, with typescript-eslint 8.71.2, and each range's floor under a `-floor` alias; the integration suite runs on all four lines, against the consumer repositories in `mechanisms/eslint/runner/test-fixtures/`.
@@ -0,0 +1,357 @@
1
+ # Extending Hone with your own rule set
2
+
3
+ A team can add its own disciplines beside the ones Hone ships, without forking Hone. They live in the team's repository as a **rule set**: a folder of discipline files and the pieces that check them. `hone check` loads them from the repository, runs them, reports them and applies exceptions to them the same way as Hone's own; the differences are listed under [What is stable](#what-is-stable).
4
+
5
+ This guide follows one tested example. `install-proof` installs the packed package into a small repository, stored in Hone's source repository under `tests/test-fixtures/consumer-proof/team/`, type-checks its rule set and runs `hone project` and `hone check` against it. Its rule set is `acme`, with two disciplines: `ACME-1` checked by ESLint and `ACME-2` checked by the audit mechanism. Every file sample below is a file of that repository, apart from the rule pages, the per-package ESLint config, the settings samples and the exception record, which are described rather than tested there.
6
+
7
+ Read [ADOPTING.md](../ADOPTING.md) first: this guide assumes Hone is installed and `disciplines.json` exists.
8
+
9
+ ## Which mechanism
10
+
11
+ - **ESLint** for anything about code syntax. The piece is an ordinary ESLint plugin, typed with ESLint's own types, and the team's editor and lint run report it too.
12
+ - **Audit** for what ESLint cannot see: which files exist, file names, and files that are not TypeScript. An audit piece is offered every tracked file in the repository, Markdown and JSON included.
13
+
14
+ ## Where the files go
15
+
16
+ ```text
17
+ disciplines.json
18
+ eslint.config.mjs
19
+ disciplines.eslint.mjs
20
+ tools/disciplines/acme/
21
+ package.json
22
+ tsconfig.pieces.json
23
+ rules/ACME-1/discipline.json
24
+ rules/ACME-1/README.md
25
+ rules/ACME-2/discipline.json
26
+ rules/ACME-2/README.md
27
+ mechanisms/eslint/ACME-1/piece.json
28
+ mechanisms/eslint/ACME-1/acme.eslint-plugin.ts
29
+ mechanisms/eslint/ACME-1/piece-settings.ts
30
+ mechanisms/audit/ACME-2/piece.json
31
+ mechanisms/audit/ACME-2/scratch-files.ts
32
+ ```
33
+
34
+ The rule set may sit anywhere inside the repository. Hone reads `rules/<ID>/discipline.json` and `mechanisms/<mechanism>/<ID>/piece.json` under it, and loads the modules the pieces name. Everything else in the folder is yours.
35
+
36
+ ## Declare the rule set
37
+
38
+ Name the folder in `disciplines.json` under `ruleSets`, then select its clauses with the rule set's name in front:
39
+
40
+ ```json
41
+ {
42
+ "version": 1,
43
+ "ruleSets": { "acme": "tools/disciplines/acme" },
44
+ "clauses": {
45
+ "acme/ACME-1#console-calls": "eslint",
46
+ "acme/ACME-2#scratch-files": "audit"
47
+ }
48
+ }
49
+ ```
50
+
51
+ - The path is relative to the repository root and must stay inside it.
52
+ - `hone` is Hone's own rule set, and its clauses can be selected beside the team's. `hone/CD-15#loops` and `CD-15#loops` are the same clause, and the report prints the short form.
53
+ - A rule set may not be called `hone` or start with `hone-`, and no declared name may be another declared name plus `-<suffix>`.
54
+ - Discipline IDs only need to be unique inside one rule set: `acme/CD-1` and `CD-1` can both exist.
55
+
56
+ The report names team clauses with their rule set:
57
+
58
+ ```text
59
+ findings (2)
60
+ acme/ACME-1#console-calls eslint src/start-banner.ts:1:0 console.log("web started");
61
+ acme/ACME-2#scratch-files audit notes.scratch.md:1:0 notes.scratch.md
62
+ verdict: fail
63
+ ```
64
+
65
+ ## Write the discipline
66
+
67
+ `rules/ACME-1/discipline.json`:
68
+
69
+ ```json
70
+ {
71
+ "version": 1,
72
+ "id": "ACME-1",
73
+ "clauses": [
74
+ {
75
+ "kind": "mechanical",
76
+ "id": "console-calls",
77
+ "summary": "no direct console output in source",
78
+ "mechanisms": ["eslint"],
79
+ "anchor": { "kind": "keyword", "keyword": "console" },
80
+ "cases": {
81
+ "flag": [
82
+ { "name": "console.log", "fileName": "src/a.ts", "source": "console.log(1);\n", "expectedLines": [1] }
83
+ ],
84
+ "allow": [
85
+ { "name": "no console", "fileName": "src/b.ts", "source": "export const b = 1;\n", "expectedLines": [] }
86
+ ]
87
+ }
88
+ }
89
+ ]
90
+ }
91
+ ```
92
+
93
+ - `id` matches the folder name. IDs are two to four capital letters, a dash and a number, with an optional lower-case letter after it.
94
+ - Each clause lists the mechanisms that can check it. Selecting one clause adopts the whole discipline, so its other mechanical clauses must be selected too.
95
+ - `anchor` is `{ "kind": "keyword", "keyword": "..." }` or `{ "kind": "file" }`.
96
+ - `cases` say what the clause must flag and what it must leave alone. They are the clause's contract. `hone check` does not run them against a team's pieces today, and will: see [What is stable](#what-is-stable).
97
+ - A clause with `"kind": "judgement"`, a `summary` and `"enforcedBy": "review"` is applied in review and cannot be selected.
98
+ - `"exceptions": "refused"` on a clause stops any exception record from exempting it.
99
+
100
+ `rules/ACME-1/README.md` is the rule's page: why the rule exists, one example that honours it and one that breaks it. Write it for the people and agents who apply the rule, not about how the check matches. It is optional today and will be required.
101
+
102
+ ## An ESLint piece
103
+
104
+ `mechanisms/eslint/ACME-1/piece.json`:
105
+
106
+ ```json
107
+ {
108
+ "version": 1,
109
+ "discipline": "ACME-1",
110
+ "mechanism": "eslint",
111
+ "clauses": [
112
+ {
113
+ "clause": "console-calls",
114
+ "settings": { "pluginNamespace": "acme", "pluginModule": "acme.eslint-plugin.ts", "rule": "no-console-calls" }
115
+ }
116
+ ]
117
+ }
118
+ ```
119
+
120
+ `mechanisms/eslint/ACME-1/acme.eslint-plugin.ts`:
121
+
122
+ ```ts
123
+ import type { ESLint, Rule } from "eslint";
124
+
125
+ export const noConsoleCalls: Rule.RuleModule = {
126
+ meta: {
127
+ type: "problem",
128
+ schema: [],
129
+ messages: { console: "Write through the logger port, not console." },
130
+ },
131
+ create: (context) => ({
132
+ "MemberExpression[object.name='console']": (node: Rule.Node) => {
133
+ context.report({ node, messageId: "console" });
134
+ },
135
+ }),
136
+ };
137
+
138
+ const plugin: ESLint.Plugin = { rules: { "no-console-calls": noConsoleCalls } };
139
+
140
+ export default plugin;
141
+ ```
142
+
143
+ - `pluginModule` is a path inside the piece folder. Its default export is the plugin, and `rule` is a key of its `rules`.
144
+ - `pluginNamespace` must be the rule set's name or start with it and a dash: `acme` or `acme-console`. `hone`, `hone-*` and `hone-core` belong to Hone.
145
+ - `options`, optional, is the rule's options array, passed to ESLint as written.
146
+
147
+ Then run `hone project`. It writes `disciplines.eslint.mjs`, which imports the plugin by a path relative to the repository root:
148
+
149
+ ```js
150
+ import piece0 from "./tools/disciplines/acme/mechanisms/eslint/ACME-1/acme.eslint-plugin.ts";
151
+
152
+ export default [
153
+ {
154
+ name: "hone-core/piece/acme",
155
+ files: ["**/*.{ts,tsx,mts,cts}"],
156
+ plugins: { "acme": piece0 },
157
+ rules: { "acme/no-console-calls": "error" },
158
+ },
159
+ ];
160
+ ```
161
+
162
+ Every `eslint.config.*` that applies to checked files spreads the projection last. The example's `eslint.config.mjs`:
163
+
164
+ ```js
165
+ import projection from "./disciplines.eslint.mjs";
166
+
167
+ export default [
168
+ { files: ["**/*.{ts,tsx,mts,cts}"] },
169
+ ...projection,
170
+ ];
171
+ ```
172
+
173
+ In a monorepo each package's own config does the same, importing the projection by its relative path, such as `../../disciplines.eslint.mjs`. A package config that leaves the projection out fails the check, listing each of its files under `unrecorded` as `acme/ACME-1#console-calls eslint config-override <file>`. [ADOPTING.md](../ADOPTING.md#4a-set-up-eslint-for-eslint-clauses) step 4a says which config ESLint applies to a file and how to state it in `disciplines.json` when detection cannot tell.
174
+
175
+ ## An audit piece
176
+
177
+ `mechanisms/audit/ACME-2/piece.json`:
178
+
179
+ ```json
180
+ {
181
+ "version": 1,
182
+ "discipline": "ACME-2",
183
+ "mechanism": "audit",
184
+ "clauses": [
185
+ {
186
+ "clause": "scratch-files",
187
+ "settings": { "module": "scratch-files.ts" }
188
+ }
189
+ ]
190
+ }
191
+ ```
192
+
193
+ `mechanisms/audit/ACME-2/scratch-files.ts`:
194
+
195
+ ```ts
196
+ import type { PieceHit, RunnerClause, WalkerPiece } from "@hailstails/hone/audit";
197
+
198
+ const SCRATCH_MARKER = ".scratch.";
199
+
200
+ const scratchHits = (request: { readonly clauses: readonly RunnerClause[]; readonly file: string }): readonly PieceHit[] =>
201
+ request.file.includes(SCRATCH_MARKER)
202
+ ? request.clauses.map((clause) => ({ clause: clause.address, anchor: { line: 1, column: 0 }, snippet: request.file }))
203
+ : [];
204
+
205
+ export const check: WalkerPiece = {
206
+ prepare: ({ clauses }) => ({
207
+ outcome: "ok",
208
+ value: {
209
+ prepareFile: ({ file }) => ({ outcome: "ok", value: { kind: "complete", hits: scratchHits({ clauses, file }) } }),
210
+ finish: () => ({ outcome: "ok", value: [] }),
211
+ },
212
+ }),
213
+ };
214
+ ```
215
+
216
+ - `module` is a path inside the piece folder, and the module exports `check`.
217
+ - `prepare` runs once with the selected clauses, the repository's file list and TypeScript's syntax API. `prepareFile` runs once per tracked file and returns `skipped`, `complete` with its hits, or `syntax` with observers that walk the file's syntax tree. `finish` returns hits that need the whole repository.
218
+ - A hit passes back the clause's `address` unchanged, a 1-based line and 0-based column, and a short snippet.
219
+ - When the piece cannot run, for example on settings it does not accept, return a failed result whose error is a `PieceFailure`: `kind` `piece-invalid`, the clause's `pieceRoot` and a `detail`. `hone check` then stops with a load failure naming the piece folder.
220
+
221
+ ### Settings a repository can change
222
+
223
+ The example's marker is fixed. To let a repository change it, a clause entry in `piece.json` declares `clauseSettings`: each key with its `default`, and optionally `choices`, a list of the values allowed. For a `marker` setting with default `".scratch."`, the clause entry would read:
224
+
225
+ ```json
226
+ {
227
+ "clause": "scratch-files",
228
+ "settings": { "module": "scratch-files.ts" },
229
+ "clauseSettings": { "marker": { "default": ".scratch." } }
230
+ }
231
+ ```
232
+
233
+ A repository that selects the clause can then override it in `disciplines.json`, keyed by the clause's address:
234
+
235
+ ```json
236
+ "clauseSettings": {
237
+ "acme/ACME-2#scratch-files": { "marker": ".scratch.md" }
238
+ }
239
+ ```
240
+
241
+ Hone refuses a value under an undeclared key, of another JSON kind than the default, or outside the `choices`, before any piece runs. The piece reads the value, the override or else the default, from `clause.clauseSettings` on each `RunnerClause`, in place of the fixed `SCRATCH_MARKER`. The value is typed as any JSON value, so the piece narrows it, for example with `typeof marker === "string"`, and returns a `piece-invalid` failure when it is not what it accepts. Name the settings on the discipline's page under a Settings heading. This section is described, not run by the example: Hone's unit tests cover reading, refusing and overriding settings.
242
+
243
+ ## TypeScript pieces under Node
244
+
245
+ Hone loads piece modules with Node, which strips the types from a `.ts` file as it loads it. Node 22.18 or later does this without flags.
246
+
247
+ - A piece module ends in `.ts` or `.js`. `.mts` and `.mjs` are refused.
248
+ - Node decides whether a `.ts` file is an ES module from the nearest `package.json`:
249
+ - `"type": "module"`: it loads, silently.
250
+ - No `"type"` field: it still loads, because Node sees the `export` syntax, but every run prints a `[MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///… is not specified` block per piece module before the report.
251
+ - `"type": "commonjs"`: it fails to load, with the `Failed to load the ES module` warning and load failure shown under [Common refusals](#common-refusals).
252
+
253
+ The example repository says `"type": "commonjs"` at its root, the hard case, so its rule set has its own `package.json`:
254
+
255
+ ```json
256
+ {
257
+ "private": true,
258
+ "type": "module"
259
+ }
260
+ ```
261
+
262
+ These three behaviours were checked by hand on Node 22.22.2; `install-proof` checks the first on every Node it runs.
263
+ - Use only syntax Node can erase, spell the `.ts` extension in relative imports, and use `import type` for types. [ADOPTING.md](../ADOPTING.md#1-check-the-prerequisites) step 1 lists the limits.
264
+ - Node does not strip types under `node_modules`. A rule set kept in an installed package is named by its repository path, for example `"acme": "node_modules/@acme/disciplines"`, and must ship `.js` piece modules; a `.ts` one fails with `Stripping types is currently unsupported for files under node_modules`.
265
+
266
+ ## Type-check the rule set
267
+
268
+ `@hailstails/hone/rule-set` and `@hailstails/hone/audit` hold types only. Import them with `import type`. A `tsconfig` for the rule set that matches how Node runs it, `tools/disciplines/acme/tsconfig.pieces.json`:
269
+
270
+ ```json
271
+ {
272
+ "compilerOptions": {
273
+ "target": "es2022",
274
+ "module": "nodenext",
275
+ "moduleResolution": "nodenext",
276
+ "strict": true,
277
+ "noEmit": true,
278
+ "allowImportingTsExtensions": true,
279
+ "erasableSyntaxOnly": true,
280
+ "verbatimModuleSyntax": true,
281
+ "resolveJsonModule": true,
282
+ "skipLibCheck": false,
283
+ "types": []
284
+ },
285
+ "include": ["**/*.ts"]
286
+ }
287
+ ```
288
+
289
+ Run it with the repository's own compiler, for example `tsc --noEmit -p tools/disciplines/acme/tsconfig.pieces.json`. `erasableSyntaxOnly` needs TypeScript 5.8 or later; leave it out on older versions.
290
+
291
+ The ESLint piece's `settings` can be checked against `EslintPieceSettings` from the JSON file itself. `mechanisms/eslint/ACME-1/piece-settings.ts`:
292
+
293
+ ```ts
294
+ import type { EslintPieceSettings } from "@hailstails/hone/rule-set";
295
+ import piece from "./piece.json" with { type: "json" };
296
+
297
+ type Settled<Settings extends EslintPieceSettings> = Settings;
298
+
299
+ export type PieceSettings = Settled<(typeof piece)["clauses"][number]["settings"]>;
300
+ ```
301
+
302
+ A wrong field then fails the type check, for example `Type 'number' is not assignable to type 'string'` for a numeric `rule`; `install-proof` checks this on TypeScript 4.8.4 and 6.0.3 with the same `Settled` type over settings typed as a JSON file types them. TypeScript reads string values in a JSON file as `string`, so this works for `settings` but not for `discipline.json` or the rest of `piece.json`, whose types name exact values such as `"mechanical"`. Hone checks those files when it reads them.
303
+
304
+ ## Test a piece
305
+
306
+ Test an ESLint rule with ESLint's own `RuleTester`, importing the rule the plugin exports, such as `noConsoleCalls`, and giving it the clause's `flag` cases as `invalid` and its `allow` cases as `valid`. Run on its own with `node`, `RuleTester` prints nothing when the cases hold and throws on the first that does not; under a test runner that defines `describe` and `it`, it reports each case as a test.
307
+
308
+ Test an audit piece end to end: commit a file that breaks the rule, run `hone check` and expect its finding, then remove the file and expect a pass. A unit test of `check` itself is harder today: clause addresses and file paths are types that only Hone creates, so a test cannot build them without a cast, and CD-2 flags that cast in a test file as anywhere else.
309
+
310
+ ## Exceptions
311
+
312
+ Exception records in `discipline-exceptions.json` name team clauses by their full address and work exactly as for Hone's own clauses. This entry, with `"fileExceptionWhyChains": "optional"` in `disciplines.json`, moves the finding to `exempted` and, after `hone project`, turns the rule off for that file in the team's own ESLint run:
313
+
314
+ ```json
315
+ {
316
+ "kind": "authorised-location",
317
+ "clause": "acme/ACME-1#console-calls",
318
+ "file": "src/start-banner.ts",
319
+ "reason": "The start banner is the one place that writes to the terminal."
320
+ }
321
+ ```
322
+
323
+ Without that setting the entry also needs a `whyChain`, and without one it is refused as `evidence-refused`. [README.md](../README.md#discipline-exceptionsjson) describes the record kinds and the why-chain each needs.
324
+
325
+ ## What is stable
326
+
327
+ Three requirements are decided and not yet built. Each will make some rule sets that pass today fail:
328
+
329
+ - **Cases are enforced.** `hone check` will run each selected team clause's `cases` against its piece, and fail the run as `nonconforming` when the piece misses a `flag` case or flags an `allow` case.
330
+ - **A rule page is required.** A selected team discipline without `rules/<ID>/README.md` will fail to load.
331
+ - **Pieces keep to import boundaries.** A team piece will be refused if it imports from anywhere but its own piece folder, its discipline's `rules/<ID>` folder, `@hailstails/hone/rule-set`, `@hailstails/hone/audit` and its mechanism's toolchain package (`eslint` or `typescript`), with values only from its own piece folder.
332
+
333
+ To be ready now: give every mechanical clause cases that its piece meets, write each discipline's `README.md`, and import nothing from Hone but its two public type entries.
334
+
335
+ | Part | Status |
336
+ | --- | --- |
337
+ | `ruleSets`, the address `[<ruleSet>/]<ID>#<clause>`, `hone` reserved | Stable |
338
+ | The folder layout `rules/<ID>/` and `mechanisms/<mechanism>/<ID>/` | Stable, with `rules/<ID>/README.md` becoming required |
339
+ | `discipline.json` and `piece.json` version 1, and the ESLint piece `settings` with the namespace rule | Stable file formats; `cases` becoming enforced |
340
+ | `@hailstails/hone/rule-set` | Stable |
341
+ | Exception records for team clauses | Stable |
342
+ | `@hailstails/hone/audit` and the walker piece contract | Experimental: may change in a minor release |
343
+ | A rule set named by a package name, such as `"acme": "@acme/disciplines"` | Not supported: name its repository path instead, as under [TypeScript pieces under Node](#typescript-pieces-under-node) |
344
+ | A new mechanism from outside Hone | Not supported |
345
+
346
+ ## Common refusals
347
+
348
+ | Output | Cause |
349
+ | --- | --- |
350
+ | `load failure: reserved-rule-set-name hone` | A rule set is declared as `hone`. Pick the team's own name. |
351
+ | `load failure: unknown-rule-set beta` | A clause names a rule set that `ruleSets` does not declare. |
352
+ | `load failure: runner-failed eslint piece-invalid <piece folder> the plugin namespace hone belongs to Hone; the rule set acme must use acme or acme-<name>` | The ESLint piece uses one of Hone's namespaces. |
353
+ | `load failure: runner-failed eslint piece-invalid <piece folder> the plugin namespace lint is not owned by the rule set acme; use acme or acme-<name>` | The namespace does not start with the rule set's name. |
354
+ | `load failure: runner-failed eslint piece-invalid <piece folder> ✖ not a path inside the piece folder ending in .ts, or .js in a built install\n → at pluginModule` | The ESLint piece's `pluginModule` is outside the piece folder or ends in neither `.ts` nor `.js`. The `\n` is printed as written, not as a line break. |
355
+ | `load failure: runner-failed audit piece-invalid <piece folder> [\n {\n "code": "custom",\n "path": [\n "module"\n ],\n "message": "the module is not a path inside the piece folder ending .ts, or .js in a built install"\n }\n]` | The audit piece's `module` is outside the piece folder or ends in neither `.ts` nor `.js`. The whole message is one line, each `\n` printed as written. |
356
+ | `(node:<pid>) Warning: Failed to load the ES module: <piece module>. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.` and ``(Use `node --trace-warnings ...` to show where the warning was created)``, then `load failure: runner-failed eslint piece-invalid <piece folder> Unexpected token 'export'` | The nearest `package.json` says `"type": "commonjs"`, so Node read the `.ts` piece as CommonJS. Node prints its warning for each `.ts` piece module it tried; the load failure names one mechanism whose piece failed. Give the rule set a `package.json` with `"type": "module"`. |
357
+ | `<clause> eslint config-override <file>` under `unrecorded` | An `eslint.config.*` that applies to the file does not spread the projection. |
@@ -1,46 +1,19 @@
1
+ import {
2
+ anyBearingOf,
3
+ assertionOf,
4
+ castSnippetAt
5
+ } from "../../../chunks/chunk-3HFJHJDO.js";
1
6
  import {
2
7
  folderScope
3
8
  } from "../../../chunks/chunk-QWA6OVLC.js";
4
9
  import "../../../chunks/chunk-NZLE2WMY.js";
5
10
 
6
11
  // mechanisms/audit/CD-1/any-cast.ts
7
- var SNIPPET_MAX_LENGTH = 80;
8
- var ZOD_MODULE_SPECIFIER_PATTERN = /^zod(\/.*)?$/;
9
- var CD1_ANY_PATTERN = /\bas\s+any\b|:\s*any\b|<any>/;
10
12
  var sourceEligibility = (request) => {
11
13
  if (!request.file.endsWith(".ts") && !request.file.endsWith(".tsx")) return "excluded";
12
14
  if (folderScope({ file: request.file }) === "generated") return "excluded";
13
15
  return "eligible";
14
16
  };
15
- var namesImportedFromZod = (request) => new Set(
16
- request.sourceFile.statements.flatMap((statement) => {
17
- if (!request.syntaxApi.isImportDeclaration(statement)) return [];
18
- if (!request.syntaxApi.isStringLiteral(statement.moduleSpecifier)) return [];
19
- if (!ZOD_MODULE_SPECIFIER_PATTERN.test(statement.moduleSpecifier.text)) return [];
20
- const namedBindings = statement.importClause?.namedBindings;
21
- if (namedBindings === void 0 || !request.syntaxApi.isNamedImports(namedBindings)) return [];
22
- return namedBindings.elements.map((element) => element.name.text);
23
- })
24
- );
25
- var castPermission = (request) => {
26
- if (!request.syntaxApi.isAsExpression(request.node)) return "forbidden";
27
- const typeNode = request.node.type;
28
- if (typeNode.kind === request.syntaxApi.SyntaxKind.UnknownKeyword) return "permitted";
29
- if (request.syntaxApi.isTypeReferenceNode(typeNode) && request.syntaxApi.isIdentifier(typeNode.typeName)) {
30
- const typeName = typeNode.typeName.text;
31
- if (typeName === "const" || request.zodImportedNames.has(typeName)) return "permitted";
32
- if (request.syntaxApi.isPropertyAccessExpression(request.node.expression) && request.node.expression.name.text === "value" && (typeName === "ReadonlyArray" || typeName === "Array")) return "permitted";
33
- }
34
- if (!request.syntaxApi.isIndexedAccessTypeNode(typeNode)) return "forbidden";
35
- const objectType = typeNode.objectType;
36
- const indexType = typeNode.indexType;
37
- if (request.syntaxApi.isTypeReferenceNode(objectType) && request.syntaxApi.isIdentifier(objectType.typeName) && objectType.typeName.text === "Tool" && request.syntaxApi.isLiteralTypeNode(indexType) && request.syntaxApi.isStringLiteral(indexType.literal) && indexType.literal.text === "inputSchema") return "permitted";
38
- return "forbidden";
39
- };
40
- var snippetAt = (request) => {
41
- const snippet = request.sourceFile.text.slice(request.position, request.position + SNIPPET_MAX_LENGTH).replace(/\n/g, " ");
42
- return snippet.length === SNIPPET_MAX_LENGTH ? `${snippet}\u2026` : snippet;
43
- };
44
17
  var check = {
45
18
  prepare: ({ clauses, syntaxApi }) => ({
46
19
  outcome: "ok",
@@ -54,15 +27,14 @@ var check = {
54
27
  value: {
55
28
  kind: "syntax",
56
29
  begin: ({ sourceFile, anchorAt }) => {
57
- const zodImportedNames = namesImportedFromZod({ sourceFile, syntaxApi });
58
30
  const hits = [];
59
31
  return {
60
32
  enter: ({ node }) => {
61
- if (!syntaxApi.isAsExpression(node) && !syntaxApi.isTypeAssertionExpression(node)) return;
62
- if (castPermission({ node, syntaxApi, zodImportedNames }) === "permitted") return;
33
+ const assertion = assertionOf({ node, syntaxApi });
34
+ if (assertion === void 0) return;
35
+ if (anyBearingOf({ typeNode: assertion.type, syntaxApi }) === "any-free") return;
63
36
  const position = node.getStart(sourceFile);
64
- const snippet = snippetAt({ sourceFile, position });
65
- if (!CD1_ANY_PATTERN.test(snippet)) return;
37
+ const snippet = castSnippetAt({ sourceFile, position });
66
38
  const anchor = anchorAt({ position });
67
39
  hits.push(...clauses.map((clause) => ({ clause: clause.address, anchor, snippet })));
68
40
  },