/** Durable project facts are neither user preferences nor troubleshooting * experiences. They record confirmed architecture decisions and tool-verified * build/runtime facts, with dependencies that make staleness observable. */ import { randomUUID } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { z } from 'zod'; import { containsForbiddenSecret, normalizeTopicPart, sha256, } from './codec.js'; import { type Dependencies, checkDependencies, dependencySchema, } from './dependencies.js'; import { acquireFileLock, atomicWriteFile, globalMemoryDir, scopeDirectory, } from './fileStore.js'; import { memoryTerms } from './retrieval.js'; import { sourceAnchor } from './automaticPolicy.js'; import { withFactBarriers } from './factGovernance.js'; export const projectKnowledgeKindSchema = z.enum([ 'architecture', 'technology', 'test', 'build', 'deployment', 'constraint', ]); const provenanceSchema = z.object({ type: z.enum([ 'user_stated', 'user_confirmed', 'agent_proposed', 'agent_inferred', 'tool_verified', ]), sessionId: z.string(), turnId: z.string(), quote: z.string().max(1200).optional(), sourceAnchor: z.string().optional(), evidenceIds: z.array(z.string()).max(12).optional(), }); const recordSchema = z.object({ id: z.string().uuid(), scope: z.enum(['workspace', 'global']), workspaceId: z.string().optional(), kind: projectKnowledgeKindSchema, subject: z.string().min(1).max(120), statement: z.string().min(1).max(1500), applicability: z.string().min(1).max(1000), aliases: z.array(z.string().max(120)).max(20).default([]), status: z.enum(['active', 'needs_review', 'superseded']), revision: z.number().int().positive(), provenance: z.array(provenanceSchema).min(1), dependencies: dependencySchema.optional(), createdAt: z.number(), updatedAt: z.number(), lastVerifiedAt: z.number().optional(), supersedesIds: z.array(z.string().uuid()).default([]), /** Set when a user explicitly dismissed this record via MemoryMaintenance * dismiss — distinct from a topic-conflict supersession (supersedesIds). */ dismissedReason: z.string().optional(), }); const candidateSchema = z.object({ id: z.string(), status: z.enum(['open', 'accepted', 'rejected']), reason: z.string(), createdAt: z.number(), oldId: z.string().uuid(), oldRevision: z.number().int(), oldStatement: z.string(), proposed: recordSchema.omit({ id: true, revision: true, status: true, createdAt: true, updatedAt: true, supersedesIds: true, }), }); const storeSchema = z.object({ version: z.literal(1), revision: z.number().int(), clearedAt: z.number().default(0), records: z.array(recordSchema), candidates: z.array(candidateSchema), }); export type ProjectKnowledge = z.infer & { dependencyWarning?: string[]; /** Whole days since this was last verified, set only once it is overdue. */ unverifiedDays?: number; }; /** Matches the `project` review window users already see in memory settings. */ export const KNOWLEDGE_REVIEW_DAYS = 90; /** * Knowledge with a dependency snapshot learns when it went stale from the * files themselves; a deployment convention or a decision has none, so without * this it stayed "active" forever however long ago anyone checked it. */ export function unverifiedDays(item: ProjectKnowledge, now = Date.now()): number | undefined { if (item.dependencies) return undefined; const days = Math.floor((now - (item.lastVerifiedAt ?? item.createdAt)) / 86_400_000); return days >= KNOWLEDGE_REVIEW_DAYS ? days : undefined; } export type ProjectKnowledgeDraft = z.infer['proposed']; export type ProjectKnowledgeCandidate = z.infer; type Store = z.infer; export type ProjectKnowledgeSnapshot = Store; export const parseProjectKnowledgeSnapshot = ( input: unknown, ): ProjectKnowledgeSnapshot => storeSchema.parse(input); const pathFor = (scope: 'workspace' | 'global', workspaceId?: string) => join( scope === 'global' ? globalMemoryDir() : scopeDirectory('workspace', workspaceId), 'project-knowledge.json', ); const empty = (): Store => ({ version: 1, revision: 0, clearedAt: 0, records: [], candidates: [], }); async function readStore( scope: 'workspace' | 'global', workspaceId?: string, ): Promise { const raw = await readFile(pathFor(scope, workspaceId), 'utf8').catch( (error) => { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; return ''; }, ); return raw ? storeSchema.parse(JSON.parse(raw)) : empty(); } export async function snapshotProjectKnowledge( workspaceId: string, ): Promise { return structuredClone(await readStore('workspace', workspaceId)); } /** Restore a maintenance-owned batch only when nobody has touched the * partition since that batch. Revision remains monotonic. */ export async function restoreProjectKnowledgeSnapshot( workspaceId: string, snapshot: ProjectKnowledgeSnapshot, expectedRevision: number, ): Promise { await mutate('workspace', workspaceId, (store) => { if (store.revision !== expectedRevision) throw new Error('PROJECT_KNOWLEDGE_ROLLBACK_CONFLICT'); store.records = structuredClone(snapshot.records); store.candidates = structuredClone(snapshot.candidates); store.clearedAt = Math.max(store.clearedAt, snapshot.clearedAt); }); } async function mutate( scope: 'workspace' | 'global', workspaceId: string | undefined, operation: (store: Store) => void | Promise, signal?: AbortSignal, ): Promise { const path = pathFor(scope, workspaceId); const release = await acquireFileLock(path, signal); try { const store = await readStore(scope, workspaceId); await operation(store); store.revision++; signal?.throwIfAborted(); await atomicWriteFile(path, `${JSON.stringify(store)}\n`); } finally { await release(); } } const sameTopic = ( record: Pick, draft: Pick, ) => { if (record.kind !== draft.kind) return false; const values = new Set( [draft.subject, ...draft.aliases].map(normalizeTopicPart), ); return [record.subject, ...record.aliases].some((value) => values.has(normalizeTopicPart(value)), ); }; /** * Forget gate, mirroring factGovernance.ts's role for the user-fact partition. * * `dismiss` soft-deletes by setting `superseded`, and every dedupe path in this * file filters superseded records out — so without this gate a background * learning run re-proposing the same fact lands in applyDraft's "no current * record" branch and creates a brand-new `active` record. The user's explicit * deletion is undone with no candidate, no conflict and no trace. * * ⚠️ The gate must NOT work by making dismissed records visible to applyDraft's * `current` lookup: that routes the re-proposal into the candidate path, and * `resolveProjectKnowledgeCandidate` with decision:'reject' sets * `current.status = 'active'` — resurrecting the very record just dismissed. * Refusing up front is the only route that cannot resurrect. * * Scope is deliberately narrow: same topic AND a byte-identical statement * (whitespace/width-normalized). Dismissing one wrong conclusion must not * blacklist the whole subject — the learner stays free to record something * genuinely different about it, which is why this matches on the statement * rather than on topic alone the way blockFact does for personal facts. */ const normalizeStatement = (value: string) => value.normalize('NFKC').trim().toLowerCase().replace(/\s+/g, ''); function dismissedMatch( store: Store, draft: ProjectKnowledgeDraft, ): ProjectKnowledge | undefined { return store.records.find( (item) => item.status === 'superseded' && item.dismissedReason && sameTopic(item, draft) && normalizeStatement(item.statement) === normalizeStatement(draft.statement), ); } type SaveResult = { record?: ProjectKnowledge; candidateId?: string; /** Set when the forget gate refused an automatic re-proposal. Callers must * surface it; a silent skip looks identical to "nothing was proposed". */ blocked?: { dismissedId: string; reason: string }; }; const parseDraft = (workspaceId: string, input: ProjectKnowledgeDraft) => candidateSchema.shape.proposed.parse({ ...input, scope: input.scope ?? 'workspace', workspaceId: input.scope === 'global' ? undefined : workspaceId, }); function applyDraft( store: Store, draft: ProjectKnowledgeDraft, guard?: { startedAt: number }, ): SaveResult { if (guard && store.clearedAt >= guard.startedAt) throw new Error('LEARNING_SOURCE_CHANGED:项目事实已被清空'); const result: { record?: ProjectKnowledge; candidateId?: string } = {}; let linked: ProjectKnowledge | undefined; if (guard) { // The same user evidence can arrive via the live learner and the historical // pipeline. A different title/kind from the second model is not a new fact. const anchors = new Set(draft.provenance.map(p => p.sourceAnchor).filter(Boolean)); const prior = anchors.size ? store.records.find(r => (r.status !== 'superseded' || r.dismissedReason) && r.provenance.some(p => p.sourceAnchor && anchors.has(p.sourceAnchor)) && normalizeStatement(r.statement) === normalizeStatement(draft.statement) && normalizeStatement(r.applicability) === normalizeStatement(draft.applicability)) : undefined; if (prior?.dismissedReason) return {blocked: {dismissedId: prior.id, reason: prior.dismissedReason}}; linked = prior; } const current = store.records.find( (item) => item.status !== 'superseded' && sameTopic(item, draft), ) ?? linked; const now = Date.now(); if ( current && normalizeStatement(current.statement) === normalizeStatement(draft.statement) && normalizeStatement(current.applicability) === normalizeStatement(draft.applicability) ) { const seen = new Set( current.provenance.map((item) => sha256(JSON.stringify(item))), ); current.provenance.push( ...draft.provenance.filter( (item) => !seen.has(sha256(JSON.stringify(item))), ), ); current.dependencies = draft.dependencies ?? current.dependencies; current.lastVerifiedAt = draft.provenance.some( (item) => item.type === 'tool_verified', ) ? now : current.lastVerifiedAt; current.updatedAt = now; current.revision++; result.record = current; return result; } if (current) { const signature = (value: ProjectKnowledgeDraft) => sha256( JSON.stringify([ value.statement, value.applicability, value.aliases, value.dependencies, value.provenance, ]), ); const proposedSignature = signature(draft); const existing = store.candidates.find( (item) => item.status === 'open' && item.oldId === current.id && signature(item.proposed) === proposedSignature, ); if (existing) { result.candidateId = existing.id; return result; } const id = sha256( JSON.stringify([current.id, current.revision, proposedSignature]), ); store.candidates.push({ id, status: 'open', reason: '同主题项目事实发生变化,需要结合当前代码或用户确认处理', createdAt: now, oldId: current.id, oldRevision: current.revision, oldStatement: current.statement, proposed: draft, }); const open = store.candidates.filter((item) => item.status === 'open'); const resolved = store.candidates .filter((item) => item.status !== 'open') .slice(-200); store.candidates = [...open, ...resolved]; if (current.status !== 'needs_review') { current.status = 'needs_review'; current.updatedAt = now; current.revision++; } result.candidateId = id; return result; } // Only automatic runs carry `guard`. An explicit user/model save (e.g. // promoteExperienceKnowledge) passes none and is never gated — dismiss must // stop the background learner from undoing a deletion, not stop the user // from changing their mind. if (guard) { const dismissed = dismissedMatch(store, draft); if (dismissed) return { blocked: { dismissedId: dismissed.id, reason: dismissed.dismissedReason ?? '用户已撤销该项目事实', }, }; } const record = recordSchema.parse({ ...draft, id: randomUUID(), status: 'active', revision: 1, createdAt: now, updatedAt: now, lastVerifiedAt: draft.provenance.some( (item) => item.type === 'tool_verified', ) ? now : undefined, supersedesIds: [], }); store.records.push(record); result.record = record; return result; } export async function saveProjectKnowledge( workspaceId: string, input: ProjectKnowledgeDraft, signal?: AbortSignal, guard?: { startedAt: number }, ): Promise { const draft = parseDraft(workspaceId, input); if (containsForbiddenSecret(JSON.stringify(draft))) throw new Error('项目事实含敏感信息,未保存'); let result: SaveResult = {}; const write = () => mutate( draft.scope, draft.scope === 'workspace' ? workspaceId : undefined, (store) => { result = applyDraft(store, draft, guard); }, signal, ); const anchors = draft.provenance.filter(p => p.type === 'user_stated' || p.type === 'user_confirmed') .map(p => p.sourceAnchor ?? sourceAnchor(p.sessionId,p.turnId,p.quote ?? '')).filter(Boolean); if ((guard || draft.scope === 'global') && anchors.length) { const allowed = await withFactBarriers('workspace', workspaceId, async ws => withFactBarriers('personal', undefined, async personal => { if (anchors.some(a => ws.blocked.includes('anchor:' + a) || personal.blocked.includes('anchor:' + a))) return false; await write(); return true; })); if (!allowed) return {blocked: {dismissedId: 'source', reason: '用户已遗忘该证据'}}; } else await write(); return result; } /** Remove only directly attributable user evidence. A separately verified * record survives with its independent provenance; never delete by similarity. */ export async function purgeKnowledgeSource(workspaceId: string | undefined, anchors: readonly string[]) { const scope = workspaceId === undefined ? 'global' : 'workspace'; const matches = (p: ProjectKnowledge['provenance'][number]) => ['user_stated','user_confirmed'].includes(p.type) && anchors.includes(p.sourceAnchor ?? sourceAnchor(p.sessionId,p.turnId,p.quote ?? '') ?? ''); const prior = await readStore(scope, workspaceId); if (!prior.records.some(r => r.provenance.some(matches)) && !prior.candidates.some(c => c.proposed.provenance.some(matches))) return false; await mutate(scope, workspaceId, store => { const removed = new Set(); for (const r of store.records) { if (!r.provenance.some(matches)) continue; r.provenance = r.provenance.filter(p => !matches(p)); // Promotion appends an applicability proposal, not an independent source // for the underlying assertion. if (!r.provenance.some(p => p.type !== 'agent_proposed')) removed.add(r.id); else r.revision++; } store.records = store.records.filter(r => !removed.has(r.id)); store.candidates = store.candidates.filter(c => !removed.has(c.oldId) && !c.proposed.provenance.some(matches)); }); return true; } /** Commit one maintenance proposal to a workspace partition with one lock and * one atomic file replacement. No valid prefix can leak when a later item fails. */ export async function saveProjectKnowledgeBatch( workspaceId: string, inputs: ProjectKnowledgeDraft[], signal?: AbortSignal, guard?: { startedAt: number }, beforeCommit?: (before: ProjectKnowledgeSnapshot, after: ProjectKnowledgeSnapshot) => Promise, ): Promise<{ results: SaveResult[]; before: ProjectKnowledgeSnapshot; afterRevision: number; }> { const drafts = inputs.map((input) => parseDraft(workspaceId, input)); if (drafts.some((draft) => draft.scope !== 'workspace')) throw new Error('项目事实批次只能写入当前工作区'); if (containsForbiddenSecret(JSON.stringify(drafts))) throw new Error('项目事实含敏感信息,未保存'); let before = empty(); let results: SaveResult[] = []; await mutate( 'workspace', workspaceId, async (store) => { before = structuredClone(store); results = drafts.map((draft) => applyDraft(store, draft, guard)); await beforeCommit?.(before, { ...structuredClone(store), revision: store.revision + 1 }); }, signal, ); return { results, before, afterRevision: before.revision + 1 }; } export async function projectKnowledgeStatus(workspaceId: string) { await (await import('./experienceStore.js')).recoverLearningTransaction(workspaceId); const [workspace, global] = await Promise.all([ readStore('workspace', workspaceId), readStore('global'), ]); return { records: [...global.records, ...workspace.records], candidates: [...global.candidates, ...workspace.candidates], }; } export async function recallProjectKnowledge( workspaceId: string, query: string, limit = 5, ): Promise { if (!query.trim()) return []; const { records } = await projectKnowledgeStatus(workspaceId); const terms = memoryTerms(query); const selected = records .filter((item) => item.status !== 'superseded') .map((item) => ({ item, score: terms.reduce( (sum, term) => sum + (JSON.stringify([ item.subject, item.statement, item.applicability, item.aliases, ]) .normalize('NFKC') .toLowerCase() .includes(term) ? 1 : 0), 0, ) * (item.status === 'needs_review' ? 0.4 : 1) * (item.scope === 'workspace' ? 1.2 : 1), })) .filter((item) => item.score > 0) .sort((a, b) => b.score - a.score || b.item.updatedAt - a.item.updatedAt) .slice(0, Math.max(0, limit) + Math.min(Math.max(0, limit), 8)); const checked = await Promise.all( selected.map(async ({ item }) => ({ ...item, dependencyWarning: item.dependencies ? await checkDependencies(item.dependencies) : [], unverifiedDays: unverifiedDays(item), })), ); const stale = (item: typeof checked[number]) => +(!!item.dependencyWarning.length || !!item.unverifiedDays || item.status === 'needs_review'); return checked.sort((a,b) => stale(a) - stale(b)).slice(0, limit); } /** * Same rule as fact candidates (factCandidates.ts::isLiveFactCandidate): a * candidate proposes replacing one exact statement of one live record. Once * that record is dismissed, replaced or rewritten, the candidate is history — * surfacing it put a dismissed statement back into prompts as "旧=…". */ export function isLiveKnowledgeCandidate( item: ProjectKnowledgeCandidate, records: readonly Pick[], ): boolean { if (item.status !== 'open') return false; const current = records.find((record) => record.id === item.oldId); return ( current !== undefined && current.status !== 'superseded' && current.statement === item.oldStatement && current.statement !== item.proposed.statement ); } export async function resolveProjectKnowledgeCandidate( workspaceId: string, id: string, decision: 'accept' | 'reject', signal?: AbortSignal, ): Promise { const global = await readStore('global'); const workspace = await readStore('workspace', workspaceId); const scope = workspace.candidates.some((item) => item.id === id) ? 'workspace' : global.candidates.some((item) => item.id === id) ? 'global' : null; if (!scope) throw new Error('项目事实候选不存在'); await mutate( scope, scope === 'workspace' ? workspaceId : undefined, (store) => { const candidate = store.candidates.find((item) => item.id === id); if (!candidate) throw new Error('项目事实候选不存在'); if ( candidate.status === (decision === 'accept' ? 'accepted' : 'rejected') ) return; if (candidate.status !== 'open') throw new Error('项目事实候选已结清'); const current = store.records.find((item) => item.id === candidate.oldId); if ( !current || current.status === 'superseded' || current.statement !== candidate.oldStatement ) { // A stale proposal can never be accepted, but refusing to reject it too // left it open forever with nothing able to close it. if (decision === 'accept') throw new Error('PROJECT_KNOWLEDGE_VERSION_CONFLICT'); candidate.status = 'rejected'; return; } if (decision === 'accept') { current.status = 'superseded'; current.revision++; current.updatedAt = Date.now(); store.records.push( recordSchema.parse({ ...candidate.proposed, id: randomUUID(), status: 'active', revision: 1, createdAt: Date.now(), updatedAt: Date.now(), supersedesIds: [current.id], lastVerifiedAt: candidate.proposed.provenance.some( (item) => item.type === 'tool_verified', ) ? Date.now() : undefined, }), ); for (const sibling of store.candidates) { if ( sibling.id !== candidate.id && sibling.oldId === current.id && sibling.status === 'open' ) { sibling.status = 'rejected'; sibling.reason += ';同一旧事实已被另一候选替代'; } } } else { const hasOtherOpen = store.candidates.some( (item) => item.id !== candidate.id && item.oldId === current.id && item.status === 'open', ); current.status = hasOtherOpen ? 'needs_review' : 'active'; current.revision++; current.updatedAt = Date.now(); } candidate.status = decision === 'accept' ? 'accepted' : 'rejected'; }, signal, ); } /** * Scalpel-precision removal of one project-knowledge record, distinct from * clearProjectKnowledge/clearGlobalProjectKnowledge (wipe an entire scope). * Looks in both workspace and global stores the way * resolveProjectKnowledgeCandidate already does, since a record may live in * either. Soft-deletes via the existing `superseded` status so it stops * surfacing through recallProjectKnowledge immediately. */ export async function dismissProjectKnowledge( workspaceId: string, id: string, reason: string, signal?: AbortSignal, ): Promise { if (!reason.trim()) throw new Error('撤销项目事实需要说明理由'); const global = await readStore('global'); const workspace = await readStore('workspace', workspaceId); const scope = workspace.records.some((item) => item.id === id) ? 'workspace' : global.records.some((item) => item.id === id) ? 'global' : null; if (!scope) throw new Error('项目事实不存在'); await mutate( scope, scope === 'workspace' ? workspaceId : undefined, (store) => { const item = store.records.find( (item) => item.id === id && item.status !== 'superseded', ); if (!item) throw new Error('项目事实不存在或已替代'); item.status = 'superseded'; item.dismissedReason = reason; item.revision++; item.updatedAt = Date.now(); }, signal, ); } /** Undo a dismiss, mirroring restoreExperience. Only reverses explicit * dismissals (`dismissedReason` is the discriminator) — a record superseded by * an accepted candidate keeps its successor. */ export async function restoreProjectKnowledge( workspaceId: string, id: string, signal?: AbortSignal, ): Promise { const global = await readStore('global'); const workspace = await readStore('workspace', workspaceId); const scope = workspace.records.some((item) => item.id === id) ? 'workspace' : global.records.some((item) => item.id === id) ? 'global' : null; if (!scope) throw new Error('项目事实不存在'); await mutate( scope, scope === 'workspace' ? workspaceId : undefined, (store) => { const item = store.records.find( (item) => item.id === id && item.dismissedReason, ); if (!item) throw new Error('项目事实不存在或不是被撤销的条目'); const live = store.records.find( (other) => other.id !== id && other.status !== 'superseded' && sameTopic(other, item), ); if (live) throw new Error( `同主题已有现行事实 ${live.id},先处理它再恢复,避免同主题两条并存`, ); item.status = 'active'; item.dismissedReason = undefined; item.revision++; item.updatedAt = Date.now(); }, signal, ); } export async function promoteProjectKnowledge( workspaceId: string, id: string, applicability: string, sessionId: string, turnId: string, signal?: AbortSignal, ): Promise { const source = (await readStore('workspace', workspaceId)).records.find( (item) => item.id === id && item.status === 'active', ); if (!source) throw new Error('仅能推广当前有效的项目事实'); if (!applicability.trim()) throw new Error('推广必须明确跨项目适用条件'); const result = await saveProjectKnowledge( workspaceId, { ...source, scope: 'global', workspaceId: undefined, applicability, provenance: [ ...source.provenance, { type: 'agent_proposed', sessionId, turnId, quote: applicability }, ], }, signal, ); if (!result.record) throw new Error(result.blocked?.reason ?? `跨项目推广产生冲突候选:${result.candidateId}`); return result.record; } /** Explicitly publish a verified workspace procedure as a cross-project fact. * The caller must supply the applicability judgment; automatic learning never * changes scope on its own. */ export async function promoteExperienceKnowledge( workspaceId: string, input: { subject: string; statement: string; applicability: string; sessionId: string; turnId: string; }, signal?: AbortSignal, ): Promise { const result = await saveProjectKnowledge( workspaceId, { scope: 'global', workspaceId: undefined, kind: 'constraint', subject: input.subject, statement: input.statement, applicability: input.applicability, aliases: [], provenance: [ { type: 'agent_proposed', sessionId: input.sessionId, turnId: input.turnId, quote: input.applicability, }, ], }, signal, ); if (!result.record) throw new Error(`跨项目推广产生冲突候选:${result.candidateId}`); return result.record; } export async function clearProjectKnowledge( workspaceId: string, ): Promise { await mutate('workspace', workspaceId, (store) => { store.records = []; store.candidates = []; store.clearedAt = Date.now(); }); } export async function clearGlobalProjectKnowledge(): Promise { await mutate('global', undefined, (store) => { store.records = []; store.candidates = []; store.clearedAt = Date.now(); }); } /** Split out so per-record callers (memoryService's addRecords) pay the header * once instead of repeating it for every single record. */ export const PROJECT_KNOWLEDGE_CONTEXT_HEADER = '【项目事实|与用户偏好分离】\n来源决定可信度:用户确认和当前工具核验优先;用户陈述须按原意使用;助手建议/推断只是待核材料。当前代码和用户明确决定优先;依赖变化时读取或测试核对。'; export function projectKnowledgeEntry(item: ProjectKnowledge): string { const sourceLabel = (item: ProjectKnowledge) => [ ...new Set( item.provenance.map( (source) => ({ user_confirmed: '用户确认', user_stated: '用户陈述', tool_verified: '工具核验', agent_proposed: '助手建议', agent_inferred: '助手推断', })[source.type], ), ), ].join('、'); return `- [${item.id}] ${item.kind}/${item.subject} (${item.scope}${item.status === 'needs_review' ? '; 待复核' : ''}; 来源:${sourceLabel(item)}):${item.statement}\n适用:${item.applicability}${item.dependencyWarning?.length ? `\n依赖已变化:${item.dependencyWarning.join('、')};请读取/测试后更新或确认。` : ''}${item.unverifiedDays ? ` 已 ${item.unverifiedDays} 天未验证;依赖它之前先核对现状,核对后可保存更新。` : ''}`; } export function projectKnowledgeContext(items: ProjectKnowledge[]): string { if (!items.length) return ''; return `${PROJECT_KNOWLEDGE_CONTEXT_HEADER}\n${items.map(projectKnowledgeEntry).join('\n')}`; }