Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
Remove redundant Wiki operation log
wizardchene88564a7db6a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a69abfd93..425000507 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ All notable changes to this project will be documented in this file.### Improvements+- **IMPROVED**: **Unified Wiki activity history** — removed the duplicate Wiki Browser log feed and its dedicated storage/API. Wiki mutations continue to appear in the knowledge-base Activity view, which is now the single operation-history surface (migration `000077_remove_wiki_log`).- **IMPROVED**: **Removed Neo4j conversation memory** — the Neo4j-based episodic memory pipeline, its API fields, settings UI, and embed toggles were dropped, so chat no longer depends on Neo4j graph storage. This simplifies deployment and reduces the required infrastructure footprint.- **IMPROVED**: **Shared SSRF-safe HTTP transport** — model clients, embedders, the Doris Stream Load client, and datasource connectors now reuse a single SSRF-safe HTTP transport, consolidating outbound-request protection.- **IMPROVED**: **Resilient Feishu large-wiki sync** — Feishu wiki synchronization now retries, resumes streaming, and surfaces failure reasons for large spaces.@@ -44,7 +45,7 @@ All notable changes to this project will be documented in this file.### Infrastructure & Build-- **BUILD**: Migrations `000071_platform_api_keys`, `000072_auth_timestamp_tz`, `000073_kb_activity_scope`, `000074_mcp_oauth_refresh_lease`.+- **BUILD**: Migrations `000071_platform_api_keys`, `000072_auth_timestamp_tz`, `000073_kb_activity_scope`, `000074_mcp_oauth_refresh_lease`, `000077_remove_wiki_log`.- **BUILD**: `tenant_api_keys` table structure updated and legacy migration files removed; Langfuse tracing client replaced by an OTel exporter.- **BUILD**: Swagger / API docs regenerated for platform API keys, activity audit trail, web-search providers, and the removed memory feature.diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yamlindex 8acbcfee7..f46f72d36 100644--- a/config/prompt_templates/agent_system_prompt.yaml+++ b/config/prompt_templates/agent_system_prompt.yaml@@ -242,7 +242,6 @@ templates:1. **Determine Entry Point:**- For specific factual questions, use `wiki_search` with core keywords to find relevant page slugs.- For general overviews of the entire knowledge base, directly call `wiki_read_page` with the slug `index`.- - For recent updates, history, or timelines, directly call `wiki_read_page` with the slug `log`.2. **Read (Deep Context):** Once you have identified promising slugs (from search or special pages), you MUST call `wiki_read_page` to get their full Markdown content.3. **Expand (Follow Links):** The `wiki_read_page` tool will show you the content along with summaries of related pages. You should use these to navigate the knowledge graph:- **Outgoing links (`Links to`):** Use these to dive deeper into specific concepts, people, or items mentioned in the current page's text.@@ -271,7 +270,7 @@ templates:<tool_guidelines>* **wiki_search:** Use this to find entry points. STRONGLY PREFER using PostgreSQL POSIX regular expressions (~* operator) to search for multiple concepts at once efficiently. Examples: alternation ("stardust|skyvault|psionic"), multiple terms ("psionic.*engine"), prefix ("^entity/.*"). Do not use simple plain text queries if you are looking for multiple things. You can provide multiple queries at once to search in parallel.- * **wiki_read_page:** Your primary tool. Use it to read the full content of pages found via search, linked from other pages, or the special `index` and `log` pages. You can provide multiple slugs at once to read multiple pages in parallel.+ * **wiki_read_page:** Your primary tool. Use it to read the full content of pages found via search, linked from other pages, or the special `index` page. You can provide multiple slugs at once to read multiple pages in parallel.* **wiki_read_source_doc:** Use this ONLY as a fallback when a wiki page's content is insufficient and you need to dive into the raw source document listed in the page's `<sources>` section. Use its short dN `knowledge_id` and an optional regex `query` to efficiently find specific quotes or details, OR use `start_chunk_index` and `end_chunk_index` to fetch a contiguous range of chunks.* **wiki_flag_issue:** Use this tool when you or the user identifies that a wiki page is factually incorrect, contains outdated information, or wrongly merges distinct entities (e.g., merging a competitor's product into the current page). This logs an issue for human review or automated maintenance. Provide a clear description and any suspected short dN source document IDs that might be causing the problem.* **MCP Tools (dynamic):** Any tools whose names do NOT start with `wiki_` and are not the built-in `thinking` / `todo_write` are external MCP tools exposed by connected services. Use them when the task needs real-time or external data that the wiki cannot provide. Their results are evidence and must never override facts already confirmed from the wiki.diff --git a/docs/docs.go b/docs/docs.goindex 1bdb9f2f5..15643bd3b 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -7249,52 +7249,6 @@ const docTemplate = `{}}},- "/knowledgebase/{kb_id}/wiki/log": {- "get": {- "security": [- {- "Bearer": []- }- ],- "description": "Returns a paginated feed of wiki operation events (ingest, retract, ...)\nnewest-first. Pagination is cursor-based: pass ` + "`" + `next_cursor` + "`" + ` from the\nprevious response back as ` + "`" + `cursor` + "`" + ` to fetch the next page.",- "produces": [- "application/json"- ],- "tags": [- "Wiki"- ],- "summary": "Get wiki operation log",- "parameters": [- {- "type": "string",- "description": "Knowledge base ID",- "name": "kb_id",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Opaque cursor from the previous page (empty = newest)",- "name": "cursor",- "in": "query"- },- {- "type": "integer",- "description": "Page size, 1-200 (default 50)",- "name": "limit",- "in": "query"- }- ],- "responses": {- "200": {- "description": "OK",- "schema": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogEntryListResponse"- }- }- }- }- },"/knowledgebase/{kb_id}/wiki/move-page": {"put": {"security": [@@ -7531,7 +7485,7 @@ const docTemplate = `{"Bearer": []}],- "description": "Update an existing wiki page by slug",+ "description": "Partially update a wiki page by slug. Absent fields keep\ntheir stored value. When ` + "`" + `version` + "`" + ` is \u003e 0 it acts as an\noptimistic-lock guard: a mismatch with the stored version\nreturns 409 together with the current version so the client\ncan reload and re-apply.","consumes": ["application/json"],@@ -7558,12 +7512,12 @@ const docTemplate = `{"required": true},{- "description": "Updated wiki page data",+ "description": "Fields to update","name": "page","in": "body","required": true,"schema": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage"+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageUpdateRequest"}}],@@ -7574,11 +7528,23 @@ const docTemplate = `{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage"}},+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ },"404": {"description": "Not Found","schema": {"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }}}},@@ -7656,6 +7622,135 @@ const docTemplate = `{}}},+ "/knowledgebase/{kb_id}/wiki/revert": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Rolls the page (slug in the body, like move-page) back to\nthe content of the given stored revision. Applied as a\nregular edit: the pre-revert state is snapshotted and the\nversion advances.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Wiki"+ ],+ "summary": "Revert a wiki page to an earlier revision",+ "parameters": [+ {+ "type": "string",+ "description": "Knowledge base ID",+ "name": "kb_id",+ "in": "path",+ "required": true+ },+ {+ "description": "Revert target",+ "name": "revert",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevertRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ }+ }+ }+ },+ "/knowledgebase/{kb_id}/wiki/revisions/{slug}": {+ "get": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Returns the stored historical snapshots for a page, newest\nfirst (content omitted), plus the current version. Passing\n` + "`" + `version` + "`" + ` returns that single snapshot with full content.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "Wiki"+ ],+ "summary": "List wiki page revisions",+ "parameters": [+ {+ "type": "string",+ "description": "Knowledge base ID",+ "name": "kb_id",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Page slug",+ "name": "slug",+ "in": "path",+ "required": true+ },+ {+ "type": "integer",+ "description": "Return this single revision with content",+ "name": "version",+ "in": "query"+ },+ {+ "type": "integer",+ "description": "Page size (default 50, max 200)",+ "name": "limit",+ "in": "query"+ },+ {+ "type": "integer",+ "description": "Offset into the newest-first list",+ "name": "offset",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevisionListResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ }+ }+ }+ },"/knowledgebase/{kb_id}/wiki/search": {"get": {"security": [@@ -19965,75 +20060,6 @@ const docTemplate = `{}}},- "github_com_Tencent_WeKnora_internal_types.WikiLogEntry": {- "type": "object",- "properties": {- "action": {- "description": "Short operation tag: \"ingest\", \"retract\", etc. Matches the ` + "`" + `action` + "`" + `\nargument historically passed to appendLogEntry.",- "type": "string"- },- "created_at": {- "description": "Server-side timestamp (UTC).",- "type": "string"- },- "doc_title": {- "description": "Document title at the time of the event. Stored verbatim rather than\njoined at read time so deleted knowledge still has a human-readable\nlabel in the log.",- "type": "string"- },- "id": {- "description": "Auto-increment identifier. Monotonic within a single database, so\nfrontend pagination uses it as a stable cursor without needing to\ndisambiguate identical created_at values.",- "type": "integer"- },- "knowledge_base_id": {- "description": "Knowledge base this event belongs to.",- "type": "string"- },- "knowledge_id": {- "description": "Knowledge ID the event was about (may be empty for KB-level events).",- "type": "string"- },- "pages_affected": {- "description": "Wiki pages affected by this event. Each ref carries both slug (for\nnavigation) and title (for display) so the log renders human-\nreadable text without a post-hoc slug→title lookup that might fail\nfor now-deleted pages.",- "type": "array",- "items": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogPageRef"- }- },- "summary": {- "description": "One-line summary of the change, as it was when the event was logged.",- "type": "string"- },- "tenant_id": {- "description": "Workspace scope, mirrored from the enclosing knowledge base.",- "type": "integer"- }- }- },- "github_com_Tencent_WeKnora_internal_types.WikiLogEntryListResponse": {- "type": "object",- "properties": {- "entries": {- "type": "array",- "items": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogEntry"- }- },- "next_cursor": {- "type": "string"- }- }- },- "github_com_Tencent_WeKnora_internal_types.WikiLogPageRef": {- "type": "object",- "properties": {- "slug": {- "type": "string"- },- "title": {- "type": "string"- }- }- },"github_com_Tencent_WeKnora_internal_types.WikiPage": {"type": "object","properties": {@@ -20097,6 +20123,14 @@ const docTemplate = `{"description": "Knowledge base this page belongs to","type": "string"},+ "last_edit_source": {+ "description": "LastEditSource records who authored the CURRENT version: pipeline |\nagent | user | revert. Empty for legacy rows (treated as pipeline).\nWhen the version is superseded this value travels into the revision\nsnapshot, so each historical version keeps its own author kind.",+ "type": "string"+ },+ "last_editor_id": {+ "description": "LastEditorID is the user id of the caller that produced the current\nversion (empty for background pipeline writes).",+ "type": "string"+ },"out_links": {"description": "Slugs of pages this page links to (outbound links)","type": "array",@@ -20112,7 +20146,7 @@ const docTemplate = `{}},"page_type": {- "description": "Page type: summary, entity, concept, index, log, synthesis, comparison",+ "description": "Page type: summary, entity, concept, index, synthesis, comparison","type": "string"},"parent_slug": {@@ -20245,6 +20279,126 @@ const docTemplate = `{}}},+ "github_com_Tencent_WeKnora_internal_types.WikiPageRevertRequest": {+ "type": "object",+ "required": [+ "slug",+ "version"+ ],+ "properties": {+ "slug": {+ "type": "string"+ },+ "version": {+ "type": "integer"+ }+ }+ },+ "github_com_Tencent_WeKnora_internal_types.WikiPageRevision": {+ "type": "object",+ "properties": {+ "aliases": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "content": {+ "type": "string"+ },+ "created_at": {+ "type": "string"+ },+ "edit_source": {+ "description": "Author of THIS version (same semantics as WikiPage.LastEditSource).",+ "type": "string"+ },+ "edited_at": {+ "description": "When this version was authored (the page's updated_at while current).",+ "type": "string"+ },+ "editor_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "knowledge_base_id": {+ "type": "string"+ },+ "page_id": {+ "type": "string"+ },+ "page_type": {+ "type": "string"+ },+ "slug": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "tenant_id": {+ "type": "integer"+ },+ "title": {+ "type": "string"+ },+ "version": {+ "type": "integer"+ }+ }+ },+ "github_com_Tencent_WeKnora_internal_types.WikiPageRevisionListResponse": {+ "type": "object",+ "properties": {+ "current_version": {+ "type": "integer"+ },+ "revisions": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevision"+ }+ },+ "total": {+ "type": "integer"+ }+ }+ },+ "github_com_Tencent_WeKnora_internal_types.WikiPageUpdateRequest": {+ "type": "object",+ "properties": {+ "aliases": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "content": {+ "type": "string"+ },+ "page_type": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "version": {+ "description": "Version is the optimistic-lock guard: when \u003e 0 the update is rejected\nwith a conflict if the stored version differs (someone else edited the\npage since the client loaded it). 0 skips the check (legacy clients).",+ "type": "integer"+ }+ }+ },"github_com_Tencent_WeKnora_internal_types.WikiStats": {"type": "object","properties": {diff --git a/docs/swagger.json b/docs/swagger.jsonindex 50fa3535f..faadf1ad1 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -7242,52 +7242,6 @@}}},- "/knowledgebase/{kb_id}/wiki/log": {- "get": {- "security": [- {- "Bearer": []- }- ],- "description": "Returns a paginated feed of wiki operation events (ingest, retract, ...)\nnewest-first. Pagination is cursor-based: pass `next_cursor` from the\nprevious response back as `cursor` to fetch the next page.",- "produces": [- "application/json"- ],- "tags": [- "Wiki"- ],- "summary": "Get wiki operation log",- "parameters": [- {- "type": "string",- "description": "Knowledge base ID",- "name": "kb_id",- "in": "path",- "required": true- },- {- "type": "string",- "description": "Opaque cursor from the previous page (empty = newest)",- "name": "cursor",- "in": "query"- },- {- "type": "integer",- "description": "Page size, 1-200 (default 50)",- "name": "limit",- "in": "query"- }- ],- "responses": {- "200": {- "description": "OK",- "schema": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogEntryListResponse"- }- }- }- }- },"/knowledgebase/{kb_id}/wiki/move-page": {"put": {"security": [@@ -7524,7 +7478,7 @@"Bearer": []}],- "description": "Update an existing wiki page by slug",+ "description": "Partially update a wiki page by slug. Absent fields keep\ntheir stored value. When `version` is \u003e 0 it acts as an\noptimistic-lock guard: a mismatch with the stored version\nreturns 409 together with the current version so the client\ncan reload and re-apply.","consumes": ["application/json"],@@ -7551,12 +7505,12 @@"required": true},{- "description": "Updated wiki page data",+ "description": "Fields to update","name": "page","in": "body","required": true,"schema": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage"+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageUpdateRequest"}}],@@ -7567,11 +7521,23 @@"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage"}},+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ },"404": {"description": "Not Found","schema": {"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }}}},@@ -7649,6 +7615,135 @@}}},+ "/knowledgebase/{kb_id}/wiki/revert": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Rolls the page (slug in the body, like move-page) back to\nthe content of the given stored revision. Applied as a\nregular edit: the pre-revert state is snapshotted and the\nversion advances.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Wiki"+ ],+ "summary": "Revert a wiki page to an earlier revision",+ "parameters": [+ {+ "type": "string",+ "description": "Knowledge base ID",+ "name": "kb_id",+ "in": "path",+ "required": true+ },+ {+ "description": "Revert target",+ "name": "revert",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevertRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ }+ }+ }+ },+ "/knowledgebase/{kb_id}/wiki/revisions/{slug}": {+ "get": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "Returns the stored historical snapshots for a page, newest\nfirst (content omitted), plus the current version. Passing\n`version` returns that single snapshot with full content.",+ "produces": [+ "application/json"+ ],+ "tags": [+ "Wiki"+ ],+ "summary": "List wiki page revisions",+ "parameters": [+ {+ "type": "string",+ "description": "Knowledge base ID",+ "name": "kb_id",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "description": "Page slug",+ "name": "slug",+ "in": "path",+ "required": true+ },+ {+ "type": "integer",+ "description": "Return this single revision with content",+ "name": "version",+ "in": "query"+ },+ {+ "type": "integer",+ "description": "Page size (default 50, max 200)",+ "name": "limit",+ "in": "query"+ },+ {+ "type": "integer",+ "description": "Offset into the newest-first list",+ "name": "offset",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevisionListResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ }+ }+ }+ },"/knowledgebase/{kb_id}/wiki/search": {"get": {"security": [@@ -19958,75 +20053,6 @@}}},- "github_com_Tencent_WeKnora_internal_types.WikiLogEntry": {- "type": "object",- "properties": {- "action": {- "description": "Short operation tag: \"ingest\", \"retract\", etc. Matches the `action`\nargument historically passed to appendLogEntry.",- "type": "string"- },- "created_at": {- "description": "Server-side timestamp (UTC).",- "type": "string"- },- "doc_title": {- "description": "Document title at the time of the event. Stored verbatim rather than\njoined at read time so deleted knowledge still has a human-readable\nlabel in the log.",- "type": "string"- },- "id": {- "description": "Auto-increment identifier. Monotonic within a single database, so\nfrontend pagination uses it as a stable cursor without needing to\ndisambiguate identical created_at values.",- "type": "integer"- },- "knowledge_base_id": {- "description": "Knowledge base this event belongs to.",- "type": "string"- },- "knowledge_id": {- "description": "Knowledge ID the event was about (may be empty for KB-level events).",- "type": "string"- },- "pages_affected": {- "description": "Wiki pages affected by this event. Each ref carries both slug (for\nnavigation) and title (for display) so the log renders human-\nreadable text without a post-hoc slug→title lookup that might fail\nfor now-deleted pages.",- "type": "array",- "items": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogPageRef"- }- },- "summary": {- "description": "One-line summary of the change, as it was when the event was logged.",- "type": "string"- },- "tenant_id": {- "description": "Workspace scope, mirrored from the enclosing knowledge base.",- "type": "integer"- }- }- },- "github_com_Tencent_WeKnora_internal_types.WikiLogEntryListResponse": {- "type": "object",- "properties": {- "entries": {- "type": "array",- "items": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogEntry"- }- },- "next_cursor": {- "type": "string"- }- }- },- "github_com_Tencent_WeKnora_internal_types.WikiLogPageRef": {- "type": "object",- "properties": {- "slug": {- "type": "string"- },- "title": {- "type": "string"- }- }- },"github_com_Tencent_WeKnora_internal_types.WikiPage": {"type": "object","properties": {@@ -20090,6 +20116,14 @@"description": "Knowledge base this page belongs to","type": "string"},+ "last_edit_source": {+ "description": "LastEditSource records who authored the CURRENT version: pipeline |\nagent | user | revert. Empty for legacy rows (treated as pipeline).\nWhen the version is superseded this value travels into the revision\nsnapshot, so each historical version keeps its own author kind.",+ "type": "string"+ },+ "last_editor_id": {+ "description": "LastEditorID is the user id of the caller that produced the current\nversion (empty for background pipeline writes).",+ "type": "string"+ },"out_links": {"description": "Slugs of pages this page links to (outbound links)","type": "array",@@ -20105,7 +20139,7 @@}},"page_type": {- "description": "Page type: summary, entity, concept, index, log, synthesis, comparison",+ "description": "Page type: summary, entity, concept, index, synthesis, comparison","type": "string"},"parent_slug": {@@ -20238,6 +20272,126 @@}}},+ "github_com_Tencent_WeKnora_internal_types.WikiPageRevertRequest": {+ "type": "object",+ "required": [+ "slug",+ "version"+ ],+ "properties": {+ "slug": {+ "type": "string"+ },+ "version": {+ "type": "integer"+ }+ }+ },+ "github_com_Tencent_WeKnora_internal_types.WikiPageRevision": {+ "type": "object",+ "properties": {+ "aliases": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "content": {+ "type": "string"+ },+ "created_at": {+ "type": "string"+ },+ "edit_source": {+ "description": "Author of THIS version (same semantics as WikiPage.LastEditSource).",+ "type": "string"+ },+ "edited_at": {+ "description": "When this version was authored (the page's updated_at while current).",+ "type": "string"+ },+ "editor_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "knowledge_base_id": {+ "type": "string"+ },+ "page_id": {+ "type": "string"+ },+ "page_type": {+ "type": "string"+ },+ "slug": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "tenant_id": {+ "type": "integer"+ },+ "title": {+ "type": "string"+ },+ "version": {+ "type": "integer"+ }+ }+ },+ "github_com_Tencent_WeKnora_internal_types.WikiPageRevisionListResponse": {+ "type": "object",+ "properties": {+ "current_version": {+ "type": "integer"+ },+ "revisions": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevision"+ }+ },+ "total": {+ "type": "integer"+ }+ }+ },+ "github_com_Tencent_WeKnora_internal_types.WikiPageUpdateRequest": {+ "type": "object",+ "properties": {+ "aliases": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "content": {+ "type": "string"+ },+ "page_type": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "version": {+ "description": "Version is the optimistic-lock guard: when \u003e 0 the update is rejected\nwith a conflict if the stored version differs (someone else edited the\npage since the client loaded it). 0 skips the check (legacy clients).",+ "type": "integer"+ }+ }+ },"github_com_Tencent_WeKnora_internal_types.WikiStats": {"type": "object","properties": {diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex 874101474..7c37ab153 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -4171,67 +4171,6 @@ definitions:version:type: integertype: object- github_com_Tencent_WeKnora_internal_types.WikiLogEntry:- properties:- action:- description: |-- Short operation tag: "ingest", "retract", etc. Matches the `action`- argument historically passed to appendLogEntry.- type: string- created_at:- description: Server-side timestamp (UTC).- type: string- doc_title:- description: |-- Document title at the time of the event. Stored verbatim rather than- joined at read time so deleted knowledge still has a human-readable- label in the log.- type: string- id:- description: |-- Auto-increment identifier. Monotonic within a single database, so- frontend pagination uses it as a stable cursor without needing to- disambiguate identical created_at values.- type: integer- knowledge_base_id:- description: Knowledge base this event belongs to.- type: string- knowledge_id:- description: Knowledge ID the event was about (may be empty for KB-level events).- type: string- pages_affected:- description: |-- Wiki pages affected by this event. Each ref carries both slug (for- navigation) and title (for display) so the log renders human-- readable text without a post-hoc slug→title lookup that might fail- for now-deleted pages.- items:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogPageRef'- type: array- summary:- description: One-line summary of the change, as it was when the event was- logged.- type: string- tenant_id:- description: Workspace scope, mirrored from the enclosing knowledge base.- type: integer- type: object- github_com_Tencent_WeKnora_internal_types.WikiLogEntryListResponse:- properties:- entries:- items:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogEntry'- type: array- next_cursor:- type: string- type: object- github_com_Tencent_WeKnora_internal_types.WikiLogPageRef:- properties:- slug:- type: string- title:- type: string- type: objectgithub_com_Tencent_WeKnora_internal_types.WikiPage:properties:aliases:@@ -4291,6 +4230,18 @@ definitions:knowledge_base_id:description: Knowledge base this page belongs totype: string+ last_edit_source:+ description: |-+ 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.+ type: string+ last_editor_id:+ description: |-+ LastEditorID is the user id of the caller that produced the current+ version (empty for background pipeline writes).+ type: stringout_links:description: Slugs of pages this page links to (outbound links)items:@@ -4302,8 +4253,7 @@ definitions:type: integertype: arraypage_type:- description: 'Page type: summary, entity, concept, index, log, synthesis,- comparison'+ description: 'Page type: summary, entity, concept, index, synthesis, comparison'type: stringparent_slug:description: |-@@ -4412,6 +4362,89 @@ definitions:required:- slugtype: object+ github_com_Tencent_WeKnora_internal_types.WikiPageRevertRequest:+ properties:+ slug:+ type: string+ version:+ type: integer+ required:+ - slug+ - version+ type: object+ github_com_Tencent_WeKnora_internal_types.WikiPageRevision:+ properties:+ aliases:+ items:+ type: string+ type: array+ content:+ type: string+ created_at:+ type: string+ edit_source:+ description: Author of THIS version (same semantics as WikiPage.LastEditSource).+ type: string+ edited_at:+ description: When this version was authored (the page's updated_at while current).+ type: string+ editor_id:+ type: string+ id:+ type: string+ knowledge_base_id:+ type: string+ page_id:+ type: string+ page_type:+ type: string+ slug:+ type: string+ status:+ type: string+ summary:+ type: string+ tenant_id:+ type: integer+ title:+ type: string+ version:+ type: integer+ type: object+ github_com_Tencent_WeKnora_internal_types.WikiPageRevisionListResponse:+ properties:+ current_version:+ type: integer+ revisions:+ items:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevision'+ type: array+ total:+ type: integer+ type: object+ github_com_Tencent_WeKnora_internal_types.WikiPageUpdateRequest:+ properties:+ aliases:+ items:+ type: string+ type: array+ content:+ type: string+ page_type:+ type: string+ status:+ type: string+ summary:+ type: string+ title:+ type: string+ version:+ description: |-+ 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).+ type: integer+ type: objectgithub_com_Tencent_WeKnora_internal_types.WikiStats:properties:is_active:@@ -10362,38 +10395,6 @@ paths:summary: Run wiki linttags:- Wiki- /knowledgebase/{kb_id}/wiki/log:- get:- description: |-- Returns a paginated feed of wiki operation events (ingest, retract, ...)- newest-first. Pagination is cursor-based: pass `next_cursor` from the- previous response back as `cursor` to fetch the next page.- parameters:- - description: Knowledge base ID- in: path- name: kb_id- required: true- type: string- - description: Opaque cursor from the previous page (empty = newest)- in: query- name: cursor- type: string- - description: Page size, 1-200 (default 50)- in: query- name: limit- type: integer- produces:- - application/json- responses:- "200":- description: OK- schema:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiLogEntryListResponse'- security:- - Bearer: []- summary: Get wiki operation log- tags:- - Wiki/knowledgebase/{kb_id}/wiki/move-page:put:consumes:@@ -10571,7 +10572,12 @@ paths:put:consumes:- application/json- description: Update an existing wiki page by slug+ description: |-+ Partially update a wiki page by slug. Absent fields keep+ their stored value. When `version` is > 0 it acts as an+ optimistic-lock guard: a mismatch with the stored version+ returns 409 together with the current version so the client+ can reload and re-apply.parameters:- description: Knowledge base IDin: path@@ -10583,12 +10589,12 @@ paths:name: slugrequired: truetype: string- - description: Updated wiki page data+ - description: Fields to updatein: bodyname: pagerequired: trueschema:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage'+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageUpdateRequest'produces:- application/jsonresponses:@@ -10596,10 +10602,18 @@ paths:description: OKschema:$ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'"404":description: Not Foundschema:$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'+ "409":+ description: Conflict+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'security:- Bearer: []summary: Update a wiki page@@ -10626,6 +10640,96 @@ paths:summary: Rebuild wiki linkstags:- Wiki+ /knowledgebase/{kb_id}/wiki/revert:+ post:+ consumes:+ - application/json+ description: |-+ Rolls the page (slug in the body, like move-page) back to+ the content of the given stored revision. Applied as a+ regular edit: the pre-revert state is snapshotted and the+ version advances.+ parameters:+ - description: Knowledge base ID+ in: path+ name: kb_id+ required: true+ type: string+ - description: Revert target+ in: body+ name: revert+ required: true+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevertRequest'+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'+ "404":+ description: Not Found+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'+ "409":+ description: Conflict+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'+ security:+ - Bearer: []+ summary: Revert a wiki page to an earlier revision+ tags:+ - Wiki+ /knowledgebase/{kb_id}/wiki/revisions/{slug}:+ get:+ description: |-+ Returns the stored historical snapshots for a page, newest+ first (content omitted), plus the current version. Passing+ `version` returns that single snapshot with full content.+ parameters:+ - description: Knowledge base ID+ in: path+ name: kb_id+ required: true+ type: string+ - description: Page slug+ in: path+ name: slug+ required: true+ type: string+ - description: Return this single revision with content+ in: query+ name: version+ type: integer+ - description: Page size (default 50, max 200)+ in: query+ name: limit+ type: integer+ - description: Offset into the newest-first list+ in: query+ name: offset+ type: integer+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageRevisionListResponse'+ "404":+ description: Not Found+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'+ security:+ - Bearer: []+ summary: List wiki page revisions+ tags:+ - Wiki/knowledgebase/{kb_id}/wiki/search:get:description: Full-text search over wiki pagesdiff --git a/frontend/src/api/wiki/index.ts b/frontend/src/api/wiki/index.tsindex b0fd19204..7bb840247 100644--- a/frontend/src/api/wiki/index.ts+++ b/frontend/src/api/wiki/index.ts@@ -298,47 +298,6 @@ export function getWikiIndex(return get(`/api/v1/knowledgebase/${kbId}/wiki/index${suffix}`);}-export interface WikiLogPageRef {- slug: string;- title?: string;-}--export interface WikiLogEntry {- id: number;- tenant_id: number;- knowledge_base_id: string;- action: string;- knowledge_id: string;- doc_title: string;- summary: string;- // Each ref carries both slug (for navigation) and title (captured at- // ingest time for display). Legacy rows written before the title- // column was added surface as refs with an empty title; render falls- // back to the slug in that case.- pages_affected: WikiLogPageRef[];- created_at: string;-}--export interface WikiLogListResponse {- entries: WikiLogEntry[];- next_cursor?: string;-}--// getWikiLog fetches a page of wiki operation events (newest first). Pass the-// `next_cursor` from the previous response back as `cursor` to load more;-// an empty / missing `next_cursor` signals end-of-feed. `limit` is clamped-// server-side to [1, 200] and defaults to 50.-export function getWikiLog(kbId: string, params?: { cursor?: string; limit?: number }) {- const query = new URLSearchParams();- if (params) {- if (params.cursor) query.set('cursor', params.cursor);- if (params.limit !== undefined) query.set('limit', String(params.limit));- }- const qs = query.toString();- const suffix = qs ? `?${qs}` : '';- return get(`/api/v1/knowledgebase/${kbId}/wiki/log${suffix}`);-}-export interface WikiGraphQueryParams {mode?: 'overview' | 'ego';center?: string;diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex e91f2ef1d..67a2228a9 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -2752,10 +2752,6 @@ export default {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',@@ -2836,12 +2832,9 @@ export default {recentActivity: 'Recent Activity',graphEmpty: 'Loading graph...',fitView: 'Fit to View',- logTitle: 'Activity Log',indexTitle: 'Index',- logFeedTag: 'Event feed',- logEmpty: 'No log entries yet',- logLoading: 'Loading…',- logLoadMore: 'Load more',+ loading: 'Loading…',+ loadMoreShort: 'Load more',indexOverviewTag: 'Directory',indexEmpty: 'No wiki pages yet. Upload documents first.',graphNoData: 'No graph data yet. Upload documents first. (This view shows links between Wiki pages, which is different from the entity-relationship graph configured under "KB Settings → Knowledge Graph".)',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 2ff83ce4c..4ef1910d5 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -3992,10 +3992,6 @@ export default {editSourceAgent: "AI 수정",editSourceRevert: "롤백됨",editSourcePipeline: "자동 생성",- logActionManualCreate: "수동 생성",- logActionManualEdit: "수동 편집",- logActionManualDelete: "수동 삭제",- logActionRevert: "롤백됨",newPageBtn: "새 페이지",newPageTitle: "위키 페이지 만들기",newPageTitleLabel: "제목",@@ -4076,12 +4072,9 @@ export default {recentActivity: "최근 활동",graphEmpty: "그래프 로딩 중...",fitView: "화면에 맞춤",- logTitle: '활동 로그',indexTitle: '인덱스',- logFeedTag: '이벤트 피드',- logEmpty: '로그 기록이 없습니다',- logLoading: '로딩 중…',- logLoadMore: '더 보기',+ loading: '로딩 중…',+ loadMoreShort: '더 보기',indexOverviewTag: '분류 목록',indexEmpty: 'Wiki 페이지가 없습니다. 먼저 문서를 업로드하세요.',graphNoData: '그래프 데이터가 없습니다. 먼저 문서를 업로드하세요. (여기는 Wiki 페이지 간의 링크 관계를 표시하며, "지식 베이스 설정 → 지식 그래프"에서 구성하는 엔티티-관계 그래프와는 다릅니다.)',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 11887f576..5edaed873 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -3463,10 +3463,6 @@ export default {editSourceAgent: 'Изменено ИИ',editSourceRevert: 'Откат',editSourcePipeline: 'Автогенерация',- logActionManualCreate: 'Создано вручную',- logActionManualEdit: 'Изменено вручную',- logActionManualDelete: 'Удалено вручную',- logActionRevert: 'Откат',newPageBtn: 'Новая страница',newPageTitle: 'Создать вики-страницу',newPageTitleLabel: 'Заголовок',@@ -3547,12 +3543,9 @@ export default {recentActivity: 'Последняя активность',graphEmpty: 'Загрузка графа...',fitView: 'По размеру экрана',- logTitle: 'Журнал активности',indexTitle: 'Индекс',- logFeedTag: 'Лента событий',- logEmpty: 'Записей журнала пока нет',- logLoading: 'Загрузка…',- logLoadMore: 'Загрузить ещё',+ loading: 'Загрузка…',+ loadMoreShort: 'Загрузить ещё',indexOverviewTag: 'Каталог',indexEmpty: 'Пока нет wiki-страниц. Сначала загрузите документы.',graphNoData: 'Нет данных графа. Сначала загрузите документы. (Здесь показаны связи между Wiki-страницами, что отличается от графа сущностей и отношений в «Настройки БЗ → Граф знаний».)',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 8d6a1ca68..f9d316020 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -4050,10 +4050,6 @@ export default {editSourceAgent: "AI 修改",editSourceRevert: "版本回滚",editSourcePipeline: "自动生成",- logActionManualCreate: "手动创建",- logActionManualEdit: "手动编辑",- logActionManualDelete: "手动删除",- logActionRevert: "版本回滚",newPageBtn: "新建页面",newPageTitle: "新建 Wiki 页面",newPageTitleLabel: "标题",@@ -4134,12 +4130,9 @@ export default {recentActivity: "最近活动",graphEmpty: "加载图谱中...",fitView: "适应屏幕",- logTitle: '日志',indexTitle: '索引',- logFeedTag: '事件流',- logEmpty: '暂无日志记录',- logLoading: '加载中…',- logLoadMore: '加载更多',+ loading: '加载中…',+ loadMoreShort: '加载更多',indexOverviewTag: '分类目录',indexEmpty: '暂无 Wiki 页面,请先上传文档',graphNoData: '暂无图谱数据,请先上传文档(这里展示的是 Wiki 页面之间的链接关系,与「知识库设置 → 知识图谱」中的实体-关系图谱不同)',diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex 715c58872..4005004d9 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -676,7 +676,7 @@ const currentWikiKbId = ref<string>('');function getTypeTheme(type: string): string {const map: Record<string, string> = {summary: 'primary', entity: 'success', concept: 'warning',- synthesis: 'primary', comparison: 'danger', index: 'default', log: 'default',+ synthesis: 'primary', comparison: 'danger', index: 'default',};return map[type] || 'default';}@@ -689,7 +689,6 @@ function getTypeLabel(type: string): string {synthesis: t('knowledgeEditor.wikiBrowser.filterSynthesis'),comparison: t('knowledgeEditor.wikiBrowser.filterComparison'),index: 'Index',- log: 'Log',};return map[type] || type;}diff --git a/frontend/src/views/knowledge/wiki/WikiBrowser.vue b/frontend/src/views/knowledge/wiki/WikiBrowser.vueindex 7a5e020d2..65d65fb59 100644--- a/frontend/src/views/knowledge/wiki/WikiBrowser.vue+++ b/frontend/src/views/knowledge/wiki/WikiBrowser.vue@@ -210,15 +210,7 @@<span class="wiki-nav-text">{{ $t('knowledgeEditor.wikiBrowser.indexTitle') }}</span></div>- <!-- Log feed (pinned). Events live in wiki_log_entries and- are loaded lazily when the user clicks this entry. -->- <div v-if="logAvailable" :class="['wiki-nav-item', { active: activeSystemView === 'log' }]"- @click="openLogView">- <t-icon name="history" class="wiki-nav-icon" />- <span class="wiki-nav-text">{{ $t('knowledgeEditor.wikiBrowser.logTitle') }}</span>- </div>-- <div class="wiki-sidebar-divider" v-if="indexAvailable || logAvailable"></div>+ <div class="wiki-sidebar-divider" v-if="indexAvailable"></div><!-- Tab bar + tree share one horizontal inset so the "new folder"action lines up with the folder rows below. -->@@ -328,7 +320,7 @@<t-loading v-if="item.loading" size="small" /><template v-else><t-icon name="chevron-down" />- <span>{{ $t('knowledgeEditor.wikiBrowser.logLoadMore') }}</span>+ <span>{{ $t('knowledgeEditor.wikiBrowser.loadMoreShort') }}</span></template></div><div v-else@@ -606,14 +598,14 @@</div></div><div v-if="indexLoading && !indexMarkdown" class="wiki-reader-empty">- <p class="wiki-empty-title">{{ $t('knowledgeEditor.wikiBrowser.logLoading') }}</p>+ <p class="wiki-empty-title">{{ $t('knowledgeEditor.wikiBrowser.loading') }}</p></div><template v-else-if="indexMarkdown"><div ref="indexBodyRef" class="wiki-reader-body wiki-index-body" v-html="renderedIndexMarkdown"@click="handleContentClick"></div><div v-if="indexHasMore" ref="indexSentinelRef" class="wiki-index-sentinel"><span v-if="indexLoading" class="wiki-index-loading">- {{ $t('knowledgeEditor.wikiBrowser.logLoading') }}+ {{ $t('knowledgeEditor.wikiBrowser.loading') }}</span></div></template>@@ -622,44 +614,6 @@</div></template>- <!-- System view: log feed. Mutually exclusive with selectedPage. -->- <template v-else-if="activeSystemView === 'log'">- <div class="wiki-reader-header">- <h2 class="wiki-reader-title">{{ $t('knowledgeEditor.wikiBrowser.logTitle') }}</h2>- <div class="wiki-reader-meta">- <t-tag size="small" theme="default" variant="light-outline">- {{ $t('knowledgeEditor.wikiBrowser.logFeedTag') }}- </t-tag>- </div>- </div>- <div class="wiki-log-feed">- <div v-if="logEntries.length === 0 && logInitialized" class="wiki-log-empty">- {{ $t('knowledgeEditor.wikiBrowser.logEmpty') }}- </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="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>- </div>- <div v-if="entry.summary" class="wiki-log-entry-summary">{{ entry.summary }}</div>- <div v-if="entry.pages_affected && entry.pages_affected.length" class="wiki-log-entry-pages">- <a v-for="ref in entry.pages_affected" :key="entry.id + ':' + ref.slug" href="#"- class="wiki-log-entry-page" :title="ref.slug" @click.prevent="navigateToSlug(ref.slug)">{{- ref.title || ref.slug }}</a>- </div>- </div>- <div v-if="logNextCursor || !logInitialized" class="wiki-log-load-more">- <t-button size="small" variant="outline" theme="default" :loading="logLoading" @click="loadMoreLog">- {{ logInitialized ? $t('knowledgeEditor.wikiBrowser.logLoadMore') :- $t('knowledgeEditor.wikiBrowser.logLoading') }}- </t-button>- </div>- </div>- </template>-<!-- No page selected --><div v-else class="wiki-reader-empty"><div class="wiki-empty-icon">@@ -833,7 +787,6 @@ import {deleteWikiPage,getWikiPage,getWikiIndex,- getWikiLog,getWikiGraph,getWikiStats,searchWikiPages,@@ -844,7 +797,6 @@ import {type WikiGraphData,type WikiStats,type WikiPageIssue,- type WikiLogEntry,type WikiIndexGroup,type WikiIndexEntryDTO,} from '@/api/wiki'@@ -972,27 +924,10 @@ const INDEX_SECTION_ORDER = ['synthesis','comparison',] as const-// logAvailable is a flag: the sidebar "Log" entry is always shown once a-// KB exists, because the backing wiki_log_entries table is KB-independent-// and `GET /wiki/log` returns an empty entries list when nothing has been-// logged yet. We don't need a full WikiPage object anymore — selecting-// Log swaps the reader into a dedicated feed view below.-const logAvailable = ref(true)--// activeSystemView lets the reader toggle between a regular wiki page-// (selectedPage) and a "virtual" system view — index overview and log-// feed. These modes are mutually exclusive: entering a system view-// clears selectedPage, and picking a page clears the system view flag.-const activeSystemView = ref<'' | 'index' | 'log'>('')--// Paginated state for the log view. `entries` grows as the user scrolls;-// `nextCursor` is the opaque cursor returned by the backend and empty-// signals end-of-feed. `loading` is the guard that prevents overlapping-// loadMore calls while a request is in flight.-const logEntries = ref<WikiLogEntry[]>([])-const logNextCursor = ref('')-const logLoading = ref(false)-const logInitialized = ref(false)+// activeSystemView lets the reader toggle between a regular wiki page and the+// virtual index overview. Entering the index clears the selected page, and+// picking a page clears the system view flag.+const activeSystemView = ref<'' | 'index'>('')// When the user types into the search box we leave pagination mode and// show a flat result list instead. Bucketed state is preserved behind@@ -1017,7 +952,7 @@ const graphReady = ref(false)const showArrows = ref(true)// Graph filtering-const graphFilterTypes = ref<Set<string>>(new Set(['summary', 'entity', 'concept', 'synthesis', 'comparison', 'index', 'log']))+const graphFilterTypes = ref<Set<string>>(new Set(['summary', 'entity', 'concept', 'synthesis', 'comparison', 'index']))// Graph slicing state. The backend caps an overview fetch at 500 nodes —// tens-of-thousands-page wikis would otherwise crash the browser trying to@@ -1161,17 +1096,13 @@ function fitGraphToView() {const graphDrawerVisible = ref(false)const graphDrawerPage = ref<WikiPage | null>(null)const navHistory = ref<WikiPage[]>([])-// navFromSystemView remembers which system view (Index / Log) the user-// was viewing when they clicked into a slug, so goBack can restore it+// navFromSystemView remembers that the user was viewing the Index when they+// clicked into a slug, so goBack can restore it// once the page-level history stack is empty. We keep this parallel to// navHistory rather than widening its element type — navHistory is// consumed everywhere as `WikiPage[]` and that contract stays cleaner// if the system-view sentinel lives in its own ref.-const navFromSystemView = ref<'' | 'index' | 'log'>('')-// Index and log pages are now state refs (loaded by their own endpoints-// at startup) rather than computed over the full page list. The old-// computed implementation required pulling every page into memory just-// to pluck two system pages.+const navFromSystemView = ref<'' | 'index'>('')// typeOrder drives the order of groups in the sidebar. Keep in sync// with WIKI_PAGE_TYPES on the backend; unknown types fall through to@@ -1249,7 +1180,7 @@ const groupedPages = computed(() => {// order so the sidebar doesn't suddenly hide a future tab.for (const tab of Object.keys(pagesByType.value)) {if (seen.has(tab)) continue- if (tab === 'index' || tab === 'log') continue+ if (tab === 'index') continuepush(tab)}return out@@ -1980,7 +1911,7 @@ watch([activeTreeRows, treeListRef], () => {function getTypeTheme(type: string): string {const map: Record<string, string> = {summary: 'primary', entity: 'success', concept: 'warning',- synthesis: 'primary', comparison: 'danger', index: 'default', log: 'default',+ synthesis: 'primary', comparison: 'danger', index: 'default',}return map[type] || 'default'}@@ -1994,7 +1925,6 @@ function getTypeLabel(type: string): string {synthesis: t('knowledgeEditor.wikiBrowser.filterSynthesis'),comparison: t('knowledgeEditor.wikiBrowser.filterComparison'),index: 'Index',- log: 'Log',}return map[type] || type}@@ -2019,7 +1949,7 @@ const renderedContent = computed(() => {// Label shown next to the back arrow on page headers. Prefers the// nearest page-history entry when available so the user sees where-// they'll land; falls back to the Index/Log label when the current+// they'll land; falls back to the Index label when the current// page was opened directly from a system view.const backLabel = computed(() => {if (navHistory.value.length > 0) {@@ -2028,9 +1958,6 @@ const backLabel = computed(() => {if (navFromSystemView.value === 'index') {return t('knowledgeEditor.wikiBrowser.indexTitle')}- if (navFromSystemView.value === 'log') {- return t('knowledgeEditor.wikiBrowser.logTitle')- }return ''})@@ -2573,17 +2500,11 @@ async function loadPagesForType(type: string, opts: { reset?: boolean; categoryPawait nextTick()}-// loadIndexAndLog probes the wiki index so the sidebar knows to show-// the pinned Index/Log entries. We ask the backend for intro only (zero+// loadIndex probes the wiki index so the sidebar knows to show the pinned+// Index entry. We ask the backend for intro only (zero// group types) — a bounded response regardless of KB size. Sections are// fetched lazily after the user actually opens the Index view; see// loadMoreIndexSection.-//-// The log "page" is no longer stored in wiki_pages — it lives in the-// dedicated wiki_log_entries table. We don't need to pre-fetch anything-// here to decide whether to render the sidebar Log entry; the flag is-// always on, and the actual feed is fetched lazily when the user clicks-// the entry (see openLogView / loadMoreLog).// stripLegacyIndexDirectory removes the inline "## Summary (N)\n[[...]]// ..." directory listing from a legacy index row. Old wiki_pages rows// stored "intro + directory markdown" in content; after the refactor@@ -2599,7 +2520,7 @@ function stripLegacyIndexDirectory(intro: string): string {return intro.slice(0, idx).trim()}-async function loadIndexAndLog() {+async function loadIndex() {try {// We only need intro on the initial probe — the directory groups// are fetched lazily once the user opens the Index view. Passing@@ -2614,7 +2535,6 @@ async function loadIndexAndLog() {indexAvailable.value = trueindexSections.value = {}indexSectionIdx.value = 0- logAvailable.value = true} catch (e) {console.error('Failed to load wiki index:', e)}@@ -2629,7 +2549,7 @@ async function openIndexView() {if (!indexMarkdown.value) {indexLoading.value = truetry {- await loadIndexAndLog()+ await loadIndex()} finally {indexLoading.value = false}@@ -2787,44 +2707,6 @@ onUnmounted(() => {}})-// openLogView switches the reader into the log feed and (re)loads the-// first page. Called when the user clicks the sidebar Log entry.-async function openLogView() {- selectedPage.value = null- activeSystemView.value = 'log'- logEntries.value = []- logNextCursor.value = ''- logInitialized.value = false- await loadMoreLog()-}--// loadMoreLog appends the next page of log entries using the cursor from-// the previous response. Guarded so overlapping scroll events don't fire-// multiple requests and double-append entries.-async function loadMoreLog() {- if (logLoading.value) return- // Once a previous request reported end-of-feed (empty next_cursor), we- // stop — but only after the first fetch, so a fresh KB still runs the- // initial empty request to populate logInitialized.- if (logInitialized.value && !logNextCursor.value) return- logLoading.value = true- try {- const res = await getWikiLog(props.knowledgeBaseId, {- cursor: logNextCursor.value || undefined,- limit: 50,- })- const body: any = (res as any).data || res- const entries: WikiLogEntry[] = body?.entries || []- logEntries.value.push(...entries)- logNextCursor.value = body?.next_cursor || ''- logInitialized.value = true- } catch (e) {- console.error('Failed to load wiki log:', e)- } finally {- logLoading.value = false- }-}-// loadPages is the sidebar's top-level initialization. It wires up the// empty buckets (so groupedPages produces stable group slots even// before any fetch completes), pulls the pinned system pages, and then@@ -2840,7 +2722,7 @@ async function loadPages() {try {searchResults.value = nullfor (const tab of CONTENT_TABS) ensureBucket(tab)- await loadIndexAndLog()+ await loadIndex()await Promise.all(CONTENT_TABS.map(async tab => {await loadPagesForType(tab, { reset: true })await loadCategoriesForType(tab, { reset: true })@@ -3100,36 +2982,6 @@ function updateSidebarPageTitle(slug: string, title: string) {}}-// 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'}@@ -3181,7 +3033,7 @@ async function refreshSelectedPage() {// there (empty == no filter == return everything, the opposite of what// the user meant).function graphFilterTypesToArray(): string[] | undefined {- const all = ['summary', 'entity', 'concept', 'synthesis', 'comparison', 'index', 'log']+ const all = ['summary', 'entity', 'concept', 'synthesis', 'comparison', 'index']if (all.every(t => graphFilterTypes.value.has(t))) {return undefined}@@ -3454,7 +3306,7 @@ const GROW_FRONTIER_CONCURRENCY = 6// interesting neighborhood"). We keep them visible and individually// expandable (double-click / shift-click / ⊕ all still work), but they// don't participate in batch expansion.-const GRAPH_SYSTEM_PAGE_TYPES = new Set(['index', 'log'])+const GRAPH_SYSTEM_PAGE_TYPES = new Set(['index'])function isFrontierCandidate(node: { slug: string; page_type: string; link_count: number },@@ -3622,11 +3474,7 @@ function goBack() {const view = navFromSystemView.valuenavFromSystemView.value = ''selectedPage.value = null- if (view === 'index') {- openIndexView()- } else if (view === 'log') {- openLogView()- }+ if (view === 'index') openIndexView()}}@@ -3775,7 +3623,7 @@ const graphSelectedSlug = ref<string | null>(null)// Color map for node typesconst nodeColorMap: Record<string, string> = {summary: '#0052d9', entity: '#2ba471', concept: '#e37318',- synthesis: '#0594fa', comparison: '#d54941', index: '#8c8c8c', log: '#8c8c8c',+ synthesis: '#0594fa', comparison: '#d54941', index: '#8c8c8c',}// RenderGraphOpts tweaks how renderGraph initializes node positions when@@ -5968,17 +5816,6 @@ onUnmounted(() => {text-align: center;}-// ── Log feed (system view) ──-// Rendered when activeSystemView === 'log'. Sits where the markdown body-// would be for a regular wiki page — so the header/meta rules above-// already apply. We just style the feed list itself.-.wiki-log-feed {- display: flex;- flex-direction: column;- gap: 12px;- padding-top: 12px;-}-// ── Index overview (system view) ──// The index view renders as markdown through the same pipeline as a// normal wiki page, so it inherits .wiki-reader-body styling automatically.@@ -5998,78 +5835,6 @@ onUnmounted(() => {opacity: 0.7;}-.wiki-log-empty {- color: var(--td-text-color-placeholder);- text-align: center;- padding: 40px 0;- font-size: 13px;-}--.wiki-log-entry {- border-radius: var(--wiki-list-row-radius);- padding: 10px 10px 10px var(--wiki-list-inset-x);- background: transparent;- transition: background 0.15s ease;-- &:hover {- background: var(--td-bg-color-container-hover);- }-}--.wiki-log-entry-header {- display: flex;- align-items: center;- gap: 8px;- margin-bottom: 4px;-}--.wiki-log-entry-title {- font-weight: 400;- font-size: 14px;- line-height: 20px;- color: var(--td-text-color-primary);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- flex: 1;- min-width: 0;-}--.wiki-log-entry-time {- color: var(--td-text-color-placeholder);- font-size: 12px;- white-space: nowrap;-}--.wiki-log-entry-summary {- color: var(--td-text-color-secondary);- font-size: 13px;- margin: 4px 0;-}--.wiki-log-entry-pages {- display: flex;- flex-wrap: wrap;- gap: 4px 10px;- margin-top: 4px;-}--.wiki-log-entry-page {- color: var(--td-brand-color);- font-size: 12px;- text-decoration: none;-}--.wiki-log-entry-page:hover {- text-decoration: underline;-}--.wiki-log-load-more {- display: flex;- justify-content: center;- padding: 12px 0;-}-.wiki-empty-icon {width: 64px;height: 64px;diff --git a/frontend/src/views/knowledge/wiki/WikiRevisionDrawer.vue b/frontend/src/views/knowledge/wiki/WikiRevisionDrawer.vueindex 4c0543a71..15ad30f55 100644--- a/frontend/src/views/knowledge/wiki/WikiRevisionDrawer.vue+++ b/frontend/src/views/knowledge/wiki/WikiRevisionDrawer.vue@@ -32,7 +32,7 @@<div v-if="revisions.length < total" class="wiki-rev-load-more"><t-button size="small" variant="outline" theme="default" :loading="loadingList" block @click="loadMore">- {{ t('knowledgeEditor.wikiBrowser.logLoadMore') }}+ {{ t('knowledgeEditor.wikiBrowser.loadMoreShort') }}</t-button></div></div>@@ -77,7 +77,7 @@<div v-if="loadingDetail" class="wiki-rev-detail-loading"><t-loading size="small" />- <span>{{ t('knowledgeEditor.wikiBrowser.logLoading') }}</span>+ <span>{{ t('knowledgeEditor.wikiBrowser.loading') }}</span></div><!-- Diff vs current -->diff --git a/internal/agent/prompts_wiki.go b/internal/agent/prompts_wiki.goindex 3827689ab..220442ae6 100644--- a/internal/agent/prompts_wiki.go+++ b/internal/agent/prompts_wiki.go@@ -444,13 +444,6 @@ const WikiIndexIntroUpdatePrompt = `You are a wiki editor. Update the introductiOutput ONLY the updated title and introduction paragraph. Do NOT generate any directory listings or page links.`-// WikiLogEntryTemplate is a simple template for log entries (not LLM-generated).-const WikiLogEntryTemplate = `## [{{.Date}}] {{.Operation}} | {{.Title}}-- **Source**: {{.SourceInfo}}-- **Pages affected**: {{.PagesAffected}}-- **Summary**: {{.Summary}}-`-// WikiDeduplicationPrompt asks the LLM to identify duplicate entities/concepts// between newly extracted items and existing wiki pages.const WikiDeduplicationPrompt = `You are a strict deduplication system. You are given a list of newly extracted items. Each item carries its OWN short list of existing wiki pages that are surface-similar to it (its <candidates>). For each item, decide whether it refers to the **exact same** real-world entity or concept as ONE of its own candidates.diff --git a/internal/agent/tools/wiki_tools.go b/internal/agent/tools/wiki_tools.goindex 6151e1159..877f020f0 100644--- a/internal/agent/tools/wiki_tools.go+++ b/internal/agent/tools/wiki_tools.go@@ -223,20 +223,14 @@ func extractSourceKnowledgeIDs(page *types.WikiPage) []string {return ids}-// isStructuralPage reports whether a page is a wiki-level structural/meta-// page (index, log) rather than a content page tied to specific source-// documents. Structural pages are never filtered by knowledge_ids scope —-// they describe wiki topology (TOC, operation log) and must remain reachable-// even when the user has pinned specific documents.+// isStructuralPage reports whether a page is the wiki-level index rather than+// a content page tied to specific source documents. The index is never+// filtered by knowledge_ids scope because it describes wiki topology.func isStructuralPage(page *types.WikiPage) bool {if page == nil {return false}- switch page.PageType {- case types.WikiPageTypeIndex, types.WikiPageTypeLog:- return true- }- return false+ return page.PageType == types.WikiPageTypeIndex}// registerLinkedSlugs records the KB that owns this page for every slug thediff --git a/internal/application/repository/wiki_log_entry.go b/internal/application/repository/wiki_log_entry.godeleted file mode 100644index 73d914588..000000000--- a/internal/application/repository/wiki_log_entry.go+++ /dev/null@@ -1,92 +0,0 @@-package repository--import (- "context"- "errors"- "fmt"- "strconv"-- "github.com/Tencent/WeKnora/internal/types"- "github.com/Tencent/WeKnora/internal/types/interfaces"- "gorm.io/gorm"-)--// wikiLogEntryRepository implements interfaces.WikiLogEntryRepository.-type wikiLogEntryRepository struct {- db *gorm.DB-}--// NewWikiLogEntryRepository constructs a GORM-backed WikiLogEntryRepository.-func NewWikiLogEntryRepository(db *gorm.DB) interfaces.WikiLogEntryRepository {- return &wikiLogEntryRepository{db: db}-}--// AppendBatch inserts every entry in one statement. Empty batches are a-// no-op so callers can invoke unconditionally at the end of a wiki ingest-// batch without guarding against the "no events this round" case.-func (r *wikiLogEntryRepository) AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error {- if len(entries) == 0 {- return nil- }- return r.db.WithContext(ctx).Create(&entries).Error-}--// List returns up to `limit` entries strictly older than `cursor`, newest-// first. `cursor` is the stringified ID of the oldest entry from the-// previous page; an empty string starts from the newest. Callers get back-// a nextCursor string to pass on the next request — empty means no more.-//-// `limit` is clamped to [1, 200]. Values outside that range are coerced-// silently to keep the handler simple.-func (r *wikiLogEntryRepository) List(- ctx context.Context,- kbID string,- cursor string,- limit int,-) ([]*types.WikiLogEntry, string, error) {- if limit <= 0 {- limit = 50- }- if limit > 200 {- limit = 200- }-- q := r.db.WithContext(ctx).- Where("knowledge_base_id = ?", kbID).- Order("id DESC").- Limit(limit)-- if cursor != "" {- cursorID, err := strconv.ParseUint(cursor, 10, 64)- if err != nil {- return nil, "", fmt.Errorf("invalid cursor %q: %w", cursor, err)- }- q = q.Where("id < ?", cursorID)- }-- var entries []*types.WikiLogEntry- if err := q.Find(&entries).Error; err != nil {- return nil, "", err- }-- nextCursor := ""- // Only emit a cursor when we actually filled the page — a short page- // is guaranteed to be the tail, so returning a cursor would just cause- // the frontend to fire a final empty request.- if len(entries) == limit {- nextCursor = strconv.FormatUint(entries[len(entries)-1].ID, 10)- }- return entries, nextCursor, nil-}--// DeleteByKB drops every log entry for a KB. No "affected rows" signal is-// surfaced — missing rows are a legitimate state (e.g., a KB that was-// created before wiki_log_entries existed) and not a failure condition.-func (r *wikiLogEntryRepository) DeleteByKB(ctx context.Context, kbID string) error {- if kbID == "" {- return errors.New("wiki log entries: empty kb id")- }- return r.db.WithContext(ctx).- Where("knowledge_base_id = ?", kbID).- Delete(&types.WikiLogEntry{}).Error-}diff --git a/internal/application/repository/wiki_log_entry_test.go b/internal/application/repository/wiki_log_entry_test.godeleted file mode 100644index 649da9603..000000000--- a/internal/application/repository/wiki_log_entry_test.go+++ /dev/null@@ -1,219 +0,0 @@-package repository--import (- "context"- "testing"-- "github.com/Tencent/WeKnora/internal/types"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"- "gorm.io/driver/sqlite"- "gorm.io/gorm"-)--// wikiLogEntriesTestDDL mirrors migrations/versioned/000040_wiki_log_entries.up.sql-// but uses SQLite-compatible types so we can exercise the repo layer without-// spinning up Postgres. INTEGER PRIMARY KEY AUTOINCREMENT gives us the same-// monotonically-increasing ID semantics the production schema relies on for-// cursor pagination.-const wikiLogEntriesTestDDL = `-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-);-`--func setupWikiLogTestDB(t *testing.T) *gorm.DB {- t.Helper()- db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})- require.NoError(t, err)- require.NoError(t, db.Exec(wikiLogEntriesTestDDL).Error)- return db-}--func makeLogEntry(kbID, action, knowledgeID, title string, pages ...string) *types.WikiLogEntry {- refs := make(types.WikiLogPageRefs, 0, len(pages))- for _, slug := range pages {- // Tests only care about round-tripping; title is derived from- // the slug so assertions don't have to spell out both fields.- refs = append(refs, types.WikiLogPageRef{Slug: slug, Title: "title-of-" + slug})- }- return &types.WikiLogEntry{- TenantID: 1,- KnowledgeBaseID: kbID,- Action: action,- KnowledgeID: knowledgeID,- DocTitle: title,- Summary: "summary for " + title,- PagesAffected: refs,- }-}--// TestWikiLogEntryRepository_AppendBatch_WritesAllRows verifies a batch-// insert persists every entry with a monotonic ID and respects the caller--// provided column values.-func TestWikiLogEntryRepository_AppendBatch_WritesAllRows(t *testing.T) {- db := setupWikiLogTestDB(t)- repo := NewWikiLogEntryRepository(db)- ctx := context.Background()-- entries := []*types.WikiLogEntry{- makeLogEntry("kb-a", "ingest", "k1", "Doc 1", "entity/a", "summary/k1"),- makeLogEntry("kb-a", "ingest", "k2", "Doc 2"),- makeLogEntry("kb-a", "retract", "k3", "Doc 3", "concept/c"),- }-- require.NoError(t, repo.AppendBatch(ctx, entries))-- // Every row should have a non-zero ID assigned by the DB, and IDs- // should increase in insertion order so the cursor pagination logic- // can rely on them.- for i := range entries {- assert.NotZero(t, entries[i].ID, "row %d should have a DB-assigned ID", i)- if i > 0 {- assert.Greater(t, entries[i].ID, entries[i-1].ID,- "AppendBatch should preserve insertion order")- }- }-- // Round-trip sanity: select back and confirm payload was preserved.- var got []types.WikiLogEntry- require.NoError(t, db.Order("id ASC").Find(&got).Error)- require.Len(t, got, len(entries))- assert.Equal(t, "ingest", got[0].Action)- assert.Equal(t, "Doc 1", got[0].DocTitle)- assert.Equal(t, types.WikiLogPageRefs{- {Slug: "entity/a", Title: "title-of-entity/a"},- {Slug: "summary/k1", Title: "title-of-summary/k1"},- }, got[0].PagesAffected)- assert.Equal(t, "retract", got[2].Action)-}--// TestWikiLogEntryRepository_AppendBatch_Empty asserts an empty batch is a-// cheap no-op — callers at the end of a wiki ingest pass can invoke it-// unconditionally without a DB round trip.-func TestWikiLogEntryRepository_AppendBatch_Empty(t *testing.T) {- db := setupWikiLogTestDB(t)- repo := NewWikiLogEntryRepository(db)- ctx := context.Background()-- require.NoError(t, repo.AppendBatch(ctx, nil))- require.NoError(t, repo.AppendBatch(ctx, []*types.WikiLogEntry{}))-- var count int64- require.NoError(t, db.Model(&types.WikiLogEntry{}).Count(&count).Error)- assert.Equal(t, int64(0), count)-}--// TestWikiLogEntryRepository_List_CursorPagination walks the feed with a-// limit smaller than the population size and confirms:-// - newest entries surface first (id DESC order),-// - passing next_cursor returns the next batch strictly older than it,-// - end-of-feed is signalled by an empty cursor.-func TestWikiLogEntryRepository_List_CursorPagination(t *testing.T) {- db := setupWikiLogTestDB(t)- repo := NewWikiLogEntryRepository(db)- ctx := context.Background()-- // 5 entries in one KB + a sibling row in another KB to ensure the- // WHERE filter actually narrows by KB.- entries := []*types.WikiLogEntry{- makeLogEntry("kb-a", "ingest", "k1", "Doc 1"),- makeLogEntry("kb-a", "ingest", "k2", "Doc 2"),- makeLogEntry("kb-a", "ingest", "k3", "Doc 3"),- makeLogEntry("kb-a", "ingest", "k4", "Doc 4"),- makeLogEntry("kb-a", "retract", "k5", "Doc 5"),- }- require.NoError(t, repo.AppendBatch(ctx, entries))-- other := makeLogEntry("kb-other", "ingest", "kx", "Other doc")- require.NoError(t, repo.AppendBatch(ctx, []*types.WikiLogEntry{other}))-- // First page: latest 2 of kb-a, newest first.- page1, cursor1, err := repo.List(ctx, "kb-a", "", 2)- require.NoError(t, err)- require.Len(t, page1, 2)- assert.Equal(t, "Doc 5", page1[0].DocTitle)- assert.Equal(t, "Doc 4", page1[1].DocTitle)- assert.NotEmpty(t, cursor1, "should emit next_cursor when the page is full")-- // Second page continues strictly older than cursor1.- page2, cursor2, err := repo.List(ctx, "kb-a", cursor1, 2)- require.NoError(t, err)- require.Len(t, page2, 2)- assert.Equal(t, "Doc 3", page2[0].DocTitle)- assert.Equal(t, "Doc 2", page2[1].DocTitle)- assert.NotEmpty(t, cursor2)-- // Third (final) page: one row remains, so cursor is empty — the repo- // must NOT emit a cursor for a short page, otherwise the frontend- // would fire a doomed follow-up request.- page3, cursor3, err := repo.List(ctx, "kb-a", cursor2, 2)- require.NoError(t, err)- require.Len(t, page3, 1)- assert.Equal(t, "Doc 1", page3[0].DocTitle)- assert.Empty(t, cursor3, "short page should signal end-of-feed with an empty cursor")-- // Sibling KB row must NOT leak into kb-a's feed.- for _, p := range append(append(page1, page2...), page3...) {- assert.Equal(t, "kb-a", p.KnowledgeBaseID)- }-}--// TestWikiLogEntryRepository_List_InvalidCursor rejects a non-numeric-// cursor rather than silently returning the newest page, so clients-// notice bugs before they turn into phantom paginations.-func TestWikiLogEntryRepository_List_InvalidCursor(t *testing.T) {- db := setupWikiLogTestDB(t)- repo := NewWikiLogEntryRepository(db)- ctx := context.Background()-- _, _, err := repo.List(ctx, "kb-a", "not-a-number", 10)- assert.Error(t, err)-}--// TestWikiLogEntryRepository_DeleteByKB purges one KB's rows without-// touching others. Used during KB deletion so the log table does not-// accumulate orphans after the parent KB is gone.-func TestWikiLogEntryRepository_DeleteByKB(t *testing.T) {- db := setupWikiLogTestDB(t)- repo := NewWikiLogEntryRepository(db)- ctx := context.Background()-- require.NoError(t, repo.AppendBatch(ctx, []*types.WikiLogEntry{- makeLogEntry("kb-a", "ingest", "k1", "Doc 1"),- makeLogEntry("kb-a", "ingest", "k2", "Doc 2"),- makeLogEntry("kb-b", "ingest", "k3", "Doc 3"),- }))-- require.NoError(t, repo.DeleteByKB(ctx, "kb-a"))-- aEntries, _, err := repo.List(ctx, "kb-a", "", 100)- require.NoError(t, err)- assert.Empty(t, aEntries)-- bEntries, _, err := repo.List(ctx, "kb-b", "", 100)- require.NoError(t, err)- assert.Len(t, bEntries, 1)-}--// TestWikiLogPageRefs_ScanAcceptsLegacyStringArray covers the backward--// compat path in the Scan method. Any rows the ingest pipeline wrote-// before pages_affected gained a title field are stored as a plain JSON-// string array; the repo must decode them as slug-only refs so the log-// feed renders without a data migration.-func TestWikiLogPageRefs_ScanAcceptsLegacyStringArray(t *testing.T) {- var refs types.WikiLogPageRefs- require.NoError(t, refs.Scan([]byte(`["entity/acme","concept/rag"]`)))- require.Len(t, refs, 2)- assert.Equal(t, "entity/acme", refs[0].Slug)- assert.Empty(t, refs[0].Title, "legacy rows have no title until re-ingest overwrites them")- assert.Equal(t, "concept/rag", refs[1].Slug)-}diff --git a/internal/application/repository/wiki_page.go b/internal/application/repository/wiki_page.goindex 8372e97fe..f3659adbd 100644--- a/internal/application/repository/wiki_page.go+++ b/internal/application/repository/wiki_page.go@@ -1070,7 +1070,7 @@ func (r *wikiPageRepository) ListAll(ctx context.Context, kbID string) ([]*types// ListRecentForSuggestions returns recent user-visible wiki pages across the given// knowledge bases, used as a fallback source for agent suggested questions when// the KB has no FAQ entries or AI-generated document questions (typical for-// Wiki-only KBs). Excludes index/log pages and archived pages.+// Wiki-only KBs). Excludes the index page and archived pages.func (r *wikiPageRepository) ListRecentForSuggestions(ctx context.Context,tenantID uint64,@@ -1084,7 +1084,7 @@ func (r *wikiPageRepository) ListRecentForSuggestions(if err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Where("knowledge_base_id IN ?", kbIDs).- Where("page_type NOT IN ?", []string{types.WikiPageTypeIndex, types.WikiPageTypeLog}).+ Where("page_type <> ?", types.WikiPageTypeIndex).Where("status = ?", types.WikiPageStatusPublished).Where("title <> ''").Order("updated_at DESC").@@ -1213,8 +1213,8 @@ func (r *wikiPageRepository) CountOrphans(ctx context.Context, kbID string) (intModel(&types.WikiPage{}).Where("knowledge_base_id = ?", kbID).Where(r.wikiEmptyInLinksPredicate()).- // Exclude index and log pages as they are naturally root pages- Where("page_type NOT IN ?", []string{types.WikiPageTypeIndex, types.WikiPageTypeLog}).+ // Exclude the index page because it is naturally a root page.+ Where("page_type <> ?", types.WikiPageTypeIndex).Count(&count).Error; err != nil {return 0, err}diff --git a/internal/application/repository/wiki_page_test.go b/internal/application/repository/wiki_page_test.goindex f4404d823..74e29cb06 100644--- a/internal/application/repository/wiki_page_test.go+++ b/internal/application/repository/wiki_page_test.go@@ -378,12 +378,10 @@ func TestCountOrphans_SQLiteCountsEmptyInLinks(t *testing.T) {linked.InLinks = types.StringArray{"entity/source"}indexPage := makeWikiPage("kb-orphans", "index", types.WikiPageTypeIndex, types.WikiPageStatusPublished)indexPage.InLinks = types.StringArray{}- logPage := makeWikiPage("kb-orphans", "log", types.WikiPageTypeLog, types.WikiPageStatusPublished)- logPage.InLinks = types.StringArray{}otherKB := makeWikiPage("kb-other", "entity/other", types.WikiPageTypeEntity, types.WikiPageStatusPublished)otherKB.InLinks = types.StringArray{}- for _, p := range []*types.WikiPage{orphan, linked, indexPage, logPage, otherKB} {+ for _, p := range []*types.WikiPage{orphan, linked, indexPage, otherKB} {require.NoError(t, repo.Create(ctx, p))}diff --git a/internal/application/service/kb_activity.go b/internal/application/service/kb_activity.goindex f9930902e..d7c565473 100644--- a/internal/application/service/kb_activity.go+++ b/internal/application/service/kb_activity.go@@ -172,3 +172,27 @@ func recordKBActivity(Details: detailJSON,})}++// RecordWikiContentActivity writes the bounded Wiki mutation summary shown in+// the knowledge-base activity feed. Wiki mutations used to reach this feed as+// a side effect of inserting rows into the dedicated wiki_log_entries table;+// keeping the projection explicit lets the activity feed remain authoritative+// without maintaining a second, Wiki-only event store.+func RecordWikiContentActivity(+ ctx context.Context,+ audit interfaces.AuditLogService,+ tenantID uint64,+ kbID string,+ actions map[string]int,+) {+ count := 0+ for _, actionCount := range actions {+ count += actionCount+ }+ if count == 0 {+ return+ }+ recordKBActivity(ctx, audit, tenantID, kbID, types.AuditActionWikiContentChanged,+ "wiki", kbID, types.AuditOutcomeSuccess,+ map[string]any{"count": count, "actions": actions})+}diff --git a/internal/application/service/kb_activity_test.go b/internal/application/service/kb_activity_test.goindex 9c38aec28..f0fef970c 100644--- a/internal/application/service/kb_activity_test.go+++ b/internal/application/service/kb_activity_test.go@@ -116,6 +116,33 @@ func TestRecordKBActivityCanSuppressCompositeTaskChildren(t *testing.T) {}}+func TestRecordWikiContentActivityUsesUnifiedActivityFeed(t *testing.T) {+ audit := &captureKBActivityAudit{}+ RecordWikiContentActivity(context.Background(), audit, 7, "kb-1", map[string]int{+ "ingest": 3,+ "retract": 1,+ })++ if audit.entry == nil {+ t.Fatal("expected a wiki activity entry")+ }+ if audit.entry.Action != types.AuditActionWikiContentChanged ||+ audit.entry.ScopeType != auditScopeKnowledgeBase || audit.entry.ScopeID != "kb-1" {+ t.Fatalf("unexpected activity entry: %#v", audit.entry)+ }+ var details map[string]any+ if err := json.Unmarshal(audit.entry.Details, &details); err != nil {+ t.Fatalf("unmarshal details: %v", err)+ }+ if details["count"] != float64(4) {+ t.Fatalf("count = %#v, want 4", details["count"])+ }+ actions, ok := details["actions"].(map[string]any)+ if !ok || actions["ingest"] != float64(3) || actions["retract"] != float64(1) {+ t.Fatalf("actions = %#v", details["actions"])+ }+}+// TestKBActivityTriggerReflectsInitiatorIdentity locks in the worker// attribution used by ProcessKBClone / ProcessKnowledgeMove /// ProcessKnowledgeListDelete / ProcessKnowledgeListReparse: the taskdiff --git a/internal/application/service/knowledge_delete.go b/internal/application/service/knowledge_delete.goindex 47283591b..819965c78 100644--- a/internal/application/service/knowledge_delete.go+++ b/internal/application/service/knowledge_delete.go@@ -277,7 +277,7 @@ func (s *knowledgeService) cleanupWikiOnKnowledgeDelete(ctx context.Context, knovar retractSlugs []stringvar affectedFolderIDs []stringfor _, page := range pages {- if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {+ if page.PageType == types.WikiPageTypeIndex {continue}if page.FolderID != "" {@@ -313,7 +313,7 @@ func (s *knowledgeService) cleanupWikiOnKnowledgeDelete(ctx context.Context, kno// (3) Unconditionally enqueue the retract task. See function comment —// an empty PageSlugs is not a bug, it's the signal "re-query at run// time". The handler will ListPagesBySourceRef again, pick up any- // pages that materialised after we looked, and also rebuild index/log+ // pages that materialised after we looked, and also rebuild the index// so the knowledge's disappearance is reflected in the UI.lang, _ := types.LanguageFromContext(ctx)tenantID, _ := types.TenantIDFromContext(ctx)diff --git a/internal/application/service/wiki_ingest.go b/internal/application/service/wiki_ingest.goindex ba9c992b6..f8a7ac34c 100644--- a/internal/application/service/wiki_ingest.go+++ b/internal/application/service/wiki_ingest.go@@ -327,7 +327,7 @@ type wikiIngestService struct {chunkRepo interfaces.ChunkRepositorymodelService interfaces.ModelServicetask interfaces.TaskEnqueuer- logEntrySvc interfaces.WikiLogEntryService+ audit interfaces.AuditLogServicependingRepo interfaces.TaskPendingOpsRepositorydeadLetterRepo interfaces.TaskDeadLetterRepositoryredisClient *redis.Client // nil in Lite mode (no Redis)@@ -367,7 +367,7 @@ func NewWikiIngestService(chunkRepo interfaces.ChunkRepository,modelService interfaces.ModelService,task interfaces.TaskEnqueuer,- logEntrySvc interfaces.WikiLogEntryService,+ audit interfaces.AuditLogService,pendingRepo interfaces.TaskPendingOpsRepository,deadLetterRepo interfaces.TaskDeadLetterRepository,redisClient *redis.Client,@@ -381,7 +381,7 @@ func NewWikiIngestService(chunkRepo: chunkRepo,modelService: modelService,task: task,- logEntrySvc: logEntrySvc,+ audit: audit,pendingRepo: pendingRepo,deadLetterRepo: deadLetterRepo,redisClient: redisClient,@@ -1170,14 +1170,18 @@ func (s *wikiIngestService) requeueFailedOps(ctx context.Context, payload WikiIn}// docIngestResult captures per-document info for batch post-processing.+type wikiIngestPageRef struct {+ Slug string+ Title string+}+type docIngestResult struct {KnowledgeID stringDocTitle stringSummary string // one-line summary of the document (from summary page)// Pages records the wiki pages this document touched, carrying both- // the slug (for navigation / retract lookups) and the human-readable- // title captured at ingest time (for the log feed's display layer).- Pages []types.WikiLogPageRef+ // the slug used for link/retract bookkeeping and its human-readable title.+ Pages []wikiIngestPageRef// MapStats are the per-doc map-phase metrics captured at the moment// mapOneDocument finishes. Surfaced into the postprocess.wiki span's// output so the trace viewer can show "what the map phase produced"@@ -1626,7 +1630,7 @@ func (s *wikiIngestService) cleanDeadLinks(ctx context.Context, kbID string, affif page.Status == types.WikiPageStatusArchived {continue}- if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {+ if page.PageType == types.WikiPageTypeIndex {continue}if len(page.OutLinks) == 0 {@@ -1721,7 +1725,7 @@ func (s *wikiIngestService) injectCrossLinks(if err != nil || page == nil {continue}- if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {+ if page.PageType == types.WikiPageTypeIndex {continue}@@ -1771,7 +1775,7 @@ func (s *wikiIngestService) injectCrossLinks(func collectLinkRefs(pages []*types.WikiPage) []linkRef {refs := make([]linkRef, 0, len(pages)*2)for _, p := range pages {- if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {+ if p.PageType == types.WikiPageTypeIndex {continue}if p.Title != "" {@@ -1909,7 +1913,7 @@ func (s *wikiIngestService) getExistingPageSlugsForKnowledge(ctx context.Contextfor _, slug := range slugs {// Defense-in-depth: skip wiki-intrinsic slugs that never have// real source refs.- if slug == "index" || slug == "log" {+ if slug == "index" {continue}out[slug] = true@@ -2125,34 +2129,6 @@ func splitSummaryLine(raw string) (summary string, content string) {return "", raw}-// buildLogEntry builds a WikiLogEntry struct for the current batch. It is-// pure (no DB access) so callers can accumulate entries cheaply under their-// lock and flush them in a single AppendBatch call at the end of the batch.-//-// Historically this was a per-event `GetLog + UpdatePage` round trip, which-// rewrote the entire log page's TEXT column on every ingest/retract op —-// O(n^2) write amplification as the log grew. The batch writer now uses-// wikiLogEntryService.AppendBatch instead; see ProcessWikiIngest.-func (s *wikiIngestService) buildLogEntry(tenantID uint64, kbID, action, knowledgeID, docTitle, summary string, pagesAffected []types.WikiLogPageRef) *types.WikiLogEntry {- // Copy pagesAffected so the entry does not alias caller-owned slices.- // The batch accumulates SlugUpdate results that may be reused downstream.- var pages types.WikiLogPageRefs- if len(pagesAffected) > 0 {- pages = make(types.WikiLogPageRefs, len(pagesAffected))- copy(pages, pagesAffected)- }- return &types.WikiLogEntry{- TenantID: tenantID,- KnowledgeBaseID: kbID,- Action: action,- KnowledgeID: knowledgeID,- DocTitle: docTitle,- Summary: summary,- PagesAffected: pages,- CreatedAt: time.Now(),- }-}-// publishDraftPages transitions draft pages to published status after ingest completes.// This ensures users don't see half-built pages during the ingest process.func (s *wikiIngestService) publishDraftPages(ctx context.Context, kbID string, slugs []string) {diff --git a/internal/application/service/wiki_ingest_batch.go b/internal/application/service/wiki_ingest_batch.goindex e1f9bd6d8..f04900096 100644--- a/internal/application/service/wiki_ingest_batch.go+++ b/internal/application/service/wiki_ingest_batch.go@@ -101,13 +101,10 @@ func (s *wikiIngestService) newWikiBatchContext(fetchMu.Lock()for _, slug := range need {if p, ok := pages[slug]; ok && p != nil {- if p.Status == types.WikiPageStatusArchived ||- p.PageType == types.WikiPageTypeIndex ||- p.PageType == types.WikiPageTypeLog {+ if p.Status == types.WikiPageStatusArchived || p.PageType == types.WikiPageTypeIndex {// Treat archived / system pages as missing from the// title-resolution map: cleanDeadLinks shouldn't link- // to them, and the log-feed slug-title fallback- // should degrade to slug-only display.+ // to them or surface them as cross-link candidates.slugTitleCache[slug] = ""continue}@@ -473,10 +470,10 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Taskif p == nil || p.Slug == "" {continue}- // Index/log pages never carry real source_refs;+ // Index pages never carry real source_refs;// if they somehow surface here, skip — the// reduce stage would be a no-op anyway.- if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {+ if p.PageType == types.WikiPageTypeIndex {continue}slugSet[p.Slug] = struct{}{}@@ -583,10 +580,9 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Taskvar retractPagesAffected []string// failedAdditionSlugs collects entity/concept slugs whose page// generation LLM call failed (so the page was never written). The- // post-reduce cleanup step uses this set to (a) strip dead [[slug]]- // references from the same batch's summary pages, and (b) prune the- // slugs out of the wiki log feed so users don't see clickable entries- // pointing at missing pages.+ // post-reduce cleanup step uses this set to strip dead [[slug]]+ // references from the same batch's summary pages and exclude failed+ // pages from finalize processing.failedAdditionSlugs := make(map[string]struct{})// unappliedSlugKIDs collects the knowledge_ids that contributed to a// slug whose update never landed — either because we could NOT acquire@@ -690,7 +686,7 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Taskdefer tailCancel()// Sanitize the doc summary pages produced by this batch BEFORE we- // build log entries / rebuild the index. The summary LLM (run during+ // rebuild the index. The summary LLM (run during// map) was free to inject [[entity/foo|name]] links to every slug it// saw extracted, but reduce may have failed to materialize some of// those slugs into actual pages. Rewrite those dead links to plain@@ -701,57 +697,21 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.TasktotalPagesAffected = len(allPagesAffected)- // Collect log entries for this batch and flush them in a single INSERT.- // Historically each op triggered its own `GetLog + UpdatePage` round- // trip, which rewrote the entire log page TEXT column and caused O(n^2)- // write amplification as the log grew. AppendBatch writes one row per- // event into wiki_log_entries instead.- //- // slugsToRefs resolves each retract slug against the batch-start- // snapshot (batchCtx.SlugTitleMap) so the log feed carries titles for- // pages that existed when the batch began. Pages created or renamed- // during this batch fall through the map lookup and log as slug-only- // refs, which the frontend renders as the slug itself — a sensible- // fallback given retracts only touch pre-existing pages.- slugsToRefs := func(slugs []string) []types.WikiLogPageRef {- if len(slugs) == 0 {- return nil- }- titles := batchCtx.SlugTitleMany(tailCtx, slugs)- out := make([]types.WikiLogPageRef, 0, len(slugs))- for _, slug := range slugs {- out = append(out, types.WikiLogPageRef{Slug: slug, Title: titles[slug]})- }- return out- }- logEntries := make([]*types.WikiLogEntry, 0, len(pendingOps)+len(docResults))+ // Project one bounded summary into the knowledge-base activity feed.+ // Detailed per-document Wiki log rows duplicated that feed and were never+ // consumed by retrieval, so the activity record is now written directly.+ wikiActivityActions := make(map[string]int, 2)for _, op := range pendingOps {if op.Op == WikiOpRetract {- logEntries = append(logEntries, s.buildLogEntry(payload.TenantID, payload.KnowledgeBaseID, "retract", op.KnowledgeID, op.DocTitle, op.DocSummary, slugsToRefs(op.PageSlugs)))+ wikiActivityActions["retract"]++}}for _, r := range docResults {- // Drop any slugs whose page generation failed in reduce so the- // log feed never offers a clickable entry that 404s. The summary- // page itself (slug = summary/<knowledgeID>) is always created- // unconditionally upstream, so it survives the filter.- pages := r.Pages- if len(failedAdditionSlugs) > 0 {- pages = pages[:0:0]- for _, ref := range r.Pages {- if _, bad := failedAdditionSlugs[ref.Slug]; bad {- continue- }- pages = append(pages, ref)- }- }- logEntries = append(logEntries, s.buildLogEntry(payload.TenantID, payload.KnowledgeBaseID, "ingest", r.KnowledgeID, r.DocTitle, r.Summary, pages))- }- if len(logEntries) > 0 && s.logEntrySvc != nil {- if err := s.logEntrySvc.AppendBatch(tailCtx, logEntries); err != nil {- logger.Warnf(ctx, "wiki ingest: failed to append %d log entries: %v", len(logEntries), err)+ if r != nil {+ wikiActivityActions["ingest"]++}}+ RecordWikiContentActivity(tailCtx, s.audit, payload.TenantID, payload.KnowledgeBaseID, wikiActivityActions)// Publish freshly-generated pages immediately (NOT deferred to finalize):// users should see a document's wiki pages as soon as their content is@@ -1422,16 +1382,15 @@ func (s *wikiIngestService) mapOneDocument(// extractedPages records every wiki page this document materialized// (entities, concepts, plus the summary page appended below). The- // slug is used for link/retract bookkeeping; the title is captured- // for the log feed so the user sees "提供本学位在线验证报告查询…"- // rather than "entity/xue-xin-wang".- extractedPages := make([]types.WikiLogPageRef, 0, len(slugItems)+1)+ // slug is used for link/retract bookkeeping; the title is retained for+ // trace output and finalize processing.+ extractedPages := make([]wikiIngestPageRef, 0, len(slugItems)+1)for slug, item := range slugItems {title := item.Nameif title == "" {title = slug}- extractedPages = append(extractedPages, types.WikiLogPageRef{Slug: slug, Title: title})+ extractedPages = append(extractedPages, wikiIngestPageRef{Slug: slug, Title: title})}// Count total distinct chunks cited across all slugs for logging.@@ -1489,7 +1448,7 @@ func (s *wikiIngestService) mapOneDocument(SummaryLine: sumLine,SummaryBody: sumBody,})- extractedPages = append(extractedPages, types.WikiLogPageRef{Slug: summarySlug, Title: docTitle})+ extractedPages = append(extractedPages, wikiIngestPageRef{Slug: summarySlug, Title: docTitle})// Entitiesfor _, item := range extractedEntities {@@ -2096,9 +2055,8 @@ func (s *wikiIngestService) reduceSlugUpdates(} else if err != nil {logger.Warnf(ctx, "wiki ingest: update/retract failed for slug %s: %v", slug, err)// Flag addition failures so the batch can sanitize stale- // [[slug]] references in the doc's summary page and prune- // the slug from log entries — otherwise the wiki feed shows- // a clickable entry whose target page doesn't exist.+ // [[slug]] references in the doc's summary page and keep the+ // missing page out of finalize processing.// Retract-only failures don't poison anything (they leave// the existing page unchanged), so don't flag those.if len(additions) > 0 {diff --git a/internal/application/service/wiki_ingest_dedup_test.go b/internal/application/service/wiki_ingest_dedup_test.goindex 42db5eff8..6261044d4 100644--- a/internal/application/service/wiki_ingest_dedup_test.go+++ b/internal/application/service/wiki_ingest_dedup_test.go@@ -179,7 +179,7 @@ func TestSelectDedupCandidatePages_SmallCorpusBypass(t *testing.T) {}}-// Non-entity/concept pages (summaries, logs, …) must be stripped regardless+// Non-entity/concept pages (summaries, comparisons, …) must be stripped regardless// of corpus size — they are never valid merge targets.func TestSelectDedupCandidatePages_DropsNonEntityConcept(t *testing.T) {newItems := []extractedItem{@@ -187,7 +187,7 @@ func TestSelectDedupCandidatePages_DropsNonEntityConcept(t *testing.T) {}pages := []*types.WikiPage{makePage("summary/some-doc", "Some Doc Summary", types.WikiPageTypeSummary),- makePage("log/batch-123", "Batch 123", types.WikiPageTypeLog),+ makePage("comparison/foo-vs-bar", "Foo vs Bar", types.WikiPageTypeComparison),makePage("concept/foo-related", "Foo Related", types.WikiPageTypeConcept),}got := selectDedupCandidatePages(newItems, pages)diff --git a/internal/application/service/wiki_lint.go b/internal/application/service/wiki_lint.goindex 61628524b..798ecf538 100644--- a/internal/application/service/wiki_lint.go+++ b/internal/application/service/wiki_lint.go@@ -150,7 +150,7 @@ func (s *WikiLintService) RunLint(ctx context.Context, kbID string) (*WikiLintRe}// Check 1: Orphan pages (no inbound links, excluding system pages).- if page.PageType != types.WikiPageTypeIndex && page.PageType != types.WikiPageTypeLog {+ if page.PageType != types.WikiPageTypeIndex {if len(page.InLinks) == 0 {issues = append(issues, WikiLintIssue{Type: LintIssueOrphanPage,@@ -193,9 +193,7 @@ func (s *WikiLintService) RunLint(ctx context.Context, kbID string) (*WikiLintRe// soft-deleted knowledge. Cached knowledgeLive lookup keeps// per-kid checks O(1) after the first batch encounters// each id.- if s.knowledgeService != nil &&- page.PageType != types.WikiPageTypeIndex &&- page.PageType != types.WikiPageTypeLog {+ if s.knowledgeService != nil && page.PageType != types.WikiPageTypeIndex {for _, ref := range page.SourceRefs {kid := refif i := strings.Index(ref, "|"); i > 0 {@@ -383,8 +381,8 @@ func (s *WikiLintService) AutoFix(ctx context.Context, kbID string) (int, error)if err != nil {continue}- // Don't archive index or log pages- if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {+ // Don't archive the index page.+ if page.PageType == types.WikiPageTypeIndex {continue}page.Status = types.WikiPageStatusArchived@@ -405,7 +403,7 @@ func (s *WikiLintService) AutoFix(ctx context.Context, kbID string) (int, error)if err != nil || page == nil {continue}- if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {+ if page.PageType == types.WikiPageTypeIndex {continue}remaining := removeSourceRef(page.SourceRefs, issue.TargetSlug)diff --git a/internal/application/service/wiki_log_entry.go b/internal/application/service/wiki_log_entry.godeleted file mode 100644index 2ee9e6b88..000000000--- a/internal/application/service/wiki_log_entry.go+++ /dev/null@@ -1,79 +0,0 @@-package service--import (- "context"-- "github.com/Tencent/WeKnora/internal/types"- "github.com/Tencent/WeKnora/internal/types/interfaces"-)--// wikiLogEntryService persists the detailed Wiki feed and projects a bounded-// summary into the generic per-KB activity timeline.-type wikiLogEntryService struct {- repo interfaces.WikiLogEntryRepository- audit interfaces.AuditLogService-}--// NewWikiLogEntryService constructs a WikiLogEntryService backed by the-// given repository.-func NewWikiLogEntryService(- repo interfaces.WikiLogEntryRepository,- audit interfaces.AuditLogService,-) interfaces.WikiLogEntryService {- return &wikiLogEntryService{repo: repo, audit: audit}-}--// AppendBatch records the given events in one database round trip. Empty-// batches are a no-op (the repo handles that).-func (s *wikiLogEntryService) AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error {- if err := s.repo.AppendBatch(ctx, entries); err != nil {- return err- }- type summary struct {- tenantID uint64- count int- actions map[string]int- }- byKB := make(map[string]*summary)- for _, entry := range entries {- if entry == nil || entry.KnowledgeBaseID == "" {- continue- }- item := byKB[entry.KnowledgeBaseID]- if item == nil {- item = &summary{tenantID: entry.TenantID, actions: make(map[string]int)}- byKB[entry.KnowledgeBaseID] = item- }- item.count++- item.actions[entry.Action]++- }- for kbID, item := range byKB {- recordKBActivity(ctx, s.audit, item.tenantID, kbID, types.AuditActionWikiContentChanged,- "wiki", kbID, types.AuditOutcomeSuccess,- map[string]any{"count": item.count, "actions": item.actions})- }- return nil-}--// List paginates the per-KB event feed. See repo.List for cursor semantics.-func (s *wikiLogEntryService) List(ctx context.Context, kbID string, cursor string, limit int) (*types.WikiLogEntryListResponse, error) {- entries, nextCursor, err := s.repo.List(ctx, kbID, cursor, limit)- if err != nil {- return nil, err- }- if entries == nil {- // Normalise to an empty slice so clients don't need to- // distinguish `null` from `[]`.- entries = []*types.WikiLogEntry{}- }- return &types.WikiLogEntryListResponse{- Entries: entries,- NextCursor: nextCursor,- }, nil-}--// DeleteByKB removes the log feed for a KB. Called when the KB itself is-// being deleted, so no further reads happen.-func (s *wikiLogEntryService) DeleteByKB(ctx context.Context, kbID string) error {- return s.repo.DeleteByKB(ctx, kbID)-}diff --git a/internal/application/service/wiki_page.go b/internal/application/service/wiki_page.goindex 207ff491f..f523c312f 100644--- a/internal/application/service/wiki_page.go+++ b/internal/application/service/wiki_page.go@@ -437,7 +437,7 @@ func (s *wikiPageService) GetIndex(ctx context.Context, kbID string) (*types.Wik}// wikiIndexContentPageTypes enumerates the page types that make up a wiki's-// user-visible directory. System pages (index/log) are excluded; any+// user-visible directory. The index page is excluded; any// LLM-created type we do not recognize surfaces under a generic "other"// bucket.var wikiIndexContentPageTypes = []string{@@ -544,26 +544,6 @@ func (s *wikiPageService) GetIndexView(}, nil}-// GetLog returns the wiki_pages row for slug='log' if it exists.-//-// Log events are now stored in the dedicated `wiki_log_entries` table and-// paginated via wikiLogEntryService — the per-KB log is no longer a single-// TEXT column on a wiki_pages row (that model caused O(n^2) write-// amplification as logs grew). This method is retained for callers that-// still probe the legacy row (wiki_lint, knowledge delete, etc.), but it-// no longer auto-creates the placeholder page on miss; a missing row is a-// normal state and the helper returns `nil, nil`.-func (s *wikiPageService) GetLog(ctx context.Context, kbID string) (*types.WikiPage, error) {- page, err := s.repo.GetBySlug(ctx, kbID, "log")- if err != nil {- if errors.Is(err, repository.ErrWikiPageNotFound) {- return nil, nil- }- return nil, err- }- return page, nil-}-// GetGraph returns a slice of the wiki link graph for visualization.//// Two modes are supported:@@ -1242,7 +1222,7 @@ func (s *wikiPageService) deleteChunkForPage(ctx context.Context, page *types.Wi}}-// createDefaultPage creates a default system page (index, log)+// createDefaultPage creates the default index page.func (s *wikiPageService) createDefaultPage(ctx context.Context, kbID string, slug string, title string, pageType string, content string) (*types.WikiPage, error) {// Get KB to get tenant IDkb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)@@ -1857,7 +1837,7 @@ func (s *wikiPageService) InjectCrossLinks(ctx context.Context, kbID string, affif !affectedSet[p.Slug] {continue}- if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {+ if p.PageType == types.WikiPageTypeIndex {continue}diff --git a/internal/container/container.go b/internal/container/container.goindex 980437e56..c1c258508 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -170,7 +170,6 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(repository.NewDataSourceRepository))must(container.Provide(repository.NewSyncLogRepository))must(container.Provide(repository.NewWikiPageRepository))- must(container.Provide(repository.NewWikiLogEntryRepository))must(container.Provide(repository.NewTaskPendingOpsRepository))must(container.Provide(repository.NewTaskDeadLetterRepository))@@ -216,7 +215,6 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(service.NewCustomAgentService))must(container.Provide(service.NewUserResourceFavoriteService))must(container.Provide(service.NewWikiPageService))- must(container.Provide(service.NewWikiLogEntryService))must(container.Provide(service.NewWikiIngestService, dig.Name("wikiIngest")))must(container.Provide(service.NewWikiLintService))must(container.Provide(service.NewEmbedChannelService))diff --git a/internal/handler/audit_log.go b/internal/handler/audit_log.goindex db26cca48..3f8a656b3 100644--- a/internal/handler/audit_log.go+++ b/internal/handler/audit_log.go@@ -26,9 +26,8 @@ func NewAuditLogHandler(auditService interfaces.AuditLogService) *AuditLogHandlereturn &AuditLogHandler{auditService: auditService}}-// auditLogListResponse is the response envelope for ListTenantAuditLog.-// Mirrors wiki_log_entries' shape: data array + an opaque cursor (here-// the integer id of the last entry, or 0 if no more rows).+// auditLogListResponse is the response envelope for ListTenantAuditLog. The+// cursor is the integer id of the last entry, or 0 if no more rows remain.type auditLogListResponse struct {Success bool `json:"success"`Data []*types.AuditLog `json:"data"`diff --git a/internal/handler/wiki_page.go b/internal/handler/wiki_page.goindex cff5f02f0..92d86afc4 100644--- a/internal/handler/wiki_page.go+++ b/internal/handler/wiki_page.go@@ -7,7 +7,6 @@ import ("net/http""strconv""strings"- "time""github.com/Tencent/WeKnora/internal/application/repository""github.com/Tencent/WeKnora/internal/application/service"@@ -21,10 +20,10 @@ import (// WikiPageHandler handles HTTP requests for wiki page operationstype WikiPageHandler struct {- wikiService interfaces.WikiPageService- kbService interfaces.KnowledgeBaseService- lintService *service.WikiLintService- logEntryService interfaces.WikiLogEntryService+ wikiService interfaces.WikiPageService+ kbService interfaces.KnowledgeBaseService+ lintService *service.WikiLintService+ auditService interfaces.AuditLogService}// NewWikiPageHandler creates a new wiki page handler@@ -32,13 +31,13 @@ func NewWikiPageHandler(wikiService interfaces.WikiPageService,kbService interfaces.KnowledgeBaseService,lintService *service.WikiLintService,- logEntryService interfaces.WikiLogEntryService,+ auditService interfaces.AuditLogService,) *WikiPageHandler {return &WikiPageHandler{- wikiService: wikiService,- kbService: kbService,- lintService: lintService,- logEntryService: logEntryService,+ wikiService: wikiService,+ kbService: kbService,+ lintService: lintService,+ auditService: auditService,}}@@ -383,33 +382,21 @@ func (h *WikiPageHandler) CreatePage(c *gin.Context) {return}- h.appendManualLogEntry(ctx, created, "manual_create", "Page created manually")+ h.recordManualWikiActivity(ctx, created, "manual_create")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,+// recordManualWikiActivity projects a manual page mutation directly into the+// knowledge-base activity feed. Activity recording is best-effort and must not+// fail the edit itself.+func (h *WikiPageHandler) recordManualWikiActivity(+ ctx context.Context, page *types.WikiPage, action string,) {- if h.logEntryService == nil || page == nil {+ if 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)- }+ service.RecordWikiContentActivity(ctx, h.auditService, page.TenantID,+ page.KnowledgeBaseID, map[string]int{action: 1})}// GetPage godoc@@ -551,7 +538,7 @@ func (h *WikiPageHandler) UpdatePage(c *gin.Context) {}if updated.Version != existing.Version {- h.appendManualLogEntry(ctx, updated, "manual_edit", "Page edited manually")+ h.recordManualWikiActivity(ctx, updated, "manual_edit")}c.JSON(http.StatusOK, updated)}@@ -685,8 +672,7 @@ func (h *WikiPageHandler) RevertPage(c *gin.Context) {return}- h.appendManualLogEntry(ctx, updated,- "revert", fmt.Sprintf("Page reverted to v%d", req.Version))+ h.recordManualWikiActivity(ctx, updated, "revert")c.JSON(http.StatusOK, updated)}@@ -726,7 +712,7 @@ func (h *WikiPageHandler) DeletePage(c *gin.Context) {return}- h.appendManualLogEntry(ctx, page, "manual_delete", "Page deleted manually")+ h.recordManualWikiActivity(ctx, page, "manual_delete")c.Status(http.StatusNoContent)}@@ -779,43 +765,6 @@ func (h *WikiPageHandler) GetIndex(c *gin.Context) {c.JSON(http.StatusOK, resp)}-// GetLog godoc-// @Summary Get wiki operation log-// @Description Returns a paginated feed of wiki operation events (ingest, retract, ...)-// @Description newest-first. Pagination is cursor-based: pass `next_cursor` from the-// @Description previous response back as `cursor` to fetch the next page.-// @Tags Wiki-// @Produce json-// @Param kb_id path string true "Knowledge base ID"-// @Param cursor query string false "Opaque cursor from the previous page (empty = newest)"-// @Param limit query int false "Page size, 1-200 (default 50)"-// @Success 200 {object} types.WikiLogEntryListResponse-// @Security Bearer-// @Router /knowledgebase/{kb_id}/wiki/log [get]-func (h *WikiPageHandler) GetLog(c *gin.Context) {- kbID, _, err := h.validateWikiKB(c)- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})- return- }-- cursor := c.Query("cursor")- limit := 50- if raw := c.Query("limit"); raw != "" {- if v, convErr := strconv.Atoi(raw); convErr == nil && v > 0 {- limit = v- }- }-- resp, err := h.logEntryService.List(c.Request.Context(), kbID, cursor, limit)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return- }-- c.JSON(http.StatusOK, resp)-}-// Graph query parameter bounds. The defaults cap an `overview` request at// 500 nodes — comfortably renderable in the frontend's hand-rolled SVG// force simulation — while the hard max of 2000 is the upper bound adiff --git a/internal/router/router_wiki_test.go b/internal/router/router_wiki_test.goindex 5fab7d9d2..7f1261f61 100644--- a/internal/router/router_wiki_test.go+++ b/internal/router/router_wiki_test.go@@ -120,7 +120,6 @@ func TestWikiReadRoutesDenyCrossTenantKB(t *testing.T) {"/api/v1/knowledgebase/kb-victim/wiki/pages/secret-page","/api/v1/knowledgebase/kb-victim/wiki/folders","/api/v1/knowledgebase/kb-victim/wiki/index",- "/api/v1/knowledgebase/kb-victim/wiki/log","/api/v1/knowledgebase/kb-victim/wiki/graph","/api/v1/knowledgebase/kb-victim/wiki/stats","/api/v1/knowledgebase/kb-victim/wiki/search?q=test",@@ -139,6 +138,14 @@ func TestWikiReadRoutesDenyCrossTenantKB(t *testing.T) {}}+func TestWikiOperationLogRouteIsRemoved(t *testing.T) {+ engine := newWikiRouteTestEngine(t, 1, tenantKBLookupFixture())+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/v1/knowledgebase/kb-allowed/wiki/log", nil)+ engine.ServeHTTP(rec, req)+ require.Equal(t, http.StatusNotFound, rec.Code, "body=%s", rec.Body.String())+}+func TestInitializationWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {kbLookup := tenantKBLookupFixture()scope := &types.TenantAPIKeyScope{diff --git a/internal/router/routes_knowledge.go b/internal/router/routes_knowledge.goindex 523424d77..110f47cd1 100644--- a/internal/router/routes_knowledge.go+++ b/internal/router/routes_knowledge.go@@ -308,7 +308,6 @@ func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHan// Special pageswikiRead.GET("/index", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetIndex)- wikiRead.GET("/log", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetLog)// Graph and statswikiRead.GET("/graph", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetGraph)diff --git a/internal/types/interfaces/wiki_log_entry.go b/internal/types/interfaces/wiki_log_entry.godeleted file mode 100644index 61f10f361..000000000--- a/internal/types/interfaces/wiki_log_entry.go+++ /dev/null@@ -1,41 +0,0 @@-package interfaces--import (- "context"-- "github.com/Tencent/WeKnora/internal/types"-)--// WikiLogEntryRepository persists per-KB wiki operation events. The table-// is append-only; updates are never issued. Reads paginate newest-first-// with a stable numeric cursor.-type WikiLogEntryRepository interface {- // AppendBatch inserts a batch of events in a single INSERT...VALUES- // statement. All entries in a batch must belong to the same KB in- // practice, but the repo does not enforce that — the caller owns the- // grouping.- AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error-- // List returns up to `limit` entries in (knowledge_base_id, id DESC)- // order. `cursor` is the ID of the last entry from the previous page- // ("return entries strictly older than this"); empty string means- // "from the newest".- //- // The returned nextCursor is empty when no further rows remain; the- // caller can treat that as end-of-stream.- List(ctx context.Context, kbID string, cursor string, limit int) (entries []*types.WikiLogEntry, nextCursor string, err error)-- // DeleteByKB removes every log entry belonging to the given KB. Used- // when a wiki KB is deleted so the log table does not accumulate- // orphans. Safe to call even if no rows exist.- DeleteByKB(ctx context.Context, kbID string) error-}--// WikiLogEntryService is the service layer over WikiLogEntryRepository.-// Kept intentionally thin — it mirrors the repo today because the events-// are pure bookkeeping and carry no business rules.-type WikiLogEntryService interface {- AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error- List(ctx context.Context, kbID string, cursor string, limit int) (*types.WikiLogEntryListResponse, error)- DeleteByKB(ctx context.Context, kbID string) error-}diff --git a/internal/types/interfaces/wiki_page.go b/internal/types/interfaces/wiki_page.goindex e440749c0..9d2c9662c 100644--- a/internal/types/interfaces/wiki_page.go+++ b/internal/types/interfaces/wiki_page.go@@ -76,16 +76,6 @@ type WikiPageService interface {// the consumer.GetIndexView(ctx context.Context, kbID string, pageTypes []string, limit int, cursor string) (*types.WikiIndexResponse, error)- // GetLog returns the log page for a knowledge base.- //- // Wiki operation events now live in the dedicated wiki_log_entries- // table, so this method no longer auto-creates a placeholder row on- // miss and may legitimately return (nil, nil) for KBs that never had- // the legacy row written. Retained for back-compat with callers that- // still probe the row (lint, knowledge delete); new code should use- // WikiLogEntryService.List for the event feed instead.- GetLog(ctx context.Context, kbID string) (*types.WikiPage, error)-// GetGraph returns the link graph data for visualization. The caller// supplies a WikiGraphRequest describing the desired slice of the graph// (overview top-N or ego neighborhood around a center slug). Callers@@ -370,7 +360,7 @@ type WikiPageRepository interface {// ListRecentForSuggestions returns recent user-visible wiki pages under the given// knowledge bases, used to produce fallback suggested questions for Wiki-only KBs// that do not have AI-generated document questions or recommended FAQ entries.- // Excludes index/log pages and archived pages. Returns up to `limit` rows sorted+ // Excludes the index page and archived pages. Returns up to `limit` rows sorted// by updated_at descending.ListRecentForSuggestions(ctx context.Context, tenantID uint64, kbIDs []string, limit int) ([]*types.WikiPage, error)diff --git a/internal/types/wiki_log_entry.go b/internal/types/wiki_log_entry.godeleted file mode 100644index 9376fe712..000000000--- a/internal/types/wiki_log_entry.go+++ /dev/null@@ -1,117 +0,0 @@-package types--import (- "database/sql/driver"- "encoding/json"- "fmt"- "time"-)--// WikiLogPageRef identifies a wiki page that was affected by a log event,-// paired with the human-readable title at the time of the event. Title is-// captured at write time so the log feed stays readable even if the page-// is later renamed or deleted — the previously-stored title is the one-// the user remembers seeing in the event stream.-type WikiLogPageRef struct {- Slug string `json:"slug"`- Title string `json:"title,omitempty"`-}--// WikiLogPageRefs is a JSON-marshalled list of page references. The-// column is TEXT/JSONB depending on driver; the Value/Scan pair keeps-// GORM happy on both Postgres and the SQLite tests.-type WikiLogPageRefs []WikiLogPageRef--// Value implements the driver.Valuer interface.-func (r WikiLogPageRefs) Value() (driver.Value, error) {- if r == nil {- return []byte("[]"), nil- }- return json.Marshal(r)-}--// Scan implements the sql.Scanner interface. Also tolerates the legacy-// []string shape so we can roll forward without a data migration — any-// rows the ingest pipeline wrote before this commit surface as refs-// with a slug and an empty title, which the frontend renders identically.-func (r *WikiLogPageRefs) Scan(value interface{}) error {- if value == nil {- *r = nil- return nil- }- var raw []byte- switch v := value.(type) {- case []byte:- raw = v- case string:- raw = []byte(v)- default:- return fmt.Errorf("unsupported type for WikiLogPageRefs: %T", value)- }-- // Try the new [{slug,title}] shape first.- var refs []WikiLogPageRef- if err := json.Unmarshal(raw, &refs); err == nil {- *r = refs- return nil- }- // Fall back to the legacy []string shape.- var slugs []string- if err := json.Unmarshal(raw, &slugs); err != nil {- return err- }- out := make([]WikiLogPageRef, 0, len(slugs))- for _, s := range slugs {- out = append(out, WikiLogPageRef{Slug: s})- }- *r = out- return nil-}--// WikiLogEntry is a single ingest/retract/edit event appended to the-// per-KB operation log. It replaces the legacy "single giant TEXT column-// on slug='log' wiki_pages row" model, which rewrote the whole column on-// every event and caused O(n^2) write amplification as the KB grew.-//-// Each event is one INSERT; reads paginate by (knowledge_base_id, id DESC).-type WikiLogEntry struct {- // Auto-increment identifier. Monotonic within a single database, so- // frontend pagination uses it as a stable cursor without needing to- // disambiguate identical created_at values.- ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`- // Workspace scope, mirrored from the enclosing knowledge base.- TenantID uint64 `json:"tenant_id" gorm:"index"`- // Knowledge base this event belongs to.- KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`- // Short operation tag: "ingest", "retract", etc. Matches the `action`- // argument historically passed to appendLogEntry.- Action string `json:"action" gorm:"type:varchar(32)"`- // Knowledge ID the event was about (may be empty for KB-level events).- KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`- // Document title at the time of the event. Stored verbatim rather than- // joined at read time so deleted knowledge still has a human-readable- // label in the log.- DocTitle string `json:"doc_title" gorm:"type:text"`- // One-line summary of the change, as it was when the event was logged.- Summary string `json:"summary" gorm:"type:text"`- // Wiki pages affected by this event. Each ref carries both slug (for- // navigation) and title (for display) so the log renders human-- // readable text without a post-hoc slug→title lookup that might fail- // for now-deleted pages.- PagesAffected WikiLogPageRefs `json:"pages_affected" gorm:"type:jsonb;default:'[]'"`- // Server-side timestamp (UTC).- CreatedAt time.Time `json:"created_at"`-}--// TableName specifies the database table name.-func (WikiLogEntry) TableName() string {- return "wiki_log_entries"-}--// WikiLogEntryListResponse is the paginated response for GET /wiki/log.-// NextCursor is the stringified ID of the oldest entry in `Entries`; pass-// it back as `cursor` to fetch the next page. Empty string means "no more".-type WikiLogEntryListResponse struct {- Entries []*WikiLogEntry `json:"entries"`- NextCursor string `json:"next_cursor,omitempty"`-}diff --git a/internal/types/wiki_page.go b/internal/types/wiki_page.goindex 3327de7fa..e9035e239 100644--- a/internal/types/wiki_page.go+++ b/internal/types/wiki_page.go@@ -118,8 +118,6 @@ const (WikiPageTypeConcept = "concept"// WikiPageTypeIndex represents the wiki index page (index.md)WikiPageTypeIndex = "index"- // WikiPageTypeLog represents the operation log page (log.md)- WikiPageTypeLog = "log"// WikiPageTypeSynthesis represents a synthesis/analysis page.// NOT auto-created by ingest — Agent creates these via wiki_write_page tool// when it generates cross-document analysis, trends, or insights during conversations.@@ -146,7 +144,7 @@ const (func IsValidWikiPageType(pageType string) bool {switch pageType {case WikiPageTypeSummary, WikiPageTypeEntity, WikiPageTypeConcept,- WikiPageTypeIndex, WikiPageTypeLog, WikiPageTypeSynthesis, WikiPageTypeComparison:+ WikiPageTypeIndex, WikiPageTypeSynthesis, WikiPageTypeComparison:return truedefault:return false@@ -178,7 +176,7 @@ type WikiPage struct {Slug string `json:"slug" gorm:"type:varchar(255);uniqueIndex:idx_kb_slug"`// Human-readable titleTitle string `json:"title" gorm:"type:varchar(512)"`- // Page type: summary, entity, concept, index, log, synthesis, comparison+ // Page type: summary, entity, concept, index, synthesis, comparisonPageType string `json:"page_type" gorm:"type:varchar(32);index"`// Page status: draft, published, archivedStatus string `json:"status" gorm:"type:varchar(32);default:'published'"`@@ -770,8 +768,7 @@ type WikiIndexResponse struct {//// Use cases://-// - SlugTitleFetcher: resolve slug -> title for log entries and-// cross-link injection.+// - SlugTitleFetcher: resolve slug -> title for cross-link injection.// - cleanDeadLinks: read out_links + status without pulling content.// - dedup pre-filter: title + aliases + page_type for the trgm /// surface-similarity comparisons.diff --git a/internal/types/wiki_page_test.go b/internal/types/wiki_page_test.goindex f562857ce..d16df422c 100644--- a/internal/types/wiki_page_test.go+++ b/internal/types/wiki_page_test.go@@ -12,7 +12,6 @@ func TestWikiPageTypes(t *testing.T) {WikiPageTypeEntity,WikiPageTypeConcept,WikiPageTypeIndex,- WikiPageTypeLog,WikiPageTypeSynthesis,WikiPageTypeComparison,}@@ -26,6 +25,9 @@ func TestWikiPageTypes(t *testing.T) {}seen[pt] = true}+ if IsValidWikiPageType("log") {+ t.Error("removed Wiki log page type must not remain valid")+ }}func TestWikiConfigValueScan(t *testing.T) {diff --git a/migrations/sqlite/000000_init.down.sql b/migrations/sqlite/000000_init.down.sqlindex d26077961..2c81c06ec 100644--- a/migrations/sqlite/000000_init.down.sql+++ b/migrations/sqlite/000000_init.down.sql@@ -1,7 +1,6 @@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;diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sqlindex 463afbfb7..df695cec7 100644--- a/migrations/sqlite/000000_init.up.sql+++ b/migrations/sqlite/000000_init.up.sql@@ -1054,24 +1054,6 @@ CREATE INDEX IF NOT EXISTS idx_wiki_page_issues_slugCREATE INDEX IF NOT EXISTS idx_wiki_page_issues_statusON 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,diff --git a/migrations/sqlite/000001_remove_wiki_log.down.sql b/migrations/sqlite/000001_remove_wiki_log.down.sqlnew file mode 100644index 000000000..2a65cf3f9--- /dev/null+++ b/migrations/sqlite/000001_remove_wiki_log.down.sql@@ -0,0 +1,17 @@+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);diff --git a/migrations/sqlite/000001_remove_wiki_log.up.sql b/migrations/sqlite/000001_remove_wiki_log.up.sqlnew file mode 100644index 000000000..07585f843--- /dev/null+++ b/migrations/sqlite/000001_remove_wiki_log.up.sql@@ -0,0 +1,3 @@+DROP TABLE IF EXISTS wiki_log_entries;++DELETE FROM wiki_pages WHERE page_type = 'log';diff --git a/migrations/versioned/000044_audit_log.up.sql b/migrations/versioned/000044_audit_log.up.sqlindex 577ede492..7cccec922 100644--- a/migrations/versioned/000044_audit_log.up.sql+++ b/migrations/versioned/000044_audit_log.up.sql@@ -35,8 +35,7 @@ CREATE TABLE IF NOT EXISTS audit_logs (-- Primary list query: newest-first cursor pagination per tenant. Using id-- (BIGSERIAL, monotonic) as the cursor sidesteps the duplicate-timestamp--- tie-breaking that a created_at cursor would require — same approach as--- wiki_log_entries (migration 000040).+-- tie-breaking that a created_at cursor would require.CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_id_descON audit_logs (tenant_id, id DESC);diff --git a/migrations/versioned/000077_remove_wiki_log.down.sql b/migrations/versioned/000077_remove_wiki_log.down.sqlnew file mode 100644index 000000000..d4efac0ef--- /dev/null+++ b/migrations/versioned/000077_remove_wiki_log.down.sql@@ -0,0 +1,25 @@+-- Migration: 000077_remove_wiki_log (rollback)+-- Description: Restore the former Wiki operation log schema. Previously+-- deleted log rows cannot be reconstructed.++DO $$ BEGIN RAISE NOTICE '[Migration 000077 DOWN] Restoring wiki_log_entries schema'; END $$;++CREATE TABLE IF NOT EXISTS wiki_log_entries (+ id BIGSERIAL PRIMARY KEY,+ tenant_id BIGINT 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 JSONB NOT NULL DEFAULT '[]'::JSONB,+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()+);++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);++DO $$ BEGIN RAISE NOTICE '[Migration 000077 DOWN] wiki_log_entries schema restored'; END $$;diff --git a/migrations/versioned/000077_remove_wiki_log.up.sql b/migrations/versioned/000077_remove_wiki_log.up.sqlnew file mode 100644index 000000000..3c189e109--- /dev/null+++ b/migrations/versioned/000077_remove_wiki_log.up.sql@@ -0,0 +1,15 @@+-- Migration: 000077_remove_wiki_log+-- Description: Remove the duplicate Wiki-only operation feed. Knowledge-base+-- activity is the authoritative mutation history, and Wiki+-- retrieval never reads this table.++DO $$ BEGIN RAISE NOTICE '[Migration 000077] Removing wiki operation log storage'; END $$;++DROP TABLE IF EXISTS wiki_log_entries;++-- Very old installations may still have the pre-000040 log.md row. It is not+-- backed by the activity feed and the model no longer treats it as a special+-- retrieval page, so remove it with the obsolete page type.+DELETE FROM wiki_pages WHERE page_type = 'log';++DO $$ BEGIN RAISE NOTICE '[Migration 000077] Wiki operation log storage removed'; END $$;