feat(core): upgrade to v2.65.0 with Cognition Layer & Proactive Advisor
- Integrated v4.0 Operational Policy into AgentEngine and AgentExecutor. - Added Context Amplification for policy-driven reasoning. - Implemented Proactive Advisor for next-action decision forks. - Added CognitionAudit diagnostics for real-time policy monitoring. - Updated test suites to support dual-execution cognition patterns.
This commit is contained in:
+9
-1
@@ -382,8 +382,16 @@ export class AgentExecutor {
|
||||
? `\n\n${renderSecondBrainTraceContext(secondBrainTrace)}`
|
||||
: '';
|
||||
const memoryCtx = this.buildMemoryContext(prompt || '', activeBrain);
|
||||
|
||||
// [Astra v4.0] 지식 관리 운영 정책 주입
|
||||
const v4PolicyCtx = [
|
||||
"\n### 🏛️ 지식 관리 정책 v4.0 (Knowledge Management Policy Applied)",
|
||||
"- [신뢰도] '의도적으로 작성된 글'은 Medium 이상의 신뢰도를 부여하여 최우선 근거로 활용할 것.",
|
||||
"- [품질] 데이터의 양보다 '추론 기여 밀도'를 중시하여 핵심 위주로 깊이 있게 서술할 것.",
|
||||
"- [충돌] 지식 간 충돌 발생 시 시스템이 독단적으로 판단하지 말고, 반드시 [CONFLICT WARNING] 플래그와 함께 상충되는 두 관점을 모두 명시하여 사용자에게 판단을 위임할 것."
|
||||
].join('\n');
|
||||
|
||||
const fullSystemPrompt = `${agentSkillCtx}\n\n${systemPrompt}${internetCtx}${memoryCtx}${designerCtx}${localProjectKnowledgeCtx}${thinkingPartnerCtx}${astraStanceCtx}${secondBrainTraceCtx}\n\n[CONTEXT]\n${brainContext}${brainInventoryCtx}\n${contextBlock}${negativeCtx}`;
|
||||
const fullSystemPrompt = `${agentSkillCtx}\n\n${systemPrompt}${internetCtx}${memoryCtx}${designerCtx}${localProjectKnowledgeCtx}${thinkingPartnerCtx}${astraStanceCtx}${secondBrainTraceCtx}${v4PolicyCtx}\n\n[CONTEXT]\n${brainContext}${brainInventoryCtx}\n${contextBlock}${negativeCtx}`;
|
||||
const messagesForRequest: ChatMessage[] = [
|
||||
{ role: 'system', content: fullSystemPrompt, internal: true },
|
||||
...reqMessages
|
||||
|
||||
+16
-6
@@ -101,10 +101,10 @@ Your sole purpose is to transform vague requests into flawless, high-resolution
|
||||
- COMPONENTS: Each blueprint must have [Objective], [Core Challenges], [Data Requirements], and [Step-by-Step Research Tasks].
|
||||
- CONSTRAINT: Do not be vague. Use professional terminology. If the request is too simple, expand it with relevant technical considerations.`;
|
||||
|
||||
async execute(input: string, brainContext?: string, signal?: AbortSignal): Promise<string> {
|
||||
async execute(input: string, brainContext?: string, signal?: AbortSignal, options?: AgentExecuteOptions): Promise<string> {
|
||||
const wrappedInput = `### SYSTEM INSTRUCTION: GENERATE EXECUTION BLUEPRINT
|
||||
1. Target Goal: ${input}
|
||||
2. Available Knowledge Base: ${brainContext}
|
||||
2. Available Knowledge Base & Policy: ${brainContext}
|
||||
3. Mission: Create a comprehensive research roadmap.`;
|
||||
return this.callLLM(this.persona, wrappedInput, signal);
|
||||
}
|
||||
@@ -118,10 +118,10 @@ Your mission is to extract, filter, and synthesize critical data based on a stra
|
||||
- CRITICAL THINKING: Identify gaps in the plan and provide extra insights to fill those gaps.
|
||||
- NO FLUFF: Be concise but extremely dense with information.`;
|
||||
|
||||
async execute(input: string, brainContext?: string, signal?: AbortSignal): Promise<string> {
|
||||
async execute(input: string, brainContext?: string, signal?: AbortSignal, options?: AgentExecuteOptions): Promise<string> {
|
||||
const wrappedInput = `### SYSTEM INSTRUCTION: DATA HARVESTING
|
||||
1. Blueprint to Follow: ${input}
|
||||
2. Contextual Constraints: ${brainContext}
|
||||
2. Contextual Constraints & Policy: ${brainContext}
|
||||
3. Mission: Provide a dense summary of facts and technical insights.`;
|
||||
return this.callLLM(this.persona, wrappedInput, signal);
|
||||
}
|
||||
@@ -135,13 +135,23 @@ Your goal is to produce a state-of-the-art final report that wows the user.
|
||||
- LANGUAGE: Always respond in the user's language (KOREAN).
|
||||
- POLISHING: Ensure logical flow between sections. Make it look like a premium report.`;
|
||||
|
||||
async execute(input: string, originalRequest?: string, signal?: AbortSignal): Promise<string> {
|
||||
async execute(input: string, originalRequest?: string, signal?: AbortSignal, options?: AgentExecuteOptions): Promise<string> {
|
||||
// [Astra v4.0] Advisor 모드 처리
|
||||
if (options?.config?.role === 'advisor') {
|
||||
const advisorPersona = `You are the [Strategic Proactive Advisor].
|
||||
Analyze the provided report and suggest 3 high-impact next actions for the user.
|
||||
- Focus on decision forks, risk mitigation, or immediate implementation steps.
|
||||
- Be extremely concrete and actionable.
|
||||
- Respond in KOREAN.`;
|
||||
return this.callLLM(advisorPersona, input, signal);
|
||||
}
|
||||
|
||||
// Fix 3: Trim input if it's too long (Basic Context Diet)
|
||||
const trimmedData = input.length > 8000 ? input.substring(0, 8000) + '... [Data Trimmed for Performance]' : input;
|
||||
|
||||
const wrappedInput = `### SYSTEM INSTRUCTION: FINAL SYNTHESIS
|
||||
1. Gathered Research Data: ${trimmedData}
|
||||
2. User's Original Objective: ${originalRequest}
|
||||
2. User's Original Objective & Policy: ${originalRequest}
|
||||
3. Mission: Write the definitive final report in KOREAN.`;
|
||||
return this.callLLM(this.persona, wrappedInput, signal);
|
||||
}
|
||||
|
||||
@@ -93,3 +93,33 @@ export class PerformanceProfiler {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class CognitionAudit {
|
||||
/**
|
||||
* [Astra v4.0] 지능적 판단 및 정책 준수 여부를 감사(Audit)합니다.
|
||||
* 시스템이 얼마나 '생각'하고 '경고'했는지 정량적으로 측정합니다.
|
||||
*/
|
||||
public static auditPolicyCompliance(stage: string, content: string): void {
|
||||
const findings = [];
|
||||
|
||||
// 1. 충돌 경고 감지 (Conflict Warning)
|
||||
if (content.includes('[CONFLICT WARNING]')) {
|
||||
findings.push('Conflict Detected & Warning Issued');
|
||||
}
|
||||
|
||||
// 2. 선제적 제안 감지 (Proactive Advice)
|
||||
if (content.includes('## 💡 Astra의 선제적 제안')) {
|
||||
findings.push('Proactive Advice Generated');
|
||||
}
|
||||
|
||||
// 3. 신뢰도 인용 패턴 확인 (Credibility Usage)
|
||||
const highTrustCitationCount = (content.match(/\[\[/g) || []).length;
|
||||
if (highTrustCitationCount > 0) {
|
||||
findings.push(`Knowledge Density: ${highTrustCitationCount} connections used`);
|
||||
}
|
||||
|
||||
if (findings.length > 0) {
|
||||
logInfo(`[CognitionAudit] [${stage}] ${findings.join(' | ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+51
-3
@@ -4,7 +4,7 @@ import * as path from 'path';
|
||||
import { lockManager } from '../core/lock';
|
||||
import { actionQueue } from '../core/queue';
|
||||
import { logInfo, logError } from '../utils';
|
||||
import { AgentDataValidator, PerformanceProfiler } from './diagnostics';
|
||||
import { AgentDataValidator, PerformanceProfiler, CognitionAudit } from './diagnostics';
|
||||
import { WikiFormatter } from './formatter';
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
@@ -506,8 +506,16 @@ export class AgentEngine {
|
||||
);
|
||||
this.validateResult(finalReport, 'Writer');
|
||||
|
||||
// --- Phase 4: Proactive Advisor (Astra v4.0) ---
|
||||
// 리포트 작성 후, 사용자의 다음 행동을 선제적으로 제안합니다.
|
||||
const proactiveAdvice = await this.generateProactiveAdvice(finalReport, prompt, brainContext, signal);
|
||||
const enrichedReport = `${finalReport}\n\n---\n## 💡 Astra의 선제적 제안 (Proactive Next Actions)\n${proactiveAdvice}`;
|
||||
|
||||
// 3. 지식 저장 포맷 표준화 (Standardization: Astra 피드백)
|
||||
const standardizedReport = WikiFormatter.format(finalReport, missionId);
|
||||
const standardizedReport = WikiFormatter.format(enrichedReport, missionId);
|
||||
|
||||
// [Astra v4.0] 지능적 판단 감사 (Cognition Audit)
|
||||
CognitionAudit.auditPolicyCompliance('MissionComplete', standardizedReport);
|
||||
|
||||
this.transition(state, 'completed', '미션 완료', onProgress);
|
||||
logInfo(`[AgentEngine] 미션 완료: ${missionId} (총 ${state.getElapsedMs()}ms)`);
|
||||
@@ -589,7 +597,12 @@ export class AgentEngine {
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
const result = await agent.execute(input, context, signal, options);
|
||||
|
||||
// [Astra v4.0] 맥락 증폭 (Context Amplification)
|
||||
// 에이전트 실행 직전, 지식 신뢰도 및 충돌 처리 정책을 주입합니다.
|
||||
const amplifiedContext = this.amplifyContext(context, options);
|
||||
|
||||
const result = await agent.execute(input, amplifiedContext, signal, options);
|
||||
const durationMs = Date.now() - startTime;
|
||||
|
||||
PerformanceProfiler.logLLMLatency(agentName, durationMs, result.length);
|
||||
@@ -680,4 +693,39 @@ export class AgentEngine {
|
||||
// Error Recovery Matrix: Permanent 오류 발생을 방지하기 위한 선제적 핸드오프 검증
|
||||
AgentDataValidator.validateHandoff(step, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* [Astra v4.0] 맥락 증폭 로직
|
||||
* 지식 관리 정책 v4.0을 LLM 지시사항으로 변환하여 주입합니다.
|
||||
*/
|
||||
private amplifyContext(context: string, options?: AgentExecuteOptions): string {
|
||||
const policyDirectives = [
|
||||
"\n### 🏛️ Knowledge Management Policy v4.0 Applied",
|
||||
"- [CREDIBILITY] 정보 출처가 의도적으로 작성된 글인 경우 Medium 이상의 신뢰도를 부여하고 우선적으로 인용하십시오.",
|
||||
"- [QUALITY] 지식의 양보다 '추론 기여 밀도'를 중시하여 핵심 위주로 서술하십시오.",
|
||||
"- [CONFLICT] 상충되는 지식 발견 시 스스로 판단하지 말고 반드시 [CONFLICT WARNING] 플래그와 함께 두 관점을 모두 보고하십시오."
|
||||
].join('\n');
|
||||
|
||||
return `${context}\n${policyDirectives}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* [Astra v4.0] 선제적 제안 생성
|
||||
* 수행된 작업 결과를 분석하여 다음 단계의 의사결정 포크를 제안합니다.
|
||||
*/
|
||||
private async generateProactiveAdvice(report: string, originalPrompt: string, context: string, signal: AbortSignal): Promise<string> {
|
||||
logInfo(`[AgentEngine] 선제적 제안 생성 중...`);
|
||||
// 본 로직은 별도의 가벼운 추론 단계를 거치거나, WriterAgent의 기능을 확장하여 구현할 수 있습니다.
|
||||
// 현재는 WriterAgent에게 한 번 더 질의하거나, 리포트에서 액션 아이템을 추출하는 구조로 시작합니다.
|
||||
const advicePrompt = `다음 리포트를 읽고, 사용자가 다음에 내려야 할 '전략적 의사결정'이나 '실행 작업' 3가지를 제안해줘.
|
||||
원래 요청: ${originalPrompt}
|
||||
리포트 요약: ${report.substring(0, 1000)}...`;
|
||||
|
||||
try {
|
||||
// WriterAgent를 Advisor 모드로 재활용
|
||||
return await this.writer.execute(advicePrompt, context, signal, { config: { role: 'advisor' } });
|
||||
} catch (err) {
|
||||
return "다음 단계에 대한 자동 제안을 생성하지 못했습니다. 리포트의 결론 섹션을 참고해 주세요.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user