@memberjunction/ai-cli 2.118.0 → 2.120.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.
package/README.md CHANGED
@@ -18,10 +18,11 @@ A fully functional command-line interface for executing MemberJunction AI agents
18
18
  - ✅ Direct prompt execution with any AI model
19
19
  - ✅ Interactive chat mode with agents
20
20
  - ✅ Comprehensive error handling and logging
21
- - ✅ Multiple output formats (compact, table, JSON)
21
+ - ✅ Multiple output formats (compact, table, JSON, markdown)
22
22
  - ✅ Real-time progress tracking with visual indicators
23
23
  - ✅ Advanced text formatting for improved readability
24
24
  - ✅ Full conversation context in chat mode
25
+ - ✅ Agent run auditing and debugging tools
25
26
 
26
27
  ## Installation
27
28
 
@@ -163,17 +164,37 @@ The chat mode maintains full conversation context:
163
164
  - Supports natural back-and-forth dialogue
164
165
  - Exit with "exit", "quit", or Ctrl+C
165
166
 
167
+ ### Agent Run Auditing
168
+
169
+ The AgentAuditService provides comprehensive debugging and performance analysis tools for AI agent executions. This service is exposed through the MJCLI `mj ai audit agent-run` command.
170
+
171
+ **Key Features:**
172
+ - **List Recent Runs**: Filter by agent name, status, and date range
173
+ - **Run Summaries**: High-level overview with step list and identifiable IDs
174
+ - **Step Detail Analysis**: Deep dive into specific step inputs/outputs with smart truncation
175
+ - **Error Analysis**: Automatic error pattern detection with suggested fixes
176
+ - **Multiple Output Formats**: Compact, JSON, table, markdown
177
+ - **Token Management**: Smart truncation prevents overwhelming large payloads (configurable with `--max-tokens`)
178
+ - **Export Capabilities**: Full data export to JSON files for offline analysis
179
+
180
+ **Smart Truncation:**
181
+ The audit system automatically truncates large input/output payloads to prevent token overflow, showing the first 70% and last 30% of content with a truncation indicator. This is especially useful for Skip-Brain agents that generate large component payloads.
182
+
183
+ **Performance Optimization:**
184
+ All audit queries use `ResultType: 'simple'` for optimal read-only performance, avoiding unnecessary entity object instantiation overhead.
185
+
166
186
  ## Architecture
167
187
 
168
188
  The CLI follows the MetadataSync pattern with:
169
189
 
170
- - **Service Layer**: AgentService, ActionService, ValidationService
190
+ - **Service Layer**: AgentService, ActionService, ValidationService, AgentAuditService
171
191
  - **Infrastructure**: MJ Provider with database integration
172
192
  - **Logging**: Comprehensive execution tracking with file output
173
193
  - **Error Handling**: User-friendly error messages with next steps
174
194
  - **Configuration**: Automatic mj.config.cjs detection and loading
175
195
  - **Text Formatting**: Advanced console output formatting with TextFormatter
176
196
  - **Progress Tracking**: Real-time execution status with visual indicators
197
+ - **Audit & Analysis**: AgentAuditService for debugging and performance analysis
177
198
 
178
199
  ### Design Decisions
179
200
 
package/dist/index.d.ts CHANGED
@@ -4,8 +4,12 @@ export { ActionService } from './services/ActionService';
4
4
  export { ConversationService } from './services/ConversationService';
5
5
  export { ValidationService } from './services/ValidationService';
6
6
  export { PromptService } from './services/PromptService';
7
+ export { AgentAuditService } from './services/AgentAuditService';
7
8
  export { OutputFormatter } from './lib/output-formatter';
8
9
  export { ExecutionLogger, createExecutionLogger } from './lib/execution-logger';
9
10
  export { initializeMJProvider, getConnectionPool, closeMJProvider } from './lib/mj-provider';
10
11
  export { loadAIConfig } from './config';
12
+ export { AuditAnalyzer } from './lib/audit-analyzer';
13
+ export { AuditFormatter } from './lib/audit-formatter';
14
+ export type { RunSummary, StepDetail, ErrorAnalysis, ListRunsOptions, StepDetailOptions, RunSummaryOptions, } from './services/AgentAuditService';
11
15
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAGlC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE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  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loadAIConfig = exports.closeMJProvider = exports.getConnectionPool = exports.initializeMJProvider = exports.createExecutionLogger = exports.ExecutionLogger = exports.OutputFormatter = exports.PromptService = exports.ValidationService = exports.ConversationService = exports.ActionService = exports.AgentService = exports.run = void 0;
3
+ exports.AuditFormatter = exports.AuditAnalyzer = exports.loadAIConfig = exports.closeMJProvider = exports.getConnectionPool = exports.initializeMJProvider = exports.createExecutionLogger = exports.ExecutionLogger = exports.OutputFormatter = exports.AgentAuditService = exports.PromptService = exports.ValidationService = exports.ConversationService = exports.ActionService = exports.AgentService = exports.run = void 0;
4
4
  var core_1 = require("@oclif/core");
5
5
  Object.defineProperty(exports, "run", { enumerable: true, get: function () { return core_1.run; } });
6
6
  // Export services for potential programmatic use
@@ -14,6 +14,8 @@ var ValidationService_1 = require("./services/ValidationService");
14
14
  Object.defineProperty(exports, "ValidationService", { enumerable: true, get: function () { return ValidationService_1.ValidationService; } });
15
15
  var PromptService_1 = require("./services/PromptService");
16
16
  Object.defineProperty(exports, "PromptService", { enumerable: true, get: function () { return PromptService_1.PromptService; } });
17
+ var AgentAuditService_1 = require("./services/AgentAuditService");
18
+ Object.defineProperty(exports, "AgentAuditService", { enumerable: true, get: function () { return AgentAuditService_1.AgentAuditService; } });
17
19
  // Export utilities
18
20
  var output_formatter_1 = require("./lib/output-formatter");
19
21
  Object.defineProperty(exports, "OutputFormatter", { enumerable: true, get: function () { return output_formatter_1.OutputFormatter; } });
@@ -26,4 +28,8 @@ Object.defineProperty(exports, "getConnectionPool", { enumerable: true, get: fun
26
28
  Object.defineProperty(exports, "closeMJProvider", { enumerable: true, get: function () { return mj_provider_1.closeMJProvider; } });
27
29
  var config_1 = require("./config");
28
30
  Object.defineProperty(exports, "loadAIConfig", { enumerable: true, get: function () { return config_1.loadAIConfig; } });
31
+ var audit_analyzer_1 = require("./lib/audit-analyzer");
32
+ Object.defineProperty(exports, "AuditAnalyzer", { enumerable: true, get: function () { return audit_analyzer_1.AuditAnalyzer; } });
33
+ var audit_formatter_1 = require("./lib/audit-formatter");
34
+ Object.defineProperty(exports, "AuditFormatter", { enumerable: true, get: function () { return audit_formatter_1.AuditFormatter; } });
29
35
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,oCAAkC;AAAzB,2FAAA,GAAG,OAAA;AAEZ,iDAAiD;AACjD,wDAAuD;AAA9C,4GAAA,YAAY,OAAA;AACrB,0DAAyD;AAAhD,8GAAA,aAAa,OAAA;AACtB,sEAAqE;AAA5D,0HAAA,mBAAmB,OAAA;AAC5B,kEAAiE;AAAxD,sHAAA,iBAAiB,OAAA;AAC1B,0DAAyD;AAAhD,8GAAA,aAAa,OAAA;AAEtB,mBAAmB;AACnB,2DAAyD;AAAhD,mHAAA,eAAe,OAAA;AACxB,2DAAgF;AAAvE,mHAAA,eAAe,OAAA;AAAE,yHAAA,qBAAqB,OAAA;AAC/C,iDAA6F;AAApF,mHAAA,oBAAoB,OAAA;AAAE,gHAAA,iBAAiB,OAAA;AAAE,8GAAA,eAAe,OAAA;AACjE,mCAAwC;AAA/B,sGAAA,YAAY,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,oCAAkC;AAAzB,2FAAA,GAAG,OAAA;AAEZ,iDAAiD;AACjD,wDAAuD;AAA9C,4GAAA,YAAY,OAAA;AACrB,0DAAyD;AAAhD,8GAAA,aAAa,OAAA;AACtB,sEAAqE;AAA5D,0HAAA,mBAAmB,OAAA;AAC5B,kEAAiE;AAAxD,sHAAA,iBAAiB,OAAA;AAC1B,0DAAyD;AAAhD,8GAAA,aAAa,OAAA;AACtB,kEAAiE;AAAxD,sHAAA,iBAAiB,OAAA;AAE1B,mBAAmB;AACnB,2DAAyD;AAAhD,mHAAA,eAAe,OAAA;AACxB,2DAAgF;AAAvE,mHAAA,eAAe,OAAA;AAAE,yHAAA,qBAAqB,OAAA;AAC/C,iDAA6F;AAApF,mHAAA,oBAAoB,OAAA;AAAE,gHAAA,iBAAiB,OAAA;AAAE,8GAAA,eAAe,OAAA;AACjE,mCAAwC;AAA/B,sGAAA,YAAY,OAAA;AACrB,uDAAqD;AAA5C,+GAAA,aAAa,OAAA;AACtB,yDAAuD;AAA9C,iHAAA,cAAc,OAAA"}
@@ -0,0 +1,65 @@
1
+ import { AIAgentRunStepEntity } from '@memberjunction/core-entities';
2
+ export interface TruncationRules {
3
+ inputMaxChars: number;
4
+ outputMaxChars: number;
5
+ }
6
+ /**
7
+ * Utility class for analyzing agent run data and applying smart truncation
8
+ */
9
+ export declare class AuditAnalyzer {
10
+ /**
11
+ * Estimate token count from string (rough approximation)
12
+ * Uses the common rule of ~4 characters per token
13
+ */
14
+ estimateTokenCount(text: string): number;
15
+ /**
16
+ * Estimate cost from token count (using average pricing)
17
+ * Note: This uses an average rate and may not reflect actual costs
18
+ */
19
+ estimateCost(tokens: number): number;
20
+ /**
21
+ * Calculate step duration from entity timestamps
22
+ */
23
+ calculateStepDuration(step: AIAgentRunStepEntity): number;
24
+ /**
25
+ * Get truncation rules based on detail level and max tokens
26
+ */
27
+ getTruncationRules(detailLevel: string, maxTokens: number): TruncationRules;
28
+ /**
29
+ * Truncate field with smart preview (first + last chars)
30
+ * Shows beginning and end of content with truncation indicator
31
+ */
32
+ truncateField(text: string, maxChars: number): string;
33
+ /**
34
+ * Detect common error patterns across multiple error messages
35
+ * Finds the longest common substring that appears in all errors
36
+ */
37
+ detectErrorPattern(errorMessages: string[]): string | undefined;
38
+ /**
39
+ * Suggest fixes based on error pattern and failed step context
40
+ * Analyzes error messages and provides actionable debugging suggestions
41
+ */
42
+ suggestFixes(errorPattern: string | undefined, failedSteps: Array<{
43
+ errorMessage: string;
44
+ stepType: string;
45
+ }>): string[];
46
+ /**
47
+ * Format duration in human-readable format
48
+ */
49
+ formatDuration(milliseconds: number): string;
50
+ /**
51
+ * Calculate aggregate statistics for a collection of runs
52
+ */
53
+ calculateAggregateStats(runs: Array<{
54
+ duration: number;
55
+ tokenCount: number;
56
+ success: boolean;
57
+ }>): {
58
+ totalRuns: number;
59
+ successRate: number;
60
+ avgDuration: number;
61
+ totalTokens: number;
62
+ avgTokens: number;
63
+ };
64
+ }
65
+ //# sourceMappingURL=audit-analyzer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-analyzer.d.ts","sourceRoot":"","sources":["../../src/lib/audit-analyzer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,MAAM,WAAW,eAAe;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,qBAAa,aAAa;IACxB;;;OAGG;IACH,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAKxC;;;OAGG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAKpC;;OAEG;IACH,qBAAqB,CAAC,IAAI,EAAE,oBAAoB,GAAG,MAAM;IAKzD;;OAEG;IACH,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,eAAe;IAqB3E;;;OAGG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM;IAgBrD;;;OAGG;IACH,kBAAkB,CAAC,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS;IAqB/D;;;OAGG;IACH,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,WAAW,EAAE,KAAK,CAAC;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG,MAAM,EAAE;IA0ExH;;OAEG;IACH,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM;IAgB5C;;OAEG;IACH,uBAAuB,CAAC,IAAI,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,GAAG;QAChG,SAAS,EAAE,MAAM,CAAC;QAClB,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;KACnB;CAmBF"}
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuditAnalyzer = void 0;
4
+ /**
5
+ * Utility class for analyzing agent run data and applying smart truncation
6
+ */
7
+ class AuditAnalyzer {
8
+ /**
9
+ * Estimate token count from string (rough approximation)
10
+ * Uses the common rule of ~4 characters per token
11
+ */
12
+ estimateTokenCount(text) {
13
+ if (!text)
14
+ return 0;
15
+ return Math.ceil(text.length / 4);
16
+ }
17
+ /**
18
+ * Estimate cost from token count (using average pricing)
19
+ * Note: This uses an average rate and may not reflect actual costs
20
+ */
21
+ estimateCost(tokens) {
22
+ // Average: $0.01 per 1000 tokens (adjust based on actual model)
23
+ return (tokens / 1000) * 0.01;
24
+ }
25
+ /**
26
+ * Calculate step duration from entity timestamps
27
+ */
28
+ calculateStepDuration(step) {
29
+ if (!step.StartedAt || !step.CompletedAt)
30
+ return 0;
31
+ return new Date(step.CompletedAt).getTime() - new Date(step.StartedAt).getTime();
32
+ }
33
+ /**
34
+ * Get truncation rules based on detail level and max tokens
35
+ */
36
+ getTruncationRules(detailLevel, maxTokens) {
37
+ const maxChars = maxTokens * 4; // Convert tokens to chars
38
+ switch (detailLevel) {
39
+ case 'minimal':
40
+ return { inputMaxChars: 500, outputMaxChars: 500 };
41
+ case 'standard':
42
+ return { inputMaxChars: 2000, outputMaxChars: 2000 };
43
+ case 'detailed':
44
+ return { inputMaxChars: maxChars, outputMaxChars: maxChars };
45
+ case 'full':
46
+ return { inputMaxChars: Infinity, outputMaxChars: Infinity };
47
+ default:
48
+ return { inputMaxChars: 2000, outputMaxChars: 2000 };
49
+ }
50
+ }
51
+ /**
52
+ * Truncate field with smart preview (first + last chars)
53
+ * Shows beginning and end of content with truncation indicator
54
+ */
55
+ truncateField(text, maxChars) {
56
+ if (!text || text.length <= maxChars || maxChars === Infinity) {
57
+ return text || '';
58
+ }
59
+ const firstChars = Math.floor(maxChars * 0.7);
60
+ const lastChars = Math.floor(maxChars * 0.3);
61
+ const truncatedCount = text.length - maxChars;
62
+ return (text.substring(0, firstChars) +
63
+ `\n\n... [TRUNCATED ${truncatedCount} characters] ...\n\n` +
64
+ text.substring(text.length - lastChars));
65
+ }
66
+ /**
67
+ * Detect common error patterns across multiple error messages
68
+ * Finds the longest common substring that appears in all errors
69
+ */
70
+ detectErrorPattern(errorMessages) {
71
+ if (errorMessages.length === 0)
72
+ return undefined;
73
+ if (errorMessages.length === 1)
74
+ return errorMessages[0];
75
+ const first = errorMessages[0];
76
+ // Try to find common substrings, starting with longest
77
+ for (let len = Math.min(first.length, 200); len > 10; len--) {
78
+ for (let start = 0; start <= first.length - len; start++) {
79
+ const pattern = first.substring(start, start + len);
80
+ if (errorMessages.every(msg => msg.includes(pattern))) {
81
+ return pattern.trim();
82
+ }
83
+ }
84
+ }
85
+ // No common pattern found, return first error
86
+ return errorMessages[0];
87
+ }
88
+ /**
89
+ * Suggest fixes based on error pattern and failed step context
90
+ * Analyzes error messages and provides actionable debugging suggestions
91
+ */
92
+ suggestFixes(errorPattern, failedSteps) {
93
+ const suggestions = [];
94
+ if (!errorPattern)
95
+ return suggestions;
96
+ const pattern = errorPattern.toLowerCase();
97
+ // Common error patterns and their solutions
98
+ if (pattern.includes('timeout')) {
99
+ suggestions.push('Increase timeout value in agent configuration');
100
+ suggestions.push('Check for slow database queries or API calls');
101
+ suggestions.push('Consider breaking long-running operations into smaller steps');
102
+ }
103
+ if (pattern.includes('runview') || pattern.includes('entity')) {
104
+ suggestions.push('Verify entity name matches exactly (check for "MJ: " prefix)');
105
+ suggestions.push('Ensure contextUser is passed to RunView on server-side');
106
+ suggestions.push('Check that the entity exists in the database schema');
107
+ }
108
+ if (pattern.includes('json') || pattern.includes('parse')) {
109
+ suggestions.push('Check for malformed JSON in previous step output');
110
+ suggestions.push('Validate prompt output format instructions');
111
+ suggestions.push('Ensure proper escaping of special characters in JSON');
112
+ }
113
+ if (pattern.includes('null') || pattern.includes('undefined')) {
114
+ suggestions.push('Add null checks for optional fields');
115
+ suggestions.push('Verify data is loaded before accessing properties');
116
+ suggestions.push('Check if required parameters are being passed correctly');
117
+ }
118
+ if (pattern.includes('permission') || pattern.includes('access')) {
119
+ suggestions.push('Check user permissions for entity operations');
120
+ suggestions.push('Verify security settings in entity metadata');
121
+ suggestions.push('Ensure the context user has appropriate roles');
122
+ }
123
+ if (pattern.includes('model') || pattern.includes('llm')) {
124
+ suggestions.push('Verify AI model is configured and available');
125
+ suggestions.push('Check API keys and credentials for AI providers');
126
+ suggestions.push('Ensure model supports the requested features');
127
+ }
128
+ if (pattern.includes('prompt') || pattern.includes('template')) {
129
+ suggestions.push('Review prompt template for syntax errors');
130
+ suggestions.push('Check that all required template variables are provided');
131
+ suggestions.push('Validate prompt references exist in database');
132
+ }
133
+ // Step-type specific suggestions
134
+ const stepTypes = failedSteps.map(s => s.stepType.toLowerCase());
135
+ if (stepTypes.includes('data_gather') || stepTypes.includes('datagather')) {
136
+ suggestions.push('Review entity filters and ensure proper SQL syntax');
137
+ suggestions.push('Check that relationships between entities are correctly configured');
138
+ }
139
+ if (stepTypes.includes('write_script') || stepTypes.includes('writescript')) {
140
+ suggestions.push('Validate generated script syntax');
141
+ suggestions.push('Check that script dependencies are available');
142
+ }
143
+ // Generic suggestions if no specific pattern matched
144
+ if (suggestions.length === 0) {
145
+ suggestions.push('Review step input/output with --step <N> --detail full');
146
+ suggestions.push('Check logs for previous step to identify data issues');
147
+ suggestions.push('Verify agent prompt instructions are clear and complete');
148
+ suggestions.push('Test with simpler inputs to isolate the problem');
149
+ }
150
+ return suggestions;
151
+ }
152
+ /**
153
+ * Format duration in human-readable format
154
+ */
155
+ formatDuration(milliseconds) {
156
+ if (milliseconds < 1000) {
157
+ return `${milliseconds}ms`;
158
+ }
159
+ else if (milliseconds < 60000) {
160
+ return `${(milliseconds / 1000).toFixed(2)}s`;
161
+ }
162
+ else if (milliseconds < 3600000) {
163
+ const minutes = Math.floor(milliseconds / 60000);
164
+ const seconds = ((milliseconds % 60000) / 1000).toFixed(0);
165
+ return `${minutes}m ${seconds}s`;
166
+ }
167
+ else {
168
+ const hours = Math.floor(milliseconds / 3600000);
169
+ const minutes = Math.floor((milliseconds % 3600000) / 60000);
170
+ return `${hours}h ${minutes}m`;
171
+ }
172
+ }
173
+ /**
174
+ * Calculate aggregate statistics for a collection of runs
175
+ */
176
+ calculateAggregateStats(runs) {
177
+ const totalRuns = runs.length;
178
+ const successCount = runs.filter(r => r.success).length;
179
+ const successRate = totalRuns > 0 ? (successCount / totalRuns) * 100 : 0;
180
+ const totalDuration = runs.reduce((sum, r) => sum + r.duration, 0);
181
+ const avgDuration = totalRuns > 0 ? totalDuration / totalRuns : 0;
182
+ const totalTokens = runs.reduce((sum, r) => sum + r.tokenCount, 0);
183
+ const avgTokens = totalRuns > 0 ? totalTokens / totalRuns : 0;
184
+ return {
185
+ totalRuns,
186
+ successRate,
187
+ avgDuration,
188
+ totalTokens,
189
+ avgTokens,
190
+ };
191
+ }
192
+ }
193
+ exports.AuditAnalyzer = AuditAnalyzer;
194
+ //# sourceMappingURL=audit-analyzer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit-analyzer.js","sourceRoot":"","sources":["../../src/lib/audit-analyzer.ts"],"names":[],"mappings":";;;AAOA;;GAEG;AACH,MAAa,aAAa;IACxB;;;OAGG;IACH,kBAAkB,CAAC,IAAY;QAC7B,IAAI,CAAC,IAAI;YAAE,OAAO,CAAC,C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ction/core-entities';
2
+ import type { RunSummary, StepDetail, ErrorAnalysis } from '../services/AgentAuditService';
3
+ export type AuditOutputFormat = 'compact' | 'json' | 'table' | 'markdown';
4
+ /**
5
+ * Utility class for formatting agent audit data for display
6
+ */
7
+ export declare class AuditFormatter {
8
+ /**
9
+ * Format list of agent runs
10
+ */
11
+ formatRunList(runs: AIAgentRunEntity[], format: AuditOutputFormat): string;
12
+ /**
13
+ * Format run list as compact text
14
+ */
15
+ private formatRunListCompact;
16
+ /**
17
+ * Format run list as table
18
+ */
19
+ private formatRunListTable;
20
+ /**
21
+ * Format run summary
22
+ */
23
+ formatRunSummary(summary: RunSummary, format: AuditOutputFormat): string;
24
+ /**
25
+ * Format run summary as compact text
26
+ */
27
+ private formatRunSummaryCompact;
28
+ /**
29
+ * Format run summary as table
30
+ */
31
+ private formatRunSummaryTable;
32
+ /**
33
+ * Format run summary as markdown (for Claude Code consumption)
34
+ */
35
+ private formatRunSummaryMarkdown;
36
+ /**
37
+ * Format step detail
38
+ */
39
+ formatStepDetail(detail: StepDetail, format: AuditOutputFormat): string;
40
+ /**
41
+ * Format step detail as compact text
42
+ */
43
+ private formatStepDetailCompact;
44
+ /**
45
+ * Format step detail as markdown
46
+ */
47
+ private formatStepDetailMarkdown;
48
+ /**
49
+ * Format error analysis
50
+ */
51
+ formatErrorAnalysis(analysis: ErrorAnalysis, format: AuditOutputFormat): string;
52
+ /**
53
+ * Format error analysis as compact text
54
+ */
55
+ private formatErrorAnalysisCompact;
56
+ /**
57
+ * Format error analysis as markdown
58
+ */
59
+ private formatErrorAnalysisMarkdown;
60
+ /**
61
+ * Format status with color coding
62
+ */
63
+ private formatStatusText;
64
+ /**
65
+ * Format status as icon
66
+ */
67
+ private formatStatusIcon;
68
+ /**
69
+ * Calculate and format duration
70
+ */
71
+ private calculateDuration;
72
+ /**
73
+ * Format JSON string with indentation
74
+ */
75
+ private formatJson;
76
+ }
77
+ //# sourceMappingURL=audit-formatter.d.ts.map
@@ -0,0 +1 @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