feat(phase6-9): Complete modular architecture and Agent Teams

Phase 6.4 - Modular Architecture:
- Add lewooogo-brain adapters for LLM providers
- Add lewooogo-data dual memory (Redis + PostgreSQL)
- Implement consensus engine for multi-agent decisions
- Add incident memory service for historical context

Phase 9 - Agent Teams (Claude Agent SDK):
- Add base agent class with Claude Sonnet 4 integration
- Implement action planner, blast radius, and security agents
- Add agent API endpoints and proposal workflow
- Integrate ADR-009 OpenClaw Agent Teams architecture

DevOps & CI/CD:
- Add GitHub Actions CI/CD workflows (ci.yaml, cd.yaml)
- Add pre-commit hooks and secrets baseline
- Add docker-compose for local development
- Update Kubernetes network policies

Frontend Improvements:
- Add auto-healing error boundary component
- Update i18n messages for agent features
- Enhance dual-state incident card with execution feedback

Documentation:
- Add 7 ADRs covering MCP, design system, architecture decisions
- Update ARCHITECTURE_MEMORY.md with modular design
- Add GLOBAL_RULES.md and SOUL.md for project identity

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
OG T
2026-03-23 18:40:36 +08:00
parent 6eccb45757
commit 7478dc0254
169 changed files with 24613 additions and 247 deletions

View File

@@ -6,6 +6,7 @@ import { getMessages } from 'next-intl/server'
import { routing, type Locale } from '@/i18n/routing'
import '../globals.css'
import { Providers } from '../providers'
import { AutoHealingErrorBoundary } from '@/components/shared/auto-healing-error-boundary'
const inter = Inter({
subsets: ['latin'],
@@ -63,7 +64,9 @@ export default async function LocaleLayout({
className={`${inter.variable} ${jetbrainsMono.variable} ${vt323.variable} font-body bg-nothing-gray-50 text-nothing-black antialiased`}
>
<NextIntlClientProvider messages={messages}>
<Providers>{children}</Providers>
<AutoHealingErrorBoundary fallbackMessage="Critical Application Error">
<Providers>{children}</Providers>
</AutoHealingErrorBoundary>
</NextIntlClientProvider>
</body>
</html>

View File

@@ -28,6 +28,7 @@
*/
import React, { useState, useCallback, useEffect, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { apiClient, DecisionInfo } from '@/lib/api-client'
type ButtonState = 'idle' | 'loading' | 'approved' | 'rejected' | 'error' | 'timeout'
@@ -60,6 +61,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
decision,
onApprovalChange,
}) => {
const t = useTranslations('incident.card')
const isAlert = status === 'alert'
const [buttonState, setButtonState] = useState<ButtonState>('idle')
const [errorMessage, setErrorMessage] = useState<string | null>(null)
@@ -105,7 +107,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => {
setButtonState('timeout')
setErrorMessage('執行超時,請檢查 API 日誌')
setErrorMessage(t('timeoutMessage'))
}, EXECUTION_TIMEOUT_MS)
try {
@@ -183,7 +185,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => {
setButtonState('timeout')
setErrorMessage('執行超時,請檢查 API 日誌')
setErrorMessage(t('timeoutMessage'))
}, EXECUTION_TIMEOUT_MS)
try {
@@ -236,19 +238,19 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
return (
<span className="px-3 py-1 bg-neutral-700 text-white text-xs flex items-center gap-2">
<span className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin" />
...
{t('executing')}
</span>
)
case 'approved':
return (
<span className="px-3 py-1 bg-green-600 text-white text-xs">
[ ]
{t('approved')}
</span>
)
case 'rejected':
return (
<span className="px-3 py-1 bg-red-600 text-white text-xs">
[ ]
{t('rejected')}
</span>
)
case 'error':
@@ -256,7 +258,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
<div className="flex flex-col gap-1 items-end">
<div className="flex items-center gap-1">
<span className="px-2 py-1 bg-red-600 text-white text-xs">
{t('error')}
</span>
<button
onClick={() => {
@@ -265,7 +267,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
}}
className="px-2 py-1 bg-neutral-700 text-white text-xs hover:bg-neutral-600 transition-colors"
>
{t('retry')}
</button>
</div>
{errorMessage && (
@@ -280,7 +282,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
<div className="flex flex-col gap-1 items-end">
<div className="flex items-center gap-1">
<span className="px-2 py-1 bg-amber-500 text-white text-xs animate-pulse">
{t('timeout')}
</span>
<button
onClick={() => {
@@ -289,11 +291,11 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
}}
className="px-2 py-1 bg-neutral-700 text-white text-xs hover:bg-neutral-600 transition-colors"
>
{t('retry')}
</button>
</div>
<span className="text-[10px] text-amber-600">
API
{t('checkApiLogs')}
</span>
</div>
)
@@ -304,7 +306,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
onClick={handleApprove}
disabled={!isDecisionReady}
className="px-2 py-1 bg-neutral-900 text-white text-xs hover:bg-green-700 active:scale-95 active:bg-neutral-800 transition-all duration-100 cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed disabled:active:scale-100"
title={!isDecisionReady ? (isAnalyzing ? '大腦分析中...' : '等待決策') : (decisionAction || '授權執行')}
title={!isDecisionReady ? (isAnalyzing ? t('analyzing') : t('waitingDecision')) : (decisionAction || t('authorizeExecution'))}
>
Y
</button>
@@ -313,7 +315,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
onClick={handleReject}
disabled={!isDecisionReady}
className="px-2 py-1 bg-neutral-900 text-white text-xs hover:bg-red-700 active:scale-95 active:bg-neutral-800 transition-all duration-100 cursor-pointer disabled:opacity-30 disabled:cursor-not-allowed disabled:active:scale-100"
title={!isDecisionReady ? (isAnalyzing ? '大腦分析中...' : '等待決策') : '拒絕提案'}
title={!isDecisionReady ? (isAnalyzing ? t('analyzing') : t('waitingDecision')) : t('rejectProposal')}
>
n
</button>
@@ -376,13 +378,13 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
<div className="flex justify-between items-center">
<span className="text-xs text-neutral-500">
{tier === 1 ? (
'>_ AI 執行中 (Tier 1)'
t('aiExecuting')
) : isAnalyzing ? (
'>_ 大腦分析中...'
t('brainAnalyzing')
) : isDecisionReady ? (
`>_ 決策就緒 (Tier ${tier})`
t('decisionReady', { tier })
) : (
`>_ 等待統帥親核 (Tier ${tier})`
t('waitingCommander', { tier })
)}
</span>
{tier > 1 && renderActionButton()}
@@ -391,7 +393,7 @@ export const DualStateIncidentCard: React.FC<DualStateIncidentCardProps> = ({
{/* Phase 6.5: 顯示 AI 建議行動 */}
{decisionAction && tier > 1 && (
<div className="mt-2 p-2 bg-neutral-50 border-[0.5px] border-neutral-200 text-[10px] font-mono text-neutral-600">
<div className="text-neutral-400 mb-1">&gt; :</div>
<div className="text-neutral-400 mb-1">{t('suggestedAction')}</div>
<div className="text-neutral-800">{decisionAction}</div>
{decisionReasoning && (
<div className="mt-1 text-neutral-500 italic">

View File

@@ -0,0 +1,141 @@
'use client'
import React, { Component, ErrorInfo, ReactNode } from 'react'
import { useTranslations } from 'next-intl'
import { useAgentStore } from '@/stores/agent.store'
interface ErrorBoundaryTranslations {
systemFailure: string;
criticalError: string;
escalating: string;
forceRestart: string;
detectingAnomaly: string;
autoHealingAttempt: (attempt: number) => string;
}
interface InnerProps {
children: ReactNode;
fallbackMessage?: string;
translations: ErrorBoundaryTranslations;
}
interface State {
hasError: boolean;
retryCount: number;
}
class AutoHealingErrorBoundaryInner extends Component<InnerProps, State> {
public state: State = {
hasError: false,
retryCount: 0
};
public static getDerivedStateFromError(_: Error): State {
return { hasError: true, retryCount: 0 };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('[AWOOOI] Frontend component crashed:', error, errorInfo);
this.attemptAutoHealing();
}
private attemptAutoHealing = () => {
const { retryCount } = this.state;
if (retryCount >= 3) {
console.error('[AWOOOI] Auto-healing failed after 3 attempts. Escalating to L3 AIOps.');
return;
}
// L1 Auto-Healing Logic
console.log(`[AWOOOI] Attempting auto-healing (Attempt ${retryCount + 1}/3)...`);
// 1. Clear toxic stored state
if (typeof window !== 'undefined') {
try {
localStorage.clear();
sessionStorage.clear();
} catch (e) {
console.warn('Failed to clear storage:', e);
}
}
// 2. Reset Zustand store explicitly outside of React render cycle
try {
if (typeof useAgentStore.getState().reset === 'function') {
useAgentStore.getState().reset();
}
} catch (e) {
console.warn('[AWOOOI] Failed to reset Agent Store during auto-healing', e);
}
// 3. Exponential Backoff remount
const delay = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s
setTimeout(() => {
console.log('[AWOOOI] Remounting component...');
this.setState({ hasError: false, retryCount: retryCount + 1 });
}, delay);
}
public render() {
const { translations } = this.props;
if (this.state.hasError) {
if (this.state.retryCount >= 3) {
return (
<div className="flex flex-col items-center justify-center p-8 bg-[#111111] text-white border border-red-500/30 rounded-lg max-w-lg mx-auto mt-12">
<h2 className="text-xl font-mono text-red-500 mb-4">{translations.systemFailure}</h2>
<p className="font-mono text-sm text-gray-400 mb-4">{this.props.fallbackMessage || translations.criticalError}</p>
<p className="font-mono text-xs text-purple-400 mb-6">{translations.escalating}</p>
<button
onClick={() => window.location.reload()}
className="px-6 py-2 bg-white text-black font-mono text-sm rounded-full hover:bg-gray-200 transition-colors"
>
{translations.forceRestart}
</button>
</div>
);
}
return (
<div className="flex flex-col items-center justify-center p-12 space-y-4 animate-pulse">
<div className="text-red-500 font-mono text-sm font-bold tracking-widest">{translations.detectingAnomaly}</div>
<div className="text-gray-400 font-mono text-xs">{translations.autoHealingAttempt(this.state.retryCount + 1)}</div>
<div className="w-48 h-1 bg-gray-800 rounded overflow-hidden mt-4">
<div className="h-full bg-white opacity-50 animate-ping"></div>
</div>
</div>
);
}
return this.props.children;
}
}
// Wrapper component that provides translations via hook
interface Props {
children: ReactNode;
fallbackMessage?: string;
}
export function AutoHealingErrorBoundary({ children, fallbackMessage }: Props) {
const t = useTranslations('errorBoundary');
const translations: ErrorBoundaryTranslations = {
systemFailure: t('systemFailure'),
criticalError: t('criticalError'),
escalating: t('escalating'),
forceRestart: t('forceRestart'),
detectingAnomaly: t('detectingAnomaly'),
autoHealingAttempt: (attempt: number) => t('autoHealingAttempt', { attempt }),
};
return (
<AutoHealingErrorBoundaryInner
translations={translations}
fallbackMessage={fallbackMessage}
>
{children}
</AutoHealingErrorBoundaryInner>
);
}

View File

@@ -66,6 +66,7 @@ interface AgentState {
// SSE 連線控制 (內部使用)
_abortController: AbortController | null
_sseRetryCount: number
// ==================== Actions ====================
setStatus: (status: AgentStatus) => void
@@ -114,6 +115,7 @@ const initialState = {
conversationId: null,
error: null,
_abortController: null,
_sseRetryCount: 0,
}
// ==================== Store ====================
@@ -153,7 +155,8 @@ export const useAgentStore = create<AgentState>()(
_abortController: abortController,
status: 'thinking',
error: null,
thinkingStream: [],
// 如果是重連,保留原本的 streams否則清空
thinkingStream: state._sseRetryCount > 0 ? state.thinkingStream : [],
})
try {
@@ -166,6 +169,9 @@ export const useAgentStore = create<AgentState>()(
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
// 連線成功,重置重試計數
set({ _sseRetryCount: 0 })
const reader = response.body?.getReader()
if (!reader) {
throw new Error('無法建立串流通道')
@@ -213,18 +219,38 @@ export const useAgentStore = create<AgentState>()(
} catch (err: unknown) {
if (err instanceof Error && err.name === 'AbortError') {
console.log('SSE 串流已手動中斷')
set({ status: 'idle' })
set({ status: 'idle', _sseRetryCount: 0 })
} else {
const message = err instanceof Error ? err.message : '未知錯誤'
set({
status: 'error',
error: message,
})
get().appendThinking({
type: 'error',
content: message,
timestamp: new Date(),
})
// L2 網路自癒機制: Exponential Backoff Retry
const maxRetries = 5
const currentRetries = state._sseRetryCount
if (currentRetries < maxRetries) {
const delay = Math.min(1000 * Math.pow(2, currentRetries), 30000)
console.log(`[AWOOOI L2 Healing] SSE Error: ${message}. Retrying in ${delay}ms (Attempt ${currentRetries + 1}/${maxRetries})...`)
get().appendThinking({
type: 'error',
content: `連線中斷: ${message}。將在 ${delay/1000} 秒後自動重連 (嘗試 ${currentRetries + 1}/${maxRetries})...`,
timestamp: new Date(),
})
set({ _sseRetryCount: currentRetries + 1 })
setTimeout(() => get().startThinkingStream(apiUrl), delay)
} else {
console.error('[AWOOOI L2 Healing] SSE Max retries reached. Escalating to L3 AIOps.')
set({
status: 'error',
error: `Maximum SSE reconnect attempts reached: ${message}`,
})
get().appendThinking({
type: 'error',
content: `嚴重錯誤: 無法建立串流連線,已達最大重試次數。`,
timestamp: new Date(),
})
}
}
}
},