deleting index.ts files

This commit is contained in:
2026-02-04 21:02:01 -05:00
parent f0609e423e
commit 74b0a0dbab
92 changed files with 385 additions and 2082 deletions

View File

@@ -10,24 +10,35 @@ import { existsSync } from "node:fs";
import { homedir } from "node:os";
import type {
BackgroundTask,
BackgroundTaskStatus,
BackgroundTaskPriority,
} from "@/types/background-task";
import {
BackgroundTask,
BackgroundTaskConfig,
TaskProgress,
TaskResult,
TaskError,
TaskMetadata,
TaskNotification,
} from "@/types/background-task";
import { DEFAULT_BACKGROUND_TASK_CONFIG, BACKGROUND_TASK_PRIORITIES } from "@/types/background-task";
} from "@interfaces/BackgroundTask";
import {
DEFAULT_BACKGROUND_TASK_CONFIG,
BACKGROUND_TASK_PRIORITIES,
} from "@constants/background-task";
import {
BACKGROUND_TASK_STORAGE,
BACKGROUND_TASK_MESSAGES,
BACKGROUND_TASK_STATUS_ICONS,
} from "@constants/background-task";
type TaskHandler = (task: BackgroundTask, updateProgress: (progress: Partial<TaskProgress>) => void) => Promise<TaskResult>;
type TaskHandler = (
task: BackgroundTask,
updateProgress: (progress: Partial<TaskProgress>) => void,
) => Promise<TaskResult>;
type NotificationHandler = (notification: TaskNotification) => void;
interface BackgroundTaskState {
@@ -64,12 +75,18 @@ const persistTask = async (task: BackgroundTask): Promise<void> => {
if (!state.config.persistTasks) return;
await ensureStorageDirectory();
const filePath = join(getStoragePath(), `${task.id}${BACKGROUND_TASK_STORAGE.FILE_EXTENSION}`);
const filePath = join(
getStoragePath(),
`${task.id}${BACKGROUND_TASK_STORAGE.FILE_EXTENSION}`,
);
await writeFile(filePath, JSON.stringify(task, null, 2));
};
const removePersistedTask = async (taskId: string): Promise<void> => {
const filePath = join(getStoragePath(), `${taskId}${BACKGROUND_TASK_STORAGE.FILE_EXTENSION}`);
const filePath = join(
getStoragePath(),
`${taskId}${BACKGROUND_TASK_STORAGE.FILE_EXTENSION}`,
);
if (existsSync(filePath)) {
await unlink(filePath);
}
@@ -80,7 +97,9 @@ const loadPersistedTasks = async (): Promise<void> => {
if (!existsSync(storagePath)) return;
const files = await readdir(storagePath);
const taskFiles = files.filter((f) => f.endsWith(BACKGROUND_TASK_STORAGE.FILE_EXTENSION));
const taskFiles = files.filter((f) =>
f.endsWith(BACKGROUND_TASK_STORAGE.FILE_EXTENSION),
);
for (const file of taskFiles) {
try {
@@ -104,7 +123,11 @@ const loadPersistedTasks = async (): Promise<void> => {
}
};
const notify = (taskId: string, type: TaskNotification["type"], message: string): void => {
const notify = (
taskId: string,
type: TaskNotification["type"],
message: string,
): void => {
const notification: TaskNotification = {
taskId,
type,
@@ -133,7 +156,10 @@ const processQueue = async (): Promise<void> => {
const taskA = state.tasks.get(a);
const taskB = state.tasks.get(b);
if (!taskA || !taskB) return 0;
return BACKGROUND_TASK_PRIORITIES[taskB.priority] - BACKGROUND_TASK_PRIORITIES[taskA.priority];
return (
BACKGROUND_TASK_PRIORITIES[taskB.priority] -
BACKGROUND_TASK_PRIORITIES[taskA.priority]
);
});
const taskId = state.queue.shift();
@@ -176,9 +202,10 @@ const executeTask = async (task: BackgroundTask): Promise<void> => {
const newProgress: TaskProgress = {
...currentTask.progress,
...partial,
percentage: partial.current !== undefined && partial.total !== undefined
? Math.round((partial.current / partial.total) * 100)
: currentTask.progress.percentage,
percentage:
partial.current !== undefined && partial.total !== undefined
? Math.round((partial.current / partial.total) * 100)
: currentTask.progress.percentage,
};
const progressTask: BackgroundTask = {
@@ -194,7 +221,10 @@ const executeTask = async (task: BackgroundTask): Promise<void> => {
const result = await Promise.race([
handler(updatedTask, updateProgress),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error("Task timeout")), state.config.defaultTimeout)
setTimeout(
() => reject(new Error("Task timeout")),
state.config.defaultTimeout,
),
),
]);
@@ -214,7 +244,10 @@ const executeTask = async (task: BackgroundTask): Promise<void> => {
}
};
const completeTask = async (taskId: string, result: TaskResult): Promise<void> => {
const completeTask = async (
taskId: string,
result: TaskResult,
): Promise<void> => {
const task = state.tasks.get(taskId);
if (!task) return;
@@ -240,7 +273,7 @@ const completeTask = async (taskId: string, result: TaskResult): Promise<void> =
const updateTaskStatus = async (
taskId: string,
status: BackgroundTaskStatus,
error?: TaskError
error?: TaskError,
): Promise<void> => {
const task = state.tasks.get(taskId);
if (!task) return;
@@ -249,7 +282,9 @@ const updateTaskStatus = async (
...task,
status,
error,
completedAt: ["completed", "failed", "cancelled"].includes(status) ? Date.now() : undefined,
completedAt: ["completed", "failed", "cancelled"].includes(status)
? Date.now()
: undefined,
};
state.tasks.set(taskId, updatedTask);
@@ -262,7 +297,9 @@ const updateTaskStatus = async (
// Public API
export const initialize = async (config?: Partial<BackgroundTaskConfig>): Promise<void> => {
export const initialize = async (
config?: Partial<BackgroundTaskConfig>,
): Promise<void> => {
state.config = { ...DEFAULT_BACKGROUND_TASK_CONFIG, ...config };
await loadPersistedTasks();
processQueue();
@@ -272,10 +309,12 @@ export const registerHandler = (name: string, handler: TaskHandler): void => {
state.handlers.set(name, handler);
};
export const onNotification = (handler: NotificationHandler): () => void => {
export const onNotification = (handler: NotificationHandler): (() => void) => {
state.notificationHandlers.push(handler);
return () => {
state.notificationHandlers = state.notificationHandlers.filter((h) => h !== handler);
state.notificationHandlers = state.notificationHandlers.filter(
(h) => h !== handler,
);
};
};
@@ -283,7 +322,7 @@ export const createTask = async (
name: string,
description: string,
metadata: TaskMetadata,
priority: BackgroundTaskPriority = "normal"
priority: BackgroundTaskPriority = "normal",
): Promise<BackgroundTask> => {
const task: BackgroundTask = {
id: randomUUID(),
@@ -349,7 +388,9 @@ export const resumeTask = async (taskId: string): Promise<boolean> => {
export const getTask = (taskId: string): BackgroundTask | undefined =>
state.tasks.get(taskId);
export const listTasks = (filter?: { status?: BackgroundTaskStatus }): ReadonlyArray<BackgroundTask> => {
export const listTasks = (filter?: {
status?: BackgroundTaskStatus;
}): ReadonlyArray<BackgroundTask> => {
let tasks = Array.from(state.tasks.values());
if (filter?.status) {
@@ -361,7 +402,10 @@ export const listTasks = (filter?: { status?: BackgroundTaskStatus }): ReadonlyA
export const clearCompletedTasks = async (): Promise<number> => {
const completed = Array.from(state.tasks.values()).filter(
(t) => t.status === "completed" || t.status === "failed" || t.status === "cancelled"
(t) =>
t.status === "completed" ||
t.status === "failed" ||
t.status === "cancelled",
);
for (const task of completed) {
@@ -377,7 +421,8 @@ export const getTaskStatusIcon = (status: BackgroundTaskStatus): string =>
export const formatTaskSummary = (task: BackgroundTask): string => {
const icon = getTaskStatusIcon(task.status);
const progress = task.status === "running" ? ` (${task.progress.percentage}%)` : "";
const progress =
task.status === "running" ? ` (${task.progress.percentage}%)` : "";
return `${icon} ${task.name}${progress} - ${task.description}`;
};

View File

@@ -1,22 +0,0 @@
/**
* Cascading Provider Service
*
* Orchestrates multi-provider cascading with quality learning
*/
export {
checkOllamaAvailability,
checkCopilotAvailability,
getProviderStatuses,
clearProviderCache,
invalidateProvider,
type ProviderStatus,
} from "./availability";
export {
executeCascade,
recordUserFeedback,
type CascadeCallbacks,
type CascadeOptions,
type ProviderCallFn,
} from "./orchestrator";

View File

@@ -1,91 +0,0 @@
/**
* Services Core - Core service exports
*/
// Agent
export {
runAgentLoop,
runAgent,
createAgent,
type AgentOptions,
type AgentResult,
} from "./agent";
// Permissions
export {
setWorkingDir as setPermissionsWorkingDir,
setPermissionHandler,
initializePermissions,
parsePattern,
matchesBashPattern,
matchesPathPattern,
isBashAllowed,
isBashDenied,
isFileOpAllowed,
generateBashPattern,
addSessionPattern,
addGlobalPattern,
addLocalPattern,
listPatterns,
clearSessionPatterns,
promptBashPermission,
promptFilePermission,
promptPermission,
getPermissionLevel,
type ToolType,
type PermissionPattern,
type PermissionsConfig,
type PermissionHandler,
} from "./permissions";
// Session
export {
createSession,
loadSession,
saveSession,
addMessage,
addContextFile,
removeContextFile,
getCurrentSession,
listSessions,
deleteSession,
clearMessages,
getMostRecentSession,
getSessionSummaries,
findSession,
setWorkingDirectory,
type SessionInfo,
} from "./session";
// Executor
export {
setWorkingDir as setExecutorWorkingDir,
getWorkingDir,
executeCommand,
executeStreamingCommand,
readFile,
writeFile,
editFile,
deleteFile,
createDirectory,
listDirectory,
pathExists,
getStats,
type ExecutionResult,
type FileOperation,
} from "./executor";
// Config
export {
loadConfig,
saveConfig,
getConfigValue,
setConfigValue,
getAllConfig,
getApiKey,
getModel,
getConfigPath,
isProtectedPath,
resetConfig,
getConfig,
} from "./config";

View File

@@ -1,10 +1,7 @@
/**
* Session management for persisting chat history
*/
import fs from "fs/promises";
import path from "path";
import type { ChatSession, ChatMessage, AgentType } from "@/types/index";
import type { AgentType } from "@/types/common";
import { ChatSession, ChatMessage, AgentType } from "@interafaces/index";
import type { SessionInfo } from "@/types/session";
import { DIRS } from "@constants/paths";

View File

@@ -4,12 +4,19 @@
* Main orchestrator for the 7-phase feature development workflow.
*/
import { PHASE_ORDER, FEATURE_DEV_CONFIG, FEATURE_DEV_ERRORS } from "@constants/feature-dev";
import {
PHASE_ORDER,
FEATURE_DEV_CONFIG,
FEATURE_DEV_ERRORS,
} from "@constants/feature-dev";
import {
executePhase,
validateTransition,
} from "@services/feature-dev/phase-executor";
import { buildWorkflowSummary, extractKeyInfo } from "@services/feature-dev/context-builder";
import {
buildWorkflowSummary,
extractKeyInfo,
} from "@services/feature-dev/context-builder";
import type {
FeatureDevPhase,
FeatureDevState,
@@ -18,11 +25,6 @@ import type {
CheckpointDecision,
} from "@/types/feature-dev";
// Re-export sub-modules
export * from "@services/feature-dev/phase-executor";
export * from "@services/feature-dev/checkpoint-handler";
export * from "@services/feature-dev/context-builder";
// Active workflows storage
const activeWorkflows = new Map<string, FeatureDevState>();
@@ -179,10 +181,11 @@ export const runWorkflow = async (
};
}
state = updateWorkflow(workflowId, {
phase: result.nextPhase,
phaseStatus: "pending",
}) ?? state;
state =
updateWorkflow(workflowId, {
phase: result.nextPhase,
phaseStatus: "pending",
}) ?? state;
ctx.state = state;
} else {
// No next phase, workflow complete
@@ -201,7 +204,9 @@ export const runWorkflow = async (
*/
export const getWorkflowProgress = (
workflowId: string,
): { summary: string; keyInfo: Record<string, string | number> } | undefined => {
):
| { summary: string; keyInfo: Record<string, string | number> }
| undefined => {
const workflow = getWorkflow(workflowId);
if (!workflow) return undefined;

View File

@@ -1,43 +0,0 @@
/**
* GitHub PR Service
*
* Service for interacting with GitHub Pull Requests using the gh CLI.
*/
export { checkGitHubCLI, clearCLIStatusCache, executeGHCommand } from "@services/github-pr/cli";
export {
parsePRUrl,
containsPRUrl,
extractPRUrls,
buildPRUrl,
} from "@services/github-pr/url";
export {
fetchPR,
fetchPRComments,
fetchPRReviews,
fetchPRDiff,
getDefaultBranch,
getCurrentBranch,
getBranchDiff,
} from "@services/github-pr/fetch";
export {
formatPRContext,
formatPRComments,
formatPRReviews,
formatPRDiffSummary,
formatCommentForSolving,
formatPendingComments,
} from "@services/github-pr/format";
export type {
GitHubPR,
GitHubPRComment,
GitHubPRReview,
GitHubPRDiff,
GitHubPRFile,
GitHubCLIStatus,
PRUrlParts,
} from "@/types/github-pr";

View File

@@ -1,15 +0,0 @@
/**
* Services Module - Business logic extracted from UI components
*/
// Feature services
export * from "@services/file-picker-service";
export * from "@services/chat-tui-service";
export * from "@services/github-issue-service";
export * from "@services/command-suggestion-service";
export * from "@services/learning-service";
export * from "@services/rules-service";
export * as brainService from "@services/brain";
// Note: Core services (agent, permissions, session, executor, config) are imported
// directly from @services/core/* to avoid naming conflicts with chat-tui-service

View File

@@ -1,67 +0,0 @@
/**
* Learning Service Exports
*
* Central export point for all learning-related functionality
*/
// Core persistence
export {
saveLearning,
getLearnings,
learningExists,
} from "@services/learning/persistence";
// Embedding service
export {
initializeEmbeddingService,
embed,
embedBatch,
isEmbeddingAvailable,
getEmbeddingModel,
getEmbeddingError,
getServiceState,
resetEmbeddingService,
} from "@services/learning/embeddings";
// Vector store
export {
cosineSimilarity,
euclideanDistance,
loadIndex,
saveIndex,
upsertEmbedding,
removeEmbedding,
hasEmbedding,
getEmbedding,
findSimilar,
findAboveThreshold,
getIndexStats,
} from "@services/learning/vector-store";
// Semantic search
export {
indexLearning,
unindexLearning,
isLearningIndexed,
searchLearnings,
rebuildIndex,
clearIndexCache,
getIndexStatistics,
} from "@services/learning/semantic-search";
// Re-export types
export type {
StoredLearning,
LearningCandidate,
LearningCategory,
} from "@/types/learning";
export type {
EmbeddingVector,
EmbeddingResult,
EmbeddingIndex,
StoredEmbedding,
SimilarityResult,
SemanticSearchResult,
SemanticSearchOptions,
} from "@/types/embeddings";

View File

@@ -1,62 +0,0 @@
/**
* MCP Service - Model Context Protocol integration
*
* Provides connectivity to MCP servers for extensible tool integration.
*/
export { MCPClient } from "@services/mcp/client";
export {
initializeMCP,
loadMCPConfig,
saveMCPConfig,
connectServer,
disconnectServer,
connectAllServers,
disconnectAllServers,
getServerInstances,
getAllTools,
callTool,
addServer,
removeServer,
getMCPConfig,
isMCPAvailable,
} from "@services/mcp/manager";
export type {
MCPConfig,
MCPServerConfig,
MCPServerInstance,
MCPToolDefinition,
MCPResourceDefinition,
MCPToolCallRequest,
MCPToolCallResult,
MCPConnectionState,
MCPTransportType,
MCPManagerState,
} from "@/types/mcp";
// Registry exports
export {
getAllServers,
getCuratedServers,
searchServers,
getServerById,
getServersByCategory,
isServerInstalled,
installServer,
installServerById,
getPopularServers,
getVerifiedServers,
getCategoriesWithCounts,
refreshRegistry,
clearRegistryCache,
} from "@services/mcp/registry";
export type {
MCPRegistryServer,
MCPSearchResult,
MCPSearchOptions,
MCPInstallResult,
MCPServerCategory,
} from "@/types/mcp-registry";

View File

@@ -1,75 +0,0 @@
/**
* Permission System Index
*
* Provides optimized permission checking with cached patterns and indexed lookups.
* Maintains backward compatibility with existing API.
*/
// Re-export optimized implementation
export {
initializePermissions,
resetPermissions,
setWorkingDir,
setPermissionHandler,
isBashAllowed,
isBashDenied,
isFileOpAllowed,
addSessionPattern,
addGlobalPattern,
addLocalPattern,
listPatterns,
clearSessionPatterns,
getPermissionStats,
generateBashPattern,
generateFilePattern,
parsePattern,
matchesBashPattern,
matchesPathPattern,
promptBashPermission,
promptFilePermission,
promptPermission,
getPermissionLevel,
} from "@services/permissions/optimized";
// Re-export pattern cache utilities
export {
clearPatternCache,
getCacheStats,
warmCache,
} from "@services/permissions/pattern-cache";
// Re-export pattern index utilities
export {
buildPatternIndex,
addToIndex,
removeFromIndex,
getPatternsForTool,
hasPattern,
getRawPatterns,
mergeIndexes,
getIndexStats,
type PatternIndex,
type PatternEntry,
type IndexStats,
} from "@services/permissions/pattern-index";
// Re-export matchers
export {
isBashAllowedByIndex,
findMatchingBashPatterns,
extractCommandPrefix,
isFileOpAllowedByIndex,
findMatchingFilePatterns,
normalizePath,
isPathInDirectory,
} from "@services/permissions/matchers";
// Re-export types
export type {
ToolType,
PermissionPattern,
PermissionsConfig,
PermissionPromptRequest,
PermissionPromptResponse,
PermissionHandler,
} from "@/types/permissions";

View File

@@ -1,23 +0,0 @@
/**
* Permission Matchers Index
*
* Re-exports all matchers for convenient access
*/
export {
matchesBashPattern,
isBashAllowedByIndex,
findMatchingBashPatterns,
generateBashPattern,
extractCommandPrefix,
} from "@services/permissions/matchers/bash";
export {
matchesPathPattern,
matchesFilePattern,
isFileOpAllowedByIndex,
findMatchingFilePatterns,
generateFilePattern,
normalizePath,
isPathInDirectory,
} from "@services/permissions/matchers/path";

View File

@@ -1,38 +0,0 @@
/**
* Provider Quality Service
*
* Manages provider quality scores, routing, and learning
*/
export { detectTaskType, getTaskTypeConfidence } from "./task-detector";
export {
detectFeedback,
isCorrection,
isApproval,
type FeedbackType,
type FeedbackResult,
} from "./feedback-detector";
export {
loadQualityData,
saveQualityData,
getProviderQuality,
updateProviderQuality,
calculateOverallScore,
} from "./persistence";
export {
updateQualityScore,
getTaskScore,
getOverallScore,
recordApproval,
recordCorrection,
recordRejection,
recordAuditResult,
type Outcome,
type ScoreUpdate,
} from "./score-manager";
export {
determineRoute,
shouldAudit,
getRoutingExplanation,
type RoutingContext,
} from "./router";

View File

@@ -1,234 +0,0 @@
/**
* Reasoning Control Layer - Public API
*
* This module provides cognitive control layers that create intelligence
* through control flow, not prompt engineering.
*
* Five cognitive functions:
* 1. Quality Evaluation - Assess response acceptability
* 2. Retry Policy - Control retry behavior through state machine
* 3. Context Compression - Reduce context while preserving information
* 4. Memory Selection - Select relevant memories for context
* 5. Termination Detection - Detect task completion through validation
*/
// =============================================================================
// QUALITY EVALUATION
// =============================================================================
export {
evaluateQuality,
computeQualityMetrics,
computeStructuralScore,
computeRelevanceScore,
computeCompletenessScore,
computeCoherenceScore,
computeVerdict,
detectDeficiencies,
hasHallucinationMarkers,
hasContradiction,
} from "@services/reasoning/quality-evaluation";
// =============================================================================
// RETRY POLICY
// =============================================================================
export {
createInitialRetryState,
createRetryBudget,
computeRetryTransition,
splitTaskDescription,
isRetryable,
getCurrentTier,
getRemainingAttempts,
getElapsedTime,
getRemainingTime,
} from "@services/reasoning/retry-policy";
// =============================================================================
// CONTEXT COMPRESSION
// =============================================================================
export {
compressContext,
determineCompressionLevel,
shouldCompress,
compressIncrementally,
calculateMessageAge,
markMessagesWithAge,
getPreservationCandidates,
} from "@services/reasoning/context-compression";
// =============================================================================
// MEMORY SELECTION
// =============================================================================
export {
selectRelevantMemories,
computeRelevance,
computeMandatoryItems,
createMemoryItem,
createQueryContext,
createMemoryStore,
addMemory,
findMemoriesByType,
findMemoriesByPath,
pruneOldMemories,
} from "@services/reasoning/memory-selection";
export { MemoryStore } from "@interfaces/memory";
// =============================================================================
// TERMINATION DETECTION
// =============================================================================
export {
createInitialTerminationState,
processTerminationTrigger,
computeTerminationConfidence,
runValidationCheck,
extractValidationFailures,
isComplete,
isFailed,
isTerminal,
requiresValidation,
getConfidencePercentage,
} from "@services/reasoning/termination-detection";
export type { ValidationContext } from "@services/reasoning/termination-detection";
// =============================================================================
// ORCHESTRATOR
// =============================================================================
export {
createOrchestratorConfig,
createInitialState,
prepareContext,
evaluateResponseQuality,
decideRetry,
checkTermination,
executeReasoningCycle,
} from "@services/reasoning/orchestrator";
export type {
OrchestratorConfig,
ContextPreparationInput,
ContextPreparationOutput,
QualityEvaluationInput,
RetryDecisionInput,
RetryDecisionOutput,
TerminationCheckInput,
TerminationCheckOutput,
ExecutionCycleInput,
ExecutionCycleOutput,
} from "@services/reasoning/orchestrator";
// =============================================================================
// UTILITIES
// =============================================================================
export {
estimateTokens,
estimateTokensForObject,
tokenize,
jaccardSimilarity,
weightedSum,
extractEntities,
createEntityTable,
mergeEntityTables,
truncateMiddle,
foldCode,
extractCodeBlocks,
recencyDecay,
createTimestamp,
generateId,
isValidJson,
hasBalancedBraces,
countMatches,
sum,
unique,
groupBy,
} from "@services/reasoning/utils";
// =============================================================================
// RE-EXPORT TYPES
// =============================================================================
export type {
// Common
MessageId,
ToolId,
MemoryId,
TaskId,
Entity,
EntityType,
EntityTable,
// Quality Evaluation
QualityVerdict,
DeficiencyTag,
QualityMetrics,
QualityEvalInput,
QualityEvalOutput,
ResponseType,
ToolCallInfo,
TaskConstraints,
AttemptRecord,
// Retry Policy
RetryStateKind,
ExhaustionReason,
RetryState,
RetryBudget,
RetryPolicyState,
ContextDelta,
SubTask,
RetryTrigger,
ToolExecutionError,
RetryTransform,
RetryAction,
EscalationContext,
RetryPolicyInput,
RetryPolicyOutput,
// Context Compression
CompressionLevel,
CompressibleMessage,
MessageMetadata,
CompressibleToolResult,
CodeBlock,
CompressionTrigger,
CompressionInput,
CompressionOutput,
// Memory Selection
MemoryItemType,
MemoryItem,
QueryContext,
RelevanceScore,
RelevanceBreakdown,
SelectionInput,
ExclusionReason,
SelectionOutput,
// Termination Detection
TerminationStatus,
CompletionSignalSource,
CompletionSignal,
ValidationCheckType,
ValidationCheck,
ValidationResult,
ValidationFailure,
TerminationState,
TerminationTrigger,
TerminationDecision,
TerminationOutput,
TerminationEvidence,
// Orchestrator
ReasoningControlState,
ExecutionPhase,
ExecutionMetrics,
ReasoningTaskResult,
} from "@/types/reasoning";