agent-rules-init 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -0
  3. package/dist/cli.d.ts +38 -1
  4. package/dist/cli.js +203 -40
  5. package/dist/core/canonical-commands.d.ts +4 -0
  6. package/dist/core/canonical-commands.js +169 -0
  7. package/dist/core/config.d.ts +25 -0
  8. package/dist/core/config.js +125 -0
  9. package/dist/core/i18n.d.ts +47 -0
  10. package/dist/core/i18n.js +207 -0
  11. package/dist/core/llm-bridge.d.ts +5 -1
  12. package/dist/core/llm-bridge.js +56 -4
  13. package/dist/core/project-unit-output.d.ts +13 -0
  14. package/dist/core/project-unit-output.js +25 -0
  15. package/dist/core/project-units.d.ts +16 -0
  16. package/dist/core/project-units.js +95 -0
  17. package/dist/core/prompt-engine.d.ts +3 -1
  18. package/dist/core/prompt-engine.js +19 -14
  19. package/dist/core/repo-facts.d.ts +30 -0
  20. package/dist/core/repo-facts.js +420 -0
  21. package/dist/core/scanner.js +153 -27
  22. package/dist/core/templates.d.ts +6 -4
  23. package/dist/core/templates.js +127 -29
  24. package/dist/core/types.d.ts +84 -2
  25. package/dist/core/writer.d.ts +1 -1
  26. package/dist/core/writer.js +6 -4
  27. package/dist/packs/cpp.js +33 -27
  28. package/dist/packs/csharp.js +32 -27
  29. package/dist/packs/dart.js +30 -31
  30. package/dist/packs/elixir.js +31 -27
  31. package/dist/packs/go.js +31 -27
  32. package/dist/packs/java.js +82 -30
  33. package/dist/packs/js-ts.js +150 -37
  34. package/dist/packs/kotlin.js +56 -31
  35. package/dist/packs/php.js +30 -27
  36. package/dist/packs/python.js +107 -34
  37. package/dist/packs/r.js +30 -27
  38. package/dist/packs/ruby.js +36 -27
  39. package/dist/packs/rust.js +33 -27
  40. package/dist/packs/scala.js +32 -27
  41. package/dist/packs/swift.js +31 -27
  42. package/package.json +7 -4
@@ -0,0 +1,125 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parse } from "yaml";
4
+ const CONFIG_FILENAMES = [".agent-rules-init.yml", ".agent-rules-init.yaml"];
5
+ const ROOT_KEYS = new Set(["lang", "exclude", "projects", "noAi"]);
6
+ const PROJECT_KEYS = ["framework", "testRunner", "linter", "packageManager"];
7
+ const PROJECT_KEY_SET = new Set(PROJECT_KEYS);
8
+ export class ConfigError extends Error {
9
+ configPath;
10
+ constructor(message, configPath, options) {
11
+ super(message, options);
12
+ this.name = "ConfigError";
13
+ this.configPath = configPath;
14
+ }
15
+ }
16
+ function isRecord(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ function unknownKeyWarnings(value, allowed, location) {
20
+ return Object.keys(value)
21
+ .filter((key) => !allowed.has(key))
22
+ .map((key) => `Unknown configuration key \"${location}${key}\"; it was ignored.`);
23
+ }
24
+ function optionalNonEmptyString(value, location, warnings) {
25
+ if (value === undefined)
26
+ return undefined;
27
+ if (typeof value !== "string" || value.trim().length === 0) {
28
+ warnings.push(`Configuration key \"${location}\" must be a non-empty string; it was ignored.`);
29
+ return undefined;
30
+ }
31
+ return value.trim();
32
+ }
33
+ function validateProjects(value, warnings) {
34
+ if (value === undefined)
35
+ return undefined;
36
+ if (!isRecord(value)) {
37
+ warnings.push('Configuration key "projects" must be an object keyed by project path; it was ignored.');
38
+ return undefined;
39
+ }
40
+ const projects = {};
41
+ for (const [projectPath, rawProject] of Object.entries(value)) {
42
+ if (projectPath.trim().length === 0) {
43
+ warnings.push("A project path must not be empty; that project was ignored.");
44
+ continue;
45
+ }
46
+ if (!isRecord(rawProject)) {
47
+ warnings.push(`Configuration key \"projects.${projectPath}\" must be an object; it was ignored.`);
48
+ continue;
49
+ }
50
+ warnings.push(...unknownKeyWarnings(rawProject, PROJECT_KEY_SET, `projects.${projectPath}.`));
51
+ const project = {};
52
+ for (const key of PROJECT_KEYS) {
53
+ const parsed = optionalNonEmptyString(rawProject[key], `projects.${projectPath}.${key}`, warnings);
54
+ if (parsed !== undefined)
55
+ project[key] = parsed;
56
+ }
57
+ projects[projectPath] = project;
58
+ }
59
+ return projects;
60
+ }
61
+ function validateConfig(value, configPath, warnings) {
62
+ // An empty YAML document is equivalent to an empty configuration.
63
+ if (value === null || value === undefined)
64
+ return {};
65
+ if (!isRecord(value)) {
66
+ throw new ConfigError(`Invalid configuration in ${configPath}: the YAML root must be an object.`, configPath);
67
+ }
68
+ warnings.push(...unknownKeyWarnings(value, ROOT_KEYS, ""));
69
+ const config = {};
70
+ if (value.lang !== undefined) {
71
+ if (value.lang === "es" || value.lang === "en")
72
+ config.lang = value.lang;
73
+ else
74
+ warnings.push('Configuration key "lang" must be "es" or "en"; it was ignored.');
75
+ }
76
+ if (value.exclude !== undefined) {
77
+ if (!Array.isArray(value.exclude)) {
78
+ warnings.push('Configuration key "exclude" must be an array of strings; it was ignored.');
79
+ }
80
+ else {
81
+ const exclude = value.exclude.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
82
+ if (exclude.length !== value.exclude.length) {
83
+ warnings.push('Configuration key "exclude" contains non-string or empty entries; they were ignored.');
84
+ }
85
+ config.exclude = exclude.map((entry) => entry.trim());
86
+ }
87
+ }
88
+ const projects = validateProjects(value.projects, warnings);
89
+ if (projects !== undefined)
90
+ config.projects = projects;
91
+ if (value.noAi !== undefined) {
92
+ if (typeof value.noAi === "boolean")
93
+ config.noAi = value.noAi;
94
+ else
95
+ warnings.push('Configuration key "noAi" must be a boolean; it was ignored.');
96
+ }
97
+ return config;
98
+ }
99
+ /** Loads and validates the optional repository-local agent-rules configuration. */
100
+ export function loadConfig(rootPath) {
101
+ const found = CONFIG_FILENAMES.map((filename) => path.resolve(rootPath, filename)).filter((candidate) => fs.existsSync(candidate));
102
+ if (found.length === 0)
103
+ return { config: {}, warnings: [] };
104
+ const sourcePath = found[0];
105
+ const warnings = [];
106
+ if (found.length > 1) {
107
+ warnings.push(`Both ${CONFIG_FILENAMES.join(" and ")} exist; ${path.basename(sourcePath)} takes precedence.`);
108
+ }
109
+ let raw;
110
+ try {
111
+ raw = fs.readFileSync(sourcePath, "utf8");
112
+ }
113
+ catch (error) {
114
+ throw new ConfigError(`Cannot read configuration file ${sourcePath}.`, sourcePath, { cause: error });
115
+ }
116
+ let parsed;
117
+ try {
118
+ parsed = parse(raw);
119
+ }
120
+ catch (error) {
121
+ const detail = error instanceof Error ? ` ${error.message}` : "";
122
+ throw new ConfigError(`Invalid YAML in ${sourcePath}.${detail}`, sourcePath, { cause: error });
123
+ }
124
+ return { config: validateConfig(parsed, sourcePath, warnings), sourcePath, warnings };
125
+ }
@@ -0,0 +1,47 @@
1
+ export type Lang = "es" | "en";
2
+ export declare function detectLang(): Lang;
3
+ export declare function summarySentence(lang: Lang, language: string, framework?: string, parenthetical?: string): string;
4
+ export declare function runTestsConvention(lang: Lang, cmd?: string): string;
5
+ export declare function reviewBody(lang: Lang, focus: string, framework?: string): string;
6
+ export declare function refactorBody(lang: Lang, extra?: string): string;
7
+ export declare function testingBody(lang: Lang, runner?: string): string;
8
+ export interface UiTexts {
9
+ generatedHeader: string;
10
+ sections: {
11
+ commands: string;
12
+ structure: string;
13
+ ci: string;
14
+ conventions: string;
15
+ architecture: string;
16
+ canonical: string;
17
+ };
18
+ andMore: (count: number, file?: string) => string;
19
+ noStackFallback: string;
20
+ question: (fieldLabel: string, language: string) => string;
21
+ fieldLabels: {
22
+ framework: string;
23
+ testRunner: string;
24
+ linter: string;
25
+ packageManager: string;
26
+ };
27
+ usage: string;
28
+ automationUsage: string;
29
+ unknownOption: (flag: string) => string;
30
+ invalidLang: (value: string) => string;
31
+ noTtyWarning: string;
32
+ skippedQuestion: (message: string) => string;
33
+ polishDetected: (assistant: string) => string;
34
+ polishConfirm: (assistant: string) => string;
35
+ polishFailed: (assistant: string, error: string) => string;
36
+ polishPrompt: (content: string) => string;
37
+ polishBatchPrompt: (filesJson: string) => string;
38
+ fileSkipped: (path: string) => string;
39
+ outroWritten: string;
40
+ outroNothing: string;
41
+ unexpectedError: (message: string) => string;
42
+ cancelled: string;
43
+ dirNotes: Record<string, string>;
44
+ testDirNote: string;
45
+ entrypointNote: string;
46
+ }
47
+ export declare const UI: Record<Lang, UiTexts>;
@@ -0,0 +1,207 @@
1
+ export function detectLang() {
2
+ try {
3
+ const locale = Intl.DateTimeFormat().resolvedOptions().locale ?? "";
4
+ return locale.toLowerCase().startsWith("es") ? "es" : "en";
5
+ }
6
+ catch {
7
+ return "en";
8
+ }
9
+ }
10
+ export function summarySentence(lang, language, framework, parenthetical) {
11
+ const paren = parenthetical ? ` (${parenthetical})` : "";
12
+ if (lang === "es")
13
+ return `Proyecto ${language}${framework ? ` con ${framework}` : ""}${paren}.`;
14
+ return `${language} project${framework ? ` using ${framework}` : ""}${paren}.`;
15
+ }
16
+ export function runTestsConvention(lang, cmd) {
17
+ if (cmd) {
18
+ return lang === "es"
19
+ ? `Ejecuta los tests con ${cmd} antes de terminar una tarea.`
20
+ : `Run the tests with ${cmd} before finishing a task.`;
21
+ }
22
+ return lang === "es"
23
+ ? "Ejecuta la suite de tests del repositorio antes de terminar una tarea."
24
+ : "Run the repository's test suite before finishing a task.";
25
+ }
26
+ export function reviewBody(lang, focus, framework) {
27
+ // Con focus vacío la frase colapsa a "bugs y desviaciones" sin coma colgante.
28
+ const focusPart = focus ? `, ${focus}` : "";
29
+ if (framework) {
30
+ return lang === "es"
31
+ ? `Revisa el diff actual buscando bugs${focusPart} y desviaciones de las convenciones de ${framework}. Señala solo problemas concretos con línea de archivo.`
32
+ : `Review the current diff looking for bugs${focusPart} and deviations from ${framework} conventions. Point out only concrete issues with file and line.`;
33
+ }
34
+ return lang === "es"
35
+ ? `Revisa el diff actual buscando bugs${focusPart}. Señala solo problemas concretos con línea de archivo.`
36
+ : `Review the current diff looking for bugs${focusPart}. Point out only concrete issues with file and line.`;
37
+ }
38
+ export function refactorBody(lang, extra) {
39
+ const base = lang === "es"
40
+ ? "Propón refactors que reduzcan duplicación y mejoren la legibilidad sin cambiar comportamiento observable."
41
+ : "Propose refactors that reduce duplication and improve readability without changing observable behavior.";
42
+ return extra ? `${base} ${extra}` : base;
43
+ }
44
+ export function testingBody(lang, runner) {
45
+ if (runner) {
46
+ return lang === "es"
47
+ ? `Escribe tests con ${runner} para el código señalado. Cubre el camino feliz y al menos un caso límite.`
48
+ : `Write tests with ${runner} for the highlighted code. Cover the happy path and at least one edge case.`;
49
+ }
50
+ return lang === "es"
51
+ ? "Escribe tests para el código señalado. Cubre el camino feliz y al menos un caso límite."
52
+ : "Write tests for the highlighted code. Cover the happy path and at least one edge case.";
53
+ }
54
+ export const UI = {
55
+ es: {
56
+ generatedHeader: "Generado por agent-rules-init a partir de lo detectado en este repo.",
57
+ sections: {
58
+ commands: "Comandos del repo",
59
+ structure: "Estructura",
60
+ ci: "Lo que ejecuta CI (GitHub Actions)",
61
+ conventions: "Convenciones",
62
+ architecture: "Arquitectura",
63
+ canonical: "Comandos canónicos",
64
+ },
65
+ andMore: (count, file) => (file ? `…y ${count} más en ${file}` : `…y ${count} más`),
66
+ noStackFallback: "No se detectó ningún stack conocido. Completa este archivo manualmente.",
67
+ question: (fieldLabel, language) => `No se pudo determinar ${fieldLabel} para ${language}. ¿Cuál usáis?`,
68
+ fieldLabels: {
69
+ framework: "el framework",
70
+ testRunner: "el test runner",
71
+ linter: "el linter",
72
+ packageManager: "el gestor de paquetes",
73
+ },
74
+ usage: `agent-rules-init — genera CLAUDE.md, AGENTS.md, copilot-instructions y prompts de review/refactor/testing a partir del stack detectado en tu repo.
75
+
76
+ Uso:
77
+ npx agent-rules-init escanea el directorio actual y genera los archivos *.generated.*
78
+ npx agent-rules-init --lang es fuerza el idioma del contenido (es|en); por defecto se detecta del sistema
79
+ npx agent-rules-init --help muestra esta ayuda
80
+ npx agent-rules-init --version muestra la versión
81
+
82
+ Los archivos se crean siempre con sufijo .generated y nunca sobrescriben nada existente:
83
+ revisa su contenido y quita el sufijo para activarlos.`,
84
+ automationUsage: `Automatización:
85
+ --dry-run renderiza y muestra archivos sin escribir
86
+ --check termina con error si faltan archivos generados; nunca escribe
87
+ --json emite un único resultado JSON legible por máquinas
88
+ --non-interactive omite preguntas y el pulido con IA`,
89
+ unknownOption: (flag) => `Opción no reconocida: ${flag}`,
90
+ invalidLang: (value) => `Valor de --lang no válido: "${value}" (usa "es" o "en").`,
91
+ noTtyWarning: "No se detectó una terminal interactiva (esto pasa a veces en Git Bash en Windows). " +
92
+ "Continuando sin preguntas ni oferta de pulido con IA; se usarán los valores detectados.",
93
+ skippedQuestion: (message) => `No se detectó una terminal interactiva; se omite la pregunta "${message}" y se usa el valor detectado.`,
94
+ polishDetected: (assistant) => `${assistant} detectado — puede ayudar a pulir la redacción final.`,
95
+ polishConfirm: (assistant) => `Se detectó ${assistant}. ¿Quieres que pula la redacción final?`,
96
+ polishFailed: (assistant, error) => `No se pudo pulir el contenido con ${assistant}, se mantiene el original: ${error}`,
97
+ polishPrompt: (content) => `Pule la redacción del siguiente documento de instrucciones para un agente de IA, sin cambiar su significado ni estructura. Devuelve únicamente el documento pulido, sin comentarios ni explicaciones adicionales:\n\n${content}`,
98
+ polishBatchPrompt: (filesJson) => "Pule la redacción de estos archivos de instrucciones sin cambiar su significado, estructura, rutas ni formato Markdown. " +
99
+ "Devuelve únicamente un array JSON válido con exactamente los mismos objetos path/content y en el mismo orden, sin bloque de código ni comentarios. " +
100
+ `Entrada JSON:\n${filesJson}`,
101
+ fileSkipped: (path) => `${path}: ya existía, se conserva sin cambios.`,
102
+ outroWritten: "Revisa los archivos *.generated.* y, cuando estés conforme, quita el sufijo " +
103
+ '".generated" (ej. "CLAUDE.generated.md" → "CLAUDE.md") para activarlos — ' +
104
+ "tu asistente de IA solo lee el nombre final, no el generado.",
105
+ outroNothing: "No se generó ningún archivo nuevo.",
106
+ unexpectedError: (message) => `Fallo inesperado: ${message}`,
107
+ cancelled: "Operación cancelada.",
108
+ dirNotes: {
109
+ src: "código fuente",
110
+ lib: "código fuente",
111
+ tests: "tests",
112
+ test: "tests",
113
+ spec: "tests",
114
+ __tests__: "tests",
115
+ docs: "documentación",
116
+ doc: "documentación",
117
+ examples: "ejemplos",
118
+ scripts: "scripts auxiliares",
119
+ tools: "herramientas auxiliares",
120
+ migrations: "migraciones de base de datos",
121
+ benchmarks: "benchmarks",
122
+ ".github": "workflows y configuración de GitHub",
123
+ public: "activos públicos",
124
+ static: "activos estáticos",
125
+ assets: "activos",
126
+ config: "configuración",
127
+ },
128
+ testDirNote: "tests",
129
+ entrypointNote: "punto de entrada",
130
+ },
131
+ en: {
132
+ generatedHeader: "Generated by agent-rules-init from what was detected in this repo.",
133
+ sections: {
134
+ commands: "Repo commands",
135
+ structure: "Structure",
136
+ ci: "What CI runs (GitHub Actions)",
137
+ conventions: "Conventions",
138
+ architecture: "Architecture",
139
+ canonical: "Canonical commands",
140
+ },
141
+ andMore: (count, file) => (file ? `…and ${count} more in ${file}` : `…and ${count} more`),
142
+ noStackFallback: "No known stack was detected. Fill in this file manually.",
143
+ question: (fieldLabel, language) => `Couldn't determine ${fieldLabel} for ${language}. Which one do you use?`,
144
+ fieldLabels: {
145
+ framework: "the framework",
146
+ testRunner: "the test runner",
147
+ linter: "the linter",
148
+ packageManager: "the package manager",
149
+ },
150
+ usage: `agent-rules-init — generates CLAUDE.md, AGENTS.md, copilot-instructions and review/refactor/testing prompts from the stack detected in your repo.
151
+
152
+ Usage:
153
+ npx agent-rules-init scan the current directory and generate the *.generated.* files
154
+ npx agent-rules-init --lang en force the content language (es|en); defaults to the system locale
155
+ npx agent-rules-init --help show this help
156
+ npx agent-rules-init --version show the version
157
+
158
+ Files are always created with the .generated suffix and never overwrite anything:
159
+ review their content and drop the suffix to activate them.`,
160
+ automationUsage: `Automation:
161
+ --dry-run render and print files without writing
162
+ --check exit non-zero if generated files are missing; never write
163
+ --json emit a single machine-readable JSON result
164
+ --non-interactive skip questions and AI polishing`,
165
+ unknownOption: (flag) => `Unknown option: ${flag}`,
166
+ invalidLang: (value) => `Invalid --lang value: "${value}" (use "es" or "en").`,
167
+ noTtyWarning: "No interactive terminal detected (this sometimes happens in Git Bash on Windows). " +
168
+ "Continuing without questions or the AI-polish offer; detected values will be used.",
169
+ skippedQuestion: (message) => `No interactive terminal detected; skipping the question "${message}" and using the detected value.`,
170
+ polishDetected: (assistant) => `${assistant} detected — it can help polish the final wording.`,
171
+ polishConfirm: (assistant) => `${assistant} was detected. Do you want it to polish the final wording?`,
172
+ polishFailed: (assistant, error) => `Couldn't polish the content with ${assistant}, keeping the original: ${error}`,
173
+ polishPrompt: (content) => `Polish the wording of the following instructions document for an AI agent, without changing its meaning or structure. Return only the polished document, with no extra comments or explanations:\n\n${content}`,
174
+ polishBatchPrompt: (filesJson) => "Polish the wording of these instruction files without changing their meaning, structure, paths, or Markdown format. " +
175
+ "Return only a valid JSON array with exactly the same path/content objects in the same order, without a code fence or commentary. " +
176
+ `Input JSON:\n${filesJson}`,
177
+ fileSkipped: (path) => `${path}: already existed, left unchanged.`,
178
+ outroWritten: "Review the *.generated.* files and, once you are happy with them, drop the " +
179
+ '".generated" suffix (e.g. "CLAUDE.generated.md" → "CLAUDE.md") to activate them — ' +
180
+ "your AI assistant only reads the final name, not the generated one.",
181
+ outroNothing: "No new files were generated.",
182
+ unexpectedError: (message) => `Unexpected failure: ${message}`,
183
+ cancelled: "Operation cancelled.",
184
+ dirNotes: {
185
+ src: "source code",
186
+ lib: "source code",
187
+ tests: "tests",
188
+ test: "tests",
189
+ spec: "tests",
190
+ __tests__: "tests",
191
+ docs: "documentation",
192
+ doc: "documentation",
193
+ examples: "examples",
194
+ scripts: "helper scripts",
195
+ tools: "helper tooling",
196
+ migrations: "database migrations",
197
+ benchmarks: "benchmarks",
198
+ ".github": "GitHub workflows and configuration",
199
+ public: "public assets",
200
+ static: "static assets",
201
+ assets: "assets",
202
+ config: "configuration",
203
+ },
204
+ testDirNote: "tests",
205
+ entrypointNote: "entry point",
206
+ },
207
+ };
@@ -1,3 +1,5 @@
1
+ import { type Lang } from "./i18n.js";
2
+ import type { GeneratedFile } from "./writer.js";
1
3
  export type AssistantId = "claude" | "codex";
2
4
  export interface ExecResult {
3
5
  stdout: string;
@@ -6,4 +8,6 @@ export interface ExecResult {
6
8
  export type ExecFn = (command: string, args: string[], stdin?: string) => Promise<ExecResult>;
7
9
  export declare const defaultExecFn: ExecFn;
8
10
  export declare function detectAvailableAssistants(execFn?: ExecFn): Promise<AssistantId[]>;
9
- export declare function polishWithAssistant(assistant: AssistantId, content: string, execFn?: ExecFn): Promise<string>;
11
+ export declare function polishWithAssistant(assistant: AssistantId, content: string, execFn?: ExecFn, lang?: Lang): Promise<string>;
12
+ /** Polishes typical runs in one assistant process, splitting only very large outputs. */
13
+ export declare function polishFilesWithAssistant(assistant: AssistantId, files: GeneratedFile[], execFn?: ExecFn, lang?: Lang): Promise<GeneratedFile[]>;
@@ -1,4 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { UI } from "./i18n.js";
2
3
  const VERSION_ARGS = {
3
4
  claude: ["--version"],
4
5
  codex: ["--version"],
@@ -34,14 +35,65 @@ export async function detectAvailableAssistants(execFn = defaultExecFn) {
34
35
  }));
35
36
  return results.filter((id) => id !== null);
36
37
  }
37
- export async function polishWithAssistant(assistant, content, execFn = defaultExecFn) {
38
- const prompt = `Pule la redacción del siguiente documento de instrucciones para un agente de IA, sin cambiar su significado ni estructura. Devuelve únicamente el documento pulido, sin comentarios ni explicaciones adicionales:\n\n${content}`;
38
+ export async function polishWithAssistant(assistant, content, execFn = defaultExecFn, lang = "es") {
39
39
  try {
40
- const result = await execFn(assistant, ["-p"], prompt);
40
+ const result = await execFn(assistant, ["-p"], UI[lang].polishPrompt(content));
41
41
  return result.stdout.trim() || content;
42
42
  }
43
43
  catch (err) {
44
- console.warn(`No se pudo pulir el contenido con ${assistant}, se mantiene el original: ${err.message}`);
44
+ console.warn(UI[lang].polishFailed(assistant, err.message));
45
45
  return content;
46
46
  }
47
47
  }
48
+ const MAX_POLISH_BATCH_CHARS = 60_000;
49
+ function makeBatches(files) {
50
+ const batches = [];
51
+ let current = [];
52
+ let currentSize = 2;
53
+ for (const file of files) {
54
+ const size = JSON.stringify(file).length + 1;
55
+ if (current.length > 0 && currentSize + size > MAX_POLISH_BATCH_CHARS) {
56
+ batches.push(current);
57
+ current = [];
58
+ currentSize = 2;
59
+ }
60
+ current.push(file);
61
+ currentSize += size;
62
+ }
63
+ if (current.length > 0)
64
+ batches.push(current);
65
+ return batches;
66
+ }
67
+ function parsePolishedBatch(stdout, originals) {
68
+ const trimmed = stdout.trim();
69
+ const withoutFence = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1] ?? trimmed;
70
+ const parsed = JSON.parse(withoutFence);
71
+ if (!Array.isArray(parsed) || parsed.length !== originals.length) {
72
+ throw new Error("assistant returned a different number of files");
73
+ }
74
+ return parsed.map((value, index) => {
75
+ if (!value || typeof value !== "object")
76
+ throw new Error("assistant returned an invalid file entry");
77
+ const entry = value;
78
+ if (entry.path !== originals[index].path || typeof entry.content !== "string") {
79
+ throw new Error("assistant changed a path or returned invalid content");
80
+ }
81
+ return { path: originals[index].path, content: entry.content };
82
+ });
83
+ }
84
+ /** Polishes typical runs in one assistant process, splitting only very large outputs. */
85
+ export async function polishFilesWithAssistant(assistant, files, execFn = defaultExecFn, lang = "es") {
86
+ const polished = [];
87
+ for (const batch of makeBatches(files)) {
88
+ try {
89
+ const input = UI[lang].polishBatchPrompt(JSON.stringify(batch));
90
+ const result = await execFn(assistant, ["-p"], input);
91
+ polished.push(...parsePolishedBatch(result.stdout, batch));
92
+ }
93
+ catch (err) {
94
+ console.warn(UI[lang].polishFailed(assistant, err.message));
95
+ polished.push(...batch);
96
+ }
97
+ }
98
+ return polished;
99
+ }
@@ -0,0 +1,13 @@
1
+ import type { Lang } from "./i18n.js";
2
+ import type { ProjectUnit } from "./project-units.js";
3
+ export interface ProjectOverrides {
4
+ framework?: string;
5
+ testRunner?: string;
6
+ linter?: string;
7
+ packageManager?: string;
8
+ }
9
+ /** Generates the path-scoped AGENTS file for one JS/TS package. */
10
+ export declare function renderProjectUnitAgents(unit: ProjectUnit, lang: Lang, overrides?: ProjectOverrides): {
11
+ path: string;
12
+ content: string;
13
+ } | null;
@@ -0,0 +1,25 @@
1
+ import { buildRepoFacts } from "./repo-facts.js";
2
+ import { renderAgentsMd } from "./templates.js";
3
+ import { jsTsPack } from "../packs/js-ts.js";
4
+ function applyOverrides(detection, overrides) {
5
+ const updated = { ...detection };
6
+ for (const field of ["framework", "testRunner", "linter", "packageManager"]) {
7
+ const value = overrides[field];
8
+ if (value)
9
+ updated[field] = { value, confidence: "high" };
10
+ }
11
+ return updated;
12
+ }
13
+ /** Generates the path-scoped AGENTS file for one JS/TS package. */
14
+ export function renderProjectUnitAgents(unit, lang, overrides = {}) {
15
+ const rawDetection = jsTsPack.detect(unit.signals);
16
+ if (!rawDetection)
17
+ return null;
18
+ const detection = applyOverrides(rawDetection, overrides);
19
+ const facts = buildRepoFacts(unit.signals, lang);
20
+ const ruleSet = jsTsPack.rules(detection, lang, { facts, signals: unit.signals });
21
+ return {
22
+ path: `${unit.path}/AGENTS.generated.md`,
23
+ content: renderAgentsMd([{ detection, ruleSet }], facts, lang),
24
+ };
25
+ }
@@ -0,0 +1,16 @@
1
+ import type { RepoSignals } from "./types.js";
2
+ export interface ProjectUnit {
3
+ /** POSIX path relative to the repository root. */
4
+ path: string;
5
+ signals: RepoSignals;
6
+ }
7
+ export declare function isProjectExcluded(projectPath: string, patterns: readonly string[]): boolean;
8
+ /** Removes excluded JS packages before repo-wide aggregation and scoped rendering. */
9
+ export declare function applyProjectExcludes(signals: RepoSignals, patterns: readonly string[]): RepoSignals;
10
+ /**
11
+ * Creates an isolated RepoSignals view for every nested JS/TS package.
12
+ *
13
+ * Files and presence checks become relative to the package, so packs can run without
14
+ * learning workspace-specific rules and cannot accidentally use a sibling's stack.
15
+ */
16
+ export declare function buildPackageUnits(signals: RepoSignals): ProjectUnit[];
@@ -0,0 +1,95 @@
1
+ import path from "node:path";
2
+ function normalize(value) {
3
+ return value.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
4
+ }
5
+ function matchesPattern(projectPath, rawPattern) {
6
+ const value = normalize(projectPath);
7
+ const pattern = normalize(rawPattern);
8
+ if (!pattern)
9
+ return false;
10
+ if (pattern.endsWith("/**") && value === pattern.slice(0, -3))
11
+ return true;
12
+ const marker = "\u0000";
13
+ const regex = pattern
14
+ .replace(/\*\*/g, marker)
15
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
16
+ .replace(/\*/g, "[^/]*")
17
+ .replace(new RegExp(marker, "g"), ".*");
18
+ return new RegExp(`^${regex}$`).test(value);
19
+ }
20
+ export function isProjectExcluded(projectPath, patterns) {
21
+ return patterns.some((pattern) => matchesPattern(projectPath, pattern));
22
+ }
23
+ /** Removes excluded JS packages before repo-wide aggregation and scoped rendering. */
24
+ export function applyProjectExcludes(signals, patterns) {
25
+ if (patterns.length === 0 || !signals.packageJsons?.length)
26
+ return signals;
27
+ const packageJsons = signals.packageJsons.filter((manifest) => {
28
+ const packageDir = path.posix.dirname(manifest.path);
29
+ return packageDir === "." || !isProjectExcluded(packageDir, patterns);
30
+ });
31
+ const excludedDirs = (signals.packageJsons ?? [])
32
+ .map((manifest) => path.posix.dirname(manifest.path))
33
+ .filter((dir) => dir !== "." && isProjectExcluded(dir, patterns));
34
+ const isExcludedPath = (relativePath) => {
35
+ const normalized = normalize(relativePath);
36
+ return excludedDirs.some((dir) => normalized === dir || normalized.startsWith(`${dir}/`));
37
+ };
38
+ const primary = packageJsons[0];
39
+ const packageJson = primary
40
+ ? {
41
+ name: primary.name,
42
+ main: primary.main,
43
+ dependencies: Object.assign({}, ...packageJsons.map((manifest) => manifest.dependencies)),
44
+ devDependencies: Object.assign({}, ...packageJsons.map((manifest) => manifest.devDependencies)),
45
+ scripts: primary.scripts,
46
+ moduleType: primary.moduleType,
47
+ packageManager: primary.packageManager,
48
+ }
49
+ : undefined;
50
+ return {
51
+ ...signals,
52
+ files: signals.files.filter((file) => !isExcludedPath(file)),
53
+ hasFile: (relativePath) => !isExcludedPath(relativePath) && signals.hasFile(relativePath),
54
+ hasDir: (relativeDir) => !isExcludedPath(relativeDir) && signals.hasDir(relativeDir),
55
+ packageJson,
56
+ packageJsons,
57
+ };
58
+ }
59
+ function withoutLocation(manifest) {
60
+ const { path: _path, ...packageJson } = manifest;
61
+ return packageJson;
62
+ }
63
+ /**
64
+ * Creates an isolated RepoSignals view for every nested JS/TS package.
65
+ *
66
+ * Files and presence checks become relative to the package, so packs can run without
67
+ * learning workspace-specific rules and cannot accidentally use a sibling's stack.
68
+ */
69
+ export function buildPackageUnits(signals) {
70
+ return (signals.packageJsons ?? [])
71
+ .filter((manifest) => manifest.path !== "package.json")
72
+ .map((manifest) => {
73
+ const unitPath = path.posix.dirname(manifest.path);
74
+ const prefix = `${unitPath}/`;
75
+ const unitFiles = signals.files
76
+ .map((file) => file.split(path.sep).join("/"))
77
+ .filter((file) => file.startsWith(prefix))
78
+ .map((file) => file.slice(prefix.length));
79
+ const packageJson = withoutLocation(manifest);
80
+ return {
81
+ path: unitPath,
82
+ signals: {
83
+ rootPath: path.join(signals.rootPath, ...unitPath.split("/")),
84
+ files: unitFiles,
85
+ hasFile: (relativePath) => signals.hasFile(`${prefix}${relativePath}`),
86
+ hasDir: (relativeDir) => signals.hasDir(`${prefix}${relativeDir}`),
87
+ packageJson,
88
+ packageJsons: [{ ...packageJson, path: "package.json" }],
89
+ guidanceFiles: (signals.guidanceFiles ?? [])
90
+ .filter((file) => file.path.startsWith(prefix))
91
+ .map((file) => ({ ...file, path: file.path.slice(prefix.length) })),
92
+ },
93
+ };
94
+ });
95
+ }
@@ -1,3 +1,4 @@
1
+ import { type Lang } from "./i18n.js";
1
2
  import type { DetectionResult } from "./types.js";
2
3
  export type QuestionField = "framework" | "testRunner" | "linter" | "packageManager";
3
4
  export interface Question {
@@ -5,9 +6,10 @@ export interface Question {
5
6
  field: QuestionField;
6
7
  message: string;
7
8
  }
8
- export declare function collectLowConfidenceQuestions(detections: DetectionResult[]): Question[];
9
+ export declare function collectLowConfidenceQuestions(detections: DetectionResult[], lang: Lang): Question[];
9
10
  export type PromptFn = (message: string) => Promise<string>;
10
11
  export declare function hasInteractiveTty(): boolean;
12
+ export declare function makeDefaultPromptFn(lang: Lang): PromptFn;
11
13
  export declare const defaultPromptFn: PromptFn;
12
14
  export declare function askQuestions(questions: Question[], promptFn?: PromptFn): Promise<Record<string, string>>;
13
15
  export declare function applyAnswers(detections: DetectionResult[], answers: Record<string, string>): DetectionResult[];