fix(agent): v2.2.62 — 출력 degeneration 방어

- 재시작 감지: auto-continuation이 "이어쓰기" 대신 답변을 처음부터
  재생성하면 버림 → 분석이 두 번 나오던 문제 제거
- degeneration 정리 패스(cleanDegeneratedOutput): 문자 벽(같은 기호 8개+),
  (Note:…) 메타 노트, Candidate records 내부 지시문 누출,
  (질문 의도:…)/[핵심 확인 질문] 누출, 연속 중복 문단 제거

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-22 16:13:39 +09:00
parent 745ebc57f6
commit 9cddf2aabc
12 changed files with 114 additions and 39 deletions
+11 -11
View File
@@ -3,15 +3,15 @@
<!-- ASTRA:AUTO-START --> <!-- ASTRA:AUTO-START -->
## Snapshot ## Snapshot
- **Workspace**: `connectai` `v2.2.61` _(absolute path varies by environment; resolved from the active VS Code workspace)_ - **Workspace**: `connectai` `v2.2.62` _(absolute path varies by environment; resolved from the active VS Code workspace)_
- **Description**: The personal intelligence layer for Antigravity and VS Code. A private cognitive partner for deep project context, memory, and proactive strategic decision-making. - **Description**: The personal intelligence layer for Antigravity and VS Code. A private cognitive partner for deep project context, memory, and proactive strategic decision-making.
- **Stack**: TypeScript, Node.js, VS Code Extension, LM Studio SDK, Test runner - **Stack**: TypeScript, Node.js, VS Code Extension, LM Studio SDK, Test runner
- **Stats**: 272 source files, ~55,207 lines across 5 top-level modules. - **Stats**: 273 source files, ~55,326 lines across 5 top-level modules.
## Last Refresh ## Last Refresh
- **Time**: 2026-05-22T06:25:57.973Z - **Time**: 2026-05-22T06:32:01.903Z
- **Files newly analysed**: 1 - **Files newly analysed**: 1
- **Files reused from cache**: 271 - **Files reused from cache**: 272
## Directory Map ## Directory Map
```mermaid ```mermaid
@@ -42,7 +42,7 @@ flowchart LR
media["media/<br/>6 files"] media["media/<br/>6 files"]
tests["tests/<br/>35 files"] tests["tests/<br/>35 files"]
core_py["core_py/<br/>6 files"] core_py["core_py/<br/>6 files"]
docs["docs/<br/>86 files"] docs["docs/<br/>87 files"]
tests --> src tests --> src
``` ```
@@ -65,7 +65,7 @@ flowchart LR
## Modules ## Modules
### `src/` — 139 files, ~38,185 lines ### `src/` — 139 files, ~38,285 lines
**Sub-directories** **Sub-directories**
- `src/features/` (66) — Astra Office — public API. 다음 세션에서 추가될 OfficeSnapshot presenter / schema 도 같은 entry 로 노출 예정. 현재 노출: full webview panel H - `src/features/` (66) — Astra Office — public API. 다음 세션에서 추가될 OfficeSnapshot presenter / schema 도 같은 entry 로 노출 예정. 현재 노출: full webview panel H
@@ -93,7 +93,7 @@ flowchart LR
- `src/retrieval/scoring.ts` (536 lines) — Scoring Engine — TF-IDF + Bilingual Tokenizer 단순 includes() 키워드 매칭을 넘어서, TF-IDF 가중치 기반의 문서 스코어링을 제공합니다. 한국어/영어 양국어 토크나이저를 포함합니다. - `src/retrieval/scoring.ts` (536 lines) — Scoring Engine — TF-IDF + Bilingual Tokenizer 단순 includes() 키워드 매칭을 넘어서, TF-IDF 가중치 기반의 문서 스코어링을 제공합니다. 한국어/영어 양국어 토크나이저를 포함합니다.
- `src/skills/agentKnowledgeMap.ts` (374 lines) - `src/skills/agentKnowledgeMap.ts` (374 lines)
- `src/retrieval/lessonHelpers.ts` (325 lines) — Lesson / Experience Memory — pure helpers (no vscode dependency) "Lesson" = a markdown file in the active brain that captures a past mistake/risk and how to avoid repeating it. Identified by a lessons - `src/retrieval/lessonHelpers.ts` (325 lines) — Lesson / Experience Memory — pure helpers (no vscode dependency) "Lesson" = a markdown file in the active brain that captures a past mistake/risk and how to avoid repeating it. Identified by a lessons
- `src/agent.ts` (3722 lines) - `src/agent.ts` (3822 lines)
- `src/features/providers/types.ts` (63 lines) — Cloud LLM provider routing — model id prefix → provider id 매핑. Prefix 규칙: openrouter:anthropic/claude-3.5-sonnet → { provider: 'openrouter', model: 'anthropic/claude-3.5-sonnet' } anthropic:claude-3-5 - `src/features/providers/types.ts` (63 lines) — Cloud LLM provider routing — model id prefix → provider id 매핑. Prefix 규칙: openrouter:anthropic/claude-3.5-sonnet → { provider: 'openrouter', model: 'anthropic/claude-3.5-sonnet' } anthropic:claude-3-5
- `src/lib/engine.ts` (906 lines) - `src/lib/engine.ts` (906 lines)
- `src/retrieval/brainIndex.ts` (325 lines) — Brain Index — persistent, mtime-keyed tokenized cache of the Second Brain RAG 검색은 매 질의마다 브레인의 모든 .md 파일을 읽고 토크나이즈해서 TF-IDF 점수를 계산했습니다 — 파일 수가 많아지면 그게 병목입니다. 이 모듈은 <brainPath>/.astra/brain-index.json 에 - `src/retrieval/brainIndex.ts` (325 lines) — Brain Index — persistent, mtime-keyed tokenized cache of the Second Brain RAG 검색은 매 질의마다 브레인의 모든 .md 파일을 읽고 토크나이즈해서 TF-IDF 점수를 계산했습니다 — 파일 수가 많아지면 그게 병목입니다. 이 모듈은 <brainPath>/.astra/brain-index.json 에
@@ -161,10 +161,10 @@ flowchart LR
- `core_py/optimizer.py` (55 lines) - `core_py/optimizer.py` (55 lines)
- `core_py/queue_worker.py` (82 lines) - `core_py/queue_worker.py` (82 lines)
### `docs/` — 86 files, ~3,316 lines ### `docs/` — 87 files, ~3,335 lines
**Sub-directories** **Sub-directories**
- `docs/records/` (73) — Bug: /Volumes/Data/project/Antigravity/ConnectAI 프로젝트 코드 리뷰 해줄 수 있어? 개선할 부분이 있는지, 그러고... - `docs/records/` (74) — Bug: /Volumes/Data/project/Antigravity/ConnectAI 프로젝트 코드 리뷰 해줄 수 있어? 개선할 부분이 있는지, 그러고...
- `docs/docs/` (5) — Bug: Viewed integrationretrieval.test.ts:1-59 integrationretrieval.test.ts를 통해 ... - `docs/docs/` (5) — Bug: Viewed integrationretrieval.test.ts:1-59 integrationretrieval.test.ts를 통해 ...
- `docs/Meeting/` (0) - `docs/Meeting/` (0)
@@ -175,7 +175,7 @@ flowchart LR
- `docs/EXPERIENCE_MEMORY_PLAN.md` (122 lines) — Experience Memory (Mistake / Lesson Loop) — Implementation Plan - `docs/EXPERIENCE_MEMORY_PLAN.md` (122 lines) — Experience Memory (Mistake / Lesson Loop) — Implementation Plan
- `docs/records/ConnectAI/development/2026-05-02_connectai_project_knowledge_overview.md` (121 lines) — Astra Project Knowledge Overview - `docs/records/ConnectAI/development/2026-05-02_connectai_project_knowledge_overview.md` (121 lines) — Astra Project Knowledge Overview
- `docs/records/ConnectAI/development/2026-05-03_connectai_project_knowledge_overview.md` (121 lines) — Astra Project Knowledge Overview - `docs/records/ConnectAI/development/2026-05-03_connectai_project_knowledge_overview.md` (121 lines) — Astra Project Knowledge Overview
- `docs/records/ConnectAI/timeline.md` (170 lines) — Project Timeline - `docs/records/ConnectAI/timeline.md` (173 lines) — Project Timeline
- `docs/Advanced_Features_Implementation_Guide.md` (40 lines) — Advanced Features Implementation Guide - `docs/Advanced_Features_Implementation_Guide.md` (40 lines) — Advanced Features Implementation Guide
- `docs/docs/records/docs/bugs/BUG-0001-viewed-integration-retrieval-test-ts-1-59-integration-retrie.md` (16 lines) — Bug: Viewed integrationretrieval.test.ts:1-59 integrationretrieval.test.ts를 통해 ... - `docs/docs/records/docs/bugs/BUG-0001-viewed-integration-retrieval-test-ts-1-59-integration-retrie.md` (16 lines) — Bug: Viewed integrationretrieval.test.ts:1-59 integrationretrieval.test.ts를 통해 ...
- `docs/docs/records/docs/chronicle.config.json` (11 lines) — JSON configuration - `docs/docs/records/docs/chronicle.config.json` (11 lines) — JSON configuration
@@ -336,7 +336,7 @@ Astra는 대표님의 명시적인 승인 하에 로컬 시스템의 강력한
**Designed for High-Performance Decision Making.** **Designed for High-Performance Decision Making.**
Copyright (C) **g1nation**. All rights reserved. Copyright (C) **g1nation**. All rights reserved.
_Last auto-scan: 2026-05-22T06:25:57.973Z · signature `32c602bb`_ _Last auto-scan: 2026-05-22T06:32:01.903Z · signature `26f10f3d`_
<!-- ASTRA:AUTO-END --> <!-- ASTRA:AUTO-END -->
## Purpose ## Purpose
+15 -8
View File
@@ -1,11 +1,11 @@
{ {
"version": 1, "version": 1,
"generatedAt": "2026-05-22T06:25:58.013Z", "generatedAt": "2026-05-22T06:32:01.938Z",
"files": { "files": {
"src/agent.ts": { "src/agent.ts": {
"mtimeMs": 1779430182152.1404, "mtimeMs": 1779431481976.8423,
"size": 217774, "size": 220892,
"lines": 3722, "lines": 3822,
"role": "", "role": "",
"imports": [ "imports": [
"src/utils", "src/utils",
@@ -1977,7 +1977,7 @@
"imports": [] "imports": []
}, },
"docs/records/ConnectAI/chronicle.config.json": { "docs/records/ConnectAI/chronicle.config.json": {
"mtimeMs": 1779430497353.3203, "mtimeMs": 1779431169044.1296,
"size": 371, "size": 371,
"lines": 11, "lines": 11,
"role": "JSON configuration", "role": "JSON configuration",
@@ -2333,6 +2333,13 @@
"role": "Discussion: 최성연 알아? 칼리버스에서 근무한데", "role": "Discussion: 최성연 알아? 칼리버스에서 근무한데",
"imports": [] "imports": []
}, },
"docs/records/ConnectAI/discussions/2026-05-22_e-wiki-connectai-git에-커밋하고-푸쉬해줘.md": {
"mtimeMs": 1779431169034.8508,
"size": 745,
"lines": 16,
"role": "Discussion: E:\\Wiki\\connectai git에 커밋하고 푸쉬해줘.",
"imports": []
},
"docs/records/ConnectAI/planning/2026-05-02_project-chronicle-guard.md": { "docs/records/ConnectAI/planning/2026-05-02_project-chronicle-guard.md": {
"mtimeMs": 1778028987339.2349, "mtimeMs": 1778028987339.2349,
"size": 3004, "size": 3004,
@@ -2383,9 +2390,9 @@
"imports": [] "imports": []
}, },
"docs/records/ConnectAI/timeline.md": { "docs/records/ConnectAI/timeline.md": {
"mtimeMs": 1779430149729.8076, "mtimeMs": 1779431169036.8623,
"size": 11074, "size": 11199,
"lines": 170, "lines": 173,
"role": "Project Timeline", "role": "Project Timeline",
"imports": [] "imports": []
}, },
@@ -1,5 +1,5 @@
{ {
"result": "Final report with inconsistencies. This should be long enough to pass validation.", "result": "Final report with inconsistencies. This should be long enough to pass validation.",
"createdAt": 1779430407981, "createdAt": 1779431564297,
"modelVersion": "unknown" "modelVersion": "unknown"
} }
@@ -1,5 +1,5 @@
{ {
"result": "[CONFLICT WARNING] 성능이 200% 증가했습니다. vs 그러나 동시에 50% 감소했습니다. 최적화와 성능 저하가 동시에 발견됨.", "result": "[CONFLICT WARNING] 성능이 200% 증가했습니다. vs 그러나 동시에 50% 감소했습니다. 최적화와 성능 저하가 동시에 발견됨.",
"createdAt": 1779430407979, "createdAt": 1779431564294,
"modelVersion": "unknown" "modelVersion": "unknown"
} }
@@ -1,5 +1,5 @@
{ {
"result": "Detailed Execution Plan: 1. Research 2. Analyze 3. Write report with high quality.", "result": "Detailed Execution Plan: 1. Research 2. Analyze 3. Write report with high quality.",
"createdAt": 1779430407976, "createdAt": 1779431564292,
"modelVersion": "unknown" "modelVersion": "unknown"
} }
@@ -1,5 +1,5 @@
{ {
"result": "---\nid: stress_conflict_1779430407960\ndate: 2026-05-22T06:13:27.983Z\ntype: knowledge_artifact\nstandard: P-Reinforce v3.0\ntags: [automated, connect_ai, brain_sync]\n---\n\n## 📌 Brief Summary\nFinal report with inconsistencies. This should be long enough to pass validation.\n\nFinal report with inconsistencies. This should be long enough to pass validation.\n\n---\n## 💡 Astra의 선제적 제안 (Proactive Next Actions)\nFinal report with inconsistencies. This should be long enough to pass validation.\n---\n## 🛡️ Reliability & Audit Summary\n> [!NOTE]\n> 이 문서는 ConnectAI의 **Intelligent Resilience** 엔진에 의해 검증 및 정제되었습니다.\n\n| Metric | Value | Status |\n| :--- | :--- | :--- |\n| **Conflict Risk** | `60/100` | ⚠️ Medium |\n| **Fallbacks Used** | `0` | ✅ None |\n| **Auto Retries** | `0` | ✅ Stable |\n| **Deduplication** | `0` | Standard |\n| **Processing Time** | `0.0s` | ✅ Fast |\n\n### 🔍 Decision Audit Trail\n- **[PLANNER]** 전략 수립 중... (15ms)\n- **[RESEARCHER]** 핵심 정보 수집 및 분석 중... (2ms)\n- **[WRITER]** 최종 리포트 작성 및 편집 중... (4ms)\n", "result": "---\nid: stress_conflict_1779431564276\ndate: 2026-05-22T06:32:44.299Z\ntype: knowledge_artifact\nstandard: P-Reinforce v3.0\ntags: [automated, connect_ai, brain_sync]\n---\n\n## 📌 Brief Summary\nFinal report with inconsistencies. This should be long enough to pass validation.\n\nFinal report with inconsistencies. This should be long enough to pass validation.\n\n---\n## 💡 Astra의 선제적 제안 (Proactive Next Actions)\nFinal report with inconsistencies. This should be long enough to pass validation.\n---\n## 🛡️ Reliability & Audit Summary\n> [!NOTE]\n> 이 문서는 ConnectAI의 **Intelligent Resilience** 엔진에 의해 검증 및 정제되었습니다.\n\n| Metric | Value | Status |\n| :--- | :--- | :--- |\n| **Conflict Risk** | `60/100` | ⚠️ Medium |\n| **Fallbacks Used** | `0` | ✅ None |\n| **Auto Retries** | `0` | ✅ Stable |\n| **Deduplication** | `0` | Standard |\n| **Processing Time** | `0.0s` | ✅ Fast |\n\n### 🔍 Decision Audit Trail\n- **[PLANNER]** 전략 수립 중... (14ms)\n- **[RESEARCHER]** 핵심 정보 수집 및 분석 중... (3ms)\n- **[WRITER]** 최종 리포트 작성 및 편집 중... (3ms)\n",
"createdAt": 1779430407983, "createdAt": 1779431564299,
"modelVersion": "unknown" "modelVersion": "unknown"
} }
@@ -1,7 +1,7 @@
{ {
"missionId": "stress_conflict_1779430407960", "missionId": "stress_conflict_1779431564276",
"status": "completed", "status": "completed",
"startTime": "2026-05-22T06:13:27.960Z", "startTime": "2026-05-22T06:32:44.276Z",
"totalElapsedMs": 24, "totalElapsedMs": 24,
"results": { "results": {
"planner": "Detailed Execution Plan: 1. Research 2. Analyze 3. Write report with high quality.", "planner": "Detailed Execution Plan: 1. Research 2. Analyze 3. Write report with high quality.",
@@ -16,30 +16,30 @@
{ {
"from": "idle", "from": "idle",
"to": "planner", "to": "planner",
"durationMs": 15, "durationMs": 14,
"message": "전략 수립 중...", "message": "전략 수립 중...",
"ts": "2026-05-22T06:13:27.975Z" "ts": "2026-05-22T06:32:44.290Z"
}, },
{ {
"from": "planner", "from": "planner",
"to": "researcher", "to": "researcher",
"durationMs": 2, "durationMs": 3,
"message": "핵심 정보 수집 및 분석 중...", "message": "핵심 정보 수집 및 분석 중...",
"ts": "2026-05-22T06:13:27.977Z" "ts": "2026-05-22T06:32:44.293Z"
}, },
{ {
"from": "researcher", "from": "researcher",
"to": "writer", "to": "writer",
"durationMs": 4, "durationMs": 3,
"message": "최종 리포트 작성 및 편집 중...", "message": "최종 리포트 작성 및 편집 중...",
"ts": "2026-05-22T06:13:27.981Z" "ts": "2026-05-22T06:32:44.296Z"
}, },
{ {
"from": "writer", "from": "writer",
"to": "completed", "to": "completed",
"durationMs": 3, "durationMs": 4,
"message": "미션 완료", "message": "미션 완료",
"ts": "2026-05-22T06:13:27.984Z" "ts": "2026-05-22T06:32:44.300Z"
} }
], ],
"resilienceMetrics": { "resilienceMetrics": {
+13
View File
@@ -1,5 +1,18 @@
# Astra Patch Notes # Astra Patch Notes
## v2.2.62 (2026-05-22)
### 🧹 모델 출력 붕괴(degeneration) 방어 — 가독성 보호
- **문제:** 긴 세션의 분석 답변에서 ①같은 분석이 통째로 두 번 생성됨 ②밑줄 `___` 수백 개 등 문자 벽 ③`(Note: I am acting as ...)` 메타 노트 반복 ④내부 지시문 `Candidate records for this discussion...` 누출 ⑤`[핵심 확인 질문]`·`(질문 의도: …)` 누출. 마크다운/테이블이 깨져 렌더링 불가.
- **원인:** 소형 로컬 모델이 긴 컨텍스트에서 붕괴. 특히 auto-continuation이 "이어서 쓰라"는 지시를 무시하고 답변을 처음부터 **재생성**`mergeContinuationParts`가 중복을 못 걸러 통째로 이어 붙임.
- **수정 1 — 재시작 감지.** continuation 결과가 기존 답변과 같은 도입부로 시작하면(앞부분 12자+ 일치) "이어쓰기"가 아닌 "재시작"으로 판정해 **버림**. 분석이 두 번 나오는 문제 제거.
- **수정 2 — degeneration 정리 패스.** 최종 출력에서 문자 벽(같은 기호 8개+), `(Note: …)` 메타 노트, `Candidate records…` 내부 지시문, `(질문 의도: …)`·`[핵심 확인 질문]` 누출, 연속 중복 문단을 제거. 모델이 붕괴해도 답변은 읽을 수 있게 유지.
- **한계:** 한글-한글 토큰 깨짐(`붕괴``붕점`, `핵심``핵점`)은 멀쩡한 단어처럼 보여 탐지 불가 — 이는 모델 자체 한계. 긴 세션에서는 `/newChat`으로 초기화 권장.
- **신규 패키징:** `astra-2.2.62.vsix`.
---
## v2.2.61 (2026-05-22) ## v2.2.61 (2026-05-22)
### 🔁 출력 없는 액션엔 2번째 LLM 호출 생략 — "빈 응답" 근본 원인 제거 ### 🔁 출력 없는 액션엔 2번째 LLM 호출 생략 — "빈 응답" 근본 원인 제거
- **문제:** `git 커밋해줘` 한 번에 LLM이 2번 호출됨 — ①`<run_command>` 액션을 뱉는 호출, ②결과를 정리하는 continuation 호출. 2번째가 빈 응답(`eosFound`)으로 실패. - **문제:** `git 커밋해줘` 한 번에 LLM이 2번 호출됨 — ①`<run_command>` 액션을 뱉는 호출, ②결과를 정리하는 continuation 호출. 2번째가 빈 응답(`eosFound`)으로 실패.
+1 -1
View File
@@ -7,5 +7,5 @@
"corePurpose": "", "corePurpose": "",
"detailLevel": "standard", "detailLevel": "standard",
"createdAt": "2026-05-20T09:42:40.003Z", "createdAt": "2026-05-20T09:42:40.003Z",
"updatedAt": "2026-05-22T06:26:09.044Z" "updatedAt": "2026-05-22T07:11:47.201Z"
} }
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "astra", "name": "astra",
"version": "2.2.61", "version": "2.2.62",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "astra", "name": "astra",
"version": "2.2.61", "version": "2.2.62",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@lmstudio/sdk": "^1.5.0", "@lmstudio/sdk": "^1.5.0",
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "astra", "name": "astra",
"displayName": "Astra", "displayName": "Astra",
"description": "The personal intelligence layer for Antigravity and VS Code. A private cognitive partner for deep project context, memory, and proactive strategic decision-making.", "description": "The personal intelligence layer for Antigravity and VS Code. A private cognitive partner for deep project context, memory, and proactive strategic decision-making.",
"version": "2.2.61", "version": "2.2.62",
"publisher": "g1nation", "publisher": "g1nation",
"license": "MIT", "license": "MIT",
"icon": "assets/icon.png", "icon": "assets/icon.png",
+56 -1
View File
@@ -269,7 +269,7 @@ export class AgentExecutor {
} }
private sanitizeAssistantContent(text: string): string { private sanitizeAssistantContent(text: string): string {
return text const stripped = text
.replace(/<rationale>[\s\S]*?<\/rationale>/gi, '') .replace(/<rationale>[\s\S]*?<\/rationale>/gi, '')
.replace(/^\s*\[PROBLEM\][\s\S]*?\[GOAL\][\s\S]*?\[REASONING\][^\n]*(?:\n+|$)/i, '') .replace(/^\s*\[PROBLEM\][\s\S]*?\[GOAL\][\s\S]*?\[REASONING\][^\n]*(?:\n+|$)/i, '')
.replace(/^\s*\[PROBLEM\][\s\S]*?(?:\n\s*\n|$)/i, '') .replace(/^\s*\[PROBLEM\][\s\S]*?(?:\n\s*\n|$)/i, '')
@@ -283,6 +283,54 @@ export class AgentExecutor {
.replace(/<\|?channel\|?>\s*final\b\s*(?:<\|?message\|?>)?/gi, '') .replace(/<\|?channel\|?>\s*final\b\s*(?:<\|?message\|?>)?/gi, '')
.replace(/<\|?(?:end|return|start|message)\|?>/gi, '') .replace(/<\|?(?:end|return|start|message)\|?>/gi, '')
.trim(); .trim();
return this.cleanDegeneratedOutput(stripped);
}
/**
* Contain the blast radius when a small local model degenerates on a long /
* near-full context: runaway character walls, leaked English meta-notes,
* leaked internal directives, stuttered duplicate paragraphs. This does not
* fix the model failure it just keeps a bad answer readable instead of a
* wall of noise.
*/
private cleanDegeneratedOutput(text: string): string {
let s = text;
// Runaway character walls — 8+ of the same separator. A real markdown rule
// is exactly 3 (`---`/`***`/`___`); nothing legitimate repeats a char 8+ times.
s = s.replace(/([_=~.*])\1{7,}/g, '');
// Leaked English meta-commentary the model narrates about itself.
s = s.replace(/\(Note:[^)]*\)/gi, '');
// Leaked project-chronicle directive (inline form — the `## ` heading form is stripped elsewhere).
s = s.replace(/\n?Candidate records for this discussion[^\n]*/gi, '');
// Leaked follow-up-question scaffolding the system prompt forbids.
s = s.replace(/\(\s*질문\s*의도\s*[:][^)]*\)/g, '');
s = s.replace(/\[\s*핵심\s*확인\s*질문\s*\]\s*/g, '');
// Collapse consecutive duplicate paragraphs (model stutter).
const paras = s.split(/\n{2,}/);
const deduped: string[] = [];
for (const p of paras) {
const norm = p.trim().replace(/\s+/g, ' ');
const prevNorm = deduped.length ? deduped[deduped.length - 1].trim().replace(/\s+/g, ' ') : '';
if (norm && norm === prevNorm) { continue; }
deduped.push(p);
}
return deduped.join('\n\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
}
/**
* True when a continuation round restarted the whole answer from the top
* instead of continuing it a small model commonly ignores "continue from
* here". Detected by a shared leading prefix with the answer so far.
*/
private isRestartedAnswer(soFar: string, cont: string): boolean {
const norm = (x: string) => x.trim().replace(/\s+/g, ' ').toLowerCase();
const a = norm(soFar);
const b = norm(cont);
if (a.length < 40 || b.length < 40) { return false; }
let i = 0;
const max = Math.min(a.length, b.length, 80);
while (i < max && a[i] === b[i]) { i++; }
return i >= 12;
} }
private async restoreLastSession() { private async restoreLastSession() {
@@ -1103,6 +1151,13 @@ export class AgentExecutor {
logInfo('Continuation produced no visible text — stopping.', { model: actualModel, round: continuationCount }); logInfo('Continuation produced no visible text — stopping.', { model: actualModel, round: continuationCount });
break; break;
} }
// A weak model often ignores "continue from here" and re-generates the
// whole answer from the top. Discard such a restart instead of merging
// it — otherwise the user gets the entire analysis twice.
if (this.isRestartedAnswer(cleaned.visible, ccl.visible)) {
logInfo('Continuation restarted the answer instead of continuing — discarding it.', { model: actualModel, round: continuationCount });
break;
}
const before = cleaned.visible; const before = cleaned.visible;
cleaned = { ...cleaned, visible: mergeContinuationParts(cleaned.visible, ccl.visible), wasThoughtOnly: false }; cleaned = { ...cleaned, visible: mergeContinuationParts(cleaned.visible, ccl.visible), wasThoughtOnly: false };
lastOutputTokens = estimateTokens(ccl.visible); lastOutputTokens = estimateTokens(ccl.visible);