nexakit 0.4.0 → 0.5.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 (36) hide show
  1. package/README.md +6 -3
  2. package/assets/runtime/package-lock.json +16 -16
  3. package/package.json +12 -11
  4. package/plugins/huellas.json +22 -0
  5. package/plugins/nexakit-ahorro/.claude-plugin/plugin.json +1 -1
  6. package/plugins/nexakit-ahorro/README.md +11 -0
  7. package/plugins/nexakit-ahorro/hooks/register.js +43 -0
  8. package/plugins/nexakit-lecciones/.claude-plugin/plugin.json +1 -1
  9. package/plugins/nexakit-lecciones/README.md +11 -0
  10. package/plugins/nexakit-lecciones/hooks/lecciones.js +76 -0
  11. package/plugins/nexakit-lecciones/hooks/register.js +63 -4
  12. package/plugins/nexakit-lecciones/tests/register.test.ts +16 -0
  13. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
  14. package/plugins/nexakit-modelo/hooks/barra.js +27 -7
  15. package/plugins/nexakit-modelo/hooks/decidir.js +58 -0
  16. package/plugins/nexakit-modelo/hooks/recomendar.js +48 -9
  17. package/plugins/nexakit-modelo/hooks/register.js +75 -4
  18. package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -1
  19. package/plugins/niveles/.claude-plugin/plugin.json +1 -1
  20. package/skills/cerrar-memoria/SKILL.md +5 -1
  21. package/skills/elegir-modelo/SKILL.md +30 -2
  22. package/skills/project-handoff/SKILL.md +1 -1
  23. package/src/agent-models.js +14 -7
  24. package/src/ahorro-command.js +64 -0
  25. package/src/cli.js +96 -0
  26. package/src/connect.js +4 -4
  27. package/src/lecciones-command.js +82 -0
  28. package/src/memory-allow-dir.js +152 -0
  29. package/src/revision-adapters.js +1 -0
  30. package/src/setup-apply.js +14 -2
  31. package/src/setup-plan.js +10 -0
  32. package/src/setup-state.js +18 -0
  33. package/src/setup-tui.js +1 -1
  34. package/src/superpowers.js +16 -2
  35. package/src/toolkit-cli.js +8 -0
  36. package/src/toolkit-commands-guide.js +8 -0
@@ -0,0 +1,152 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { IS_WINDOWS } from "./platform.js";
6
+ import {
7
+ ConnectionError,
8
+ readJson,
9
+ resolveConfiguredPath,
10
+ resolveManifestPath,
11
+ writeTextAtomic
12
+ } from "./connect.js";
13
+
14
+ // Claude Code solo lee y escribe fuera de la carpeta del proyecto si esa carpeta está declarada. Esta orden
15
+ // añade la bóveda de memoria a `permissions.additionalDirectories` del archivo LOCAL del proyecto
16
+ // (.claude/settings.local.json), que es personal: la ruta de tu equipo no debe llegar a un commit.
17
+ //
18
+ // Lo que concede: las lecturas de esa carpeta dejan de pedir permiso. Las ediciones siguen el modo de permisos
19
+ // de la sesión, así que en modo manual cada escritura sigue pidiéndolo. No toca los ajustes del usuario ni quita
20
+ // `blockReadsOutsideWorkingDirectories`: abre una sola carpeta, no desactiva la protección.
21
+
22
+ const SETTINGS_RELATIVE = [".claude", "settings.local.json"];
23
+ const SETTINGS_GIT_PATH = ".claude/settings.local.json";
24
+
25
+ const same = (left, right) =>
26
+ IS_WINDOWS ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase() : path.resolve(left) === path.resolve(right);
27
+
28
+ function git(repository, args) {
29
+ const result = spawnSync("git", ["-C", repository, ...args], { encoding: "utf8", shell: false });
30
+ return { status: result.status, stdout: (result.stdout ?? "").trim() };
31
+ }
32
+
33
+ function lstatOrNull(target) {
34
+ try {
35
+ return fs.lstatSync(target);
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ function isDirectory(target) {
42
+ try {
43
+ return fs.statSync(target).isDirectory();
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ function conflict(report, reason) {
50
+ report.status = "conflict";
51
+ report.reasons.push(reason);
52
+ return report;
53
+ }
54
+
55
+ function readSettings(settingsPath) {
56
+ const info = lstatOrNull(settingsPath);
57
+ if (!info) return { settings: {}, exists: false };
58
+ if (info.isSymbolicLink() || !info.isFile()) {
59
+ throw new ConnectionError([`${settingsPath} no es un archivo normal (enlace simbólico o carpeta).`]);
60
+ }
61
+ const settings = readJson(settingsPath, "los ajustes locales de Claude Code");
62
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
63
+ throw new ConnectionError([`${settingsPath} debe contener un objeto JSON.`]);
64
+ }
65
+ return { settings, exists: true };
66
+ }
67
+
68
+ export async function allowMemoryDirectory(options = {}) {
69
+ const target = path.resolve(options.targetPath ?? process.cwd());
70
+ const manifestPath = resolveManifestPath(target, options.manifestPath);
71
+ if (!manifestPath) throw new ConnectionError(["No se encontró project-memory.json."]);
72
+
73
+ const manifest = readJson(manifestPath, "manifiesto");
74
+ const manifestDirectory = path.dirname(manifestPath);
75
+ if (typeof manifest?.memory?.vaultPath !== "string" || typeof manifest?.source?.repositoryPath !== "string") {
76
+ throw new ConnectionError(["El manifiesto no declara memory.vaultPath y source.repositoryPath."]);
77
+ }
78
+ const vaultPath = resolveConfiguredPath(manifestDirectory, manifest.memory.vaultPath);
79
+ const repository = resolveConfiguredPath(manifestDirectory, manifest.source.repositoryPath);
80
+ const settingsPath = path.join(repository, ...SETTINGS_RELATIVE);
81
+
82
+ const report = {
83
+ command: "project-memory allow-dir",
84
+ status: "preview",
85
+ agent: "claude",
86
+ vaultPath,
87
+ repositoryPath: repository,
88
+ settingsPath,
89
+ changes: [],
90
+ reasons: []
91
+ };
92
+
93
+ if (!isDirectory(vaultPath)) return conflict(report, `La bóveda no existe: ${vaultPath}`);
94
+ if (!isDirectory(repository)) return conflict(report, `El repositorio fuente no existe: ${repository}`);
95
+
96
+ const claudeDirectory = path.join(repository, SETTINGS_RELATIVE[0]);
97
+ if (lstatOrNull(claudeDirectory)?.isSymbolicLink()) {
98
+ return conflict(report, `${claudeDirectory} es un enlace simbólico: Claude Code trataría estos ajustes como del repositorio.`);
99
+ }
100
+
101
+ let current;
102
+ try {
103
+ current = readSettings(settingsPath);
104
+ } catch (error) {
105
+ if (!(error instanceof ConnectionError)) throw error;
106
+ return conflict(report, error.details.join(" "));
107
+ }
108
+
109
+ const isRepository = git(repository, ["rev-parse", "--git-dir"]).status === 0;
110
+ if (isRepository && git(repository, ["ls-files", "--error-unmatch", "--", SETTINGS_GIT_PATH]).status === 0) {
111
+ return conflict(report, `git ya sigue ${SETTINGS_GIT_PATH}: la ruta de tu equipo acabaría en el repositorio. Deja de seguirlo antes (git rm --cached).`);
112
+ }
113
+
114
+ const directories = Array.isArray(current.settings.permissions?.additionalDirectories)
115
+ ? current.settings.permissions.additionalDirectories
116
+ : [];
117
+ if (current.settings.permissions !== undefined &&
118
+ (current.settings.permissions === null || typeof current.settings.permissions !== "object" || Array.isArray(current.settings.permissions))) {
119
+ return conflict(report, `${settingsPath}: «permissions» no es un objeto.`);
120
+ }
121
+ const alreadyAllowed = directories.some((entry) => typeof entry === "string" && same(entry, vaultPath));
122
+ if (!alreadyAllowed) report.changes.push({ id: "additionalDirectories", action: current.exists ? "update" : "create" });
123
+
124
+ let excludePath = null;
125
+ if (isRepository && git(repository, ["check-ignore", "-q", "--", SETTINGS_GIT_PATH]).status !== 0) {
126
+ const resolved = git(repository, ["rev-parse", "--git-path", "info/exclude"]).stdout;
127
+ excludePath = path.resolve(repository, resolved);
128
+ report.changes.push({ id: "gitExclude", action: "update" });
129
+ }
130
+
131
+ if (report.changes.length === 0) {
132
+ report.status = "unchanged";
133
+ return report;
134
+ }
135
+ if (!options.apply) return report;
136
+
137
+ if (!alreadyAllowed) {
138
+ const next = {
139
+ ...current.settings,
140
+ permissions: { ...(current.settings.permissions ?? {}), additionalDirectories: [...directories, vaultPath] }
141
+ };
142
+ writeTextAtomic(settingsPath, `${JSON.stringify(next, null, 2)}\n`);
143
+ }
144
+ if (excludePath) {
145
+ fs.mkdirSync(path.dirname(excludePath), { recursive: true });
146
+ const previous = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, "utf8") : "";
147
+ const separator = previous === "" || previous.endsWith("\n") ? "" : "\n";
148
+ fs.writeFileSync(excludePath, `${previous}${separator}${SETTINGS_GIT_PATH}\n`);
149
+ }
150
+ report.status = "applied";
151
+ return report;
152
+ }
@@ -35,6 +35,7 @@ export async function buildRevisionInvocation({
35
35
  'read-only',
36
36
  '--json',
37
37
  '--ignore-user-config',
38
+ '--skip-git-repo-check',
38
39
  '-C',
39
40
  root,
40
41
  '-',
@@ -5,6 +5,7 @@ import { planReviewInstructions, applyReviewInstructions } from './review-instru
5
5
  import fs from 'node:fs/promises';
6
6
  import path from 'node:path';
7
7
  import { connectMemory } from './connect.js';
8
+ import { allowMemoryDirectory } from './memory-allow-dir.js';
8
9
  import { diagnoseMemory } from './doctor.js';
9
10
  import { initializeMemory } from './init.js';
10
11
  import { acquireLock } from './install-lock.js';
@@ -158,6 +159,10 @@ export async function applySetup(
158
159
  if (diagnosis.summary.errors > 0)
159
160
  throw new Error('La memoria se creó, pero su comprobación encontró errores.');
160
161
  },
162
+ 'memory-allow-dir': async () => {
163
+ const report = await allowMemoryDirectory({ targetPath: memoryPath, apply: true });
164
+ if (report.status === 'conflict') throw new Error(report.reasons.join(' '));
165
+ },
161
166
  answers: () =>
162
167
  withLock(homeDirectory, acquire, (lock) => writeSetupAnswers(state.project.root, answers, lock)),
163
168
  'final-check': async () => {
@@ -211,6 +216,7 @@ export async function applySetup(
211
216
  throw new Error(`Bloque desconocido: ${id}`);
212
217
  };
213
218
 
219
+ const skipped = [];
214
220
  for (const { id } of confirmation.blocks) {
215
221
  onProgress(id, 'start');
216
222
  try {
@@ -221,11 +227,17 @@ export async function applySetup(
221
227
  ? `${detail.startsWith('No se pudo') ? detail : `No se pudo conectar la memoria a ${AGENT_NAMES[id.split(':')[1]]}: ${detail}`} ${RETRY}`
222
228
  : `Falló «${confirmation.blocks.find((block) => block.id === id).label}»: ${detail} ${RETRY}`;
223
229
  onProgress(id, 'failed', message);
224
- return { ok: false, done, failed: { id, message }, finalCheck };
230
+ // Superpowers comes from each agent's own marketplace: when that fails, the memory, the rules and the other
231
+ // agents are still worth leaving ready. The run ends as not ready and the final check lists it as pending.
232
+ if (id.startsWith('superpowers:')) {
233
+ skipped.push({ id, message });
234
+ continue;
235
+ }
236
+ return { ok: false, done, failed: { id, message }, ...(skipped.length && { skipped }), finalCheck };
225
237
  }
226
238
  done.push(id);
227
239
  onProgress(id, 'done');
228
240
  }
229
241
  // A final check that finds something still pending is a failure: the person must not read «Listo».
230
- return { ok: finalCheck?.ok ?? true, done, finalCheck };
242
+ return { ok: (finalCheck?.ok ?? true) && !skipped.length, done, ...(skipped.length && { skipped }), finalCheck };
231
243
  }
package/src/setup-plan.js CHANGED
@@ -200,6 +200,16 @@ export function buildConfirmation(state, answers) {
200
200
  add('!', `No encontré ${AGENT_NAMES[agent]}; no puedo conectarle la memoria`);
201
201
  }
202
202
  for (const agent of need) block(`memory-connect:${agent}`, `Memoria conectada a ${AGENT_NAMES[agent]}`);
203
+ // Claude Code refuses files outside the project unless the folder is declared; closing the memory needs it.
204
+ if (agents.includes('claude') && state.agentsFound.claude) {
205
+ const allowDir = state.memory.allowDir?.[target];
206
+ if (allowDir === 'create') {
207
+ add('+', 'Permitir a Claude Code abrir la memoria desde este proyecto (solo en tu copia; escribir sigue pidiendo permiso)');
208
+ block('memory-allow-dir', 'Memoria permitida en Claude Code');
209
+ } else if (allowDir === 'conflict') {
210
+ add('!', 'No pude declarar la memoria como carpeta permitida de Claude Code; revisa `nexakit memoria allow-dir`');
211
+ }
212
+ }
203
213
  }
204
214
  }
205
215
 
@@ -10,6 +10,7 @@ import { planReviewInstructions } from './review-instructions.js';
10
10
  import path from 'node:path';
11
11
  import { pathToFileURL } from 'node:url';
12
12
  import { connectMemory } from './connect.js';
13
+ import { allowMemoryDirectory } from './memory-allow-dir.js';
13
14
  import { ACTIONABLE_LINK_STATES } from './link-states.js';
14
15
  import {
15
16
  findKnownMemories,
@@ -121,6 +122,19 @@ export async function memoryConnections(
121
122
  return result;
122
123
  }
123
124
 
125
+ // Read-only preview of `project-memory allow-dir`: create (not declared yet), unchanged or conflict.
126
+ async function allowDirState(vaultPath) {
127
+ try {
128
+ const report = await allowMemoryDirectory({ targetPath: vaultPath });
129
+ if (report.status === 'unchanged') return 'unchanged';
130
+ // Only the git exclusion pending is not worth a setup step: the folder is already allowed.
131
+ if (report.status === 'preview') return report.changes.some((change) => change.id === 'additionalDirectories') ? 'create' : 'unchanged';
132
+ return 'conflict';
133
+ } catch {
134
+ return 'conflict';
135
+ }
136
+ }
137
+
124
138
  export async function gatherSetupState({
125
139
  start = process.cwd(),
126
140
  homeDirectory = os.homedir(),
@@ -219,6 +233,7 @@ export async function gatherSetupState({
219
233
  suggestedPath,
220
234
  kinds: {},
221
235
  connections: {},
236
+ allowDir: {},
222
237
  };
223
238
  // The chosen path is always inspected, also one typed in "otra carpeta…" (memoryPaths).
224
239
  const candidates = [
@@ -241,6 +256,9 @@ export async function gatherSetupState({
241
256
  memory.kinds[candidate] = kind;
242
257
  if (kind === 'memory' || kind === 'new')
243
258
  memory.connections[candidate] = await memoryConnections(candidate, { ...context, kind });
259
+ // Whether Claude Code may open the vault from this project: a memory to create always needs it declared.
260
+ if (kind === 'new') memory.allowDir[candidate] = 'create';
261
+ else if (kind === 'memory') memory.allowDir[candidate] = await allowDirState(candidate);
244
262
  }
245
263
 
246
264
  const reviewInstructions = await planReviewInstructions({ homeDirectory, environment, codexHome });
package/src/setup-tui.js CHANGED
@@ -392,7 +392,7 @@ function finalLines(model) {
392
392
  if (result?.finalCheck) lines.push(`${result.finalCheck.ok ? '◇' : '!'} Comprobación final: ${result.finalCheck.message}`);
393
393
  if (model.step !== 'done') return { lines, end: [] };
394
394
  if (!result.ok) {
395
- const reason = result.failed?.message ?? `Comprobación final: ${result.finalCheck?.message ?? ''}`;
395
+ const reason = result.failed?.message ?? result.skipped?.map(item => item.message).join(' ') ?? `Comprobación final: ${result.finalCheck?.message ?? ''}`;
396
396
  return { lines, end: [result.failed ? 'Se detuvo aquí.' : 'Terminó, pero algo no quedó listo.', ...wrapText(reason, 60)] };
397
397
  }
398
398
  const names = joinNames(answers.agents.map(agent => AGENT_NAMES[agent]));
@@ -15,6 +15,13 @@ export const SUPERPOWERS = Object.freeze({
15
15
  list: ['plugin', 'list', '--json'],
16
16
  install: ['plugin', 'install', 'superpowers@claude-plugins-official'],
17
17
  enable: ['plugin', 'enable', 'superpowers@claude-plugins-official'],
18
+ // A HOME where Claude Code never opened only has the built-in directory: the reviewed marketplace has to be
19
+ // added (or refreshed, when its local copy is old) before the plugin can be found.
20
+ marketplace: Object.freeze({
21
+ missing: /not found in marketplace|marketplace\b.*\bnot found/iu,
22
+ add: ['plugin', 'marketplace', 'add', 'anthropics/claude-plugins-official'],
23
+ update: ['plugin', 'marketplace', 'update', 'claude-plugins-official'],
24
+ }),
18
25
  }),
19
26
  codex: Object.freeze({
20
27
  command: 'codex',
@@ -124,9 +131,16 @@ export async function applySuperpowers(agent, state, { runCommand, environment }
124
131
  const args = state === 'falta' ? entry.install : entry.enable;
125
132
  if (!args) throw new Error(`Superpowers está desactivado en ${AGENT_NAMES[agent]}; actívalo desde ${AGENT_NAMES[agent]} (/plugins).`);
126
133
  const run = runCommand ?? (await defaultRunner(entry.command, environment));
127
- const result = await run(entry.command, args);
134
+ const detailOf = (output) => String(output?.stderr || output?.stdout || output?.errorCode || '').trim();
135
+ let result = await run(entry.command, args);
136
+ if (result?.status !== 0 && state === 'falta' && entry.marketplace?.missing.test(detailOf(result))) {
137
+ const prepared =
138
+ (await run(entry.command, entry.marketplace.add))?.status === 0 ||
139
+ (await run(entry.command, entry.marketplace.update))?.status === 0;
140
+ if (prepared) result = await run(entry.command, args);
141
+ }
128
142
  if (result?.status !== 0) {
129
- const detail = String(result?.stderr || result?.stdout || result?.errorCode || '').trim();
143
+ const detail = detailOf(result);
130
144
  throw new Error(`No se pudo ${state === 'falta' ? 'instalar' : 'activar'} Superpowers en ${AGENT_NAMES[agent]}.${detail ? ` ${detail}` : ''}`);
131
145
  }
132
146
  return true;
@@ -1,6 +1,8 @@
1
1
  import os from 'node:os';
2
2
  import { runCli } from './cli.js';
3
3
  import { runModelCommand } from './model-command.js';
4
+ import { runAhorroCommand } from './ahorro-command.js';
5
+ import { runLeccionesCommand } from './lecciones-command.js';
4
6
  import { runRevisionCommand } from './revision.js';
5
7
  import path from 'node:path';
6
8
  import readline from 'node:readline';
@@ -37,6 +39,8 @@ const HELP = `Uso: npx nexakit [--project <ruta>] [--si]
37
39
  nexakit revision --disponibles [--principal claude|codex|antigravity]
38
40
  nexakit revision --con <ia> --modelo <m> --esfuerzo <e> --encargo <archivo> [--base <rama>]
39
41
  nexakit modelo [--nivel <nivel>] [--ia claude|codex|antigravity] [--perfil-codex <nombre>]
42
+ nexakit ahorro [--json]
43
+ nexakit lecciones [--json | --descartar]
40
44
  npx nexakit recommend [--project <ruta>] [--profile frontend|backend|mcp|security] [--client codex|claude] [--dry-run] [--json]
41
45
  npx nexakit scan <carpeta de skill> [--json]
42
46
  npx nexakit doctor [--agent codex|claude|antigravity|all] [--perfil-codex <nombre>] [--json]
@@ -54,6 +58,8 @@ reparar re-apunta enlaces rotos de una instalación anterior (--desde es la carp
54
58
  que ya no existe); lista lo que encontró y siempre pregunta.
55
59
  memoria ejecuta los subcomandos de project-memory (init, connect, doctor, status, sync).
56
60
  revision y modelo piden una revisión a otra IA o consultan los modelos disponibles.
61
+ ahorro resume cuánta salida de comandos recortó el mod nexakit-ahorro (caracteres y tokens estimados).
62
+ lecciones resume las correcciones y lecciones que registra el mod nexakit-lecciones y las que siguen pendientes.
57
63
  recommend inspecciona el proyecto en solo lectura; setup prepara las skills base globales y respeta las que quitaste
58
64
  (--omitir <skill> declara quitada una que ya no tiene enlace; --reponer <skill> devuelve una; ambos se repiten).
59
65
  (Alias local compatible: agent-toolkit)
@@ -91,6 +97,8 @@ export async function runToolkitCli(
91
97
 
92
98
  const [command, ...rest] = argv;
93
99
  if (command === 'modelo') return runModelCommand(rest, { out, err }, options);
100
+ if (command === 'ahorro') return runAhorroCommand(rest, { out, err }, options);
101
+ if (command === 'lecciones') return runLeccionesCommand(rest, { out, err }, options);
94
102
  if (command === 'revision') return runRevisionCommand(rest, { out, err }, { options });
95
103
  if (command === 'memoria') {
96
104
  return runCli(
@@ -95,6 +95,14 @@ export function getToolkitCommandsGuide({ clients = {} } = {}) {
95
95
  command: 'nexakit modelo',
96
96
  description: 'Consulta modelos reales, esfuerzos y valores guardados.',
97
97
  },
98
+ {
99
+ command: 'nexakit ahorro',
100
+ description: 'Resume cuánta salida de comandos recortó el mod nexakit-ahorro.',
101
+ },
102
+ {
103
+ command: 'nexakit lecciones',
104
+ description: 'Resume las correcciones y lecciones que registra el mod nexakit-lecciones y las pendientes.',
105
+ },
98
106
  ];
99
107
 
100
108
  return {