export type SignalSourceType = 'filesystem' | 'webhook' | 'schedule' | 'message' | 'api_poll'; export interface FileSystemSignalConfig { type: 'filesystem'; paths: string[]; patterns?: string[]; ignorePatterns?: string[]; } export interface WebhookSignalConfig { type: 'webhook'; port: number; path: string; secret?: string; } export interface ScheduleSignalConfig { type: 'schedule'; intervalMs: number; label: string; } export interface MessageSignalConfig { type: 'message'; channel: string; } export interface ApiPollSignalConfig { type: 'api_poll'; url: string; intervalMs: number; headers?: Record; } export type SignalConfig = FileSystemSignalConfig | WebhookSignalConfig | ScheduleSignalConfig | MessageSignalConfig | ApiPollSignalConfig; export type ObservationUrgency = 'critical' | 'high' | 'normal' | 'low'; export interface Observation { id: string; source: SignalSourceType; urgency: ObservationUrgency; timestamp: string; payload: ObservationPayload; relatedExperienceIds?: string[]; } export type ObservationPayload = FileChangePayload | WebhookPayload | ScheduleTickPayload | MessagePayload | ApiPollPayload; export interface FileChangePayload { type: 'file_change'; event: 'create' | 'modify' | 'delete'; path: string; diff?: string; } export interface WebhookPayload { type: 'webhook'; method: string; path: string; headers: Record; body: unknown; } export interface ScheduleTickPayload { type: 'schedule_tick'; label: string; tickNumber: number; } export interface MessagePayload { type: 'message'; channel: string; sender: string; content: string; } export interface ApiPollPayload { type: 'api_poll'; url: string; statusCode: number; body: unknown; previousBody?: unknown; } export type DecisionAction = 'act' | 'ignore' | 'defer'; export interface Decision { id: string; observationId: string; action: DecisionAction; reasoning: string; confidence: number; proposedActions: ProposedAction[]; risks: string[]; modelUsage: { inputTokens: number; outputTokens: number; }; timestamp: string; } export interface ProposedAction { description: string; operationType: OperationType; target: string; details: string; } export type OperationType = 'code_write' | 'code_run' | 'api_call' | 'git' | 'message'; export type ApprovalLevel = 'auto' | 'single' | 'escalate'; export interface ActionPlan { id: string; decisionId: string; steps: ActionStep[]; totalSteps: number; estimatedDurationMs: number; overallRisk: ApprovalLevel; timestamp: string; } export interface ActionStep { id: string; planId: string; index: number; description: string; operation: Operation; preConditions: Condition[]; postConditions: Condition[]; approvalLevel: ApprovalLevel; dependsOn: string[]; } export interface Condition { description: string; check: string; } export type Operation = CodeWriteOp | CodeRunOp | ApiCallOp | GitOp | MessageOp; export interface CodeWriteOp { type: 'code_write'; filePath: string; content: string; mode: 'create' | 'edit' | 'append'; editTarget?: string; } export interface CodeRunOp { type: 'code_run'; command: string; cwd?: string; timeoutMs: number; env?: Record; } export interface ApiCallOp { type: 'api_call'; method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; url: string; headers?: Record; body?: unknown; expectedStatus?: number; } export interface GitOp { type: 'git'; command: 'add' | 'commit' | 'push' | 'branch' | 'checkout'; args: string[]; cwd?: string; } export interface MessageOp { type: 'message'; channel: 'console' | 'slack' | 'email'; recipient?: string; subject?: string; content: string; } export type VerificationVerdict = 'pass' | 'warn' | 'fail' | 'escalate'; export interface StepVerification { stepId: string; verdict: VerificationVerdict; claims: VerificationClaim[]; reasoning: string; formalOverrides: number; timestamp: string; } export interface VerificationClaim { id: string; text: string; verdict: 'PASS' | 'PARTIAL' | 'FAIL' | 'N/A' | 'UNVERIFIABLE'; confidence: number; method: 'formal' | 'llm'; } export interface PlanVerification { planId: string; overallVerdict: VerificationVerdict; stepVerifications: StepVerification[]; blockedSteps: string[]; escalatedSteps: string[]; totalClaims: number; passedClaims: number; failedClaims: number; timestamp: string; } export type ExecutionStatus = 'success' | 'partial' | 'failure' | 'skipped'; export interface StepExecution { stepId: string; status: ExecutionStatus; output: string; error?: string; durationMs: number; timestamp: string; } export interface PlanExecution { planId: string; status: ExecutionStatus; stepExecutions: StepExecution[]; completedSteps: number; totalSteps: number; totalDurationMs: number; timestamp: string; } export type ExperienceOutcome = 'success' | 'partial_success' | 'failure' | 'unexpected'; export interface Experience { id: string; observation: Observation; decision: Decision; plan: ActionPlan; verification: PlanVerification; execution: PlanExecution; outcome: ExperienceOutcome; delta: string; lessons: string[]; domain: string; tags: string[]; timestamp: string; } export interface SkillProfile { domain: string; totalExperiences: number; successRate: number; firstPassRate: number; commonPatterns: string[]; commonAntiPatterns: string[]; lastUpdated: string; } export interface PatternEntry { id: string; domain: string; description: string; codeExample: string; language: string; verificationCount: number; lastVerified: string; formallyVerified: boolean; } export interface AntiPatternEntry { id: string; domain: string; description: string; badExample: string; fixedExample: string; language: string; claimCategory: string; occurrenceCount: number; lastSeen: string; } export interface ScoredExperience { experience: Experience; similarity: number; } export interface VerificationHotspot { claimCategory: string; failRate: number; totalClaims: number; failedClaims: number; formalCoverage: number; topFailureReasons: string[]; candidateForFormalRule: boolean; } export interface Strategy { id: string; domain: string; operationType: OperationType; name: string; description: string; planTemplate: string; timesUsed: number; timesSucceeded: number; successRate: number; avgVerificationPassRate: number; avgDurationMs: number; lastUsed: string; discoveredFrom: string[]; createdAt: string; } export interface CalibrationBucket { confidenceRange: [number, number]; totalDecisions: number; actualSuccessRate: number; gap: number; } export interface CalibrationProfile { domain: string; buckets: CalibrationBucket[]; expectedCalibrationError: number; adjustmentFactor: number; lastUpdated: string; } export interface RuleCandidate { id: string; claimCategory: string; description: string; rationale: string; substrate: 'regex' | 'ast'; pattern: string; language: string; testCases: RuleCandidateTest[]; sourceHotspot: string; supportingExperiences: string[]; estimatedFormalCoverage: number; status: 'proposed' | 'shadow' | 'promoted' | 'rejected'; proposedAt: string; promotedAt?: string; rejectedAt?: string; } export interface RuleCandidateTest { input: string; language: string; expectedVerdict: 'PASS' | 'FAIL'; description: string; } export interface ShadowResult { id: string; candidateId: string; formalVerdict: 'PASS' | 'FAIL'; llmVerdict: 'PASS' | 'FAIL' | 'PARTIAL'; agreed: boolean; codeSnippet?: string; timestamp: string; } export interface ShadowStats { candidateId: string; totalEvaluations: number; agreements: number; disagreements: number; formalCaughtLlmMiss: number; falsePositives: number; accuracy: number; shadowDays: number; } export interface PromotionDecision { candidateId: string; decision: 'promote' | 'keep_shadowing' | 'reject'; reason: string; stats: ShadowStats; } export interface ReasoningContext { relevantExperiences: ScoredExperience[]; skillProfile: SkillProfile | null; patterns: PatternEntry[]; antiPatterns: AntiPatternEntry[]; calibration: CalibrationProfile | null; promptSection: string; } export interface PlanningContext { rankedStrategies: Strategy[]; hotspots: VerificationHotspot[]; promptSection: string; } export interface LearningConfig { supabaseUrl?: string; supabaseServiceKey?: string; extractionThreshold: number; embeddingModel: string; enrichedPromptTokenBudget: number; shadowRunnerEnabled: boolean; } export interface AgentScope { allowedDirectories: string[]; allowedCommands: string[]; allowedUrls: string[]; blockedPatterns: string[]; maxFileSize: number; } export interface HardLimits { maxActionsPerHour: number; maxTokensPerHour: number; maxConcurrentSteps: number; maxPlanSteps: number; commandTimeoutMs: number; maxSessionCostCents?: number; } export interface AgentConfig { name: string; description: string; scope: AgentScope; limits: HardLimits; signals: SignalConfig[]; approvalDefaults: Record; modelId: string; experienceStorePath: string; controlPort?: number; jsonLogs?: boolean; learningConfig?: LearningConfig; } export type AgentPhase = 'idle' | 'observing' | 'reasoning' | 'planning' | 'verifying' | 'awaiting_approval' | 'executing' | 'reflecting' | 'paused' | 'stopped'; export interface AgentState { phase: AgentPhase; currentObservation: Observation | null; currentDecision: Decision | null; currentPlan: ActionPlan | null; queueDepth: number; actionsThisHour: number; tokensThisHour: number; totalExperiences: number; uptime: number; lastActivityTimestamp: string; errors: AgentError[]; } export interface AgentError { phase: AgentPhase; message: string; timestamp: string; recoverable: boolean; } export type ApprovalStatus = 'pending' | 'approved' | 'rejected' | 'expired'; export interface ApprovalRequest { id: string; planId: string; stepId?: string; action: string; reasoning: string; riskLevel: ApprovalLevel; verification: PlanVerification; status: ApprovalStatus; createdAt: string; resolvedAt?: string; resolvedBy?: string; rejectionReason?: string; } export type AuditEventType = 'observation_received' | 'decision_made' | 'plan_created' | 'verification_completed' | 'approval_requested' | 'approval_resolved' | 'step_executed' | 'experience_stored' | 'agent_started' | 'agent_stopped' | 'agent_error' | 'message_sent' | 'verification_run' | 'trust_change' | 'handoff_decision' | 'task_status_change' | 'escalation'; export interface AuditEntry { id: string; eventType: AuditEventType; agentName: string; timestamp: string; details: Record; relatedIds: { observationId?: string; decisionId?: string; planId?: string; stepId?: string; experienceId?: string; }; prevHash?: string; } export type AgentSpecialization = 'coordinator' | 'code' | 'review' | 'test' | 'ops' | 'research' | 'planner'; export type TrustLevel = 'untrusted' | 'provisional' | 'trusted' | 'formal'; export interface AgentCapability { readonly name: string; readonly description: string; readonly tools: readonly string[]; } export interface AgentIdentity { readonly id: string; readonly name: string; readonly specialization: AgentSpecialization; readonly capabilities: readonly AgentCapability[]; readonly trustLevel: TrustLevel; readonly model: string; readonly spawnedAt: string; readonly verificationHistory: { readonly totalHandoffs: number; readonly passRate: number; readonly formalOverrides: number; }; } export type MultiAgentMessageType = 'task_assignment' | 'task_result' | 'question' | 'answer' | 'approval_request' | 'approval_response' | 'finding' | 'context_share' | 'escalation' | 'status_update'; export type BoundaryVerificationStatus = 'unverified' | 'pending' | 'verified' | 'partially_verified' | 'failed' | 'formally_verified'; export interface AgentMessage { readonly id: string; readonly sender: string; readonly recipient: string | 'coordinator' | 'broadcast'; readonly type: MultiAgentMessageType; readonly payload: T; readonly verificationStatus: BoundaryVerificationStatus; readonly timestamp: string; readonly replyTo?: string; readonly threadId: string; readonly claims?: readonly BoundaryClaim[]; } export interface BoundaryClaim { readonly id: string; readonly text: string; readonly category: 'correctness' | 'security' | 'performance' | 'error-handling' | 'edge-case' | 'type-safety' | 'completeness' | 'test-quality'; readonly severity: 'critical' | 'high' | 'medium' | 'low'; readonly source: 'explicit' | 'implicit'; readonly verificationMethod: 'formal' | 'llm'; readonly verdict: 'PASS' | 'FAIL' | 'PARTIAL' | 'N/A' | 'UNVERIFIABLE'; readonly evidence: string; readonly formalOverride?: { readonly originalLlmVerdict: 'PASS' | 'FAIL' | 'PARTIAL' | 'N/A' | 'UNVERIFIABLE'; readonly formalVerdict: 'PASS' | 'FAIL'; readonly reason: string; }; } export interface CompositionBoundary { readonly id: string; readonly sourceAgent: string; readonly targetAgent: string; readonly artifact: BoundaryArtifact; readonly extractedClaims: readonly BoundaryClaim[]; readonly verificationResult: BoundaryVerificationResult; readonly timestamp: string; } export interface BoundaryArtifact { readonly type: 'code_patch' | 'test_file' | 'review_report' | 'deploy_result' | 'research_finding' | 'coverage_report' | 'health_check' | 'architecture_plan'; readonly path?: string; readonly content: string; readonly language?: string; readonly metadata: Record; } export interface BoundaryVerificationResult { readonly boundaryId: string; readonly passed: number; readonly failed: number; readonly partial: number; readonly total: number; readonly formalStats: { readonly formallyVerified: number; readonly llmVerified: number; readonly disagreements: number; readonly formalOverrides: number; }; readonly verdict: 'PASS' | 'FAIL' | 'PARTIAL'; readonly blockers: readonly BoundaryClaim[]; readonly durationMs: number; } export type HandoffDecision = { readonly action: 'pass'; } | { readonly action: 'pass_with_warnings'; readonly warnings: readonly BoundaryClaim[]; } | { readonly action: 'reject'; readonly blockers: readonly BoundaryClaim[]; } | { readonly action: 'escalate'; readonly reason: string; }; export interface VerifiedHandoff { readonly id: string; readonly boundary: CompositionBoundary; readonly artifact: BoundaryArtifact; readonly verificationResult: BoundaryVerificationResult; readonly decision: HandoffDecision; readonly timestamp: string; } export type MultiAgentTaskStatus = 'pending' | 'ready' | 'assigned' | 'in_progress' | 'in_review' | 'verified' | 'rejected' | 'completed' | 'blocked' | 'failed'; export interface TaskNode { readonly id: string; readonly goal: string; readonly assignedTo: string | null; readonly specialization: AgentSpecialization; readonly status: MultiAgentTaskStatus; readonly dependencies: readonly TaskEdge[]; readonly artifacts: readonly VerifiedHandoff[]; readonly attempts: number; readonly maxAttempts: number; readonly threadId: string; readonly createdAt: string; readonly completedAt?: string; } export interface TaskEdge { readonly from: string; readonly to: string; readonly type: 'blocks' | 'informs'; readonly reason: string; } export interface TaskGraph { readonly goalId: string; readonly originalGoal: string; readonly tasks: readonly TaskNode[]; readonly edges: readonly TaskEdge[]; readonly status: 'planning' | 'executing' | 'completed' | 'failed' | 'stalled'; readonly createdAt: string; readonly completedAt?: string; } export type ContextRefType = 'file' | 'snippet' | 'claim_set' | 'task_history' | 'search_result'; export interface ContextRef { readonly type: ContextRefType; readonly uri: string; readonly summary: string; readonly relevanceScore: number; readonly sizeTokens: number; } export interface StallReport { readonly taskId: string; readonly type: 'timeout' | 'reject_loop' | 'dependency_deadlock' | 'resource_contention'; readonly duration: number; readonly attempts: number; readonly suggestedAction: 'reassign' | 'simplify' | 'escalate' | 'abort'; } export interface SafetyPolicy { readonly formalOverridesConsensus: true; readonly noSelfVerification: true; readonly criticalClaimsRequireFormal: true; readonly escalationRules: { readonly maxFormalOverridesBeforeHalt: number; readonly maxTrustDemotions: number; readonly maxRejectCyclesPerTask: number; }; readonly preferModelDiversity: boolean; } export interface MultiAgentConfig { teamSize: number; agents: AgentRoleConfig[]; safetyPolicy: SafetyPolicy; coordinatorModel: string; maxConcurrentTasks: number; stallTimeoutMs: number; trustPromotionThreshold: number; trustDemotionOnOverride: boolean; } export interface AgentRoleConfig { specialization: AgentSpecialization; model: string; capabilities: AgentCapability[]; initialTrustLevel: TrustLevel; } export interface TaskDecomposition { readonly originalGoal: string; readonly subtasks: readonly Subtask[]; readonly dependencies: readonly TaskEdge[]; readonly gapAnalysis: { readonly coveredRequirements: readonly string[]; readonly uncoveredRequirements: readonly string[]; readonly redundantTasks: readonly string[]; }; } export interface Subtask { readonly id: string; readonly goal: string; readonly assignedTo: AgentSpecialization; readonly estimatedComplexity: 'trivial' | 'small' | 'medium' | 'large'; readonly requiredCapabilities: readonly string[]; readonly contextRefs: readonly ContextRef[]; } export interface TestQualityClaim { readonly testFile: string; readonly testName: string; readonly claimedBehavior: string; readonly actualAssertions: readonly string[]; readonly mockUsage: { readonly totalMocks: number; readonly realInteractions: number; }; readonly verdict: 'meaningful' | 'trivial' | 'deceptive'; } export type MemoryEntryType = 'fact' | 'decision' | 'convention' | 'finding' | 'requirement' | 'assumption'; export interface MemoryEntry { readonly id: string; readonly type: MemoryEntryType; readonly content: string; readonly author: string; readonly tags: readonly string[]; readonly verificationStatus: BoundaryVerificationStatus; readonly claims: readonly BoundaryClaim[]; readonly confidence: number; readonly createdAt: string; readonly supersedes?: string; } export interface MemoryFilter { readonly type?: MemoryEntryType; readonly tags?: readonly string[]; readonly minConfidence?: number; readonly verificationStatus?: BoundaryVerificationStatus; readonly author?: string; readonly since?: string; } export interface MemoryConflict { readonly id: string; readonly entries: readonly [MemoryEntry, MemoryEntry]; readonly detectedBy: 'assay' | 'agent' | 'coordinator'; readonly resolution?: ConflictResolution; readonly status: 'open' | 'resolved' | 'escalated'; } export type ConflictResolution = { readonly strategy: 'evidence_wins'; readonly winner: string; readonly reason: string; readonly evidence: string; } | { readonly strategy: 'formal_wins'; readonly winner: string; readonly formalVerdict: string; } | { readonly strategy: 'human_decided'; readonly winner: string; readonly humanNote: string; } | { readonly strategy: 'both_wrong'; readonly supersededBy: string; }; export interface TeamConfig { readonly goal: string; readonly agents: readonly AgentSpecialization[]; readonly safetyPolicy: SafetyPolicy; readonly maxConcurrentTasks: number; readonly stallTimeoutMs: number; readonly maxTotalAttempts: number; readonly models?: Partial>; readonly verificationTier?: VerificationTier; readonly useFastVerification?: boolean; } export interface TeamResult { readonly goalId: string; readonly status: 'completed' | 'failed' | 'stalled' | 'escalated'; readonly taskGraph: TaskGraph; readonly artifacts: readonly VerifiedHandoff[]; readonly sharedMemorySnapshot: readonly MemoryEntry[]; readonly auditTrail: readonly AuditEntry[]; readonly totalDurationMs: number; readonly stalls: readonly StallReport[]; } export interface TrustWindow { readonly agentId: string; readonly windowSize: number; readonly results: readonly TrustWindowEntry[]; readonly passRate: number; readonly formalOverrideCount: number; } export interface TrustWindowEntry { readonly boundaryId: string; readonly verdict: 'PASS' | 'FAIL' | 'PARTIAL'; readonly hadFormalOverride: boolean; readonly timestamp: string; } export interface TrustTransition { readonly agentId: string; readonly agentName: string; readonly previousLevel: TrustLevel; readonly newLevel: TrustLevel; readonly reason: 'promotion' | 'demotion_formal_override' | 'demotion_low_pass_rate' | 'demotion_collusion'; readonly passRate: number; readonly windowSize: number; readonly timestamp: string; } export interface CollusionEvent { readonly id: string; readonly agentA: string; readonly agentB: string; readonly agreedVerdict: 'PASS' | 'FAIL' | 'PARTIAL' | 'N/A' | 'UNVERIFIABLE'; readonly formalVerdict: 'PASS' | 'FAIL'; readonly claimId: string; readonly claimText: string; readonly severity: 'critical' | 'high' | 'medium' | 'low'; readonly timestamp: string; } export interface HumanEscalation { readonly id: string; readonly trigger: HumanEscalationTrigger; readonly context: { readonly taskGraph: TaskGraph; readonly relevantMessages: readonly AgentMessage[]; readonly conflictingClaims: readonly MemoryConflict[]; readonly recentAudit: readonly AuditEntry[]; readonly trustSnapshots: readonly TrustWindow[]; readonly collusionEvents: readonly CollusionEvent[]; }; readonly suggestedActions: readonly string[]; readonly status: 'pending' | 'resolved'; readonly humanResponse?: { readonly action: string; readonly reasoning: string; readonly timestamp: string; }; } export type HumanEscalationTrigger = { readonly type: 'safety_threshold'; readonly rule: string; readonly value: number; readonly max: number; } | { readonly type: 'collusion_detected'; readonly event: CollusionEvent; } | { readonly type: 'stall_unresolvable'; readonly stalls: readonly StallReport[]; } | { readonly type: 'trust_collapse'; readonly agentId: string; readonly demotions: number; } | { readonly type: 'agent_stuck'; readonly taskId: string; readonly attempts: number; }; export interface ModelDiversityConfig { readonly enabled: boolean; readonly providerMap: Partial>; readonly fallbackModel: string; } export interface SafetyCircuitBreaker { readonly id: string; readonly rule: string; readonly currentValue: number; readonly threshold: number; readonly tripped: boolean; readonly trippedAt?: string; readonly action: 'halt' | 'escalate' | 'demote'; } export type PricingTier = 'team' | 'pro' | 'platform'; export interface PricingTierConfig { readonly tier: PricingTier; readonly name: string; readonly maxAgents: number; readonly maxVerificationsPerMonth: number; readonly hasFormalVerifier: boolean; readonly hasHumanEscalation: boolean; readonly overageCostCents: number; readonly allowedAgentTypes: readonly AgentSpecialization[]; } export interface ApiKeyInfo { readonly key: string; readonly tier: PricingTier; readonly organizationId: string; readonly createdAt: string; readonly verificationsThisMonth: number; readonly monthlyLimit: number; } export interface TeamSession { readonly id: string; readonly apiKey: string; readonly goal: string; readonly status: 'running' | 'completed' | 'failed' | 'halted'; readonly agents: readonly AgentSpecialization[]; readonly createdAt: string; readonly completedAt?: string; readonly result?: TeamResult; } export interface TeamCreateRequest { readonly goal: string; readonly agents?: readonly AgentSpecialization[]; readonly models?: Partial>; readonly maxConcurrentTasks?: number; readonly stallTimeoutMs?: number; readonly codebaseContext?: string; } export interface TeamCreateResponse { readonly sessionId: string; readonly streamUrl: string; readonly statusUrl: string; readonly agents: readonly AgentSpecialization[]; readonly createdAt: string; } export interface TeamStatusResponse { readonly sessionId: string; readonly status: TeamSession['status']; readonly taskGraph: TaskGraph | null; readonly agents: readonly { readonly name: string; readonly specialization: AgentSpecialization; readonly trustLevel: TrustLevel; readonly passRate: number; }[]; readonly verificationCount: number; readonly auditEntryCount: number; readonly durationMs: number; readonly stalls: readonly StallReport[]; } export interface TeamAuditResponse { readonly sessionId: string; readonly entries: readonly AuditEntry[]; readonly total: number; readonly offset: number; readonly limit: number; } export interface SSEEvent { readonly event: 'audit' | 'task_update' | 'verification' | 'trust_change' | 'escalation' | 'complete' | 'error'; readonly data: Record; readonly id?: string; readonly timestamp: string; } export type ToolType = 'mcp_server' | 'cli_wrapper' | 'api_client' | 'data_transform' | 'verification_helper'; export interface ToolDefinition { readonly id: string; readonly name: string; readonly type: ToolType; readonly version: string; readonly description: string; readonly interface: ToolInterface; readonly constraints: ToolConstraints; readonly source: ToolSource; readonly created_by: string; readonly created_at: string; readonly status: ToolStatus; } export type ToolStatus = 'proposed' | 'verified' | 'approved' | 'active' | 'deprecated' | 'revoked'; export interface ToolInterface { readonly inputs: readonly ToolParameter[]; readonly outputs: readonly ToolParameter[]; readonly errors: readonly ToolError[]; readonly idempotent: boolean; readonly side_effects: readonly string[]; } export interface ToolParameter { readonly name: string; readonly type: string; readonly required: boolean; readonly description: string; readonly constraints?: readonly string[]; } export interface ToolError { readonly code: string; readonly description: string; readonly recoverable: boolean; } export interface ToolConstraints { readonly timeout_ms: number; readonly max_memory_mb: number; readonly network_access: NetworkAccess; readonly filesystem_access: FilesystemAccess; readonly max_invocations_per_minute: number; } export interface NetworkAccess { readonly allowed: boolean; readonly allowlisted_domains: readonly string[]; } export interface FilesystemAccess { readonly read_paths: readonly string[]; readonly write_paths: readonly string[]; } export interface ToolSource { readonly language: string; readonly entry_point: string; readonly source_hash: string; readonly dependencies: readonly ToolDependency[]; } export interface ToolDependency { readonly name: string; readonly version: string; readonly source: 'npm' | 'pypi' | 'system' | 'vendored'; readonly hash: string; } export type ToolRiskLevel = 'none' | 'low' | 'medium' | 'high' | 'critical'; export interface ToolVerification { readonly tool_id: string; readonly verification_id: string; readonly timestamp: string; readonly code_verification: { readonly claims_extracted: number; readonly claims_passed: number; readonly claims_failed: number; readonly critical_failures: readonly ToolVerificationFailure[]; }; readonly security: { readonly ssrf_risk: ToolRiskLevel; readonly injection_risk: ToolRiskLevel; readonly privilege_escalation_risk: ToolRiskLevel; readonly data_exfiltration_risk: ToolRiskLevel; readonly findings: readonly SecurityFinding[]; }; readonly sandbox_tests: { readonly happy_path: ToolTestResult; readonly malformed_input: ToolTestResult; readonly timeout_behavior: ToolTestResult; readonly constraint_compliance: ToolTestResult; }; readonly verdict: 'approve' | 'reject' | 'needs_review'; readonly confidence: number; readonly reasoning: string; readonly blockers: readonly string[]; } export interface ToolVerificationFailure { readonly claim: string; readonly verdict: 'FAIL'; readonly severity: 'critical' | 'high' | 'medium' | 'low'; readonly evidence: string; } export interface SecurityFinding { readonly type: string; readonly severity: ToolRiskLevel; readonly location: string; readonly description: string; readonly recommendation: string; } export interface ToolTestResult { readonly status: 'pass' | 'fail' | 'error' | 'timeout'; readonly input_summary: string; readonly output_summary: string; readonly duration_ms: number; readonly error?: string; } export type ModificationType = 'tool' | 'agent' | 'rule' | 'prompt' | 'memory'; export interface ModificationProposal { readonly id: string; readonly type: ModificationType; readonly timestamp: string; readonly title: string; readonly description: string; readonly payload: unknown; readonly justification: { readonly capability_gap: string; readonly evidence: readonly string[]; readonly expected_impact: string; readonly risk_assessment: string; }; readonly safety: { readonly modifies_layer2: false; readonly modifies_approval_framework: false; readonly trust_level_required: TrustLevel; readonly rollback_plan: string; }; readonly proposed_by: string; readonly status: ProposalStatus; readonly verification_id?: string; } export type ProposalStatus = 'proposed' | 'verifying' | 'verified' | 'pending_approval' | 'approved' | 'deployed' | 'rejected' | 'rolled_back'; export interface ModificationApproval { readonly proposal_id: string; readonly decision: 'approved' | 'rejected' | 'deferred'; readonly decided_by: string; readonly decided_at: string; readonly reasoning: string; readonly conditions?: readonly string[]; readonly rollback_trigger?: string; } export interface CapabilityRegistry { readonly version: string; readonly last_modified: string; readonly modified_by: string; readonly tools: { readonly active: readonly ToolDefinition[]; readonly deprecated: readonly ToolDefinition[]; }; readonly manifest_hash: string; readonly layer2_hash: string; readonly modifications: readonly ModificationLogEntry[]; } export interface ModificationLogEntry { readonly timestamp: string; readonly proposal_id: string; readonly type: ModificationType; readonly action: 'added' | 'modified' | 'deprecated' | 'revoked' | 'rolled_back'; readonly target_id: string; readonly approved_by: string; readonly registry_version_before: string; readonly registry_version_after: string; } export type Phase4AuditEventType = AuditEventType | 'tool_proposed' | 'tool_verified' | 'tool_approved' | 'tool_rejected' | 'tool_activated' | 'tool_deprecated' | 'tool_rollback' | 'sandbox_execution' | 'registry_updated'; export type SpawnedAgentTrustLevel = 'sandboxed' | 'standard' | 'elevated' | 'coordinator'; export interface AgentDefinition { readonly id: string; readonly name: string; readonly version: string; readonly domain: AgentDomain; readonly system_prompt: string; readonly tools: readonly string[]; readonly trust_level: SpawnedAgentTrustLevel; readonly verification_rules: readonly string[]; readonly constraints: SpawnedAgentConstraints; readonly created_by: string; readonly created_at: string; readonly approved_by: string; readonly approved_at: string; readonly status: AgentDefinitionStatus; } export type AgentDefinitionStatus = 'proposed' | 'verified' | 'approved' | 'active' | 'suspended' | 'retired'; export interface AgentDomain { readonly description: string; readonly languages: readonly string[]; readonly frameworks: readonly string[]; readonly claim_categories: readonly string[]; } export interface SpawnedAgentConstraints { readonly max_concurrent_tasks: number; readonly max_tokens_per_task: number; readonly max_tools_per_task: number; readonly can_spawn_agents: boolean; readonly max_spawned_trust: SpawnedAgentTrustLevel; readonly requires_approval_for: readonly string[]; } export interface AgentVerification { readonly agent_id: string; readonly verification_id: string; readonly timestamp: string; readonly domain_coverage: { readonly claimed_scope: string; readonly verified_scope: string; readonly gaps: readonly string[]; readonly overreach: readonly string[]; }; readonly prompt_safety: { readonly contains_verification_bypass: boolean; readonly contains_privilege_escalation: boolean; readonly contains_self_reference: boolean; readonly findings: readonly PromptSafetyFinding[]; }; readonly tool_access: { readonly justified: readonly string[]; readonly questionable: readonly string[]; readonly missing: readonly string[]; }; readonly trust_inheritance: { readonly parent_trust: SpawnedAgentTrustLevel | 'human'; readonly requested_trust: SpawnedAgentTrustLevel; readonly valid: boolean; readonly reason: string; }; readonly verdict: 'approve' | 'reject' | 'needs_review'; readonly blockers: readonly string[]; } export interface PromptSafetyFinding { readonly type: PromptSafetyFindingType; readonly severity: 'critical' | 'high' | 'medium' | 'low'; readonly location: string; readonly description: string; } export type PromptSafetyFindingType = 'verification_bypass' | 'privilege_escalation' | 'self_reference' | 'unbounded_action' | 'missing_constraint'; export type Phase4M2AuditEventType = Phase4AuditEventType | 'agent_proposed' | 'agent_verified' | 'agent_approved' | 'agent_rejected' | 'agent_spawned' | 'agent_suspended' | 'agent_retired'; export type RuleSubstrate = 'formal_pattern' | 'formal_ast' | 'formal_type' | 'formal_taint' | 'llm_semantic' | 'llm_behavioral' | 'composite'; export interface VerificationRule { readonly id: string; readonly name: string; readonly version: string; readonly substrate: RuleSubstrate; readonly confidence: number; readonly target: { readonly claim_categories: readonly string[]; readonly languages: readonly string[]; readonly frameworks: readonly string[]; }; readonly check: FormalCheck | LLMCheck | CompositeCheck; readonly test_cases: readonly RuleTestCase[]; readonly created_by: string; readonly created_at: string; readonly approved_by: string; readonly approved_at: string; readonly status: RuleStatus; } export type RuleStatus = 'proposed' | 'meta_verified' | 'approved' | 'shadow' | 'canary' | 'active' | 'deprecated'; export interface FormalCheck { readonly type: 'formal'; readonly patterns: readonly FormalPattern[]; readonly logic: 'all_match' | 'any_match' | 'none_match' | 'custom'; readonly custom_logic?: string; } export interface FormalPattern { readonly description: string; readonly pattern: string; readonly pattern_type: 'regex' | 'tree_sitter' | 'semgrep'; readonly target: 'source' | 'ast' | 'dataflow'; } export interface LLMCheck { readonly type: 'llm'; readonly prompt_template: string; readonly expected_output_format: string; readonly temperature: number; readonly max_tokens: number; } export interface CompositeCheck { readonly type: 'composite'; readonly formal_component: FormalCheck; readonly llm_component: LLMCheck; readonly merge_strategy: 'formal_gate' | 'formal_override' | 'weighted'; } export interface RuleTestCase { readonly id: string; readonly description: string; readonly input_code: string; readonly input_language: string; readonly expected_verdict: 'PASS' | 'FAIL'; readonly expected_evidence_contains?: string; } export interface RuleMetaVerification { readonly rule_id: string; readonly verification_id: string; readonly timestamp: string; readonly test_results: readonly RuleTestResult[]; readonly consistency: { readonly runs: number; readonly consistent: boolean; readonly variance: number; }; readonly conflict_check: { readonly conflicting_rules: readonly string[]; readonly resolution: string; }; readonly verdict: 'approve' | 'reject' | 'needs_review'; readonly blockers: readonly string[]; } export interface RuleTestResult { readonly case_id: string; readonly actual_verdict: 'PASS' | 'FAIL'; readonly expected_verdict: 'PASS' | 'FAIL'; readonly match: boolean; readonly evidence: string; } export type CanaryStage = 'shadow' | 'canary_5' | 'canary_25' | 'full_rollout'; export interface CanaryDeployment { readonly rule_id: string; readonly stage: CanaryStage; readonly started_at: string; readonly promoted_at?: string; readonly stage_duration_hours: number; readonly metrics: CanaryMetrics; readonly exit_criteria: CanaryExitCriteria; } export interface CanaryMetrics { readonly total_evaluations: number; readonly agreements_with_baseline: number; readonly disagreements: number; readonly error_rate: number; readonly false_positive_rate: number; readonly false_negative_rate: number; readonly avg_latency_ms: number; } export interface CanaryExitCriteria { readonly min_evaluations: number; readonly max_error_rate: number; readonly max_disagreement_rate: number; readonly min_duration_hours: number; } export type Phase4M3AuditEventType = Phase4M2AuditEventType | 'rule_proposed' | 'rule_meta_verified' | 'rule_approved' | 'rule_rejected' | 'rule_shadow_started' | 'rule_canary_started' | 'rule_promoted' | 'rule_deprecated' | 'rule_conflict_detected' | 'rule_rollback'; export type Layer2Component = 'formal_verifier' | 'verification_protocol' | 'approval_framework' | 'immutability_constraint' | 'kill_switch'; export interface Layer2Manifest { readonly version: string; readonly deployed_at: string; readonly deployed_by: string; readonly components: readonly Layer2ComponentEntry[]; readonly manifest_hash: string; readonly signing_key_id: string; } export interface Layer2ComponentEntry { readonly component: Layer2Component; readonly file_path: string; readonly hash: string; readonly size_bytes: number; readonly last_verified: string; } export interface IntegrityCheckResult { readonly timestamp: string; readonly manifest_version: string; readonly components_checked: number; readonly components_valid: number; readonly components_invalid: readonly IntegrityViolation[]; readonly overall: 'valid' | 'violation'; } export interface IntegrityViolation { readonly component: Layer2Component; readonly file_path: string; readonly expected_hash: string; readonly actual_hash: string; readonly severity: 'critical'; readonly action: 'halt'; } export type KillSwitchLevel = 'layer2' | 'human' | 'coordinator' | 'agent'; export type KillSwitchAction = 'halt_system' | 'suspend_agent' | 'suspend_tool' | 'suspend_rule' | 'reassign_task' | 'halt_task'; export interface KillSwitchEvent { readonly id: string; readonly level: KillSwitchLevel; readonly action: KillSwitchAction; readonly target: string; readonly triggered_by: string; readonly reason: string; readonly timestamp: string; readonly auto_restart: boolean; readonly requires_redeployment: boolean; } export type RollbackTrigger = 'automatic' | 'human' | 'layer2' | 'coordinator'; export interface RollbackEvent { readonly id: string; readonly trigger: RollbackTrigger; readonly triggered_by: string; readonly target_type: 'tool' | 'agent' | 'rule' | 'registry'; readonly target_id: string; readonly from_version: string; readonly to_version: string; readonly timestamp: string; readonly verification_after_rollback: 'pass' | 'fail' | 'pending'; readonly reason: string; } export type Phase4M4AuditEventType = Phase4M3AuditEventType | 'integrity_check_passed' | 'integrity_violation' | 'kill_switch_activated' | 'kill_switch_released' | 'rollback_triggered' | 'rollback_completed' | 'layer2_startup_verified' | 'layer2_deployment' | 'modification_proposal_blocked'; export type VerificationTier = 'full' | 'lightweight' | 'skip'; export interface AppDescription { readonly name: string; readonly description: string; readonly techStack: TechStackConfig; readonly features: readonly string[]; readonly constraints?: readonly string[]; readonly authModel?: AuthModelConfig; } export interface TechStackConfig { readonly language: 'typescript' | 'python'; readonly framework: 'next.js' | 'express' | 'sveltekit' | 'electron'; readonly database: 'supabase' | 'postgresql' | 'sqlite'; readonly styling?: string; readonly deployment?: string; } export interface AuthModelConfig { readonly provider: 'supabase' | 'nextauth' | 'custom'; readonly methods: readonly string[]; readonly roles?: readonly string[]; } export interface ArchitecturePlan { readonly schema: readonly SchemaEntity[]; readonly apiRoutes: readonly ApiRouteSpec[]; readonly pages: readonly PageSpec[]; readonly features: readonly FeaturePlan[]; readonly ipcChannels?: readonly IpcChannel[]; readonly dependencyOrder: readonly string[]; readonly authPlan?: { readonly provider: string; readonly methods: readonly string[]; readonly roles: readonly string[]; readonly protectedRoutes: readonly string[]; }; readonly deployConfig?: { readonly platform: string; readonly buildCommand: string; readonly envVars: readonly string[]; }; } export interface SchemaEntity { readonly name: string; readonly fields: readonly SchemaField[]; readonly relations: readonly SchemaRelation[]; } export interface SchemaField { readonly name: string; readonly type: string; readonly nullable: boolean; readonly primaryKey?: boolean; readonly unique?: boolean; readonly defaultValue?: string; } export interface SchemaRelation { readonly target: string; readonly type: 'one-to-one' | 'one-to-many' | 'many-to-many'; readonly foreignKey: string; } export interface ApiRouteSpec { readonly method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; readonly path: string; readonly description: string; readonly auth: boolean; readonly requestType?: string; readonly responseType?: string; readonly featureId?: string; } export interface IpcChannel { readonly channel: string; readonly direction: 'renderer-to-main' | 'main-to-renderer' | 'bidirectional'; readonly description: string; readonly requestType?: string; readonly responseType?: string; readonly featureId?: string; } export interface PageSpec { readonly path: string; readonly component: string; readonly auth: boolean; readonly featureId?: string; readonly description?: string; } export interface FeaturePlan { readonly id: string; readonly name: string; readonly dependsOn: readonly string[]; readonly schemaEntities: readonly string[]; readonly apiRoutes: readonly string[]; readonly pages: readonly string[]; readonly ipcChannels?: readonly string[]; readonly complexityEstimate: 'trivial' | 'small' | 'medium' | 'large'; } export type AppCreatePhase = { readonly phase: 'initializing'; } | { readonly phase: 'planning'; } | { readonly phase: 'verifying_plan'; } | { readonly phase: 'requirements_refining'; } | { readonly phase: 'plan_questioning'; readonly questions: PlanQuestion[]; readonly round: number; readonly confidence: number; } | { readonly phase: 'plan_refining'; readonly round: number; } | { readonly phase: 'plan_readiness'; readonly confidence: number; readonly gaps: readonly string[]; readonly summary: string; readonly ready: boolean; } | { readonly phase: 'chat_message'; readonly message: string; readonly cards?: readonly PlanQuestion[]; readonly readiness: ReadinessEvaluation; } | { readonly phase: 'awaiting_approval'; readonly planSummary: PlanSummary; } | { readonly phase: 'scaffolding'; } | { readonly phase: 'building_feature'; readonly featureId: string; readonly featureIndex: number; readonly totalFeatures: number; } | { readonly phase: 'building_wave'; readonly waveIndex: number; readonly totalWaves: number; readonly featureIds: readonly string[]; } | { readonly phase: 'build_verifying'; readonly attempt: number; readonly maxAttempts: number; } | { readonly phase: 'build_repairing'; readonly attempt: number; readonly maxAttempts: number; readonly errorCount: number; } | { readonly phase: 'integration_verifying'; } | { readonly phase: 'functional_testing'; readonly attempt: number; readonly maxAttempts: number; } | { readonly phase: 'functional_repairing'; readonly attempt: number; readonly maxAttempts: number; readonly failureCount: number; } | { readonly phase: 'provisioning_supabase'; } | { readonly phase: 'supabase_migrations'; } | { readonly phase: 'cross_verifying'; } | { readonly phase: 'finalizing'; } | { readonly phase: 'completed'; } | { readonly phase: 'failed'; readonly reason: string; }; export interface AppCreateProgress { readonly phase: AppCreatePhase; readonly currentFeatureIndex: number; readonly totalFeatures: number; readonly completedFeatures: readonly string[]; readonly failedFeatures: readonly string[]; readonly elapsedMs: number; } export interface AppCreateResult { readonly status: 'completed' | 'failed' | 'partial'; readonly projectPath: string; readonly plan: ArchitecturePlan | null; readonly featureResults: readonly FeatureBuildResult[]; readonly buildVerification: BuildVerificationResult | null; readonly integrationVerification: IntegrationVerificationResult | null; readonly crossVerification: CrossFeatureVerification | null; readonly functionalTestResult: FunctionalTestResult | null; readonly totalDurationMs: number; readonly auditTrail: readonly AuditEntry[]; } export interface FeatureBuildResult { readonly featureId: string; readonly featureName: string; readonly status: 'completed' | 'failed' | 'skipped'; readonly filesCreated: readonly string[]; readonly verificationSummary: { readonly totalClaims: number; readonly passed: number; readonly failed: number; }; readonly durationMs: number; readonly error?: string; } export interface CrossFeatureVerification { readonly checks: readonly CrossFeatureCheck[]; readonly passedCount: number; readonly failedCount: number; readonly verdict: 'PASS' | 'FAIL' | 'PARTIAL'; } export interface CrossFeatureCheck { readonly type: 'api_route_exists' | 'page_references_valid' | 'schema_entity_exists' | 'dependency_consistency' | 'ipc_channel_exists' | 'link_integrity' | 'import_path_valid' | 'package_deps_complete' | 'no_self_fetch' | 'typescript_compiles' | 'env_vars_complete' | 'asset_refs_valid'; readonly description: string; readonly verdict: 'PASS' | 'FAIL'; readonly evidence: string; } export type IntegrationCheckType = 'routing_provider' | 'ipc_handler_coverage' | 'stub_function' | 'unreachable_page' | 'response_shape'; export interface IntegrationCheck { readonly type: IntegrationCheckType; readonly verdict: 'PASS' | 'FAIL'; readonly evidence: string; readonly file: string; readonly severity: 'critical' | 'high' | 'medium'; } export interface IntegrationVerificationResult { readonly checks: readonly IntegrationCheck[]; readonly passedCount: number; readonly failedCount: number; readonly verdict: 'PASS' | 'FAIL'; readonly framework: string; readonly totalDurationMs: number; } export type BuildStepStatus = 'pass' | 'fail' | 'skip' | 'timeout'; export interface BuildStepResult { readonly step: 'install' | 'build' | 'start' | 'health_check'; readonly status: BuildStepStatus; readonly command: string; readonly stdout: string; readonly stderr: string; readonly durationMs: number; readonly exitCode: number | null; } export type BuildErrorCategory = 'type_error' | 'module_not_found' | 'syntax_error' | 'runtime_error' | 'dependency_error' | 'other'; export interface BuildError { readonly file: string; readonly line: number | null; readonly message: string; readonly category: BuildErrorCategory; } export interface BuildRepairAttempt { readonly attempt: number; readonly errors: readonly BuildError[]; readonly filesModified: readonly string[]; readonly repairSucceeded: boolean; readonly durationMs: number; } export interface BuildVerificationResult { readonly status: 'pass' | 'fail' | 'repaired' | 'skipped'; readonly install: BuildStepResult | null; readonly build: BuildStepResult | null; readonly start: BuildStepResult | null; readonly healthCheck: BuildStepResult | null; readonly repairAttempts: readonly BuildRepairAttempt[]; readonly finalErrors: readonly BuildError[]; readonly totalDurationMs: number; } export interface AppCreateOptions { readonly outputPath: string; readonly models?: Partial>; readonly maxConcurrentTasks?: number; readonly stallTimeoutMs?: number; readonly maxRetries?: number; readonly sequential?: boolean; readonly noDirectMode?: boolean; readonly fullVerification?: boolean; readonly maxBuildRepairAttempts?: number; readonly skipBuildVerification?: boolean; readonly autoApprove?: boolean; readonly skipFunctionalTesting?: boolean; readonly skipPlanQuestions?: boolean; readonly supabaseOrgId?: string; readonly supabaseRegion?: string; readonly documents?: ReadonlyArray<{ readonly name: string; readonly content: string; }>; } export interface SupabaseProvisionResult { readonly status: 'success' | 'failed'; readonly projectRef?: string; readonly url?: string; readonly anonKey?: string; readonly serviceRoleKey?: string; readonly dbPassword?: string; readonly error?: string; readonly durationMs: number; } export interface PlanQuestionOption { label: string; description: string; } export interface PlanQuestion { id: string; question: string; header: string; options: PlanQuestionOption[]; multiSelect: boolean; } export interface PlanAnswer { questionId: string; selectedOptions: string[]; customText?: string; } export interface PlanRefinementRound { round: number; questions: PlanQuestion[]; answers: PlanAnswer[]; confidence: number; } export interface ReadinessEvaluation { readonly confidence: number; readonly ready: boolean; readonly gaps: readonly string[]; readonly summary: string; } export interface ChatMessage { readonly role: 'user' | 'architect'; readonly content: string; readonly cards?: readonly PlanQuestion[]; readonly cardAnswers?: readonly PlanAnswer[]; } export interface ChatResponse { readonly message: string; readonly cards?: readonly PlanQuestion[]; readonly readiness: ReadinessEvaluation; } export interface PlanModeState { rounds: PlanRefinementRound[]; currentConfidence: number; maxRounds: number; status: 'asking' | 'refining' | 'confident' | 'approved'; } export interface PlanSummary { readonly appName: string; readonly description: string; readonly techStack: string; readonly featureCount: number; readonly features: readonly PlanSummaryFeature[]; readonly schemaEntities: number; readonly apiRouteCount: number; readonly pageCount: number; readonly estimatedComplexity: 'small' | 'medium' | 'large'; readonly warnings: readonly string[]; } export interface PlanSummaryFeature { readonly id: string; readonly name: string; readonly complexity: string; readonly dependsOn: readonly string[]; readonly routeCount: number; readonly pageCount: number; } export type PlanApprovalResult = { readonly decision: 'approved'; } | { readonly decision: 'approved_with_modifications'; readonly modifications: readonly PlanModification[]; } | { readonly decision: 'rejected'; readonly reason: string; }; export interface PlanModification { readonly type: 'remove_feature' | 'add_feature' | 'modify_feature'; readonly featureId: string; readonly details?: string; } export interface FunctionalTest { readonly id: string; readonly type: 'api_route' | 'page_load' | 'auth_flow' | 'data_persistence'; readonly name: string; readonly method?: string; readonly path: string; readonly body?: unknown; readonly expectedStatusRange: [number, number]; readonly errorPatterns: readonly string[]; readonly featureId?: string; readonly verifyPath?: string; readonly idField?: string; } export interface FunctionalTestExecution { readonly test: FunctionalTest; readonly status: 'pass' | 'fail' | 'error' | 'timeout'; readonly statusCode: number | null; readonly responseBody: string; readonly errorMatch?: string; readonly durationMs: number; } export interface FunctionalTestRepairAttempt { readonly attempt: number; readonly failures: readonly FunctionalTestExecution[]; readonly filesModified: readonly string[]; readonly repairSucceeded: boolean; readonly durationMs: number; } export interface FunctionalTestResult { readonly status: 'pass' | 'fail' | 'repaired' | 'skipped'; readonly tests: readonly FunctionalTestExecution[]; readonly passedCount: number; readonly failedCount: number; readonly repairAttempts: readonly FunctionalTestRepairAttempt[]; readonly serverPort: number | null; readonly totalDurationMs: number; } export type CheckStrategyType = 'pattern_presence' | 'pattern_absence' | 'cross_reference' | 'import_reachability' | 'response_shape' | 'conditional_presence' | 'file_reference' | 'ordering'; export interface PatternPresenceStrategy { readonly type: 'pattern_presence'; readonly fileGlob: string; readonly pattern: string; readonly requireIn: 'any' | 'all'; readonly contextGlob?: string; readonly contextPattern?: string; } export interface PatternAbsenceStrategy { readonly type: 'pattern_absence'; readonly fileGlob: string; readonly pattern: string; readonly allowIn?: readonly string[]; } export interface CrossReferenceStrategy { readonly type: 'cross_reference'; readonly sourceGlob: string; readonly sourcePattern: string; readonly targetGlob: string; readonly targetPattern: string; } export interface ImportReachabilityStrategy { readonly type: 'import_reachability'; readonly pageGlob: string; readonly entryPattern: string; } export interface ResponseShapeStrategy { readonly type: 'response_shape'; readonly preloadGlob: string; readonly handlerGlob: string; readonly invokePattern: string; readonly handlePattern: string; readonly wrappedReturnPattern: string; readonly unwrapAccessPattern: string; } /** If a file matches conditionPattern, it must also contain requiredPattern. */ export interface ConditionalPresenceStrategy { readonly type: 'conditional_presence'; readonly fileGlob: string; readonly conditionPattern: string; readonly requiredPattern: string; /** When 'project', requiredPattern is checked across ALL matching files, not per-file. * This handles cases like shared Suspense boundaries wrapping multiple lazy imports. * Default: 'file'. */ readonly requiredScope?: 'file' | 'project'; } /** A file-path reference extracted from code must point to an existing file. */ export interface FileReferenceStrategy { readonly type: 'file_reference'; readonly fileGlob: string; readonly referencePattern: string; readonly baseDir?: string; } /** Pattern A must appear before pattern B in the same file. */ export interface OrderingStrategy { readonly type: 'ordering'; readonly fileGlob: string; readonly beforePattern: string; readonly afterPattern: string; } export type CheckStrategy = PatternPresenceStrategy | PatternAbsenceStrategy | CrossReferenceStrategy | ImportReachabilityStrategy | ResponseShapeStrategy | ConditionalPresenceStrategy | FileReferenceStrategy | OrderingStrategy; export interface IntegrationCheckDefinition { readonly id: string; readonly name: string; readonly type: string; readonly strategy: CheckStrategy; readonly severity: 'critical' | 'high' | 'medium'; readonly frameworks: readonly string[]; readonly status: 'proposed' | 'shadow' | 'active' | 'deprecated'; readonly createdAt: string; readonly evidenceTemplate: string; } export interface CheckLoopResult { readonly proposedChecks: readonly IntegrationCheckDefinition[]; readonly duplicatesSkipped: number; readonly classificationErrors: number; } export type AllowedBinary = 'supabase' | 'npm' | 'npx' | 'node' | 'git' | 'tsc' | 'claude' | 'gh'; export interface SafeExecResult { readonly stdout: string; readonly stderr: string; readonly exitCode: number | null; readonly timedOut: boolean; readonly durationMs: number; } export interface SafeExecOptions { readonly cwd?: string; readonly timeout?: number; readonly maxBuffer?: number; readonly env?: Record; } export interface SafeSpawnOptions { readonly cwd?: string; readonly env?: Record; readonly stdio?: readonly ('pipe' | 'ignore' | 'inherit')[]; } export interface ValidationResult { readonly valid: boolean; readonly errors: readonly ValidationError[]; readonly sanitized: AppDescription | null; } export interface ValidationError { readonly field: string; readonly message: string; readonly value?: unknown; } export type InjectionCategory = 'role_override' | 'system_impersonation' | 'instruction_override' | 'encoding_evasion' | 'delimiter_escape'; export interface InjectionFinding { readonly category: InjectionCategory; readonly pattern: string; readonly match: string; readonly severity: 'high' | 'medium' | 'low'; readonly weight: number; } export interface PromptGuardResult { readonly clean: boolean; readonly score: number; readonly findings: readonly InjectionFinding[]; readonly action: 'allow' | 'warn' | 'block'; } export type TaskCategory = 'scaffolding' | 'code_generation' | 'verification' | 'planning' | 'repair' | 'testing'; export type ModelTier = 'fast' | 'standard' | 'advanced'; export type LLMProviderType = 'api' | 'cli' | 'ollama'; export interface LLMCompletionOptions { readonly model: string; readonly systemPrompt: string; readonly userPrompt: string; readonly maxTokens?: number; readonly temperature?: number; /** * Stable, repeated portion of the user prompt. Providers with prompt * caching mark it as a cache breakpoint; other providers prepend it to * userPrompt verbatim (callers must include any separator here). */ readonly cacheableUserPrefix?: string; /** * Cache entry lifetime. Default ephemeral TTL is 5 minutes (1.25x write); * '1h' costs 2x to write but survives the 10-20 minute gap between * verification/extraction passes, where the 5m entry would expire and * every pass would re-pay the write premium with zero reads. */ readonly cacheTtl?: '1h'; } export interface LLMResult { readonly content: string; readonly inputTokens: number | null; readonly outputTokens: number | null; readonly provider: LLMProviderType; readonly durationMs: number; readonly cacheReadInputTokens?: number | null; readonly cacheCreationInputTokens?: number | null; } export interface LLMProvider { readonly type: LLMProviderType; complete(opts: LLMCompletionOptions): Promise; }