작업실 기억 프로젝트별 분리 + 기억 재순위 파서 버그 수정 — ① 작업실 대화는 memory/workshop/<프로젝트ID>/에 기록, 추출 때 project 메타를 붙이고, 회상은 그 프로젝트와 _common(K2 등 작업실 공통)만(FTS는 "<workspace>#<project>" 범위). 기존 84건은 프로젝트 9곳 52건·공통 2건·옛 프로젝트 _archive 32건(회상 안 함)으로 태깅. ② rerankCandidates가 Haiku의 "[1],[2],[3]" 답을 parseInt로 못 읽어 재순위를 거치는 회상이 통째로 비던 것(Haiku 전환 10-17부터로 추정) — 숫자만 뽑는 parseRerankIndices. ③ 재순위가 다시 걸러 주므로 일일 추출 기억 거리 문턱 0.55→0.62("우리 집 대지 크기"가 0.607로 빠지던 것), 일상 질문 잡음 증가 없음 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5.5 committed 2026-10-25 12:43:32 +09:00
1 parent ec0c649e44
commit 2909205d0f
6 files changed
+59 -26

No files matched your search

+15 -11
View File
@@ -57,11 +57,13 @@ ${dayContent}
.filter(l => l && l !== '없음');
}
async function processWorkspace(workspace: string, label: string, kind: Kind = 'daily') {
// 작업실(ws_) 대화는 server.ts logToDaily가 memory/workshop/에 따로 쓰고, 여기서 workshop_facts로 간다(2026-10-25).
const memDir = kind === 'workshop' ? path.join(workspace, 'memory', 'workshop') : path.join(workspace, 'memory');
async function processWorkspace(workspace: string, label: string, kind: Kind = 'daily', project = '') {
// 작업실(ws_) 대화는 server.ts logToDaily가 memory/workshop/<프로젝트ID>/에 따로 쓰고, 여기서 workshop_facts로
// 프로젝트 ID를 붙여 간다 — 회상은 그 프로젝트(+ _common)에서만(2026-10-25).
const memDir = kind === 'workshop' ? path.join(workspace, 'memory', 'workshop', project) : path.join(workspace, 'memory');
const collection = kind === 'workshop' ? WORKSHOP_FACTS_COLLECTION : DAILY_EXTRACTS_COLLECTION;
label = kind === 'workshop' ? `${label}/작업실` : label;
const scope: Record<string, string> = kind === 'workshop' ? { project } : {};
label = kind === 'workshop' ? `${label}/작업실/${project}` : label;
if (!fs.existsSync(memDir)) {
console.log(`[${label}] no memory dir, skip`);
return;
@@ -81,7 +83,7 @@ async function processWorkspace(workspace: string, label: string, kind: Kind = '
const content = fs.readFileSync(path.join(memDir, f), 'utf-8').trim();
if (!content) { daysSkipped++; continue; }
if (await hasAnyVector(collection, { workspace, date })) {
if (await hasAnyVector(collection, { workspace, date, ...scope })) {
daysSkipped++;
continue;
}
@@ -92,21 +94,21 @@ async function processWorkspace(workspace: string, label: string, kind: Kind = '
// Record a sentinel so hasAnyVector() sees this date as processed on future reruns —
// otherwise a legitimately fact-free day gets re-sent to the LLM every single rerun.
await addVector(collection, {
id: `${workspace}:${kind === 'workshop' ? 'workshop' : 'daily'}-extract:${date}:none`,
id: `${workspace}:${kind === 'workshop' ? `workshop-extract:${project}` : 'daily-extract'}:${date}:none`,
text: '(해당 날짜에 재사용 가치 있는 사실 없음)',
metadata: { workspace, date, source: kind === 'workshop' ? 'workshop-extract' : 'daily-extract', empty: true },
metadata: { workspace, date, ...scope, source: kind === 'workshop' ? 'workshop-extract' : 'daily-extract', empty: true },
});
} else {
for (let i = 0; i < facts.length; i++) {
const id = `${workspace}:${kind === 'workshop' ? 'workshop' : 'daily'}-extract:${date}:${i}`;
const id = `${workspace}:${kind === 'workshop' ? `workshop-extract:${project}` : 'daily-extract'}:${date}:${i}`;
// 거의 같은 사실이 이미 있으면 다시 넣지 않는다(2026-10-25: 대시보드 주소 6개·서버 사양 20여 개가 날마다 쌓임).
const dup = await findNearDuplicate(collection, facts[i], workspace).catch(() => null)
const dup = await findNearDuplicate(collection, facts[i], workspace, scope).catch(() => null)
|| await findNearDuplicate(USER_FACTS_COLLECTION, facts[i], workspace).catch(() => null);
if (dup) { dupSkipped++; continue; }
await addVector(collection, {
id,
text: facts[i],
metadata: { workspace, date, source: kind === 'workshop' ? 'workshop-extract' : 'daily-extract' },
metadata: { workspace, date, ...scope, source: kind === 'workshop' ? 'workshop-extract' : 'daily-extract' },
});
}
}
@@ -125,7 +127,9 @@ async function processWorkspace(workspace: string, label: string, kind: Kind = '
async function main() {
for (const { workspace, label } of WORKSPACES) {
await processWorkspace(workspace, label);
await processWorkspace(workspace, label, 'workshop');
const wsRoot = path.join(workspace, 'memory', 'workshop');
const projects = fs.existsSync(wsRoot) ? fs.readdirSync(wsRoot, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name) : [];
for (const project of projects) await processWorkspace(workspace, label, 'workshop', project);
}
}
+7 -3
View File
@@ -9,6 +9,7 @@ import {
DAILY_EXTRACTS_COLLECTION,
WORKSHOP_FACTS_COLLECTION,
dedupeFacts,
ftsScope,
} from '../memory/memory-vector';
import { keywordSearch } from '../memory/memory-fts';
import { rerankCandidates } from '../memory/memory-rerank';
@@ -435,18 +436,21 @@ return async function buildPersonalityContext(
// 작업실 기억(workshop_facts)은 작업실 채팅(ws_)에서만 — 메인 채팅 회상과 섞지 않는다(2026-10-25).
// 작업실에선 프로젝트 기억을 일일 추출 기억과 같은 칸(더 엄격한 거리 기준)에 합쳐 넣는다.
const isWorkshop = /^ws_/.test(String(sessionId || ''));
// 프로젝트별(ws_<프로젝트ID>) — 그 프로젝트와 작업실 공통(_common)만. 옛 프로젝트(_archive)는 회상 안 함.
const wsProject = String(sessionId || '').slice(3);
const wsProjects = [wsProject, '_common'];
const [userFactHits, dailyHits, workshopHits] = await Promise.all([
queryVectorsWithEmbedding(USER_FACTS_COLLECTION, queryEmbedding, 15, { workspace: workspacePath }),
queryVectorsWithEmbedding(DAILY_EXTRACTS_COLLECTION, queryEmbedding, 15, { workspace: workspacePath }),
isWorkshop
? queryVectorsWithEmbedding(WORKSHOP_FACTS_COLLECTION, queryEmbedding, 15, { workspace: workspacePath }).catch(() => [])
? queryVectorsWithEmbedding(WORKSHOP_FACTS_COLLECTION, queryEmbedding, 15, { workspace: workspacePath, project: { $in: wsProjects } }).catch(() => [])
: Promise.resolve([]),
]);
const dailyExtractHits = [...dailyHits, ...workshopHits];
const keywordHits = [
...keywordSearch(USER_FACTS_COLLECTION, messageText, 15, workspacePath),
...keywordSearch(DAILY_EXTRACTS_COLLECTION, messageText, 15, workspacePath),
...(isWorkshop ? keywordSearch(WORKSHOP_FACTS_COLLECTION, messageText, 15, workspacePath) : []),
...(isWorkshop ? wsProjects.flatMap(p => keywordSearch(WORKSHOP_FACTS_COLLECTION, messageText, 15, ftsScope(workspacePath, p))) : []),
];
// Thresholds recalibrated for EmbeddingGemma's wider distance spread (2026-07-24 switch
@@ -461,7 +465,7 @@ return async function buildPersonalityContext(
.sort((a, b) => a.distance - b.distance));
const byDistanceThreshold = dedupeFacts([
...userFactHits.filter(h => h.distance < 0.65),
...dailyExtractHits.filter(h => h.distance < 0.55 && !h.metadata?.empty),
...dailyExtractHits.filter(h => h.distance < 0.62 && !h.metadata?.empty),
].sort((a, b) => a.distance - b.distance)).slice(0, 8);
// Merge vector + keyword candidates, deduped by id (vector hits win the text on overlap —
+12 -5
View File
@@ -31,6 +31,17 @@ function getOllamaEndpoint(): string {
// Returns the subset of candidate ids that are actually relevant, ranked best-first,
// capped at topK. Returns null (not []) on failure so callers can distinguish "reranked,
// turned out nothing was relevant" from "reranking itself didn't happen."
/**
* 재순위 모델 답에서 후보 번호를 뽑는다 — 숫자만 본다. Haiku는 "[1],[2],[3]"처럼 괄호를 붙여 답해 쉼표로 나눠
* parseInt하던 옛 방식이 전부 NaN → 회상이 통째로 비었다(2026-10-25 발견, Haiku 전환 10-17부터로 추정).
*/
export function parseRerankIndices(raw: string, count: number): number[] {
const seen = new Set<number>();
return (String(raw).match(/\d+/g) || [])
.map(s => parseInt(s, 10))
.filter(n => n < count && !seen.has(n) && !!seen.add(n));
}
export async function rerankCandidates(query: string, candidates: RerankCandidate[], topK: number): Promise<string[] | null> {
if (candidates.length === 0) return [];
const listText = candidates.map((c, i) => `[${i}] ${c.text}`).join('\n');
@@ -47,11 +58,7 @@ ${listText}`;
if (raw === null) throw new Error('rerank call failed');
if (!raw || raw === '없음') return [];
const seen = new Set<number>();
const indices = raw
.split(',')
.map(s => parseInt(s.trim(), 10))
.filter(n => Number.isInteger(n) && n >= 0 && n < candidates.length && !seen.has(n) && seen.add(n));
const indices = parseRerankIndices(raw, candidates.length);
return indices.slice(0, topK).map(i => candidates[i].id);
} catch (err: any) {
console.warn('[memory-rerank] rerank failed (falling back to distance-threshold):', err.message);
+11 -6
View File
@@ -105,13 +105,18 @@ async function getCollection(name: string): Promise<Collection> {
// exactly one operator, but got 2" (verified 2026-07-24). Callers write plain flat objects;
// this wraps them in $and automatically so they don't all need to know Chroma's where-clause
// quirks.
function toChromaWhere(where?: Record<string, string | number | boolean>): any {
function toChromaWhere(where?: Record<string, any>): any {
if (!where) return undefined;
const keys = Object.keys(where);
if (keys.length <= 1) return where;
return { $and: keys.map(k => ({ [k]: where[k] })) };
}
/** FTS 미러의 workspace 칸 — 작업실 기억은 프로젝트별로 갈라 찾도록 "<workspace>#<project>"(2026-10-25). */
export function ftsScope(workspace: string, project?: string): string {
return project ? `${workspace}#${project}` : workspace;
}
export interface MemoryVectorRecord {
id: string;
text: string;
@@ -130,7 +135,7 @@ export async function addVector(collectionName: string, rec: MemoryVectorRecord)
// Keyword-search mirror for hybrid retrieval (see memory-fts.ts) — kept best-effort:
// a write failing here must not fail the vector write it's piggybacking on.
try {
upsertFtsRecord(collectionName, rec.id, rec.text, String(rec.metadata?.workspace || ''));
upsertFtsRecord(collectionName, rec.id, rec.text, ftsScope(String(rec.metadata?.workspace || ''), rec.metadata?.project as string | undefined));
} catch (err: any) {
console.warn('[memory-vector] FTS mirror write failed (non-fatal):', err.message);
}
@@ -180,10 +185,10 @@ export function dedupeFacts<T extends { text: string }>(hits: T[]): T[] {
return out;
}
/** 저장 전 확인: 같은 workspace에 거의 같은 사실이 이미 있으면 그 항목을 돌려준다. */
export async function findNearDuplicate(collectionName: string, text: string, workspace: string): Promise<MemoryVectorHit | null> {
export async function findNearDuplicate(collectionName: string, text: string, workspace: string, extraWhere: Record<string, any> = {}): Promise<MemoryVectorHit | null> {
const col = await getCollection(collectionName);
const embedding = await embedText(text, 'document');
const res = await col.query({ queryEmbeddings: [embedding], nResults: 3, where: { workspace } as any });
const res = await col.query({ queryEmbeddings: [embedding], nResults: 3, where: toChromaWhere({ workspace, ...extraWhere }) });
const docs = res.documents?.[0] || [];
for (let i = 0; i < docs.length; i++) {
const dist = res.distances?.[0]?.[i] ?? Infinity;
@@ -203,7 +208,7 @@ export async function queryVectorsWithEmbedding(
collectionName: string,
embedding: number[],
topK = 6,
where?: Record<string, string | number | boolean>,
where?: Record<string, any>,
): Promise<MemoryVectorHit[]> {
const col = await getCollection(collectionName);
const res = await col.query({ queryEmbeddings: [embedding], nResults: topK, where: toChromaWhere(where) });
@@ -223,7 +228,7 @@ export async function queryVectorsWithEmbedding(
// skip already-processed items without needing to know their exact IDs up front.
export async function hasAnyVector(
collectionName: string,
where: Record<string, string | number | boolean>,
where: Record<string, any>,
): Promise<boolean> {
const col = await getCollection(collectionName);
const res = await col.get({ where: toChromaWhere(where), limit: 1 });
+5 -1
View File
@@ -1255,7 +1255,11 @@ function logToDaily(workspacePath: string, role: string, content: string, sessio
if (sessionId && /^(dt_|dr_|lw_)/.test(sessionId)) return;
try {
// 작업실(ws_) 대화는 memory/workshop/에 따로 — 밤마다 workshop_facts로 추출(scripts/extract-daily-memory.ts).
const memDir = sessionId && sessionId.startsWith('ws_') ? path.join(workspacePath, 'memory', 'workshop') : path.join(workspacePath, 'memory');
// 프로젝트별 폴더(ws_<프로젝트ID> → memory/workshop/<프로젝트ID>/, 프로젝트 없는 작업실은 _common).
const wsProject = sessionId && sessionId.startsWith('ws_') ? (sessionId.slice(3).replace(/[^A-Za-z0-9_-]/g, '') || '_common') : '';
const memDir = wsProject
? path.join(workspacePath, 'memory', 'workshop', wsProject === 'noproject' ? '_common' : wsProject)
: path.join(workspacePath, 'memory');
if (!fs.existsSync(memDir)) fs.mkdirSync(memDir, { recursive: true });
const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
+9
View File
@@ -59,3 +59,12 @@ describe('비공개 앱은 장기 기억에 쓰지 않는다(10-25)', () => {
assert.equal(on('4545cbaf-x'), true);
});
});
import { parseRerankIndices } from '../src/gateway/memory/memory-rerank';
describe('parseRerankIndices', () => {
test('괄호 붙은 Haiku 답(10-25 실측)과 평범한 답 모두', () => {
assert.deepEqual(parseRerankIndices('[1],[2],[3],[5],[7],[13],[14],[0]', 15), [1, 2, 3, 5, 7, 13, 14, 0]);
assert.deepEqual(parseRerankIndices('2,0,5', 6), [2, 0, 5]);
assert.deepEqual(parseRerankIndices('3, 3, 9', 5), [3]);
});
});