import { normalizeTopicPart } from './codec.js'; import { retainFactCandidate } from './factCandidates.js'; import { memoryService, MemoryTopicConflictError } from './memoryService.js'; import { saveProjectKnowledge, type ProjectKnowledgeDraft, } from './projectKnowledge.js'; /** Both extractors route user decisions here. Keep a legacy/explicit workspace * decision authoritative if one already exists; don't create a shadow in the * knowledge partition. Existing records are never overwritten by a model. */ export async function saveUserProjectClaim( workspaceId: string, input: ProjectKnowledgeDraft, signal: AbortSignal | undefined, guard: { startedAt: number }, ): Promise<{ record?: { id: string }; candidateId?: string; blocked?: { dismissedId: string; reason: string }; excluded?: string; }> { const proof = input.provenance[0]; if (!proof?.quote) throw new Error('项目决定缺少用户证据'); const names = new Set( [input.subject, ...input.aliases].map(normalizeTopicPart), ); const existing = (await memoryService.snapshot(workspaceId)).records.filter( (r) => r.scope === 'workspace' && r.workspaceId === workspaceId && r.status !== 'superseded' && (!r.validUntil || r.validUntil > Date.now()) && (r.category === 'project' || r.category === 'decision') && [r.subject, ...r.aliases].some((n) => names.has(normalizeTopicPart(n))), ); const first = existing[0]; if (!first) return saveProjectKnowledge(workspaceId, input, signal, guard); if (first.sensitivity !== 'normal' || existing.length > 1) return { excluded: '现有项目决定需要人工消歧或确认敏感项' }; const draft = { scope: 'workspace' as const, workspaceId, category: first.category, subject: first.subject, statement: input.statement, aliases: input.aliases, evidence: 'user_stated' as const, evidenceQuote: proof.quote, sourceAnchor: proof.sourceAnchor, sourceSessionId: proof.sessionId, sourceMessageId: proof.turnId, sensitivity: 'normal' as const, }; try { return { record: await memoryService.remember(draft, { ...guard, sourceWorkspaceId: workspaceId, signal, }), }; } catch (error) { if (!(error instanceof MemoryTopicConflictError)) throw error; const old = await memoryService.readWithVersion( error.recordId, 'workspace', workspaceId, ); return { candidateId: await retainFactCandidate( workspaceId, draft, error.message, old ?? undefined, guard.startedAt, signal, ), }; } }