133 lines
7.2 KiB
TypeScript
133 lines
7.2 KiB
TypeScript
// Backfill: LLM-extract atomic, reusable facts from raw daily conversation logs and store them
|
|
// in the daily_extracts Chroma collection (separate from memory_write's clean user_facts
|
|
// collection — see project_vector_memory_chroma memory for why). Naive paragraph-chunking of
|
|
// raw transcripts was tried first and abandoned (too noisy, see migrate-memory-to-chroma.ts) —
|
|
// this replaces that approach with real extraction.
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { lightChat } from '../src/providers/light-chat';
|
|
import { addVector, hasAnyVector, findNearDuplicate, DAILY_EXTRACTS_COLLECTION, USER_FACTS_COLLECTION, WORKSHOP_FACTS_COLLECTION } from '../src/gateway/memory/memory-vector';
|
|
|
|
const WORKSPACES: { workspace: string; label: string }[] = [
|
|
{ workspace: '/srv/homeclaw/.smallclaw/users/papa/workspace', label: 'papa' },
|
|
{ workspace: '/srv/homeclaw/.smallclaw/users/jasmine/workspace', label: 'jasmine' },
|
|
{ workspace: '/srv/homeclaw/.smallclaw/users/cherry/workspace', label: 'cherry' },
|
|
{ workspace: '/srv/homeclaw/.smallclaw/workspace', label: 'global' },
|
|
];
|
|
|
|
|
|
type Kind = 'daily' | 'workshop';
|
|
|
|
async function extractFacts(dayContent: string, kind: Kind = 'daily'): Promise<string[]> {
|
|
const prompt = kind === 'workshop' ? `다음은 하루치 "작업실"(메이커 프로젝트) 대화 로그입니다. 나중에 다시 참고할 가치가 있는 프로젝트 사실만 뽑아줘.
|
|
|
|
규칙:
|
|
- 프로젝트 이름을 꼭 붙여서: 부품과 그 상태(보유·주문), 실측 치수, 핀·배선, 설계 결정과 이유, 파일(SCAD/STL) 이름과 역할, 출력 설정과 결과
|
|
- 일반 지식·웹 검색 결과(사지 않은 부품의 스펙·가격 등)와 일회성 잡담은 제외
|
|
- 로그에 없는 것을 짐작해 쓰지 말고, "로그에 기록되지 않음" 같은 메모도 쓰지 마
|
|
- 각 사실은 한 줄에 하나씩, 문맥 없이도 이해되는 완결된 문장으로
|
|
- 뽑을 게 없으면 "없음"이라고만 답해
|
|
- 사실 목록 외의 설명이나 서두는 쓰지 마
|
|
|
|
--- 로그 시작 ---
|
|
${dayContent}
|
|
--- 로그 끝 ---` : `다음은 하루치 대화 로그입니다. 이 중에서 나중에 다시 참고할 가치가 있는 사실만 뽑아줘.
|
|
|
|
규칙:
|
|
- 사용자 본인에 관한 것만: 사용자·가족·집, 사용자가 가진 기기·서버의 사양과 설정값, 진행 중인 프로젝트와 그 결정사항, 취향·제약·일정
|
|
- 일반 지식과 웹 검색 결과는 제외 — 사용자가 갖고 있지 않은 제품의 스펙·가격·출시일, 뉴스·통계·논문 내용·역사 등은 다시 검색하면 되고 시간이 지나면 낡는다
|
|
- 일회성 질문-답변, 잡담, 이미 끝난 계산/설명은 제외
|
|
- 로그에 없는 것을 짐작해 쓰지 말고, "로그에 기록되지 않음" 같은 메모도 쓰지 마
|
|
- 각 사실은 한 줄에 하나씩, 문맥 없이도 이해되는 완결된 문장으로 작성 (예: "클로서버는 RTX 3060 12GB 2개를 사용한다" 처럼 — 어느 대상 얘기인지 반드시 명시)
|
|
- 뽑을 게 없으면 "없음"이라고만 답해
|
|
- 사실 목록 외의 설명이나 서두는 쓰지 마
|
|
|
|
--- 로그 시작 ---
|
|
${dayContent}
|
|
--- 로그 끝 ---`;
|
|
|
|
// 활성 provider의 싼 모델로(올라마 직접 호출 제거) — 실패하면 던져서 그 날을 '실패'로 세고 다음 실행에서 다시 시도한다
|
|
const raw = await lightChat([{ role: 'user', content: prompt }], { max_tokens: 2000, temperature: 0.1, timeoutMs: 120_000 });
|
|
if (raw === null) throw new Error('extract LLM call failed');
|
|
if (!raw || raw === '없음') return [];
|
|
|
|
return raw
|
|
.split('\n')
|
|
.map(l => l.trim().replace(/^[-*]\s*/, ''))
|
|
.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');
|
|
const collection = kind === 'workshop' ? WORKSHOP_FACTS_COLLECTION : DAILY_EXTRACTS_COLLECTION;
|
|
label = kind === 'workshop' ? `${label}/작업실` : label;
|
|
if (!fs.existsSync(memDir)) {
|
|
console.log(`[${label}] no memory dir, skip`);
|
|
return;
|
|
}
|
|
// Never process today's file — it's still being written to during the day, so extracting
|
|
// it early would capture a partial day and then skip it forever (hasAnyVector marks it
|
|
// "done"). A nightly cron run naturally picks up "yesterday" once it's actually complete.
|
|
const today = new Date().toISOString().slice(0, 10);
|
|
const dailyFiles = fs.readdirSync(memDir)
|
|
.filter(f => /^\d{4}-\d{2}-\d{2}\.md$/.test(f))
|
|
.filter(f => f.replace('.md', '') < today)
|
|
.sort();
|
|
let totalFacts = 0, daysProcessed = 0, daysSkipped = 0, daysFailed = 0, dupSkipped = 0;
|
|
|
|
for (const f of dailyFiles) {
|
|
const date = f.replace('.md', '');
|
|
const content = fs.readFileSync(path.join(memDir, f), 'utf-8').trim();
|
|
if (!content) { daysSkipped++; continue; }
|
|
|
|
if (await hasAnyVector(collection, { workspace, date })) {
|
|
daysSkipped++;
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
const facts = await extractFacts(content, kind);
|
|
if (facts.length === 0) {
|
|
// 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`,
|
|
text: '(해당 날짜에 재사용 가치 있는 사실 없음)',
|
|
metadata: { workspace, date, 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}`;
|
|
// 거의 같은 사실이 이미 있으면 다시 넣지 않는다(2026-10-25: 대시보드 주소 6개·서버 사양 20여 개가 날마다 쌓임).
|
|
const dup = await findNearDuplicate(collection, facts[i], workspace).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' },
|
|
});
|
|
}
|
|
}
|
|
totalFacts += facts.length;
|
|
daysProcessed++;
|
|
console.log(`[${label}] ${date}: ${facts.length}개 추출`);
|
|
} catch (err: any) {
|
|
daysFailed++;
|
|
console.warn(`[${label}] ${date} 실패: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
console.log(`[${label}] 완료 — ${daysProcessed}일 처리, ${totalFacts}개 사실, ${daysSkipped}일 스킵(빈파일), ${daysFailed}일 실패, 중복 ${dupSkipped}개 건너뜀`);
|
|
}
|
|
|
|
async function main() {
|
|
for (const { workspace, label } of WORKSPACES) {
|
|
await processWorkspace(workspace, label);
|
|
await processWorkspace(workspace, label, 'workshop');
|
|
}
|
|
}
|
|
|
|
main().then(() => process.exit(0)).catch(err => { console.error(err); process.exit(1); });
|