@alex-dbs/coderuler 0.0.0-stage → 1.3.1

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 (121) hide show
  1. package/LICENSE +175 -0
  2. package/README.md +218 -2
  3. package/dist/adapter/cli/commands/check.d.ts +3 -0
  4. package/dist/adapter/cli/commands/check.js +93 -0
  5. package/dist/adapter/cli/commands/deps.d.ts +3 -0
  6. package/dist/adapter/cli/commands/deps.js +4 -0
  7. package/dist/adapter/cli/commands/inspect.d.ts +3 -0
  8. package/dist/adapter/cli/commands/inspect.js +59 -0
  9. package/dist/adapter/cli/commands/rules.d.ts +10 -0
  10. package/dist/adapter/cli/commands/rules.js +17 -0
  11. package/dist/adapter/cli/commands/skill.d.ts +4 -0
  12. package/dist/adapter/cli/commands/skill.js +7 -0
  13. package/dist/adapter/cli/commands/test.d.ts +3 -0
  14. package/dist/adapter/cli/commands/test.js +78 -0
  15. package/dist/adapter/cli/commands/update.d.ts +3 -0
  16. package/dist/adapter/cli/commands/update.js +7 -0
  17. package/dist/adapter/cli/commands/validate.d.ts +3 -0
  18. package/dist/adapter/cli/commands/validate.js +12 -0
  19. package/dist/adapter/cli/exit.d.ts +7 -0
  20. package/dist/adapter/cli/exit.js +10 -0
  21. package/dist/adapter/cli/inspect-json.d.ts +9 -0
  22. package/dist/adapter/cli/inspect-json.js +160 -0
  23. package/dist/adapter/cli/inspect-usage.d.ts +9 -0
  24. package/dist/adapter/cli/inspect-usage.js +14 -0
  25. package/dist/adapter/cli/program.d.ts +4 -0
  26. package/dist/adapter/cli/program.js +216 -0
  27. package/dist/adapter/cli/progress.d.ts +22 -0
  28. package/dist/adapter/cli/progress.js +79 -0
  29. package/dist/adapter/cli/reports.d.ts +47 -0
  30. package/dist/adapter/cli/reports.js +735 -0
  31. package/dist/adapter/cli/self-update.d.ts +1 -0
  32. package/dist/adapter/cli/self-update.js +89 -0
  33. package/dist/adapter/cli/services.d.ts +101 -0
  34. package/dist/adapter/cli/services.js +1 -0
  35. package/dist/adapter/cli/text.d.ts +5 -0
  36. package/dist/adapter/cli/text.js +36 -0
  37. package/dist/adapter/cli/version.d.ts +1 -0
  38. package/dist/adapter/cli/version.js +3 -0
  39. package/dist/adapter/decision/jev.d.ts +11 -0
  40. package/dist/adapter/decision/jev.js +138 -0
  41. package/dist/adapter/filesystem/dependencies.d.ts +26 -0
  42. package/dist/adapter/filesystem/dependencies.js +577 -0
  43. package/dist/adapter/filesystem/dependency-installation.d.ts +11 -0
  44. package/dist/adapter/filesystem/dependency-installation.js +373 -0
  45. package/dist/adapter/filesystem/project.d.ts +14 -0
  46. package/dist/adapter/filesystem/project.js +387 -0
  47. package/dist/adapter/filesystem/rule-resolution.d.ts +4 -0
  48. package/dist/adapter/filesystem/rule-resolution.js +516 -0
  49. package/dist/adapter/filesystem/rule-test-worker.d.ts +17 -0
  50. package/dist/adapter/filesystem/rule-test-worker.js +47 -0
  51. package/dist/adapter/filesystem/rule-tests.d.ts +3 -0
  52. package/dist/adapter/filesystem/rule-tests.js +264 -0
  53. package/dist/adapter/filesystem/rules.d.ts +13 -0
  54. package/dist/adapter/filesystem/rules.js +242 -0
  55. package/dist/adapter/git/changes.d.ts +1 -0
  56. package/dist/adapter/git/changes.js +54 -0
  57. package/dist/adapter/git/environment.d.ts +1 -0
  58. package/dist/adapter/git/environment.js +10 -0
  59. package/dist/adapter/github/api.d.ts +5 -0
  60. package/dist/adapter/github/api.js +40 -0
  61. package/dist/adapter/github/comments.d.ts +3 -0
  62. package/dist/adapter/github/comments.js +235 -0
  63. package/dist/adapter/github/pull-request.d.ts +16 -0
  64. package/dist/adapter/github/pull-request.js +139 -0
  65. package/dist/adapter/scope/astgrep-languages.d.ts +5 -0
  66. package/dist/adapter/scope/astgrep-languages.js +119 -0
  67. package/dist/adapter/scope/astgrep.d.ts +14 -0
  68. package/dist/adapter/scope/astgrep.js +183 -0
  69. package/dist/adapter/scope/csv.d.ts +4 -0
  70. package/dist/adapter/scope/csv.js +158 -0
  71. package/dist/adapter/scope/file.d.ts +2 -0
  72. package/dist/adapter/scope/file.js +4 -0
  73. package/dist/adapter/scope/json.d.ts +7 -0
  74. package/dist/adapter/scope/json.js +132 -0
  75. package/dist/adapter/scope/lines.d.ts +10 -0
  76. package/dist/adapter/scope/lines.js +42 -0
  77. package/dist/adapter/scope/protobuf-options.d.ts +29 -0
  78. package/dist/adapter/scope/protobuf-options.js +64 -0
  79. package/dist/adapter/scope/protobuf-parser.d.ts +30 -0
  80. package/dist/adapter/scope/protobuf-parser.js +772 -0
  81. package/dist/adapter/scope/protobuf.d.ts +5 -0
  82. package/dist/adapter/scope/protobuf.js +53 -0
  83. package/dist/adapter/scope/structured.d.ts +10 -0
  84. package/dist/adapter/scope/structured.js +84 -0
  85. package/dist/adapter/scope/yaml.d.ts +7 -0
  86. package/dist/adapter/scope/yaml.js +224 -0
  87. package/dist/adapter/skills/cli.d.ts +10 -0
  88. package/dist/adapter/skills/cli.js +77 -0
  89. package/dist/app/concurrency.d.ts +1 -0
  90. package/dist/app/concurrency.js +44 -0
  91. package/dist/app/evaluators.d.ts +14 -0
  92. package/dist/app/evaluators.js +175 -0
  93. package/dist/app/execute.d.ts +2 -0
  94. package/dist/app/execute.js +427 -0
  95. package/dist/app/jsonpath.d.ts +1 -0
  96. package/dist/app/jsonpath.js +8 -0
  97. package/dist/app/ports.d.ts +165 -0
  98. package/dist/app/ports.js +1 -0
  99. package/dist/app/rule-tests.d.ts +20 -0
  100. package/dist/app/rule-tests.js +11 -0
  101. package/dist/app/rule.d.ts +121 -0
  102. package/dist/app/rule.js +24 -0
  103. package/dist/app/selection.d.ts +2 -0
  104. package/dist/app/selection.js +23 -0
  105. package/dist/app/usage.d.ts +2 -0
  106. package/dist/app/usage.js +13 -0
  107. package/dist/app/validate.d.ts +11 -0
  108. package/dist/app/validate.js +415 -0
  109. package/dist/app/violation-comments.d.ts +10 -0
  110. package/dist/app/violation-comments.js +1 -0
  111. package/dist/cli.d.ts +2 -0
  112. package/dist/cli.js +3 -0
  113. package/dist/index.d.ts +22 -0
  114. package/dist/index.js +11 -0
  115. package/dist/infra/runtime.d.ts +3 -0
  116. package/dist/infra/runtime.js +168 -0
  117. package/dist/infra/settings.d.ts +5 -0
  118. package/dist/infra/settings.js +91 -0
  119. package/package.json +86 -4
  120. package/skills/coderuler-new-rule/SKILL.md +141 -0
  121. package/skills/coderuler-new-rule/reference.md +447 -0
package/LICENSE ADDED
@@ -0,0 +1,175 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this License, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding those notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and do
116
+ not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,219 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="coderuler-icon.webp" alt="CodeRuler shield logo" width="144">
4
+
5
+ </p>
6
+
7
+ **Tired of asking your AI agent to follow your conventions, only to watch it ignore them?** Define your conventions as simple rules and let **CodeRuler** check your code against them, without forgetting one.
8
+
9
+ ## Install
10
+
11
+ CodeRuler requires Node.js 24.15+, or Node.js 26+. Git is required for `check --diff` and `check --pr`.
12
+
13
+ Install the CLI globally:
14
+
15
+ ```sh
16
+ npm install -g @alex-dbs/coderuler
17
+ coderuler --help
18
+ ```
19
+
20
+ The npm package is scoped. The command is `coderuler`. A global installation can load rules without a project-local dependency.
21
+
22
+ For a project-specific CLI version, install it locally:
23
+
24
+ ```sh
25
+ npm install --save-dev @alex-dbs/coderuler
26
+ npx coderuler --help
27
+ ```
28
+
29
+ The global installation is optional: with only the project-local dependency, run commands through `npx coderuler`.
30
+
31
+ The npm install commands require the first release to be published. To run an unreleased checkout, use `npm ci`, `npm run build`, then `npm start -- --help`.
32
+
33
+ ## Rule dependencies
34
+
35
+ Use ordinary JavaScript or TypeScript imports in rules. Add public npm packages without running `npm install` or changing application dependencies:
36
+
37
+ ```sh
38
+ coderuler deps add bignumber.js@11.1.5
39
+ coderuler deps add bignumber.js@latest
40
+ coderuler deps remove bignumber.js
41
+ coderuler deps sync
42
+ ```
43
+
44
+ `deps add` accepts names, versions, ranges, and tags.
45
+
46
+ ## Write a rule
47
+
48
+ Save rules in `.coderuler` (or any subfolders) with a name that ends in `.rule.ts`, `.rule.mts`, `.rule.js`, or `.rule.mjs`. A rule is a class that extends `Rule` and is the module's default export. Save the example below as `.coderuler/no-any.rule.ts`.
49
+
50
+ This rule reports explicit `any` types in TypeScript files.
51
+
52
+ ```ts
53
+ import { Rule, scopes, test, violation } from '@alex-dbs/coderuler';
54
+
55
+ export default class NoAny extends Rule {
56
+ files = ['src/**/*.{ts,tsx}']; // Which files?
57
+
58
+ scope = scopes.astGrep({ // Which part of the file to check; here ast Grep
59
+ language: 'typescript',
60
+ rule: {
61
+ kind: 'predefined_type',
62
+ pattern: { context: 'type ExplicitAny = any;', selector: 'predefined_type' },
63
+ },
64
+ });
65
+
66
+ // The check is simple: if something matches the scope, then it is a violation.
67
+ check = () => violation('Replace explicit any with a specific type or unknown and narrow it.');
68
+ }
69
+
70
+ // You can also write tests here for better developer experience!
71
+ export const tests = [
72
+ test('explicit any violates').withFiles({
73
+ 'src/example.ts': 'let value: any;',
74
+ }).violates(),
75
+ test('a specific type passes').withFiles({
76
+ 'src/example.ts': 'let value: string;',
77
+ }).passes(),
78
+ ];
79
+ ```
80
+
81
+ ### Regular-expression rule
82
+
83
+ Use a regular expression for a pattern with a clear pass or fail condition. This rule selects `google.api.http` URLs from protobuf files and requires versioned, such as `/v1/invoices`.
84
+
85
+ ```ts
86
+ import { Rule, regex, scopes } from '@alex-dbs/coderuler';
87
+
88
+ export default class PublicApiPaths extends Rule {
89
+ files = ['api/**/*.proto'];
90
+
91
+ scope = scopes.protobuf({ path: "$.rpcs[*].options['google.api.http']..['get','put','post','delete','patch','path']" });
92
+
93
+ check = regex({
94
+ pattern: /^\/v\d+\/[a-z][a-z0-9_]*s(?:\/.*)?$/,
95
+ violationMessage: 'Use a versioned lowercase plural path.',
96
+ });
97
+ }
98
+ ```
99
+
100
+ ### AI rule
101
+
102
+ Use an AI rule when a policy needs meaning or context that a fixed pattern cannot capture. This rule sends one selected function to the AI decision API, Jev from [Typesafe](https://typesafe.ai/).
103
+
104
+ ```ts
105
+ import { Rule, ai, scopes } from '@alex-dbs/coderuler';
106
+ import type { ScopeSubject } from '@alex-dbs/coderuler';
107
+
108
+ export default class SafeResponseHeaders extends Rule {
109
+ files = ['src/**/*.js'];
110
+
111
+ scope = scopes.astGrep({
112
+ language: 'javascript',
113
+ rule: { kind: 'function_declaration' },
114
+ });
115
+
116
+ check = ai({
117
+ rule: 'Report a violation only when this function writes request data into an HTTP response header without rejecting CR and LF first. Judge only this function. Do not assume unseen callers or helpers validate the data.',
118
+ input: subject => (subject as ScopeSubject).source,
119
+ violationMessage: 'Reject CR and LF in request data before writing a response header.',
120
+ });
121
+ }
122
+ ```
123
+
124
+ This example shows an AI check for CWE-113.
125
+
126
+ AI rules require a configured service and can incur charges.
127
+
128
+ > [!TIP]
129
+ > Keep the selected scope as small as the rule allows. A smaller input can reduce token costs and help the model focus on relevant code. Include enough context for the policy to make a sound decision.
130
+
131
+ Run validation, tests, and the rule against your project (use `npx coderuler` for a project-local installation):
132
+
133
+ ```sh
134
+ coderuler validate no-any
135
+ coderuler test no-any
136
+ coderuler check . --rules no-any
137
+ ```
138
+
139
+ ## Rule pipeline
140
+
141
+ A scope is a file or selected part of a file. CodeRuler validates selected rules, then applies this pipeline to each rule:
142
+
143
+ `enabled → when → files and excludes → scope or select → filter → group → check → report`
144
+
145
+ - `enabled` defaults to `true`. Set it to `false` to disable a rule.
146
+ - `when(context)` runs once for each enabled rule before file selection. It defaults to `true`. Return `false` to skip the rule, or return `{ applies: false, reason: '...' }` to explain why. An example: apply a rule based on some conditions, for instance, the Go version of the project.
147
+ - `files` is a nonempty list of root-relative globs. It defaults to `['**/*']`. `exclude` is a list of root-relative globs that removes matching files. It defaults to `[]`.
148
+ - `scope` selects the parts of each file to evaluate. Without it, CodeRuler uses one whole-file scope. Use `scopes.file()`, `scopes.json()`, `scopes.yaml()`, `scopes.csv()`, `scopes.protobuf()`, or `scopes.astGrep()` to choose the source or data.
149
+ - Override `select(context)` when you need custom file or scope selection. Call `context.select({ files, exclude, scope })` to reuse built-in selection.
150
+ - `filter(subject, context)` runs once per selected scope, before grouping. It defaults to `true`. Return `false` or `{ applies: false, reason: '...' }` to skip a scope. Put applicability and required-data checks here (null check for instance).
151
+ - `group` controls which scopes the evaluator sees together. It defaults to `'scope'`, which evaluates each scope separately. Set it to `'file'`, `'folder'`, `'project'`, or `{ by: 'folder', level }`. `folder` groups scopes within each containing folder. `project` groups all selected scopes together. `level` is a nonpositive integer.
152
+ - `check` is the required evaluator. Assign `regex(...)`, `ai(...)`, or a function as a property. Return `pass()` or `violation(message)` from a custom function.
153
+ - `comment` optionally replaces each GitHub finding body for this rule when you use `--auto-comment` with `check --diff` or `check --pr`. Set a nonblank Markdown string, for example `comment = 'Follow [our policy](https://example.com/policy).'`. Without it, CodeRuler uses the generated body. Inline locations do not change.
154
+
155
+ The `settings` field sets AI options for one rule, such as its model, decision threshold, and input or output token prices.
156
+
157
+ > [!TIP]
158
+ > Browse the [`.coderuler` folder](.coderuler) for rule examples.
159
+
160
+ ## Commands
161
+
162
+ - `update` upgrades the active global npm installation to the latest release. Update local dependencies with their package manager instead.
163
+ - `validate [rule]` loads rules and validates their structure without running them.
164
+ - `test [rule]` runs the inline tests declared by selected rules.
165
+ - `check [path]` runs selected rules against a file or folder. Use `--rules <rule>` to select a rule name, module path, or directory. It exits with status 1 when a rule reports a violation.
166
+ - `inspect <rule> [folder]` shows how one rule selects and evaluates subjects.
167
+ - `skill install` and `skill update` install or refresh CodeRuler's rule-writing skill for coding agents.
168
+ - `deps add`, `deps remove`, and `deps sync` manage locked rule packages and editor declarations.
169
+
170
+ For `validate`, `test`, and `check --rules`, a rule name is the exact filename stem of a discovered rule. Discovery searches `.coderuler` in the project and `~/.coderuler` in your home directory, including subfolders. A name filters discovered rules; an explicit module path or directory replaces discovery. Use `--help` after a command for its options.
171
+
172
+ ## AI decisions
173
+
174
+ AI rules use Jev through Typesafe. Set `TYPESAFE_API_KEY` before running a rule that uses `ai()`. You can set `TYPESAFE_BASE_URL` and `TYPESAFE_DEFAULT_MODEL` to choose the service URL and model. See [`.env.example`](.env.example) for the available environment variables and pricing defaults.
175
+
176
+ AI calls can send rule input to the configured service and can incur charges. The normal `test` command runs offline. Use `test --ai` to run cases declared as `aiTests`.
177
+
178
+ ## FAQ
179
+
180
+ ### Why not use a linter?
181
+
182
+ Use a linter for common syntax and style rules. Use CodeRuler for project policies that need custom code, structured scopes, or AI judgment. The tools work well together.
183
+
184
+ ### Why not use `AGENTS.md`?
185
+
186
+ `AGENTS.md` guides coding agents, but it does not enforce the instructions by itself. CodeRuler runs executable rules against project files and reports violations. Use both when you need instructions and enforcement.
187
+
188
+ ### Why not use a subagent?
189
+
190
+ A subagent can review code, but each review uses time and tokens. CodeRuler lets you save recurring policies as rules and run them when needed. Use a subagent for broad reviews or questions that do not fit a rule.
191
+
192
+ ### Why TypeScript or JavaScript?
193
+
194
+ Neither language is chosen for raw execution speed. Many developers already know one of them, and a rule can live in a single module. CodeRuler keeps work focused with file and scope selection, and it bounds concurrency. We replace LONG and COSTLY AI Agent verification checks by predictable code, running at the speed of less than 1ms per verification; way faster than any LLM. Having a faster tool is better of course, but the developer experience is more important than 0.3ms gain per rule 😉. Perhaps one day, the core will be re-written in rust... who knows!
195
+
196
+ ### Does CodeRuler support every language?
197
+
198
+ Rules are TypeScript or JavaScript modules, but they can inspect text files in any language. AST rules use the built-in and bundled ast-grep grammars. If a language has no grammar, write a custom selector or evaluator that reads its source text.
199
+
200
+ ### Can I do anything with a rule?
201
+
202
+ Rule modules are trusted Node.js code. You can write custom selectors, filters, and evaluators. When a simple code is not enough, you can rely on AI decision api. So yes, you can do whatever you like with CodeRuler. Keep in mind that a good rule MUST be auditable, easy to read, maintain and review.
203
+
204
+ ## Contributing
205
+
206
+ Before you contribute, install dependencies and run the project checks from the repository root:
207
+
208
+ ```sh
209
+ npm ci
210
+ npm test
211
+ node dist/cli.js deps sync
212
+ npm run typecheck
213
+ ```
214
+
215
+ Add or update tests for changes to rule behavior. The [rule-writing skill](skills/coderuler-new-rule/SKILL.md) explains how to create rules, add inline tests, and inspect rule behavior.
216
+
217
+ ## License
218
+
219
+ This project is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,3 @@
1
+ import type { CheckOptions, CheckServices, CliContext } from '../services.js';
2
+ declare function runCheck(target: string, options: CheckOptions, context: CliContext, services: CheckServices): Promise<void>;
3
+ export { runCheck };
@@ -0,0 +1,93 @@
1
+ import { relative, resolve, sep } from 'node:path';
2
+ import { CliExit, EXIT_VIOLATION } from '../exit.js';
3
+ import { createProgress } from '../progress.js';
4
+ import { countViolations, createMetadataRenderer, createRuleHeadings, createWalkthroughRenderer, renderCheckJson, renderCheckJsonl, renderCheckSummary, renderViolationComments, } from '../reports.js';
5
+ import { planWalk } from './rules.js';
6
+ async function runCheck(target, options, context, services) {
7
+ const diffOnly = options.diffOnly === true || options.pr !== undefined;
8
+ const debug = options.debug === true;
9
+ const verbose = options.verbose === true;
10
+ const machine = options.json === true || options.jsonl === true;
11
+ const progress = context.terminal?.interactive === true && !machine && !debug && !verbose
12
+ ? createProgress(context.writeError, () => context.terminal?.columns ?? 80)
13
+ : undefined;
14
+ let checkout;
15
+ try {
16
+ let reports;
17
+ let durationMs;
18
+ let root;
19
+ let rules;
20
+ let walkthrough;
21
+ try {
22
+ if (options.pr !== undefined) {
23
+ checkout = await services.checkoutPullRequest(options.pr, options.base);
24
+ }
25
+ const area = await services.resolveTarget(checkout?.root ?? context.cwd, target);
26
+ root = area.root;
27
+ let changedFiles = checkout?.changedFiles ?? (diffOnly
28
+ ? await services.changedFiles(area.root, options.base ?? 'HEAD')
29
+ : undefined);
30
+ const choice = options.rules === undefined
31
+ ? {}
32
+ : await services.resolveRuleSelector(options.rules, context.cwd, true);
33
+ const prepared = await planWalk(context.cwd, services, area.root, filepath => area.contains(filepath), choice, checkout?.rulesRoot ?? area.root);
34
+ rules = options.tags.length === 0 && options.excludeTags.length === 0
35
+ ? prepared.rules
36
+ : prepared.rules.filter(({ rule }) => (options.tags.length === 0 ||
37
+ rule.tags?.some(tag => options.tags.includes(tag)) === true) &&
38
+ !rule.tags?.some(tag => options.excludeTags.includes(tag)));
39
+ if (changedFiles !== undefined) {
40
+ const ruleFiles = new Set(prepared.rules.map(entry => relative(area.root, resolve(entry.ruleFile)).split(sep).join('/')));
41
+ changedFiles = new Set([...changedFiles].filter(path => !ruleFiles.has(path)));
42
+ }
43
+ const concurrency = debug ? 1 : options.concurrency;
44
+ walkthrough = verbose
45
+ ? createWalkthroughRenderer({
46
+ write: context.writeError,
47
+ headings: createRuleHeadings(rules),
48
+ redact: context.redact,
49
+ columns: () => context.terminal?.columns ?? 80,
50
+ concurrency,
51
+ })
52
+ : undefined;
53
+ const emit = walkthrough?.emit ?? (debug
54
+ ? createMetadataRenderer(context.writeError, context.redact)
55
+ : progress?.emit);
56
+ const runContext = {
57
+ project: prepared.project,
58
+ isTarget: prepared.isTarget,
59
+ concurrency,
60
+ resolveDecision: services.decisionResolver(options.threshold),
61
+ ...(emit === undefined ? {} : { emit }),
62
+ ...(changedFiles === undefined ? {} : { changedFiles }),
63
+ };
64
+ const startedAt = performance.now();
65
+ reports = await services.runRules(rules, runContext);
66
+ durationMs = performance.now() - startedAt;
67
+ }
68
+ finally {
69
+ walkthrough?.finish();
70
+ progress?.stop();
71
+ }
72
+ const reportOptions = {
73
+ durationMs,
74
+ outputAll: options.outputAll === true,
75
+ color: context.terminal?.color === true,
76
+ };
77
+ context.write(options.json === true
78
+ ? renderCheckJson(reports, reportOptions)
79
+ : options.jsonl === true
80
+ ? renderCheckJsonl(reports, reportOptions)
81
+ : renderCheckSummary(reports, context.redact, reportOptions));
82
+ if (countViolations(reports) > 0) {
83
+ if (options.autoComment === true) {
84
+ await services.commentOnPullRequest(root, renderViolationComments(reports, context.redact, rules), checkout?.pullRequest);
85
+ }
86
+ throw new CliExit(EXIT_VIOLATION);
87
+ }
88
+ }
89
+ finally {
90
+ await checkout?.cleanup();
91
+ }
92
+ }
93
+ export { runCheck };
@@ -0,0 +1,3 @@
1
+ import type { DependencyOptions, DependencyServices } from '../services.js';
2
+ declare function runDeps(operation: 'add' | 'remove' | 'sync', packages: readonly string[], options: DependencyOptions, services: DependencyServices): Promise<void>;
3
+ export { runDeps };
@@ -0,0 +1,4 @@
1
+ async function runDeps(operation, packages, options, services) {
2
+ await services.manageDependencies(operation, packages, options);
3
+ }
4
+ export { runDeps };
@@ -0,0 +1,3 @@
1
+ import type { CliContext, InspectOptions, InspectServices } from '../services.js';
2
+ declare function runInspect(rule: string, folder: string, options: InspectOptions, context: CliContext, services: InspectServices): Promise<void>;
3
+ export { runInspect };
@@ -0,0 +1,59 @@
1
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
2
+ import { createInspectJsonRenderer } from '../inspect-json.js';
3
+ import { CliExit, EXIT_VIOLATION } from '../exit.js';
4
+ import { countViolations, createInspectRenderer, createRuleHeadings, } from '../reports.js';
5
+ import { escapeText } from '../text.js';
6
+ import { planWalk } from './rules.js';
7
+ async function runInspect(rule, folder, options, context, services) {
8
+ let inspect = options.json === true || options.jsonl === true
9
+ ? createInspectJsonRenderer({
10
+ write: context.write,
11
+ redact: context.redact,
12
+ format: options.json === true ? 'json' : 'jsonl',
13
+ })
14
+ : undefined;
15
+ try {
16
+ const resolved = await services.resolveRuleSelector(rule, context.cwd);
17
+ const folderPath = resolve(context.cwd, folder);
18
+ const relativeFolder = relative(context.cwd, folderPath);
19
+ const insideInvocationRoot = relativeFolder !== '..' &&
20
+ !relativeFolder.startsWith(`..${sep}`) &&
21
+ !isAbsolute(relativeFolder);
22
+ const area = await services.resolveTarget(insideInvocationRoot ? context.cwd : folderPath, insideInvocationRoot ? (relativeFolder === '' ? '.' : relativeFolder) : '.');
23
+ if (area.kind !== 'directory') {
24
+ throw new Error(`Inspect folder ${escapeText(folder)} is not a directory`);
25
+ }
26
+ const prepared = await planWalk(context.cwd, services, join(area.root, area.path), () => true, resolved);
27
+ inspect ??= createInspectRenderer({
28
+ write: context.write,
29
+ headings: createRuleHeadings(prepared.rules),
30
+ redact: context.redact,
31
+ color: options.raw !== true && context.terminal?.color === true,
32
+ columns: () => context.terminal?.stdoutColumns ?? context.terminal?.columns ?? 80,
33
+ raw: options.raw === true,
34
+ });
35
+ const reports = await services.runRules(prepared.rules, {
36
+ project: prepared.project,
37
+ isTarget: prepared.isTarget,
38
+ concurrency: 1,
39
+ resolveDecision: services.decisionResolver(undefined, {
40
+ ...(options.inputCostPerMillion === undefined ? {} : { inputCostPerMillion: options.inputCostPerMillion }),
41
+ ...(options.outputCostPerMillion === undefined ? {} : { outputCostPerMillion: options.outputCostPerMillion }),
42
+ }),
43
+ emit: inspect.emit,
44
+ });
45
+ inspect.finish(reports);
46
+ if (countViolations(reports) > 0)
47
+ throw new CliExit(EXIT_VIOLATION);
48
+ }
49
+ catch (error) {
50
+ if (!(error instanceof CliExit)) {
51
+ inspect?.finish([], error instanceof Error ? error.message : String(error));
52
+ }
53
+ throw error;
54
+ }
55
+ finally {
56
+ inspect?.finish([]);
57
+ }
58
+ }
59
+ export { runInspect };
@@ -0,0 +1,10 @@
1
+ import type { LoadedRule, Project, RuleSelection } from '../../../app/ports.js';
2
+ import type { ExecutionServices, RuleSelectorResolution } from '../services.js';
3
+ interface ExecutionPlan {
4
+ readonly rules: readonly LoadedRule[];
5
+ readonly project: Project;
6
+ readonly isTarget: (filepath: string) => boolean;
7
+ }
8
+ declare function ruleSelection(cwd: string, choice: RuleSelectorResolution, root: string): RuleSelection;
9
+ declare function planWalk(cwd: string, services: ExecutionServices, root: string, isTarget: (filepath: string) => boolean, choice: RuleSelectorResolution, rulesRoot?: string): Promise<ExecutionPlan>;
10
+ export { planWalk, ruleSelection };
@@ -0,0 +1,17 @@
1
+ function ruleSelection(cwd, choice, root) {
2
+ if (choice.explicit !== undefined) {
3
+ return { root, explicit: choice.explicit, invocationCwd: cwd };
4
+ }
5
+ if (choice.name !== undefined) {
6
+ return { root, name: choice.name, invocationCwd: cwd };
7
+ }
8
+ return { root, invocationCwd: cwd };
9
+ }
10
+ async function planWalk(cwd, services, root, isTarget, choice, rulesRoot = root) {
11
+ const rules = await services.loadRules(ruleSelection(cwd, choice, rulesRoot));
12
+ const project = services.createProject(root, {
13
+ excludeFiles: rules.map(entry => entry.ruleFile),
14
+ });
15
+ return { rules, project, isTarget };
16
+ }
17
+ export { planWalk, ruleSelection };
@@ -0,0 +1,4 @@
1
+ import type { SkillOptions } from '../../skills/cli.js';
2
+ import type { SkillServices } from '../services.js';
3
+ declare function runSkill(operation: 'install' | 'update', options: SkillOptions, services: SkillServices): Promise<void>;
4
+ export { runSkill };
@@ -0,0 +1,7 @@
1
+ import { CliExit, EXIT_OK } from '../exit.js';
2
+ async function runSkill(operation, options, services) {
3
+ const status = await services.manageSkill(operation, options);
4
+ if (status !== EXIT_OK)
5
+ throw new CliExit(status);
6
+ }
7
+ export { runSkill };
@@ -0,0 +1,3 @@
1
+ import type { CliContext, TestOptions, TestServices } from '../services.js';
2
+ declare function runTest(rulePath: string | undefined, options: TestOptions, context: CliContext, services: TestServices): Promise<void>;
3
+ export { runTest };