@hublo/sentinel 1.7.0-alpha.3 → 1.7.0-alpha.31

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 (70) hide show
  1. package/README.md +4 -0
  2. package/dist/bin/sentinel.js +95 -82
  3. package/dist/chunk-2DUG6GVU.js +19301 -0
  4. package/dist/chunk-F5WISUN3.js +17 -0
  5. package/dist/chunk-F5WISUN3.js.map +1 -0
  6. package/dist/{chunk-P6KTBQ2Q.js → chunk-FZLUCPST.js} +24 -15
  7. package/dist/{chunk-ZNANJEMK.js → chunk-KKHKRY7P.js} +40 -16
  8. package/dist/chunk-KKHKRY7P.js.map +1 -0
  9. package/dist/chunk-NE3IEJBN.js +59 -0
  10. package/dist/chunk-NE3IEJBN.js.map +1 -0
  11. package/dist/chunk-NGLEGAEN.js +190 -0
  12. package/dist/chunk-NGLEGAEN.js.map +1 -0
  13. package/dist/chunk-PXTU5MPW.js +9 -0
  14. package/dist/chunk-PXTU5MPW.js.map +1 -0
  15. package/dist/{chunk-4YQXLPJ5.js → chunk-QMIJ4ZGJ.js} +2 -2
  16. package/dist/chunk-TMVKYXZ3.js +18 -0
  17. package/dist/chunk-TMVKYXZ3.js.map +1 -0
  18. package/dist/chunk-U7G2Y6YC.js +15 -0
  19. package/dist/chunk-U7G2Y6YC.js.map +1 -0
  20. package/dist/chunk-VWASE6NN.js +34 -0
  21. package/dist/chunk-VWASE6NN.js.map +1 -0
  22. package/dist/{chunk-THTXP2QU.js → chunk-XMAXE2Q2.js} +10 -7
  23. package/dist/chunk-XMAXE2Q2.js.map +1 -0
  24. package/dist/chunk-XYOIXC6A.js +126 -0
  25. package/dist/chunk-XYOIXC6A.js.map +1 -0
  26. package/dist/chunk-ZZMYV576.js +297 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +14 -5
  29. package/dist/{migrate-NWQ3LYER.js → migrate-X7PB2X7R.js} +237 -228
  30. package/dist/roles/arch/config.d.ts +25 -0
  31. package/dist/roles/arch/config.js +8 -0
  32. package/dist/roles/arch/config.js.map +1 -0
  33. package/dist/roles/build/nest/toolchain.js +3 -3
  34. package/dist/roles/code-churn/config.d.ts +92 -0
  35. package/dist/roles/code-churn/config.js +10 -0
  36. package/dist/roles/code-churn/config.js.map +1 -0
  37. package/dist/roles/runtime-analysis/config.d.ts +97 -0
  38. package/dist/roles/runtime-analysis/config.js +10 -0
  39. package/dist/roles/runtime-analysis/config.js.map +1 -0
  40. package/dist/roles/runtime-analysis/gateway.d.ts +2 -0
  41. package/dist/roles/runtime-analysis/gateway.js +89 -0
  42. package/dist/roles/runtime-analysis/gateway.js.map +1 -0
  43. package/dist/roles/runtime-analysis/mock-api.d.ts +2 -0
  44. package/dist/roles/runtime-analysis/mock-api.js +43 -0
  45. package/dist/roles/runtime-analysis/mock-api.js.map +1 -0
  46. package/dist/roles/sql/config.d.ts +68 -0
  47. package/dist/roles/sql/config.js +8 -0
  48. package/dist/roles/sql/config.js.map +1 -0
  49. package/dist/roles/static-analysis/config.js +2 -1
  50. package/dist/roles/test/setup/file-boundary.js +3 -3
  51. package/dist/roles/test/setup/jest-parity.js +4 -4
  52. package/dist/roles/test/setup/workspace-entry.js +2 -2
  53. package/dist/{validate-4V3EGTXN.js → validate-GTBRD2M4.js} +2 -2
  54. package/docs/arch-adoption.md +201 -0
  55. package/docs/code-churn-adoption.md +237 -0
  56. package/docs/runtime-analysis-adoption.md +198 -0
  57. package/docs/sql-adoption.md +598 -0
  58. package/docs/static-analysis-adoption.md +1 -1
  59. package/docs/static-analysis-study.md +49 -10
  60. package/docs/typescript-adoption.md +47 -6
  61. package/docs/typescript-traces.md +512 -8
  62. package/docs/using-sentinel.md +4 -2
  63. package/package.json +25 -2
  64. package/runtime-analysis-deps/load.mjs +6 -0
  65. package/runtime-analysis-deps/package-lock.json +1766 -0
  66. package/runtime-analysis-deps/package.json +11 -0
  67. package/dist/chunk-F6ART7RH.js +0 -9555
  68. package/dist/chunk-THTXP2QU.js.map +0 -1
  69. package/dist/chunk-ZNANJEMK.js.map +0 -1
  70. /package/dist/{chunk-4YQXLPJ5.js.map → chunk-QMIJ4ZGJ.js.map} +0 -0
@@ -0,0 +1,9 @@
1
+ // src/shared/deep-merge.ts
2
+ function isPlainObject(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+
6
+ export {
7
+ isPlainObject
8
+ };
9
+ //# sourceMappingURL=chunk-PXTU5MPW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/deep-merge.ts"],"sourcesContent":["/**\n * Is this a plain JSON object?\n *\n * The file is named for a `deepMerge` that no longer exists. It was written when the engine\n * merged JSON in memory and wrote the result; that approach was replaced by editing the\n * document IN PLACE with jsonc-parser, so a project's comments, key order and formatting\n * survive a `merge-json` op. Nothing has called `deepMerge` since, except its own recursion,\n * so it went.\n *\n * What remains is the predicate the in-place merge still needs, to decide whether a value is\n * a branch to walk into or a leaf to set.\n */\n\n/** True for a mergeable plain object (not null, not an array). */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";AAcO,SAAS,cAAc,OAAkD;AAC9E,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-ELZHIN6E.js";
4
4
  import {
5
5
  findWorkspaceRoot
6
- } from "./chunk-ZNANJEMK.js";
6
+ } from "./chunk-KKHKRY7P.js";
7
7
 
8
8
  // src/roles/test/setup/workspace.ts
9
9
  function isMissingModule(error) {
@@ -60,4 +60,4 @@ export {
60
60
  installWorkspaceSetup,
61
61
  pinWorkspaceTimezone
62
62
  };
63
- //# sourceMappingURL=chunk-4YQXLPJ5.js.map
63
+ //# sourceMappingURL=chunk-QMIJ4ZGJ.js.map
@@ -0,0 +1,18 @@
1
+ import {
2
+ isPlainObject
3
+ } from "./chunk-PXTU5MPW.js";
4
+
5
+ // src/roles/arch/configs/define.ts
6
+ function defineArch(input = {}) {
7
+ const severity = isPlainObject(input.overrides?.severity) ? { ...input.overrides?.severity } : {};
8
+ return {
9
+ root: input.root ?? null,
10
+ severity,
11
+ moved: Object.keys(severity).map((rule) => `severity.${rule}`).sort()
12
+ };
13
+ }
14
+
15
+ export {
16
+ defineArch
17
+ };
18
+ //# sourceMappingURL=chunk-TMVKYXZ3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/arch/configs/define.ts"],"sourcesContent":["/**\n * `defineArch`: what a module imports to declare its own architecture settings.\n *\n * ```js\n * // arch.config.mjs\n * import { defineArch } from '@hublo/sentinel/arch'\n *\n * export default defineArch({\n * root: import.meta.dirname,\n * overrides: { severity: { G3: 'warn' } },\n * })\n * ```\n *\n * The shape of `defineStaticAnalysis` and `defineSql`, as CONTRIBUTING asks of every analysis role.\n * Which decision applies is not here: the repository's map says it, so a module cannot point\n * itself at another rule set. What a module may move is how hard each rule bites in it.\n *\n * `overrides` REPLACES what it names, and every path it sets lands in `moved`, so the report says\n * a level is the module's own and not the decision's.\n */\nimport { isPlainObject } from '../../../shared/deep-merge.js'\n\n/** A rule's level in one module: `off` skips it, which no rule set may say. */\nexport type ModuleSeverity = 'error' | 'warn' | 'off'\n\n/** What a module may move. */\nexport interface ArchOverrides {\n /** A level per rule, by the rule's name in the decision's rule set. */\n severity?: Record<string, ModuleSeverity>\n}\n\n/** What a module's config file passes. Everything is optional, including the file itself. */\nexport interface ArchInput {\n /** The module's own directory, normally `import.meta.dirname`. */\n root?: string\n overrides?: ArchOverrides\n}\n\nexport interface ResolvedArchConfig {\n /** The module's directory, or null when its config file did not say. */\n root: string | null\n /** The levels the module set, by rule. The others come from the map, then the rule set. */\n severity: Record<string, ModuleSeverity>\n /** Dotted paths the module set through `overrides`, sorted so two runs print the same report. */\n moved: string[]\n}\n\n/** Resolve a module's declaration. */\nexport function defineArch(input: ArchInput = {}): ResolvedArchConfig {\n const severity = isPlainObject(input.overrides?.severity)\n ? { ...(input.overrides?.severity as Record<string, ModuleSeverity>) }\n : {}\n return {\n root: input.root ?? null,\n severity,\n moved: Object.keys(severity)\n .map((rule) => `severity.${rule}`)\n .sort(),\n }\n}\n"],"mappings":";;;;;AAgDO,SAAS,WAAW,QAAmB,CAAC,GAAuB;AACpE,QAAM,WAAW,cAAc,MAAM,WAAW,QAAQ,IACpD,EAAE,GAAI,MAAM,WAAW,SAA4C,IACnE,CAAC;AACL,SAAO;AAAA,IACL,MAAM,MAAM,QAAQ;AAAA,IACpB;AAAA,IACA,OAAO,OAAO,KAAK,QAAQ,EACxB,IAAI,CAAC,SAAS,YAAY,IAAI,EAAE,EAChC,KAAK;AAAA,EACV;AACF;","names":[]}
@@ -0,0 +1,15 @@
1
+ import {
2
+ defaults
3
+ } from "./chunk-F5WISUN3.js";
4
+
5
+ // src/roles/runtime-analysis/config/define.ts
6
+ var DEFAULT_LOCALE = defaults.locale;
7
+ function defineRuntimeAnalysis(input) {
8
+ return { ...input, defined: true };
9
+ }
10
+
11
+ export {
12
+ DEFAULT_LOCALE,
13
+ defineRuntimeAnalysis
14
+ };
15
+ //# sourceMappingURL=chunk-U7G2Y6YC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/runtime-analysis/config/define.ts"],"sourcesContent":["/**\n * `defineRuntimeAnalysis`: what a front imports to declare how its Core Web Vitals are measured.\n *\n * ```js\n * // runtime-analysis.config.mjs, at the front's root\n * import { defineRuntimeAnalysis } from '@hublo/sentinel/runtime-analysis'\n *\n * export default defineRuntimeAnalysis({\n * root: import.meta.dirname,\n * basePath: '/admin',\n * health: '/admin/api/health',\n * ready: '/bff-admin/session',\n * build: { output: '.output', server: '.output/server/index.mjs', env: { VITE_API: '{origin}/api' } },\n * api: [{ path: '/bff-admin/session', file: 'runtime-analysis/api/session.json' }],\n * router: { tsconfig: 'tsconfig.app.json', shell: ['src/router.tsx'], routes: 'src/routes' },\n * screens: [{ id: 'home', route: 'index.tsx', path: '/admin', expectText: ['Home'], interact: { click: 'nav a' } }],\n * })\n * ```\n *\n * The same shape as the monorepo harness's `cwv.json` (hublo/monorepo#23672), moved into each\n * front as the other roles' configs are: the data is the repository's, the measure is sentinel's.\n * Two keys go: `name`, which is the module's own, and `root`'s meaning, which is now the module's\n * directory instead of its path in one repository. Every path in it is relative to the front.\n *\n * Validated before anything is built (`checks.ts`), so a mistake costs seconds and names its field\n * instead of a red measure twenty minutes later.\n */\nimport { defaults } from '../preset-data.js'\n\nimport type { ApiEntry } from './api.js'\n\n/** The one interaction a screen's flow performs, timed for INP. */\nexport type Interaction =\n | { click: string }\n | { clickText: string }\n | { type: { selector: string; text: string } }\n\n/** A screen measured: the route that renders it, the path opened, and what proves it opened. */\nexport interface Screen {\n id: string\n /** The route file, relative to `router.routes`: a change to what it loads measures it. */\n route: string\n /** The path opened, starting with `/`. */\n path: string\n /** Texts the screen shows once opened: each must be visible before the figures count. */\n expectText: string[]\n interact: Interaction\n /** Rows the screen must list once opened, by count or at least a minimum. */\n rows?: { selector: string; count?: number; min?: number }\n /** An element that must be there once opened. */\n expectSelector?: string\n /**\n * This screen's own ready call, when it does not make the front's: console's institution screens\n * and its client page share no BFF call. Checked like the front's, answered by the mocks with 200.\n */\n ready?: string\n}\n\n/** What a front's config file passes to `defineRuntimeAnalysis`. */\nexport interface RuntimeAnalysisInput {\n /** The front's own directory, normally `import.meta.dirname`. */\n root?: string\n /** The path the app is served under: the rest goes to the mocks. Or `mockPrefixes`, not both. */\n basePath?: string\n /** The paths sent to the mocks, for an app served at the root. Or `basePath`, not both. */\n mockPrefixes?: string[]\n /** The app's health path, answered once it is up. */\n health: string\n /** The call that tells the app is ready (a session): answered by the mocks, with 200. */\n ready: string\n build: {\n /** The build output, relative to the front. */\n output: string\n /** The server the output starts with (`node <server>`, `HOST` and `PORT` set). */\n server: string\n /** The build variables; `{origin}` is the gateway the build is served behind. */\n env: Record<string, string>\n }\n /** The answers of the calls the screens make. */\n api: ApiEntry[]\n router: {\n /** The tsconfig the route imports are resolved with. */\n tsconfig: string\n /** The app shell files every screen loads. */\n shell: string[]\n /** The file routes directory (TanStack Router), holding `__root.tsx`. */\n routes: string\n }\n screens: Screen[]\n /**\n * The translations folder, relative to the front, holding `<lang>/<namespace>.json`: a change\n * to one measures the screens whose code names its namespace, not every screen.\n */\n translations?: string\n /**\n * The browser's language, as the screens' expected texts are written (`fr-FR`): a front that\n * picks its language from the browser otherwise renders the runner's. `en-US` when left out.\n */\n locale?: string\n}\n\n/** The browser language when a config names none. */\nexport const DEFAULT_LOCALE = defaults.locale\n\n/** The config as sentinel reads it: what the module passed, marked as defined here. */\nexport type RuntimeAnalysisConfig = RuntimeAnalysisInput & { readonly defined: true }\n\nexport function defineRuntimeAnalysis(input: RuntimeAnalysisInput): RuntimeAnalysisConfig {\n return { ...input, defined: true }\n}\n"],"mappings":";;;;;AAsGO,IAAM,iBAAiB,SAAS;AAKhC,SAAS,sBAAsB,OAAoD;AACxF,SAAO,EAAE,GAAG,OAAO,SAAS,KAAK;AACnC;","names":[]}
@@ -0,0 +1,34 @@
1
+ import {
2
+ defaults
3
+ } from "./chunk-F5WISUN3.js";
4
+
5
+ // src/roles/runtime-analysis/config/resolve.ts
6
+ import { existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+ var RUNTIME_CONFIG_FILE = defaults.configFile;
10
+ async function loadRuntimeConfig(cwd) {
11
+ const path = join(cwd, RUNTIME_CONFIG_FILE);
12
+ if (!existsSync(path)) return { adopted: false };
13
+ try {
14
+ const loaded = await import(pathToFileURL(path).href);
15
+ const exported = loaded.default;
16
+ if (exported === null || typeof exported !== "object")
17
+ return { adopted: true, unreadable: `${RUNTIME_CONFIG_FILE} exports no config` };
18
+ return {
19
+ adopted: true,
20
+ config: { ...exported, defined: true }
21
+ };
22
+ } catch (error) {
23
+ return {
24
+ adopted: true,
25
+ unreadable: `${RUNTIME_CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`
26
+ };
27
+ }
28
+ }
29
+
30
+ export {
31
+ RUNTIME_CONFIG_FILE,
32
+ loadRuntimeConfig
33
+ };
34
+ //# sourceMappingURL=chunk-VWASE6NN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/runtime-analysis/config/resolve.ts"],"sourcesContent":["/**\n * Read a front's `runtime-analysis.config.mjs`. A `.mjs` for the reason the static analysis role\n * gives: sentinel needs its values, and Node imports it with no transpiler.\n *\n * Unlike static analysis, there are no defaults to fall back to: the screens, the mocks and the\n * build are the front's own, so a front with no file is not adopted, and a file that cannot be\n * loaded is reported, never measured around.\n */\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { defaults } from '../preset-data.js'\n\nimport type { RuntimeAnalysisConfig } from './define.js'\n\n/** The file a front writes, at its root. Written by `--init`. */\nexport const RUNTIME_CONFIG_FILE = defaults.configFile\n\nexport type RuntimeConfigLoad =\n | { adopted: false }\n | { adopted: true; config: RuntimeAnalysisConfig }\n | { adopted: true; unreadable: string }\n\nexport async function loadRuntimeConfig(cwd: string): Promise<RuntimeConfigLoad> {\n const path = join(cwd, RUNTIME_CONFIG_FILE)\n if (!existsSync(path)) return { adopted: false }\n try {\n const loaded = (await import(pathToFileURL(path).href)) as { default?: unknown }\n const exported = loaded.default\n if (exported === null || typeof exported !== 'object')\n return { adopted: true, unreadable: `${RUNTIME_CONFIG_FILE} exports no config` }\n // An object written without `defineRuntimeAnalysis` is read the same: the checks decide.\n return {\n adopted: true,\n config: { ...(exported as object), defined: true } as RuntimeAnalysisConfig,\n }\n } catch (error) {\n return {\n adopted: true,\n unreadable: `${RUNTIME_CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n}\n"],"mappings":";;;;;AAQA,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,qBAAqB;AAOvB,IAAM,sBAAsB,SAAS;AAO5C,eAAsB,kBAAkB,KAAyC;AAC/E,QAAM,OAAO,KAAK,KAAK,mBAAmB;AAC1C,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,EAAE,SAAS,MAAM;AAC/C,MAAI;AACF,UAAM,SAAU,MAAM,OAAO,cAAc,IAAI,EAAE;AACjD,UAAM,WAAW,OAAO;AACxB,QAAI,aAAa,QAAQ,OAAO,aAAa;AAC3C,aAAO,EAAE,SAAS,MAAM,YAAY,GAAG,mBAAmB,qBAAqB;AAEjF,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ,EAAE,GAAI,UAAqB,SAAS,KAAK;AAAA,IACnD;AAAA,EACF,SAAS,OAAO;AACd,WAAO;AAAA,MACL,SAAS;AAAA,MACT,YAAY,GAAG,mBAAmB,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAC/F;AAAA,EACF;AACF;","names":[]}
@@ -1,7 +1,6 @@
1
- // src/shared/deep-merge.ts
2
- function isPlainObject(value) {
3
- return typeof value === "object" && value !== null && !Array.isArray(value);
4
- }
1
+ import {
2
+ isPlainObject
3
+ } from "./chunk-PXTU5MPW.js";
5
4
 
6
5
  // src/core/domain.ts
7
6
  var VERBS = ["run", "inspect", "init", "migrate", "validate", "report", "status"];
@@ -13,14 +12,18 @@ var TARGETS = [
13
12
  "dev",
14
13
  "test",
15
14
  "static-analysis",
15
+ "sql",
16
+ "code-churn",
16
17
  "env",
17
18
  "runtime-analysis",
18
19
  "arch"
19
20
  ];
20
21
  var REPOSITORY_TARGETS = ["env"];
21
22
  var LONG_RUNNING_TARGETS = ["dev"];
23
+ var ON_DEMAND_TARGETS = ["runtime-analysis"];
24
+ var STDOUT_PHASE_TARGETS = ["runtime-analysis"];
22
25
  var SWEEPABLE_TARGETS = TARGETS.filter(
23
- (target) => !LONG_RUNNING_TARGETS.includes(target)
26
+ (target) => !LONG_RUNNING_TARGETS.includes(target) && !ON_DEMAND_TARGETS.includes(target)
24
27
  );
25
28
  var PRESET_NAMES = ["react", "nest", "svelte", "node", "tools"];
26
29
  var OUTPUT_SHAPES = ["console", "json", "html", "markdown"];
@@ -203,12 +206,12 @@ export {
203
206
  TARGETS,
204
207
  REPOSITORY_TARGETS,
205
208
  LONG_RUNNING_TARGETS,
209
+ STDOUT_PHASE_TARGETS,
206
210
  SWEEPABLE_TARGETS,
207
211
  PRESET_NAMES,
208
212
  OUTPUT_SHAPES,
209
213
  ENV_LEVELS,
210
214
  DEFAULT_ENV_LEVEL,
211
- isPlainObject,
212
215
  REPORT_DIR,
213
216
  TARGET,
214
217
  SHAPES,
@@ -218,4 +221,4 @@ export {
218
221
  overridableSettings,
219
222
  defineStaticAnalysis
220
223
  };
221
- //# sourceMappingURL=chunk-THTXP2QU.js.map
224
+ //# sourceMappingURL=chunk-XMAXE2Q2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/domain.ts","../src/roles/static-analysis/presets/shared.json","../src/roles/static-analysis/preset-data.ts","../src/roles/static-analysis/configs/define.ts"],"sourcesContent":["/**\n * The domain vocabulary: the fixed sets of verbs, targets, and presets, and the\n * types derived from them. This is the model, and the extension point: adding a\n * verb / target / preset is a one-line edit to a list here, and because the types\n * are DERIVED (`(typeof LIST)[number]`), the compiler forces every switch/handler\n * to cover the new member.\n *\n * Tunable behaviour (defaults, detection signals, marker filenames) lives in\n * `settings.ts`, not here.\n */\n\n/**\n * Verbs: what to do.\n *\n * The axis is not \"who runs it\" but **what survives the run**, which is the distinction that\n * outlives any sharing of the work:\n *\n * | verb | writes | what remains |\n * | --- | --- | --- |\n * | `init` | a module's config + the workspace prep it needs | the module's new state, that IS the deliverable |\n * | `migrate` | changes an already-initialized setup | same; `--typescript` detaches the module from `tsconfig.base.json` (sentinel#147) |\n * | `validate` | instrumentation, if it needs any | **nothing**, the project returns to what it was |\n * | `run` / `inspect` / `report` / `status` | nothing | they execute or introspect |\n *\n * `validate` is the one that judges. Héla, 2026-09-25: it does not carry the migration's\n * strictness, so it MAY write into the project under validation, a `data-testid` to make something\n * addressable for instance, provided it takes it back out. That freedom is what makes its\n * dependability the thing to design: idempotent, reversible on error, recoverable after a kill,\n * and never silent about instrumentation it failed to remove.\n */\nexport const VERBS = ['run', 'inspect', 'init', 'migrate', 'validate', 'report', 'status'] as const\nexport type Verb = (typeof VERBS)[number]\n\n/** Targets: the kind of check. The CLI `--<target>` flags map 1:1 to these. */\nexport const TARGETS = [\n 'lint',\n 'format',\n 'typescript',\n 'build',\n 'dev',\n 'test',\n 'static-analysis',\n 'sql',\n 'code-churn',\n 'env',\n 'runtime-analysis',\n 'arch',\n] as const\nexport type Target = (typeof TARGETS)[number]\n\n/**\n * Targets that check the REPOSITORY, not a module, and therefore run once, at its root.\n *\n * Every other target is a question about one module, so the engine asks it per module. `env` is a\n * question about the repository as a whole: which env files git tracks, which contract declares a\n * variable the code reads in another app, whether a Dockerfile copies a path that exists. Asked per\n * module, it would scan the same tree 441 times on the monorepo and report every finding 441 times,\n * and in a repository that is not an nx workspace there are no modules to ask at all.\n *\n * So the location rule is different, and it is the only difference:\n *\n * - it runs from the repository ROOT, the git top-level, found by git and never by nx;\n * - a sweep (`sentinel --run`) includes it once, and only when run from that root, so a sweep inside\n * a module stays about the module and its output does not change;\n * - named from anywhere else, it is REFUSED with the root's path, rather than scoped to a\n * subdirectory: a contract in one app and a reader in another is exactly the finding a scoped\n * scan cannot see, so a scoped report would be a smaller report that looks like a clean one.\n *\n * It answers `--run` only. It writes no config, so it has nothing to `--init`, `--inspect` or\n * `--validate`, and those verbs never sweep it.\n */\nexport const REPOSITORY_TARGETS: readonly Target[] = ['env']\n\n/**\n * Targets that do not TERMINATE, and are therefore never swept.\n *\n * Every other target is a check: it runs, it answers, it exits. `dev` starts a server and\n * stays up until someone stops it. That difference matters exactly once, and it matters a lot:\n * `sentinel --run` with no named target means \"every wired target\", so without this a sweep\n * would launch a dev server per module and never come back — on a 441-module workspace, from a\n * command whose whole purpose is to answer a question.\n *\n * So a long-running target is reachable only when NAMED. `sentinel --run --dev` starts the\n * server; `sentinel --run` never does.\n *\n * It is a target rather than a flag on `--build` because it is the app's second invocation of\n * the same toolchain: `build` stopped calling `vite build` directly, and `serve` still called\n * `vite` directly. Same migration, same tool, one script left behind.\n */\nexport const LONG_RUNNING_TARGETS: readonly Target[] = ['dev']\n\n/**\n * Targets that terminate, and are still never swept: each run of one costs minutes and a build.\n *\n * `runtime-analysis` builds a front, serves it and drives a real Chrome through Lighthouse user\n * flows, several minutes per front. A sweep (`sentinel --run`, `sentinel --init` with no target)\n * would start that in every front of the workspace, and a bare `--init` would write every front a\n * config it has to fill with its own screens before anything can run. So it is reached only when\n * NAMED, `--runtime-analysis`, the same rule as `dev` for a different reason: not that it never\n * ends, but that it is a measure a team adopts on purpose.\n */\nexport const ON_DEMAND_TARGETS: readonly Target[] = ['runtime-analysis']\n\n/**\n * Targets whose phases write machine output on stdout: `env` prints shell exports a CI sources, and\n * `detect` prints `screens=` a CI reads. With a phase after `--`, their summary row goes to stderr,\n * or the next `. env.sh` fails on the row's `(react)`: measured on the monorepo's first CI run.\n */\nexport const STDOUT_PHASE_TARGETS: readonly Target[] = ['runtime-analysis']\n\n/** The targets an unqualified `--run` / `--all` covers: every check that terminates and is cheap. */\nexport const SWEEPABLE_TARGETS: readonly Target[] = TARGETS.filter(\n (target) => !LONG_RUNNING_TARGETS.includes(target) && !ON_DEMAND_TARGETS.includes(target),\n)\n\n/** Presets: the stack preset a project resolves to (strict by default). */\nexport const PRESET_NAMES = ['react', 'nest', 'svelte', 'node', 'tools'] as const\nexport type PresetName = (typeof PRESET_NAMES)[number]\n\n/**\n * The shapes `--output` can ask a report-writing role for. `console` writes nothing to disk.\n *\n * ⛔ Here rather than in the role that happens to implement them today, for the same reason\n * `PRESET_NAMES` is here: `--output` is a GLOBAL flag, so the CLI has to validate it before any\n * role is chosen. It used to be validated inside the static-analysis adapter, which runs on\n * `--run` only, and the measured consequence was that `--inspect`, `--status` and `--init`\n * accepted `--output xml` silently and exited 0. A flag that is refused by one verb out of four\n * is worse than one that is never refused: it teaches you it was checked.\n */\nexport const OUTPUT_SHAPES = ['console', 'json', 'html', 'markdown'] as const\nexport type OutputShape = (typeof OUTPUT_SHAPES)[number]\n\n/**\n * What the env role does with what it finds, from `SENTINEL_ENV_LEVEL`.\n *\n * | level | reports | in GitHub Actions | exit |\n * | --- | --- | --- | --- |\n * | `info` | yes | nothing more | 0 |\n * | `warning`, the default | yes | a `::warning` annotation per finding | 0 |\n * | `error` | yes | `::error` on a blocking finding, `::warning` on the rest | 1 on a blocking finding |\n *\n * An environment variable and not a flag, because the same command runs in a developer's shell and\n * in every repository's CI, and what changes between them is the policy, not the command: a team\n * moves from `warning` to `error` by setting one variable in its workflow, without editing the step.\n *\n * ⛔ Here and not in the role for the reason `OUTPUT_SHAPES` is: it is read and VALIDATED at the CLI\n * edge, once, before any role runs, and handed to the role as data. A role that read the\n * environment itself would be the one place in this package whose behaviour a test cannot pin by\n * its inputs.\n */\nexport const ENV_LEVELS = ['info', 'warning', 'error'] as const\nexport type EnvLevel = (typeof ENV_LEVELS)[number]\nexport const DEFAULT_ENV_LEVEL: EnvLevel = 'warning'\n\n/**\n * The outcome of one module × target check. `unsupported` is a distinct third state\n * (a requested target has no adapter yet): it must never read as a pass, and an\n * explicitly-requested unsupported target is a usage error (non-zero exit), while an\n * unsupported target swept in by `--all` is just skipped and shown.\n */\nexport type ResultStatus = 'ok' | 'failed' | 'unsupported'\n\n/**\n * @deprecated Renamed to `PresetName`. Kept so an existing `import type { Flavour }` keeps\n * compiling: the CLI kept `--flavour` working for the same reason, and breaking the type\n * while sparing the flag would be an odd place to draw the line.\n */\nexport type Flavour = PresetName\n","{\n \"entry\": [\n \"**/*.integration-spec.ts\",\n \"**/*.steps.ts\",\n \"src/client.tsx\",\n \"src/start.ts\",\n \"src/router.tsx\",\n \"src/RouterContext.tsx\"\n ],\n \"ignore\": [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/coverage/**\",\n \"**/.next/**\",\n \"**/__mocks__/**\",\n \"**/mocks/**\",\n \"**/_mock_/**\",\n \"**/**Mock**/**\",\n \"**/__fixtures__/**\",\n \"**/fixtures/**\",\n \"**/public/**\",\n \"**/.husky/**\",\n \"**/.vscode/**\",\n \"**/.idea/**\",\n \"**/.github/**\",\n \"**/*.d.ts\",\n \"**/*.gen.ts\",\n \"**/*.generated.ts\"\n ],\n \"languages\": [\"javascript\", \"typescript\", \"jsx\", \"tsx\", \"css\", \"scss\"],\n \"journeys\": {},\n \"duplication\": {\n \"minTokens\": 50,\n \"minLines\": 5,\n \"kinds\": [\"exact\"],\n \"tests\": [\n \"*.{test,spec,steps,e2e-spec,integration-spec,stories}.{ts,tsx,js,jsx}\",\n \"*.{msw,mock,test-data}.{ts,tsx,js,jsx}\",\n \"{tests,__tests__,test,testing,stubs}/**/*.{ts,tsx,js,jsx}\"\n ]\n },\n \"deadCode\": {\n \"minConfidence\": 60,\n \"categories\": [\"unused-file\", \"unused-export\", \"unused-symbol\", \"unused-import\"]\n },\n \"graph\": {\n \"resolution\": 1\n },\n \"tools\": {\n \"jscpd\": {}\n }\n}\n","/**\n * The static analysis preset: the role's settings, as data.\n *\n * One shared layer and no per-stack preset yet, because nothing measured so far varies by stack:\n * duplication, dead code and complexity are the same questions in Nest and in React. The split\n * that is already foreseen is `LCOM4`, which is meaningless on a functional front end and real on\n * nest's 16 568 classes; when it arrives it becomes `nest.json` beside this layer, which is why\n * the values live here as JSON rather than inline in the code.\n *\n * ## Why these values are the role's and not the module's\n *\n * A team declares FACTS about its own domain (which journeys exist, which files are entry points);\n * it does not declare the values a number is judged by. Two files with the same measurement\n * getting different verdicts in two modules would make every figure incomparable, and the first\n * thing this role has to be able to say is that a number means the same thing everywhere.\n *\n * That is a default, not a wall: a module CAN move any of them (see `configs/define.ts`), and when\n * it does the report prints `(module)` next to the value. The seam exists from the first commit\n * because retrofitting one later means rewriting every module's file.\n *\n * ⛔ There are no thresholds here, and their absence is a decision rather than an omission.\n *\n * A threshold was written first, at 5% of duplicated lines, and then removed. Measured over all 228\n * nx projects: 5% flags 65 of the 201 measurable modules, a third of the repository, and moving the\n * figure until the count felt manageable is not calibration, it is fitting the instrument to the\n * answer. Calibration is legitimate when a bench is polluted and the noise is removed, or when the\n * reference frame changes; neither applies to a share of duplicated lines.\n *\n * And there is nothing to calibrate AGAINST: of the sources in `docs/static-analysis-study.md`\n * section 5, NDepend, Lattix, ArchUnit, CodeScene and Arcan, none publishes a threshold for\n * duplicated lines. One invented here would travel as if it were published.\n *\n * So the role reports the measurement. What makes a single figure readable is the distribution it\n * sits in, which only a workspace-wide run can know, so that belongs to the sweep and to the\n * migration page, not to a module's own report. The first defensible warning will not be an absolute\n * number either: a module that got WORSE than its own previous measurement is a signal that needs no\n * invented bar, which is what a baseline gives, and that was already deferred for its own reasons.\n *\n * ## Where each value comes from, so nobody has to guess later\n *\n * - `entry` is the single most consequential line in the file. Measured on\n * `apps/nest/microservices/network` with jscpd 5.4.0: with nothing declared the dead-code pass\n * reports **33.4%** of lines dead (79 657 lines, 232 files, 13 entry points); with these two\n * patterns declared it reports **1.0%** (2 462 lines, 207 entry points). The cause is a naming\n * convention and not a bug: our integration tests are `foo.integration-spec.ts` with a HYPHEN,\n * so they do not end in `.spec.ts` and the tool's own test-file detection never sees them, and\n * the 115 `.steps.ts` BDD definitions are tests by no convention it knows. A module ADDS to\n * this list rather than replacing it, precisely so no team can lose these two by declaring a\n * third.\n *\n * ⭐ The four `src/` files are the FRONT bootstrap, and they are the most consequential thing\n * measured on this pass. The tool recognises around fifty frameworks and TanStack Start is not\n * one of them, so nothing in the repository imports these files: the framework finds them by\n * convention at build time. Measured without them declared, `apps/front/console` reports\n * `src/client.tsx`, `src/router.tsx` and `src/start.ts` among its 5 dead files, which are its\n * hydration entry, its router factory and its Start config. `host-admin` reports `client.tsx`\n * too and `career` reports `router.tsx` and `RouterContext.tsx`. Three of console's five\n * findings were its own bootstrap, and the first team to see that stops trusting the tool on\n * the spot. They exist in 2 to 3 front apps each.\n *\n * ⛔ `scripts/**` is deliberately NOT here, although 8 modules have one and\n * `apps/nest/microservices/contract` reports two `scripts/e2e-*.ts` as dead. No `package.json`\n * script invokes them, so whether they run at all is a fact only the team holds. Declaring them\n * would hide a finding that may well be true, and that is the opposite of this role's job.\n *\n * - `languages` is this role's name for what the tool calls `format`, a word that already names\n * another sentinel role and means something else there. Stating it has a measured cost either\n * way: on `apps/front/console`, naming `typescript` alone scans 300 of 523 files because `.tsx`\n * is a SEPARATE language to the tool, naming all four scans 522 (the one left out being\n * `styles.css`), and naming nothing scans every one of its 224 languages, json and markdown\n * included. Stylesheets are in deliberately: measured on `libs/front` they duplicate at 9.64%\n * against 3.50% for the code, a signal that only survives because the report is broken down per\n * language.\n *\n * - `duplication.minTokens` and `minLines` are the detection window, and the window decides what\n * is INVISIBLE: a fragment shorter than it is not reported at all, so a reader comparing two\n * runs has to know both values. They are the tool's own defaults, written out rather than\n * inherited for that reason.\n *\n * - `duplication.kinds` is `exact` alone, and that is a correctness constraint rather than\n * caution. Measured: with a second kind enabled, `duplicatedLines` adds up overlapping clones.\n * Two 9-line files reported 13 duplicated lines out of 18, 72%, because an `exact` clone of\n * lines 1-4 and a `similar` clone of lines 1-9 containing it were both counted; the real extent\n * is 9 of 18, 50%. The tool's own answer is to cap the display at 100%, which does not make a\n * threshold meaningful. Opening another kind therefore requires computing the share ourselves\n * from the UNION of the line ranges.\n *\n * - `duplication.tests` is the glob that splits the pass in two, and the split is the finding that\n * forced it. Measured across 8 modules of the three families, **71% of all duplicated lines are\n * between two test files**: `libs/nest/auth` reports 35.77% and its product code is at 5.96%,\n * `apps/front/host-admin` 7.91% against 3.59%. A single blended figure is therefore mostly a\n * measure of spec duplication wearing the name of the module's duplication, and the number\n * travels while that nuance does not. So the role reports the two side by side, the way it\n * already refuses to blend languages, and neither is hidden: a module whose specs carry 93% of\n * its clones is saying something about its specs that excluding them would erase.\n *\n * ⚠️ The two passes PARTITION the files and therefore lose a clone that spans them: a fragment\n * shared between a test and a product file has no partner in either scan. Measured on the same\n * 8 modules, that is 42 entries of 5117, 0.8%, 650 lines. Stated in the caveat rather than\n * silently accepted, and it is the price of the split.\n *\n * Two patterns and not one, because a suffix convention does not cover a DIRECTORY convention,\n * and the directory one is not a quirk: 635 files across 26 modules live under `tests/` or\n * `__tests__/` without a name this role's suffixes recognise, `apps/nest/microservices/recruitment`\n * alone holding 160. They are step definitions, in-memory doubles and stubs, which is test-side\n * code by any reading. A role default rather than 26 identical overrides.\n *\n * ⚠️ The patterns are RELATIVE here, and the adapter prefixes and composes them, because the\n * tool's `--pattern` takes exactly one glob. Verified on four modules that the two passes\n * partition exactly: console 479 + 87 = 566, contract 399 + 151 = 550, backends-for-frontends/admin\n * 2062 + 773 = 2835, recruitment 936 + 621 = 1557.\n *\n * ⚠️ And a trap that cost a wrong table before it was caught: these globs contain commas, so they\n * survive the config FILE and are destroyed by the `-i` command-line flag, which splits on\n * commas and cuts `{test,spec}` in half. The adapter writes a file, which is one more reason it\n * does.\n *\n * - `deadCode.minConfidence` is the tool's own default of 60. It scores every finding and names\n * what lowered it (a file calling `eval`, an unrecognised decorator, a name appearing in a\n * string literal, a file in the scan that did not parse). Measured on sentinel: 60 yields 20\n * files, 10 exports and 22 symbols; 90 yields 18 files; 100 yields nothing.\n *\n * - `deadCode.categories` leaves out `unused-member` deliberately: without type information\n * `x.render()` could reach any `render` in the project, which the tool itself calls its least\n * certain rule.\n *\n * - `ignore` excludes generated, vendored and fixture code, which duplicates by nature and buries\n * the clones a developer can act on. It is load-bearing rather than tidy: measured on this\n * package, scanning the module root with no ignore list reports 18 186 files and 32 153 clones,\n * **31 969** of them touching `node_modules`; with the list, 408 files and zero.\n *\n * - `graph.resolution` is Louvain's, and it is 1 because that is the value the papers use and\n * graphology's own default. It decides how large a community must be to survive, so it changes\n * both the community count and `Q`, and graphology's documentation warns in its own words that\n * it is finicky to tweak. `code-health-meter` ships 0.74, arrived at by trying values until the\n * partition looked right; this role declines to do that, for the same reason it ships no\n * duplication threshold. A module that has a reason can move it, and the report prints the\n * value every figure was produced with.\n *\n * ⚠️ What is NOT tunable is the random seed, and that is deliberate. Louvain is greedy, so its\n * answer depends on the order it visits nodes, which graphology draws from `Math.random`.\n * Measured over 20 runs per module: `console` produced 16 distinct values of `Q` and between 12\n * and 14 communities, `recruitment` 19 distinct values spanning 0.0357. With the role's own\n * generator all five modules produce one value. A figure that moves on its own between two runs\n * is not a figure a team can act on, so this one is the role's and nobody's to change.\n *\n * - `tools.jscpd` is passed to the tool verbatim, and it is **sentinel's own** escape hatch, not a\n * module's: `defineStaticAnalysis` excludes it from what a module can override. Everything above\n * uses OUR key names, translated on the way out, so that replacing the tool one day does not\n * oblige a single module to edit its config file, and a module only ever knows the ROLE. This\n * block is where that guarantee stops, which is why it stays on this side and why it is empty:\n * the first thing to put in it would be an option a single preset needs, not a workaround.\n */\nimport { OUTPUT_SHAPES } from '../../core/domain.js'\n\nimport sharedData from './presets/shared.json'\n\n/**\n * Where the json and html reports are written, relative to the module.\n *\n * Named for the role rather than left on the tool's default `report/`, and added to `.gitignore`\n * by `--init`. Both halves matter: the format role once shipped a `lint/` directory that nothing\n * ignored, and every adopting module grew an untracked directory nobody could explain.\n */\nexport const REPORT_DIR = 'static-analysis-report'\n\n/** The target this role serves, which is also the npm script a module runs and the nx target. */\nexport const TARGET = 'static-analysis'\n\n/**\n * The output shapes `--run` can produce. `console` writes nothing to disk.\n *\n * Re-exported from `core/domain` rather than declared here: `--output` is a global CLI flag and\n * the CLI validates it before a role is chosen, so one list has to serve both. This spelling\n * stays because the role and its report read it everywhere.\n */\nexport const SHAPES = OUTPUT_SHAPES\n\n/**\n * The npm scripts a module gets: one per shape a developer runs, which is three of the four.\n *\n * Here rather than in the adapter because the REPORT needs them too, to tell a reader of the\n * console summary where the detail is, and two spellings of one script name is drift nobody\n * notices until a developer types the one that does not exist.\n */\nexport const SCRIPTS = {\n console: TARGET,\n json: `${TARGET}:json`,\n html: `${TARGET}:html`,\n // ⛔ No entry for the `markdown` shape, deliberately, and this is NOT a gap: these are the npm\n // scripts a module gets, and markdown is the recap a workflow posts on a pull request, built\n // from one file per affected module. A developer who wants it by hand gets the console shape,\n // which says the same thing in less space and writes nothing. A fourth script here would be a\n // command nobody runs, carried in 198 package.json files.\n} as const\n\n/**\n * What each language the role scans is called on disk.\n *\n * ⚠️ Two lists that MUST agree, and they were maintained separately: the role declares the\n * languages it asks the tool to scan, and the adapter declared the extensions it looks for when\n * deciding whether a module has anything to measure at all. A module that narrowed `languages`\n * would still be probed for the extensions it had removed, and a language added to the preset\n * would never reach the probe. Derived from one source now, with a test that every language maps.\n */\nconst EXTENSIONS_BY_LANGUAGE: Record<string, string[]> = {\n javascript: ['.js', '.mjs', '.cjs'],\n typescript: ['.ts'],\n jsx: ['.jsx'],\n tsx: ['.tsx'],\n css: ['.css'],\n scss: ['.scss'],\n}\n\n/** The file extensions of the languages given, for deciding whether a module has anything to read. */\nexport function extensionsOf(languages: readonly string[]): string[] {\n return [...new Set(languages.flatMap((language) => EXTENSIONS_BY_LANGUAGE[language] ?? []))]\n}\n\n/** Every language the mapping knows, so a test can hold it against the preset. */\nexport const MAPPED_LANGUAGES = Object.keys(EXTENSIONS_BY_LANGUAGE)\n\nexport type StaticDefaults = {\n entry: string[]\n ignore: string[]\n languages: string[]\n journeys: Record<string, string[]>\n duplication: { minTokens: number; minLines: number; kinds: string[]; tests: string[] }\n deadCode: { minConfidence: number; categories: string[] }\n graph: { resolution: number }\n tools: { jscpd: Record<string, unknown> }\n}\n\n/** The role's settings. Read-only here; `defineStaticAnalysis` resolves a module against them. */\nexport const defaults: StaticDefaults = sharedData as StaticDefaults\n\n/**\n * Keys a module declares DIRECTLY rather than through `overrides`, and how each one combines.\n *\n * They are apart because the verb differs: these two are added to and merged, so a team cannot\n * lose what the role ships by declaring its own. Everything else replaces.\n */\nconst DECLARED: Record<string, string> = {\n entry: 'added to the patterns the role ships, never replacing them',\n journeys: \"merged by name with the role's\",\n}\n\n/**\n * ⛔ Not a module's to set, and the catalogue says so rather than leaving it absent: a key that is\n * simply missing from a list reads as an oversight, and someone will try it. Passing it is dropped\n * with a message, see `configs/define.ts`.\n */\nconst NOT_YOURS: Record<string, string> = {\n tools: \"sentinel's own passthrough to the tool underneath; a module never names the vendor\",\n // ⛔ Listed as movable until it was tried: the catalogue said \"what this module can move\" and\n // moving it exits 1, because any kind beyond `exact` overlaps the first and the duplicated-line\n // share then counts the same lines twice. A setting that is refused at run time belongs here,\n // where the reason is readable, rather than in the list of things to turn.\n 'duplication.kinds': 'only `exact` is supported: any other kind overlaps it and double-counts',\n}\n\n/** A value as a reader compares it: short lists in full, long ones as a count. */\nfunction render(value: unknown): string {\n if (Array.isArray(value)) {\n const joined = value.join(', ')\n return value.length <= 6 && joined.length <= 72 ? joined : `${value.length} patterns`\n }\n if (value && typeof value === 'object') return `${Object.keys(value).length} entries`\n return String(value)\n}\n\n/** One documented key: its path, the role's value, and the note a reader needs. */\nexport interface OverridableSetting {\n /** The dotted path a module writes, e.g. `duplication.minTokens`. */\n key: string\n /** The role's current value, rendered. */\n value: string\n /** How it combines, or why it is not available. */\n note: string\n /** Where it goes: directly in the config, inside `overrides`, or nowhere. */\n where: 'declared' | 'overrides' | 'refused'\n}\n\n/**\n * Every setting a module can touch, DERIVED from the values rather than written beside them.\n *\n * Héla's ask, and the reason it is generated: a hand-written list is a second copy of the preset,\n * and the first setting somebody adds makes it a lie that nobody notices, because a stale comment\n * fails no test. Here a new key appears in the next module's config file on its own, with its real\n * value, and `tests/role-layout.test.ts` refuses a key that reaches none of the three groups.\n *\n * It is a snapshot: `--init` leaves an EXISTING config alone, by design, so a module that adopted\n * earlier keeps the catalogue of that day. The report is the live answer, since it prints the value\n * every figure was produced with.\n */\nexport function overridableSettings(from: StaticDefaults = defaults): OverridableSetting[] {\n const rows: OverridableSetting[] = []\n\n for (const [key, value] of Object.entries(from)) {\n if (key in NOT_YOURS) {\n rows.push({ key, value: render(value), note: NOT_YOURS[key] ?? '', where: 'refused' })\n continue\n }\n if (key in DECLARED) {\n rows.push({ key, value: render(value), note: DECLARED[key] ?? '', where: 'declared' })\n continue\n }\n // A group is documented by its leaves, because `duplication` whole is not what anyone writes.\n const leaves =\n value && typeof value === 'object' && !Array.isArray(value)\n ? Object.entries(value).map(([leaf, own]) => ({ key: `${key}.${leaf}`, own }))\n : [{ key, own: value }]\n for (const leaf of leaves) {\n /*\n * ⛔ A LEAF can be refused too, and this check was missing. `NOT_YOURS` holds the dotted key\n * `duplication.kinds`, but the test above only ran on top-level keys: `duplication` is not\n * in `NOT_YOURS`, so every one of its leaves fell through to here and the catalogue printed\n * `duplication.kinds` under \"What this module can move\".\n *\n * ⚠️ A developer who followed it got exit 1 on the next run, with a message refusing the\n * very setting the generated config had invited them to write. The test that was supposed\n * to cover this passed because the key DID reach a group, just the wrong one.\n */\n if (leaf.key in NOT_YOURS) {\n rows.push({\n key: leaf.key,\n value: render(leaf.own),\n note: NOT_YOURS[leaf.key] ?? '',\n where: 'refused',\n })\n continue\n }\n rows.push({ key: leaf.key, value: render(leaf.own), note: 'replaced', where: 'overrides' })\n }\n }\n\n return rows\n}\n","/**\n * `defineStaticAnalysis`: what a module imports to declare its own static analysis settings.\n *\n * ```js\n * // static-analysis.config.mjs\n * import { defineStaticAnalysis } from '@hublo/sentinel/static-analysis'\n *\n * export default defineStaticAnalysis({\n * root: import.meta.dirname,\n * entry: ['**\\/*.steps.ts'],\n * journeys: { planning: ['src/planning/**'] },\n * })\n * ```\n *\n * ## Why a function and not `{ ...baseConfig, ... }`\n *\n * A spread is SHALLOW, so a module writing `deadCode: { minConfidence: 80 }` would replace the\n * whole block and silently lose `categories`. And the flattening happens in the module's file,\n * before this package ever sees the object, so nothing here could tell \"set one key, keep the\n * rest\" from \"set one key, drop the rest\". A function receives the module's INTENT, the keys it\n * actually passed, and merges them here. Second reason: the defaults are never copied into a\n * module, so changing one reaches every module at the next release instead of leaving 108 stale\n * copies behind.\n *\n * Same shape as `reactTestConfig` in the test role, for the same reasons.\n *\n * ## Two semantics, one obvious and one deliberate\n *\n * `entry` and `journeys` are FACTS a team declares, and they ADD to what this role ships: no\n * module can lose `**\\/*.integration-spec.ts` by declaring a third pattern, which matters\n * because that one pattern is the difference between 33.4% and 1.0% of dead code on a real\n * service (see `defaults.ts`).\n *\n * `overrides` REPLACES, including those lists. It is the seam for the day a team has a real\n * reason, it is not documented anywhere a developer would meet it, and every path it sets is\n * recorded in `moved` so the report can print `(module)` next to the value. Without that trace\n * two modules stop being comparable and nobody knows. It reaches every setting EXCEPT the vendor\n * passthrough, for the reason stated on the field itself.\n */\nimport { isPlainObject } from '../../../shared/deep-merge.js'\nimport { defaults, type StaticDefaults } from '../preset-data.js'\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] }\n\n/** What a module's config file passes. Everything is optional, including the file itself. */\nexport interface StaticAnalysisInput {\n /** The module's own directory, normally `import.meta.dirname`. */\n root?: string\n /** Files that run although nothing imports them. ADDED to the shipped patterns. */\n entry?: string[]\n /**\n * Named journeys, as `{ name: [globs] }`. MERGED by name with any shipped ones.\n *\n * ⛔ **No pass reads this yet, and the generated config stub no longer asks for it.** It is the\n * seam for the product axis, where a figure is reported per journey rather than per module, and\n * that is V2 work tracked in issue #98. It stays accepted so a module that already declared one\n * is not broken, and `--inspect` echoes it back, but nothing measures against it.\n *\n * It was in the stub for a while, under a comment telling every adopting team to fill it in. A\n * team that did would have waited for a breakdown that never came and concluded their globs were\n * wrong. Asking for something nothing consumes is worse than not offering it.\n */\n journeys?: Record<string, string[]>\n /**\n * The seam. Replaces whatever it names, and every path it sets lands in `moved`.\n *\n * ⛔ `tools` is excluded, and the reason is the whole point of translating the vocabulary: a\n * module knows the ROLE, not the tool underneath it. A key named after the vendor would mean\n * nothing to the person reading their own config file, and showing it would invite them to learn\n * a name we are working to keep out of their world. The passthrough still exists, on sentinel's\n * side, for a preset that needs a vendor option; a module that genuinely needs one gets a key in\n * OUR vocabulary, which is the right friction because it goes through a review instead of\n * spreading silently.\n */\n overrides?: DeepPartial<Omit<StaticDefaults, 'tools'>>\n}\n\nexport interface ResolvedStaticConfig extends StaticDefaults {\n /** The module's directory, or null when its config file did not say. */\n root: string | null\n /**\n * Dotted paths the module set through `overrides`, so the report can mark them. Sorted, so\n * two runs on the same config produce the same report.\n */\n moved: string[]\n}\n\n/**\n * Merge `patch` into `base`, recursively, patch winning.\n *\n * Not the `deepMerge` this repo once had: that one existed for WRITING a module's json and was\n * replaced by an in-place jsonc edit, which is why only `isPlainObject` survived. This is the\n * read side, which has no file to preserve and only has to resolve two objects into one.\n *\n * Arrays are replaced, never concatenated. Additive behaviour is a decision about a specific\n * key, which `defineStaticAnalysis` makes explicitly for `entry`, rather than a property of the\n * merge: a merge that silently concatenates cannot express \"replace this list\", and a team\n * reaching for `overrides` is asking for exactly that.\n */\nfunction mergeInto<T>(base: T, patch: unknown): T {\n if (!isPlainObject(patch)) return base\n if (!isPlainObject(base)) return patch as T\n const out: Record<string, unknown> = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n out[key] = isPlainObject(value) ? mergeInto(out[key], value) : value\n }\n return out as T\n}\n\n/** Every leaf path in `patch`, dotted, so a reader can be told what the module decided. */\nfunction leafPaths(patch: unknown, prefix = ''): string[] {\n if (!isPlainObject(patch)) return prefix ? [prefix] : []\n return Object.entries(patch).flatMap(([key, value]) =>\n leafPaths(value, prefix ? `${prefix}.${key}` : key),\n )\n}\n\n/** The same list with duplicates dropped, keeping the first occurrence's order. */\nfunction unique(values: string[]): string[] {\n return [...new Set(values)]\n}\n\n/**\n * Drop the vendor passthrough from what a module sent.\n *\n * ⚠️ Enforced here and not by the type, because the type cannot: a module's config file is `.mjs`,\n * so nothing type-checks it, and `Omit` on the input would be documentation that compiles away. A\n * `tools` key written there is dropped and NAMED on stderr rather than ignored, so a developer who\n * found the key somewhere learns why it did nothing instead of concluding the role is broken.\n */\nfunction withoutVendorKeys(overrides: unknown): unknown {\n if (!isPlainObject(overrides) || !('tools' in overrides)) return overrides\n const { tools: _vendor, ...rest } = overrides\n process.stderr.write(\n 'sentinel static-analysis: ignoring `overrides.tools` from this module. The tool underneath ' +\n \"the role is not part of a module's surface; if a setting is missing, it needs a key of \" +\n 'its own.\\n',\n )\n return rest\n}\n\n/** Resolve a module's declaration against this role's defaults. */\nexport function defineStaticAnalysis(input: StaticAnalysisInput = {}): ResolvedStaticConfig {\n const declared: StaticDefaults = {\n ...defaults,\n entry: unique([...defaults.entry, ...(input.entry ?? [])]),\n journeys: { ...defaults.journeys, ...(input.journeys ?? {}) },\n }\n const overrides = withoutVendorKeys(input.overrides)\n\n return {\n ...mergeInto(declared, overrides),\n root: input.root ?? null,\n moved: leafPaths(overrides).sort(),\n }\n}\n"],"mappings":";;;;;AA8BO,IAAM,QAAQ,CAAC,OAAO,WAAW,QAAQ,WAAW,YAAY,UAAU,QAAQ;AAIlF,IAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAwBO,IAAM,qBAAwC,CAAC,KAAK;AAkBpD,IAAM,uBAA0C,CAAC,KAAK;AAYtD,IAAM,oBAAuC,CAAC,kBAAkB;AAOhE,IAAM,uBAA0C,CAAC,kBAAkB;AAGnE,IAAM,oBAAuC,QAAQ;AAAA,EAC1D,CAAC,WAAW,CAAC,qBAAqB,SAAS,MAAM,KAAK,CAAC,kBAAkB,SAAS,MAAM;AAC1F;AAGO,IAAM,eAAe,CAAC,SAAS,QAAQ,UAAU,QAAQ,OAAO;AAahE,IAAM,gBAAgB,CAAC,WAAW,QAAQ,QAAQ,UAAU;AAqB5D,IAAM,aAAa,CAAC,QAAQ,WAAW,OAAO;AAE9C,IAAM,oBAA8B;;;ACxJ3C;AAAA,EACE,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IAC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AAA,IAC/B,GAAG;AAAA,IACH,OAAO,OAAO,CAAC,GAAG,SAAS,OAAO,GAAI,MAAM,SAAS,CAAC,CAAE,CAAC;AAAA,IACzD,UAAU,EAAE,GAAG,SAAS,UAAU,GAAI,MAAM,YAAY,CAAC,EAAG;AAAA,EAC9D;AACA,QAAM,YAAY,kBAAkB,MAAM,SAAS;AAEnD,SAAO;AAAA,IACL,GAAG,UAAU,UAAU,SAAS;AAAA,IAChC,MAAM,MAAM,QAAQ;AAAA,IACpB,OAAO,UAAU,SAAS,EAAE,KAAK;AAAA,EACnC;AACF;","names":[]}
@@ -0,0 +1,126 @@
1
+ import {
2
+ isPlainObject
3
+ } from "./chunk-PXTU5MPW.js";
4
+
5
+ // src/roles/code-churn/presets/shared.json
6
+ var shared_default = {
7
+ window: {
8
+ reworkDays: 21,
9
+ periodDays: 90
10
+ },
11
+ maxFilesPerCommit: 100,
12
+ levels: {
13
+ minimumAdded: 500,
14
+ low: 3,
15
+ above: 11,
16
+ watch: 16
17
+ },
18
+ include: ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,svelte,vue}"],
19
+ includeTests: false,
20
+ tests: [
21
+ "**/{test,tests,__tests__,e2e,fixtures,mocks,__mocks__,test-utils}/**",
22
+ "**/*.{spec,test,integration-spec,e2e-spec,steps,test-util,mock}.{ts,tsx,mts,cts,js,jsx}"
23
+ ],
24
+ ignore: [
25
+ "**/node_modules/**",
26
+ "**/dist/**",
27
+ "**/build/**",
28
+ "**/coverage/**",
29
+ "**/*.d.{ts,mts,cts}",
30
+ "**/*.generated.*",
31
+ "**/*.gen.*",
32
+ "**/generated/**"
33
+ ],
34
+ listed: 10
35
+ };
36
+
37
+ // src/roles/code-churn/preset-data.ts
38
+ var TARGET = "code-churn";
39
+ var CODE_CHURN_CONFIG_FILE = "code-churn.config.mjs";
40
+ var REPORT_DIR = "code-churn-report";
41
+ var SCRIPTS = {
42
+ console: "code-churn",
43
+ json: "code-churn:json",
44
+ html: "code-churn:html"
45
+ };
46
+ var defaults = shared_default;
47
+
48
+ // src/roles/code-churn/configs/define.ts
49
+ function mergeInto(base, patch) {
50
+ if (!isPlainObject(patch)) return base;
51
+ if (!isPlainObject(base)) return patch;
52
+ const out = { ...base };
53
+ for (const [key, value] of Object.entries(patch)) {
54
+ out[key] = isPlainObject(value) ? mergeInto(out[key], value) : value;
55
+ }
56
+ return out;
57
+ }
58
+ function leafPaths(patch, prefix = "") {
59
+ if (!isPlainObject(patch)) return prefix ? [prefix] : [];
60
+ return Object.entries(patch).flatMap(
61
+ ([key, value]) => leafPaths(value, prefix ? `${prefix}.${key}` : key)
62
+ );
63
+ }
64
+ function defineCodeChurn(input = {}) {
65
+ return {
66
+ ...mergeInto(defaults, input.overrides),
67
+ root: input.root ?? null,
68
+ moved: leafPaths(input.overrides).sort()
69
+ };
70
+ }
71
+ function invalidSettings(config) {
72
+ const problems = [];
73
+ const positive = (path, value) => {
74
+ if (!Number.isInteger(value) || value < 1) {
75
+ problems.push(`${path} must be a whole number of 1 or more, got ${JSON.stringify(value)}`);
76
+ }
77
+ };
78
+ const strings = (path, value, allowEmpty) => {
79
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
80
+ problems.push(`${path} must be a list of globs, got ${JSON.stringify(value)}`);
81
+ } else if (!allowEmpty && value.length === 0) {
82
+ problems.push(`${path} must name at least one glob, or nothing is measured`);
83
+ }
84
+ };
85
+ positive("window.reworkDays", config.window?.reworkDays);
86
+ positive("window.periodDays", config.window?.periodDays);
87
+ positive("maxFilesPerCommit", config.maxFilesPerCommit);
88
+ positive("levels.minimumAdded", config.levels?.minimumAdded);
89
+ const percentage = (path, value) => {
90
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 100) {
91
+ problems.push(
92
+ `${path} must be a percentage above 0 and at most 100, got ${JSON.stringify(value)}`
93
+ );
94
+ }
95
+ };
96
+ percentage("levels.low", config.levels?.low);
97
+ percentage("levels.above", config.levels?.above);
98
+ percentage("levels.watch", config.levels?.watch);
99
+ const { low, above, watch } = config.levels ?? {};
100
+ if (typeof low === "number" && typeof above === "number" && typeof watch === "number" && !(low < above && above < watch)) {
101
+ problems.push(`levels must rise: low < above < watch, got ${low}, ${above}, ${watch}`);
102
+ }
103
+ if (!Number.isInteger(config.listed) || config.listed < 0) {
104
+ problems.push(
105
+ `listed must be a whole number of 0 or more, got ${JSON.stringify(config.listed)}`
106
+ );
107
+ }
108
+ if (typeof config.includeTests !== "boolean") {
109
+ problems.push(`includeTests must be true or false, got ${JSON.stringify(config.includeTests)}`);
110
+ }
111
+ strings("include", config.include, false);
112
+ strings("tests", config.tests, true);
113
+ strings("ignore", config.ignore, true);
114
+ return problems;
115
+ }
116
+
117
+ export {
118
+ TARGET,
119
+ CODE_CHURN_CONFIG_FILE,
120
+ REPORT_DIR,
121
+ SCRIPTS,
122
+ defaults,
123
+ defineCodeChurn,
124
+ invalidSettings
125
+ };
126
+ //# sourceMappingURL=chunk-XYOIXC6A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/code-churn/presets/shared.json","../src/roles/code-churn/preset-data.ts","../src/roles/code-churn/configs/define.ts"],"sourcesContent":["{\n \"window\": {\n \"reworkDays\": 21,\n \"periodDays\": 90\n },\n \"maxFilesPerCommit\": 100,\n \"levels\": {\n \"minimumAdded\": 500,\n \"low\": 3,\n \"above\": 11,\n \"watch\": 16\n },\n \"include\": [\"**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,svelte,vue}\"],\n \"includeTests\": false,\n \"tests\": [\n \"**/{test,tests,__tests__,e2e,fixtures,mocks,__mocks__,test-utils}/**\",\n \"**/*.{spec,test,integration-spec,e2e-spec,steps,test-util,mock}.{ts,tsx,mts,cts,js,jsx}\"\n ],\n \"ignore\": [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/coverage/**\",\n \"**/*.d.{ts,mts,cts}\",\n \"**/*.generated.*\",\n \"**/*.gen.*\",\n \"**/generated/**\"\n ],\n \"listed\": 10\n}\n","/**\n * The code churn role's values: what it reads, where it writes, and what a module may move.\n *\n * ## What this role measures\n *\n * Code churn in the sense Sourcegraph and DevStats give it: of the lines a module ADDED in a period,\n * the share that was rewritten or deleted within a few weeks of being written. A line rewritten\n * days after it landed is work done twice, which is what the figure is about, and a module whose\n * share is high is one where the code is written before what it must do is settled.\n *\n * It reads the git history and nothing else: no build, no test run, no network. The static\n * analysis role answers what the code IS today; this one answers how it got there. The two are\n * separate roles because one reads the tree and the other reads the history, and a module adopts\n * either without the other (HUB-46818, hublo/sentinel#98).\n *\n * ## Which modules: the ones that hold code\n *\n * Every preset, like the static analysis role: rework is the same question whatever the stack. A\n * module with no file the role reads is skipped by `--init`, and said so.\n */\nimport sharedData from './presets/shared.json'\n\n/** The target this role serves, and the flag that runs it: `sentinel --run --code-churn`. */\nexport const TARGET = 'code-churn'\n\n/** The file a module writes at its root to move a setting. Optional at every moment. */\nexport const CODE_CHURN_CONFIG_FILE = 'code-churn.config.mjs'\n\n/**\n * Where the files of `--output json|html|markdown` land, inside the module.\n *\n * Its own directory rather than `static-analysis-report/`: two roles writing into one folder would\n * each clear the other's stale files.\n */\nexport const REPORT_DIR = 'code-churn-report'\n\n/**\n * One script per shape a DEVELOPER runs. `markdown` gets none: it is the pull request comment a CI\n * workflow produces, the decision static analysis took for the same reason.\n */\nexport const SCRIPTS = {\n console: 'code-churn',\n json: 'code-churn:json',\n html: 'code-churn:html',\n} as const\n\nexport interface CodeChurnDefaults {\n /** The two durations the figure is made of, in days. */\n window: {\n /**\n * How long after a line is written a change to it counts as rework. 21 days, the window\n * Sourcegraph uses (\"code rewritten or deleted within three weeks of being written\"); DevStats\n * gives 14 to 21. A change after it is maintenance, not rework, and is not counted.\n */\n reworkDays: number\n /**\n * How far back the lines that are measured were written, in days, ending `reworkDays` before\n * the newest commit read. The period stops there so every line it holds has had its full\n * window: a line written yesterday cannot have been rewritten yet, and counting it would lower\n * the figure for a reason that has nothing to do with the code.\n */\n periodDays: number\n }\n /**\n * A commit that touches more files than this IN THE MODULE is a sweep, a formatter run or a\n * rename sweep, and its lines are not counted. Counted in the module and not in the repository,\n * which was measured: see `churn.ts`, \"What is not counted\".\n */\n maxFilesPerCommit: number\n /**\n * Where a module's figure stands, in percent, and below how many added lines it has none.\n *\n * Calibrated on hublo/monorepo `main` f12da701121 (2026-07-28 to 2026-10-26): of the 113 sentinel\n * modules, 33 added no line and 44 fewer than 500 (26 in the median), where one rewrite moves the\n * figure by points; over the 36 others, the 25th, 75th and 90th percentiles are 3.1, 11.4 and\n * 15.9%, rounded DOWN to 3, 11 and 16. They say where a module stands among those modules, never\n * whether its code is good, and are recalibrated by a sweep at each stable release.\n */\n levels: {\n /** Below this many lines added in the period, the module is `quiet`: no percentage stated. */\n minimumAdded: number\n /** Under this, `low`. */\n low: number\n /** Over this, `above`. Between `low` and it, `usual`. */\n above: number\n /** Over this, `watch`. */\n watch: number\n }\n /** The files whose lines are measured, as globs relative to the module. */\n include: string[]\n /**\n * Measure the tests too. OFF by default: the figure is about the product code, and a test\n * rewritten with the code it checks is the expected case, not rework. A module that decides\n * otherwise sets it to true, and the report says so.\n */\n includeTests: boolean\n /** What counts as a test, by path. The list the sql role measured, extended to JavaScript. */\n tests: string[]\n /**\n * Files never measured, whatever `include` says: generated and built output. `*.gen.*` is\n * TanStack Router's `routeTree.gen.ts`, regenerated on every route change (career, console and\n * host-admin on hublo/monorepo): measured, it was one of host-admin's most changed files.\n */\n ignore: string[]\n /** How many files the report lists, highest churn first. */\n listed: number\n}\n\n/**\n * The role's values, read from `presets/shared.json`: preset data is JSON, never TypeScript, in every\n * role (AGENTS.md, and `tests/role-layout.test.ts` holds it). The reasons for each value are the\n * comments on `CodeChurnDefaults` above, since JSON carries none.\n */\nexport const defaults: CodeChurnDefaults = sharedData as CodeChurnDefaults\n","/**\n * `defineCodeChurn`: what a module imports to declare its own code churn settings.\n *\n * ```js\n * // code-churn.config.mjs\n * import { defineCodeChurn } from '@hublo/sentinel/code-churn'\n *\n * export default defineCodeChurn({\n * root: import.meta.dirname,\n * overrides: { window: { periodDays: 180 } },\n * })\n * ```\n *\n * The shape of `defineStaticAnalysis` and `defineSql`, for the two reasons stated there. A function\n * receives the module's INTENT, the keys it actually passed, and merges them here, so setting one\n * key never drops its siblings: a spread in the module's file would replace the whole `window` block\n * to set `periodDays`, and lose `reworkDays` with nobody seeing it. And the defaults are never\n * copied into a module, so a changed default reaches every module at the next release instead of\n * leaving stale copies behind.\n *\n * `overrides` REPLACES what it names, lists included, and every path it sets lands in `moved`, so\n * the report prints `(module)` beside it: two modules measured with different windows no longer\n * compare, and the reader has to be told.\n */\nimport { isPlainObject } from '../../../shared/deep-merge.js'\nimport { defaults, type CodeChurnDefaults } from '../preset-data.js'\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] }\n\n/** What a module's config file passes. Everything is optional, including the file itself. */\nexport interface CodeChurnInput {\n /** The module's own directory, normally `import.meta.dirname`. */\n root?: string\n /** The seam. Replaces whatever it names, and every path it sets lands in `moved`. */\n overrides?: DeepPartial<CodeChurnDefaults>\n}\n\nexport interface ResolvedCodeChurnConfig extends CodeChurnDefaults {\n /** The module's directory, or null when its config file did not say. */\n root: string | null\n /** Dotted paths the module set through `overrides`, sorted so two runs print the same report. */\n moved: string[]\n}\n\n/**\n * Merge `patch` into `base`, recursively, patch winning.\n *\n * Arrays are REPLACED, never concatenated: a merge that concatenates cannot express \"replace this\n * list\", which is exactly what a team reaching for `overrides` asks for.\n */\nfunction mergeInto<T>(base: T, patch: unknown): T {\n if (!isPlainObject(patch)) return base\n if (!isPlainObject(base)) return patch as T\n const out: Record<string, unknown> = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n out[key] = isPlainObject(value) ? mergeInto(out[key], value) : value\n }\n return out as T\n}\n\n/** Every leaf path in `patch`, dotted, so a reader can be told what the module decided. */\nfunction leafPaths(patch: unknown, prefix = ''): string[] {\n if (!isPlainObject(patch)) return prefix ? [prefix] : []\n return Object.entries(patch).flatMap(([key, value]) =>\n leafPaths(value, prefix ? `${prefix}.${key}` : key),\n )\n}\n\n/** Resolve a module's declaration against this role's defaults. */\nexport function defineCodeChurn(input: CodeChurnInput = {}): ResolvedCodeChurnConfig {\n return {\n ...mergeInto(defaults, input.overrides),\n root: input.root ?? null,\n moved: leafPaths(input.overrides).sort(),\n }\n}\n\n/**\n * The settings of a resolved config that cannot be measured with, one sentence each naming the\n * setting and the value. Empty when the config is usable.\n *\n * ⛔ Checked rather than trusted: a negative window runs the period into the future, a `listed` of\n * -1 drops the last file through `slice(0, -1)`, a cap of 0 makes every commit a sweep, an empty\n * `include` measures nothing, levels that do not rise put every module in two bands at once, and\n * none of them says so. Each one is a figure that looks right.\n */\nexport function invalidSettings(config: CodeChurnDefaults): string[] {\n const problems: string[] = []\n const positive = (path: string, value: unknown): void => {\n if (!Number.isInteger(value) || (value as number) < 1) {\n problems.push(`${path} must be a whole number of 1 or more, got ${JSON.stringify(value)}`)\n }\n }\n const strings = (path: string, value: unknown, allowEmpty: boolean): void => {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n problems.push(`${path} must be a list of globs, got ${JSON.stringify(value)}`)\n } else if (!allowEmpty && value.length === 0) {\n problems.push(`${path} must name at least one glob, or nothing is measured`)\n }\n }\n positive('window.reworkDays', config.window?.reworkDays)\n positive('window.periodDays', config.window?.periodDays)\n positive('maxFilesPerCommit', config.maxFilesPerCommit)\n positive('levels.minimumAdded', config.levels?.minimumAdded)\n const percentage = (path: string, value: unknown): void => {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 100) {\n problems.push(\n `${path} must be a percentage above 0 and at most 100, got ${JSON.stringify(value)}`,\n )\n }\n }\n percentage('levels.low', config.levels?.low)\n percentage('levels.above', config.levels?.above)\n percentage('levels.watch', config.levels?.watch)\n const { low, above, watch } = config.levels ?? {}\n if (\n typeof low === 'number' &&\n typeof above === 'number' &&\n typeof watch === 'number' &&\n !(low < above && above < watch)\n ) {\n problems.push(`levels must rise: low < above < watch, got ${low}, ${above}, ${watch}`)\n }\n if (!Number.isInteger(config.listed) || config.listed < 0) {\n problems.push(\n `listed must be a whole number of 0 or more, got ${JSON.stringify(config.listed)}`,\n )\n }\n if (typeof config.includeTests !== 'boolean') {\n problems.push(`includeTests must be true or false, got ${JSON.stringify(config.includeTests)}`)\n }\n strings('include', config.include, false)\n strings('tests', config.tests, true)\n strings('ignore', config.ignore, true)\n return problems\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE,QAAU;AAAA,IACR,YAAc;AAAA,IACd,YAAc;AAAA,EAChB;AAAA,EACA,mBAAqB;AAAA,EACrB,QAAU;AAAA,IACR,cAAgB;AAAA,IAChB,KAAO;AAAA,IACP,OAAS;AAAA,IACT,OAAS;AAAA,EACX;AAAA,EACA,SAAW,CAAC,iDAAiD;AAAA,EAC7D,cAAgB;AAAA,EAChB,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAU;AACZ;;;ACNO,IAAM,SAAS;AAGf,IAAM,yBAAyB;AAQ/B,IAAM,aAAa;AAMnB,IAAM,UAAU;AAAA,EACrB,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AACR;AAqEO,IAAM,WAA8B;;;AC/D3C,SAAS,UAAa,MAAS,OAAmB;AAChD,MAAI,CAAC,cAAc,KAAK,EAAG,QAAO;AAClC,MAAI,CAAC,cAAc,IAAI,EAAG,QAAO;AACjC,QAAM,MAA+B,EAAE,GAAG,KAAK;AAC/C,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,GAAG,IAAI,cAAc,KAAK,IAAI,UAAU,IAAI,GAAG,GAAG,KAAK,IAAI;AAAA,EACjE;AACA,SAAO;AACT;AAGA,SAA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