Spaces:
Paused

dushyantsingh0 commited on
Commit
736319b
·
1 Parent(s): ff535f7

fix: resolve typescript build errors in internal portal navigation

Browse files
alembic/versions/9f3a6a7bdb00_add_kb_article_version_tracking.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """add kb article version tracking
2
+
3
+ Revision ID: 9f3a6a7bdb00
4
+ Revises: 1ba57c9a2c30
5
+ Create Date: 2026-04-25 02:09:13.458601
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = '9f3a6a7bdb00'
16
+ down_revision: Union[str, None] = '1ba57c9a2c30'
17
+ branch_labels: Union[str, Sequence[str], None] = None
18
+ depends_on: Union[str, Sequence[str], None] = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ # ### commands auto generated by Alembic - please adjust! ###
23
+ op.create_table('kb_article_versions',
24
+ sa.Column('article_id', sa.UUID(), nullable=False),
25
+ sa.Column('version_number', sa.Integer(), nullable=False),
26
+ sa.Column('author_id', sa.UUID(), nullable=False),
27
+ sa.Column('title', sa.String(length=500), nullable=False),
28
+ sa.Column('content', sa.Text(), nullable=False),
29
+ sa.Column('category', sa.String(length=100), nullable=True),
30
+ sa.Column('id', sa.UUID(), nullable=False),
31
+ sa.Column('created_at', sa.DateTime(), nullable=False),
32
+ sa.Column('updated_at', sa.DateTime(), nullable=False),
33
+ sa.ForeignKeyConstraint(['article_id'], ['kb_articles.id'], ondelete='CASCADE'),
34
+ sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
35
+ sa.PrimaryKeyConstraint('id')
36
+ )
37
+ op.create_index(op.f('ix_kb_article_versions_article_id'), 'kb_article_versions', ['article_id'], unique=False)
38
+ op.create_index(op.f('ix_kb_article_versions_id'), 'kb_article_versions', ['id'], unique=False)
39
+ op.add_column('kb_articles', sa.Column('version', sa.Integer(), server_default='1', nullable=False))
40
+ # ### end Alembic commands ###
41
+
42
+
43
+ def downgrade() -> None:
44
+ # ### commands auto generated by Alembic - please adjust! ###
45
+ op.drop_column('kb_articles', 'version')
46
+ op.drop_index(op.f('ix_kb_article_versions_id'), table_name='kb_article_versions')
47
+ op.drop_index(op.f('ix_kb_article_versions_article_id'), table_name='kb_article_versions')
48
+ op.drop_table('kb_article_versions')
49
+ # ### end Alembic commands ###
api/v1/kb.py CHANGED
@@ -14,6 +14,7 @@ from core.logging import get_logger
14
  from models.user import User, UserRole
15
  from models.kb_article import KBArticle
16
  from models.kb_article_chunk import KBArticleChunk
 
17
  from models.project import Project
18
  from core.llm import get_llm, get_text_embeddings
19
  from models.attachment import Attachment
@@ -55,12 +56,25 @@ async def create_kb_article(
55
  category=payload.category,
56
  project_id=payload.project_id,
57
  workspace_id=current_user.workspace_id,
58
- author_id=current_user.id
 
59
  )
60
  db.add(new_article)
61
  await db.commit()
62
  await db.refresh(new_article)
63
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  # Unified ARQ Indexing Lifecycle (Categorization, Embedding, Chunking, Summary)
65
  from core.tasks import enqueue_task
66
  await enqueue_task(arq_pool, "index_kb_article", new_article.id)
@@ -666,9 +680,28 @@ async def update_kb_article(
666
  for field, value in update_data.items():
667
  setattr(article, field, value)
668
 
669
- db.add(article)
670
- await db.commit()
671
- await db.refresh(article)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672
 
673
  # Proactive Cache Invalidation
674
  from core.cache import invalidate_cache, delete_by_pattern
@@ -735,6 +768,174 @@ async def delete_kb_article(
735
  logger.info(f"KB Article and children inactivated: {article_id} by user {current_user.id}")
736
  return {"status": "deleted"}
737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
738
  @router.post("/bulk-publish/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
739
  async def bulk_publish_articles(
740
  payload: KBBulkSyncRequest,
 
14
  from models.user import User, UserRole
15
  from models.kb_article import KBArticle
16
  from models.kb_article_chunk import KBArticleChunk
17
+ from models.kb_article_version import KBArticleVersion
18
  from models.project import Project
19
  from core.llm import get_llm, get_text_embeddings
20
  from models.attachment import Attachment
 
56
  category=payload.category,
57
  project_id=payload.project_id,
58
  workspace_id=current_user.workspace_id,
59
+ author_id=current_user.id,
60
+ version=1
61
  )
62
  db.add(new_article)
63
  await db.commit()
64
  await db.refresh(new_article)
65
 
66
+ # Store initial version
67
+ v1 = KBArticleVersion(
68
+ article_id=new_article.id,
69
+ version_number=1,
70
+ author_id=current_user.id,
71
+ title=new_article.title,
72
+ content=new_article.content,
73
+ category=new_article.category
74
+ )
75
+ db.add(v1)
76
+ await db.commit()
77
+
78
  # Unified ARQ Indexing Lifecycle (Categorization, Embedding, Chunking, Summary)
79
  from core.tasks import enqueue_task
80
  await enqueue_task(arq_pool, "index_kb_article", new_article.id)
 
680
  for field, value in update_data.items():
681
  setattr(article, field, value)
682
 
683
+ if "content" in update_data or "title" in update_data or "category" in update_data:
684
+ article.version = article.version + 1
685
+
686
+ db.add(article)
687
+ await db.commit()
688
+ await db.refresh(article)
689
+
690
+ # Create version snapshot
691
+ new_version = KBArticleVersion(
692
+ article_id=article.id,
693
+ version_number=article.version,
694
+ author_id=current_user.id,
695
+ title=article.title,
696
+ content=article.content,
697
+ category=article.category
698
+ )
699
+ db.add(new_version)
700
+ await db.commit()
701
+ else:
702
+ db.add(article)
703
+ await db.commit()
704
+ await db.refresh(article)
705
 
706
  # Proactive Cache Invalidation
707
  from core.cache import invalidate_cache, delete_by_pattern
 
768
  logger.info(f"KB Article and children inactivated: {article_id} by user {current_user.id}")
769
  return {"status": "deleted"}
770
 
771
+ @router.get("/{article_id}/versions/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
772
+ async def list_article_versions(
773
+ article_id: UUID,
774
+ current_user: User = Depends(get_current_user),
775
+ db: AsyncSession = Depends(get_db)
776
+ ) -> Any:
777
+ """Agents/Admin only: Get chronological list of previous article versions."""
778
+ from sqlalchemy.orm import selectinload
779
+
780
+ # Ensure article exists and belongs to workspace
781
+ stmt = select(KBArticle).where(
782
+ KBArticle.id == article_id,
783
+ KBArticle.workspace_id == current_user.workspace_id,
784
+ KBArticle.deleted_at.is_(None)
785
+ )
786
+ if not (await db.execute(stmt)).scalar_one_or_none():
787
+ raise HTTPException(status_code=404, detail="Article not found")
788
+
789
+ versions_stmt = (
790
+ select(KBArticleVersion)
791
+ .options(selectinload(KBArticleVersion.author))
792
+ .where(KBArticleVersion.article_id == article_id)
793
+ .order_by(desc(KBArticleVersion.version_number))
794
+ )
795
+ result = await db.execute(versions_stmt)
796
+ versions = result.scalars().all()
797
+
798
+ res = []
799
+ for v in versions:
800
+ author_name = v.author.full_name if v.author else "System"
801
+ res.append({
802
+ "id": str(v.id),
803
+ "version_number": v.version_number,
804
+ "title": v.title,
805
+ "content": v.content,
806
+ "category": v.category,
807
+ "created_at": v.created_at.isoformat(),
808
+ "author_id": str(v.author_id),
809
+ "author_name": author_name
810
+ })
811
+ return res
812
+
813
+ @router.post("/{article_id}/restore/{version_id}/", response_model=KBArticleResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
814
+ async def restore_article_version(
815
+ article_id: UUID,
816
+ version_id: UUID,
817
+ background_tasks: BackgroundTasks,
818
+ current_user: User = Depends(get_current_user),
819
+ db: AsyncSession = Depends(get_db),
820
+ arq_pool: Any = Depends(get_arq_pool)
821
+ ) -> Any:
822
+ """Agents/Admin only: Restore article to a previous version."""
823
+ # Ensure article exists
824
+ stmt = select(KBArticle).where(
825
+ KBArticle.id == article_id,
826
+ KBArticle.workspace_id == current_user.workspace_id,
827
+ KBArticle.deleted_at.is_(None)
828
+ )
829
+ article = (await db.execute(stmt)).scalar_one_or_none()
830
+ if not article:
831
+ raise HTTPException(status_code=404, detail="Article not found")
832
+
833
+ # Get the version snapshot
834
+ v_stmt = select(KBArticleVersion).where(
835
+ KBArticleVersion.id == version_id,
836
+ KBArticleVersion.article_id == article_id
837
+ )
838
+ version = (await db.execute(v_stmt)).scalar_one_or_none()
839
+ if not version:
840
+ raise HTTPException(status_code=404, detail="Version not found")
841
+
842
+ # Overwrite article content and increment version
843
+ article.title = version.title
844
+ article.content = version.content
845
+ article.category = version.category
846
+ article.version = article.version + 1
847
+ db.add(article)
848
+ await db.commit()
849
+ await db.refresh(article)
850
+
851
+ # Store the restored version as a new snapshot for auditability
852
+ restored_v = KBArticleVersion(
853
+ article_id=article.id,
854
+ version_number=article.version,
855
+ author_id=current_user.id,
856
+ title=article.title,
857
+ content=article.content,
858
+ category=article.category
859
+ )
860
+ db.add(restored_v)
861
+ await db.commit()
862
+
863
+ from core.cache import invalidate_cache, delete_by_pattern
864
+ await invalidate_cache(f"kb:article:{article_id}")
865
+ await invalidate_cache(f"kb:list:{current_user.workspace_id}:all")
866
+ await invalidate_cache(f"kb:categories:{current_user.workspace_id}")
867
+ await delete_by_pattern(f"cache:search:kb:{current_user.workspace_id}*")
868
+
869
+ from core.tasks import enqueue_task
870
+ await enqueue_task(arq_pool, "index_kb_article", article.id)
871
+
872
+ logger.info(f"Article {article_id} restored to version {version.version_number}")
873
+ return article
874
+
875
+ from fastapi import UploadFile, File
876
+
877
+ @router.post("/parse-file/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])
878
+ async def parse_kb_file(
879
+ file: UploadFile = File(...),
880
+ current_user: User = Depends(get_current_user)
881
+ ) -> Any:
882
+ """Agents/Admin only: Parse an uploaded file into structured Markdown using LLM."""
883
+ if not file.filename.endswith(('.txt', '.md')):
884
+ raise HTTPException(status_code=400, detail="Only .txt and .md files are supported for AI parsing.")
885
+
886
+ contents = await file.read()
887
+ # 2.5 MB hard limit
888
+ max_size = 2.5 * 1024 * 1024
889
+ if len(contents) > max_size:
890
+ raise HTTPException(status_code=400, detail="File size exceeds the 2.5MB limit.")
891
+
892
+ try:
893
+ text = contents.decode('utf-8')
894
+ except UnicodeDecodeError:
895
+ raise HTTPException(status_code=400, detail="File must be valid UTF-8 text.")
896
+
897
+ from core.llm import get_llm
898
+ from langchain_core.messages import SystemMessage, HumanMessage
899
+
900
+ llm = get_llm(timeout=180) # Grant extra time for extensive markdown generation
901
+ prompt = [
902
+ SystemMessage(content=(
903
+ "You are an expert technical writer. Convert the following unstructured text "
904
+ "into a high-quality Markdown knowledge base article.\n\n"
905
+ "REQUIREMENTS:\n"
906
+ "1. Output ONLY the raw markdown content without any summary or conversational preamble.\n"
907
+ "2. Add a clear # Title at the top.\n"
908
+ "3. Use structured headings (##, ###).\n"
909
+ "4. Add bolding for emphasis, code blocks for technical parameters, and tables for comparative data.\n"
910
+ "5. If describing a process or system architecture, explicitly generate a Mermaid.js diagram (` ```mermaid `)."
911
+ )),
912
+ HumanMessage(content=f"UNSTRUCTURED CONTENT:\n\n{text}")
913
+ ]
914
+
915
+ try:
916
+ resp = await llm.ainvoke(prompt)
917
+ ai_content = resp.content.strip()
918
+
919
+ # Strip potential markdown formatting block if LLM wraps the whole response
920
+ if ai_content.startswith("```markdown") and ai_content.endswith("```"):
921
+ ai_content = ai_content[11:-3].strip()
922
+
923
+ # Try to extract a title (first h1)
924
+ import re
925
+ title_match = re.search(r'^#\s+(.+)$', ai_content, re.MULTILINE)
926
+ title = title_match.group(1).strip() if title_match else "AI Generated Article"
927
+
928
+ return {
929
+ "title": title,
930
+ "content": ai_content,
931
+ "category": "General"
932
+ }
933
+ except Exception as e:
934
+ logger.error(f"AI Parse Failed: {e}")
935
+ raise HTTPException(status_code=500, detail=f"AI transformation failed: {str(e)}")
936
+
937
+
938
+
939
  @router.post("/bulk-publish/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
940
  async def bulk_publish_articles(
941
  payload: KBBulkSyncRequest,
core/tasks.py CHANGED
@@ -585,6 +585,11 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
585
  return True
586
  return False
587
 
 
 
 
 
 
588
  # --- PHASE 1: Sync Markdown Images ---
589
  try:
590
  await sync_markdown_images(db, article.id, article.workspace_id, article.content, entity_type="article", uploader_id=article.author_id)
@@ -613,12 +618,23 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
613
  await db.commit()
614
  await db.refresh(article)
615
  phase2_success = True
 
616
  logger.info(f"PHASE 2 [Embeddings] Complete for {article_id} (Dim: {len(vector)})")
617
  else:
618
  error_msg = f"Dimension mismatch: Got {len(vector) if vector else 0}, expected {settings.AI_EMBEDDING_DIM}"
619
  logger.error(f"PHASE 2 [Embeddings] Failed for {article_id}: {error_msg}")
 
620
  except Exception as e:
621
- logger.error(f"PHASE 2 [Embeddings] Failed for {article_id} (Length: {len(text_to_embed)}): {str(e)}")
 
 
 
 
 
 
 
 
 
622
 
623
  # --- PHASE 3: Chunking & Architecture Enrichment ---
624
  try:
@@ -654,11 +670,18 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
654
  if await _abort_if_deleted(): return
655
  await db.commit()
656
  await db.refresh(article)
 
657
  logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)")
658
  except Exception as e:
659
  logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
 
660
  await db.rollback()
661
  await db.refresh(article)
 
 
 
 
 
662
 
663
  # --- PHASE 4: Auto-Categorization ---
664
  try:
@@ -683,11 +706,16 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
683
  if await _abort_if_deleted(): return
684
  await db.commit()
685
  await db.refresh(article)
 
686
  logger.info(f"PHASE 4 [Category] Complete for {article_id}: {article.category}")
687
  except Exception as e:
688
  logger.error(f"PHASE 4 [Category] Failed for {article_id}: {e}")
 
689
  await db.rollback()
690
  await db.refresh(article)
 
 
 
691
 
692
  # --- PHASE 5: Attachment/Multimodal Indexing ---
693
  try:
@@ -786,24 +814,39 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
786
  if await _abort_if_deleted(): return
787
  await db.commit()
788
  await db.refresh(article)
 
789
  logger.info(f"PHASE 7 [Summarization] Complete for {article_id}")
790
  except Exception as e:
791
  logger.error(f"PHASE 7 [Summarization] Failed for {article_id}: {e}")
 
792
  await db.rollback()
793
  await db.refresh(article)
 
 
794
 
795
  # --- 10. Record Trace ---
796
  try:
 
797
  await record_workflow_step(
798
  db, article_id, article.workspace_id, "LIFECYCLE", "KB_INDEXING_COMPLETE",
799
- output_data={"images": len(attachments) if 'attachments' in locals() else 0, "summary_len": len(article.summary or "")},
 
 
 
 
 
 
800
  current_stage="READY_FOR_SEARCH", duration_ms=(time.perf_counter() - start_time) * 1000
801
  )
802
  await db.commit()
803
  except Exception as e:
804
  logger.warning(f"Final trace recording failed for {article_id}: {e}")
805
 
806
- logger.info(f"SUCCESS: Hardened KB indexing complete for {article_id}")
 
 
 
 
807
 
808
  except Exception as e:
809
  await db.rollback()
 
585
  return True
586
  return False
587
 
588
+ phases_succeeded = []
589
+ phases_failed = []
590
+ is_transient = lambda e: any(err in str(e) for err in ["502", "503", "504", "ConnectionReset", "Timeout", "RemoteDisconnected"])
591
+
592
+
593
  # --- PHASE 1: Sync Markdown Images ---
594
  try:
595
  await sync_markdown_images(db, article.id, article.workspace_id, article.content, entity_type="article", uploader_id=article.author_id)
 
618
  await db.commit()
619
  await db.refresh(article)
620
  phase2_success = True
621
+ phases_succeeded.append("PHASE 2 [Embeddings]")
622
  logger.info(f"PHASE 2 [Embeddings] Complete for {article_id} (Dim: {len(vector)})")
623
  else:
624
  error_msg = f"Dimension mismatch: Got {len(vector) if vector else 0}, expected {settings.AI_EMBEDDING_DIM}"
625
  logger.error(f"PHASE 2 [Embeddings] Failed for {article_id}: {error_msg}")
626
+ phases_failed.append("PHASE 2 [Embeddings]")
627
  except Exception as e:
628
+ logger.error(f"PHASE 2 [Embeddings] Failed for {article_id}: {str(e)}")
629
+ phases_failed.append("PHASE 2 [Embeddings]")
630
+ if is_transient(e):
631
+ raise RuntimeError(f"Transient provider error in Phase 2: {e}")
632
+
633
+ # CIRCUIT BREAK: If Phase 2 (Mandatory) failed, do not proceed with AI heavy tasks
634
+ if not phase2_success:
635
+ logger.warning(f"KB Indexing Mandatory Phase 2 Failed for {article_id}. Aborting further AI phases.")
636
+ raise RuntimeError(f"Mandatory indexing phase (Embeddings) failed for {article_id}. Retrying...")
637
+
638
 
639
  # --- PHASE 3: Chunking & Architecture Enrichment ---
640
  try:
 
670
  if await _abort_if_deleted(): return
671
  await db.commit()
672
  await db.refresh(article)
673
+ phases_succeeded.append("PHASE 3 [Chunking]")
674
  logger.info(f"PHASE 3 [Enrichment] Complete for {article_id} ({len(raw_chunks)} chunks)")
675
  except Exception as e:
676
  logger.error(f"PHASE 3 [Chunking] Failed for {article_id}: {e}")
677
+ phases_failed.append("PHASE 3 [Chunking]")
678
  await db.rollback()
679
  await db.refresh(article)
680
+ if is_transient(e):
681
+ raise RuntimeError(f"Transient provider error in Phase 3: {e}")
682
+ # Chunking is mandatory
683
+ raise RuntimeError(f"Mandatory indexing phase (Chunking) failed for {article_id}. Retrying...")
684
+
685
 
686
  # --- PHASE 4: Auto-Categorization ---
687
  try:
 
706
  if await _abort_if_deleted(): return
707
  await db.commit()
708
  await db.refresh(article)
709
+ phases_succeeded.append("PHASE 4 [Category]")
710
  logger.info(f"PHASE 4 [Category] Complete for {article_id}: {article.category}")
711
  except Exception as e:
712
  logger.error(f"PHASE 4 [Category] Failed for {article_id}: {e}")
713
+ phases_failed.append("PHASE 4 [Category]")
714
  await db.rollback()
715
  await db.refresh(article)
716
+ if is_transient(e):
717
+ raise RuntimeError(f"Transient provider error in Phase 4: {e}")
718
+
719
 
720
  # --- PHASE 5: Attachment/Multimodal Indexing ---
721
  try:
 
814
  if await _abort_if_deleted(): return
815
  await db.commit()
816
  await db.refresh(article)
817
+ phases_succeeded.append("PHASE 7 [Summarization]")
818
  logger.info(f"PHASE 7 [Summarization] Complete for {article_id}")
819
  except Exception as e:
820
  logger.error(f"PHASE 7 [Summarization] Failed for {article_id}: {e}")
821
+ phases_failed.append("PHASE 7 [Summarization]")
822
  await db.rollback()
823
  await db.refresh(article)
824
+ if is_transient(e):
825
+ raise RuntimeError(f"Transient provider error in Phase 7: {e}")
826
 
827
  # --- 10. Record Trace ---
828
  try:
829
+ final_status = "SUCCESS" if not phases_failed else "DEGRADED"
830
  await record_workflow_step(
831
  db, article_id, article.workspace_id, "LIFECYCLE", "KB_INDEXING_COMPLETE",
832
+ output_data={
833
+ "images": len(attachments) if 'attachments' in locals() else 0,
834
+ "summary_len": len(article.summary or ""),
835
+ "phases_succeeded": phases_succeeded,
836
+ "phases_failed": phases_failed,
837
+ "final_status": final_status
838
+ },
839
  current_stage="READY_FOR_SEARCH", duration_ms=(time.perf_counter() - start_time) * 1000
840
  )
841
  await db.commit()
842
  except Exception as e:
843
  logger.warning(f"Final trace recording failed for {article_id}: {e}")
844
 
845
+ if final_status == "SUCCESS":
846
+ logger.info(f"SUCCESS: Hardened KB indexing complete for {article_id}")
847
+ else:
848
+ logger.warning(f"DEGRADED: Hardened KB indexing finished with partial failures for {article_id}. Failed: {phases_failed}")
849
+
850
 
851
  except Exception as e:
852
  await db.rollback()
frontend/apps/internal/src/components/KnowledgeBase.module.css CHANGED
@@ -1280,4 +1280,177 @@
1280
  color: var(--text-muted);
1281
  text-transform: uppercase;
1282
  letter-spacing: 0.1em;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1283
  }
 
1280
  color: var(--text-muted);
1281
  text-transform: uppercase;
1282
  letter-spacing: 0.1em;
1283
+ }
1284
+
1285
+ /* History Drawer Styles */
1286
+ .historyContainer {
1287
+ padding: 32px;
1288
+ background: white;
1289
+ height: 100%;
1290
+ overflow-y: auto;
1291
+ }
1292
+
1293
+ .historyHeader {
1294
+ display: flex;
1295
+ align-items: center;
1296
+ gap: 12px;
1297
+ color: var(--primary);
1298
+ margin-bottom: 8px;
1299
+ }
1300
+
1301
+ .historyHeader h3 {
1302
+ font-size: 20px;
1303
+ font-weight: 800;
1304
+ margin: 0;
1305
+ }
1306
+
1307
+ .historySub {
1308
+ font-size: 13px;
1309
+ color: var(--text-muted);
1310
+ margin-bottom: 32px;
1311
+ }
1312
+
1313
+ .timelineList {
1314
+ display: flex;
1315
+ flex-direction: column;
1316
+ position: relative;
1317
+ border-left: 2px solid var(--border-subtle);
1318
+ margin-left: 14px;
1319
+ padding-left: 30px;
1320
+ gap: 32px;
1321
+ }
1322
+
1323
+ .timelineNode {
1324
+ position: relative;
1325
+ display: flex;
1326
+ flex-direction: column;
1327
+ }
1328
+
1329
+ .nodeDot {
1330
+ position: absolute;
1331
+ left: -38px;
1332
+ top: 0;
1333
+ width: 14px;
1334
+ height: 14px;
1335
+ border-radius: 50%;
1336
+ background: white;
1337
+ border: 2px solid var(--primary);
1338
+ display: flex;
1339
+ align-items: center;
1340
+ justify-content: center;
1341
+ font-size: 8px;
1342
+ color: var(--primary);
1343
+ font-weight: 900;
1344
+ }
1345
+
1346
+ .nodeContent {
1347
+ background: #F8FAFC;
1348
+ border: 1px solid var(--border-subtle);
1349
+ border-radius: 12px;
1350
+ padding: 16px 20px;
1351
+ transition: all 0.2s;
1352
+ }
1353
+
1354
+ .nodeContent:hover {
1355
+ background: white;
1356
+ border-color: var(--primary);
1357
+ box-shadow: 0 4px 12px rgba(0,0,0,0.05);
1358
+ }
1359
+
1360
+ .nodeHeader {
1361
+ display: flex;
1362
+ justify-content: space-between;
1363
+ align-items: center;
1364
+ margin-bottom: 12px;
1365
+ }
1366
+
1367
+ .nodeVersion {
1368
+ font-size: 14px;
1369
+ font-weight: 900;
1370
+ color: var(--text-main);
1371
+ }
1372
+
1373
+ .nodeDate {
1374
+ font-size: 11px;
1375
+ font-weight: 700;
1376
+ color: var(--text-muted);
1377
+ letter-spacing: 0.05em;
1378
+ }
1379
+
1380
+ .nodeMeta {
1381
+ display: flex;
1382
+ flex-direction: column;
1383
+ gap: 4px;
1384
+ font-size: 13px;
1385
+ color: var(--text-main);
1386
+ margin-bottom: 20px;
1387
+ }
1388
+
1389
+ .restoreBtn {
1390
+ background: white;
1391
+ border: 1px solid var(--border-subtle);
1392
+ color: var(--text-main);
1393
+ padding: 8px 16px;
1394
+ border-radius: 6px;
1395
+ font-size: 11px;
1396
+ font-weight: 800;
1397
+ cursor: pointer;
1398
+ display: flex;
1399
+ align-items: center;
1400
+ gap: 6px;
1401
+ transition: all 0.2s;
1402
+ }
1403
+
1404
+ .restoreBtn:hover {
1405
+ background: var(--primary);
1406
+ color: white;
1407
+ border-color: var(--primary);
1408
+ }
1409
+
1410
+ /* File Upload / Dropdown Styles */
1411
+ .newIntelDropdownWrapper {
1412
+ position: relative;
1413
+ z-index: 50;
1414
+ }
1415
+
1416
+ .newIntelDropdown {
1417
+ position: absolute;
1418
+ top: calc(100% + 8px);
1419
+ right: 0;
1420
+ width: 260px;
1421
+ background: white;
1422
+ border-radius: 12px;
1423
+ padding: 8px;
1424
+ box-shadow: 0 10px 40px rgba(0,0,0,0.2);
1425
+ border: 1px solid rgba(0,0,0,0.1);
1426
+ display: flex;
1427
+ flex-direction: column;
1428
+ gap: 4px;
1429
+ }
1430
+
1431
+ .intelOption {
1432
+ background: none;
1433
+ border: none;
1434
+ text-align: left;
1435
+ padding: 12px;
1436
+ border-radius: 8px;
1437
+ cursor: pointer;
1438
+ display: flex;
1439
+ flex-direction: column;
1440
+ gap: 4px;
1441
+ font-size: 14px;
1442
+ font-weight: 800;
1443
+ color: var(--text-main);
1444
+ transition: all 0.2s;
1445
+ }
1446
+
1447
+ .intelOption span {
1448
+ font-size: 11px;
1449
+ font-weight: 500;
1450
+ color: var(--text-muted);
1451
+ }
1452
+
1453
+ .intelOption:hover {
1454
+ background: var(--bg-hover);
1455
+ color: var(--primary);
1456
  }
frontend/apps/internal/src/components/KnowledgeBase.tsx CHANGED
@@ -3,7 +3,7 @@ import ReactMarkdown from 'react-markdown';
3
  import remarkGfm from 'remark-gfm';
4
  import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
5
  import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
6
- import { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles } from 'lucide-react';
7
  import { motion, AnimatePresence } from 'framer-motion';
8
  import { api, useAuth, NexusMermaid } from '@nexus/shared';
9
  import styles from './KnowledgeBase.module.css';
@@ -27,6 +27,7 @@ interface KBArticle {
27
  match_type?: string;
28
  created_at?: string;
29
  summary?: string;
 
30
  }
31
 
32
  interface KnowledgeBaseProps {
@@ -44,6 +45,17 @@ interface KBInsight {
44
  evidence_count: number;
45
  }
46
 
 
 
 
 
 
 
 
 
 
 
 
47
  // Mermaid logic moved to centralized NexusMermaid.tsx component in @nexus/shared
48
 
49
  export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => {
@@ -77,6 +89,16 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
77
  const [editCategory, setEditCategory] = useState('');
78
  const [editPublished, setEditPublished] = useState(true);
79
 
 
 
 
 
 
 
 
 
 
 
80
  // AI Search Enhanced State
81
  const [suggestions, setSuggestions] = useState<string[]>([]);
82
  const [aiSuggestion, setAiSuggestion] = useState<string | null>(null);
@@ -242,12 +264,78 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
242
  const handleCreateNew = () => {
243
  setSelectedArticle(null);
244
  setSelectedInsight(null);
 
245
  setEditTitle('NEW STRATEGIC ASSET');
246
  setEditContent('# Technical Directive\n\nStart your documentation here...\n\n```mermaid\ngraph TD;\n A-->B;\n```');
247
  setEditCategory('General');
248
  setEditPublished(false);
249
  setIsEditing(true);
250
  setDrawerOpen(true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  };
252
 
253
  const [isSaving, setIsSaving] = useState(false);
@@ -387,9 +475,46 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
387
  )}
388
  </div>
389
  {canEdit && (
390
- <button type="button" className={styles.newIntelBtn} onClick={handleCreateNew}>
391
- <Plus size={18} /> NEW INTEL
392
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  )}
394
  </form>
395
 
@@ -681,7 +806,29 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
681
  <div className={styles.metaTop}>
682
  <span className={styles.metaLabel}>{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}</span>
683
  <div className={styles.headerRight}>
684
- {canEdit && (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
  <div className={styles.modeToggle}>
686
  <button
687
  className={`${styles.modeBtn} ${!isEditing ? styles.activeMode : ''}`}
@@ -782,20 +929,65 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
782
  </div>
783
  ) : (
784
  <div className={styles.viewInterface}>
785
- <div className={styles.telemetryBar}>
786
- <div className={styles.telItem}>
787
- <label>{selectedInsight ? 'CONFIDENCE' : 'AUTHOR ID'}</label>
788
- <span>{selectedInsight ? `${Math.round(selectedInsight.confidence_score * 100)}%` : (selectedArticle?.author_id || 'REDACTED')}</span>
789
- </div>
790
- <div className={styles.telItem}>
791
- <label>{selectedInsight ? 'EVIDENCE COUNT' : 'LAST SYNC'}</label>
792
- <span>{selectedInsight ? selectedInsight.evidence_count : (selectedArticle ? new Date(selectedArticle.updated_at).toLocaleString() : 'N/A')}</span>
793
- </div>
794
- <div className={styles.telItem}>
795
- <label>MATCH SCORE</label>
796
- <span>{(selectedInsight ? selectedInsight.confidence_score : selectedArticle?.score) ? `${Math.round((selectedInsight ? selectedInsight.confidence_score : (selectedArticle?.score || 0)) * 100)}%` : 'STATIC'}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797
  </div>
798
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
799
 
800
  <div className={styles.viewScrollArea}>
801
  <AnimatePresence>
@@ -844,13 +1036,15 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
844
  </ReactMarkdown>
845
  </div>
846
  </div>
847
- </div>
848
  )}
849
  </div>
850
- </motion.div>
851
- </>
852
- )}
853
- </AnimatePresence>
 
 
854
  </div>
855
  );
856
  };
 
3
  import remarkGfm from 'remark-gfm';
4
  import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
5
  import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
6
+ import { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles, UploadCloud, History, RotateCcw } from 'lucide-react';
7
  import { motion, AnimatePresence } from 'framer-motion';
8
  import { api, useAuth, NexusMermaid } from '@nexus/shared';
9
  import styles from './KnowledgeBase.module.css';
 
27
  match_type?: string;
28
  created_at?: string;
29
  summary?: string;
30
+ version?: number;
31
  }
32
 
33
  interface KnowledgeBaseProps {
 
45
  evidence_count: number;
46
  }
47
 
48
+ interface KBArticleVersion {
49
+ id: string;
50
+ version_number: number;
51
+ title: string;
52
+ content: string;
53
+ category: string;
54
+ created_at: string;
55
+ author_id: string;
56
+ author_name: string;
57
+ }
58
+
59
  // Mermaid logic moved to centralized NexusMermaid.tsx component in @nexus/shared
60
 
61
  export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => {
 
89
  const [editCategory, setEditCategory] = useState('');
90
  const [editPublished, setEditPublished] = useState(true);
91
 
92
+ // Version History State
93
+ const [showHistory, setShowHistory] = useState(false);
94
+ const [versions, setVersions] = useState<KBArticleVersion[]>([]);
95
+ const [versionsLoading, setVersionsLoading] = useState(false);
96
+
97
+ // File Upload State
98
+ const [isDropdownOpen, setIsDropdownOpen] = useState(false);
99
+ const [isParsingFile, setIsParsingFile] = useState(false);
100
+ const fileInputRef = useRef<HTMLInputElement>(null);
101
+
102
  // AI Search Enhanced State
103
  const [suggestions, setSuggestions] = useState<string[]>([]);
104
  const [aiSuggestion, setAiSuggestion] = useState<string | null>(null);
 
264
  const handleCreateNew = () => {
265
  setSelectedArticle(null);
266
  setSelectedInsight(null);
267
+ setShowHistory(false);
268
  setEditTitle('NEW STRATEGIC ASSET');
269
  setEditContent('# Technical Directive\n\nStart your documentation here...\n\n```mermaid\ngraph TD;\n A-->B;\n```');
270
  setEditCategory('General');
271
  setEditPublished(false);
272
  setIsEditing(true);
273
  setDrawerOpen(true);
274
+ setIsDropdownOpen(false);
275
+ };
276
+
277
+ const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
278
+ const file = event.target.files?.[0];
279
+ if (!file) return;
280
+
281
+ setIsDropdownOpen(false);
282
+ setIsParsingFile(true);
283
+
284
+ const formData = new FormData();
285
+ formData.append('file', file);
286
+
287
+ try {
288
+ const resp = await api.post('kb/parse-file/', formData, {
289
+ headers: { 'Content-Type': 'multipart/form-data' }
290
+ });
291
+
292
+ setSelectedArticle(null);
293
+ setSelectedInsight(null);
294
+ setShowHistory(false);
295
+ setEditTitle(resp.data.title || 'AI Parsed Document');
296
+ setEditContent(resp.data.content || '');
297
+ setEditCategory(resp.data.category || 'General');
298
+ setEditPublished(false);
299
+ setIsEditing(true);
300
+ setDrawerOpen(true);
301
+ } catch (err: any) {
302
+ console.error('File parsing failed:', err);
303
+ // Fallback open empty format on fail
304
+ alert(err.response?.data?.detail || 'Failed to parse file via AI.');
305
+ } finally {
306
+ setIsParsingFile(false);
307
+ if (fileInputRef.current) fileInputRef.current.value = '';
308
+ }
309
+ };
310
+
311
+ const loadVersions = async () => {
312
+ if (!selectedArticle) return;
313
+ setVersionsLoading(true);
314
+ try {
315
+ const resp = await api.get(`kb/${selectedArticle.id}/versions/`);
316
+ setVersions(resp.data || []);
317
+ } catch (err) {
318
+ console.error('Failed to load version history', err);
319
+ } finally {
320
+ setVersionsLoading(false);
321
+ }
322
+ };
323
+
324
+ const handleRestoreVersion = async (versionId: string) => {
325
+ if (!selectedArticle || !window.confirm("Restore this version? This will overwrite the current article with this historical snapshot.")) return;
326
+ try {
327
+ const resp = await api.post(`kb/${selectedArticle.id}/restore/${versionId}/`);
328
+ setArticles(prev => prev.map(a => a.id === selectedArticle.id ? { ...a, ...resp.data } : a));
329
+ setSelectedArticle({ ...selectedArticle, ...resp.data });
330
+ setEditTitle(resp.data.title);
331
+ setEditContent(resp.data.content);
332
+ setEditCategory(resp.data.category);
333
+ // Reload versions to show current newly created snapshot
334
+ await loadVersions();
335
+ } catch (err) {
336
+ console.error('Failed to restore version', err);
337
+ alert('Failed to restore version.');
338
+ }
339
  };
340
 
341
  const [isSaving, setIsSaving] = useState(false);
 
475
  )}
476
  </div>
477
  {canEdit && (
478
+ <div className={styles.newIntelDropdownWrapper}>
479
+ <button
480
+ type="button"
481
+ className={styles.newIntelBtn}
482
+ onClick={() => setIsDropdownOpen(!isDropdownOpen)}
483
+ disabled={isParsingFile}
484
+ >
485
+ {isParsingFile ? (
486
+ <><Radio size={18} className={styles.pulseIcon} /> PARSING</>
487
+ ) : (
488
+ <><Plus size={18} /> NEW INTEL</>
489
+ )}
490
+ </button>
491
+ <AnimatePresence>
492
+ {isDropdownOpen && (
493
+ <motion.div
494
+ className={styles.newIntelDropdown}
495
+ initial={{ opacity: 0, y: 10 }}
496
+ animate={{ opacity: 1, y: 0 }}
497
+ exit={{ opacity: 0, scale: 0.95 }}
498
+ >
499
+ <button type="button" onClick={handleCreateNew} className={styles.intelOption}>
500
+ <Edit3 size={16} /> Write Article
501
+ <span>Start from an empty technical directive</span>
502
+ </button>
503
+ <button type="button" onClick={() => fileInputRef.current?.click()} className={styles.intelOption}>
504
+ <UploadCloud size={16} /> Upload & Parse (AI)
505
+ <span>Convert .txt / .md into structured article</span>
506
+ </button>
507
+ </motion.div>
508
+ )}
509
+ </AnimatePresence>
510
+ <input
511
+ type="file"
512
+ ref={fileInputRef}
513
+ onChange={handleFileUpload}
514
+ accept=".txt,.md"
515
+ style={{ display: 'none' }}
516
+ />
517
+ </div>
518
  )}
519
  </form>
520
 
 
806
  <div className={styles.metaTop}>
807
  <span className={styles.metaLabel}>{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}</span>
808
  <div className={styles.headerRight}>
809
+ {canEdit && !selectedInsight && (
810
+ <div className={styles.modeToggle}>
811
+ <button
812
+ className={`${styles.modeBtn} ${!isEditing && !showHistory ? styles.activeMode : ''}`}
813
+ onClick={() => { setIsEditing(false); setShowHistory(false); }}
814
+ >
815
+ <Eye size={14} /> VIEW
816
+ </button>
817
+ <button
818
+ className={`${styles.modeBtn} ${!isEditing && showHistory ? styles.activeMode : ''}`}
819
+ onClick={() => { setIsEditing(false); setShowHistory(true); loadVersions(); }}
820
+ >
821
+ <History size={14} /> HISTORY
822
+ </button>
823
+ <button
824
+ className={`${styles.modeBtn} ${isEditing ? styles.activeMode : ''}`}
825
+ onClick={() => { setIsEditing(true); setShowHistory(false); }}
826
+ >
827
+ <Edit3 size={14} /> EDIT
828
+ </button>
829
+ </div>
830
+ )}
831
+ {canEdit && selectedInsight && (
832
  <div className={styles.modeToggle}>
833
  <button
834
  className={`${styles.modeBtn} ${!isEditing ? styles.activeMode : ''}`}
 
929
  </div>
930
  ) : (
931
  <div className={styles.viewInterface}>
932
+ {showHistory && !isEditing && selectedArticle ? (
933
+ <div className={styles.historyContainer}>
934
+ <div className={styles.historyHeader}>
935
+ <History size={18} />
936
+ <h3>Article Version Ledger</h3>
937
+ </div>
938
+ <p className={styles.historySub}>Previous iterations automatically snapshotted upon modification.</p>
939
+
940
+ {versionsLoading ? (
941
+ <div className={styles.emptyState}>
942
+ <div className={styles.loadingPulse} />
943
+ </div>
944
+ ) : versions.length === 0 ? (
945
+ <div className={styles.emptyState}>
946
+ <p>No historical versions found.</p>
947
+ </div>
948
+ ) : (
949
+ <div className={styles.timelineList}>
950
+ {versions.map((ver, idx) => (
951
+ <div key={ver.id} className={styles.timelineNode}>
952
+ <div className={styles.nodeLine} />
953
+ <div className={styles.nodeDot}>{versions.length - idx === selectedArticle.version ? '★' : ''}</div>
954
+ <div className={styles.nodeContent}>
955
+ <div className={styles.nodeHeader}>
956
+ <span className={styles.nodeVersion}>v{ver.version_number}</span>
957
+ <span className={styles.nodeDate}>{new Date(ver.created_at).toLocaleString()}</span>
958
+ </div>
959
+ <div className={styles.nodeMeta}>
960
+ <span>Author: {ver.author_name}</span>
961
+ <span>Title: {ver.title}</span>
962
+ </div>
963
+ <button
964
+ className={styles.restoreBtn}
965
+ onClick={() => handleRestoreVersion(ver.id)}
966
+ >
967
+ <RotateCcw size={14} /> RESTORE
968
+ </button>
969
+ </div>
970
+ </div>
971
+ ))}
972
+ </div>
973
+ )}
974
  </div>
975
+ ) : (
976
+ <>
977
+ <div className={styles.telemetryBar}>
978
+ <div className={styles.telItem}>
979
+ <label>{selectedInsight ? 'CONFIDENCE' : 'AUTHOR ID'}</label>
980
+ <span>{selectedInsight ? `${Math.round(selectedInsight.confidence_score * 100)}%` : (selectedArticle?.author_id || 'REDACTED')}</span>
981
+ </div>
982
+ <div className={styles.telItem}>
983
+ <label>{selectedInsight ? 'EVIDENCE COUNT' : 'LAST SYNC'}</label>
984
+ <span>{selectedInsight ? selectedInsight.evidence_count : (selectedArticle ? new Date(selectedArticle.updated_at).toLocaleString() : 'N/A')}</span>
985
+ </div>
986
+ <div className={styles.telItem}>
987
+ <label>MATCH SCORE</label>
988
+ <span>{(selectedInsight ? selectedInsight.confidence_score : selectedArticle?.score) ? `${Math.round((selectedInsight ? selectedInsight.confidence_score : (selectedArticle?.score || 0)) * 100)}%` : 'STATIC'}</span>
989
+ </div>
990
+ </div>
991
 
992
  <div className={styles.viewScrollArea}>
993
  <AnimatePresence>
 
1036
  </ReactMarkdown>
1037
  </div>
1038
  </div>
1039
+ </>
1040
  )}
1041
  </div>
1042
+ )}
1043
+ </div>
1044
+ </motion.div>
1045
+ </>
1046
+ )}
1047
+ </AnimatePresence>
1048
  </div>
1049
  );
1050
  };
models/__init__.py CHANGED
@@ -13,6 +13,7 @@ from models.feedback import Feedback
13
  from models.project import Project
14
  from models.kb_article import KBArticle
15
  from models.kb_article_chunk import KBArticleChunk
 
16
  from models.audit_log import AuditLog
17
  from models.ai_workflow import AIWorkflow
18
  from models.ai_interaction import AIInteraction
@@ -41,6 +42,7 @@ __all__ = [
41
  "Project",
42
  "KBArticle",
43
  "KBArticleChunk",
 
44
  "AuditLog",
45
  "AIWorkflow",
46
  "AIInteraction",
 
13
  from models.project import Project
14
  from models.kb_article import KBArticle
15
  from models.kb_article_chunk import KBArticleChunk
16
+ from models.kb_article_version import KBArticleVersion
17
  from models.audit_log import AuditLog
18
  from models.ai_workflow import AIWorkflow
19
  from models.ai_interaction import AIInteraction
 
42
  "Project",
43
  "KBArticle",
44
  "KBArticleChunk",
45
+ "KBArticleVersion",
46
  "AuditLog",
47
  "AIWorkflow",
48
  "AIInteraction",
models/kb_article.py CHANGED
@@ -30,6 +30,9 @@ class KBArticle(Base, PrimaryKeyMixin, TimestampMixin, SoftDeleteMixin):
30
  # Semantic vector for RAG
31
  embedding = Column(Vector(settings.AI_EMBEDDING_DIM), nullable=True)
32
 
 
 
 
33
  # --- Search Optimization ---
34
  # 1. Computed TSVector for GIN search (Keyword Engine)
35
  search_vector = Column(
@@ -55,6 +58,7 @@ class KBArticle(Base, PrimaryKeyMixin, TimestampMixin, SoftDeleteMixin):
55
  project = relationship("Project", back_populates="kb_articles")
56
  chunks = relationship("KBArticleChunk", back_populates="article", cascade="all, delete-orphan")
57
  attachments = relationship("Attachment", back_populates="article", cascade="all, delete-orphan")
 
58
 
59
  # Self-referential for duplicates
60
  duplicate_of = relationship("KBArticle", remote_side="KBArticle.id", backref="duplicates")
 
30
  # Semantic vector for RAG
31
  embedding = Column(Vector(settings.AI_EMBEDDING_DIM), nullable=True)
32
 
33
+ # Version Control
34
+ version = Column(Integer, default=1, nullable=False)
35
+
36
  # --- Search Optimization ---
37
  # 1. Computed TSVector for GIN search (Keyword Engine)
38
  search_vector = Column(
 
58
  project = relationship("Project", back_populates="kb_articles")
59
  chunks = relationship("KBArticleChunk", back_populates="article", cascade="all, delete-orphan")
60
  attachments = relationship("Attachment", back_populates="article", cascade="all, delete-orphan")
61
+ versions = relationship("KBArticleVersion", back_populates="article", cascade="all, delete-orphan", order_by="desc(KBArticleVersion.version_number)")
62
 
63
  # Self-referential for duplicates
64
  duplicate_of = relationship("KBArticle", remote_side="KBArticle.id", backref="duplicates")
models/kb_article_version.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlalchemy import Column, String, Text, ForeignKey, Integer
2
+ from sqlalchemy.dialects.postgresql import UUID
3
+ from sqlalchemy.orm import relationship
4
+ from core.database import Base
5
+ from models.base import PrimaryKeyMixin, TimestampMixin
6
+
7
+ class KBArticleVersion(Base, PrimaryKeyMixin, TimestampMixin):
8
+ __tablename__ = "kb_article_versions"
9
+
10
+ article_id = Column(UUID(as_uuid=True), ForeignKey("kb_articles.id", ondelete="CASCADE"), nullable=False, index=True)
11
+ version_number = Column(Integer, nullable=False)
12
+ author_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
13
+
14
+ title = Column(String(500), nullable=False)
15
+ content = Column(Text, nullable=False)
16
+ category = Column(String(100), nullable=True)
17
+
18
+ article = relationship("KBArticle", back_populates="versions")
19
+ author = relationship("User")