textoneitor 0.0.0-stage → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +101 -0
  2. package/LICENSE-AGPL-3.0 +661 -0
  3. package/README.md +69 -2
  4. package/dist/api/index.d.ts +34 -0
  5. package/dist/api/index.js +98 -0
  6. package/dist/baseline/index.d.ts +20 -0
  7. package/dist/baseline/index.js +81 -0
  8. package/dist/bundle/dist/cli.mjs +29861 -0
  9. package/dist/bundle/package.json +6 -0
  10. package/dist/bundle/rulepack/rulepack.json +1496 -0
  11. package/dist/bundle/rules/situaciones.yml +27 -0
  12. package/dist/cli/benchmark.d.ts +89 -0
  13. package/dist/cli/benchmark.js +185 -0
  14. package/dist/cli/main.d.ts +2 -0
  15. package/dist/cli/main.js +357 -0
  16. package/dist/config/core.d.ts +55 -0
  17. package/dist/config/core.js +244 -0
  18. package/dist/config/glob.d.ts +2 -0
  19. package/dist/config/glob.js +72 -0
  20. package/dist/config/index.d.ts +8 -0
  21. package/dist/config/index.js +38 -0
  22. package/dist/config/situaciones.d.ts +17 -0
  23. package/dist/config/situaciones.js +43 -0
  24. package/dist/contracts/index.d.ts +238 -0
  25. package/dist/contracts/index.js +4 -0
  26. package/dist/document/index.d.ts +10 -0
  27. package/dist/document/index.js +68 -0
  28. package/dist/document/text.d.ts +22 -0
  29. package/dist/document/text.js +91 -0
  30. package/dist/document/tokenize.d.ts +4 -0
  31. package/dist/document/tokenize.js +59 -0
  32. package/dist/markdown/index.d.ts +7 -0
  33. package/dist/markdown/index.js +178 -0
  34. package/dist/paths.d.ts +4 -0
  35. package/dist/paths.js +14 -0
  36. package/dist/reporters/index.d.ts +29 -0
  37. package/dist/reporters/index.js +182 -0
  38. package/dist/rules/compiler/build.d.ts +1 -0
  39. package/dist/rules/compiler/build.js +46 -0
  40. package/dist/rules/compiler/index.d.ts +40 -0
  41. package/dist/rules/compiler/index.js +343 -0
  42. package/dist/rules/compiler/safety.d.ts +16 -0
  43. package/dist/rules/compiler/safety.js +124 -0
  44. package/dist/rules/detectors/index.d.ts +4 -0
  45. package/dist/rules/detectors/index.js +636 -0
  46. package/dist/rules/detectors/shared.d.ts +30 -0
  47. package/dist/rules/detectors/shared.js +87 -0
  48. package/dist/rules/runtime/index.d.ts +17 -0
  49. package/dist/rules/runtime/index.js +74 -0
  50. package/dist/runner/index.d.ts +16 -0
  51. package/dist/runner/index.js +171 -0
  52. package/dist/runner/lint-text.d.ts +19 -0
  53. package/dist/runner/lint-text.js +20 -0
  54. package/dist/scoring/index.d.ts +16 -0
  55. package/dist/scoring/index.js +41 -0
  56. package/dist/suppressions/index.d.ts +23 -0
  57. package/dist/suppressions/index.js +86 -0
  58. package/dist/web/engine.meta.json +1 -0
  59. package/dist/web/engine.mjs +11018 -0
  60. package/dist/web/index.d.ts +39 -0
  61. package/dist/web/index.js +37 -0
  62. package/dist/web/node-crypto-shim.d.ts +9 -0
  63. package/dist/web/node-crypto-shim.js +24 -0
  64. package/dist/web/sha256.d.ts +11 -0
  65. package/dist/web/sha256.js +89 -0
  66. package/package.json +88 -4
  67. package/rulepack/rulepack.json +1496 -0
  68. package/rules/profiles/academico.yml +4 -0
  69. package/rules/profiles/chat.yml +4 -0
  70. package/rules/profiles/correo.yml +3 -0
  71. package/rules/profiles/general.yml +2 -0
  72. package/rules/profiles/marketing.yml +4 -0
  73. package/rules/profiles/readme.yml +5 -0
  74. package/rules/profiles/redes.yml +6 -0
  75. package/rules/profiles/tecnico.yml +4 -0
  76. package/rules/situaciones.yml +27 -0
  77. package/schemas/rule.schema.json +90 -0
@@ -0,0 +1,27 @@
1
+ # Situaciones: la capa de contexto de la humanización (docs/decisions.md, 2026-09-18).
2
+ #
3
+ # Cada situación junta tres cosas:
4
+ # perfil el perfil de reglas con el que se revisa (rules/profiles/<perfil>.yml)
5
+ # guia el principio de su viñeta en la sección «Según la situación» de la guía
6
+ # (integrations/claude-code/guia/humano.md); el gate `situaciones` comprueba que existe
7
+ # archivos los tipos de archivo de texto que le corresponden. Con `--profile auto`, la ruta decide la situación:
8
+ # gana la primera que coincide. Un archivo que no coincide con ninguna no se revisa con `auto`.
9
+ #
10
+ # Los overrides de textoneitor.yml siguen mandando sobre esto.
11
+ schema_version: 1
12
+ situaciones:
13
+ - id: chat
14
+ perfil: chat
15
+ guia: "Conversación"
16
+ - id: correo
17
+ perfil: correo
18
+ guia: "Correo"
19
+ archivos: ["**/correo*.{md,txt}", "**/*.correo.md", "**/correos/**/*.{md,txt}"]
20
+ - id: readme
21
+ perfil: readme
22
+ guia: "README y textos de un proyecto"
23
+ archivos: ["**/README*.md", "**/CHANGELOG*.md", "**/CONTRIBUTING*.md", "**/docs/**/*.md"]
24
+ - id: redes
25
+ perfil: redes
26
+ guia: "Redes"
27
+ archivos: ["**/*.post.md", "**/redes/**/*.{md,txt}"]
@@ -0,0 +1,89 @@
1
+ import { type RunnerContext } from "../runner/index.js";
2
+ export interface CorpusSample {
3
+ id: string;
4
+ class: "human" | "ai";
5
+ file: string;
6
+ register: string;
7
+ sha256: string;
8
+ [k: string]: unknown;
9
+ }
10
+ export interface BenchmarkReport {
11
+ schema_version: 1;
12
+ partition: string;
13
+ tool: {
14
+ version: string;
15
+ rulepack: string;
16
+ };
17
+ config: {
18
+ threshold: number;
19
+ min_words_for_index: number;
20
+ profile: string;
21
+ register?: string;
22
+ annotations?: string;
23
+ };
24
+ corpus: {
25
+ samples: number;
26
+ human: number;
27
+ ai: number;
28
+ human_words: number;
29
+ ai_words: number;
30
+ manifest_sha256: string;
31
+ };
32
+ per_rule: Record<string, {
33
+ status: string;
34
+ findings_human: number;
35
+ findings_ai: number;
36
+ docs_human: number;
37
+ docs_ai: number;
38
+ fp_per_1000_human_words: number;
39
+ per_1000_ai_words: number;
40
+ adjudicated: {
41
+ correct: number;
42
+ incorrect: number;
43
+ precision: number | null;
44
+ };
45
+ by_register: Record<string, {
46
+ human: number;
47
+ ai: number;
48
+ }>;
49
+ ms: number;
50
+ }>;
51
+ aggregate: {
52
+ threshold: number;
53
+ confusion: {
54
+ tp: number;
55
+ fp: number;
56
+ tn: number;
57
+ fn: number;
58
+ skipped_short: number;
59
+ };
60
+ tpr: number | null;
61
+ fpr: number | null;
62
+ precision: number | null;
63
+ balanced_accuracy: number | null;
64
+ ci95: {
65
+ tpr: [number, number] | null;
66
+ fpr: [number, number] | null;
67
+ };
68
+ index_median_human: number;
69
+ index_median_ai: number;
70
+ by_register: Record<string, {
71
+ n_human: number;
72
+ n_ai: number;
73
+ median_human: number | null;
74
+ median_ai: number | null;
75
+ }>;
76
+ };
77
+ notes: string[];
78
+ }
79
+ /** Contexto con el que se evalúa un corpus: reglas a su nivel por defecto en el perfil pedido, sin overrides ni caché. Lo usa también dump-findings. */
80
+ export declare function benchmarkContext(ctx: RunnerContext): RunnerContext;
81
+ /**
82
+ * `annotations`: archivo de adjudicaciones. Sin él se busca `benchmark/annotations/<partición>.yml` junto al corpus, que es lo que
83
+ * reproducen los informes publicados. Ese nombre no lleva versión y lo comparten corpus distintos con la misma partición, así que
84
+ * para adjudicar un corpus concreto hay que pasar el archivo.
85
+ */
86
+ export declare function runBenchmark(ctx: RunnerContext, corpusDir: string, partition: string, opts?: {
87
+ register?: string;
88
+ annotations?: string;
89
+ }): BenchmarkReport;
@@ -0,0 +1,185 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { parse as parseYaml } from "yaml";
5
+ import { lintDocumentText } from "../runner/index.js";
6
+ import { buildDocument } from "../document/index.js";
7
+ import { runRules } from "../rules/runtime/index.js";
8
+ function wilson(k, n) {
9
+ if (n === 0)
10
+ return null;
11
+ const z = 1.96;
12
+ const p = k / n;
13
+ const d = 1 + (z * z) / n;
14
+ const c = p + (z * z) / (2 * n);
15
+ const m = z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n));
16
+ return [round3((c - m) / d), round3((c + m) / d)];
17
+ }
18
+ const round3 = (x) => Math.round(x * 1000) / 1000;
19
+ const median = (a) => {
20
+ if (!a.length)
21
+ return 0;
22
+ const s = [...a].sort((x, y) => x - y);
23
+ const m = s.length >> 1;
24
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
25
+ };
26
+ /** Contexto con el que se evalúa un corpus: reglas a su nivel por defecto en el perfil pedido, sin overrides ni caché. Lo usa también dump-findings. */
27
+ export function benchmarkContext(ctx) {
28
+ return { ...ctx, config: { ...ctx.config, rules: {}, overrides: [], cache: { ...ctx.config.cache, enabled: false } } };
29
+ }
30
+ /**
31
+ * `annotations`: archivo de adjudicaciones. Sin él se busca `benchmark/annotations/<partición>.yml` junto al corpus, que es lo que
32
+ * reproducen los informes publicados. Ese nombre no lleva versión y lo comparten corpus distintos con la misma partición, así que
33
+ * para adjudicar un corpus concreto hay que pasar el archivo.
34
+ */
35
+ export function runBenchmark(ctx, corpusDir, partition, opts = {}) {
36
+ const manifestPath = path.join(corpusDir, "manifests", `${partition}.yml`);
37
+ if (!fs.existsSync(manifestPath))
38
+ throw new Error(`no existe el manifiesto ${manifestPath}`);
39
+ const manifestRaw = fs.readFileSync(manifestPath, "utf8");
40
+ const manifest = parseYaml(manifestRaw);
41
+ // Filtro por registro: un corpus con varios registros se evalúa con el perfil de cada uno por separado.
42
+ const selected = opts.register ? manifest.samples.filter((s) => s.register === opts.register) : manifest.samples;
43
+ if (opts.register && !selected.length)
44
+ throw new Error(`el manifiesto ${partition} no tiene muestras del registro ${opts.register}`);
45
+ const benchRoot = path.resolve(corpusDir, "..", "benchmark");
46
+ const thrFile = path.join(benchRoot, "configs", "threshold.yml");
47
+ const threshold = fs.existsSync(thrFile) ? Number(parseYaml(fs.readFileSync(thrFile, "utf8")).index_threshold) : 20;
48
+ if (opts.annotations && !fs.existsSync(opts.annotations))
49
+ throw new Error(`no existe el archivo de adjudicaciones ${opts.annotations}`);
50
+ const annFile = opts.annotations ?? path.join(benchRoot, "annotations", `${partition}.yml`);
51
+ const ann = fs.existsSync(annFile) ? parseYaml(fs.readFileSync(annFile, "utf8")) ?? {} : {};
52
+ const usedKeys = new Set();
53
+ // El benchmark siempre se ejecuta con todas las reglas activas a su nivel por defecto y sin caché.
54
+ const bctx = benchmarkContext(ctx);
55
+ const perRule = {};
56
+ for (const r of ctx.pack.rules) {
57
+ perRule[r.id] = {
58
+ status: r.status, findings_human: 0, findings_ai: 0, docs_human: 0, docs_ai: 0, fp_per_1000_human_words: 0,
59
+ per_1000_ai_words: 0, adjudicated: { correct: 0, incorrect: 0, precision: null }, by_register: {}, ms: 0,
60
+ };
61
+ }
62
+ let humanWords = 0;
63
+ let aiWords = 0;
64
+ const idx = [];
65
+ const notes = [];
66
+ for (const s of selected) {
67
+ const abs = path.join(corpusDir, s.file);
68
+ const text = fs.readFileSync(abs, "utf8");
69
+ const sha = createHash("sha256").update(text).digest("hex");
70
+ if (sha !== s.sha256)
71
+ throw new Error(`hash distinto para ${s.id}: el corpus no coincide con el manifiesto`);
72
+ const res = lintDocumentText(text, bctx, { relPath: s.file });
73
+ const tdoc = buildDocument(text, { path: s.file });
74
+ for (const r of ctx.pack.rules) {
75
+ const t0 = performance.now();
76
+ runRules(tdoc, [r]);
77
+ perRule[r.id].ms += performance.now() - t0;
78
+ }
79
+ if (s.class === "human")
80
+ humanWords += res.score.eligibleWords;
81
+ else
82
+ aiWords += res.score.eligibleWords;
83
+ idx.push({ cls: s.class, register: s.register, index: res.score.index });
84
+ const seen = new Set();
85
+ for (const f of res.findings) {
86
+ const pr = perRule[f.rule];
87
+ if (!pr)
88
+ continue;
89
+ if (s.class === "human")
90
+ pr.findings_human++;
91
+ else
92
+ pr.findings_ai++;
93
+ const br = (pr.by_register[s.register] ??= { human: 0, ai: 0 });
94
+ br[s.class]++;
95
+ if (!seen.has(f.rule)) {
96
+ seen.add(f.rule);
97
+ if (s.class === "human")
98
+ pr.docs_human++;
99
+ else
100
+ pr.docs_ai++;
101
+ }
102
+ const key = `${s.id}|${f.rule}|${f.fingerprint}`;
103
+ const a = ann.adjudications?.[key];
104
+ if (a)
105
+ usedKeys.add(key);
106
+ if (a === "correct")
107
+ pr.adjudicated.correct++;
108
+ else if (a === "incorrect")
109
+ pr.adjudicated.incorrect++;
110
+ }
111
+ }
112
+ for (const pr of Object.values(perRule)) {
113
+ pr.ms = Math.round(pr.ms * 10) / 10;
114
+ pr.fp_per_1000_human_words = humanWords ? round3((pr.findings_human * 1000) / humanWords) : 0;
115
+ pr.per_1000_ai_words = aiWords ? round3((pr.findings_ai * 1000) / aiWords) : 0;
116
+ const n = pr.adjudicated.correct + pr.adjudicated.incorrect;
117
+ pr.adjudicated.precision = n ? round3(pr.adjudicated.correct / n) : null;
118
+ }
119
+ let tp = 0, fp = 0, tn = 0, fn = 0, skipped = 0;
120
+ for (const d of idx) {
121
+ if (d.index === null) {
122
+ skipped++;
123
+ continue;
124
+ }
125
+ const flagged = d.index >= threshold;
126
+ if (d.cls === "ai")
127
+ flagged ? tp++ : fn++;
128
+ else
129
+ flagged ? fp++ : tn++;
130
+ }
131
+ const tpr = tp + fn ? round3(tp / (tp + fn)) : null;
132
+ const fpr = fp + tn ? round3(fp / (fp + tn)) : null;
133
+ const registers = [...new Set(idx.map((d) => d.register))].sort();
134
+ const byReg = {};
135
+ for (const r of registers) {
136
+ const h = idx.filter((d) => d.register === r && d.cls === "human" && d.index !== null).map((d) => d.index);
137
+ const a = idx.filter((d) => d.register === r && d.cls === "ai" && d.index !== null).map((d) => d.index);
138
+ byReg[r] = { n_human: h.length, n_ai: a.length, median_human: h.length ? median(h) : null, median_ai: a.length ? median(a) : null };
139
+ }
140
+ if (!ann.adjudications)
141
+ notes.push("Sin adjudicaciones para esta partición: la precisión adjudicada por regla es null.");
142
+ else if (opts.annotations) {
143
+ // Una adjudicación que no casa con ningún hallazgo suele ser una huella vieja: el texto o la regla cambiaron después de adjudicar.
144
+ const huerfanas = Object.keys(ann.adjudications).filter((k) => !usedKeys.has(k)).length;
145
+ if (huerfanas)
146
+ notes.push(`${huerfanas} adjudicaciones no corresponden a ningún hallazgo de esta ejecución.`);
147
+ }
148
+ notes.push("No se publica recall por regla: el corpus no está anotado exhaustivamente.");
149
+ notes.push("El índice mide densidad de patrones editoriales; el umbral solo se usa para evaluar separación, no como veredicto de autoría.");
150
+ return {
151
+ schema_version: 1,
152
+ partition,
153
+ tool: { version: ctx.toolVersion, rulepack: ctx.pack.version },
154
+ config: {
155
+ threshold,
156
+ min_words_for_index: bctx.config.min_words_for_index,
157
+ profile: bctx.config.profile,
158
+ ...(opts.register ? { register: opts.register } : {}),
159
+ // Relativa a la carpeta que contiene el corpus, para que el informe no lleve rutas del equipo.
160
+ ...(opts.annotations ? { annotations: path.relative(path.resolve(corpusDir, ".."), path.resolve(opts.annotations)).replace(/\\/g, "/") } : {}),
161
+ },
162
+ corpus: {
163
+ samples: selected.length,
164
+ human: selected.filter((s) => s.class === "human").length,
165
+ ai: selected.filter((s) => s.class === "ai").length,
166
+ human_words: humanWords,
167
+ ai_words: aiWords,
168
+ manifest_sha256: createHash("sha256").update(manifestRaw).digest("hex"),
169
+ },
170
+ per_rule: perRule,
171
+ aggregate: {
172
+ threshold,
173
+ confusion: { tp, fp, tn, fn, skipped_short: skipped },
174
+ tpr,
175
+ fpr,
176
+ precision: tp + fp ? round3(tp / (tp + fp)) : null,
177
+ balanced_accuracy: tpr !== null && fpr !== null ? round3((tpr + (1 - fpr)) / 2) : null,
178
+ ci95: { tpr: wilson(tp, tp + fn), fpr: wilson(fp, fp + tn) },
179
+ index_median_human: median(idx.filter((d) => d.cls === "human" && d.index !== null).map((d) => d.index)),
180
+ index_median_ai: median(idx.filter((d) => d.cls === "ai" && d.index !== null).map((d) => d.index)),
181
+ by_register: byReg,
182
+ },
183
+ notes,
184
+ };
185
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,357 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { Command, CommanderError } from "commander";
5
+ import fg from "fast-glob";
6
+ import { explainConfig, loadConfig } from "../config/index.js";
7
+ import { loadSituaciones, overridesDeSituaciones, situacionDe } from "../config/situaciones.js";
8
+ import { createBaseline, readBaseline, updateBaseline, writeBaseline } from "../baseline/index.js";
9
+ import { render } from "../reporters/index.js";
10
+ import { scanProject, lintDocumentText, evaluatePolicy } from "../runner/index.js";
11
+ import { loadRulePack, toolVersion } from "../api/index.js";
12
+ import { SCHEMA_VERSION } from "../contracts/index.js";
13
+ /** Códigos de salida: 0 OK, 1 la política falla, 2 error de uso o configuración. */
14
+ /** Nombre por defecto de la baseline. El viejo se sigue leyendo si es el que hay en el proyecto. */
15
+ const BASELINE_DEFECTO = "textoneitor-baseline.json";
16
+ const BASELINE_ANTERIOR = "ia-linter-baseline.json";
17
+ const EXIT_FAIL = 1;
18
+ const EXIT_USAGE = 2;
19
+ function die(msg) {
20
+ process.stderr.write(`textoneitor: ${msg}\n`);
21
+ process.exit(EXIT_USAGE);
22
+ }
23
+ function context(g) {
24
+ const cwd = path.resolve(g.cwd ?? process.cwd());
25
+ const loaded = loadConfig({ cwd, file: g.config });
26
+ if (g.config && !fs.existsSync(path.resolve(cwd, g.config)))
27
+ die(`no existe el archivo de configuración ${g.config}`);
28
+ if (loaded.issues.length) {
29
+ die(`configuración inválida (${loaded.file}):\n` + loaded.issues.map((i) => ` ${i.path || "(raíz)"}: ${i.message}`).join("\n"));
30
+ }
31
+ let pack;
32
+ try {
33
+ pack = loadRulePack(g.rulepack);
34
+ }
35
+ catch (e) {
36
+ die(e.message);
37
+ }
38
+ // Un id mal escrito en `rules` u `overrides` no hace nada: se avisa en vez de callarlo (config validate lo trata como error).
39
+ const known = new Set(pack.rules.flatMap((r) => [r.id, `${r.category}/*`]));
40
+ const unknown = [
41
+ ...Object.keys(loaded.config.rules).filter((k) => !known.has(k)).map((k) => `rules.${k}`),
42
+ ...loaded.config.overrides.flatMap((o, i) => Object.keys(o.rules ?? {}).filter((k) => !known.has(k)).map((k) => `overrides[${i}].rules.${k}`)),
43
+ ];
44
+ for (const u of unknown)
45
+ process.stderr.write(`textoneitor: aviso: ${u} no es ninguna regla ni categoría; se ignora\n`);
46
+ return { config: loaded.config, root: loaded.root, pack, toolVersion: toolVersion(), configFile: loaded.file, cwd };
47
+ }
48
+ /**
49
+ * Las rutas de la línea de órdenes son relativas al directorio de trabajo, no a la raíz del proyecto
50
+ * (la carpeta del textoneitor.yml). Las que existen se pasan absolutas; los globs se anclan al directorio de trabajo.
51
+ */
52
+ function rutasDesde(cwd, root, rutas) {
53
+ if (path.resolve(cwd) === path.resolve(root))
54
+ return rutas;
55
+ const prefijo = fg.convertPathToPattern(path.relative(root, cwd).replace(/\\/g, "/"));
56
+ return rutas.map((r) => (fs.existsSync(path.resolve(cwd, r)) ? path.resolve(cwd, r) : `${prefijo}/${r.replace(/\\/g, "/")}`));
57
+ }
58
+ function readStdin() {
59
+ return fs.readFileSync(0, "utf8");
60
+ }
61
+ const program = new Command();
62
+ // Los errores de uso que detecta commander (opción o comando desconocido, falta un argumento) salen con 2, no con su 1
63
+ // por defecto, que se confundiría con «la política falla». Va antes de declarar subcomandos para que lo hereden.
64
+ program.exitOverride();
65
+ program
66
+ .name("textoneitor")
67
+ .description("Revisor de textos en español: marca lo que suena a máquina y explica por qué. Mide patrones editoriales, no autoría.")
68
+ .version(toolVersion())
69
+ .option("-c, --config <archivo>", "archivo de configuración (por defecto se busca textoneitor.yml hacia arriba)")
70
+ .option("--cwd <dir>", "directorio de trabajo")
71
+ .option("--rulepack <archivo>", "Rule Pack alternativo (JSON compilado)");
72
+ program
73
+ .command("lint")
74
+ .description("analiza archivos, directorios o globs")
75
+ .argument("[rutas...]", "archivos, directorios o globs (por defecto, el proyecto)")
76
+ .option("-f, --format <reporter>", "terminal | json | sarif | revision")
77
+ .option("-o, --output <archivo>", "escribe el informe en un archivo")
78
+ .option("--stdin", "lee el texto de la entrada estándar")
79
+ .option("--stdin-filename <nombre>", "nombre lógico para --stdin (decide formato y overrides)")
80
+ .option("--fail-on <nivel>", "never | info | warning | error")
81
+ .option("--max-index <n>", "falla si el índice de algún archivo supera n")
82
+ .option("--profile <perfil>", "general | tecnico | academico | marketing | chat | correo | readme | redes | auto (por la ruta, según situaciones.yml)")
83
+ .option("--baseline <archivo>", "baseline a aplicar")
84
+ .option("--no-baseline", "ignora la baseline configurada")
85
+ .option("--no-cache", "no usa la caché")
86
+ .option("--no-color", "sin color")
87
+ .option("-v, --verbose", "muestra snippets, contribuyentes y archivos sin hallazgos")
88
+ .action((rutas, o) => {
89
+ const ctx = context(program.opts());
90
+ if (o.failOn) {
91
+ if (!["never", "info", "warning", "error"].includes(o.failOn))
92
+ die("--fail-on debe ser never, info, warning o error");
93
+ ctx.config.fail_on = o.failOn;
94
+ }
95
+ if (o.maxIndex !== undefined) {
96
+ const n = Number(o.maxIndex);
97
+ if (!Number.isFinite(n) || n < 0 || n > 100)
98
+ die("--max-index debe estar entre 0 y 100");
99
+ ctx.config.max_index = n;
100
+ }
101
+ // `auto`: el perfil sale de la ruta según rules/situaciones.yml. Los overrides del proyecto siguen mandando.
102
+ let sinSituacion = false;
103
+ let situaciones = null;
104
+ if (o.profile === "auto") {
105
+ try {
106
+ situaciones = loadSituaciones();
107
+ }
108
+ catch (e) {
109
+ die(e.message);
110
+ }
111
+ ctx.config.overrides = [...overridesDeSituaciones(situaciones), ...ctx.config.overrides];
112
+ if (o.stdin) {
113
+ if (!o.stdinFilename)
114
+ die("--profile auto con --stdin necesita --stdin-filename: la ruta decide la situación");
115
+ sinSituacion = situacionDe(o.stdinFilename, situaciones) === null;
116
+ }
117
+ }
118
+ else if (o.profile) {
119
+ if (!["general", "tecnico", "academico", "marketing", "chat", "correo", "readme", "redes"].includes(o.profile))
120
+ die("--profile inválido");
121
+ ctx.config.profile = o.profile;
122
+ }
123
+ const reporter = (o.format ?? ctx.config.reporter);
124
+ if (!["terminal", "json", "sarif", "revision"].includes(reporter))
125
+ die("--format debe ser terminal, json, sarif o revision");
126
+ let result;
127
+ if (o.stdin) {
128
+ if (rutas.length)
129
+ process.stderr.write(`textoneitor: aviso: con --stdin se analiza la entrada estándar y se ignoran las rutas (${rutas.join(", ")})\n`);
130
+ if (sinSituacion)
131
+ process.stderr.write(`textoneitor: ${o.stdinFilename} no corresponde a ninguna situación de situaciones.yml; con --profile auto no se analiza\n`);
132
+ const files = sinSituacion ? [] : [lintDocumentText(readStdin(), ctx, { relPath: o.stdinFilename, format: o.stdinFilename ? undefined : "text" })];
133
+ result = {
134
+ schema_version: SCHEMA_VERSION,
135
+ tool: { name: "textoneitor", version: ctx.toolVersion, rulepack: ctx.pack.version },
136
+ files,
137
+ policy: evaluatePolicy(files, ctx.config),
138
+ durationMs: 0,
139
+ };
140
+ }
141
+ else {
142
+ const baseline = o.baseline === false ? null : typeof o.baseline === "string" ? o.baseline : undefined;
143
+ result = scanProject(ctx, { targets: rutasDesde(ctx.cwd, ctx.root, rutas), noCache: o.cache === false, baseline });
144
+ // Si las rutas existen pero `exclude` o .gitignore las dejan fuera (pre-commit con un CHANGELOG), no hay nada que analizar
145
+ // y no es un error. Solo es un error de uso que ninguna ruta exista ni coincida con nada.
146
+ if (rutas.length && result.files.length === 0 && !rutas.some((r) => fs.existsSync(path.resolve(ctx.cwd, r)))) {
147
+ die(`ninguna ruta coincide: ${rutas.join(", ")}`);
148
+ }
149
+ // Con `auto`, igual que con --stdin: lo que no corresponde a ninguna situación no se analiza.
150
+ if (situaciones) {
151
+ const sit = situaciones;
152
+ const fuera = result.files.filter((f) => situacionDe(f.path, sit) === null);
153
+ if (fuera.length) {
154
+ process.stderr.write(`textoneitor: ${fuera.length} archivo(s) sin situación en situaciones.yml; con --profile auto no se analizan (${fuera.slice(0, 5).map((f) => f.path).join(", ")}${fuera.length > 5 ? ", …" : ""})\n`);
155
+ const files = result.files.filter((f) => !fuera.includes(f));
156
+ result = { ...result, files, policy: evaluatePolicy(files, ctx.config) };
157
+ }
158
+ }
159
+ }
160
+ const color = o.color !== false && reporter === "terminal" && !o.output && process.stdout.isTTY === true && !process.env.NO_COLOR;
161
+ const out = render(reporter, result, ctx.pack.rules, { color, verbose: o.verbose, uriBase: pathToFileUri(ctx.root) });
162
+ if (o.output)
163
+ fs.writeFileSync(path.resolve(o.output), out, "utf8");
164
+ else
165
+ process.stdout.write(out);
166
+ process.exitCode = result.policy.ok ? 0 : EXIT_FAIL;
167
+ });
168
+ const rules = program.command("rules").description("consulta las reglas del Rule Pack");
169
+ rules
170
+ .command("list")
171
+ .option("--json", "salida JSON")
172
+ .option("--status <estado>", "filtra por estado")
173
+ .action((o) => {
174
+ const ctx = context(program.opts());
175
+ const list = ctx.pack.rules.filter((r) => !o.status || r.status === o.status);
176
+ if (o.json) {
177
+ process.stdout.write(JSON.stringify(list.map((r) => ({ id: r.id, status: r.status, category: r.category, detector: r.detector, default_level: r.default_level, title: r.title })), null, 2) + "\n");
178
+ return;
179
+ }
180
+ const w = Math.max(...list.map((r) => r.id.length));
181
+ for (const r of list)
182
+ process.stdout.write(`${r.id.padEnd(w)} ${r.status.padEnd(10)} ${r.default_level.padEnd(8)} ${r.title}\n`);
183
+ process.stdout.write(`\n${list.length} reglas (Rule Pack ${ctx.pack.version})\n`);
184
+ });
185
+ rules
186
+ .command("explain")
187
+ .argument("<id>", "identificador de la regla")
188
+ .option("--json", "salida JSON")
189
+ .action((id, o) => {
190
+ const ctx = context(program.opts());
191
+ const r = ctx.pack.rules.find((x) => x.id === id);
192
+ if (!r)
193
+ die(`regla desconocida: ${id}`);
194
+ if (o.json) {
195
+ process.stdout.write(JSON.stringify(r, null, 2) + "\n");
196
+ return;
197
+ }
198
+ process.stdout.write([
199
+ `${r.id} (rev ${r.revision}, ${r.status})`,
200
+ r.title,
201
+ "",
202
+ r.summary,
203
+ "",
204
+ r.explanation,
205
+ "",
206
+ `Orientación: ${r.rewrite_guidance}`,
207
+ "",
208
+ `Categoría: ${r.category} · Detector: ${r.detector} · Nivel: ${r.default_level} · Peso: ${r.score.weight} (cap ${r.score.cap})`,
209
+ Object.keys(r.profiles).length ? `Perfiles: ${Object.entries(r.profiles).map(([k, v]) => `${k}=${v}`).join(", ")}` : "",
210
+ "",
211
+ ].join("\n"));
212
+ });
213
+ const config = program.command("config").description("valida y explica la configuración");
214
+ /** `-c` apunta a un archivo que no existe: se dice así, no como «YAML inválido: ENOENT». */
215
+ function exigirConfig(g) {
216
+ if (g.config && !fs.existsSync(path.resolve(g.cwd ?? process.cwd(), g.config)))
217
+ die(`no existe el archivo de configuración ${g.config}`);
218
+ }
219
+ config.command("validate").action(() => {
220
+ const g = program.opts();
221
+ exigirConfig(g);
222
+ const loaded = loadConfig({ cwd: path.resolve(g.cwd ?? process.cwd()), file: g.config });
223
+ if (!loaded.file) {
224
+ process.stdout.write("Sin archivo de configuración: se usan los valores internos.\n");
225
+ return;
226
+ }
227
+ const pack = loadRulePack(g.rulepack);
228
+ const known = new Set(pack.rules.map((r) => r.id));
229
+ const cats = new Set(pack.rules.map((r) => `${r.category}/*`));
230
+ const unknown = [];
231
+ const check = (m, where) => {
232
+ for (const k of Object.keys(m ?? {}))
233
+ if (!known.has(k) && !cats.has(k))
234
+ unknown.push(`${where}.${k}`);
235
+ };
236
+ check(loaded.config.rules, "rules");
237
+ loaded.config.overrides.forEach((o, i) => check(o.rules, `overrides[${i}].rules`));
238
+ for (const i of loaded.issues)
239
+ process.stdout.write(`✘ ${i.path || "(raíz)"}: ${i.message}\n`);
240
+ for (const u of unknown)
241
+ process.stdout.write(`✘ ${u}: regla o categoría desconocida\n`);
242
+ if (loaded.issues.length || unknown.length) {
243
+ process.exitCode = EXIT_USAGE;
244
+ return;
245
+ }
246
+ process.stdout.write(`✔ ${loaded.file} es válida\n`);
247
+ });
248
+ config
249
+ .command("explain")
250
+ .argument("[archivo]", "archivo para el que se resuelve la configuración efectiva")
251
+ .option("--json", "salida JSON")
252
+ .action((archivo, o) => {
253
+ const g = program.opts();
254
+ exigirConfig(g);
255
+ const cwd = path.resolve(g.cwd ?? process.cwd());
256
+ const loaded = loadConfig({ cwd, file: g.config });
257
+ if (loaded.issues.length)
258
+ die("configuración inválida; ejecuta `config validate`");
259
+ const pack = loadRulePack(g.rulepack);
260
+ const rel = archivo ? path.relative(loaded.root, path.resolve(cwd, archivo)).replace(/\\/g, "/") : null;
261
+ const ex = explainConfig(loaded, pack.rules, rel);
262
+ if (o.json) {
263
+ process.stdout.write(JSON.stringify(ex, null, 2) + "\n");
264
+ return;
265
+ }
266
+ const c = ex.config;
267
+ process.stdout.write([
268
+ `Archivo de configuración: ${ex.file ?? "(ninguno; valores internos)"}`,
269
+ `Raíz del proyecto: ${ex.root}`,
270
+ `Archivo analizado: ${rel ?? "(ninguno)"}`,
271
+ `Perfil: ${c.profile} · Registro: ${c.register} · fail_on: ${c.fail_on} · max_index: ${c.max_index ?? "—"}`,
272
+ `Baseline: ${c.baseline.path ?? "—"} · Caché: ${c.cache.enabled ? c.cache.dir : "desactivada"} · Reporter: ${c.reporter}`,
273
+ "",
274
+ "Reglas (nivel efectivo ← origen):",
275
+ ...ex.effective.map((e) => ` ${e.rule.padEnd(40)} ${e.level.padEnd(8)} ← ${e.source}: ${e.detail}`),
276
+ "",
277
+ ].join("\n"));
278
+ });
279
+ const baseline = program.command("baseline").description("gestiona la baseline de hallazgos existentes");
280
+ baseline
281
+ .command("create")
282
+ .argument("[rutas...]")
283
+ .option("-o, --output <archivo>", "ruta de la baseline")
284
+ .option("--reason <texto>", "motivo que se guarda en cada entrada")
285
+ .action((rutas, o) => {
286
+ const ctx = context(program.opts());
287
+ const out = o.output ?? ctx.config.baseline.path ?? BASELINE_DEFECTO;
288
+ if (ctx.config.baseline.require_reason && !o.reason)
289
+ die("la configuración exige --reason para crear la baseline");
290
+ const result = scanProject(ctx, { targets: rutasDesde(ctx.cwd, ctx.root, rutas), baseline: null, noCache: true });
291
+ const b = createBaseline(result.files, o.reason);
292
+ writeBaseline(path.resolve(ctx.root, out), b);
293
+ process.stdout.write(`Baseline creada: ${out} (${b.entries.length} entradas)\n`);
294
+ });
295
+ baseline
296
+ .command("update")
297
+ .argument("[rutas...]")
298
+ .option("-o, --output <archivo>", "ruta de la baseline")
299
+ .option("--add-new", "añade también los hallazgos nuevos")
300
+ .option("--reason <texto>", "motivo para las entradas nuevas")
301
+ .action((rutas, o) => {
302
+ const ctx = context(program.opts());
303
+ // Si no se dice cuál y la del nombre nuevo no está, se usa la del nombre viejo.
304
+ const porDefecto = !fs.existsSync(path.resolve(ctx.root, BASELINE_DEFECTO)) && fs.existsSync(path.resolve(ctx.root, BASELINE_ANTERIOR))
305
+ ? BASELINE_ANTERIOR
306
+ : BASELINE_DEFECTO;
307
+ const out = o.output ?? ctx.config.baseline.path ?? porDefecto;
308
+ const abs = path.resolve(ctx.root, out);
309
+ if (!fs.existsSync(abs))
310
+ die(`no existe la baseline ${out}; usa \`baseline create\``);
311
+ if (o.addNew && ctx.config.baseline.require_reason && !o.reason)
312
+ die("la configuración exige --reason para añadir entradas");
313
+ const existing = readBaseline(abs);
314
+ const result = scanProject(ctx, { targets: rutasDesde(ctx.cwd, ctx.root, rutas), baseline: null, noCache: true });
315
+ const b = updateBaseline(existing, result.files, { addNew: Boolean(o.addNew), reason: o.reason });
316
+ writeBaseline(abs, b);
317
+ process.stdout.write(`Baseline actualizada: ${out} (${existing.entries.length} → ${b.entries.length} entradas)\n`);
318
+ });
319
+ program
320
+ .command("benchmark")
321
+ .description("ejecuta el benchmark reproducible sobre un corpus con manifiestos")
322
+ .command("run")
323
+ .requiredOption("--corpus <dir>", "directorio raíz del corpus")
324
+ .requiredOption("--partition <nombre>", "development | holdout | challenge")
325
+ .option("--profile <perfil>", "perfil con el que evaluar el corpus (queda registrado en el informe)")
326
+ .option("--register <registro>", "evalúa solo las muestras de ese registro del manifiesto")
327
+ .option("--annotations <archivo>", "adjudicaciones de hallazgos; sin esta opción se usa benchmark/annotations/<partición>.yml")
328
+ .option("-o, --output <archivo>", "informe JSON")
329
+ .action(async (o) => {
330
+ if (o.profile && !["general", "tecnico", "academico", "marketing", "chat", "correo", "readme", "redes"].includes(o.profile))
331
+ die("--profile inválido");
332
+ const base = context(program.opts());
333
+ const ctx = o.profile ? { ...base, config: { ...base.config, profile: o.profile } } : base;
334
+ const { runBenchmark } = await import("./benchmark.js");
335
+ const report = runBenchmark(ctx, path.resolve(o.corpus), o.partition, {
336
+ ...(o.register ? { register: String(o.register) } : {}),
337
+ ...(o.annotations ? { annotations: path.resolve(String(o.annotations)) } : {}),
338
+ });
339
+ const json = JSON.stringify(report, null, 2) + "\n";
340
+ if (o.output) {
341
+ fs.mkdirSync(path.dirname(path.resolve(o.output)), { recursive: true });
342
+ fs.writeFileSync(path.resolve(o.output), json, "utf8");
343
+ process.stdout.write(`Informe: ${o.output}\n`);
344
+ }
345
+ else
346
+ process.stdout.write(json);
347
+ });
348
+ function pathToFileUri(p) {
349
+ const s = p.replace(/\\/g, "/");
350
+ return (s.startsWith("/") ? `file://${encodeURI(s)}` : `file:///${encodeURI(s)}`) + "/";
351
+ }
352
+ program.parseAsync(process.argv).catch((e) => {
353
+ // commander ya ha escrito su mensaje; --help y --version salen con 0.
354
+ if (e instanceof CommanderError)
355
+ process.exit(e.exitCode === 0 ? 0 : EXIT_USAGE);
356
+ die(e.message);
357
+ });