feat(wiki): add page revision history with diff, revert, and manual editing

Store superseded wiki page versions for diff and rollback, attribute edits
to user/agent/pipeline/revert sources, and expose revision APIs plus an
editor UI with optimistic locking on save.
main
wizardchen 2026-07-27 15:01:43 +08:00 committed by lyingbug
parent 1d64fc6234
commit 80a5003cc9
29 changed files with 2627 additions and 35 deletions

View File

@ -30,6 +30,10 @@ export interface WikiPage {
out_links: string[];
page_metadata: Record<string, any>;
version: number;
// Author kind of the current version: 'pipeline' | 'agent' | 'user' |
// 'revert'. Empty/missing on legacy rows (treat as 'pipeline').
last_edit_source?: string;
last_editor_id?: string;
created_at: string;
updated_at: string;
}
@ -177,7 +181,21 @@ export function getWikiPage(kbId: string, slug: string) {
return get(`/api/v1/knowledgebase/${kbId}/wiki/pages/${encodeSlugPath(slug)}`);
}
export function updateWikiPage(kbId: string, slug: string, data: Partial<WikiPage>) {
// WikiPageUpdatePayload is a partial update: absent fields keep their stored
// value. `version` is the optimistic-lock guard — send the version the page
// had when the user started editing; the backend answers 409 (with
// `current_version` in the body) when someone else edited in between.
export interface WikiPageUpdatePayload {
title?: string;
content?: string;
summary?: string;
page_type?: string;
status?: string;
aliases?: string[];
version?: number;
}
export function updateWikiPage(kbId: string, slug: string, data: WikiPageUpdatePayload) {
return put(`/api/v1/knowledgebase/${kbId}/wiki/pages/${encodeSlugPath(slug)}`, data);
}
@ -185,6 +203,56 @@ export function deleteWikiPage(kbId: string, slug: string) {
return del(`/api/v1/knowledgebase/${kbId}/wiki/pages/${encodeSlugPath(slug)}`);
}
// WikiPageRevision is one immutable snapshot of a superseded page version.
// `content` is only populated when fetching a single revision.
export interface WikiPageRevision {
id: string;
tenant_id: number;
knowledge_base_id: string;
page_id: string;
slug: string;
version: number;
title: string;
page_type: string;
status: string;
content?: string;
summary: string;
aliases: string[];
edit_source: string;
editor_id: string;
edited_at: string;
created_at: string;
}
export interface WikiRevisionListResponse {
revisions: WikiPageRevision[];
total: number;
current_version: number;
}
// listWikiRevisions returns the page's historical snapshots newest-first
// (content omitted) plus the current version number. The current version has
// no revision row — it is the page itself.
export function listWikiRevisions(kbId: string, slug: string, params?: { limit?: number; offset?: number }) {
const query = new URLSearchParams();
if (params?.limit !== undefined) query.set('limit', String(params.limit));
if (params?.offset !== undefined) query.set('offset', String(params.offset));
const qs = query.toString();
return get(`/api/v1/knowledgebase/${kbId}/wiki/revisions/${encodeSlugPath(slug)}${qs ? '?' + qs : ''}`);
}
// getWikiRevision returns one snapshot with full content.
export function getWikiRevision(kbId: string, slug: string, version: number) {
return get(`/api/v1/knowledgebase/${kbId}/wiki/revisions/${encodeSlugPath(slug)}?version=${version}`);
}
// revertWikiPage rolls the page back to a stored revision. Applied as a
// regular edit: the pre-revert state is snapshotted and version advances,
// so a revert is itself revertable.
export function revertWikiPage(kbId: string, slug: string, version: number) {
return post(`/api/v1/knowledgebase/${kbId}/wiki/revert`, { slug, version });
}
export interface WikiIndexEntryDTO {
slug: string;
title: string;

View File

@ -2731,6 +2731,54 @@ export default {
rebuildSkip: 'You can manually trigger a rebuild later from Data Sources',
},
wikiBrowser: {
// --- Manual editing & revision history ---
editBtn: 'Edit',
historyBtn: 'History',
historyTitle: 'Revision history · {title}',
deletePageBtn: 'Delete',
deletePageConfirm: 'Delete page "{title}"? It will disappear from the wiki.',
deletePageSuccess: 'Page deleted',
deletePageFailed: 'Failed to delete page',
editTitlePlaceholder: 'Page title',
editSummaryPlaceholder: 'One-line summary (shown in the index)',
editContentPlaceholder: 'Markdown body, [[wiki-link]] syntax supported',
editSaveSuccess: 'Page saved',
editSaveFailed: 'Failed to save',
editConflictHint: 'Save conflict: the page was updated to v{ver} by someone else. Reload the latest version (discarding your draft) or overwrite (the overwritten version stays in history).',
editConflictReload: 'Load latest',
editConflictOverwrite: 'Overwrite',
editSourceUser: 'Manually edited',
editSourceAgent: 'AI edited',
editSourceRevert: 'Reverted',
editSourcePipeline: 'Auto-generated',
logActionManualCreate: 'Created manually',
logActionManualEdit: 'Edited manually',
logActionManualDelete: 'Deleted manually',
logActionRevert: 'Reverted',
newPageBtn: 'New page',
newPageTitle: 'Create wiki page',
newPageTitleLabel: 'Title',
newPageTitlePlaceholder: 'Enter a page title',
newPageSlugLabel: 'Slug (page address)',
newPageSlugPlaceholder: 'e.g. concept/my-topic',
newPageSlugHint: 'Letters/digits/dashes, "/" for hierarchy; cannot be changed later',
newPageTypeLabel: 'Page type',
newPageContentLabel: 'Content (optional)',
newPageMissingFields: 'Title and slug are required',
newPageSuccess: 'Page created',
newPageFailed: 'Failed to create page',
revisionCurrent: 'Current',
revisionCurrentHint: 'This is the current version. Pick a historical version on the left to diff or revert.',
revisionSelectHint: 'Select a version on the left',
revisionEmpty: 'No history yet — snapshots are recorded automatically when the content changes',
revisionDiff: 'Diff vs current',
revisionRaw: 'Raw content',
revisionDiffCaption: 'v{from} → v{to} (red = that version, green = current)',
revisionLoadFailed: 'Failed to load revision history',
revertBtn: 'Revert to this version',
revertConfirm: 'Revert to v{ver}? The current content is snapshotted first, so the revert itself can be undone.',
revertSuccess: 'Reverted to v{ver}',
revertFailed: 'Failed to revert',
viewInGraph: 'View in Graph',
tabDocuments: 'Documents',
tabWiki: 'Wiki',

View File

@ -3969,6 +3969,54 @@ export default {
rebuildSkip: "데이터 소스에서 나중에 수동으로 재구축할 수 있습니다",
},
wikiBrowser: {
// --- Manual editing & revision history ---
editBtn: "편집",
historyBtn: "기록",
historyTitle: "버전 기록 · {title}",
deletePageBtn: "삭제",
deletePageConfirm: '"{title}" 페이지를 삭제하시겠습니까?',
deletePageSuccess: "페이지가 삭제되었습니다",
deletePageFailed: "페이지 삭제에 실패했습니다",
editTitlePlaceholder: "페이지 제목",
editSummaryPlaceholder: "한 줄 요약 (인덱스에 표시)",
editContentPlaceholder: "Markdown 본문, [[위키 링크]] 문법 지원",
editSaveSuccess: "페이지가 저장되었습니다",
editSaveFailed: "저장에 실패했습니다",
editConflictHint: "저장 충돌: 페이지가 다른 사용자에 의해 v{ver}(으)로 업데이트되었습니다. 최신 버전을 불러오거나 덮어쓸 수 있습니다(덮어쓴 버전은 기록에 남습니다).",
editConflictReload: "최신 버전 불러오기",
editConflictOverwrite: "덮어쓰기",
editSourceUser: "수동 편집",
editSourceAgent: "AI 수정",
editSourceRevert: "롤백됨",
editSourcePipeline: "자동 생성",
logActionManualCreate: "수동 생성",
logActionManualEdit: "수동 편집",
logActionManualDelete: "수동 삭제",
logActionRevert: "롤백됨",
newPageBtn: "새 페이지",
newPageTitle: "위키 페이지 만들기",
newPageTitleLabel: "제목",
newPageTitlePlaceholder: "페이지 제목을 입력하세요",
newPageSlugLabel: "Slug (페이지 주소)",
newPageSlugPlaceholder: "예: concept/my-topic",
newPageSlugHint: "영문/숫자/하이픈, 계층은 / 사용, 생성 후 변경 불가",
newPageTypeLabel: "페이지 유형",
newPageContentLabel: "본문 (선택)",
newPageMissingFields: "제목과 Slug를 입력하세요",
newPageSuccess: "페이지가 생성되었습니다",
newPageFailed: "페이지 생성에 실패했습니다",
revisionCurrent: "현재 버전",
revisionCurrentHint: "현재 버전입니다. 왼쪽에서 이전 버전을 선택하면 비교하거나 롤백할 수 있습니다.",
revisionSelectHint: "왼쪽에서 버전을 선택하세요",
revisionEmpty: "기록이 없습니다 — 내용이 변경되면 스냅샷이 자동 기록됩니다",
revisionDiff: "현재와 비교",
revisionRaw: "원문 보기",
revisionDiffCaption: "v{from} → v{to} (빨강 = 해당 버전, 초록 = 현재)",
revisionLoadFailed: "버전 기록을 불러오지 못했습니다",
revertBtn: "이 버전으로 롤백",
revertConfirm: "v{ver}(으)로 롤백하시겠습니까? 현재 내용은 먼저 기록으로 저장됩니다.",
revertSuccess: "v{ver}(으)로 롤백했습니다",
revertFailed: "롤백에 실패했습니다",
viewInGraph: "그래프에서 보기",
tabDocuments: "문서",
tabWiki: "Wiki",

View File

@ -3442,6 +3442,54 @@ export default {
rebuildSkip: 'Перестроение можно запустить вручную позже в источниках данных',
},
wikiBrowser: {
// --- Manual editing & revision history ---
editBtn: 'Редактировать',
historyBtn: 'История',
historyTitle: 'История версий · {title}',
deletePageBtn: 'Удалить',
deletePageConfirm: 'Удалить страницу «{title}»?',
deletePageSuccess: 'Страница удалена',
deletePageFailed: 'Не удалось удалить страницу',
editTitlePlaceholder: 'Заголовок страницы',
editSummaryPlaceholder: 'Краткое описание (для индекса)',
editContentPlaceholder: 'Текст в Markdown, поддерживается синтаксис [[вики-ссылок]]',
editSaveSuccess: 'Страница сохранена',
editSaveFailed: 'Не удалось сохранить',
editConflictHint: 'Конфликт сохранения: страница обновлена до v{ver}. Загрузите последнюю версию (черновик будет отброшен) или перезапишите (перезаписанная версия останется в истории).',
editConflictReload: 'Загрузить последнюю',
editConflictOverwrite: 'Перезаписать',
editSourceUser: 'Изменено вручную',
editSourceAgent: 'Изменено ИИ',
editSourceRevert: 'Откат',
editSourcePipeline: 'Автогенерация',
logActionManualCreate: 'Создано вручную',
logActionManualEdit: 'Изменено вручную',
logActionManualDelete: 'Удалено вручную',
logActionRevert: 'Откат',
newPageBtn: 'Новая страница',
newPageTitle: 'Создать вики-страницу',
newPageTitleLabel: 'Заголовок',
newPageTitlePlaceholder: 'Введите заголовок страницы',
newPageSlugLabel: 'Slug (адрес страницы)',
newPageSlugPlaceholder: 'например concept/my-topic',
newPageSlugHint: 'Буквы/цифры/дефисы, «/» для иерархии; нельзя изменить позже',
newPageTypeLabel: 'Тип страницы',
newPageContentLabel: 'Содержимое (необязательно)',
newPageMissingFields: 'Укажите заголовок и slug',
newPageSuccess: 'Страница создана',
newPageFailed: 'Не удалось создать страницу',
revisionCurrent: 'Текущая',
revisionCurrentHint: 'Это текущая версия. Выберите историческую версию слева для сравнения или отката.',
revisionSelectHint: 'Выберите версию слева',
revisionEmpty: 'Истории пока нет — снимки записываются автоматически при изменении содержимого',
revisionDiff: 'Сравнить с текущей',
revisionRaw: 'Исходный текст',
revisionDiffCaption: 'v{from} → v{to} (красный — та версия, зелёный — текущая)',
revisionLoadFailed: 'Не удалось загрузить историю версий',
revertBtn: 'Откатить к этой версии',
revertConfirm: 'Откатить к v{ver}? Текущее содержимое сначала будет сохранено в историю.',
revertSuccess: 'Выполнен откат к v{ver}',
revertFailed: 'Не удалось выполнить откат',
viewInGraph: 'Открыть в графе',
tabDocuments: 'Документы',
tabWiki: 'Wiki',

View File

@ -4027,6 +4027,54 @@ export default {
rebuildSkip: "稍后可在数据源中手动触发重建",
},
wikiBrowser: {
// --- Manual editing & revision history ---
editBtn: "编辑",
historyBtn: "历史",
historyTitle: "版本历史 · {title}",
deletePageBtn: "删除",
deletePageConfirm: "确定要删除页面“{title}”吗?删除后可在回收周期内由管理员恢复数据库记录,但页面将从 Wiki 中消失。",
deletePageSuccess: "页面已删除",
deletePageFailed: "删除页面失败",
editTitlePlaceholder: "页面标题",
editSummaryPlaceholder: "一句话摘要(用于索引列表)",
editContentPlaceholder: "Markdown 正文,支持 [[页面链接]] 语法",
editSaveSuccess: "页面已保存",
editSaveFailed: "保存失败",
editConflictHint: "保存冲突:页面已被他人或系统更新至 v{ver}。你可以放弃本地修改加载最新版本,或覆盖保存(被覆盖的版本会保留在历史中)。",
editConflictReload: "加载最新版本",
editConflictOverwrite: "覆盖保存",
editSourceUser: "手动编辑",
editSourceAgent: "AI 修改",
editSourceRevert: "版本回滚",
editSourcePipeline: "自动生成",
logActionManualCreate: "手动创建",
logActionManualEdit: "手动编辑",
logActionManualDelete: "手动删除",
logActionRevert: "版本回滚",
newPageBtn: "新建页面",
newPageTitle: "新建 Wiki 页面",
newPageTitleLabel: "标题",
newPageTitlePlaceholder: "请输入页面标题",
newPageSlugLabel: "Slug(页面地址)",
newPageSlugPlaceholder: "例如 concept/my-topic",
newPageSlugHint: "由字母/数字/中划线组成,可用 / 分层,创建后不可修改",
newPageTypeLabel: "页面类型",
newPageContentLabel: "正文(可选)",
newPageMissingFields: "请填写标题和 Slug",
newPageSuccess: "页面已创建",
newPageFailed: "创建页面失败",
revisionCurrent: "当前版本",
revisionCurrentHint: "这是页面的当前版本,选择左侧的历史版本可查看差异或回滚。",
revisionSelectHint: "选择左侧的版本查看内容",
revisionEmpty: "暂无历史版本,页面内容变化后会自动记录快照",
revisionDiff: "对比当前",
revisionRaw: "查看原文",
revisionDiffCaption: "v{from} → v{to}(红色为该版本内容,绿色为当前内容)",
revisionLoadFailed: "加载版本历史失败",
revertBtn: "回滚到此版本",
revertConfirm: "确定回滚到 v{ver} 吗?当前内容会先保存为历史版本,回滚操作可再次撤销。",
revertSuccess: "已回滚到 v{ver}",
revertFailed: "回滚失败",
viewInGraph: '在图谱中查看',
tabDocuments: "文档",
tabWiki: "Wiki",

View File

@ -0,0 +1,49 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { diffWikiLines } from './wikiLineDiff.ts'
function render(lines: ReturnType<typeof diffWikiLines>): string {
return lines
.map((l) => (l.type === 'same' ? ` ${l.text}` : l.type === 'del' ? `- ${l.text}` : `+ ${l.text}`))
.join('\n')
}
test('identical texts diff to all-same rows', () => {
const out = diffWikiLines('a\nb\nc', 'a\nb\nc')
assert.equal(out.length, 3)
assert.ok(out.every((l) => l.type === 'same'))
})
test('a changed middle line becomes del+add', () => {
assert.equal(render(diffWikiLines('a\nold\nc', 'a\nnew\nc')), ' a\n- old\n+ new\n c')
})
test('pure insertion and pure deletion', () => {
assert.equal(render(diffWikiLines('a\nc', 'a\nb\nc')), ' a\n+ b\n c')
assert.equal(render(diffWikiLines('a\nb\nc', 'a\nc')), ' a\n- b\n c')
})
test('empty sides', () => {
assert.equal(diffWikiLines('', 'x\ny').filter((l) => l.type === 'add').length, 2)
assert.equal(diffWikiLines('x\ny', '').filter((l) => l.type === 'del').length, 2)
// '' splits into one empty line on each side → one same row.
assert.deepEqual(diffWikiLines('', ''), [{ type: 'same', text: '' }])
})
test('unchanged prefix/suffix stay in order around a block edit', () => {
const oldText = 'h1\nintro\nbody old 1\nbody old 2\noutro'
const newText = 'h1\nintro\nbody new\noutro'
assert.equal(
render(diffWikiLines(oldText, newText)),
' h1\n intro\n- body old 1\n- body old 2\n+ body new\n outro',
)
})
test('coarse fallback beyond the LCS limit loses no lines', () => {
const oldText = Array.from({ length: 2000 }, (_, i) => `o${i}`).join('\n')
const newText = Array.from({ length: 2000 }, (_, i) => `n${i}`).join('\n')
const out = diffWikiLines(oldText, newText)
assert.equal(out.filter((l) => l.type === 'del').length, 2000)
assert.equal(out.filter((l) => l.type === 'add').length, 2000)
})

View File

@ -0,0 +1,90 @@
// Line-level diff for the wiki revision viewer. Deliberately small: the
// consumer renders "removed / added / unchanged" rows, nothing fancier, so a
// trimmed-LCS diff is enough — no need to pull in a diff dependency.
export interface WikiDiffLine {
type: 'same' | 'add' | 'del'
text: string
}
// Beyond this many lines (per side, after common prefix/suffix trimming) the
// O(n·m) LCS table gets expensive; fall back to a coarse "whole middle
// changed" diff, which is still honest, just less minimal.
const LCS_LINE_LIMIT = 1500
// diffWikiLines compares two texts line-by-line and returns a flat list of
// rows in display order: `del` rows come from `oldText`, `add` rows from
// `newText`, `same` rows from both. Common leading/trailing lines are
// detected first so typical wiki edits (one section changed) stay cheap even
// on long pages.
export function diffWikiLines(oldText: string, newText: string): WikiDiffLine[] {
const oldLines = oldText.split('\n')
const newLines = newText.split('\n')
// Trim common prefix.
let start = 0
while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) {
start++
}
// Trim common suffix (not overlapping the prefix).
let oldEnd = oldLines.length
let newEnd = newLines.length
while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
oldEnd--
newEnd--
}
const prefix: WikiDiffLine[] = oldLines.slice(0, start).map((text) => ({ type: 'same' as const, text }))
const suffix: WikiDiffLine[] = oldLines.slice(oldEnd).map((text) => ({ type: 'same' as const, text }))
const oldMid = oldLines.slice(start, oldEnd)
const newMid = newLines.slice(start, newEnd)
let middle: WikiDiffLine[]
if (oldMid.length === 0) {
middle = newMid.map((text) => ({ type: 'add' as const, text }))
} else if (newMid.length === 0) {
middle = oldMid.map((text) => ({ type: 'del' as const, text }))
} else if (oldMid.length > LCS_LINE_LIMIT || newMid.length > LCS_LINE_LIMIT) {
middle = [
...oldMid.map((text) => ({ type: 'del' as const, text })),
...newMid.map((text) => ({ type: 'add' as const, text })),
]
} else {
middle = lcsDiff(oldMid, newMid)
}
return [...prefix, ...middle, ...suffix]
}
// lcsDiff produces a minimal line diff of two smallish line arrays via the
// classic LCS dynamic program, walked back from the bottom-right corner.
function lcsDiff(a: string[], b: string[]): WikiDiffLine[] {
const n = a.length
const m = b.length
// dp[i][j] = LCS length of a[i:], b[j:]
const dp: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1))
for (let i = n - 1; i >= 0; i--) {
for (let j = m - 1; j >= 0; j--) {
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
}
}
const out: WikiDiffLine[] = []
let i = 0
let j = 0
while (i < n && j < m) {
if (a[i] === b[j]) {
out.push({ type: 'same', text: a[i] })
i++
j++
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
out.push({ type: 'del', text: a[i] })
i++
} else {
out.push({ type: 'add', text: b[j] })
j++
}
}
while (i < n) out.push({ type: 'del', text: a[i++] })
while (j < m) out.push({ type: 'add', text: b[j++] })
return out
}

View File

@ -259,6 +259,12 @@
<t-icon name="folder-add" />
</button>
</t-tooltip>
<t-tooltip v-if="props.canEdit" :content="$t('knowledgeEditor.wikiBrowser.newPageBtn')" placement="top">
<button type="button" class="wiki-tab-bar-action"
:aria-label="$t('knowledgeEditor.wikiBrowser.newPageBtn')" @click.stop="openCreatePageDialog">
<t-icon name="file-add" />
</button>
</t-tooltip>
</div>
</div>
@ -479,12 +485,37 @@
selectedPage.version
})
}}</span>
<!-- Provenance of the current version; only surfaced when a
human / agent / revert touched it — pipeline is the
default and would just be noise. -->
<t-tag v-if="editSourceVisible(selectedPage.last_edit_source)" size="small"
:theme="editSourceTheme(selectedPage.last_edit_source)" variant="light">
{{ editSourceLabel(selectedPage.last_edit_source) }}
</t-tag>
<span class="wiki-reader-meta-text">{{ formatDate(selectedPage.updated_at) }}</span>
<t-link theme="primary" hover="color" class="wiki-reader-graph-link"
@click="emit('view-graph', selectedPage.slug)">
<template #prefixIcon><t-icon name="chart-bubble" /></template>
{{ $t('knowledgeEditor.wikiBrowser.viewInGraph') }}
</t-link>
<span class="wiki-reader-actions">
<t-link theme="default" hover="color" @click="openRevisionDrawer">
<template #prefixIcon><t-icon name="history" /></template>
{{ $t('knowledgeEditor.wikiBrowser.historyBtn') }}
</t-link>
<t-link v-if="props.canEdit && !editingPage" theme="primary" hover="color" @click="startEditPage">
<template #prefixIcon><t-icon name="edit" /></template>
{{ $t('knowledgeEditor.wikiBrowser.editBtn') }}
</t-link>
<t-popconfirm v-if="props.canEdit" theme="danger"
:content="$t('knowledgeEditor.wikiBrowser.deletePageConfirm', { title: selectedPage.title })"
@confirm="confirmDeletePage">
<t-link theme="danger" hover="color">
<template #prefixIcon><t-icon name="delete" /></template>
{{ $t('knowledgeEditor.wikiBrowser.deletePageBtn') }}
</t-link>
</t-popconfirm>
</span>
</div>
</div>
@ -499,7 +530,40 @@
</div>
<!-- Content -->
<div ref="readerBodyRef" class="wiki-reader-body" v-html="renderedContent" @click="handleContentClick">
<div v-if="!editingPage" ref="readerBodyRef" class="wiki-reader-body" v-html="renderedContent"
@click="handleContentClick">
</div>
<!-- Inline markdown editor (canEdit only). Saves are guarded by
the page version captured at edit start; the backend answers
409 when someone (or the pipeline) edited in between. -->
<div v-else class="wiki-page-editor">
<t-input v-model="editForm.title" class="wiki-page-editor-title"
:placeholder="$t('knowledgeEditor.wikiBrowser.editTitlePlaceholder')" />
<t-textarea v-model="editForm.summary" class="wiki-page-editor-summary"
:autosize="{ minRows: 2, maxRows: 4 }"
:placeholder="$t('knowledgeEditor.wikiBrowser.editSummaryPlaceholder')" />
<t-textarea v-model="editForm.content" class="wiki-page-editor-content"
:autosize="{ minRows: 16, maxRows: 40 }"
:placeholder="$t('knowledgeEditor.wikiBrowser.editContentPlaceholder')" />
<div v-if="editConflictVersion !== null" class="wiki-page-editor-conflict">
<t-icon name="error-circle" />
<span>{{ $t('knowledgeEditor.wikiBrowser.editConflictHint', { ver: editConflictVersion }) }}</span>
<t-link theme="primary" hover="color" @click="reloadLatestIntoEditor">
{{ $t('knowledgeEditor.wikiBrowser.editConflictReload') }}
</t-link>
<t-link theme="warning" hover="color" @click="overwriteSavePage">
{{ $t('knowledgeEditor.wikiBrowser.editConflictOverwrite') }}
</t-link>
</div>
<div class="wiki-page-editor-footer">
<t-button theme="primary" :loading="savingPage" @click="savePageEdit()">
{{ $t('common.save') }}
</t-button>
<t-button variant="outline" :disabled="savingPage" @click="cancelEditPage">
{{ $t('common.cancel') }}
</t-button>
</div>
</div>
<!-- Source refs -->
@ -562,8 +626,8 @@
</div>
<div v-for="entry in logEntries" :key="entry.id" class="wiki-log-entry">
<div class="wiki-log-entry-header">
<t-tag size="small" :theme="entry.action === 'retract' ? 'danger' : 'primary'" variant="light">
{{ entry.action }}
<t-tag size="small" :theme="logActionTheme(entry.action)" variant="light">
{{ logActionLabel(entry.action) }}
</t-tag>
<span class="wiki-log-entry-title">{{ entry.doc_title || entry.knowledge_id || '—' }}</span>
<span class="wiki-log-entry-time">{{ formatDate(entry.created_at) }}</span>
@ -664,6 +728,45 @@
:kbIds="[props.knowledgeBaseId]" :embeddedMode="true" />
</t-drawer>
<!-- Revision history drawer -->
<WikiRevisionDrawer v-model:visible="showRevisionDrawer" :kb-id="props.knowledgeBaseId"
:slug="selectedPage?.slug || ''" :current-page="selectedPage" :can-edit="props.canEdit"
@reverted="onPageReverted" />
<!-- Create page dialog -->
<t-dialog v-model:visible="showCreatePageDialog" :header="$t('knowledgeEditor.wikiBrowser.newPageTitle')"
:confirm-btn="{ content: $t('common.confirm'), loading: creatingPage }" :cancel-btn="$t('common.cancel')"
width="520px" @confirm="submitCreatePage">
<div class="wiki-create-page-form">
<div class="wiki-create-page-field">
<label>{{ $t('knowledgeEditor.wikiBrowser.newPageTitleLabel') }}</label>
<t-input v-model="createPageForm.title"
:placeholder="$t('knowledgeEditor.wikiBrowser.newPageTitlePlaceholder')" @input="syncCreatePageSlug" />
</div>
<div class="wiki-create-page-field">
<label>{{ $t('knowledgeEditor.wikiBrowser.newPageSlugLabel') }}</label>
<t-input v-model="createPageForm.slug"
:placeholder="$t('knowledgeEditor.wikiBrowser.newPageSlugPlaceholder')"
@input="createPageSlugTouched = true" />
<div class="wiki-create-page-hint">{{ $t('knowledgeEditor.wikiBrowser.newPageSlugHint') }}</div>
</div>
<div class="wiki-create-page-field">
<label>{{ $t('knowledgeEditor.wikiBrowser.newPageTypeLabel') }}</label>
<t-select v-model="createPageForm.pageType">
<t-option value="concept" :label="$t('knowledgeEditor.wikiBrowser.filterConcept')" />
<t-option value="entity" :label="$t('knowledgeEditor.wikiBrowser.filterEntity')" />
<t-option value="synthesis" :label="$t('knowledgeEditor.wikiBrowser.filterSynthesis')" />
<t-option value="comparison" :label="$t('knowledgeEditor.wikiBrowser.filterComparison')" />
</t-select>
</div>
<div class="wiki-create-page-field">
<label>{{ $t('knowledgeEditor.wikiBrowser.newPageContentLabel') }}</label>
<t-textarea v-model="createPageForm.content" :autosize="{ minRows: 6, maxRows: 16 }"
:placeholder="$t('knowledgeEditor.wikiBrowser.editContentPlaceholder')" />
</div>
</div>
</t-dialog>
<!-- In-place move confirmation, anchored at the drop point. Confirming runs
the actual move API; cancelling discards the staged move. -->
<teleport to="body">
@ -702,6 +805,7 @@ import { RecycleScroller } from 'vue-virtual-scroller'
import { hydrateProtectedFileImages, sanitizeMarkdownHTML } from '@/utils/security'
import picturePreview from '@/components/picture-preview.vue'
import WikiFolderActions from './WikiFolderActions.vue'
import WikiRevisionDrawer from './WikiRevisionDrawer.vue'
import { createSessions } from '@/api/chat'
import ChatView from '@/views/chat/index.vue'
import {
@ -711,6 +815,9 @@ import {
updateWikiFolder,
deleteWikiFolder,
moveWikiPage,
createWikiPage,
updateWikiPage,
deleteWikiPage,
getWikiPage,
getWikiIndex,
getWikiLog,
@ -2206,7 +2313,7 @@ async function confirmPendingMove() {
} catch (e: any) {
console.error('Failed to move wiki folder:', e)
MessagePlugin.error(
e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.moveFolderFailed'),
e?.message || t('knowledgeEditor.wikiBrowser.moveFolderFailed'),
)
}
}
@ -2229,7 +2336,7 @@ async function createFolder(parentId: string, parentPath: string[], name: string
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to create wiki folder:', e)
MessagePlugin.error(e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.createFolderFailed'))
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.createFolderFailed'))
}
}
@ -2292,7 +2399,7 @@ async function commitRenameFolder(folderId: string, originalName: string) {
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to rename wiki folder:', e)
MessagePlugin.error(e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.renameFolderFailed'))
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.renameFolderFailed'))
}
}
@ -2304,7 +2411,7 @@ async function deleteFolder(folderId: string) {
await reloadDirectoryForType(activeTab.value)
} catch (e: any) {
console.error('Failed to delete wiki folder:', e)
MessagePlugin.error(e?.response?.data?.message || t('knowledgeEditor.wikiBrowser.deleteFolderFailed'))
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.deleteFolderFailed'))
}
}
@ -2758,6 +2865,251 @@ async function loadStats() {
} catch (e) { /* ignore */ }
}
// --- Manual page editing / version management ---------------------------
const editingPage = ref(false)
const savingPage = ref(false)
const editForm = ref({ title: '', summary: '', content: '' })
// Version the user started editing from — the optimistic-lock guard sent
// with the save. 409 → someone (or the pipeline) edited in between.
const editBaseVersion = ref(0)
const editConflictVersion = ref<number | null>(null)
const showRevisionDrawer = ref(false)
const showCreatePageDialog = ref(false)
const creatingPage = ref(false)
const createPageForm = ref({ title: '', slug: '', pageType: 'concept', content: '' })
const createPageSlugTouched = ref(false)
// Navigating to another page (or view) silently drops an in-progress edit;
// the editor is inline, so a route-level guard would be overkill here.
watch(() => selectedPage.value?.slug, () => {
editingPage.value = false
editConflictVersion.value = null
})
function startEditPage() {
if (!selectedPage.value) return
editForm.value = {
title: selectedPage.value.title,
summary: selectedPage.value.summary || '',
content: selectedPage.value.content || '',
}
editBaseVersion.value = selectedPage.value.version
editConflictVersion.value = null
editingPage.value = true
}
function cancelEditPage() {
editingPage.value = false
editConflictVersion.value = null
}
async function savePageEdit(versionOverride?: number) {
if (!selectedPage.value) return
const slug = selectedPage.value.slug
savingPage.value = true
try {
const res = await updateWikiPage(props.knowledgeBaseId, slug, {
title: editForm.value.title,
summary: editForm.value.summary,
content: editForm.value.content,
version: versionOverride ?? editBaseVersion.value,
})
const updated = ((res as any).data || res) as WikiPage
selectedPage.value = updated
editingPage.value = false
editConflictVersion.value = null
updateSidebarPageTitle(slug, updated.title)
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.editSaveSuccess'))
} catch (e: any) {
// The request interceptor rejects with a flattened { status, message,
// ...body } object, so the conflict payload sits on `e` directly.
if (e?.status === 409) {
editConflictVersion.value = e?.current_version ?? 0
} else {
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.editSaveFailed'))
}
} finally {
savingPage.value = false
}
}
// overwriteSavePage resolves an edit conflict by re-saving on top of the
// server's current version (last write wins, but the loser's version stays
// in the revision history, so nothing is destroyed).
async function overwriteSavePage() {
if (!selectedPage.value) return
try {
const res = await getWikiPage(props.knowledgeBaseId, selectedPage.value.slug)
const latest = ((res as any).data || res) as WikiPage
await savePageEdit(latest.version)
} catch (e) {
console.error('Failed to fetch latest version for overwrite save:', e)
MessagePlugin.error(t('knowledgeEditor.wikiBrowser.editSaveFailed'))
}
}
// reloadLatestIntoEditor resolves an edit conflict by discarding the local
// draft and re-opening the editor on the server's current content.
async function reloadLatestIntoEditor() {
await refreshSelectedPage()
startEditPage()
}
async function confirmDeletePage() {
if (!selectedPage.value) return
const slug = selectedPage.value.slug
try {
await deleteWikiPage(props.knowledgeBaseId, slug)
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.deletePageSuccess'))
selectedPage.value = null
editingPage.value = false
loadPages()
} catch (e: any) {
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.deletePageFailed'))
}
}
function openRevisionDrawer() {
if (!selectedPage.value) return
showRevisionDrawer.value = true
}
function onPageReverted(page: WikiPage) {
selectedPage.value = page
editingPage.value = false
updateSidebarPageTitle(page.slug, page.title)
}
function openCreatePageDialog() {
createPageForm.value = { title: '', slug: '', pageType: 'concept', content: '' }
createPageSlugTouched.value = false
showCreatePageDialog.value = true
}
// syncCreatePageSlug derives "<type>/<slugified-title>" while the user has
// not touched the slug field themselves. Only ASCII-ish titles produce a
// usable slug automatically; otherwise the user types one.
function syncCreatePageSlug() {
if (createPageSlugTouched.value) return
const base = createPageForm.value.title
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s_-]/g, '')
.replace(/\s+/g, '-')
.replace(/-{2,}/g, '-')
.replace(/^-|-$/g, '')
createPageForm.value.slug = base ? `${createPageForm.value.pageType}/${base}` : ''
}
async function submitCreatePage() {
const title = createPageForm.value.title.trim()
const slug = createPageForm.value.slug.trim().replace(/^\/+|\/+$/g, '')
if (!title || !slug) {
MessagePlugin.warning(t('knowledgeEditor.wikiBrowser.newPageMissingFields'))
return
}
if (!/^[\p{L}\p{N}][\p{L}\p{N}\s_\-/]*$/u.test(slug)) {
MessagePlugin.warning(t('knowledgeEditor.wikiBrowser.newPageSlugHint'))
return
}
creatingPage.value = true
try {
await createWikiPage(props.knowledgeBaseId, {
slug,
title,
page_type: createPageForm.value.pageType,
content: createPageForm.value.content,
})
showCreatePageDialog.value = false
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.newPageSuccess'))
loadPages()
navigateToSlug(slug)
} catch (e: any) {
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.newPageFailed'))
} finally {
creatingPage.value = false
}
}
// updateSidebarPageTitle patches the already-loaded sidebar entries in place
// after a rename so the tree reflects the edit without a full reload.
function updateSidebarPageTitle(slug: string, title: string) {
for (const p of pages.value) {
if (p.slug === slug) p.title = title
}
for (const bucket of Object.values(pagesByType.value)) {
for (const p of bucket.items) {
if (p.slug === slug) p.title = title
}
for (const p of bucket.flatItems) {
if (p.slug === slug) p.title = title
}
}
}
// Log actions written by the manual editing paths. Pipeline actions keep
// their raw tag (they are already short English verbs the log has always
// shown); these four are new and would otherwise read as snake_case.
const MANUAL_LOG_ACTION_KEYS: Record<string, string> = {
manual_create: 'logActionManualCreate',
manual_edit: 'logActionManualEdit',
manual_delete: 'logActionManualDelete',
revert: 'logActionRevert',
}
function logActionLabel(action: string): string {
const key = MANUAL_LOG_ACTION_KEYS[action]
return key ? t(`knowledgeEditor.wikiBrowser.${key}`) : action
}
function logActionTheme(action: string): 'primary' | 'danger' | 'warning' | 'success' {
switch (action) {
case 'retract':
case 'manual_delete':
return 'danger'
case 'revert':
return 'warning'
case 'manual_create':
case 'manual_edit':
return 'success'
default:
return 'primary'
}
}
function editSourceVisible(source?: string): boolean {
return source === 'user' || source === 'agent' || source === 'revert'
}
function editSourceLabel(source?: string): string {
switch (source) {
case 'user':
return t('knowledgeEditor.wikiBrowser.editSourceUser')
case 'agent':
return t('knowledgeEditor.wikiBrowser.editSourceAgent')
case 'revert':
return t('knowledgeEditor.wikiBrowser.editSourceRevert')
default:
return t('knowledgeEditor.wikiBrowser.editSourcePipeline')
}
}
function editSourceTheme(source?: string): 'primary' | 'success' | 'warning' | 'default' {
switch (source) {
case 'user':
return 'success'
case 'agent':
return 'primary'
case 'revert':
return 'warning'
default:
return 'default'
}
}
// Refresh the currently selected page's content without touching navigation history
async function refreshSelectedPage() {
if (!selectedPage.value) return
@ -5108,6 +5460,7 @@ onUnmounted(() => {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.wiki-reader-meta-text {
@ -5120,6 +5473,69 @@ onUnmounted(() => {
font-size: 13px;
}
.wiki-reader-actions {
display: inline-flex;
align-items: center;
gap: 12px;
font-size: 13px;
}
.wiki-page-editor {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 8px;
.wiki-page-editor-title :deep(.t-input__inner) {
font-weight: 600;
}
.wiki-page-editor-content :deep(textarea) {
font-family: var(--td-font-family-mono, monospace);
font-size: 13px;
line-height: 1.7;
}
}
.wiki-page-editor-conflict {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-radius: 6px;
background: var(--td-warning-color-1);
color: var(--td-warning-color-7);
font-size: 13px;
flex-wrap: wrap;
}
.wiki-page-editor-footer {
display: flex;
gap: 8px;
}
.wiki-create-page-form {
display: flex;
flex-direction: column;
gap: 14px;
.wiki-create-page-field {
display: flex;
flex-direction: column;
gap: 6px;
label {
font-size: 13px;
color: var(--td-text-color-secondary);
}
}
.wiki-create-page-hint {
font-size: 12px;
color: var(--td-text-color-placeholder);
}
}
.wiki-reader-links {
padding: 12px 16px;
background: var(--td-bg-color-secondarycontainer);

View File

@ -0,0 +1,416 @@
<template>
<t-drawer :visible="visible" size="760px" :footer="false" class="wiki-revision-drawer"
:header="t('knowledgeEditor.wikiBrowser.historyTitle', { title: currentPage?.title || slug })"
@update:visible="(v: boolean) => emit('update:visible', v)">
<div class="wiki-rev-layout">
<!-- Version list -->
<div class="wiki-rev-list">
<!-- Current version pseudo-entry -->
<div v-if="currentPage" class="wiki-rev-item"
:class="{ 'wiki-rev-item--active': selectedVersion === currentPage.version }"
@click="selectCurrent">
<div class="wiki-rev-item-head">
<span class="wiki-rev-version">v{{ currentPage.version }}</span>
<t-tag size="small" theme="primary" variant="light">
{{ t('knowledgeEditor.wikiBrowser.revisionCurrent') }}
</t-tag>
<t-tag size="small" :theme="sourceTheme(currentPage.last_edit_source)" variant="light-outline">
{{ sourceLabel(currentPage.last_edit_source) }}
</t-tag>
</div>
<div class="wiki-rev-item-meta">{{ formatTime(currentPage.updated_at) }}</div>
</div>
<div v-for="rev in revisions" :key="rev.id" class="wiki-rev-item"
:class="{ 'wiki-rev-item--active': selectedVersion === rev.version }" @click="selectRevision(rev)">
<div class="wiki-rev-item-head">
<span class="wiki-rev-version">v{{ rev.version }}</span>
<t-tag size="small" :theme="sourceTheme(rev.edit_source)" variant="light-outline">
{{ sourceLabel(rev.edit_source) }}
</t-tag>
</div>
<div class="wiki-rev-item-meta">
{{ formatTime(rev.edited_at) }}
<span v-if="rev.editor_id" class="wiki-rev-editor">· {{ rev.editor_id }}</span>
</div>
</div>
<div v-if="revisions.length < total" class="wiki-rev-load-more">
<t-link theme="primary" hover="color" :disabled="loadingList" @click="loadMore">
{{ t('knowledgeEditor.wikiBrowser.logLoadMore') }}
</t-link>
</div>
<div v-if="!loadingList && revisions.length === 0" class="wiki-rev-empty">
{{ t('knowledgeEditor.wikiBrowser.revisionEmpty') }}
</div>
</div>
<!-- Detail pane -->
<div class="wiki-rev-detail">
<template v-if="selectedVersion !== null && currentPage && selectedVersion === currentPage.version">
<div class="wiki-rev-detail-hint">{{ t('knowledgeEditor.wikiBrowser.revisionCurrentHint') }}</div>
</template>
<template v-else-if="selectedRevision">
<div class="wiki-rev-detail-toolbar">
<div class="wiki-rev-detail-title">
v{{ selectedRevision.version }} · {{ selectedRevision.title }}
</div>
<div class="wiki-rev-detail-actions">
<t-radio-group v-model="detailMode" variant="default-filled" size="small">
<t-radio-button value="diff">{{ t('knowledgeEditor.wikiBrowser.revisionDiff') }}</t-radio-button>
<t-radio-button value="raw">{{ t('knowledgeEditor.wikiBrowser.revisionRaw') }}</t-radio-button>
</t-radio-group>
<t-popconfirm v-if="canEdit" :content="t('knowledgeEditor.wikiBrowser.revertConfirm', { ver: selectedRevision.version })"
@confirm="doRevert">
<t-button size="small" theme="warning" variant="outline" :loading="reverting">
<template #icon><t-icon name="rollback" /></template>
{{ t('knowledgeEditor.wikiBrowser.revertBtn') }}
</t-button>
</t-popconfirm>
</div>
</div>
<div v-if="loadingDetail" class="wiki-rev-detail-hint">{{ t('knowledgeEditor.wikiBrowser.logLoading') }}</div>
<!-- Diff vs current -->
<div v-else-if="detailMode === 'diff'" class="wiki-rev-diff">
<div class="wiki-rev-diff-caption">
{{ t('knowledgeEditor.wikiBrowser.revisionDiffCaption', {
from: selectedRevision.version, to: currentPage?.version ?? '?' }) }}
</div>
<pre class="wiki-rev-diff-body"><span v-for="(line, idx) in diffLines" :key="idx"
:class="['wiki-rev-diff-line', `wiki-rev-diff-line--${line.type}`]">{{ diffPrefix(line.type) }}{{ line.text }}
</span></pre>
</div>
<!-- Raw content -->
<pre v-else class="wiki-rev-raw">{{ detailContent }}</pre>
</template>
<div v-else class="wiki-rev-detail-hint">{{ t('knowledgeEditor.wikiBrowser.revisionSelectHint') }}</div>
</div>
</div>
</t-drawer>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import {
listWikiRevisions,
getWikiRevision,
revertWikiPage,
type WikiPage,
type WikiPageRevision,
} from '@/api/wiki'
import { diffWikiLines, type WikiDiffLine } from '@/utils/wikiLineDiff'
const props = defineProps<{
visible: boolean
kbId: string
slug: string
currentPage: WikiPage | null
canEdit?: boolean
}>()
const emit = defineEmits<{
(e: 'update:visible', visible: boolean): void
(e: 'reverted', page: WikiPage): void
}>()
const { t } = useI18n()
const PAGE_SIZE = 50
const revisions = ref<WikiPageRevision[]>([])
const total = ref(0)
const loadingList = ref(false)
const selectedVersion = ref<number | null>(null)
const selectedRevision = ref<WikiPageRevision | null>(null)
const detailContent = ref('')
const loadingDetail = ref(false)
const detailMode = ref<'diff' | 'raw'>('diff')
const reverting = ref(false)
const diffLines = computed<WikiDiffLine[]>(() => {
if (!props.currentPage || !selectedRevision.value) return []
return diffWikiLines(detailContent.value, props.currentPage.content || '')
})
watch(
() => [props.visible, props.slug] as const,
([visible]) => {
if (visible && props.slug) {
resetAndLoad()
}
},
)
function resetAndLoad() {
detailRequestSeq++
revisions.value = []
total.value = 0
selectedVersion.value = props.currentPage?.version ?? null
selectedRevision.value = null
detailContent.value = ''
loadingDetail.value = false
loadList(0)
}
async function loadList(offset: number) {
loadingList.value = true
try {
const res = await listWikiRevisions(props.kbId, props.slug, { limit: PAGE_SIZE, offset })
const data = (res as any).data || (res as any)
const items: WikiPageRevision[] = data.revisions || []
if (offset === 0) {
revisions.value = items
} else {
// Snapshots are created while the user pages through, which shifts the
// newest-first window. Drop versions we already hold so an overlapping
// page cannot produce duplicate rows (and duplicate :key values).
const seen = new Set(revisions.value.map((r) => r.version))
revisions.value = [...revisions.value, ...items.filter((r) => !seen.has(r.version))]
}
total.value = data.total ?? revisions.value.length
} catch (e: any) {
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.revisionLoadFailed'))
} finally {
loadingList.value = false
}
}
function loadMore() {
if (loadingList.value) return
loadList(revisions.value.length)
}
function selectCurrent() {
detailRequestSeq++
selectedVersion.value = props.currentPage?.version ?? null
selectedRevision.value = null
detailContent.value = ''
loadingDetail.value = false
}
// Monotonic token guarding the detail fetch: clicking through the list fires
// overlapping requests, and a slow earlier one must not overwrite the body of
// the revision the user is actually looking at.
let detailRequestSeq = 0
async function selectRevision(rev: WikiPageRevision) {
const seq = ++detailRequestSeq
selectedVersion.value = rev.version
selectedRevision.value = rev
detailContent.value = ''
loadingDetail.value = true
try {
const res = await getWikiRevision(props.kbId, props.slug, rev.version)
if (seq !== detailRequestSeq) return
const data = (res as any).data || (res as any)
detailContent.value = data.content || ''
} catch (e: any) {
if (seq !== detailRequestSeq) return
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.revisionLoadFailed'))
} finally {
if (seq === detailRequestSeq) loadingDetail.value = false
}
}
async function doRevert() {
if (!selectedRevision.value) return
reverting.value = true
try {
const res = await revertWikiPage(props.kbId, props.slug, selectedRevision.value.version)
const updated = ((res as any).data || (res as any)) as WikiPage
MessagePlugin.success(t('knowledgeEditor.wikiBrowser.revertSuccess', { ver: selectedRevision.value.version }))
emit('reverted', updated)
// Stay open: reload so the just-created snapshot of the pre-revert
// version shows up and the "current" entry reflects the new version.
resetAndLoad()
} catch (e: any) {
MessagePlugin.error(e?.message || t('knowledgeEditor.wikiBrowser.revertFailed'))
} finally {
reverting.value = false
}
}
function diffPrefix(type: WikiDiffLine['type']): string {
return type === 'add' ? '+ ' : type === 'del' ? '- ' : ' '
}
function sourceLabel(source?: string): string {
switch (source) {
case 'user':
return t('knowledgeEditor.wikiBrowser.editSourceUser')
case 'agent':
return t('knowledgeEditor.wikiBrowser.editSourceAgent')
case 'revert':
return t('knowledgeEditor.wikiBrowser.editSourceRevert')
default:
return t('knowledgeEditor.wikiBrowser.editSourcePipeline')
}
}
function sourceTheme(source?: string): 'primary' | 'success' | 'warning' | 'default' {
switch (source) {
case 'user':
return 'success'
case 'agent':
return 'primary'
case 'revert':
return 'warning'
default:
return 'default'
}
}
function formatTime(iso?: string): string {
if (!iso) return ''
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
return d.toLocaleString()
}
</script>
<style scoped>
.wiki-rev-layout {
display: flex;
gap: 16px;
height: 100%;
min-height: 0;
}
.wiki-rev-list {
width: 220px;
flex-shrink: 0;
overflow-y: auto;
border-right: 1px solid var(--td-component-stroke);
padding-right: 12px;
}
.wiki-rev-item {
padding: 8px 10px;
border-radius: 6px;
cursor: pointer;
margin-bottom: 4px;
}
.wiki-rev-item:hover {
background: var(--td-bg-color-container-hover);
}
.wiki-rev-item--active {
background: var(--td-brand-color-light);
}
.wiki-rev-item-head {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.wiki-rev-version {
font-weight: 600;
font-family: var(--td-font-family-mono, monospace);
}
.wiki-rev-item-meta {
margin-top: 4px;
font-size: 12px;
color: var(--td-text-color-placeholder);
word-break: break-all;
}
.wiki-rev-load-more,
.wiki-rev-empty {
text-align: center;
padding: 12px 0;
font-size: 13px;
color: var(--td-text-color-placeholder);
}
.wiki-rev-detail {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.wiki-rev-detail-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.wiki-rev-detail-title {
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wiki-rev-detail-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.wiki-rev-detail-hint {
color: var(--td-text-color-placeholder);
padding: 40px 0;
text-align: center;
}
.wiki-rev-diff {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.wiki-rev-diff-caption {
font-size: 12px;
color: var(--td-text-color-placeholder);
margin-bottom: 8px;
}
.wiki-rev-diff-body,
.wiki-rev-raw {
flex: 1;
overflow: auto;
margin: 0;
padding: 12px;
background: var(--td-bg-color-page);
border-radius: 6px;
font-size: 12px;
line-height: 1.7;
font-family: var(--td-font-family-mono, monospace);
white-space: pre-wrap;
word-break: break-word;
}
.wiki-rev-diff-line {
display: block;
}
.wiki-rev-diff-line--add {
background: var(--td-success-color-1);
color: var(--td-success-color-7);
}
.wiki-rev-diff-line--del {
background: var(--td-error-color-1);
color: var(--td-error-color-6);
text-decoration: line-through;
}
</style>

View File

@ -46,6 +46,9 @@ func NewWikiDeletePageTool(
}
func (t *wikiDeletePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
// Attribute every page write performed by this tool to the agent so
// revision history distinguishes agent edits from pipeline/user ones.
ctx = types.WithWikiEditSource(ctx, types.WikiEditSourceAgent)
var params struct {
Slug string `json:"slug"`
}

View File

@ -49,6 +49,9 @@ func NewWikiRenamePageTool(
}
func (t *wikiRenamePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
// Attribute every page write performed by this tool to the agent so
// revision history distinguishes agent edits from pipeline/user ones.
ctx = types.WithWikiEditSource(ctx, types.WikiEditSourceAgent)
var params struct {
Slug string `json:"slug"`
NewSlug string `json:"new_slug"`

View File

@ -71,6 +71,9 @@ func (t *wikiReplaceTextTool) WithSearchTargets(searchTargets types.SearchTarget
}
func (t *wikiReplaceTextTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
// Attribute every page write performed by this tool to the agent so
// revision history distinguishes agent edits from pipeline/user ones.
ctx = types.WithWikiEditSource(ctx, types.WikiEditSourceAgent)
var params struct {
Slug string `json:"slug"`
OldText string `json:"old_text"`

View File

@ -85,6 +85,9 @@ func (t *wikiWritePageTool) WithSearchTargets(searchTargets types.SearchTargets)
}
func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
// Attribute every page write performed by this tool to the agent so
// revision history distinguishes agent edits from pipeline/user ones.
ctx = types.WithWikiEditSource(ctx, types.WikiEditSourceAgent)
var params struct {
Slug string `json:"slug"`
Title string `json:"title"`

View File

@ -11,6 +11,7 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// ErrWikiPageNotFound is returned when a wiki page is not found
@ -51,21 +52,81 @@ func (r *wikiPageRepository) Create(ctx context.Context, page *types.WikiPage) e
// Update updates an existing wiki page record with optimistic locking.
// Increments version — use only for content changes visible to the user.
// The caller must set page.Version to the expected current version.
//
// The write goes through an explicit column map (not GORM's struct Updates)
// so cleared fields persist: struct Updates skips zero values, which used to
// make "empty the summary" silently not stick while the follow-up UpdateMeta
// map call *did* write empty status — one inconsistent half-update. The map
// covers every column UpdatePage mutates, so no UpdateMeta chaser is needed.
func (r *wikiPageRepository) Update(ctx context.Context, page *types.WikiPage) error {
return updateWikiPageRow(r.db.WithContext(ctx), page)
}
// UpdateWithRevision snapshots the version being superseded and applies the
// update atomically. Doing both in one transaction is what makes the history
// trustworthy: a failed update can no longer leave behind a snapshot of a
// version that is still current, which would show up twice in the history
// and be un-revertable.
func (r *wikiPageRepository) UpdateWithRevision(
ctx context.Context, page *types.WikiPage, rev *types.WikiPageRevision,
) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if rev != nil {
// An already-present (page_id, version) pair means a concurrent
// writer snapshotted the same version first; its copy is
// identical, so leaving it alone is correct.
if err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "page_id"}, {Name: "version"}},
DoNothing: true,
}).Create(rev).Error; err != nil {
return err
}
}
return updateWikiPageRow(tx, page)
})
}
// updateWikiPageRow performs the versioned page write on the given handle
// (plain connection or transaction). On failure page.Version is restored so
// the caller never observes a bumped version for a write that did not land.
func updateWikiPageRow(db *gorm.DB, page *types.WikiPage) error {
expectedVersion := page.Version
page.Version = expectedVersion + 1
result := r.db.WithContext(ctx).
result := db.
Model(page).
Where("id = ? AND version = ?", page.ID, expectedVersion).
Updates(page)
Updates(map[string]interface{}{
"title": page.Title,
"content": page.Content,
"summary": page.Summary,
"page_type": page.PageType,
"status": page.Status,
"aliases": page.Aliases,
"out_links": page.OutLinks,
"source_refs": page.SourceRefs,
"chunk_refs": page.ChunkRefs,
"page_metadata": page.PageMetadata,
"parent_slug": page.ParentSlug,
"folder_id": page.FolderID,
"category_path": page.CategoryPath,
"wiki_path": page.WikiPath,
"depth": page.Depth,
"sort_order": page.SortOrder,
"last_edit_source": page.LastEditSource,
"last_editor_id": page.LastEditorID,
"version": page.Version,
"updated_at": page.UpdatedAt,
})
if result.Error != nil {
page.Version = expectedVersion
return result.Error
}
if result.RowsAffected == 0 {
page.Version = expectedVersion
// Could be not found or version conflict — check which
var count int64
r.db.WithContext(ctx).Model(&types.WikiPage{}).Where("id = ?", page.ID).Count(&count)
db.Model(&types.WikiPage{}).Where("id = ?", page.ID).Count(&count)
if count == 0 {
return ErrWikiPageNotFound
}
@ -74,6 +135,90 @@ func (r *wikiPageRepository) Update(ctx context.Context, page *types.WikiPage) e
return nil
}
// wikiRevisionListColumns is the projection for revision listings — every
// column except the potentially multi-hundred-KB content body.
const wikiRevisionListColumns = "id, tenant_id, knowledge_base_id, page_id, slug, version, " +
"title, page_type, status, summary, aliases, edit_source, editor_id, edited_at, created_at"
// ListRevisions returns snapshots for a page newest-first, content omitted.
func (r *wikiPageRepository) ListRevisions(
ctx context.Context, kbID string, pageID string, limit int, offset int,
) ([]*types.WikiPageRevision, int64, error) {
base := r.db.WithContext(ctx).Model(&types.WikiPageRevision{}).
Where("knowledge_base_id = ? AND page_id = ?", kbID, pageID)
var total int64
if err := base.Count(&total).Error; err != nil {
return nil, 0, err
}
var revs []*types.WikiPageRevision
if err := base.
Select(wikiRevisionListColumns).
Order("version DESC").
Limit(limit).
Offset(offset).
Find(&revs).Error; err != nil {
return nil, 0, err
}
return revs, total, nil
}
// GetRevision returns one snapshot with content.
func (r *wikiPageRepository) GetRevision(
ctx context.Context, kbID string, pageID string, version int,
) (*types.WikiPageRevision, error) {
var rev types.WikiPageRevision
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND page_id = ? AND version = ?", kbID, pageID, version).
First(&rev).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWikiPageNotFound
}
return nil, err
}
return &rev, nil
}
// PruneRevisions applies the two-tier retention described by req: the soft
// cap only touches snapshots whose author is listed as prunable, the hard cap
// applies to everything.
func (r *wikiPageRepository) PruneRevisions(ctx context.Context, req types.WikiRevisionPruneRequest) error {
if req.PageID == "" {
return nil
}
db := r.db.WithContext(ctx)
if req.KeepFromVersion > 0 && len(req.PrunableSources) > 0 {
if err := db.
Where("page_id = ? AND version < ? AND edit_source IN ?",
req.PageID, req.KeepFromVersion, req.PrunableSources).
Delete(&types.WikiPageRevision{}).Error; err != nil {
return err
}
}
if req.HardKeepFromVersion > 0 {
if err := db.
Where("page_id = ? AND version < ?", req.PageID, req.HardKeepFromVersion).
Delete(&types.WikiPageRevision{}).Error; err != nil {
return err
}
}
return nil
}
// DeleteRevisionsByPage hard-deletes a page's whole snapshot history. Pages
// themselves are soft-deleted, but a soft-deleted page is unreachable through
// every read path, so its snapshots would be dead weight — and they are the
// bulkiest rows the wiki stores.
func (r *wikiPageRepository) DeleteRevisionsByPage(ctx context.Context, pageID string) error {
if pageID == "" {
return nil
}
return r.db.WithContext(ctx).
Where("page_id = ?", pageID).
Delete(&types.WikiPageRevision{}).Error
}
// UpdateAutoLinkedContent persists content changes produced by the automatic
// link decorators (cross-link injection, dead-link cleanup) without bumping
// `version`. These passes rewrite the same revision with wiki-link markup

View File

@ -2,6 +2,7 @@ package repository
import (
"context"
"strconv"
"strings"
"testing"
"time"
@ -42,12 +43,39 @@ CREATE TABLE IF NOT EXISTS wiki_pages (
page_metadata TEXT DEFAULT '{}',
aliases TEXT DEFAULT '[]',
version INTEGER NOT NULL DEFAULT 1,
last_edit_source VARCHAR(16) NOT NULL DEFAULT '',
last_editor_id VARCHAR(64) NOT NULL DEFAULT '',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
);
`
// wikiPageRevisionsTestDDL mirrors the production wiki_page_revisions DDL
// (migrations/versioned/000075_wiki_page_revisions.up.sql) for SQLite.
const wikiPageRevisionsTestDDL = `
CREATE TABLE IF NOT EXISTS wiki_page_revisions (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL,
knowledge_base_id VARCHAR(36) NOT NULL,
page_id VARCHAR(36) NOT NULL,
slug VARCHAR(255) NOT NULL,
version INTEGER NOT NULL,
title VARCHAR(512) NOT NULL DEFAULT '',
page_type VARCHAR(32) NOT NULL DEFAULT 'summary',
status VARCHAR(32) NOT NULL DEFAULT 'published',
content TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
aliases TEXT DEFAULT '[]',
edit_source VARCHAR(16) NOT NULL DEFAULT '',
editor_id VARCHAR(64) NOT NULL DEFAULT '',
edited_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_wiki_page_revisions_page_version
ON wiki_page_revisions (page_id, version);
`
// wikiFoldersTestDDL mirrors the production wiki_folders DDL for SQLite.
const wikiFoldersTestDDL = `
CREATE TABLE IF NOT EXISTS wiki_folders (
@ -71,6 +99,12 @@ func setupWikiPagesTestDB(t *testing.T) *gorm.DB {
require.NoError(t, err)
require.NoError(t, db.Exec(wikiPagesTestDDL).Error)
require.NoError(t, db.Exec(wikiFoldersTestDDL).Error)
for _, stmt := range strings.Split(strings.TrimSpace(wikiPageRevisionsTestDDL), ";") {
if strings.TrimSpace(stmt) == "" {
continue
}
require.NoError(t, db.Exec(stmt).Error)
}
return db
}
@ -357,3 +391,132 @@ func TestCountOrphans_SQLiteCountsEmptyInLinks(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, int64(1), got)
}
// makeWikiRevision builds a snapshot row for the given page state.
func makeWikiRevision(page *types.WikiPage, version int, editSource string) *types.WikiPageRevision {
return &types.WikiPageRevision{
ID: uuid.New().String(),
TenantID: page.TenantID,
KnowledgeBaseID: page.KnowledgeBaseID,
PageID: page.ID,
Slug: page.Slug,
Version: version,
Title: page.Title,
PageType: page.PageType,
Status: page.Status,
Content: "content of v" + strconv.Itoa(version),
EditSource: editSource,
EditedAt: time.Now(),
CreatedAt: time.Now(),
}
}
func countWikiRevisions(t *testing.T, db *gorm.DB, pageID string) int64 {
t.Helper()
var n int64
require.NoError(t, db.Model(&types.WikiPageRevision{}).Where("page_id = ?", pageID).Count(&n).Error)
return n
}
func TestUpdateWithRevisionRollsBackSnapshotOnVersionConflict(t *testing.T) {
db := setupWikiPagesTestDB(t)
repo := NewWikiPageRepository(db)
ctx := context.Background()
page := makeWikiPage("kb-tx", "concept/tx", types.WikiPageTypeConcept, types.WikiPageStatusPublished)
require.NoError(t, repo.Create(ctx, page))
// Simulate a writer working from a stale read: it expects v1 while the
// row has already moved on.
require.NoError(t, db.Model(&types.WikiPage{}).Where("id = ?", page.ID).
Update("version", 7).Error)
stale := *page
stale.Version = 1
stale.Content = "loser body"
err := repo.UpdateWithRevision(ctx, &stale, makeWikiRevision(page, 1, types.WikiEditSourceUser))
require.ErrorIs(t, err, ErrWikiPageConflict)
assert.Equal(t, 1, stale.Version, "a rejected write must not leave a bumped version behind")
assert.Zero(t, countWikiRevisions(t, db, page.ID),
"the snapshot must roll back with the failed update, or history would list a still-current version")
}
func TestUpdateWithRevisionIgnoresDuplicateSnapshot(t *testing.T) {
db := setupWikiPagesTestDB(t)
repo := NewWikiPageRepository(db)
ctx := context.Background()
page := makeWikiPage("kb-dup", "concept/dup", types.WikiPageTypeConcept, types.WikiPageStatusPublished)
require.NoError(t, repo.Create(ctx, page))
require.NoError(t, repo.UpdateWithRevision(ctx, page, makeWikiRevision(page, 1, types.WikiEditSourceUser)))
require.Equal(t, 2, page.Version)
// A concurrent writer that already snapshotted v1 must not fail here.
again := *page
again.Version = 2
require.NoError(t, repo.UpdateWithRevision(ctx, &again, makeWikiRevision(page, 1, types.WikiEditSourceUser)))
assert.Equal(t, int64(1), countWikiRevisions(t, db, page.ID))
}
func TestPruneRevisionsKeepsHumanEditsUntilHardCap(t *testing.T) {
db := setupWikiPagesTestDB(t)
repo := NewWikiPageRepository(db)
ctx := context.Background()
page := makeWikiPage("kb-prune", "concept/prune", types.WikiPageTypeConcept, types.WikiPageStatusPublished)
require.NoError(t, repo.Create(ctx, page))
// v1 is a human edit buried under a long tail of pipeline rewrites.
require.NoError(t, db.Create(makeWikiRevision(page, 1, types.WikiEditSourceUser)).Error)
require.NoError(t, db.Create(makeWikiRevision(page, 2, types.WikiEditSourceAgent)).Error)
for v := 3; v <= 120; v++ {
require.NoError(t, db.Create(makeWikiRevision(page, v, types.WikiEditSourcePipeline)).Error)
}
// Soft cap only: pipeline snapshots below v71 go, the two authored ones stay.
require.NoError(t, repo.PruneRevisions(ctx, types.WikiRevisionPruneRequest{
PageID: page.ID,
KeepFromVersion: 121 - types.WikiMaxRevisionsPerPage,
PrunableSources: types.WikiPrunableEditSources,
}))
for _, v := range []int{1, 2} {
_, err := repo.GetRevision(ctx, page.KnowledgeBaseID, page.ID, v)
require.NoError(t, err, "authored v%d must survive pipeline churn", v)
}
_, err := repo.GetRevision(ctx, page.KnowledgeBaseID, page.ID, 3)
require.ErrorIs(t, err, ErrWikiPageNotFound)
assert.Equal(t, int64(types.WikiMaxRevisionsPerPage+2), countWikiRevisions(t, db, page.ID))
// Hard cap ignores authorship.
require.NoError(t, repo.PruneRevisions(ctx, types.WikiRevisionPruneRequest{
PageID: page.ID,
KeepFromVersion: 121 - types.WikiMaxRevisionsPerPage,
PrunableSources: types.WikiPrunableEditSources,
HardKeepFromVersion: 100,
}))
_, err = repo.GetRevision(ctx, page.KnowledgeBaseID, page.ID, 1)
require.ErrorIs(t, err, ErrWikiPageNotFound)
assert.Equal(t, int64(21), countWikiRevisions(t, db, page.ID))
}
func TestDeleteRevisionsByPageOnlyTouchesThatPage(t *testing.T) {
db := setupWikiPagesTestDB(t)
repo := NewWikiPageRepository(db)
ctx := context.Background()
victim := makeWikiPage("kb-del", "concept/victim", types.WikiPageTypeConcept, types.WikiPageStatusPublished)
bystander := makeWikiPage("kb-del", "concept/bystander", types.WikiPageTypeConcept, types.WikiPageStatusPublished)
require.NoError(t, repo.Create(ctx, victim))
require.NoError(t, repo.Create(ctx, bystander))
require.NoError(t, db.Create(makeWikiRevision(victim, 1, types.WikiEditSourceUser)).Error)
require.NoError(t, db.Create(makeWikiRevision(bystander, 1, types.WikiEditSourceUser)).Error)
require.NoError(t, repo.DeleteRevisionsByPage(ctx, victim.ID))
assert.Zero(t, countWikiRevisions(t, db, victim.ID))
assert.Equal(t, int64(1), countWikiRevisions(t, db, bystander.ID))
// An empty id must not turn into a table-wide delete.
require.NoError(t, repo.DeleteRevisionsByPage(ctx, ""))
assert.Equal(t, int64(1), countWikiRevisions(t, db, bystander.ID))
}

View File

@ -83,6 +83,8 @@ func (s *wikiPageService) CreatePage(ctx context.Context, page *types.WikiPage)
if page.Version == 0 {
page.Version = 1
}
page.LastEditSource = types.WikiEditSourceFromContext(ctx)
page.LastEditorID, _ = types.UserIDFromContext(ctx)
stripWikiPageInlineChunkCitations(page)
// Parse outbound links from content
@ -134,6 +136,10 @@ func (s *wikiPageService) UpdatePage(ctx context.Context, page *types.WikiPage)
existing.Status != page.Status ||
!slices.Equal(existing.Aliases, page.Aliases)
// Keep an unmutated copy of the version being replaced: it becomes the
// revision snapshot when this turns out to be a real content change.
prev := *existing
existing.Title = page.Title
existing.Content = page.Content
existing.Summary = page.Summary
@ -161,15 +167,19 @@ func (s *wikiPageService) UpdatePage(ctx context.Context, page *types.WikiPage)
normalizeWikiHierarchy(existing)
if contentChanged {
if err := s.repo.Update(ctx, existing); err != nil {
// The new version is authored by whoever is driving this write.
existing.LastEditSource = types.WikiEditSourceFromContext(ctx)
existing.LastEditorID, _ = types.UserIDFromContext(ctx)
// Snapshot the superseded version and write the new one atomically,
// so the content of every past version is preserved and a failed
// update leaves no snapshot behind.
if err := s.repo.UpdateWithRevision(ctx, existing, revisionFromPage(&prev)); err != nil {
return nil, fmt.Errorf("update wiki page: %w", err)
}
// GORM's struct Updates path skips zero values, so persist hierarchy
// metadata through the explicit map path as well. This keeps clearing
// parent/category fields deterministic without changing version again.
if err := s.repo.UpdateMeta(ctx, existing); err != nil {
return nil, fmt.Errorf("update wiki page hierarchy meta: %w", err)
}
// Bound per-page history; best-effort — a failed prune only means
// slightly more storage until the next content change.
s.pruneRevisions(ctx, existing.ID, existing.Version)
} else {
// No user-visible change — persist bookkeeping fields but preserve
// the version so downstream consumers can rely on it.
@ -220,6 +230,117 @@ func (s *wikiPageService) UpdateAutoLinkedContent(ctx context.Context, page *typ
return nil
}
// revisionFromPage builds the immutable snapshot row for the given page
// state. EditSource on the snapshot is the author of THAT version — the
// page's provenance columns as they stood while the version was current —
// not whoever is performing the write that supersedes it.
func revisionFromPage(p *types.WikiPage) *types.WikiPageRevision {
return &types.WikiPageRevision{
ID: uuid.New().String(),
TenantID: p.TenantID,
KnowledgeBaseID: p.KnowledgeBaseID,
PageID: p.ID,
Slug: p.Slug,
Version: p.Version,
Title: p.Title,
PageType: p.PageType,
Status: p.Status,
Content: p.Content,
Summary: p.Summary,
Aliases: append(types.StringArray(nil), p.Aliases...),
EditSource: types.NormalizeWikiEditSource(p.LastEditSource),
EditorID: p.LastEditorID,
EditedAt: p.UpdatedAt,
CreatedAt: time.Now(),
}
}
// pruneRevisions bounds one page's snapshot history after it advanced to
// currentVersion. Machine-authored snapshots are dropped once they fall out
// of the recent window; human/agent/revert ones survive until the hard cap,
// so pipeline churn on a hot page cannot evict the edits users care about.
func (s *wikiPageService) pruneRevisions(ctx context.Context, pageID string, currentVersion int) {
req := types.WikiRevisionPruneRequest{
PageID: pageID,
KeepFromVersion: currentVersion - types.WikiMaxRevisionsPerPage,
PrunableSources: types.WikiPrunableEditSources,
HardKeepFromVersion: currentVersion - types.WikiMaxRevisionsHardCap,
}
if req.KeepFromVersion <= 0 && req.HardKeepFromVersion <= 0 {
return
}
if err := s.repo.PruneRevisions(ctx, req); err != nil {
logger.Warnf(ctx, "prune wiki page revisions for %s failed: %v", pageID, err)
}
}
// ErrWikiRevertToCurrentVersion is returned when a revert targets the version
// the page is already on — a client-side mistake (usually a stale history
// list), not a server fault, so handlers map it to 400.
var ErrWikiRevertToCurrentVersion = errors.New("cannot revert to the current version")
// ListRevisions returns the stored historical snapshots for a page (newest
// first, content omitted) plus the page's current version.
func (s *wikiPageService) ListRevisions(
ctx context.Context, kbID string, slug string, limit int, offset int,
) (*types.WikiPageRevisionListResponse, error) {
page, err := s.repo.GetBySlug(ctx, kbID, slug)
if err != nil {
return nil, err
}
revs, total, err := s.repo.ListRevisions(ctx, kbID, page.ID, limit, offset)
if err != nil {
return nil, fmt.Errorf("list wiki page revisions: %w", err)
}
return &types.WikiPageRevisionListResponse{
Revisions: revs,
Total: total,
CurrentVersion: page.Version,
}, nil
}
// GetRevision returns one historical snapshot with content.
func (s *wikiPageService) GetRevision(
ctx context.Context, kbID string, slug string, version int,
) (*types.WikiPageRevision, error) {
page, err := s.repo.GetBySlug(ctx, kbID, slug)
if err != nil {
return nil, err
}
return s.repo.GetRevision(ctx, kbID, page.ID, version)
}
// RevertPageToVersion rolls the page back to a stored revision by applying
// that revision's content fields as a regular edit: the pre-revert state is
// snapshotted, version advances, links are re-parsed. Placement (folder,
// sort order) and provenance refs keep their current values — a revert is
// about content, not about undoing directory moves.
func (s *wikiPageService) RevertPageToVersion(
ctx context.Context, kbID string, slug string, version int,
) (*types.WikiPage, error) {
page, err := s.repo.GetBySlug(ctx, kbID, slug)
if err != nil {
return nil, err
}
if version == page.Version {
return nil, ErrWikiRevertToCurrentVersion
}
rev, err := s.repo.GetRevision(ctx, kbID, page.ID, version)
if err != nil {
return nil, err
}
target := *page
target.Title = rev.Title
target.Content = rev.Content
target.Summary = rev.Summary
target.PageType = rev.PageType
target.Status = rev.Status
target.Aliases = append(types.StringArray(nil), rev.Aliases...)
return s.UpdatePage(types.WithWikiEditSource(ctx, types.WikiEditSourceRevert), &target)
}
// GetPageBySlug retrieves a wiki page by its slug
func (s *wikiPageService) GetPageBySlug(ctx context.Context, kbID string, slug string) (*types.WikiPage, error) {
page, err := s.repo.GetBySlug(ctx, kbID, slug)
@ -288,6 +409,13 @@ func (s *wikiPageService) DeletePage(ctx context.Context, kbID string, slug stri
return err
}
// Drop the snapshot history too: the page is gone from every read path,
// so its revisions are unreachable rows holding full content bodies.
// Best-effort — the page is already deleted and cannot be rolled back.
if err := s.repo.DeleteRevisionsByPage(ctx, page.ID); err != nil {
logger.Warnf(ctx, "delete wiki page revisions for %s failed: %v", page.ID, err)
}
// Delete synced chunk
s.deleteChunkForPage(ctx, page)
@ -1101,8 +1229,13 @@ func (s *wikiPageService) removeInLinks(ctx context.Context, kbID string, source
}
}
// deleteChunkForPage removes the synced chunk for a wiki page
// deleteChunkForPage removes the synced chunk for a wiki page. Chunk sync is
// optional wiring, so a service built without a chunk repository just skips
// it rather than taking the delete down with it.
func (s *wikiPageService) deleteChunkForPage(ctx context.Context, page *types.WikiPage) {
if s.chunkRepo == nil {
return
}
chunkID := "wp-" + page.ID
if err := s.chunkRepo.DeleteChunk(ctx, page.TenantID, chunkID); err != nil {
logger.Warnf(ctx, "wiki: failed to delete chunk for page %s: %v", page.Slug, err)

View File

@ -0,0 +1,232 @@
package service
import (
"context"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
ifaces "github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type wikiRevisionTestHarness struct {
svc ifaces.WikiPageService
}
func newWikiRevisionTestService(t *testing.T) (context.Context, wikiRevisionTestHarness, *gorm.DB) {
t.Helper()
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
repo := repository.NewWikiPageRepository(db)
svc := NewWikiPageService(repo, nil, nil, nil, nil)
return context.Background(), wikiRevisionTestHarness{svc: svc}, db
}
func TestUpdateWikiPageSnapshotsSupersededVersion(t *testing.T) {
ctx, h, _ := newWikiRevisionTestService(t)
const kb = "kb-rev"
created, err := h.svc.CreatePage(types.WithWikiEditSource(ctx, types.WikiEditSourceUser), &types.WikiPage{
KnowledgeBaseID: kb, TenantID: 1, Slug: "concept/rag",
Title: "RAG", PageType: types.WikiPageTypeConcept, Content: "v1 body", Summary: "s1",
})
require.NoError(t, err)
require.Equal(t, 1, created.Version)
require.Equal(t, types.WikiEditSourceUser, created.LastEditSource)
// First real edit: v1 must be snapshotted, v2 becomes current.
edit := *created
edit.Content = "v2 body"
updated, err := h.svc.UpdatePage(types.WithWikiEditSource(ctx, types.WikiEditSourceAgent), &edit)
require.NoError(t, err)
require.Equal(t, 2, updated.Version)
require.Equal(t, types.WikiEditSourceAgent, updated.LastEditSource)
resp, err := h.svc.ListRevisions(ctx, kb, "concept/rag", 50, 0)
require.NoError(t, err)
require.Equal(t, 2, resp.CurrentVersion)
require.Equal(t, int64(1), resp.Total)
require.Len(t, resp.Revisions, 1)
require.Equal(t, 1, resp.Revisions[0].Version)
// Snapshot attribution is the author of the superseded version, not the
// editor that replaced it.
require.Equal(t, types.WikiEditSourceUser, resp.Revisions[0].EditSource)
// List mode omits the content column.
require.Empty(t, resp.Revisions[0].Content)
rev, err := h.svc.GetRevision(ctx, kb, "concept/rag", 1)
require.NoError(t, err)
require.Equal(t, "v1 body", rev.Content)
// Bookkeeping-only write (identical content) must not create a snapshot.
same := *updated
_, err = h.svc.UpdatePage(ctx, &same)
require.NoError(t, err)
resp, err = h.svc.ListRevisions(ctx, kb, "concept/rag", 50, 0)
require.NoError(t, err)
require.Equal(t, int64(1), resp.Total)
require.Equal(t, 2, resp.CurrentVersion)
}
func TestUpdateWikiPagePersistsClearedFields(t *testing.T) {
ctx, h, _ := newWikiRevisionTestService(t)
const kb = "kb-clear"
created, err := h.svc.CreatePage(ctx, &types.WikiPage{
KnowledgeBaseID: kb, TenantID: 1, Slug: "concept/x",
Title: "X", PageType: types.WikiPageTypeConcept, Content: "body", Summary: "to be cleared",
})
require.NoError(t, err)
edit := *created
edit.Summary = ""
updated, err := h.svc.UpdatePage(ctx, &edit)
require.NoError(t, err)
require.Equal(t, 2, updated.Version)
require.Empty(t, updated.Summary)
// The cleared value must actually be stored, not skipped by a zero-value
// aware write path: a fresh update with identical fields must be treated
// as a no-op (no version bump).
again := *updated
roundTripped, err := h.svc.UpdatePage(ctx, &again)
require.NoError(t, err)
require.Equal(t, 2, roundTripped.Version)
require.Empty(t, roundTripped.Summary)
}
func TestRevertWikiPageToVersion(t *testing.T) {
ctx, h, _ := newWikiRevisionTestService(t)
const kb = "kb-revert"
created, err := h.svc.CreatePage(ctx, &types.WikiPage{
KnowledgeBaseID: kb, TenantID: 1, Slug: "entity/acme",
Title: "Acme", PageType: types.WikiPageTypeEntity, Content: "original body", Summary: "s1",
})
require.NoError(t, err)
edit := *created
edit.Content = "rewritten body"
edit.Title = "Acme Corp"
_, err = h.svc.UpdatePage(ctx, &edit)
require.NoError(t, err)
// Reverting to the current version is a client mistake, and must be
// distinguishable so the handler can answer 400 rather than 500.
_, err = h.svc.RevertPageToVersion(ctx, kb, "entity/acme", 2)
require.ErrorIs(t, err, ErrWikiRevertToCurrentVersion)
reverted, err := h.svc.RevertPageToVersion(ctx, kb, "entity/acme", 1)
require.NoError(t, err)
require.Equal(t, 3, reverted.Version, "revert applies as a fresh edit")
require.Equal(t, "original body", reverted.Content)
require.Equal(t, "Acme", reverted.Title)
require.Equal(t, types.WikiEditSourceRevert, reverted.LastEditSource)
// Both superseded versions are now snapshotted, so the revert itself is
// undoable.
resp, err := h.svc.ListRevisions(ctx, kb, "entity/acme", 50, 0)
require.NoError(t, err)
require.Equal(t, int64(2), resp.Total)
require.Equal(t, 2, resp.Revisions[0].Version)
rev2, err := h.svc.GetRevision(ctx, kb, "entity/acme", 2)
require.NoError(t, err)
require.Equal(t, "rewritten body", rev2.Content)
}
func TestWikiPageRevisionsArePruned(t *testing.T) {
ctx, h, db := newWikiRevisionTestService(t)
const kb = "kb-prune-rev"
page, err := h.svc.CreatePage(ctx, &types.WikiPage{
KnowledgeBaseID: kb, TenantID: 1, Slug: "concept/hot",
Title: "Hot", PageType: types.WikiPageTypeConcept, Content: "v1", Summary: "s",
})
require.NoError(t, err)
total := types.WikiMaxRevisionsPerPage + 5
for i := 2; i <= total+1; i++ {
edit := *page
edit.Content = fmt.Sprintf("v%d", i)
page, err = h.svc.UpdatePage(ctx, &edit)
require.NoError(t, err)
}
require.Equal(t, total+1, page.Version)
var count int64
require.NoError(t, db.Model(&types.WikiPageRevision{}).Where("page_id = ?", page.ID).Count(&count).Error)
require.LessOrEqual(t, count, int64(types.WikiMaxRevisionsPerPage))
// The newest snapshot survives, the oldest is gone.
_, err = h.svc.GetRevision(ctx, kb, "concept/hot", page.Version-1)
require.NoError(t, err)
_, err = h.svc.GetRevision(ctx, kb, "concept/hot", 1)
require.Error(t, err)
}
// A page the pipeline rewrites constantly must not lose the handful of human
// edits that motivated keeping history in the first place.
func TestPipelineChurnDoesNotEvictHumanRevisions(t *testing.T) {
ctx, h, _ := newWikiRevisionTestService(t)
const kb = "kb-mixed-rev"
page, err := h.svc.CreatePage(types.WithWikiEditSource(ctx, types.WikiEditSourceUser), &types.WikiPage{
KnowledgeBaseID: kb, TenantID: 1, Slug: "concept/hub",
Title: "Hub", PageType: types.WikiPageTypeConcept, Content: "handwritten v1", Summary: "s",
})
require.NoError(t, err)
// One more human edit, then a long tail of pipeline rewrites.
edit := *page
edit.Content = "handwritten v2"
page, err = h.svc.UpdatePage(types.WithWikiEditSource(ctx, types.WikiEditSourceUser), &edit)
require.NoError(t, err)
for i := 0; i < types.WikiMaxRevisionsPerPage+10; i++ {
next := *page
next.Content = fmt.Sprintf("pipeline rewrite %d", i)
page, err = h.svc.UpdatePage(ctx, &next)
require.NoError(t, err)
}
v1, err := h.svc.GetRevision(ctx, kb, "concept/hub", 1)
require.NoError(t, err, "the first human version must outlive pipeline churn")
require.Equal(t, "handwritten v1", v1.Content)
v2, err := h.svc.GetRevision(ctx, kb, "concept/hub", 2)
require.NoError(t, err)
require.Equal(t, "handwritten v2", v2.Content)
// Old pipeline snapshots are still pruned.
_, err = h.svc.GetRevision(ctx, kb, "concept/hub", 3)
require.Error(t, err)
}
func TestDeletePageDropsRevisionHistory(t *testing.T) {
ctx, h, db := newWikiRevisionTestService(t)
const kb = "kb-del-rev"
page, err := h.svc.CreatePage(ctx, &types.WikiPage{
KnowledgeBaseID: kb, TenantID: 1, Slug: "concept/doomed",
Title: "Doomed", PageType: types.WikiPageTypeConcept, Content: "v1", Summary: "s",
})
require.NoError(t, err)
edit := *page
edit.Content = "v2"
page, err = h.svc.UpdatePage(ctx, &edit)
require.NoError(t, err)
var before int64
require.NoError(t, db.Model(&types.WikiPageRevision{}).Where("page_id = ?", page.ID).Count(&before).Error)
require.Equal(t, int64(1), before)
require.NoError(t, h.svc.DeletePage(ctx, kb, "concept/doomed"))
var after int64
require.NoError(t, db.Model(&types.WikiPageRevision{}).Where("page_id = ?", page.ID).Count(&after).Error)
require.Zero(t, after, "a deleted page must not leave unreachable content snapshots behind")
}

View File

@ -17,7 +17,7 @@ import (
func TestPruneEmptyFolderChainsDeletesOnlyEmptyCandidateAncestors(t *testing.T) {
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}))
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
ctx := context.Background()
repo := repository.NewWikiPageRepository(db)
@ -73,7 +73,7 @@ func TestStripWikiInlineChunkCitationsPreservesOrdinaryMarkdown(t *testing.T) {
func TestUpdateWikiPagePersistsAndClearsAliases(t *testing.T) {
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}))
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
ctx := context.Background()
repo := repository.NewWikiPageRepository(db)
@ -176,7 +176,7 @@ func TestParseOutLinks(t *testing.T) {
func TestRepairContentLinks(t *testing.T) {
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}))
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}, &types.WikiPageRevision{}))
ctx := context.Background()
repo := repository.NewWikiPageRepository(db)

View File

@ -1,11 +1,13 @@
package handler
import (
"context"
stderrors "errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
@ -363,16 +365,53 @@ func (h *WikiPageHandler) CreatePage(c *gin.Context) {
page.KnowledgeBaseID = kbID
page.TenantID = tenantID
page.PageType = strings.TrimSpace(page.PageType)
page.Status = strings.TrimSpace(page.Status)
if page.PageType != "" && !types.IsValidWikiPageType(page.PageType) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid page_type: " + page.PageType})
return
}
if page.Status != "" && !types.IsValidWikiPageStatus(page.Status) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status: " + page.Status})
return
}
created, err := h.wikiService.CreatePage(c.Request.Context(), &page)
ctx := types.WithWikiEditSource(c.Request.Context(), types.WikiEditSourceUser)
created, err := h.wikiService.CreatePage(ctx, &page)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
h.appendManualLogEntry(ctx, created, "manual_create", "Page created manually")
c.JSON(http.StatusCreated, created)
}
// appendManualLogEntry records a manual page mutation in the wiki operation
// log so human/agent-driven edits show up in the same event feed as ingest.
// Best-effort: a log write failure must never fail the edit itself.
func (h *WikiPageHandler) appendManualLogEntry(
ctx context.Context, page *types.WikiPage, action string, summary string,
) {
if h.logEntryService == nil || page == nil {
return
}
entry := &types.WikiLogEntry{
TenantID: page.TenantID,
KnowledgeBaseID: page.KnowledgeBaseID,
Action: action,
// Manual edits have no source document, so the log feed's title slot
// would fall back to a placeholder. Use the page title instead.
DocTitle: page.Title,
Summary: summary,
PagesAffected: types.WikiLogPageRefs{{Slug: page.Slug, Title: page.Title}},
CreatedAt: time.Now(),
}
if err := h.logEntryService.AppendBatch(ctx, []*types.WikiLogEntry{entry}); err != nil {
logger.Warnf(ctx, "wiki: failed to append %s log entry for %s: %v", action, page.Slug, err)
}
}
// GetPage godoc
// @Summary Get a wiki page by slug
// @Description Retrieve a wiki page by its slug
@ -412,19 +451,25 @@ func (h *WikiPageHandler) GetPage(c *gin.Context) {
// UpdatePage godoc
// @Summary Update a wiki page
// @Description Update an existing wiki page by slug
// @Description Partially update a wiki page by slug. Absent fields keep
// @Description their stored value. When `version` is > 0 it acts as an
// @Description optimistic-lock guard: a mismatch with the stored version
// @Description returns 409 together with the current version so the client
// @Description can reload and re-apply.
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param slug path string true "Page slug"
// @Param page body types.WikiPage true "Updated wiki page data"
// @Param kb_id path string true "Knowledge base ID"
// @Param slug path string true "Page slug"
// @Param page body types.WikiPageUpdateRequest true "Fields to update"
// @Success 200 {object} types.WikiPage
// @Failure 400 {object} errors.AppError
// @Failure 404 {object} errors.AppError
// @Failure 409 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/pages/{slug} [put]
func (h *WikiPageHandler) UpdatePage(c *gin.Context) {
kbID, tenantID, err := h.validateWikiKB(c)
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@ -436,17 +481,15 @@ func (h *WikiPageHandler) UpdatePage(c *gin.Context) {
return
}
var page types.WikiPage
if err := c.ShouldBindJSON(&page); err != nil {
var req types.WikiPageUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
page.KnowledgeBaseID = kbID
page.TenantID = tenantID
page.Slug = slug
ctx := types.WithWikiEditSource(c.Request.Context(), types.WikiEditSourceUser)
updated, err := h.wikiService.UpdatePage(c.Request.Context(), &page)
existing, err := h.wikiService.GetPageBySlug(ctx, kbID, slug)
if err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
@ -455,7 +498,195 @@ func (h *WikiPageHandler) UpdatePage(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if req.Version > 0 && req.Version != existing.Version {
c.JSON(http.StatusConflict, gin.H{
"error": "Wiki page was modified by someone else",
"current_version": existing.Version,
})
return
}
// Merge the provided fields onto the stored page so absent fields keep
// their value — the service's UpdatePage semantics are "full intended
// state", and sending it a half-empty struct would clear real data.
page := *existing
if req.Title != nil {
page.Title = strings.TrimSpace(*req.Title)
}
if req.Content != nil {
page.Content = *req.Content
}
if req.Summary != nil {
page.Summary = *req.Summary
}
if req.PageType != nil {
page.PageType = strings.TrimSpace(*req.PageType)
if !types.IsValidWikiPageType(page.PageType) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid page_type: " + page.PageType})
return
}
}
if req.Status != nil {
page.Status = strings.TrimSpace(*req.Status)
if !types.IsValidWikiPageStatus(page.Status) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status: " + page.Status})
return
}
}
if req.Aliases != nil {
page.Aliases = *req.Aliases
}
updated, err := h.wikiService.UpdatePage(ctx, &page)
if err != nil {
switch {
case stderrors.Is(err, repository.ErrWikiPageNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
case stderrors.Is(err, repository.ErrWikiPageConflict):
c.JSON(http.StatusConflict, gin.H{"error": "Wiki page was modified by someone else"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
if updated.Version != existing.Version {
h.appendManualLogEntry(ctx, updated, "manual_edit", "Page edited manually")
}
c.JSON(http.StatusOK, updated)
}
// ListRevisions godoc
// @Summary List wiki page revisions
// @Description Returns the stored historical snapshots for a page, newest
// @Description first (content omitted), plus the current version. Passing
// @Description `version` returns that single snapshot with full content.
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param slug path string true "Page slug"
// @Param version query int false "Return this single revision with content"
// @Param limit query int false "Page size (default 50, max 200)"
// @Param offset query int false "Offset into the newest-first list"
// @Success 200 {object} types.WikiPageRevisionListResponse
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/revisions/{slug} [get]
func (h *WikiPageHandler) ListRevisions(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
slug := getSlugParam(c)
if slug == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
return
}
ctx := c.Request.Context()
if raw := c.Query("version"); raw != "" {
version, parseErr := strconv.Atoi(raw)
if parseErr != nil || version < 1 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid version"})
return
}
rev, err := h.wikiService.GetRevision(ctx, kbID, slug, version)
if err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page revision not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, rev)
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
if limit < 1 {
limit = 50
}
if limit > 200 {
limit = 200
}
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
if offset < 0 {
offset = 0
}
resp, err := h.wikiService.ListRevisions(ctx, kbID, slug, limit, offset)
if err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, resp)
}
// RevertPage godoc
// @Summary Revert a wiki page to an earlier revision
// @Description Rolls the page (slug in the body, like move-page) back to
// @Description the content of the given stored revision. Applied as a
// @Description regular edit: the pre-revert state is snapshotted and the
// @Description version advances.
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param revert body types.WikiPageRevertRequest true "Revert target"
// @Success 200 {object} types.WikiPage
// @Failure 400 {object} errors.AppError
// @Failure 404 {object} errors.AppError
// @Failure 409 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/revert [post]
func (h *WikiPageHandler) RevertPage(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var req types.WikiPageRevertRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
slug := strings.TrimSpace(req.Slug)
if slug == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
return
}
if req.Version < 1 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid version"})
return
}
ctx := c.Request.Context()
updated, err := h.wikiService.RevertPageToVersion(ctx, kbID, slug, req.Version)
if err != nil {
switch {
case stderrors.Is(err, repository.ErrWikiPageNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page or revision not found"})
case stderrors.Is(err, repository.ErrWikiPageConflict):
c.JSON(http.StatusConflict, gin.H{"error": "Wiki page was modified by someone else"})
case stderrors.Is(err, service.ErrWikiRevertToCurrentVersion):
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
h.appendManualLogEntry(ctx, updated,
"revert", fmt.Sprintf("Page reverted to v%d", req.Version))
c.JSON(http.StatusOK, updated)
}
@ -482,7 +713,11 @@ func (h *WikiPageHandler) DeletePage(c *gin.Context) {
return
}
if err := h.wikiService.DeletePage(c.Request.Context(), kbID, slug); err != nil {
ctx := c.Request.Context()
// Load first so the log entry can carry the page title after deletion.
page, _ := h.wikiService.GetPageBySlug(ctx, kbID, slug)
if err := h.wikiService.DeletePage(ctx, kbID, slug); err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
return
@ -491,6 +726,7 @@ func (h *WikiPageHandler) DeletePage(c *gin.Context) {
return
}
h.appendManualLogEntry(ctx, page, "manual_delete", "Page deleted manually")
c.Status(http.StatusNoContent)
}

View File

@ -126,6 +126,7 @@ func TestWikiReadRoutesDenyCrossTenantKB(t *testing.T) {
"/api/v1/knowledgebase/kb-victim/wiki/search?q=test",
"/api/v1/knowledgebase/kb-victim/wiki/lint",
"/api/v1/knowledgebase/kb-victim/wiki/issues",
"/api/v1/knowledgebase/kb-victim/wiki/revisions/secret-page",
}
for _, path := range paths {
@ -189,6 +190,7 @@ func TestWikiWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
{http.MethodPost, "/api/v1/knowledgebase/kb-other/wiki/rebuild-links"},
{http.MethodPost, "/api/v1/knowledgebase/kb-other/wiki/auto-fix"},
{http.MethodPut, "/api/v1/knowledgebase/kb-other/wiki/issues/1/status"},
{http.MethodPost, "/api/v1/knowledgebase/kb-other/wiki/revert"},
}
for _, tc := range cases {

View File

@ -295,6 +295,11 @@ func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHan
wiki.PUT("/pages/*slug", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdatePage)
wiki.DELETE("/pages/*slug", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.DeletePage)
// Revision history (slug is a catch-all like /pages; revert carries
// the slug in the body for the same reason move-page does)
wikiRead.GET("/revisions/*slug", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListRevisions)
wiki.POST("/revert", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.RevertPage)
// Folder tree (directory nodes)
wikiRead.GET("/folders", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListFolders)
wiki.POST("/folders", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.CreateFolder)

View File

@ -29,6 +29,10 @@ const (
SessionTenantIDContextKey ContextKey = "SessionTenantID"
// EmbedQueryContextKey is the context key for embedding query text
EmbedQueryContextKey ContextKey = "EmbedQuery"
// WikiEditSourceContextKey carries who is authoring the current wiki
// page write (user / agent / revert). Absent means the wiki ingest
// pipeline. See types.WithWikiEditSource.
WikiEditSourceContextKey ContextKey = "WikiEditSource"
// LanguageContextKey is the context key for user language preference (e.g. "zh-CN", "en-US")
LanguageContextKey ContextKey = "Language"
// EmbedVisitorContextKey is the anonymous visitor id for embed OAuth isolation.

View File

@ -54,6 +54,20 @@ func UserIDFromContext(ctx context.Context) (string, bool) {
return v, ok && v != ""
}
// WithWikiEditSource marks ctx so wiki page writes performed under it are
// attributed to the given edit source (WikiEditSourceUser / Agent / Revert).
// Writes without the mark are attributed to the ingest pipeline.
func WithWikiEditSource(ctx context.Context, source string) context.Context {
return context.WithValue(ctx, WikiEditSourceContextKey, NormalizeWikiEditSource(source))
}
// WikiEditSourceFromContext returns the wiki edit source carried by ctx,
// defaulting to WikiEditSourcePipeline when absent.
func WikiEditSourceFromContext(ctx context.Context) string {
v, _ := ctx.Value(WikiEditSourceContextKey).(string)
return NormalizeWikiEditSource(v)
}
// TaskInitiator is the authenticated caller that submitted an asynchronous
// task. Workers restore it into their context so audit entries describe who
// initiated the operation, while tasks created by schedulers remain

View File

@ -215,6 +215,21 @@ type WikiPageService interface {
// SearchPages performs full-text search over wiki pages.
SearchPages(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error)
// ListRevisions returns the stored historical snapshots for a page
// (newest first, content omitted) plus the total snapshot count and the
// page's current version. The current version itself has no revision
// row — it lives in wiki_pages.
ListRevisions(ctx context.Context, kbID string, slug string, limit int, offset int) (*types.WikiPageRevisionListResponse, error)
// GetRevision returns one historical snapshot (content included).
GetRevision(ctx context.Context, kbID string, slug string, version int) (*types.WikiPageRevision, error)
// RevertPageToVersion rolls the page back to the content of the given
// stored revision by applying it as a regular edit: the pre-revert state
// is snapshotted, version advances, and links are re-parsed. The edit is
// attributed to WikiEditSourceRevert.
RevertPageToVersion(ctx context.Context, kbID string, slug string, version int) (*types.WikiPage, error)
// CreateIssue logs a new issue for a wiki page.
CreateIssue(ctx context.Context, issue *types.WikiPageIssue) (*types.WikiPageIssue, error)
@ -374,6 +389,26 @@ type WikiPageRepository interface {
// CountOrphans returns the number of pages with no inbound links.
CountOrphans(ctx context.Context, kbID string) (int64, error)
// UpdateWithRevision snapshots the version being superseded and applies
// the page update in a single transaction, so history can never contain
// a snapshot of a version that is still current. Inserting an already-
// present (page_id, version) pair is a silent no-op.
UpdateWithRevision(ctx context.Context, page *types.WikiPage, rev *types.WikiPageRevision) error
// ListRevisions returns snapshots for a page newest-first (content
// column omitted) plus the total snapshot count.
ListRevisions(ctx context.Context, kbID string, pageID string, limit int, offset int) ([]*types.WikiPageRevision, int64, error)
// GetRevision returns one snapshot with content.
GetRevision(ctx context.Context, kbID string, pageID string, version int) (*types.WikiPageRevision, error)
// PruneRevisions bounds per-page history storage using the two-tier
// retention described by the request.
PruneRevisions(ctx context.Context, req types.WikiRevisionPruneRequest) error
// DeleteRevisionsByPage hard-deletes a page's entire snapshot history.
DeleteRevisionsByPage(ctx context.Context, pageID string) error
// CreateIssue inserts a new wiki page issue record.
CreateIssue(ctx context.Context, issue *types.WikiPageIssue) error

View File

@ -140,6 +140,29 @@ const (
WikiPageStatusArchived = "archived"
)
// IsValidWikiPageType reports whether pageType is one of the known page
// types. Unknown values would silently disappear from the type-filtered
// listings the browser is built on, so write paths reject them.
func IsValidWikiPageType(pageType string) bool {
switch pageType {
case WikiPageTypeSummary, WikiPageTypeEntity, WikiPageTypeConcept,
WikiPageTypeIndex, WikiPageTypeLog, WikiPageTypeSynthesis, WikiPageTypeComparison:
return true
default:
return false
}
}
// IsValidWikiPageStatus reports whether status is one of the known statuses.
func IsValidWikiPageStatus(status string) bool {
switch status {
case WikiPageStatusDraft, WikiPageStatusPublished, WikiPageStatusArchived:
return true
default:
return false
}
}
// WikiPage represents a single wiki page in a wiki knowledge base.
// Wiki pages are LLM-generated, interlinked markdown documents that form
// a persistent, compounding knowledge artifact.
@ -212,6 +235,14 @@ type WikiPage struct {
// sync from background jobs) leave it untouched so it can be used as a
// real "the page was edited" signal.
Version int `json:"version" gorm:"default:1"`
// LastEditSource records who authored the CURRENT version: pipeline |
// agent | user | revert. Empty for legacy rows (treated as pipeline).
// When the version is superseded this value travels into the revision
// snapshot, so each historical version keeps its own author kind.
LastEditSource string `json:"last_edit_source,omitempty" gorm:"type:varchar(16);default:''"`
// LastEditorID is the user id of the caller that produced the current
// version (empty for background pipeline writes).
LastEditorID string `json:"last_editor_id,omitempty" gorm:"type:varchar(64);default:''"`
// Creation time
CreatedAt time.Time `json:"created_at"`
// Last update time
@ -225,6 +256,135 @@ func (WikiPage) TableName() string {
return "wiki_pages"
}
// Wiki edit source constants describe who authored a page version. Stored in
// WikiPage.LastEditSource (current version) and WikiPageRevision.EditSource
// (historical versions).
const (
// WikiEditSourcePipeline marks versions written by the wiki ingest
// pipeline (also the fallback for legacy rows with an empty source).
WikiEditSourcePipeline = "pipeline"
// WikiEditSourceAgent marks versions written through the agent wiki
// tools (wiki_write_page / wiki_replace_text / ...).
WikiEditSourceAgent = "agent"
// WikiEditSourceUser marks versions written by a human through the
// wiki editor UI / REST API.
WikiEditSourceUser = "user"
// WikiEditSourceRevert marks versions produced by rolling the page
// back to an earlier revision.
WikiEditSourceRevert = "revert"
)
// NormalizeWikiEditSource maps unknown / empty values to
// WikiEditSourcePipeline so legacy rows and forgotten call sites degrade to
// the historical behavior ("the machine wrote this").
func NormalizeWikiEditSource(source string) string {
switch source {
case WikiEditSourceAgent, WikiEditSourceUser, WikiEditSourceRevert, WikiEditSourcePipeline:
return source
default:
return WikiEditSourcePipeline
}
}
// WikiPageRevision is one immutable snapshot of a superseded page version.
// The current version lives only in wiki_pages; when an edit replaces
// version V the pre-edit state is inserted here as (page_id, V) inside the
// same transaction, so every historical version stays diffable and
// revertable. Rows are pruned per WikiRevisionPruneRequest to bound storage
// on hot pipeline pages.
type WikiPageRevision struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"index"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index:idx_wiki_page_revisions_kb_slug"`
PageID string `json:"page_id" gorm:"type:varchar(36);uniqueIndex:idx_wiki_page_revisions_page_version"`
Slug string `json:"slug" gorm:"type:varchar(255);index:idx_wiki_page_revisions_kb_slug"`
Version int `json:"version" gorm:"uniqueIndex:idx_wiki_page_revisions_page_version"`
Title string `json:"title" gorm:"type:varchar(512)"`
PageType string `json:"page_type" gorm:"type:varchar(32)"`
Status string `json:"status" gorm:"type:varchar(32)"`
Content string `json:"content,omitempty" gorm:"type:text"`
Summary string `json:"summary" gorm:"type:text"`
Aliases StringArray `json:"aliases" gorm:"type:json"`
// Author of THIS version (same semantics as WikiPage.LastEditSource).
EditSource string `json:"edit_source" gorm:"type:varchar(16);default:''"`
EditorID string `json:"editor_id" gorm:"type:varchar(64);default:''"`
// When this version was authored (the page's updated_at while current).
EditedAt time.Time `json:"edited_at"`
CreatedAt time.Time `json:"created_at"`
}
// TableName specifies the database table name
func (WikiPageRevision) TableName() string {
return "wiki_page_revisions"
}
// Snapshot retention is two-tiered, because the two kinds of history have
// very different value. A hot hub page is rewritten by the ingest pipeline on
// every related batch, so machine snapshots would otherwise crowd out the
// handful of human/agent edits this feature exists to protect.
const (
// WikiMaxRevisionsPerPage is how many recent versions are kept for
// prunable (machine-authored) snapshots.
WikiMaxRevisionsPerPage = 50
// WikiMaxRevisionsHardCap is the absolute per-page ceiling, applied
// regardless of author, so a page edited only by hand still has bounded
// storage.
WikiMaxRevisionsHardCap = 200
)
// WikiPrunableEditSources lists the edit sources whose snapshots may be
// dropped by the soft cap. Everything else (user / agent / revert) survives
// until the hard cap. Legacy rows carry an empty source, hence "".
var WikiPrunableEditSources = []string{"", WikiEditSourcePipeline}
// WikiRevisionPruneRequest describes the two-tier retention applied to one
// page's snapshot history. A version threshold <= 0 disables that tier.
type WikiRevisionPruneRequest struct {
PageID string
// KeepFromVersion: snapshots below this version are dropped, but only
// when their edit source is listed in PrunableSources.
KeepFromVersion int
PrunableSources []string
// HardKeepFromVersion: snapshots below this version are always dropped,
// whatever their author.
HardKeepFromVersion int
}
// WikiPageUpdateRequest is the partial-update payload for
// PUT /wiki/pages/*slug. All content fields are optional pointers — absent
// fields keep their stored value, so a client can change just the body
// without re-sending (and risking clobbering) title/status/aliases.
type WikiPageUpdateRequest struct {
Title *string `json:"title,omitempty"`
Content *string `json:"content,omitempty"`
Summary *string `json:"summary,omitempty"`
PageType *string `json:"page_type,omitempty"`
Status *string `json:"status,omitempty"`
Aliases *StringArray `json:"aliases,omitempty"`
// Version is the optimistic-lock guard: when > 0 the update is rejected
// with a conflict if the stored version differs (someone else edited the
// page since the client loaded it). 0 skips the check (legacy clients).
Version int `json:"version,omitempty"`
}
// WikiPageRevisionListResponse is the payload for GET /wiki/revisions/*slug.
// Revisions hold the superseded versions (content omitted in list mode);
// the current version is described by CurrentVersion + the page row itself,
// which the frontend already has.
type WikiPageRevisionListResponse struct {
Revisions []*WikiPageRevision `json:"revisions"`
Total int64 `json:"total"`
CurrentVersion int `json:"current_version"`
}
// WikiPageRevertRequest rolls a page back to one of its stored revisions.
// Slug travels in the body (not the path) for the same reason as
// WikiPageMoveRequest: hierarchical slugs collide with gin's catch-all.
type WikiPageRevertRequest struct {
Slug string `json:"slug" binding:"required"`
Version int `json:"version" binding:"required"`
}
// WikiFolderRootID is the sentinel parent/folder id meaning "the wiki root"
// (a page or folder directly under the top level, with no parent folder).
const WikiFolderRootID = ""

View File

@ -1,5 +1,10 @@
DROP TABLE IF EXISTS tenant_invitations;
DROP TABLE IF EXISTS tenant_api_keys;
DROP TABLE IF EXISTS wiki_page_revisions;
DROP TABLE IF EXISTS wiki_log_entries;
DROP TABLE IF EXISTS wiki_page_issues;
DROP TABLE IF EXISTS wiki_pages;
DROP TABLE IF EXISTS wiki_folders;
DROP TABLE IF EXISTS user_kb_pins;
DROP TABLE IF EXISTS user_resource_favorites;
DROP TABLE IF EXISTS tenant_disabled_shared_agents;

View File

@ -72,6 +72,8 @@ CREATE TABLE IF NOT EXISTS knowledge_bases (
vector_store_id VARCHAR(36),
storage_backend_id VARCHAR(36),
creator_id VARCHAR(36),
wiki_config TEXT,
indexing_strategy TEXT DEFAULT '{"vector_enabled":true,"keyword_enabled":true,"wiki_enabled":false,"graph_enabled":false}',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
@ -941,3 +943,156 @@ CREATE TABLE IF NOT EXISTS temporary_documents (
CREATE INDEX IF NOT EXISTS idx_temporary_documents_scope ON temporary_documents(tenant_id, session_id);
CREATE INDEX IF NOT EXISTS idx_temporary_documents_status ON temporary_documents(status);
CREATE INDEX IF NOT EXISTS idx_temporary_documents_expires ON temporary_documents(expires_at);
-- ---------------------------------------------------------------------------
-- Wiki (consolidated from Postgres migrations 000037, 000040, 000061, 000075)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS wiki_pages (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL,
knowledge_base_id VARCHAR(36) NOT NULL,
slug VARCHAR(255) NOT NULL,
title VARCHAR(512) NOT NULL DEFAULT '',
page_type VARCHAR(32) NOT NULL DEFAULT 'summary',
status VARCHAR(32) NOT NULL DEFAULT 'published',
content TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
parent_slug VARCHAR(255) NOT NULL DEFAULT '',
folder_id VARCHAR(36) NOT NULL DEFAULT '',
category_path TEXT DEFAULT '[]',
wiki_path VARCHAR(1024) NOT NULL DEFAULT '',
depth INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
source_refs TEXT DEFAULT '[]',
chunk_refs TEXT DEFAULT '[]',
in_links TEXT DEFAULT '[]',
out_links TEXT DEFAULT '[]',
page_metadata TEXT DEFAULT '{}',
aliases TEXT DEFAULT '[]',
version INTEGER NOT NULL DEFAULT 1,
last_edit_source VARCHAR(16) NOT NULL DEFAULT '',
last_editor_id VARCHAR(64) NOT NULL DEFAULT '',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_wiki_pages_kb_slug
ON wiki_pages (knowledge_base_id, slug)
WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_wiki_pages_kb_id
ON wiki_pages (knowledge_base_id);
CREATE INDEX IF NOT EXISTS idx_wiki_pages_page_type
ON wiki_pages (knowledge_base_id, page_type);
CREATE INDEX IF NOT EXISTS idx_wiki_pages_parent_slug
ON wiki_pages (knowledge_base_id, parent_slug);
CREATE INDEX IF NOT EXISTS idx_wiki_pages_tree
ON wiki_pages (knowledge_base_id, page_type, wiki_path, sort_order, title);
CREATE INDEX IF NOT EXISTS idx_wiki_pages_folder
ON wiki_pages (knowledge_base_id, folder_id);
CREATE INDEX IF NOT EXISTS idx_wiki_pages_tenant_id
ON wiki_pages (tenant_id);
CREATE INDEX IF NOT EXISTS idx_wiki_pages_deleted_at
ON wiki_pages (deleted_at);
CREATE TABLE IF NOT EXISTS wiki_folders (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL DEFAULT 0,
knowledge_base_id VARCHAR(36) NOT NULL,
parent_id VARCHAR(36) NOT NULL DEFAULT '',
name VARCHAR(255) NOT NULL,
path VARCHAR(1024) NOT NULL DEFAULT '',
depth INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_wiki_folders_parent_name
ON wiki_folders (knowledge_base_id, parent_id, name)
WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_wiki_folders_parent
ON wiki_folders (knowledge_base_id, parent_id);
CREATE INDEX IF NOT EXISTS idx_wiki_folders_deleted_at
ON wiki_folders (deleted_at);
CREATE TABLE IF NOT EXISTS wiki_page_issues (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL,
knowledge_base_id VARCHAR(36) NOT NULL,
slug VARCHAR(255) NOT NULL,
issue_type VARCHAR(50) NOT NULL,
description TEXT NOT NULL,
suspected_knowledge_ids TEXT,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
reported_by VARCHAR(100) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
);
CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_tenant_id
ON wiki_page_issues(tenant_id);
CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_knowledge_base_id
ON wiki_page_issues(knowledge_base_id);
CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_slug
ON wiki_page_issues(slug);
CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_status
ON wiki_page_issues(status);
CREATE TABLE IF NOT EXISTS wiki_log_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tenant_id INTEGER NOT NULL,
knowledge_base_id VARCHAR(36) NOT NULL,
action VARCHAR(32) NOT NULL,
knowledge_id VARCHAR(36) NOT NULL DEFAULT '',
doc_title TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
pages_affected TEXT NOT NULL DEFAULT '[]',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_wiki_log_entries_kb_id_desc
ON wiki_log_entries (knowledge_base_id, id DESC);
CREATE INDEX IF NOT EXISTS idx_wiki_log_entries_tenant_id
ON wiki_log_entries (tenant_id);
CREATE TABLE IF NOT EXISTS wiki_page_revisions (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL,
knowledge_base_id VARCHAR(36) NOT NULL,
page_id VARCHAR(36) NOT NULL,
slug VARCHAR(255) NOT NULL,
version INTEGER NOT NULL,
title VARCHAR(512) NOT NULL DEFAULT '',
page_type VARCHAR(32) NOT NULL DEFAULT 'summary',
status VARCHAR(32) NOT NULL DEFAULT 'published',
content TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
aliases TEXT DEFAULT '[]',
edit_source VARCHAR(16) NOT NULL DEFAULT '',
editor_id VARCHAR(64) NOT NULL DEFAULT '',
edited_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_wiki_page_revisions_page_version
ON wiki_page_revisions (page_id, version);
CREATE INDEX IF NOT EXISTS idx_wiki_page_revisions_kb_slug
ON wiki_page_revisions (knowledge_base_id, slug);

View File

@ -0,0 +1,7 @@
-- Rollback: 000075_wiki_page_revisions
DO $$ BEGIN RAISE NOTICE '[Migration 000075] Reverting wiki page revisions schema'; END $$;
DROP TABLE IF EXISTS wiki_page_revisions;
ALTER TABLE wiki_pages DROP COLUMN IF EXISTS last_edit_source;
ALTER TABLE wiki_pages DROP COLUMN IF EXISTS last_editor_id;

View File

@ -0,0 +1,53 @@
-- Migration: 000075_wiki_page_revisions
-- Description: Wiki page revision history (content snapshots for diff/rollback)
-- plus edit provenance columns on wiki_pages.
DO $$ BEGIN RAISE NOTICE '[Migration 000075] Applying wiki page revisions schema'; END $$;
-- ---------------------------------------------------------------------------
-- 1) Edit provenance on wiki_pages
-- last_edit_source records who authored the CURRENT version of the page:
-- 'pipeline' (wiki ingest), 'agent' (wiki fixer tools), 'user' (manual edit
-- via the editor UI) or 'revert' (rollback to an earlier revision). Empty for
-- legacy rows, which are treated as 'pipeline'.
-- ---------------------------------------------------------------------------
ALTER TABLE wiki_pages ADD COLUMN IF NOT EXISTS last_edit_source VARCHAR(16) NOT NULL DEFAULT '';
ALTER TABLE wiki_pages ADD COLUMN IF NOT EXISTS last_editor_id VARCHAR(64) NOT NULL DEFAULT '';
COMMENT ON COLUMN wiki_pages.last_edit_source IS 'Author kind of the current version: pipeline | agent | user | revert ('''' = legacy, treated as pipeline)';
COMMENT ON COLUMN wiki_pages.last_editor_id IS 'User id of the caller that produced the current version (empty for background pipeline writes)';
-- ---------------------------------------------------------------------------
-- 2) wiki_page_revisions table
-- One immutable snapshot per superseded page version. The CURRENT version
-- lives only in wiki_pages; when an edit replaces version V, the pre-edit
-- state is inserted here as (page_id, V) before the row is rewritten, so
-- every historical version stays diffable and revertable.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS wiki_page_revisions (
id VARCHAR(36) PRIMARY KEY,
tenant_id BIGINT NOT NULL,
knowledge_base_id VARCHAR(36) NOT NULL,
page_id VARCHAR(36) NOT NULL,
slug VARCHAR(255) NOT NULL,
version INT NOT NULL,
title VARCHAR(512) NOT NULL DEFAULT '',
page_type VARCHAR(32) NOT NULL DEFAULT 'summary',
status VARCHAR(32) NOT NULL DEFAULT 'published',
content TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
aliases JSONB DEFAULT '[]'::JSONB,
-- Author of THIS version (mirrors wiki_pages.last_edit_source semantics).
edit_source VARCHAR(16) NOT NULL DEFAULT '',
editor_id VARCHAR(64) NOT NULL DEFAULT '',
-- When this version was authored (the page's updated_at while current).
edited_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
-- Exactly one snapshot per page version; ON CONFLICT DO NOTHING keeps the
-- snapshot-then-update write path idempotent under retries.
CREATE UNIQUE INDEX IF NOT EXISTS idx_wiki_page_revisions_page_version
ON wiki_page_revisions (page_id, version);
CREATE INDEX IF NOT EXISTS idx_wiki_page_revisions_kb_slug
ON wiki_page_revisions (knowledge_base_id, slug);