@justmpm/ai-tool 1.0.0 → 1.0.2

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.
@@ -5,13 +5,15 @@ import {
5
5
  formatOutput,
6
6
  getAllCodeFiles,
7
7
  getCachedSymbolsIndex,
8
+ hint,
8
9
  indexProject,
9
10
  isCacheValid,
10
11
  isFileIgnored,
12
+ nextSteps,
11
13
  parseCommandOptions,
12
14
  readConfig,
13
15
  updateCacheMeta
14
- } from "./chunk-LC7H7LGY.js";
16
+ } from "./chunk-36CYBYVT.js";
15
17
 
16
18
  // src/commands/describe.ts
17
19
  var STOPWORDS = /* @__PURE__ */ new Set([
@@ -147,11 +149,34 @@ function findAreaMatches(normalizedQuery, candidates, config, cwd) {
147
149
  }
148
150
  async function describe(query, options = {}) {
149
151
  const { cwd, format } = parseCommandOptions(options);
152
+ const ctx = options.ctx || "cli";
150
153
  if (!query || query.trim().length === 0) {
151
154
  throw new Error("Query \xE9 obrigat\xF3ria. Exemplo: ai-tool describe 'autentica\xE7\xE3o'");
152
155
  }
153
156
  try {
154
157
  const config = readConfig(cwd);
158
+ const hasAreas = Object.keys(config.areas).length > 0;
159
+ if (!hasAreas) {
160
+ let out = `\u26A0\uFE0F Nenhuma area configurada neste projeto.
161
+
162
+ `;
163
+ out += `O comando describe busca em areas configuradas.
164
+ `;
165
+ out += `Para configurar areas:
166
+ `;
167
+ out += ` 1. ${hint("areas_init", ctx)} - gerar arquivo de configuracao
168
+ `;
169
+ out += ` 2. Edite .analyze/areas.config.json com as areas do projeto
170
+
171
+ `;
172
+ out += `Enquanto isso, use:
173
+ `;
174
+ out += ` \u2192 ${hint("find", ctx)} - buscar simbolos no codigo
175
+ `;
176
+ out += ` \u2192 ${hint("map", ctx)} - ver estrutura do projeto
177
+ `;
178
+ return out;
179
+ }
155
180
  const normalizedQuery = query.toLowerCase().trim();
156
181
  const candidates = Object.entries(config.areas).map(([id, area]) => ({
157
182
  id,
@@ -172,8 +197,8 @@ async function describe(query, options = {}) {
172
197
  { maxDistance: 2, limit: 3 }
173
198
  );
174
199
  suggestions.push(
175
- ...similarAreaIds.map((id) => `\u2192 ai-tool describe ${id}`),
176
- ...similarNames.map((name) => `\u2192 ai-tool describe "${name}"`)
200
+ ...similarAreaIds.map((id) => `\u2192 ${hint("describe", ctx, { "<termo>": id })}`),
201
+ ...similarNames.map((name) => `\u2192 ${hint("describe", ctx, { "<termo>": `"${name}"` })}`)
177
202
  );
178
203
  }
179
204
  const result = {
@@ -183,20 +208,20 @@ async function describe(query, options = {}) {
183
208
  areas: matches,
184
209
  suggestions: suggestions.length > 0 ? suggestions : void 0
185
210
  };
186
- return formatOutput(result, format, formatDescribeText);
211
+ return formatOutput(result, format, (r) => formatDescribeText(r, ctx));
187
212
  } catch (error) {
188
213
  const message = error instanceof Error ? error.message : String(error);
189
214
  throw new Error(`Erro ao executar describe: ${message}`);
190
215
  }
191
216
  }
192
- function formatDescribeText(result) {
217
+ function formatDescribeText(result, ctx = "cli") {
193
218
  let out = "";
194
219
  if (result.areas.length === 0) {
195
- out += `\u274C Nenhuma \xE1rea encontrada para: "${result.query}"
220
+ out += `\u274C Nenhuma area encontrada para: "${result.query}"
196
221
 
197
222
  `;
198
223
  if (result.suggestions && result.suggestions.length > 0) {
199
- out += `\u{1F4A1} Voc\xEA quis dizer?
224
+ out += `\u{1F4A1} Voce quis dizer?
200
225
  `;
201
226
  for (const suggestion of result.suggestions) {
202
227
  out += ` ${suggestion}
@@ -205,7 +230,12 @@ function formatDescribeText(result) {
205
230
  out += `
206
231
  `;
207
232
  }
208
- out += `\u{1F4D6} Dica: Use 'ai-tool areas' para listar todas as \xE1reas dispon\xEDveis`;
233
+ out += `\u{1F4D6} Dicas:
234
+ `;
235
+ out += ` \u2192 ${hint("areas", ctx)} - listar todas as areas disponiveis
236
+ `;
237
+ out += ` \u2192 ${hint("find", ctx)} - buscar simbolos por nome
238
+ `;
209
239
  return out;
210
240
  }
211
241
  out += `\u{1F50D} Busca: "${result.query}"
@@ -232,18 +262,13 @@ function formatDescribeText(result) {
232
262
  if (remaining > 0) {
233
263
  out += ` ... e mais ${remaining} arquivo(s)
234
264
  `;
235
- out += ` \u2192 Use 'ai-tool area ${area.id}' para ver todos
265
+ out += ` \u2192 ${hint("area", ctx, { "<nome>": area.id })} - ver todos
236
266
  `;
237
267
  }
238
268
  out += "\n";
239
269
  }
240
270
  }
241
- out += `\u{1F4D6} Pr\xF3ximos passos:
242
- `;
243
- out += ` \u2192 ai-tool area <id> - ver detalhes de uma \xE1rea
244
- `;
245
- out += ` \u2192 ai-tool context --area=<id> - contexto completo de uma \xE1rea
246
- `;
271
+ out += nextSteps("describe", ctx);
247
272
  return out;
248
273
  }
249
274
 
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  describe
4
- } from "./chunk-35SMNOXI.js";
4
+ } from "./chunk-M32V3QZD.js";
5
5
  import {
6
6
  VERSION,
7
7
  area,
@@ -16,7 +16,7 @@ import {
16
16
  impact,
17
17
  map,
18
18
  suggest
19
- } from "./chunk-LC7H7LGY.js";
19
+ } from "./chunk-36CYBYVT.js";
20
20
 
21
21
  // src/cli.ts
22
22
  import { resolve } from "path";
@@ -113,7 +113,7 @@ async function main() {
113
113
  }
114
114
  }
115
115
  if (flags.mcp) {
116
- const { startMcpServer } = await import("./server-DN6J3SYB.js");
116
+ const { startMcpServer } = await import("./server-ZWEQAS6N.js");
117
117
  await startMcpServer();
118
118
  return;
119
119
  }
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ interface CommandOptions {
8
8
  cwd?: string;
9
9
  save?: boolean;
10
10
  cache?: boolean;
11
+ ctx?: "cli" | "mcp";
11
12
  }
12
13
  interface MapOptions extends CommandOptions {
13
14
  trackDependencies?: boolean;
@@ -35,6 +36,7 @@ interface MapResult {
35
36
  version: string;
36
37
  timestamp: string;
37
38
  cwd: string;
39
+ framework?: string;
38
40
  summary: {
39
41
  totalFiles: number;
40
42
  totalFolders: number;
@@ -290,9 +292,6 @@ interface AreaContextResult {
290
292
  * Comando MAP - Mapa do projeto usando Skott
291
293
  */
292
294
 
293
- /**
294
- * Executa o comando MAP
295
- */
296
295
  declare function map(options?: MapOptions): Promise<string>;
297
296
 
298
297
  /**
@@ -329,6 +328,51 @@ declare function impact(target: string, options?: ImpactOptions): Promise<string
329
328
  */
330
329
  declare function suggest(target: string, options?: SuggestOptions): Promise<string>;
331
330
 
331
+ /**
332
+ * Sistema de dicas contextuais para CLI e MCP
333
+ *
334
+ * Gera instruções de uso corretas dependendo do contexto de execução.
335
+ * - CLI: "ai-tool impact Button"
336
+ * - MCP: "aitool_impact_analysis { target: 'Button' }"
337
+ *
338
+ * Também fornece "próximos passos" contextuais que guiam a IA ou
339
+ * o usuário para a ação mais relevante após cada comando.
340
+ */
341
+ /**
342
+ * Contexto de execução: CLI (terminal) ou MCP (protocolo para IAs)
343
+ */
344
+ type HintContext = "cli" | "mcp";
345
+ /**
346
+ * Retorna a instrução de uso de um comando no formato correto (CLI ou MCP)
347
+ *
348
+ * @param command - Nome interno do comando (ex: "impact", "suggest")
349
+ * @param ctx - Contexto de execução
350
+ * @param params - Substituições de parâmetros (ex: { "<arquivo>": "Button.tsx" })
351
+ * @returns String de instrução formatada
352
+ */
353
+ declare function hint(command: string, ctx: HintContext, params?: Record<string, string>): string;
354
+ /**
355
+ * Gera seção de "Próximos passos" formatada para o contexto correto
356
+ *
357
+ * @param command - Comando que acabou de ser executado
358
+ * @param ctx - Contexto de execução (cli ou mcp)
359
+ * @returns String formatada com próximos passos
360
+ */
361
+ declare function nextSteps(command: string, ctx: HintContext): string;
362
+ /**
363
+ * Gera uma dica de recuperação quando algo dá errado.
364
+ * Sugere a ação mais relevante para o cenário de erro.
365
+ *
366
+ * @param errorType - Tipo de erro ocorrido
367
+ * @param ctx - Contexto de execução
368
+ * @param extra - Informação extra sobre o erro
369
+ * @returns String formatada com dica de recuperação
370
+ */
371
+ type RecoveryErrorType = "file_not_found" | "area_not_found" | "no_results" | "no_firebase" | "no_areas_configured" | "symbol_not_found" | "index_failed" | "generic";
372
+ declare function recoveryHint(errorType: RecoveryErrorType, ctx: HintContext, _extra?: {
373
+ command?: string;
374
+ }): string;
375
+
332
376
  /**
333
377
  * Comando CONTEXT - Extrai assinaturas de funcoes e tipos de um arquivo
334
378
  * Também suporta --area para contexto consolidado de toda uma área
@@ -379,6 +423,7 @@ declare function areasInit(options?: InitOptions): Promise<string>;
379
423
  * Detecta automaticamente projetos Firebase e extrai informações
380
424
  * de triggers como path (Firestore) e schedule (cron).
381
425
  */
426
+
382
427
  /**
383
428
  * Informação de uma Cloud Function
384
429
  */
@@ -416,6 +461,7 @@ interface FunctionsOptions {
416
461
  format?: "text" | "json";
417
462
  cache?: boolean;
418
463
  trigger?: string;
464
+ ctx?: HintContext;
419
465
  }
420
466
  /**
421
467
  * Executa o comando FUNCTIONS
@@ -447,6 +493,7 @@ interface FindOptions {
447
493
  def?: boolean;
448
494
  refs?: boolean;
449
495
  cache?: boolean;
496
+ ctx?: HintContext;
450
497
  }
451
498
  /**
452
499
  * Representa uma ocorrência encontrada
@@ -697,99 +744,58 @@ declare function findBestMatch<T>(target: string, candidates: T[], extractKey?:
697
744
  declare function extractFileName(filePath: string): string;
698
745
 
699
746
  /**
700
- * Formatadores de mensagens de erro com sugestões inteligentes
747
+ * Formatadores de mensagens de erro com sugestoes inteligentes
701
748
  *
702
- * Todas as funções retornam strings formatadas para exibição,
703
- * com sugestões "você quis dizer?" e referência de comandos.
749
+ * Todas as funcoes recebem um parametro `ctx` (HintContext)
750
+ * que determina o formato das dicas de navegacao:
751
+ * - "cli": instrucoes no formato CLI (ex: "ai-tool impact Button")
752
+ * - "mcp": instrucoes no formato MCP (ex: "analyze__aitool_impact_analysis { target: 'Button' }")
704
753
  */
705
- /**
706
- * Referência rápida de comandos disponíveis
707
- */
708
- declare const COMMAND_REFERENCE: Record<string, string>;
754
+
709
755
  interface FormatFileNotFoundOptions {
710
756
  /** Termo buscado */
711
757
  target: string;
712
- /** Lista de todos os arquivos disponíveis */
758
+ /** Lista de todos os arquivos disponiveis */
713
759
  allFiles: string[];
714
760
  /** Comando que gerou o erro (para contexto) */
715
761
  command?: string;
762
+ /** Contexto de execucao */
763
+ ctx?: HintContext;
716
764
  }
717
765
  /**
718
- * Formata mensagem de arquivo não encontrado
766
+ * Formata mensagem de arquivo nao encontrado
719
767
  *
720
- * Inclui sugestões de arquivos similares e referência de comandos.
768
+ * Inclui sugestoes de arquivos similares e referencia de comandos.
721
769
  */
722
770
  declare function formatFileNotFound(options: FormatFileNotFoundOptions): string;
723
771
  interface AreaInfo {
724
- /** ID da área */
772
+ /** ID da area */
725
773
  id: string;
726
- /** Número de arquivos na área */
774
+ /** Numero de arquivos na area */
727
775
  count: number;
728
776
  }
729
777
  interface FormatAreaNotFoundOptions {
730
778
  /** Termo buscado */
731
779
  target: string;
732
- /** Lista de áreas disponíveis */
780
+ /** Lista de areas disponiveis */
733
781
  availableAreas: AreaInfo[];
782
+ /** Contexto de execucao */
783
+ ctx?: HintContext;
734
784
  }
735
785
  /**
736
- * Formata mensagem de área não encontrada
786
+ * Formata mensagem de area nao encontrada
737
787
  *
738
- * Inclui sugestões de áreas similares usando Levenshtein.
788
+ * Inclui sugestoes de areas similares usando Levenshtein.
739
789
  */
740
790
  declare function formatAreaNotFound(options: FormatAreaNotFoundOptions): string;
741
791
  /**
742
- * Formata mensagem de target obrigatório faltando
743
- */
744
- declare function formatMissingTarget(command: string): string;
745
- /**
746
- * Formata mensagem de comando inválido
747
- */
748
- declare function formatInvalidCommand(command: string): string;
749
-
750
- /**
751
- * Sistema de dicas contextuais para CLI e MCP
752
- *
753
- * Gera instruções de uso corretas dependendo do contexto de execução.
754
- * - CLI: "ai-tool impact Button"
755
- * - MCP: "aitool_impact_analysis { target: 'Button' }"
756
- *
757
- * Também fornece "próximos passos" contextuais que guiam a IA ou
758
- * o usuário para a ação mais relevante após cada comando.
759
- */
760
- /**
761
- * Contexto de execução: CLI (terminal) ou MCP (protocolo para IAs)
762
- */
763
- type HintContext = "cli" | "mcp";
764
- /**
765
- * Retorna a instrução de uso de um comando no formato correto (CLI ou MCP)
766
- *
767
- * @param command - Nome interno do comando (ex: "impact", "suggest")
768
- * @param ctx - Contexto de execução
769
- * @param params - Substituições de parâmetros (ex: { "<arquivo>": "Button.tsx" })
770
- * @returns String de instrução formatada
771
- */
772
- declare function hint(command: string, ctx: HintContext, params?: Record<string, string>): string;
773
- /**
774
- * Gera seção de "Próximos passos" formatada para o contexto correto
775
- *
776
- * @param command - Comando que acabou de ser executado
777
- * @param ctx - Contexto de execução (cli ou mcp)
778
- * @returns String formatada com próximos passos
792
+ * Formata mensagem de target obrigatorio faltando
779
793
  */
780
- declare function nextSteps(command: string, ctx: HintContext): string;
794
+ declare function formatMissingTarget(command: string, ctx?: HintContext): string;
781
795
  /**
782
- * Gera uma dica de recuperação quando algo dá errado.
783
- * Sugere a ação mais relevante para o cenário de erro.
784
- *
785
- * @param errorType - Tipo de erro ocorrido
786
- * @param ctx - Contexto de execução
787
- * @param extra - Informação extra sobre o erro
788
- * @returns String formatada com dica de recuperação
796
+ * Formata mensagem de comando invalido
789
797
  */
790
- declare function recoveryHint(errorType: "file_not_found" | "area_not_found" | "no_results" | "no_firebase" | "generic", ctx: HintContext, _extra?: {
791
- command?: string;
792
- }): string;
798
+ declare function formatInvalidCommand(command: string, ctx?: HintContext): string;
793
799
 
794
800
  /**
795
801
  * Utilitários para detecção de Firebase Cloud Functions
@@ -929,4 +935,4 @@ declare function inferFileDescription(filePath: string, category: string): strin
929
935
 
930
936
  declare const VERSION: string;
931
937
 
932
- export { type AreaConfig, type AreaContextComponentInfo, type AreaContextFunctionInfo, type AreaContextResult, type AreaContextStoreInfo, type AreaContextTriggerInfo, type AreaContextTypeInfo, type AreaDetailResult, type AreaFile, type AreaInfo, type AreaOptions, type AreasConfigFile, type AreasOptions, type AreasResult, COMMAND_REFERENCE, type CloudFunctionInfo, type CommandOptions, type ContextOptions, type ContextResult, type DeadFile, type DeadOptions, type DeadResult, type DetectedArea, type FileCategory, type FileInfo, type FindMatch, type FindOptions, type FindResult, type FindSimilarOptions, type FolderStats, type FormatAreaNotFoundOptions, type FormatFileNotFoundOptions, type FunctionInfo, type FunctionsOptions, type FunctionsResult, type HintContext, type ImpactFile, type ImpactOptions, type ImpactResult, type ImportInfo$1 as ImportInfo, type MapOptions, type MapResult, type OutputFormat, type ParamInfo, type ProjectIndex, type RiskInfo, type SuggestOptions, type SuggestResult, type Suggestion, type SuggestionPriority, type SymbolInfo, type SymbolType, type TriggerInfo, type TypeInfo, type TypeKind, VERSION, area, areas, areasInit, categoryIcons, clearFirebaseCache, configExists, context, dead, deadFix, detectCategory, detectFileAreas, extractFileName, filterCloudFunctionsFalsePositives, find, findBestMatch, findSimilar, formatAreaNotFound, formatFileNotFound, formatInvalidCommand, formatMissingTarget, functions, getAreaDescription, getAreaName, getCacheDir, getFileDescription, hasFirebaseFunctions, hint, impact, inferFileDescription, invalidateCache, isCacheValid, isCodeFile, isEntryPoint, isExportedCloudFunction, isFileIgnored, isFirebaseProject, levenshteinDistance, map, nextSteps, readConfig, recoveryHint, removeArea, setArea, setFileDescription, suggest, writeConfig };
938
+ export { type AreaConfig, type AreaContextComponentInfo, type AreaContextFunctionInfo, type AreaContextResult, type AreaContextStoreInfo, type AreaContextTriggerInfo, type AreaContextTypeInfo, type AreaDetailResult, type AreaFile, type AreaInfo, type AreaOptions, type AreasConfigFile, type AreasOptions, type AreasResult, type CloudFunctionInfo, type CommandOptions, type ContextOptions, type ContextResult, type DeadFile, type DeadOptions, type DeadResult, type DetectedArea, type FileCategory, type FileInfo, type FindMatch, type FindOptions, type FindResult, type FindSimilarOptions, type FolderStats, type FormatAreaNotFoundOptions, type FormatFileNotFoundOptions, type FunctionInfo, type FunctionsOptions, type FunctionsResult, type HintContext, type ImpactFile, type ImpactOptions, type ImpactResult, type ImportInfo$1 as ImportInfo, type MapOptions, type MapResult, type OutputFormat, type ParamInfo, type ProjectIndex, type RecoveryErrorType, type RiskInfo, type SuggestOptions, type SuggestResult, type Suggestion, type SuggestionPriority, type SymbolInfo, type SymbolType, type TriggerInfo, type TypeInfo, type TypeKind, VERSION, area, areas, areasInit, categoryIcons, clearFirebaseCache, configExists, context, dead, deadFix, detectCategory, detectFileAreas, extractFileName, filterCloudFunctionsFalsePositives, find, findBestMatch, findSimilar, formatAreaNotFound, formatFileNotFound, formatInvalidCommand, formatMissingTarget, functions, getAreaDescription, getAreaName, getCacheDir, getFileDescription, hasFirebaseFunctions, hint, impact, inferFileDescription, invalidateCache, isCacheValid, isCodeFile, isEntryPoint, isExportedCloudFunction, isFileIgnored, isFirebaseProject, levenshteinDistance, map, nextSteps, readConfig, recoveryHint, removeArea, setArea, setFileDescription, suggest, writeConfig };
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import {
2
- COMMAND_REFERENCE,
3
2
  VERSION,
4
3
  area,
5
4
  areas,
@@ -47,9 +46,8 @@ import {
47
46
  setFileDescription,
48
47
  suggest,
49
48
  writeConfig
50
- } from "./chunk-LC7H7LGY.js";
49
+ } from "./chunk-36CYBYVT.js";
51
50
  export {
52
- COMMAND_REFERENCE,
53
51
  VERSION,
54
52
  area,
55
53
  areas,