@justmpm/ai-tool 0.9.3 → 1.0.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.
@@ -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-J3MX6NK3.js";
16
+ } from "./chunk-4HAUIZQ7.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}"
@@ -220,21 +250,25 @@ function formatDescribeText(result) {
220
250
 
221
251
  `;
222
252
  if (area.files.length > 0) {
253
+ const MAX_FILES = 5;
254
+ const filesToShow = area.files.slice(0, MAX_FILES);
255
+ const remaining = area.files.length - filesToShow.length;
223
256
  out += `Arquivos:
224
257
  `;
225
- for (const file of area.files) {
258
+ for (const file of filesToShow) {
226
259
  out += ` \u2022 ${file}
260
+ `;
261
+ }
262
+ if (remaining > 0) {
263
+ out += ` ... e mais ${remaining} arquivo(s)
264
+ `;
265
+ out += ` \u2192 ${hint("area", ctx, { "<nome>": area.id })} - ver todos
227
266
  `;
228
267
  }
229
268
  out += "\n";
230
269
  }
231
270
  }
232
- out += `\u{1F4D6} Pr\xF3ximos passos:
233
- `;
234
- out += ` \u2192 ai-tool area <id> - ver detalhes de uma \xE1rea
235
- `;
236
- out += ` \u2192 ai-tool context --area=<id> - contexto completo de uma \xE1rea
237
- `;
271
+ out += nextSteps("describe", ctx);
238
272
  return out;
239
273
  }
240
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-5RMB6OEA.js";
4
+ } from "./chunk-LJZCMVX5.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-J3MX6NK3.js";
19
+ } from "./chunk-4HAUIZQ7.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-TDSMX4PG.js");
116
+ const { startMcpServer } = await import("./server-K4Z4PEO3.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;
@@ -160,6 +162,11 @@ interface TypeInfo {
160
162
  definition: string;
161
163
  isExported: boolean;
162
164
  }
165
+ interface ConstantInfo {
166
+ name: string;
167
+ type: string;
168
+ isExported: boolean;
169
+ }
163
170
  interface ContextResult {
164
171
  version: string;
165
172
  timestamp: string;
@@ -169,6 +176,7 @@ interface ContextResult {
169
176
  exports: string[];
170
177
  functions: FunctionInfo[];
171
178
  types: TypeInfo[];
179
+ constants?: ConstantInfo[];
172
180
  }
173
181
  interface AreaConfig {
174
182
  name: string;
@@ -284,9 +292,6 @@ interface AreaContextResult {
284
292
  * Comando MAP - Mapa do projeto usando Skott
285
293
  */
286
294
 
287
- /**
288
- * Executa o comando MAP
289
- */
290
295
  declare function map(options?: MapOptions): Promise<string>;
291
296
 
292
297
  /**
@@ -323,6 +328,51 @@ declare function impact(target: string, options?: ImpactOptions): Promise<string
323
328
  */
324
329
  declare function suggest(target: string, options?: SuggestOptions): Promise<string>;
325
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
+
326
376
  /**
327
377
  * Comando CONTEXT - Extrai assinaturas de funcoes e tipos de um arquivo
328
378
  * Também suporta --area para contexto consolidado de toda uma área
@@ -373,6 +423,7 @@ declare function areasInit(options?: InitOptions): Promise<string>;
373
423
  * Detecta automaticamente projetos Firebase e extrai informações
374
424
  * de triggers como path (Firestore) e schedule (cron).
375
425
  */
426
+
376
427
  /**
377
428
  * Informação de uma Cloud Function
378
429
  */
@@ -410,6 +461,7 @@ interface FunctionsOptions {
410
461
  format?: "text" | "json";
411
462
  cache?: boolean;
412
463
  trigger?: string;
464
+ ctx?: HintContext;
413
465
  }
414
466
  /**
415
467
  * Executa o comando FUNCTIONS
@@ -441,6 +493,7 @@ interface FindOptions {
441
493
  def?: boolean;
442
494
  refs?: boolean;
443
495
  cache?: boolean;
496
+ ctx?: HintContext;
444
497
  }
445
498
  /**
446
499
  * Representa uma ocorrência encontrada
@@ -691,55 +744,58 @@ declare function findBestMatch<T>(target: string, candidates: T[], extractKey?:
691
744
  declare function extractFileName(filePath: string): string;
692
745
 
693
746
  /**
694
- * Formatadores de mensagens de erro com sugestões inteligentes
747
+ * Formatadores de mensagens de erro com sugestoes inteligentes
695
748
  *
696
- * Todas as funções retornam strings formatadas para exibição,
697
- * 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' }")
698
753
  */
699
- /**
700
- * Referência rápida de comandos disponíveis
701
- */
702
- declare const COMMAND_REFERENCE: Record<string, string>;
754
+
703
755
  interface FormatFileNotFoundOptions {
704
756
  /** Termo buscado */
705
757
  target: string;
706
- /** Lista de todos os arquivos disponíveis */
758
+ /** Lista de todos os arquivos disponiveis */
707
759
  allFiles: string[];
708
760
  /** Comando que gerou o erro (para contexto) */
709
761
  command?: string;
762
+ /** Contexto de execucao */
763
+ ctx?: HintContext;
710
764
  }
711
765
  /**
712
- * Formata mensagem de arquivo não encontrado
766
+ * Formata mensagem de arquivo nao encontrado
713
767
  *
714
- * Inclui sugestões de arquivos similares e referência de comandos.
768
+ * Inclui sugestoes de arquivos similares e referencia de comandos.
715
769
  */
716
770
  declare function formatFileNotFound(options: FormatFileNotFoundOptions): string;
717
771
  interface AreaInfo {
718
- /** ID da área */
772
+ /** ID da area */
719
773
  id: string;
720
- /** Número de arquivos na área */
774
+ /** Numero de arquivos na area */
721
775
  count: number;
722
776
  }
723
777
  interface FormatAreaNotFoundOptions {
724
778
  /** Termo buscado */
725
779
  target: string;
726
- /** Lista de áreas disponíveis */
780
+ /** Lista de areas disponiveis */
727
781
  availableAreas: AreaInfo[];
782
+ /** Contexto de execucao */
783
+ ctx?: HintContext;
728
784
  }
729
785
  /**
730
- * Formata mensagem de área não encontrada
786
+ * Formata mensagem de area nao encontrada
731
787
  *
732
- * Inclui sugestões de áreas similares usando Levenshtein.
788
+ * Inclui sugestoes de areas similares usando Levenshtein.
733
789
  */
734
790
  declare function formatAreaNotFound(options: FormatAreaNotFoundOptions): string;
735
791
  /**
736
- * Formata mensagem de target obrigatório faltando
792
+ * Formata mensagem de target obrigatorio faltando
737
793
  */
738
- declare function formatMissingTarget(command: string): string;
794
+ declare function formatMissingTarget(command: string, ctx?: HintContext): string;
739
795
  /**
740
- * Formata mensagem de comando inválido
796
+ * Formata mensagem de comando invalido
741
797
  */
742
- declare function formatInvalidCommand(command: string): string;
798
+ declare function formatInvalidCommand(command: string, ctx?: HintContext): string;
743
799
 
744
800
  /**
745
801
  * Utilitários para detecção de Firebase Cloud Functions
@@ -879,4 +935,4 @@ declare function inferFileDescription(filePath: string, category: string): strin
879
935
 
880
936
  declare const VERSION: string;
881
937
 
882
- 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 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, impact, inferFileDescription, invalidateCache, isCacheValid, isCodeFile, isEntryPoint, isExportedCloudFunction, isFileIgnored, isFirebaseProject, levenshteinDistance, map, readConfig, 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,
@@ -27,6 +26,7 @@ import {
27
26
  getCacheDir,
28
27
  getFileDescription,
29
28
  hasFirebaseFunctions,
29
+ hint,
30
30
  impact,
31
31
  inferFileDescription,
32
32
  invalidateCache,
@@ -38,15 +38,16 @@ import {
38
38
  isFirebaseProject,
39
39
  levenshteinDistance,
40
40
  map,
41
+ nextSteps,
41
42
  readConfig,
43
+ recoveryHint,
42
44
  removeArea,
43
45
  setArea,
44
46
  setFileDescription,
45
47
  suggest,
46
48
  writeConfig
47
- } from "./chunk-J3MX6NK3.js";
49
+ } from "./chunk-4HAUIZQ7.js";
48
50
  export {
49
- COMMAND_REFERENCE,
50
51
  VERSION,
51
52
  area,
52
53
  areas,
@@ -74,6 +75,7 @@ export {
74
75
  getCacheDir,
75
76
  getFileDescription,
76
77
  hasFirebaseFunctions,
78
+ hint,
77
79
  impact,
78
80
  inferFileDescription,
79
81
  invalidateCache,
@@ -85,7 +87,9 @@ export {
85
87
  isFirebaseProject,
86
88
  levenshteinDistance,
87
89
  map,
90
+ nextSteps,
88
91
  readConfig,
92
+ recoveryHint,
89
93
  removeArea,
90
94
  setArea,
91
95
  setFileDescription,