nexakit 0.2.0 → 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 (64) hide show
  1. package/.claude-plugin/marketplace.json +10 -5
  2. package/README.md +20 -4
  3. package/assets/runtime/package-lock.json +2 -2
  4. package/catalogs/generadores.json +936 -0
  5. package/package.json +1 -1
  6. package/plugins/nexakit-ahorro/.claude-plugin/plugin.json +1 -0
  7. package/plugins/nexakit-ahorro/README.md +13 -0
  8. package/plugins/nexakit-ahorro/hooks/compactar.js +39 -0
  9. package/plugins/nexakit-ahorro/hooks/hooks.json +1 -0
  10. package/plugins/nexakit-ahorro/hooks/register.js +32 -0
  11. package/plugins/nexakit-lecciones/.claude-plugin/plugin.json +1 -0
  12. package/plugins/nexakit-lecciones/README.md +19 -0
  13. package/plugins/nexakit-lecciones/hooks/hooks.json +1 -0
  14. package/plugins/nexakit-lecciones/hooks/lecciones.js +39 -0
  15. package/plugins/nexakit-lecciones/hooks/register.js +61 -0
  16. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
  17. package/plugins/nexakit-modelo/hooks/barra.js +72 -0
  18. package/plugins/nexakit-modelo/hooks/recomendar.js +27 -0
  19. package/plugins/nexakit-modelo/hooks/register.js +73 -17
  20. package/plugins/nexakit-modelo/hooks/umbrales.js +3 -0
  21. package/plugins/nexakit-modelo/tests/register.test.ts +1 -1
  22. package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -1
  23. package/plugins/nexakit-sesion/README.md +3 -3
  24. package/plugins/nexakit-sesion/hooks/aviso.js +28 -11
  25. package/plugins/nexakit-sesion/hooks/register.js +30 -2
  26. package/plugins/nexakit-sesion/tests/register.test.ts +3 -16
  27. package/plugins/niveles/agents/nivel-alto.md +3 -3
  28. package/plugins/niveles/agents/nivel-exigente.md +3 -3
  29. package/plugins/niveles/agents/nivel-ligero.md +3 -3
  30. package/plugins/niveles/agents/nivel-normal.md +3 -3
  31. package/schemas/generators.schema.json +299 -0
  32. package/skills/quality-gate/SKILL.md +1 -1
  33. package/skills/revisar/SKILL.md +46 -6
  34. package/src/clean-command.js +29 -0
  35. package/src/clean-project-flow.js +105 -0
  36. package/src/clean-project.js +431 -0
  37. package/src/cli-executable.js +1 -1
  38. package/src/gemini-files.js +3 -3
  39. package/src/gemini-tools.js +23 -8
  40. package/src/generators-catalog.js +63 -0
  41. package/src/level-agents.js +4 -3
  42. package/src/project-root.js +21 -2
  43. package/src/project-signals.js +6 -0
  44. package/src/redact.js +9 -0
  45. package/src/review-instructions.js +18 -29
  46. package/src/setup-state.js +7 -0
  47. package/src/setup-tui.js +98 -6
  48. package/src/skill-recommendations.js +25 -2
  49. package/src/toolkit-cli.js +0 -4
  50. package/src/toolkit-commands-guide.js +1 -1
  51. package/src/toolkit-setup.js +2 -2
  52. package/plugins/nexakit-modelo/hooks/status.js +0 -8
  53. package/plugins/nexakit-panel/.claude-plugin/plugin.json +0 -1
  54. package/plugins/nexakit-panel/README.md +0 -20
  55. package/plugins/nexakit-panel/hooks/hooks.json +0 -1
  56. package/plugins/nexakit-panel/hooks/lienzo.js +0 -382
  57. package/plugins/nexakit-panel/hooks/panel.js +0 -279
  58. package/plugins/nexakit-panel/hooks/register.tsx +0 -248
  59. package/plugins/nexakit-panel/tests/lienzo.test.ts +0 -142
  60. package/plugins/nexakit-panel/tests/panel.test.ts +0 -240
  61. package/plugins/nexakit-panel/tests/register.test.ts +0 -167
  62. package/plugins/nexakit-panel/types/index.d.ts +0 -41
  63. package/skills/revision-cruzada/SKILL.md +0 -59
  64. package/src/panel-cli.js +0 -182
@@ -0,0 +1,431 @@
1
+ import { constants } from 'node:fs';
2
+ import { runCleanCommand } from './clean-command.js';
3
+ import { sinSecretos } from './redact.js';
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { gitTopLevel, runGit as defaultRunGit } from './project-root.js';
7
+
8
+ const ignoredEntries = new Set(['.git', '.DS_Store', 'Thumbs.db']);
9
+ export async function inspectFolder(dir, { runGit = defaultRunGit } = {}) {
10
+ const root = await fs.realpath(dir);
11
+ const entries = (await fs.readdir(root)).sort();
12
+ return {
13
+ empty: entries.every((name) => ignoredEntries.has(name)),
14
+ insideGit: Boolean(await gitTopLevel(root, runGit)),
15
+ entries,
16
+ };
17
+ }
18
+ export function projectName(dir) {
19
+ const normalized = path
20
+ .basename(dir)
21
+ .normalize('NFD')
22
+ .replace(/\p{M}/gu, '')
23
+ .toLowerCase()
24
+ .replace(/[^a-z0-9-]+/g, '-')
25
+ .replace(/^-+|-+$/g, '')
26
+ .slice(0, 214)
27
+ .replace(/-+$/g, '');
28
+ return normalized || 'proyecto';
29
+ }
30
+
31
+ // Pure plan: cwd and write paths are relative to the selected project root.
32
+ // The executor (a later task) owns venv creation, confinement and exclusive writes.
33
+ export function planCleanProject({ choice, catalog, name, platform = process.platform }) {
34
+ if (!choice || typeof choice !== 'object' || Array.isArray(choice))
35
+ throw new Error('Elección de proyecto inválida.');
36
+ const order = ['frontend', 'backend', 'mobile'];
37
+ for (const part of Object.keys(choice))
38
+ if (![...order, 'database'].includes(part)) throw new Error(`Parte desconocida: ${part}.`);
39
+ const selected = {};
40
+ for (const part of [...order, 'database']) {
41
+ if (choice[part] == null) continue;
42
+ const generator = catalog.generators.find((g) => g.id === choice[part] && g.part === part);
43
+ if (!generator) throw new Error(`Elección inválida para ${part}.`);
44
+ selected[part] = generator;
45
+ }
46
+ const database = selected.database;
47
+ if (database && database.id !== 'supabase' && !selected.backend)
48
+ throw new Error('Esta base de datos necesita un backend.');
49
+ const hostPart = database?.id === 'supabase' && selected.frontend ? 'frontend' : 'backend';
50
+ if (database && !selected[hostPart]) throw new Error('La base de datos necesita un frontend o backend.');
51
+ const hostConfig = database?.database.backends[selected[hostPart]?.id];
52
+ if (database && !hostConfig) throw new Error('La base de datos no admite la parte elegida.');
53
+ const count = order.filter((part) => selected[part]).length;
54
+ const venvBin = platform === 'win32' ? '.venv\\Scripts' : '.venv/bin';
55
+ const python = platform === 'win32' ? `${venvBin}\\python.exe` : `${venvBin}/python`;
56
+ const normalizedName = projectName(name);
57
+ const parts = order
58
+ .filter((part) => selected[part])
59
+ .map((part) => {
60
+ const g = selected[part],
61
+ dir = count === 1 ? '.' : part === 'mobile' ? 'movil' : part;
62
+ const substitutions = { dir, name: normalizedName, python, venvBin };
63
+ const expand = (value) =>
64
+ value.replace(
65
+ /\{(dir|name|python|venvBin)\}(\/)?/g,
66
+ (_, key, slash) =>
67
+ substitutions[key] + (slash ? (key === 'venvBin' && platform === 'win32' ? '\\' : '/') : ''),
68
+ );
69
+ const commands = [],
70
+ writes = [];
71
+ const append = (steps, root = false) => {
72
+ for (const step of steps) {
73
+ if (step.kind === 'run')
74
+ commands.push({ argv: step.argv.map(expand), cwd: root || step.cwd === 'parent' ? '.' : dir });
75
+ else writes.push({ path: path.posix.join(dir, expand(step.path)), content: expand(step.content) });
76
+ }
77
+ };
78
+ append(g.steps);
79
+ append(g.install);
80
+ if (database && part === hostPart) {
81
+ append(database.steps, true);
82
+ append(database.install, true);
83
+ append(hostConfig.install);
84
+ if (hostConfig.envExample)
85
+ writes.push({ path: path.posix.join(dir, '.env.example'), content: expand(hostConfig.envExample) });
86
+ }
87
+ return { part, id: g.id, dir, commands, writes, check: { argv: g.check.argv.map(expand), cwd: dir } };
88
+ });
89
+ const pythonUsed = Object.values(selected).some((g) => g.requires.some((r) => r.program === 'python'));
90
+ return { parts, databaseId: database?.id ?? null, gitignore: [...(pythonUsed ? ['.venv/'] : []), '.env'] };
91
+ }
92
+
93
+ export async function checkRequirements(
94
+ plan,
95
+ catalog,
96
+ { runCommand, platform = process.platform, timeoutMs = 10000, signal } = {},
97
+ ) {
98
+ const required = new Map();
99
+ for (const id of [...plan.parts.map((p) => p.id), plan.databaseId].filter(Boolean)) {
100
+ for (const requirement of catalog.generators.find((g) => g.id === id).requires) {
101
+ const previous = required.get(requirement.program);
102
+ if (!previous || compareVersions(requirement.minVersion, previous) > 0)
103
+ required.set(requirement.program, requirement.minVersion);
104
+ }
105
+ }
106
+ const results = [];
107
+ for (const [program, minVersion] of required) {
108
+ let found = null,
109
+ timer,
110
+ cancel;
111
+ const controller = new AbortController();
112
+ try {
113
+ const result = await Promise.race([
114
+ Promise.resolve().then(() => {
115
+ if (controller.signal.aborted) throw Error('Cancelado');
116
+ return runCommand(
117
+ program === 'python' ? (platform === 'win32' ? 'py' : 'python3') : 'node',
118
+ ['--version'],
119
+ { signal: controller.signal, timeoutMs },
120
+ );
121
+ }),
122
+ new Promise((_, reject) => {
123
+ cancel = () => {
124
+ controller.abort();
125
+ reject(Error('Cancelado'));
126
+ };
127
+ signal?.addEventListener('abort', cancel, { once: true });
128
+ if (signal?.aborted) cancel();
129
+ timer = setTimeout(cancel, timeoutMs);
130
+ }),
131
+ ]);
132
+ const output =
133
+ typeof result === 'string' ? result : result?.status === 0 || result?.code === 0 ? result.stdout : '';
134
+ found = String(output ?? '').match(/\b(?:v|Python\s+)?(\d+\.\d+(?:\.\d+)?)\b/)?.[1] ?? null;
135
+ } catch {
136
+ /* Missing or timed-out programs are a blocking result. */
137
+ } finally {
138
+ clearTimeout(timer);
139
+ signal?.removeEventListener('abort', cancel);
140
+ }
141
+ results.push({
142
+ program,
143
+ minVersion,
144
+ found,
145
+ ok: found !== null && compareVersions(found, minVersion) >= 0,
146
+ });
147
+ }
148
+ return results;
149
+ }
150
+ function compareVersions(a, b) {
151
+ const aa = a.split('.').map(Number),
152
+ bb = b.split('.').map(Number);
153
+ for (let i = 0; i < 3; i++) if ((aa[i] ?? 0) !== (bb[i] ?? 0)) return (aa[i] ?? 0) - (bb[i] ?? 0);
154
+ return 0;
155
+ }
156
+
157
+ const lstatOrNull = (full) =>
158
+ fs.lstat(full).catch((e) => {
159
+ if (e.code === 'ENOENT') return null;
160
+ throw e;
161
+ });
162
+ async function physicalDirectory(full) {
163
+ const stat = await lstatOrNull(full);
164
+ if (!stat) {
165
+ await fs.mkdir(full);
166
+ return;
167
+ }
168
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error('La carpeta de destino no es segura.');
169
+ }
170
+ function confined(root, relative) {
171
+ if (
172
+ typeof relative !== 'string' ||
173
+ path.isAbsolute(relative) ||
174
+ relative.includes('\\') ||
175
+ relative.includes(':') ||
176
+ relative.split('/').includes('..')
177
+ )
178
+ throw Error('Ruta fuera del proyecto.');
179
+ const full = path.resolve(root, relative);
180
+ if (full !== root && !full.startsWith(root + path.sep)) throw Error('Ruta fuera del proyecto.');
181
+ return full;
182
+ }
183
+ async function copyExclusive(source, destination, sourceRoot, destinationRoot, ignored = new Set()) {
184
+ for (const entry of await fs.readdir(source, { withFileTypes: true })) {
185
+ if (ignored.has(entry.name)) continue;
186
+ if (entry.name === '.git') throw Error('El generador intentó crear un repositorio Git propio.');
187
+ const from = path.join(source, entry.name),
188
+ to = path.join(destination, entry.name);
189
+ if (entry.isDirectory()) {
190
+ await fs.mkdir(to);
191
+ await copyExclusive(from, to, sourceRoot, destinationRoot);
192
+ } else if (entry.isFile()) await fs.copyFile(from, to, constants.COPYFILE_EXCL);
193
+ else if (entry.isSymbolicLink()) {
194
+ const target = await fs.readlink(from),
195
+ resolved = path.resolve(path.dirname(from), target);
196
+ if (path.isAbsolute(target) || !resolved.startsWith(sourceRoot + path.sep))
197
+ throw Error('Enlace generado fuera del proyecto.');
198
+ await fs.symlink(target, to);
199
+ } else throw Error('Archivo generado no admitido.');
200
+ }
201
+ }
202
+ export async function runCleanProject(
203
+ plan,
204
+ {
205
+ projectRoot,
206
+ runCommand = runCleanCommand,
207
+ onProgress = () => {},
208
+ now = Date.now,
209
+ timeoutMs = 600000,
210
+ platform = process.platform,
211
+ onCreated = async () => {},
212
+ signal,
213
+ } = {},
214
+ ) {
215
+ const root = await fs.realpath(projectRoot),
216
+ done = [],
217
+ log = [];
218
+ let workspace,
219
+ currentPart = plan.parts[0]?.part ?? 'proyecto',
220
+ currentArgv = [];
221
+ const toolkit = path.join(root, '.agent-toolkit');
222
+ const record = (text) => log.push(`${new Date(now()).toISOString()} ${sinSecretos(text)}`);
223
+ const runPlannedCommand = async (values, cwd) => {
224
+ currentArgv = values;
225
+ onProgress(currentPart, values);
226
+ record(values.join(' '));
227
+ const controller = new AbortController();
228
+ let timer,
229
+ cancel,
230
+ running,
231
+ interrupted = false,
232
+ partial = '';
233
+ try {
234
+ const result = await Promise.race([
235
+ (running = Promise.resolve().then(() =>
236
+ runCommand(values[0], values.slice(1), {
237
+ cwd,
238
+ signal: controller.signal,
239
+ timeoutMs,
240
+ onOutput: (chunk) => {
241
+ if (partial.length < 16 * 1024 * 1024) partial += chunk;
242
+ },
243
+ env: {
244
+ ...process.env,
245
+ CI: '1',
246
+ npm_config_cache: path.join(workspace, 'npm-cache'),
247
+ PIP_CACHE_DIR: path.join(workspace, 'pip-cache'),
248
+ PIP_NO_INPUT: '1',
249
+ },
250
+ }),
251
+ )),
252
+ new Promise((_, reject) => {
253
+ cancel = () => {
254
+ interrupted = true;
255
+ controller.abort();
256
+ reject(Error('Creación cancelada.'));
257
+ };
258
+ signal?.addEventListener('abort', cancel, { once: true });
259
+ if (signal?.aborted) cancel();
260
+ timer = setTimeout(() => {
261
+ interrupted = true;
262
+ controller.abort();
263
+ reject(Error('La orden superó el tiempo límite.'));
264
+ }, timeoutMs);
265
+ }),
266
+ ]);
267
+ const status = result?.status ?? result?.code;
268
+ const output = commandOutput(result);
269
+ record(`salida ${status ?? 0}: ${output}`);
270
+ if (typeof result !== 'string' && status !== 0) throw Error(output || 'La orden falló.');
271
+ } catch (error) {
272
+ if (interrupted) {
273
+ let closeTimer;
274
+ const stopped = await Promise.race([
275
+ running.catch(() => null),
276
+ new Promise((resolve) => {
277
+ closeTimer = setTimeout(() => resolve(null), 1000);
278
+ }),
279
+ ]);
280
+ clearTimeout(closeTimer);
281
+ record(`salida parcial: ${stopped ? `${stopped.stdout ?? ''}\n${stopped.stderr ?? ''}` : partial}`);
282
+ }
283
+ throw error;
284
+ } finally {
285
+ clearTimeout(timer);
286
+ signal?.removeEventListener('abort', cancel);
287
+ }
288
+ };
289
+ try {
290
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw Error('Tiempo límite inválido.');
291
+ const entries = await fs.readdir(root);
292
+ if (entries.some((n) => !ignoredEntries.has(n)))
293
+ throw Error('La carpeta contiene archivos existentes; no se sobrescribirá nada.');
294
+ await physicalDirectory(toolkit);
295
+ workspace = await fs.mkdtemp(path.join(toolkit, 'creacion-'));
296
+ // A temporary Git boundary prevents upstream generators (Expo) initializing
297
+ // or prompting about Git. It is never copied into the actual project.
298
+ const git = path.join(workspace, '.git');
299
+ await fs.mkdir(git);
300
+ for (const sub of ['objects', 'refs']) await fs.mkdir(path.join(git, sub));
301
+ await fs.writeFile(path.join(git, 'HEAD'), 'ref: refs/heads/main\n', { flag: 'wx' });
302
+ await fs.writeFile(path.join(git, 'config'), '[core]\nrepositoryformatversion = 0\nbare = false\n', {
303
+ flag: 'wx',
304
+ });
305
+ const stage = path.join(workspace, projectName(root));
306
+ await fs.mkdir(stage);
307
+ const promotedShared = new Set(plan.parts.map((p) => p.dir));
308
+ for (const part of plan.parts) {
309
+ currentPart = part.part;
310
+ const dir = confined(stage, part.dir);
311
+ const pythonUsed = part.commands.some((c) => /\.venv[\\/]/.test(c.argv[0]));
312
+ if (pythonUsed || part.writes.length) await physicalDirectory(dir);
313
+ const destination = confined(root, part.dir);
314
+ if (destination !== root) await fs.mkdir(destination);
315
+ if (pythonUsed)
316
+ await runPlannedCommand(
317
+ [platform === 'win32' ? 'py' : 'python3', '-m', 'venv', '.venv'],
318
+ destination,
319
+ );
320
+ const finalArgv = (values) =>
321
+ values.map((value) =>
322
+ /^\.venv[\\/]/.test(value) ? path.join(destination, ...value.split(/[\\/]/)) : value,
323
+ );
324
+ for (const w of part.writes) {
325
+ const full = confined(stage, w.path);
326
+ await fs.writeFile(full, w.content, { flag: 'wx' });
327
+ }
328
+ for (const c of part.commands) await runPlannedCommand(finalArgv(c.argv), confined(stage, c.cwd));
329
+ await copyExclusive(dir, destination, stage, root);
330
+ if (part.dir !== '.') {
331
+ const shared = (await fs.readdir(stage)).filter((name) => !promotedShared.has(name));
332
+ await copyExclusive(stage, root, stage, root, promotedShared);
333
+ shared.forEach((name) => promotedShared.add(name));
334
+ }
335
+ await onCreated(part.part);
336
+ await runPlannedCommand(finalArgv(part.check.argv), destination);
337
+ done.push(part.part);
338
+ }
339
+ record('Creación comprobada.');
340
+ await fs.rm(workspace, { recursive: true });
341
+ return { ok: true, done };
342
+ } catch (error) {
343
+ const output = sinSecretos(error.message ?? String(error));
344
+ record(output);
345
+ return {
346
+ ok: false,
347
+ done,
348
+ failed: { part: currentPart, argv: currentArgv, output },
349
+ ...(workspace && { workspace }),
350
+ };
351
+ } finally {
352
+ // An unsafe .agent-toolkit is not followed even to save an error report.
353
+ try {
354
+ await physicalDirectory(toolkit);
355
+ const file = path.join(toolkit, 'creacion.log'),
356
+ stat = await lstatOrNull(file);
357
+ if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1))
358
+ throw Error('Registro inseguro.');
359
+ await fs.appendFile(file, log.join('\n') + '\n', { mode: 0o600 });
360
+ } catch (error) {
361
+ return {
362
+ ok: false,
363
+ done,
364
+ failed: {
365
+ part: currentPart,
366
+ argv: currentArgv,
367
+ output: sinSecretos(`No se pudo guardar el registro: ${error.message}`),
368
+ },
369
+ };
370
+ }
371
+ }
372
+ }
373
+
374
+ export async function ensureCleanIgnore(projectRoot, gitignore = []) {
375
+ const root = await fs.realpath(projectRoot),
376
+ file = path.join(root, '.gitignore'),
377
+ stat = await lstatOrNull(file);
378
+ if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 1024 * 1024))
379
+ throw Error('.gitignore no es un archivo seguro.');
380
+ const text = stat ? await fs.readFile(file, 'utf8') : '',
381
+ lines = new Set(text.split(/\r?\n/));
382
+ const missing = [...new Set([...gitignore, '.agent-toolkit/'])].filter((line) => !lines.has(line));
383
+ if (missing.length)
384
+ await fs.appendFile(file, `${text && !text.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
385
+ }
386
+ export async function appendCleanLog(root, text) {
387
+ const dir = path.join(root, '.agent-toolkit');
388
+ await physicalDirectory(dir);
389
+ const file = path.join(dir, 'creacion.log'),
390
+ stat = await lstatOrNull(file);
391
+ if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1))
392
+ throw Error('Registro inseguro.');
393
+ await fs.appendFile(file, `${new Date().toISOString()} ${sinSecretos(text)}\n`, { mode: 0o600 });
394
+ }
395
+ export async function initGit(
396
+ projectRoot,
397
+ { runCommand = runCleanCommand, insideGit, gitignore = [], onCommand = async () => {} } = {},
398
+ ) {
399
+ if (insideGit) return 'omitido-repo-existente';
400
+ const root = await fs.realpath(projectRoot);
401
+ const run = async (args) => {
402
+ let result;
403
+ try {
404
+ result = await runCommand('git', args, { cwd: root, signal: AbortSignal.timeout(30000) });
405
+ } catch (error) {
406
+ await onCommand(['git', ...args], error.message);
407
+ throw Object.assign(error, { argv: ['git', ...args] });
408
+ }
409
+ const status = typeof result === 'string' ? 0 : (result?.status ?? result?.code);
410
+ const output = typeof result === 'string' ? result : `${result?.stdout ?? ''}\n${result?.stderr ?? ''}`;
411
+ await onCommand(['git', ...args], `salida ${status}: ${output}`);
412
+ if (status !== 0)
413
+ throw Object.assign(Error(sinSecretos(output || 'Git no completó la orden.')), {
414
+ argv: ['git', ...args],
415
+ });
416
+ };
417
+ try {
418
+ await run(['--version']);
419
+ } catch {
420
+ return 'sin-git';
421
+ }
422
+ await ensureCleanIgnore(root, gitignore);
423
+ await run(['init']);
424
+ await run(['add', '-A']);
425
+ await run(['commit', '-m', 'chore: crear la base del proyecto con nexakit']);
426
+ return 'hecho';
427
+ }
428
+
429
+ function commandOutput(result) {
430
+ return typeof result === 'string' ? result : `${result?.stdout ?? ''}\n${result?.stderr ?? ''}`;
431
+ }
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { IS_WINDOWS } from "./platform.js";
4
4
 
5
- const PACKAGES = { codex: "@openai/codex", claude: "@anthropic-ai/claude-code" };
5
+ const PACKAGES = { npm: "npm", npx: "npm", codex: "@openai/codex", claude: "@anthropic-ai/claude-code" };
6
6
  const NODE_EXTENSIONS = new Set([".js", ".cjs", ".mjs"]);
7
7
  const unavailable = () => { throw Object.assign(new Error("CLI executable unavailable"), { code: "ENOENT" }); };
8
8
  const invalidBin = () => { throw Object.assign(new Error("El bin npm debe ser un archivo .js, .cjs o .mjs existente."), { code: "EINVAL" }); };
@@ -9,16 +9,16 @@ export async function readRegular(file, limit = 20 * 1024 * 1024) {
9
9
  const handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
10
10
  try {
11
11
  const opened = await handle.stat();
12
- if (!opened.isFile() || opened.nlink !== 1 || opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size) throw new Error('El archivo cambió.');
12
+ if (!opened.isFile() || opened.nlink !== 1 || opened.ino !== before.ino || opened.dev !== before.dev || opened.size !== before.size) throw Object.assign(new Error('El archivo cambió.'), { code: 'EFILECHANGED' });
13
13
  const bytes = Buffer.alloc(opened.size); let offset = 0;
14
14
  while (offset < bytes.length) {
15
15
  const { bytesRead } = await handle.read(bytes, offset, Math.min(65536, bytes.length-offset), offset);
16
- if (!bytesRead) throw new Error('Lectura incompleta.'); offset += bytesRead;
16
+ if (!bytesRead) throw Object.assign(new Error('Lectura incompleta.'), { code: 'EFILECHANGED' }); offset += bytesRead;
17
17
  }
18
18
  const after = await handle.stat();
19
19
  const named = await fs.lstat(file);
20
20
  if (!named.isFile() || named.isSymbolicLink() || named.nlink !== 1 || named.ino !== opened.ino || named.dev !== opened.dev ||
21
- after.nlink !== 1 || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs) throw new Error('El archivo cambió.');
21
+ after.nlink !== 1 || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs) throw Object.assign(new Error('El archivo cambió.'), { code: 'EFILECHANGED' });
22
22
  return bytes;
23
23
  } finally { await handle.close(); }
24
24
  }
@@ -129,17 +129,32 @@ async function collectImages(cwd, conversationId, { brainDirectory = brain(), wa
129
129
  } catch (error) { if (error.code !== "ENOENT") throw error; }
130
130
  if (names.length) {
131
131
  if (names.length > 16) throw new GeminiError("Demasiados artefactos de imagen.");
132
- const files = [];
132
+ // Read the complete batch before publishing any file. A producer can still
133
+ // be writing when readdir first exposes an image; retry only transient reads.
134
+ const images = [];
135
+ let pending = false;
133
136
  for (const name of names) {
134
- const bytes = await readRegular(path.join(artifacts, name));
135
- const destination = path.join(cwd, name);
136
- try { await fs.writeFile(destination, bytes, { flag: "wx", mode: 0o600 }); }
137
- catch (error) {
138
- if (error.code !== "EEXIST" || !(await readRegular(destination)).equals(bytes)) throw new GeminiError("No se pudo guardar la imagen sin sobrescribir.");
137
+ try {
138
+ const bytes = await readRegular(path.join(artifacts, name));
139
+ if (!bytes.length) { pending = true; break; }
140
+ images.push({ name, bytes });
141
+ } catch (error) {
142
+ if (!['EFILECHANGED', 'ENOENT'].includes(error.code)) throw error;
143
+ pending = true; break;
139
144
  }
140
- files.push(destination);
141
145
  }
142
- return files;
146
+ if (!pending) {
147
+ const files = [];
148
+ for (const { name, bytes } of images) {
149
+ const destination = path.join(cwd, name);
150
+ try { await fs.writeFile(destination, bytes, { flag: "wx", mode: 0o600 }); }
151
+ catch (error) {
152
+ if (error.code !== "EEXIST" || !(await readRegular(destination)).equals(bytes)) throw new GeminiError("No se pudo guardar la imagen sin sobrescribir.");
153
+ }
154
+ files.push(destination);
155
+ }
156
+ return files;
157
+ }
143
158
  }
144
159
  if (now() >= deadline) throw new GeminiError(`La generación no terminó; conversación ${conversationId}. Recupera sin repetir la consulta: agent-toolkit-gemini recuperar --directorio "${cwd}".`);
145
160
  await sleep(Math.min(pollMs, Math.max(1, deadline-now())));
@@ -0,0 +1,63 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import Ajv2020 from 'ajv/dist/2020.js';
4
+ import schema from '../schemas/generators.schema.json' with { type: 'json' };
5
+ import { SIGNAL_LABELS } from './project-signals.js';
6
+
7
+ const validate = new Ajv2020({ strict: true, allErrors: true }).compile(schema);
8
+ const placeholders = new Set(['dir', 'name', 'python', 'venvBin']);
9
+ export class GeneratorsCatalogError extends Error {
10
+ constructor(message) { super(message); this.name = 'GeneratorsCatalogError'; this.code = 'GENERATORS_CATALOG_INVALID'; }
11
+ }
12
+ const fail = message => { throw new GeneratorsCatalogError(message); };
13
+ function freeze(value) {
14
+ if (value && typeof value === 'object') { Object.values(value).forEach(freeze); Object.freeze(value); }
15
+ return value;
16
+ }
17
+ function markers(value) {
18
+ // Content may contain ordinary Python/JSON braces; only identifier markers are substituted.
19
+ for (const match of value.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g)) {
20
+ if (!placeholders.has(match[1])) fail(`Marcador desconocido: ${match[1]}.`);
21
+ }
22
+ }
23
+ function stepsFor(generator) {
24
+ return [...generator.steps, ...generator.install,
25
+ ...Object.values(generator.database?.backends ?? {}).flatMap(b => b.install)];
26
+ }
27
+ export function validateGeneratorsCatalog(value) {
28
+ let copy;
29
+ try { copy = structuredClone(value); } catch { fail('El catálogo debe ser un objeto JSON válido.'); }
30
+ if (!validate(copy)) fail('El catálogo de generadores no cumple el esquema requerido.');
31
+ const ids = new Set();
32
+ for (const g of copy.generators) {
33
+ if (ids.has(g.id)) fail(`Generador duplicado: ${g.id}.`);
34
+ ids.add(g.id);
35
+ if (g.part !== 'database' && !g.signals.length) fail(`Falta una señal en ${g.id}.`);
36
+ for (const s of g.signals) if (!Object.hasOwn(SIGNAL_LABELS, s)) fail(`Señal desconocida: ${s}.`);
37
+ if ((g.part === 'database') !== Boolean(g.database)) fail(`Configuración de base de datos inválida: ${g.id}.`);
38
+ for (const step of stepsFor(g)) {
39
+ if (step.kind === 'write') {
40
+ if (g.id !== 'fastapi') fail('Solo fastapi admite pasos de escritura.');
41
+ if (step.path.includes('\\') || step.path.includes('\0') || path.posix.isAbsolute(step.path)
42
+ || step.path.includes(':') || step.path.split('/').some(p => !p || p === '..' || p === '.')) fail(`Ruta de escritura inválida: ${step.path}.`);
43
+ markers(step.path); markers(step.content);
44
+ } else step.argv.forEach(markers);
45
+ }
46
+ for (const backend of Object.values(g.database?.backends ?? {})) {
47
+ if (backend.envExample !== undefined) markers(backend.envExample);
48
+ }
49
+ g.check.argv.forEach(markers);
50
+ }
51
+ for (const g of copy.generators) for (const id of Object.keys(g.database?.backends ?? {})) {
52
+ const target = copy.generators.find(e => e.id === id);
53
+ if (!target || !['frontend', 'backend'].includes(target.part)) fail(`Destino de base de datos desconocido: ${id}.`);
54
+ }
55
+ return freeze(copy);
56
+ }
57
+ export async function loadGeneratorsCatalog({ catalogUrl = new URL('../catalogs/generadores.json', import.meta.url) } = {}) {
58
+ try { return validateGeneratorsCatalog(JSON.parse(await fs.readFile(catalogUrl, 'utf8'))); }
59
+ catch (error) {
60
+ if (error instanceof GeneratorsCatalogError) throw error;
61
+ throw new GeneratorsCatalogError('No se pudo leer el catálogo de generadores.');
62
+ }
63
+ }
@@ -7,6 +7,7 @@ import { agentModels } from "./agent-models.js";
7
7
  // Codex has no plugins, so its level agents are files. Claude's come from the `niveles` plugin.
8
8
  // The top level is "alto"; xhigh is asked per spawn, only after high failed.
9
9
  const LEVELS = [["Ligero", "ligero"], ["Normal", "normal"], ["Exigente", "exigente"], ["Alto", "alto"]];
10
+ const USES = { ligero: "comandos, búsquedas, lecturas y cambios mecánicos", normal: "implementar con un diseño claro", exigente: "pruebas, casos borde o un fallo acotado", alto: "un fallo sutil, seguridad o lo que exigente no resolvió" };
10
11
  const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/u;
11
12
 
12
13
  export class LevelAgentsError extends Error {
@@ -17,14 +18,14 @@ function content(slug, level, { model, effort }) {
17
18
  const task = `nivel ${level} (${model}, ${effort})`;
18
19
  return [`# Generado por \`agent-toolkit-inbox agentes\`. Ese comando nunca sobrescribe ni borra: lo anterior queda como .anterior-*.`,
19
20
  `name = ${JSON.stringify(`nivel_${slug}`)}`,
20
- `description = ${JSON.stringify(`Ejecuta una tarea delegada de ${task}. Úsalo solo cuando la skill revision-cruzada indique este nivel.`)}`,
21
+ `description = ${JSON.stringify(`Ejecuta una tarea delegada de ${task}. Úsalo para ${USES[slug]}.`)}`,
21
22
  `model = ${JSON.stringify(model)}`, `model_reasoning_effort = ${JSON.stringify(effort)}`,
22
23
  `developer_instructions = """`,
23
- `Ejecutas una tarea que te delega la sesión principal de la revisión cruzada, con el ${task}.`,
24
+ `Ejecutas una tarea que te delega la sesión principal, con el ${task}.`,
24
25
  "Haz solo lo que pide la delegación y respeta las reglas del proyecto (AGENTS.md y sus skills).",
25
26
  "Si la tarea es de código: cambio mínimo, pruebas que lo cubran, y ejecútalas junto con el lint o la compilación que correspondan.",
26
27
  "No hagas commit, push ni PR, y no envíes, apruebes ni reclames encargos de revisión.",
27
- "Termina con los cambios por archivo, las comprobaciones ejecutadas con su resultado real y lo que no comprobaste.",
28
+ "Responde breve, en menos de 200 palabras: cambios por archivo (sin pegar el diff), comprobaciones con su resultado real y lo que no comprobaste. En búsquedas, solo rutas con línea. No repitas el encargo.",
28
29
  `"""`, ""].join("\n");
29
30
  }
30
31
 
@@ -21,7 +21,7 @@ export function projectIdentity(root) {
21
21
  const realpathOrNull = target => fs.realpath(target).catch(() => null);
22
22
 
23
23
  // Any Git failure (not installed, not a repository, dubious ownership) means "no Git": detection never breaks on it.
24
- async function gitTopLevel(startedIn, run) {
24
+ export async function gitTopLevel(startedIn, run) {
25
25
  try {
26
26
  const output = String(run(['rev-parse', '--show-toplevel'], startedIn) ?? '').trim();
27
27
  return output ? await realpathOrNull(output) : null;
@@ -30,12 +30,31 @@ async function gitTopLevel(startedIn, run) {
30
30
  }
31
31
  }
32
32
 
33
+ async function cleanBoundary(start, topLevel) {
34
+ let current = start;
35
+ while (true) {
36
+ try {
37
+ const dir=await fs.lstat(path.join(current,'.agent-toolkit'));
38
+ if(dir.isDirectory() && !dir.isSymbolicLink()) {
39
+ const file=path.join(current,'.agent-toolkit/manifest.json'),stat=await fs.lstat(file);
40
+ if(stat.isFile() && !stat.isSymbolicLink() && stat.nlink===1 && stat.size<=128000) {
41
+ const data=JSON.parse(await fs.readFile(file,'utf8'));
42
+ if(data.managedBy==='nexakit' && ['confirmado','creado','fallido'].includes(data.answers?.cleanProject?.status)) return current;
43
+ }
44
+ }
45
+ } catch { /* Only an owned readable marker establishes a boundary. */ }
46
+ if(current===topLevel || path.dirname(current)===current) return null;
47
+ current=path.dirname(current);
48
+ }
49
+ }
50
+
33
51
  export async function resolveProjectRoot(start, { homeDirectory = os.homedir(), runGit: run = runGit } = {}) {
34
52
  const startedIn = await fs.realpath(start);
35
53
  const topLevel = await gitTopLevel(startedIn, run);
36
54
  // A repository at the home folder (dotfiles) is not the project: climbing there would scan and install into ~.
37
55
  const home = await realpathOrNull(homeDirectory);
38
56
  const git = Boolean(topLevel) && topLevel !== home;
39
- const root = git ? topLevel : startedIn;
57
+ const boundary = await cleanBoundary(startedIn, git ? topLevel : home);
58
+ const root = boundary ?? (git ? topLevel : startedIn);
40
59
  return { root, startedIn, git, fromSubfolder: root !== startedIn, ...projectIdentity(root) };
41
60
  }
@@ -10,6 +10,9 @@ const MAX_README_BYTES = 64 * 1024;
10
10
  const MAX_SUBFOLDERS = 20;
11
11
 
12
12
  export const SIGNAL_LABELS = Object.freeze({
13
+ angular: 'Angular',
14
+ nestjs: 'NestJS',
15
+ expo: 'Expo',
13
16
  nodejs: 'Node.js',
14
17
  typescript: 'TypeScript',
15
18
  'mcp-sdk': 'MCP SDK',
@@ -36,6 +39,9 @@ export const SIGNAL_LABELS = Object.freeze({
36
39
  });
37
40
 
38
41
  export const PACKAGE_TO_SIGNAL = Object.freeze({
42
+ '@angular/core': 'angular',
43
+ '@nestjs/core': 'nestjs',
44
+ expo: 'expo',
39
45
  '@modelcontextprotocol/sdk': 'mcp-sdk',
40
46
  '@modelcontextprotocol/server': 'mcp-sdk',
41
47
  '@modelcontextprotocol/client': 'mcp-sdk',
package/src/redact.js ADDED
@@ -0,0 +1,9 @@
1
+ // Tacha los secretos evidentes de un detalle antes de mostrarlo o guardarlo en disco.
2
+ export function sinSecretos(texto) {
3
+ return String(texto)
4
+ .replace(/([a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:)[^\s@]+@/giu, '$1***@')
5
+ .replace(/\b([A-Za-z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD)[A-Za-z0-9_]*)=([^\s"']+)/giu, '$1=***')
6
+ .replace(/(Bearer\s+)[^\s"']+/giu, '$1***')
7
+ .replace(/(--?(?:password|passwd|token|secret|api-key)[= ])[^\s"']+/giu, '$1***');
8
+ }
9
+