@yearofthedan/warp 0.0.0-stage → 0.2.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.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/dist/analysis/complexity.d.ts +4 -0
  4. package/dist/analysis/complexity.js +84 -0
  5. package/dist/analysis/folders.d.ts +2 -0
  6. package/dist/analysis/folders.js +15 -0
  7. package/dist/analysis/imports.d.ts +13 -0
  8. package/dist/analysis/imports.js +135 -0
  9. package/dist/analysis/members.d.ts +4 -0
  10. package/dist/analysis/members.js +190 -0
  11. package/dist/analysis/source.d.ts +13 -0
  12. package/dist/analysis/source.js +29 -0
  13. package/dist/analysis/specifiers.d.ts +2 -0
  14. package/dist/analysis/specifiers.js +6 -0
  15. package/dist/analysis/typescript.d.ts +2 -0
  16. package/dist/analysis/typescript.js +105 -0
  17. package/dist/app/check.d.ts +23 -0
  18. package/dist/app/check.js +15 -0
  19. package/dist/app/checkModel.d.ts +5 -0
  20. package/dist/app/checkModel.js +30 -0
  21. package/dist/app/diff.d.ts +25 -0
  22. package/dist/app/diff.js +53 -0
  23. package/dist/app/facts.d.ts +7 -0
  24. package/dist/app/facts.js +55 -0
  25. package/dist/app/load.d.ts +13 -0
  26. package/dist/app/load.js +76 -0
  27. package/dist/app/ports.d.ts +41 -0
  28. package/dist/app/ports.js +1 -0
  29. package/dist/app/unclassified.d.ts +5 -0
  30. package/dist/app/unclassified.js +13 -0
  31. package/dist/builtins/cognitive-complexity/cognitiveComplexity.d.ts +6 -0
  32. package/dist/builtins/cognitive-complexity/cognitiveComplexity.js +26 -0
  33. package/dist/builtins/components.d.ts +2 -0
  34. package/dist/builtins/components.js +20 -0
  35. package/dist/builtins/dependency-direction/dependencyDirection.d.ts +2 -0
  36. package/dist/builtins/dependency-direction/dependencyDirection.js +68 -0
  37. package/dist/builtins/file-cohesion/fileCohesion.d.ts +6 -0
  38. package/dist/builtins/file-cohesion/fileCohesion.js +30 -0
  39. package/dist/builtins/function-cohesion/functionCohesion.d.ts +6 -0
  40. package/dist/builtins/function-cohesion/functionCohesion.js +30 -0
  41. package/dist/builtins/index.d.ts +4 -0
  42. package/dist/builtins/index.js +30 -0
  43. package/dist/builtins/loops.d.ts +25 -0
  44. package/dist/builtins/loops.js +64 -0
  45. package/dist/builtins/module-cycle/moduleCycle.d.ts +3 -0
  46. package/dist/builtins/module-cycle/moduleCycle.js +61 -0
  47. package/dist/builtins/module-externals/moduleExternals.d.ts +2 -0
  48. package/dist/builtins/module-externals/moduleExternals.js +41 -0
  49. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.d.ts +2 -0
  50. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +47 -0
  51. package/dist/builtins/no-cycle/noCycle.d.ts +3 -0
  52. package/dist/builtins/no-cycle/noCycle.js +39 -0
  53. package/dist/builtins/no-double-export/noDoubleExport.d.ts +2 -0
  54. package/dist/builtins/no-double-export/noDoubleExport.js +38 -0
  55. package/dist/builtins/packages.d.ts +2 -0
  56. package/dist/builtins/packages.js +5 -0
  57. package/dist/builtins/place.d.ts +2 -0
  58. package/dist/builtins/place.js +6 -0
  59. package/dist/builtins/shared.d.ts +10 -0
  60. package/dist/builtins/shared.js +13 -0
  61. package/dist/builtins/unused-declaration/declarations.d.ts +32 -0
  62. package/dist/builtins/unused-declaration/declarations.js +26 -0
  63. package/dist/builtins/unused-declaration/empty.d.ts +3 -0
  64. package/dist/builtins/unused-declaration/empty.js +22 -0
  65. package/dist/builtins/unused-declaration/grants.d.ts +3 -0
  66. package/dist/builtins/unused-declaration/grants.js +48 -0
  67. package/dist/builtins/unused-declaration/surfaces.d.ts +3 -0
  68. package/dist/builtins/unused-declaration/surfaces.js +57 -0
  69. package/dist/builtins/unused-declaration/unusedDeclaration.d.ts +2 -0
  70. package/dist/builtins/unused-declaration/unusedDeclaration.js +14 -0
  71. package/dist/cli.d.ts +2 -0
  72. package/dist/cli.js +168 -0
  73. package/dist/config/loadConfig.d.ts +7 -0
  74. package/dist/config/loadConfig.js +53 -0
  75. package/dist/config/toolDigest.d.ts +1 -0
  76. package/dist/config/toolDigest.js +16 -0
  77. package/dist/git/cache.d.ts +3 -0
  78. package/dist/git/cache.js +41 -0
  79. package/dist/git/repository.d.ts +3 -0
  80. package/dist/git/repository.js +76 -0
  81. package/dist/index.d.ts +8 -0
  82. package/dist/index.js +4 -0
  83. package/dist/model/archetype/builder.d.ts +183 -0
  84. package/dist/model/archetype/builder.js +85 -0
  85. package/dist/model/archetype/data.d.ts +92 -0
  86. package/dist/model/archetype/data.js +1 -0
  87. package/dist/model/archetype/draft.d.ts +37 -0
  88. package/dist/model/archetype/draft.js +275 -0
  89. package/dist/model/archetype/reach.d.ts +35 -0
  90. package/dist/model/archetype/reach.js +209 -0
  91. package/dist/model/archetype/references.d.ts +13 -0
  92. package/dist/model/archetype/references.js +166 -0
  93. package/dist/model/archetype/requirements.d.ts +5 -0
  94. package/dist/model/archetype/requirements.js +69 -0
  95. package/dist/model/archetype/resolve.d.ts +30 -0
  96. package/dist/model/archetype/resolve.js +315 -0
  97. package/dist/model/archetype/rulesets.d.ts +4 -0
  98. package/dist/model/archetype/rulesets.js +115 -0
  99. package/dist/model/archetype/settings.d.ts +21 -0
  100. package/dist/model/archetype/settings.js +64 -0
  101. package/dist/model/archetype/shared.d.ts +5 -0
  102. package/dist/model/archetype/shared.js +4 -0
  103. package/dist/model/configError.d.ts +3 -0
  104. package/dist/model/configError.js +3 -0
  105. package/dist/model/facts.d.ts +57 -0
  106. package/dist/model/facts.js +1 -0
  107. package/dist/reporters/agent.d.ts +4 -0
  108. package/dist/reporters/agent.js +24 -0
  109. package/dist/reporters/claudeHook.d.ts +2 -0
  110. package/dist/reporters/claudeHook.js +10 -0
  111. package/dist/reporters/index.d.ts +2 -0
  112. package/dist/reporters/index.js +9 -0
  113. package/dist/reporters/json.d.ts +2 -0
  114. package/dist/reporters/json.js +4 -0
  115. package/dist/reporters/model.d.ts +4 -0
  116. package/dist/reporters/model.js +60 -0
  117. package/dist/reporters/omp.d.ts +2 -0
  118. package/dist/reporters/omp.js +6 -0
  119. package/dist/reporters/reporter.d.ts +22 -0
  120. package/dist/reporters/reporter.js +5 -0
  121. package/dist/reporters/sarif.d.ts +2 -0
  122. package/dist/reporters/sarif.js +44 -0
  123. package/dist/reporters/text.d.ts +8 -0
  124. package/dist/reporters/text.js +39 -0
  125. package/dist/rules/diff.d.ts +10 -0
  126. package/dist/rules/diff.js +31 -0
  127. package/dist/rules/registry.d.ts +5 -0
  128. package/dist/rules/registry.js +33 -0
  129. package/dist/rules/rule.d.ts +59 -0
  130. package/dist/rules/rule.js +18 -0
  131. package/package.json +43 -4
@@ -0,0 +1,315 @@
1
+ import { ConfigError } from '../configError.js';
2
+ export const declarationOf = (config, module) => module.parent && config.archetypes[module.parent.archetype].modules.find((data) => data.name === module.name);
3
+ const placeholders = /\{(\w+)\}/g;
4
+ const join = (dir, name) => (dir === '' ? name : `${dir}/${name}`);
5
+ const parentDir = (path) => path.slice(0, Math.max(path.lastIndexOf('/'), 0));
6
+ const fill = (pattern, captures) => {
7
+ const missing = [...pattern.matchAll(placeholders)].find(([, key]) => !Object.hasOwn(captures, key))?.[1];
8
+ if (missing !== undefined)
9
+ return { missing };
10
+ return { filled: pattern.replace(placeholders, (_, key) => captures[key]) };
11
+ };
12
+ export const fillPattern = (pattern, captures) => {
13
+ const filled = fill(pattern, captures);
14
+ return 'filled' in filled ? filled.filled : undefined;
15
+ };
16
+ export const resolveModel = (config, folders, files) => {
17
+ const resolution = { config, folders, byDir: new Map(), errors: new Set() };
18
+ const root = build(resolution, { dir: '', archetype: config.archetypes[config.root], captures: {} });
19
+ const moduleOf = new Map();
20
+ const tests = new Set();
21
+ const isTest = testMatcher(config.tests);
22
+ for (const file of [...files].sort()) {
23
+ const { module, test } = assign(resolution, file, isTest(file));
24
+ if (test)
25
+ tests.add(file);
26
+ moduleOf.set(file, module);
27
+ }
28
+ if (resolution.errors.size > 0)
29
+ throw new ConfigError([...resolution.errors].join('\n'));
30
+ order(config, root);
31
+ return {
32
+ root,
33
+ modules: [...walk(root)],
34
+ moduleOf: (file) => moduleOf.get(file),
35
+ isTest: (file) => tests.has(file),
36
+ };
37
+ };
38
+ const assign = (resolution, file, entry) => {
39
+ const folder = deepest(resolution.byDir, file);
40
+ const claim = claimOf(resolution, folder, file);
41
+ if (claim) {
42
+ const support = claim.kind === 'dir' ? place(resolution, claim, file, 'tests') : claim;
43
+ if (support.test)
44
+ support.files.push(file);
45
+ else
46
+ claim.tests.push(file);
47
+ return { module: support.test ? support : claim, test: true };
48
+ }
49
+ if (entry) {
50
+ folder.tests.push(file);
51
+ return { module: folder, test: true };
52
+ }
53
+ const module = place(resolution, folder, file, 'all');
54
+ module.files.push(file);
55
+ return { module, test: module.test === true };
56
+ };
57
+ const testMatcher = (patterns = []) => {
58
+ const regexes = patterns.map(globRegex);
59
+ return (file) => regexes.some((regex) => regex.test(file));
60
+ };
61
+ const walk = function* (module) {
62
+ yield module;
63
+ for (const child of module.children)
64
+ yield* walk(child);
65
+ };
66
+ const order = (config, module) => {
67
+ if (module.archetype === undefined)
68
+ return;
69
+ const archetype = config.archetypes[module.archetype];
70
+ const declared = [
71
+ ...archetype.modules.map((data) => data.name),
72
+ ...(archetype.tests?.modules ?? []).map((data) => `tests.${data.name}`),
73
+ ];
74
+ module.children.sort((a, b) => declared.indexOf(a.name) - declared.indexOf(b.name) || a.dir.localeCompare(b.dir));
75
+ for (const child of module.children)
76
+ order(config, child);
77
+ };
78
+ const place = (resolution, folder, file, among) => {
79
+ const archetype = resolution.config.archetypes[folder.archetype];
80
+ const candidates = [
81
+ ...(among === 'all' ? archetype.modules : []),
82
+ ...(archetype.tests?.modules ?? []).map((module) => ({ ...module, name: `tests.${module.name}` })),
83
+ ];
84
+ if (candidates.length === 0 || (among === 'all' && isEntry(archetype, folder, file)))
85
+ return folder;
86
+ const name = filesModule(resolution, folder, archetype, candidates, file);
87
+ if (name === undefined) {
88
+ if (among === 'all' && archetype.modules.length > 0)
89
+ folder.looseFiles.push(file);
90
+ return folder;
91
+ }
92
+ return childModule(folder, name);
93
+ };
94
+ const isEntry = (archetype, folder, file) => {
95
+ const { exposes } = archetype;
96
+ if (exposes?.kind !== 'files' || !exposes.entry)
97
+ return false;
98
+ const path = folder.dir === '' ? file : file.slice(folder.dir.length + 1);
99
+ return exposes.patterns.some((pattern) => {
100
+ const filled = fillPattern(pattern, folder.captures);
101
+ return filled !== undefined && globRegex(filled).test(path);
102
+ });
103
+ };
104
+ const childModule = (folder, name) => {
105
+ const id = `${folder.id}:${name}`;
106
+ let module = folder.children.find((child) => child.id === id);
107
+ if (!module) {
108
+ module = {
109
+ id,
110
+ name,
111
+ kind: 'files',
112
+ dir: folder.dir,
113
+ captures: folder.captures,
114
+ parent: folder,
115
+ children: [],
116
+ files: [],
117
+ looseFiles: [],
118
+ tests: [],
119
+ ...(name.startsWith('tests.') ? { test: true } : {}),
120
+ };
121
+ folder.children.push(module);
122
+ }
123
+ return module;
124
+ };
125
+ const claimOf = (resolution, folder, file) => {
126
+ for (let at = folder; at; at = at.parent) {
127
+ const archetype = resolution.config.archetypes[at.archetype];
128
+ const level = at;
129
+ const claims = [
130
+ ...(locates(level, archetype.tests?.locator, file) ? [level] : []),
131
+ ...archetype.modules
132
+ .filter((declared) => declared.kind === 'files')
133
+ .filter((declared) => locates(level, declared.tests?.locator, file))
134
+ .map((declared) => childModule(level, declared.name)),
135
+ ];
136
+ if (claims.length > 1)
137
+ resolution.errors.add(`${file}: claimed as tests by ${claims.map((claim) => claim.id).join(' and ')}; narrow one of their locators`);
138
+ if (claims.length > 0)
139
+ return claims[0];
140
+ }
141
+ return undefined;
142
+ };
143
+ const locates = (module, locator, file) => {
144
+ if (!locator)
145
+ return false;
146
+ const path = module.dir === '' ? file : file.slice(module.dir.length + 1);
147
+ return locator.patterns.some((pattern) => {
148
+ const filled = fillPattern(pattern, module.captures);
149
+ if (filled === undefined)
150
+ return false;
151
+ return locator.kind === 'dir' ? path.startsWith(`${filled}/`) : globRegex(filled).test(path);
152
+ });
153
+ };
154
+ const pathOf = (module) => module.parent?.name === undefined ? module.name : `${pathOf(module.parent)}.${module.name}`;
155
+ const build = (resolution, { dir, archetype, captures, parent, name }) => {
156
+ const module = {
157
+ id: dir === '' ? '.' : dir,
158
+ ...(name === undefined ? {} : { name }),
159
+ kind: 'dir',
160
+ dir,
161
+ archetype: archetype.name,
162
+ captures,
163
+ ...(parent === undefined ? {} : { parent }),
164
+ children: [],
165
+ files: [],
166
+ looseFiles: [],
167
+ tests: [],
168
+ };
169
+ resolution.byDir.set(dir, module);
170
+ for (const [childDir, claims] of [...claimsIn(resolution, module, archetype)].sort(([a], [b]) => a.localeCompare(b))) {
171
+ const winner = mostSpecific(resolution, archetype, childDir, claims);
172
+ const existing = resolution.byDir.get(childDir);
173
+ if (existing) {
174
+ const found = module.name === undefined ? winner.module.name : `${pathOf(module)}.${winner.module.name}`;
175
+ resolution.errors.add(`${childDir}: found as a module of ${found} and of ${pathOf(existing)}; one folder is one module`);
176
+ continue;
177
+ }
178
+ module.children.push(build(resolution, {
179
+ dir: childDir,
180
+ archetype: winner.archetype,
181
+ captures: winner.captures,
182
+ parent: module,
183
+ name: winner.module.name,
184
+ }));
185
+ }
186
+ return module;
187
+ };
188
+ const claimsIn = (resolution, module, archetype) => {
189
+ const claims = new Map();
190
+ for (const declared of archetype.modules) {
191
+ if (declared.kind !== 'dir')
192
+ continue;
193
+ for (const claim of claimsOf(resolution, module, declared))
194
+ claims.set(claim.dir, [...(claims.get(claim.dir) ?? []), claim]);
195
+ }
196
+ return claims;
197
+ };
198
+ const claimsOf = (resolution, module, declared) => {
199
+ const child = resolution.config.archetypes[declared.archetype];
200
+ return declared.paths.flatMap((path) => matchFolders(resolution.folders, module.dir, path).flatMap((match) => {
201
+ const captures = identify(resolution, child, match.dir, match.captures, module);
202
+ return captures ? [{ module: declared, path, archetype: child, ...match, captures }] : [];
203
+ }));
204
+ };
205
+ const matchFolders = (folders, base, path) => {
206
+ let found = [{ dir: base, captures: {}, rank: [] }];
207
+ for (const segment of path.split('/')) {
208
+ const capture = segment.startsWith('{') ? segment.slice(1, -1) : undefined;
209
+ found = found.flatMap(({ dir, captures, rank }) => folders
210
+ .folders(dir)
211
+ .filter((name) => capture !== undefined || name === segment)
212
+ .map((name) => ({
213
+ dir: join(dir, name),
214
+ captures: capture === undefined ? captures : { ...captures, [capture]: name },
215
+ rank: [...rank, capture === undefined ? 1 : 0],
216
+ })));
217
+ }
218
+ return found;
219
+ };
220
+ const identify = (resolution, archetype, dir, captures, parent) => {
221
+ const how = archetype.identify;
222
+ if (how === undefined)
223
+ return captures;
224
+ if ('match' in how) {
225
+ const matched = how.match(dir, chain(parent));
226
+ return matched === false ? undefined : { ...captures, ...matched };
227
+ }
228
+ const marker = fill(how.marker, captures);
229
+ if ('missing' in marker) {
230
+ resolution.errors.add(`${dir}: ${archetype.name}'s marker '${how.marker}' names {${marker.missing}}, which its dir path doesn't capture`);
231
+ return undefined;
232
+ }
233
+ return resolution.folders.exists(join(dir, marker.filled)) ? captures : undefined;
234
+ };
235
+ const chain = (module) => (module.parent ? [...chain(module.parent), module] : [module]);
236
+ const compareRanks = (a, b) => {
237
+ const index = a.findIndex((value, at) => value !== b[at]);
238
+ return index < 0 ? 0 : a[index] - b[index];
239
+ };
240
+ const mostSpecific = (resolution, archetype, dir, claims) => {
241
+ const best = claims.reduce((top, claim) => (compareRanks(claim.rank, top.rank) > 0 ? claim : top));
242
+ const tied = claims.filter((claim) => claim.module !== best.module && compareRanks(claim.rank, best.rank) === 0);
243
+ if (tied.length > 0) {
244
+ const names = [best, ...tied].map((claim) => `${claim.module.name} ('${claim.path}')`).join(' and ');
245
+ resolution.errors.add(`${dir}: ${archetype.name}'s dir modules ${names} are equally specific; narrow one of the paths`);
246
+ }
247
+ return best;
248
+ };
249
+ const deepest = (byDir, file) => {
250
+ for (let dir = parentDir(file);; dir = parentDir(dir)) {
251
+ const module = byDir.get(dir);
252
+ if (module)
253
+ return module;
254
+ }
255
+ };
256
+ const filesModule = (resolution, module, archetype, candidates, file) => {
257
+ const path = module.dir === '' ? file : file.slice(module.dir.length + 1);
258
+ const matches = [];
259
+ for (const declared of candidates) {
260
+ if (declared.kind !== 'files')
261
+ continue;
262
+ for (const pattern of declared.patterns) {
263
+ const filled = fill(pattern, module.captures);
264
+ if ('missing' in filled) {
265
+ resolution.errors.add(`${module.id}: ${archetype.name}.${declared.name} '${pattern}' names {${filled.missing}}, which ${module.id} doesn't capture`);
266
+ }
267
+ else if (globRegex(filled.filled).test(path))
268
+ matches.push({ module: declared.name, pattern, score: specificity(filled.filled) });
269
+ }
270
+ }
271
+ if (matches.length === 0)
272
+ return undefined;
273
+ const best = matches.reduce((top, match) => (match.score > top.score ? match : top));
274
+ const tied = matches.filter((match) => match.module !== best.module && match.score === best.score);
275
+ if (tied.length > 0)
276
+ resolution.errors.add(`${file}: ${archetype.name}'s ${tie([best, ...tied])}`);
277
+ return best.module;
278
+ };
279
+ const tie = (clash) => {
280
+ const names = clash.map((match) => `${match.module} ('${match.pattern}')`).join(' and ');
281
+ const folders = clash.every((match) => match.pattern.endsWith('/**'));
282
+ const fix = folders ? 'declare the folders with dir(), where the deeper folder wins' : 'narrow one of the patterns';
283
+ return `files modules ${names} are equally specific; ${fix}`;
284
+ };
285
+ export const specificity = (pattern) => {
286
+ if (!pattern.includes('*'))
287
+ return Number.POSITIVE_INFINITY;
288
+ if (pattern === '**')
289
+ return -1;
290
+ return pattern.length - pattern.lastIndexOf('*') - 1;
291
+ };
292
+ const globCache = new Map();
293
+ export const globRegex = (pattern) => {
294
+ const cached = globCache.get(pattern);
295
+ if (cached)
296
+ return cached;
297
+ let source = '';
298
+ for (let at = 0; at < pattern.length; at += 1) {
299
+ if (pattern.startsWith('**/', at)) {
300
+ source += '(?:.*/)?';
301
+ at += 2;
302
+ }
303
+ else if (pattern.startsWith('**', at)) {
304
+ source += '.*';
305
+ at += 1;
306
+ }
307
+ else if (pattern[at] === '*')
308
+ source += '[^/]*';
309
+ else
310
+ source += pattern[at].replace(/[.+?^${}()|[\]\\]/g, '\\$&');
311
+ }
312
+ const regex = new RegExp(`^${source}$`);
313
+ globCache.set(pattern, regex);
314
+ return regex;
315
+ };
@@ -0,0 +1,4 @@
1
+ import type { ConfigData, RuleSettingsData } from './data.ts';
2
+ import { type Fail } from './shared.ts';
3
+ export type ParseRules = (value: unknown, at: string) => RuleSettingsData | undefined;
4
+ export declare const withRuleset: (config: ConfigData, rulesets: unknown, name: string | undefined, parse: ParseRules, fail: Fail) => ConfigData;
@@ -0,0 +1,115 @@
1
+ import { ConfigError } from '../configError.js';
2
+ import { recordedAs } from './builder.js';
3
+ import { isName, isRecord, list } from './shared.js';
4
+ export const withRuleset = (config, rulesets, name, parse, fail) => {
5
+ const named = rulesetsOf(rulesets, fail);
6
+ if (name !== undefined && !named.has(name)) {
7
+ const names = [...named.keys()];
8
+ throw new ConfigError(`no ruleset called ${name}. ${names.length > 0 ? `Rulesets: ${names.join(', ')}` : 'The config declares none'}`);
9
+ }
10
+ const chosen = named.get(name ?? 'default');
11
+ return chosen ? applied(config, layersOf(chosen, named, fail), parse, fail) : config;
12
+ };
13
+ const rulesetsOf = (value, fail) => {
14
+ const named = new Map();
15
+ if (value === undefined)
16
+ return named;
17
+ if (!isRecord(value)) {
18
+ fail('config.rulesets: expected rulesets by name, { default: base, edit }');
19
+ return named;
20
+ }
21
+ for (const [name, ruleset] of Object.entries(value)) {
22
+ const recorded = recordedAs(ruleset, 'ruleset');
23
+ if (recorded)
24
+ named.set(name, recorded);
25
+ else
26
+ fail(`config.rulesets.${name}: expected a ruleset, ruleset().rules(...)`);
27
+ }
28
+ return named;
29
+ };
30
+ const layersOf = (ruleset, named, fail) => {
31
+ const label = (of) => [...named].find(([, candidate]) => candidate === of)?.[0] ?? 'extends';
32
+ const chain = [];
33
+ for (let current = ruleset; current;) {
34
+ chain.unshift(current);
35
+ if (current.base === undefined)
36
+ break;
37
+ const base = recordedAs(current.base, 'ruleset');
38
+ if (!base)
39
+ fail(`rulesets.${label(current)}.extends: expected a ruleset`);
40
+ current = base;
41
+ }
42
+ return chain.flatMap((of) => {
43
+ const at = `rulesets.${label(of)}`;
44
+ return of.entries.map(({ target, settings }) => {
45
+ if (target === undefined)
46
+ return { settings, at: `${at}.rules` };
47
+ const resolved = targetOf(target);
48
+ if (!resolved) {
49
+ fail(`${at}.on: expected an archetype or one of its modules, such as component or component.modules.logic`);
50
+ return { settings: undefined, at };
51
+ }
52
+ const shown = resolved.module === undefined
53
+ ? resolved.archetype
54
+ : `${resolved.archetype.replaceAll('.', '.modules.')}.modules.${resolved.module}`;
55
+ return { target: resolved, settings, at: `${at}.on(${shown})` };
56
+ });
57
+ });
58
+ };
59
+ const targetOf = (value) => {
60
+ const archetype = recordedAs(value, 'archetype');
61
+ if (archetype)
62
+ return isName(archetype.definition.name) ? { archetype: archetype.definition.name } : undefined;
63
+ const handle = recordedAs(value, 'handle');
64
+ return handle && { archetype: handle.archetype, module: handle.module };
65
+ };
66
+ const applied = (config, layers, parse, fail) => {
67
+ let rules = config.rules;
68
+ const archetypes = Object.fromEntries(Object.entries(config.archetypes).map(([name, data]) => [name, { ...data, modules: [...data.modules] }]));
69
+ for (const { target, settings, at } of layers) {
70
+ const layer = parse(settings, at);
71
+ if (!target) {
72
+ rules = merged(rules, layer);
73
+ continue;
74
+ }
75
+ const archetype = archetypes[target.archetype];
76
+ if (!archetype) {
77
+ fail(`${at}: ${target.archetype} is not in the config`);
78
+ continue;
79
+ }
80
+ applyTo(archetype, target.module, layer, at, fail);
81
+ }
82
+ return rules === undefined ? { ...config, archetypes } : { ...config, archetypes, rules };
83
+ };
84
+ const applyTo = (archetype, module, layer, at, fail) => {
85
+ if (module === undefined) {
86
+ archetype.rules = merged(archetype.rules, layer);
87
+ return;
88
+ }
89
+ if (module === 'tests') {
90
+ if (archetype.tests)
91
+ archetype.tests = { ...archetype.tests, rules: merged(archetype.tests.rules, layer) };
92
+ else
93
+ fail(`${at}: ${archetype.name} has no test layer`);
94
+ return;
95
+ }
96
+ const index = archetype.modules.findIndex((declared) => declared.name === module);
97
+ if (index < 0)
98
+ fail(`${at}: ${archetype.name} has modules ${list(archetype.modules.map((declared) => declared.name), 'none')}`);
99
+ else
100
+ archetype.modules[index] = { ...archetype.modules[index], rules: merged(archetype.modules[index].rules, layer) };
101
+ };
102
+ const merged = (base, layer) => {
103
+ if (layer === undefined)
104
+ return base;
105
+ if (layer === 'off')
106
+ return 'off';
107
+ const result = base === 'off' ? { '*': false } : { ...base };
108
+ for (const [id, setting] of Object.entries(layer)) {
109
+ const was = result[id];
110
+ if (setting === true && isRecord(was))
111
+ continue;
112
+ result[id] = isRecord(setting) && isRecord(was) ? { ...was, ...setting } : setting;
113
+ }
114
+ return result;
115
+ };
@@ -0,0 +1,21 @@
1
+ import type { ConfigData } from './data.ts';
2
+ import { type Model, type ModuleView } from './resolve.ts';
3
+ export interface RuleAt {
4
+ on: boolean;
5
+ options: Record<string, unknown>;
6
+ }
7
+ export interface Settings {
8
+ atFile(file: string, id: string, defaults?: object): RuleAt;
9
+ atModule(module: ModuleView, id: string, defaults?: object): RuleAt;
10
+ decidedAt(module: ModuleView, id: string): boolean | undefined;
11
+ }
12
+ export declare const settings: (config: ConfigData, model: Model) => Settings;
13
+ export type ResolvedRules = Record<string, false | Record<string, unknown>>;
14
+ export interface RulesOf {
15
+ defaults: ResolvedRules;
16
+ module(module: ModuleView): ResolvedRules;
17
+ }
18
+ export declare const rulesOf: (config: ConfigData, model: Model, rules: readonly {
19
+ id: string;
20
+ defaults?: object;
21
+ }[]) => RulesOf;
@@ -0,0 +1,64 @@
1
+ import { declarationOf } from './resolve.js';
2
+ import { isRecord } from './shared.js';
3
+ const layerOf = (config, module) => {
4
+ if (module.archetype !== undefined)
5
+ return config.archetypes[module.archetype].tests;
6
+ const declared = declarationOf(config, module);
7
+ return declared?.kind === 'files' ? declared.tests : undefined;
8
+ };
9
+ const own = (config, module) => [
10
+ declarationOf(config, module)?.rules,
11
+ module.archetype === undefined ? undefined : config.archetypes[module.archetype].rules,
12
+ ];
13
+ const testModuleRules = (config, module) => layerOf(config, module.parent)?.modules.find((data) => `tests.${data.name}` === module.name)?.rules;
14
+ const levels = (config, module) => {
15
+ if (module.test)
16
+ return [testModuleRules(config, module), ...testLevels(config, module.parent)];
17
+ return [...own(config, module), ...(module.parent ? levels(config, module.parent) : [config.rules])];
18
+ };
19
+ const testLevels = (config, owner) => [
20
+ layerOf(config, owner)?.rules,
21
+ ...own(config, owner),
22
+ ...(owner.parent ? testLevels(config, owner.parent) : [config.rules]),
23
+ ];
24
+ export const settings = (config, model) => {
25
+ const fileLevels = (file) => {
26
+ const module = model.moduleOf(file);
27
+ if (!module)
28
+ return [config.rules];
29
+ return model.isTest(file) && !module.test ? testLevels(config, module) : levels(config, module);
30
+ };
31
+ return {
32
+ atFile: (file, id, defaults) => ruleAt(fileLevels(file), id, defaults),
33
+ atModule: (module, id, defaults) => ruleAt(levels(config, module), id, defaults),
34
+ decidedAt: (module, id) => decided(levels(config, module), id),
35
+ };
36
+ };
37
+ const decision = (level, id) => {
38
+ if (level === undefined)
39
+ return undefined;
40
+ if (level === 'off')
41
+ return false;
42
+ if (Object.hasOwn(level, id))
43
+ return level[id] !== false;
44
+ return level['*'];
45
+ };
46
+ const optionsAt = (level, id) => {
47
+ const setting = typeof level === 'object' ? level[id] : undefined;
48
+ return isRecord(setting) ? setting : undefined;
49
+ };
50
+ const decided = (levels, id) => levels.map((level) => decision(level, id)).find((said) => said !== undefined);
51
+ const ruleAt = (levels, id, defaults = {}) => ({
52
+ on: decided(levels, id) ?? true,
53
+ options: Object.assign({}, defaults, ...levels.map((level) => optionsAt(level, id)).reverse()),
54
+ });
55
+ export const rulesOf = (config, model, rules) => {
56
+ const settled = settings(config, model);
57
+ return {
58
+ defaults: Object.fromEntries(rules.map(({ id, defaults }) => [id, { ...defaults }])),
59
+ module: (module) => Object.fromEntries(rules.map(({ id, defaults }) => {
60
+ const { on, options } = settled.atModule(module, id, defaults);
61
+ return [id, on ? options : false];
62
+ })),
63
+ };
64
+ };
@@ -0,0 +1,5 @@
1
+ export type Fail = (message: string) => void;
2
+ export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
3
+ export declare const isName: (value: unknown) => value is string;
4
+ export declare const list: (items: readonly string[], none: string) => string;
5
+ export declare const defined: <T extends object>(object: T) => T;
@@ -0,0 +1,4 @@
1
+ export const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2
+ export const isName = (value) => typeof value === 'string' && value !== '';
3
+ export const list = (items, none) => (items.length > 0 ? items.join(', ') : none);
4
+ export const defined = (object) => Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
@@ -0,0 +1,3 @@
1
+ export declare class ConfigError extends Error {
2
+ name: string;
3
+ }
@@ -0,0 +1,3 @@
1
+ export class ConfigError extends Error {
2
+ name = 'ConfigError';
3
+ }
@@ -0,0 +1,57 @@
1
+ export interface Project {
2
+ files: FileFacts[];
3
+ }
4
+ export interface FileFacts {
5
+ path: string;
6
+ lines: number;
7
+ imports: ImportEdge[];
8
+ externals: ExternalImport[];
9
+ members: MemberGraph;
10
+ functions: FunctionFacts[];
11
+ }
12
+ export interface ImportEdge {
13
+ from: string;
14
+ to: string;
15
+ via?: string;
16
+ specifier: string;
17
+ names: string[];
18
+ typeOnly: boolean;
19
+ reExport?: true;
20
+ line: number;
21
+ }
22
+ export interface ExternalImport {
23
+ from: string;
24
+ package: string;
25
+ specifier: string;
26
+ names: string[];
27
+ typeOnly: boolean;
28
+ reExport?: true;
29
+ line: number;
30
+ }
31
+ export type MemberKind = 'function' | 'class' | 'state' | 'type' | 'code';
32
+ export interface Member {
33
+ name: string;
34
+ kind: MemberKind;
35
+ line: number;
36
+ endLine: number;
37
+ }
38
+ export interface MemberGraph {
39
+ members: Member[];
40
+ links: [number, number][];
41
+ }
42
+ export interface FunctionFacts {
43
+ name: string;
44
+ line: number;
45
+ endLine: number;
46
+ lines: number;
47
+ statements: MemberGraph;
48
+ complexity?: Complexity;
49
+ }
50
+ export interface Complexity {
51
+ total: number;
52
+ increments: {
53
+ line: number;
54
+ amount: number;
55
+ reason: string;
56
+ }[];
57
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import { type Report } from './reporter.ts';
2
+ export declare const shownFindings = 20;
3
+ export declare const shownChars = 500;
4
+ export declare const agentContext: (report: Report) => string;
@@ -0,0 +1,24 @@
1
+ import { actionable, ruleDocs } from './reporter.js';
2
+ import { diffLines, diffSummary, line } from './text.js';
3
+ export const shownFindings = 20;
4
+ export const shownChars = 500;
5
+ export const agentContext = (report) => {
6
+ const body = report.mode === 'diff'
7
+ ? [
8
+ 'New or worse architecture fitness findings. Address them if this edit caused them:',
9
+ ...shown(diffLines(report.delta)),
10
+ '',
11
+ diffSummary(report.delta),
12
+ ]
13
+ : ['Architecture fitness findings:', ...shown(report.findings.map(line))];
14
+ const docs = ruleDocs(actionable(report));
15
+ return [
16
+ ...body,
17
+ ...(docs.length === 0 ? [] : ['', 'Rule docs:', ...docs.map(([rule, url]) => `- ${rule}: ${url}`)]),
18
+ ].join('\n');
19
+ };
20
+ const shown = (lines) => [
21
+ ...lines.slice(0, shownFindings).map(clipped),
22
+ ...(lines.length > shownFindings ? [`...and ${lines.length - shownFindings} more, not shown here.`] : []),
23
+ ];
24
+ const clipped = (text) => (text.length > shownChars ? `${text.slice(0, shownChars)}...` : text);
@@ -0,0 +1,2 @@
1
+ import { type Reporter } from './reporter.ts';
2
+ export declare const claudeHookReporter: Reporter;
@@ -0,0 +1,10 @@
1
+ import { actionable, unavailable } from './reporter.js';
2
+ import { agentContext } from './agent.js';
3
+ const warnWithoutBlocking = 1;
4
+ const response = (additionalContext) => JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext } });
5
+ export const claudeHookReporter = {
6
+ id: 'claude-hook',
7
+ render: (report) => (actionable(report).length === 0 ? '' : response(agentContext(report))),
8
+ renderFailure: (problem) => response(unavailable(problem)),
9
+ failureExitCode: warnWithoutBlocking,
10
+ };
@@ -0,0 +1,2 @@
1
+ import type { Reporter } from './reporter.ts';
2
+ export declare const reporters: ReadonlyMap<string, Reporter>;
@@ -0,0 +1,9 @@
1
+ import { claudeHookReporter } from './claudeHook.js';
2
+ import { jsonReporter } from './json.js';
3
+ import { ompReporter } from './omp.js';
4
+ import { sarifReporter } from './sarif.js';
5
+ import { textReporter } from './text.js';
6
+ export const reporters = new Map([textReporter, jsonReporter, claudeHookReporter, ompReporter, sarifReporter].map((reporter) => [
7
+ reporter.id,
8
+ reporter,
9
+ ]));
@@ -0,0 +1,2 @@
1
+ import type { Reporter } from './reporter.ts';
2
+ export declare const jsonReporter: Reporter;