Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(datasource): perform real sync deletions scoped per data source (#2690)

MidoriKurage236d8c098f9f
diff --git a/frontend/src/i18n/localeKeyAudit.ts b/frontend/src/i18n/localeKeyAudit.ts
index c9b2f46ad..0cb915f38 100644
--- a/frontend/src/i18n/localeKeyAudit.ts
+++ b/frontend/src/i18n/localeKeyAudit.ts
@@ -86,6 +86,7 @@ const EXTRA_PREFIXES = [
'contextualGuide.chat.steps.',
'contextualGuide.agentList.steps.',
'contextualGuide.agentCreate.steps.',
+ 'datasource.syncError.',
'kbSettings.parser.engines.',
'model.editor.description.',
'integrations.tabs.',
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 49d1910d9..a21161e6e 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5792,7 +5792,12 @@ export default {
justNow: 'Just now',
minutesAgo: '{n}m ago',
hoursAgo: '{n}h ago',
- daysAgo: '{n}d ago'
+ daysAgo: '{n}d ago',
+ syncError: {
+ deletion_lookup_failed: 'Failed to look up the item before deletion; see server logs',
+ deletion_failed: 'Deletion failed; see server logs',
+ ingest_failed: 'Ingest failed; see server logs'
+ }
},
integrations: {
title: 'Publish & Integrations',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 1e0d45b46..eac163180 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -784,6 +784,11 @@ export default {
loadAuthHint: "앱 자격 증명이 유효하지 않거나 드라이브 권한이 없습니다. App ID / App Secret 및 drive:drive:readonly 권한을 확인하세요.",
loadNotFoundHint: "folder_token이 존재하지 않거나 삭제되었습니다. 페이슈 드라이브 폴더 URL에서 복사한 토큰이 맞는지 확인하세요.",
},
+ syncError: {
+ deletion_lookup_failed: '삭제 전 항목 조회에 실패했습니다. 서버 로그를 확인하세요',
+ deletion_failed: '삭제에 실패했습니다. 서버 로그를 확인하세요',
+ ingest_failed: '가져오기에 실패했습니다. 서버 로그를 확인하세요'
+ },
},
ollama: {
unknown: '알 수 없음',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 86bbda617..494aac779 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -784,6 +784,11 @@ export default {
loadAuthHint: 'Учётные данные приложения недействительны или отсутствуют области Drive. Проверьте App ID / App Secret и разрешения drive:drive:readonly.',
loadNotFoundHint: 'folder_token не существует или удалён. Проверьте токен, скопированный из URL папки Feishu Drive.',
},
+ syncError: {
+ deletion_lookup_failed: 'Не удалось найти элемент перед удалением; подробности в журнале сервера',
+ deletion_failed: 'Не удалось удалить элемент; подробности в журнале сервера',
+ ingest_failed: 'Не удалось импортировать элемент; подробности в журнале сервера'
+ },
},
ollama: {
unknown: 'Неизвестно',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index d2395f5e6..a50f8c0d8 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -786,6 +786,11 @@ export default {
loadAuthHint: "应用凭证无效或缺少云盘权限,请检查 App ID / App Secret 及 drive:drive:readonly 等权限。",
loadNotFoundHint: "folder_token 不存在或已删除,请确认从飞书云盘文件夹 URL 复制的 token 正确。",
},
+ syncError: {
+ deletion_lookup_failed: '删除前查找文档失败,请查看服务器日志',
+ deletion_failed: '删除失败,请查看服务器日志',
+ ingest_failed: '导入失败,请查看服务器日志'
+ },
},
ollama: {
unknown: '未知',
diff --git a/internal/application/repository/knowledge.go b/internal/application/repository/knowledge.go
index c2989e8f2..687ff4713 100644
--- a/internal/application/repository/knowledge.go
+++ b/internal/application/repository/knowledge.go
@@ -755,6 +755,46 @@ func (r *knowledgeRepository) FindByMetadataKeyPrefix(
return items, nil
}
+// FindByDataSourceExternalID locates a synced knowledge item without allowing
+// identical external IDs from two data sources to collide in one knowledge base.
+func (r *knowledgeRepository) FindByDataSourceExternalID(
+ ctx context.Context,
+ tenantID uint64,
+ kbID, dataSourceID, externalID string,
+) (*types.Knowledge, error) {
+ var knowledge types.Knowledge
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND knowledge_base_id = ? AND deleted_at IS NULL", tenantID, kbID).
+ Where("metadata->>'datasource_id' = ? AND metadata->>'external_id' = ?", dataSourceID, externalID).
+ First(&knowledge).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return &knowledge, nil
+}
+
+// HardDeleteKnowledge physically removes a knowledge row. Call it AFTER
+// DeleteKnowledge's soft-delete cascade so sync-internal deletions never
+// become tombstones that block a later re-sync of the same external item.
+func (r *knowledgeRepository) HardDeleteKnowledge(ctx context.Context, tenantID uint64, id string) error {
+ return r.db.Unscoped().WithContext(ctx).
+ Where("tenant_id = ? AND id = ?", tenantID, id).
+ Delete(&types.Knowledge{}).Error
+}
+
+// HardDeleteKnowledgeList is the batch counterpart of HardDeleteKnowledge.
+func (r *knowledgeRepository) HardDeleteKnowledgeList(ctx context.Context, tenantID uint64, ids []string) error {
+ if len(ids) == 0 {
+ return nil
+ }
+ return r.db.Unscoped().WithContext(ctx).
+ Where("tenant_id = ? AND id IN ?", tenantID, ids).
+ Delete(&types.Knowledge{}).Error
+}
+
func (r *knowledgeRepository) SearchKnowledge(
ctx context.Context,
tenantID uint64,
diff --git a/internal/application/repository/knowledge_datasource_external_id_test.go b/internal/application/repository/knowledge_datasource_external_id_test.go
new file mode 100644
index 000000000..24d33f959
--- /dev/null
+++ b/internal/application/repository/knowledge_datasource_external_id_test.go
@@ -0,0 +1,85 @@
+package repository
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFindByDataSourceExternalID(t *testing.T) {
+ db := setupKnowledgeTestDB(t)
+ repo := NewKnowledgeRepository(db).(*knowledgeRepository)
+ ctx := context.Background()
+
+ const tenantID uint64 = 50
+ kbID := uuid.New().String()
+ dsA := uuid.New().String()
+ dsB := uuid.New().String()
+
+ insertRow := func(dsID, extID string) string {
+ id := uuid.New().String()
+ metadata := fmt.Sprintf(`{"datasource_id":%q,"external_id":%q}`, dsID, extID)
+ require.NoError(t, db.Exec(`
+ INSERT INTO knowledges
+ (id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata)
+ VALUES (?, ?, ?, 'document', ?, 'feishu', 'completed', ?)
+ `, id, tenantID, kbID, extID, metadata).Error)
+ return id
+ }
+
+ idA := insertRow(dsA, "file:shared")
+ _ = insertRow(dsB, "file:shared")
+
+ found, err := repo.FindByDataSourceExternalID(ctx, tenantID, kbID, dsA, "file:shared")
+ require.NoError(t, err)
+ require.NotNil(t, found)
+ assert.Equal(t, idA, found.ID)
+}
+
+func TestFindByDataSourceExternalID_DeletedRowsExcluded(t *testing.T) {
+ db := setupKnowledgeTestDB(t)
+ repo := NewKnowledgeRepository(db).(*knowledgeRepository)
+ ctx := context.Background()
+
+ const tenantID uint64 = 51
+ kbID := uuid.New().String()
+ dsID := uuid.New().String()
+
+ id := uuid.New().String()
+ metadata := fmt.Sprintf(`{"datasource_id":%q,"external_id":%q}`, dsID, "file:gone")
+ require.NoError(t, db.Exec(`
+ INSERT INTO knowledges
+ (id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata, deleted_at)
+ VALUES (?, ?, ?, 'document', 'gone', 'feishu', 'completed', ?, '2026-01-01 00:00:00')
+ `, id, tenantID, kbID, metadata).Error)
+
+ found, err := repo.FindByDataSourceExternalID(ctx, tenantID, kbID, dsID, "file:gone")
+ require.NoError(t, err)
+ assert.Nil(t, found)
+}
+
+func TestHardDeleteKnowledge(t *testing.T) {
+ db := setupKnowledgeTestDB(t)
+ repo := NewKnowledgeRepository(db).(*knowledgeRepository)
+ ctx := context.Background()
+
+ const tenantID uint64 = 52
+ kbID := uuid.New().String()
+ id := uuid.New().String()
+ metadata := `{"datasource_id":"ds-1","external_id":"file:1"}`
+ require.NoError(t, db.Exec(`
+ INSERT INTO knowledges
+ (id, tenant_id, knowledge_base_id, type, title, source, parse_status, metadata, deleted_at)
+ VALUES (?, ?, ?, 'document', 'file:1', 'feishu', 'completed', ?, '2026-01-01 00:00:00')
+ `, id, tenantID, kbID, metadata).Error)
+
+ require.NoError(t, repo.HardDeleteKnowledge(ctx, tenantID, id))
+
+ var count int64
+ require.NoError(t, db.Unscoped().Model(&struct{}{}).Table("knowledges").Where("id = ?", id).Count(&count).Error)
+ assert.Equal(t, int64(0), count)
+}
diff --git a/internal/application/service/datasource_service.go b/internal/application/service/datasource_service.go
index f33284d5a..71eff04ad 100644
--- a/internal/application/service/datasource_service.go
+++ b/internal/application/service/datasource_service.go
@@ -774,6 +774,20 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e
}
resultJSON, _ = result.ToJSON()
}
+ if result.Failed > 0 {
+ // Per-document failures flip the sync to partial so the drawer shows
+ // which docs didn't make it (mirrors the streaming path). Deletion
+ // failures additionally only retry on a later full sync.
+ syncStatus = types.SyncLogStatusPartial
+ if syncErrorMessage != "" {
+ syncErrorMessage += "; "
+ }
+ syncErrorMessage += fmt.Sprintf("%d document(s) failed to sync", result.Failed)
+ if result.DeletionFailed > 0 {
+ syncErrorMessage += fmt.Sprintf(
+ "; %d deletion failure(s) will only retry on the next full sync", result.DeletionFailed)
+ }
+ }
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, syncStatus, syncErrorMessage, wasPaused)
logger.Infof(ctx, "data source sync completed: ds=%s created=%d updated=%d deleted=%d",
@@ -841,12 +855,67 @@ func (s *DataSourceService) applyFetchedItem(
tagIDs []string, result *types.SyncResult,
) {
if item.IsDeleted {
- if ds.SyncDeletions {
- // Count only — actual KB deletion is intentionally not performed.
- // Users manage knowledge removal explicitly via the KB UI to avoid
- // accidental data loss from connector misdetection or reconfiguration.
- result.Deleted++
+ if !ds.SyncDeletions {
+ // Sync deletion disabled: neither count nor delete.
+ return
+ }
+ if item.ExternalID == "" {
+ logger.Warnf(ctx, "skipping deletion for item %q: empty external_id", item.Title)
+ result.Skipped++
+ return
+ }
+ // Perform real KB deletion, scoped to items owned by this data source
+ // so identical external IDs from different data sources cannot collide.
+ repo := s.knowledgeService.GetRepository()
+ existing, lookupErr := repo.FindByDataSourceExternalID(
+ ctx, ds.TenantID, ds.KnowledgeBaseID, ds.ID, item.ExternalID,
+ )
+ if lookupErr != nil {
+ logger.Errorf(ctx, "failed to find deleted knowledge for external_id=%s (ds=%s, kb=%s): %v",
+ item.ExternalID, ds.ID, ds.KnowledgeBaseID, lookupErr)
+ result.Failed++
+ result.DeletionFailed++
+ recordSyncError(result, types.SyncItemError{
+ Title: item.Title,
+ Code: "deletion_lookup_failed",
+ Message: "Failed to look up the item before deletion; see server logs",
+ })
+ return
+ }
+ if existing == nil {
+ // Deletion is idempotent: the source item may already have been
+ // removed manually or by an earlier sync.
+ result.Skipped++
+ return
+ }
+ if deleteErr := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); deleteErr != nil {
+ // The cursor is already past this item, so a failed deletion normally
+ // retries only on a later full sync. Counted separately so the
+ // sync-log message can warn the operator about this gap.
+ result.Failed++
+ result.DeletionFailed++
+ logger.Errorf(ctx, "failed to delete knowledge %s for external_id=%s (ds=%s): %v",
+ existing.ID, item.ExternalID, ds.ID, deleteErr)
+ recordSyncError(result, types.SyncItemError{
+ Title: item.Title,
+ Code: "deletion_failed",
+ Message: "Deletion failed; see server logs",
+ })
+ return
}
+ if herr := repo.HardDeleteKnowledge(ctx, ds.TenantID, existing.ID); herr != nil {
+ result.Failed++
+ result.DeletionFailed++
+ logger.Errorf(ctx, "failed to hard-delete knowledge %s for external_id=%s (ds=%s): %v",
+ existing.ID, item.ExternalID, ds.ID, herr)
+ recordSyncError(result, types.SyncItemError{
+ Title: item.Title,
+ Code: "deletion_failed",
+ Message: "Deletion failed; see server logs",
+ })
+ return
+ }
+ result.Deleted++
return
}
@@ -1026,13 +1095,18 @@ func (s *DataSourceService) processSyncStreaming(
// Surface per-document failures as a partial sync (not silent success), so
// the sync-log drawer's failure detail explains which docs didn't make it —
// the visibility gap behind "status normal but not everything syncs"
- // (Tencent/WeKnora#2136). Failed nodes were not advanced in the cursor, so
- // the next run retries them.
+ // (Tencent/WeKnora#2136). Fetch failures abort the stream before the failed
+ // page is checkpointed, so the next run retries them; deletion failures are
+ // past the cursor and only retry on a full sync in the normal case (see
+ // applyFetchedItem).
status := types.SyncLogStatusSuccess
errMsg := ""
if result.Failed > 0 {
status = types.SyncLogStatusPartial
errMsg = fmt.Sprintf("%d document(s) failed to sync", result.Failed)
+ if result.DeletionFailed > 0 {
+ errMsg += fmt.Sprintf("; %d deletion failure(s) will only retry on the next full sync", result.DeletionFailed)
+ }
}
s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, status, errMsg, wasPaused)
logger.Infof(ctx, "streaming sync completed: ds=%s created=%d updated=%d deleted=%d skipped=%d failed=%d",
@@ -1185,7 +1259,10 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
isUpdate := false
if item.ExternalID != "" {
repo := s.knowledgeService.GetRepository()
- existing, err := repo.FindByMetadataKey(ctx, ds.TenantID, ds.KnowledgeBaseID, "external_id", item.ExternalID)
+ // Scope the lookup to items owned by this data source so identical
+ // external IDs from two data sources cannot collide or overwrite each
+ // other during updates.
+ existing, err := repo.FindByDataSourceExternalID(ctx, ds.TenantID, ds.KnowledgeBaseID, ds.ID, item.ExternalID)
if err != nil {
logger.Warnf(ctx, "failed to check existing knowledge for external_id=%s: %v", item.ExternalID, err)
// Non-fatal: proceed with creation (may produce duplicate)
@@ -1194,6 +1271,9 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
if err := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); err != nil {
logger.Warnf(ctx, "failed to delete existing knowledge %s: %v", existing.ID, err)
} else {
+ if herr := repo.HardDeleteKnowledge(ctx, ds.TenantID, existing.ID); herr != nil {
+ logger.Warnf(ctx, "failed to hard-delete replaced knowledge %s: %v", existing.ID, herr)
+ }
isUpdate = true
}
}
@@ -1231,7 +1311,7 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
// Case 2: only a remote URL — let WeKnora handle downloading and parsing
if item.URL != "" {
- if _, err := s.knowledgeService.CreateKnowledgeFromURL(
+ created, err := s.knowledgeService.CreateKnowledgeFromURL(
ctx,
ds.KnowledgeBaseID,
item.URL,
@@ -1242,7 +1322,8 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
tagIDs, // auto-tag from data source
channel,
nil,
- ); err != nil {
+ )
+ if err != nil {
var dupErr *types.DuplicateKnowledgeError
if errors.As(err, &dupErr) && dupIsSameNode(dupErr, item) {
// Identical content is already present in the KB under THIS node's
@@ -1252,6 +1333,19 @@ func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource
}
return isUpdate, err
}
+ // URL-created knowledge has no metadata, so a later deletion could
+ // never find it. Attach the datasource keys on fresh creation only;
+ // the duplicate path reuses an existing row that must not be re-tagged.
+ if created != nil {
+ metadataBytes, mErr := json.Marshal(metadata)
+ if mErr != nil {
+ return isUpdate, fmt.Errorf("marshal datasource metadata: %w", mErr)
+ }
+ created.Metadata = types.JSON(metadataBytes)
+ if uErr := s.knowledgeService.GetRepository().UpdateKnowledge(ctx, created); uErr != nil {
+ return isUpdate, fmt.Errorf("attach datasource metadata: %w", uErr)
+ }
+ }
s.sweepStaleSubtree(ctx, ds, item)
return isUpdate, nil
}
@@ -1301,6 +1395,11 @@ func (s *DataSourceService) sweepStaleSubtree(ctx context.Context, ds *types.Dat
}
ids := make([]string, 0, len(children))
for _, child := range children {
+ // Scope to this data source so identical external_id prefixes from
+ // another connector in the same KB cannot be swept.
+ if child.GetMetadata()["datasource_id"] != ds.ID {
+ continue
+ }
// A child still present in the source is preserved even if it could not be
// re-ingested this sync; only children that vanished from the source are
// stale and swept. Every child here was selected by the external_id-prefix
@@ -1322,6 +1421,9 @@ func (s *DataSourceService) sweepStaleSubtree(ctx context.Context, ds *types.Dat
if derr := s.knowledgeService.DeleteKnowledgeList(ctx, ids); derr != nil {
logger.Warnf(ctx, "failed to delete %d stale sub-item(s) of external_id=%s: %v",
len(ids), item.ExternalID, derr)
+ } else if herr := repo.HardDeleteKnowledgeList(ctx, ds.TenantID, ids); herr != nil {
+ logger.Warnf(ctx, "failed to hard-delete %d stale sub-item(s) of external_id=%s: %v",
+ len(ids), item.ExternalID, herr)
}
}
diff --git a/internal/application/service/datasource_service_test.go b/internal/application/service/datasource_service_test.go
index 972653dfb..a781f4c6a 100644
--- a/internal/application/service/datasource_service_test.go
+++ b/internal/application/service/datasource_service_test.go
@@ -9,6 +9,7 @@ import (
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/hibiken/asynq"
@@ -59,29 +60,37 @@ func TestProcessSyncCancelsWhenKnowledgeBaseDeleted(t *testing.T) {
type processSyncKBService struct {
getErr error
+ kb *types.KnowledgeBase
}
func (s *processSyncKBService) CreateKnowledgeBase(context.Context, *types.KnowledgeBase) (*types.KnowledgeBase, error) {
return nil, nil
}
+
func (s *processSyncKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
- return nil, s.getErr
+ return s.kb, s.getErr
}
+
func (s *processSyncKBService) GetKnowledgeBaseByIDOnly(context.Context, string) (*types.KnowledgeBase, error) {
- return nil, s.getErr
+ return s.kb, s.getErr
}
+
func (s *processSyncKBService) GetKnowledgeBasesByIDsOnly(context.Context, []string) ([]*types.KnowledgeBase, error) {
return nil, nil
}
+
func (s *processSyncKBService) FillKnowledgeBaseCounts(context.Context, *types.KnowledgeBase) error {
return nil
}
+
func (s *processSyncKBService) ListKnowledgeBases(context.Context) ([]*types.KnowledgeBase, error) {
return nil, nil
}
+
func (s *processSyncKBService) ListKnowledgeBasesByTenantID(context.Context, uint64) ([]*types.KnowledgeBase, error) {
return nil, nil
}
+
func (s *processSyncKBService) UpdateKnowledgeBase(
context.Context, string, string, string, *types.KnowledgeBaseConfig,
) (*types.KnowledgeBase, error) {
@@ -91,18 +100,23 @@ func (s *processSyncKBService) DeleteKnowledgeBase(context.Context, string) erro
func (s *processSyncKBService) TogglePinKnowledgeBase(context.Context, string) (*types.KnowledgeBase, error) {
return nil, nil
}
+
func (s *processSyncKBService) HybridSearch(context.Context, string, types.SearchParams) ([]*types.SearchResult, error) {
return nil, nil
}
+
func (s *processSyncKBService) GetQueryEmbedding(context.Context, string, string) ([]float32, error) {
return nil, nil
}
+
func (s *processSyncKBService) ResolveEmbeddingModelKeys(context.Context, []*types.KnowledgeBase) map[string]string {
return nil
}
+
func (s *processSyncKBService) CopyKnowledgeBase(context.Context, string, string) (*types.KnowledgeBase, *types.KnowledgeBase, error) {
return nil, nil, nil
}
+
func (s *processSyncKBService) DuplicateKnowledgeBase(context.Context, string) (*types.KnowledgeBase, error) {
return nil, nil
}
@@ -121,6 +135,7 @@ func (r *processSyncSyncLogRepo) Create(_ context.Context, log *types.SyncLog) e
r.logs[log.ID] = log
return nil
}
+
func (r *processSyncSyncLogRepo) FindByID(_ context.Context, id string) (*types.SyncLog, error) {
log, ok := r.logs[id]
if !ok {
@@ -128,22 +143,28 @@ func (r *processSyncSyncLogRepo) FindByID(_ context.Context, id string) (*types.
}
return log, nil
}
+
func (r *processSyncSyncLogRepo) FindByDataSource(context.Context, string, int, int) ([]*types.SyncLog, error) {
return nil, nil
}
+
func (r *processSyncSyncLogRepo) FindLatest(context.Context, string) (*types.SyncLog, error) {
return nil, nil
}
+
func (r *processSyncSyncLogRepo) HasRunningSync(context.Context, string) (bool, error) {
return false, nil
}
+
func (r *processSyncSyncLogRepo) Update(_ context.Context, log *types.SyncLog) error {
r.logs[log.ID] = log
return nil
}
+
func (r *processSyncSyncLogRepo) UpdateResult(_ context.Context, log *types.SyncLog) error {
return r.Update(context.Background(), log)
}
+
func (r *processSyncSyncLogRepo) CancelPendingByDataSource(context.Context, string) error {
return nil
}
@@ -187,3 +208,500 @@ func TestAllFetchedItemsFailedErrorTruncatesLongDetail(t *testing.T) {
assert.LessOrEqual(t, len(err.Error()), 560)
assert.Contains(t, err.Error(), "...")
}
+
+const deletedItemConnectorType = "test-sync-deletion"
+
+type deletedItemConnector struct{}
+
+func (deletedItemConnector) Type() string { return deletedItemConnectorType }
+func (deletedItemConnector) Validate(context.Context, *types.DataSourceConfig) error {
+ return nil
+}
+
+func (deletedItemConnector) ListResources(context.Context, *types.DataSourceConfig, string) ([]types.Resource, error) {
+ return nil, nil
+}
+
+func (deletedItemConnector) ResolveResourceAncestors(
+ context.Context, *types.DataSourceConfig, []string,
+) ([]string, error) {
+ return nil, nil
+}
+
+func (deletedItemConnector) FetchAll(context.Context, *types.DataSourceConfig, []string) ([]types.FetchedItem, error) {
+ return []types.FetchedItem{{
+ ExternalID: "file:gone",
+ SourceResourceID: "folder:1",
+ IsDeleted: true,
+ }}, nil
+}
+
+func (deletedItemConnector) FetchIncremental(
+ context.Context, *types.DataSourceConfig, *types.SyncCursor,
+) ([]types.FetchedItem, *types.SyncCursor, error) {
+ items, err := (deletedItemConnector{}).FetchAll(context.Background(), nil, nil)
+ return items, nil, err
+}
+
+type processSyncTenantRepo struct {
+ interfaces.TenantRepository
+ tenant *types.Tenant
+}
+
+func (r *processSyncTenantRepo) GetTenantByID(context.Context, uint64) (*types.Tenant, error) {
+ return r.tenant, nil
+}
+
+type processSyncTagService struct {
+ interfaces.KnowledgeTagService
+}
+
+func (*processSyncTagService) FindOrCreateTagByName(context.Context, string, string) (*types.KnowledgeTag, error) {
+ return nil, nil
+}
+
+type deletionLookupKnowledgeRepo struct {
+ interfaces.KnowledgeRepository
+ knowledge *types.Knowledge
+ lookupErr error
+ metadataUpdates []map[string]string // metadata persisted via UpdateKnowledge
+ metadataUpdateErr error
+ hardDeleted []string
+ hardDeleteErr error
+ tenantID uint64
+ knowledgeBaseID string
+ dataSourceID string
+ externalID string
+}
+
+func (r *deletionLookupKnowledgeRepo) UpdateKnowledge(_ context.Context, knowledge *types.Knowledge) error {
+ if r.metadataUpdateErr != nil {
+ return r.metadataUpdateErr
+ }
+ metadata := map[string]string{}
+ if len(knowledge.Metadata) > 0 {
+ if err := json.Unmarshal(knowledge.Metadata, &metadata); err != nil {
+ return err
+ }
+ }
+ r.metadataUpdates = append(r.metadataUpdates, metadata)
+ return nil
+}
+
+func (r *deletionLookupKnowledgeRepo) FindByDataSourceExternalID(
+ _ context.Context, tenantID uint64, knowledgeBaseID, dataSourceID, externalID string,
+) (*types.Knowledge, error) {
+ if r.lookupErr != nil {
+ return nil, r.lookupErr
+ }
+ r.tenantID = tenantID
+ r.knowledgeBaseID = knowledgeBaseID
+ r.dataSourceID = dataSourceID
+ r.externalID = externalID
+ return r.knowledge, nil
+}
+
+func (r *deletionLookupKnowledgeRepo) HardDeleteKnowledge(_ context.Context, _ uint64, id string) error {
+ if r.hardDeleteErr != nil {
+ return r.hardDeleteErr
+ }
+ r.hardDeleted = append(r.hardDeleted, id)
+ return nil
+}
+
+func (r *deletionLookupKnowledgeRepo) HardDeleteKnowledgeList(_ context.Context, _ uint64, ids []string) error {
+ for _, id := range ids {
+ if err := r.HardDeleteKnowledge(context.Background(), 0, id); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// scopedDeletionRepo models two data sources sharing the same external_id.
+type scopedDeletionRepo struct {
+ interfaces.KnowledgeRepository
+ live map[string]*types.Knowledge
+ hardDeleted []string
+}
+
+func (r *scopedDeletionRepo) FindByDataSourceExternalID(
+ _ context.Context, _ uint64, _, dataSourceID, externalID string,
+) (*types.Knowledge, error) {
+ if r.live == nil {
+ return nil, nil
+ }
+ return r.live[dataSourceID+"|"+externalID], nil
+}
+
+func (r *scopedDeletionRepo) HardDeleteKnowledge(_ context.Context, _ uint64, id string) error {
+ r.hardDeleted = append(r.hardDeleted, id)
+ return nil
+}
+
+func (r *scopedDeletionRepo) HardDeleteKnowledgeList(_ context.Context, _ uint64, ids []string) error {
+ r.hardDeleted = append(r.hardDeleted, ids...)
+ return nil
+}
+
+// keyedDeletionRepo maps external_id to live knowledge for multi-item sync tests.
+type keyedDeletionRepo struct {
+ interfaces.KnowledgeRepository
+ items map[string]*types.Knowledge
+ hardDeleted []string
+ hardDeleteErr error
+}
+
+func (r *keyedDeletionRepo) FindByDataSourceExternalID(
+ _ context.Context, _ uint64, _, _, externalID string,
+) (*types.Knowledge, error) {
+ if r.items == nil {
+ return nil, nil
+ }
+ return r.items[externalID], nil
+}
+
+func (r *keyedDeletionRepo) HardDeleteKnowledge(_ context.Context, _ uint64, id string) error {
+ if r.hardDeleteErr != nil {
+ return r.hardDeleteErr
+ }
+ r.hardDeleted = append(r.hardDeleted, id)
+ return nil
+}
+
+func (r *keyedDeletionRepo) HardDeleteKnowledgeList(_ context.Context, _ uint64, ids []string) error {
+ for _, id := range ids {
+ if err := r.HardDeleteKnowledge(context.Background(), 0, id); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// syncDeletionHarness wires a DataSourceService around a connector that always
+// reports one deleted item, with overridable lookup/delete fakes.
+type syncDeletionHarness struct {
+ ds *types.DataSource
+ syncLogID string
+ syncLogRepo *processSyncSyncLogRepo
+ knowledgeRepo *deletionLookupKnowledgeRepo
+ knowledgeSvc *sweepFakeKS
+ svc *DataSourceService
+}
+
+// newSyncDeletionHarness builds a full-sync ProcessSync fixture. Passing nil
+// for repo/ks selects the happy-path defaults: an existing knowledge item and
+// no lookup/delete errors.
+func newSyncDeletionHarness(
+ t *testing.T, syncDeletions bool, dsID, logID string,
+ repo *deletionLookupKnowledgeRepo, ks *sweepFakeKS,
+) *syncDeletionHarness {
+ t.Helper()
+ configJSON, err := (&types.DataSourceConfig{Type: deletedItemConnectorType}).ToJSON()
+ require.NoError(t, err)
+
+ ds := &types.DataSource{
+ ID: dsID,
+ TenantID: 1,
+ KnowledgeBaseID: "kb-1",
+ Name: "Sync Deletion",
+ Type: deletedItemConnectorType,
+ Config: configJSON,
+ SyncMode: types.SyncModeFull,
+ Status: types.DataSourceStatusActive,
+ SyncDeletions: syncDeletions,
+ }
+ syncLog := &types.SyncLog{
+ ID: logID,
+ DataSourceID: ds.ID,
+ TenantID: ds.TenantID,
+ Status: types.SyncLogStatusRunning,
+ StartedAt: time.Now().UTC(),
+ }
+ if repo == nil {
+ repo = &deletionLookupKnowledgeRepo{knowledge: &types.Knowledge{ID: "knowledge-gone"}}
+ }
+ if ks == nil {
+ ks = &sweepFakeKS{repo: repo}
+ }
+ syncLogRepo := &processSyncSyncLogRepo{logs: map[string]*types.SyncLog{syncLog.ID: syncLog}}
+ registry := datasource.NewConnectorRegistry()
+ require.NoError(t, registry.Register(deletedItemConnector{}))
+
+ return &syncDeletionHarness{
+ ds: ds,
+ syncLogID: syncLog.ID,
+ syncLogRepo: syncLogRepo,
+ knowledgeRepo: repo,
+ knowledgeSvc: ks,
+ svc: &DataSourceService{
+ dsRepo: newKBDeleteDSRepo(ds.KnowledgeBaseID, ds),
+ syncLogRepo: syncLogRepo,
+ knowledgeService: ks,
+ kbService: &processSyncKBService{kb: &types.KnowledgeBase{ID: ds.KnowledgeBaseID, TenantID: ds.TenantID}},
+ connectorRegistry: registry,
+ tenantRepo: &processSyncTenantRepo{tenant: &types.Tenant{ID: ds.TenantID}},
+ tagService: &processSyncTagService{},
+ },
+ }
+}
+
+// run executes a full sync and returns the persisted sync log plus the error
+// ProcessSync returned (non-nil when every fetched item failed).
+func (h *syncDeletionHarness) run(t *testing.T) (*types.SyncLog, error) {
+ t.Helper()
+ payload, err := json.Marshal(types.DataSourceSyncPayload{
+ DataSourceID: h.ds.ID,
+ TenantID: h.ds.TenantID,
+ SyncLogID: h.syncLogID,
+ ForceFull: true,
+ })
+ require.NoError(t, err)
+ err = h.svc.ProcessSync(context.Background(), asynq.NewTask(types.TypeDataSourceSync, payload))
+
+ updated := h.syncLogRepo.logs[h.syncLogID]
+ require.NotNil(t, updated)
+ return updated, err
+}
+
+// deletionFailedCount extracts the SyncResult.deletion_failed counter without
+// referencing the SyncResult type, so these tests stay independent of the
+// field's commit.
+func deletionFailedCount(t *testing.T, log *types.SyncLog) int {
+ t.Helper()
+ var counters struct {
+ DeletionFailed int `json:"deletion_failed"`
+ }
+ require.NoError(t, json.Unmarshal(log.Result, &counters))
+ return counters.DeletionFailed
+}
+
+// TestProcessSync_SyncDeletionsDeletesMatchingKnowledge verifies that a
+// deleted source item removes the matching KB knowledge (counted as Deleted),
+// and that the lookup is scoped to tenant, KB, data source and external ID.
+// TestIngestItem_URLCreationAttachesDataSourceMetadata verifies that a
+// URL-only item gets its datasource scoping keys attached right after
+// creation, so a later source-side deletion can find it via
+// FindByDataSourceExternalID (CreateKnowledgeFromURL itself persists no
+// metadata).
+func TestIngestItem_URLCreationAttachesDataSourceMetadata(t *testing.T) {
+ ds := &types.DataSource{ID: "ds-1", TenantID: 1, KnowledgeBaseID: "kb-1"}
+ repo := &deletionLookupKnowledgeRepo{}
+ ks := &sweepFakeKS{repo: repo, createURLKnowledge: &types.Knowledge{ID: "url-knowledge-1"}}
+ svc := &DataSourceService{knowledgeService: ks}
+
+ isUpdate, err := svc.ingestItem(context.Background(), ds, &types.FetchedItem{
+ ExternalID: "url:1",
+ URL: "https://example.com/doc",
+ }, nil)
+ require.NoError(t, err)
+ assert.False(t, isUpdate)
+ require.Len(t, repo.metadataUpdates, 1)
+ assert.Equal(t, ds.ID, repo.metadataUpdates[0]["datasource_id"])
+ assert.Equal(t, "url:1", repo.metadataUpdates[0]["external_id"])
+}
+
+func TestProcessSync_SyncDeletionsDeletesMatchingKnowledge(t *testing.T) {
+ h := newSyncDeletionHarness(t, true, "ds-delete-characterization", "log-delete-characterization", nil, nil)
+ updated, err := h.run(t)
+ require.NoError(t, err)
+
+ assert.Equal(t, 1, updated.ItemsDeleted)
+ assert.Equal(t, []string{"knowledge-gone"}, h.knowledgeSvc.deleted)
+ assert.Equal(t, h.ds.TenantID, h.knowledgeRepo.tenantID)
+ assert.Equal(t, h.ds.KnowledgeBaseID, h.knowledgeRepo.knowledgeBaseID)
+ assert.Equal(t, h.ds.ID, h.knowledgeRepo.dataSourceID)
+ assert.Equal(t, "file:gone", h.knowledgeRepo.externalID)
+}
+
+// TestProcessSync_SyncDeletionsDisabledSkipsDeletion verifies that with
+// SyncDeletions off the item is neither deleted nor counted (Deleted=0,
+// Skipped=0, no DeleteKnowledge call).
+func TestProcessSync_SyncDeletionsDisabledSkipsDeletion(t *testing.T) {
+ h := newSyncDeletionHarness(t, false, "ds-delete-disabled", "log-delete-disabled", nil, nil)
+ updated, err := h.run(t)
+ require.NoError(t, err)
+
+ assert.Empty(t, h.knowledgeSvc.deleted)
+ assert.Equal(t, 0, updated.ItemsDeleted)
+ assert.Equal(t, 0, updated.ItemsSkipped)
+}
+
+// TestProcessSync_SyncDeletionsAlreadyGoneCountsSkipped verifies the
+// idempotent path: the source item reports deletion but no KB knowledge
+// matches, so the item counts as Skipped and nothing is deleted.
+func TestProcessSync_SyncDeletionsAlreadyGoneCountsSkipped(t *testing.T) {
+ h := newSyncDeletionHarness(t, true, "ds-delete-gone", "log-delete-gone", &deletionLookupKnowledgeRepo{}, nil)
+ updated, err := h.run(t)
+ require.NoError(t, err)
+
+ assert.Empty(t, h.knowledgeSvc.deleted)
+ assert.Equal(t, 0, updated.ItemsDeleted)
+ assert.Equal(t, 1, updated.ItemsSkipped)
+}
+
+// TestProcessSync_SyncDeletionsLookupFailureCountsFailed verifies that a
+// failing scoped lookup surfaces as a Failed item with the
+// deletion_lookup_failed code, increments DeletionFailed, and never calls
+// DeleteKnowledge.
+func TestProcessSync_SyncDeletionsLookupFailureCountsFailed(t *testing.T) {
+ repo := &deletionLookupKnowledgeRepo{lookupErr: errors.New("lookup failed")}
+ h := newSyncDeletionHarness(t, true, "ds-delete-lookup-fail", "log-delete-lookup-fail", repo, nil)
+ updated, err := h.run(t)
+ require.Error(t, err)
+
+ assert.Empty(t, h.knowledgeSvc.deleted)
+ assert.Equal(t, 0, updated.ItemsDeleted)
+ assert.Equal(t, 1, updated.ItemsFailed)
+ result, err := updated.ParseResult()
+ require.NoError(t, err)
+ require.Len(t, result.Errors, 1)
+ assert.Equal(t, "deletion_lookup_failed", result.Errors[0].Code)
+ assert.Equal(t, 1, deletionFailedCount(t, updated))
+}
+
+// TestProcessSync_SyncDeletionsDeleteFailureCountsFailed verifies that a
+// failing DeleteKnowledge call surfaces as a Failed item with the
+// deletion_failed code and increments DeletionFailed without counting
+// the item as Deleted.
+func TestProcessSync_SyncDeletionsDeleteFailureCountsFailed(t *testing.T) {
+ h := newSyncDeletionHarness(t, true, "ds-delete-fail", "log-delete-fail", nil, nil)
+ h.knowledgeSvc.deleteErr = errors.New("delete failed")
+ updated, err := h.run(t)
+ require.Error(t, err)
+
+ assert.Equal(t, []string{"knowledge-gone"}, h.knowledgeSvc.deleted)
+ assert.Equal(t, 0, updated.ItemsDeleted)
+ assert.Equal(t, 1, updated.ItemsFailed)
+ result, err := updated.ParseResult()
+ require.NoError(t, err)
+ require.Len(t, result.Errors, 1)
+ assert.Equal(t, "deletion_failed", result.Errors[0].Code)
+ assert.Equal(t, 1, deletionFailedCount(t, updated))
+}
+
+func TestProcessSync_SyncDeletionsHardDeletesRow(t *testing.T) {
+ h := newSyncDeletionHarness(t, true, "ds-delete-hard", "log-delete-hard", nil, nil)
+ updated, err := h.run(t)
+ require.NoError(t, err)
+
+ assert.Equal(t, 1, updated.ItemsDeleted)
+ assert.Equal(t, []string{"knowledge-gone"}, h.knowledgeSvc.deleted)
+ assert.Equal(t, []string{"knowledge-gone"}, h.knowledgeRepo.hardDeleted)
+}
+
+func TestApplyFetchedItem_SyncDeletionScopedPerDataSource(t *testing.T) {
+ repo := &scopedDeletionRepo{live: map[string]*types.Knowledge{
+ "ds-a|file:shared": {ID: "knowledge-a"},
+ "ds-b|file:shared": {ID: "knowledge-b"},
+ }}
+ ks := &sweepFakeKS{repo: repo}
+ svc := &DataSourceService{knowledgeService: ks}
+
+ result := &types.SyncResult{}
+ dsA := &types.DataSource{
+ ID: "ds-a", TenantID: 1, KnowledgeBaseID: "kb-1", SyncDeletions: true,
+ }
+ svc.applyFetchedItem(context.Background(), dsA, &types.FetchedItem{
+ ExternalID: "file:shared",
+ IsDeleted: true,
+ }, nil, result)
+
+ assert.Equal(t, 1, result.Deleted)
+ assert.Equal(t, []string{"knowledge-a"}, ks.deleted)
+ assert.Equal(t, []string{"knowledge-a"}, repo.hardDeleted)
+ assert.NotContains(t, ks.deleted, "knowledge-b")
+}
+
+type mixedSyncConnector struct{}
+
+func (mixedSyncConnector) Type() string { return "test-sync-mixed" }
+func (mixedSyncConnector) Validate(context.Context, *types.DataSourceConfig) error {
+ return nil
+}
+
+func (mixedSyncConnector) ListResources(context.Context, *types.DataSourceConfig, string) ([]types.Resource, error) {
+ return nil, nil
+}
+
+func (mixedSyncConnector) ResolveResourceAncestors(
+ context.Context, *types.DataSourceConfig, []string,
+) ([]string, error) {
+ return nil, nil
+}
+
+func (mixedSyncConnector) FetchAll(context.Context, *types.DataSourceConfig, []string) ([]types.FetchedItem, error) {
+ return []types.FetchedItem{
+ {ExternalID: "file:gone", IsDeleted: true},
+ {ExternalID: "file:new", Content: []byte("hello"), FileName: "new.txt"},
+ }, nil
+}
+
+func (mixedSyncConnector) FetchIncremental(
+ context.Context, *types.DataSourceConfig, *types.SyncCursor,
+) ([]types.FetchedItem, *types.SyncCursor, error) {
+ items, err := (mixedSyncConnector{}).FetchAll(context.Background(), nil, nil)
+ return items, nil, err
+}
+
+func TestProcessSync_SyncDeletionsPartialWhenMixedResults(t *testing.T) {
+ configJSON, err := (&types.DataSourceConfig{Type: "test-sync-mixed"}).ToJSON()
+ require.NoError(t, err)
+
+ ds := &types.DataSource{
+ ID: "ds-mixed", TenantID: 1, KnowledgeBaseID: "kb-1",
+ Type: "test-sync-mixed", Config: configJSON,
+ SyncMode: types.SyncModeFull, Status: types.DataSourceStatusActive,
+ SyncDeletions: true,
+ }
+ syncLog := &types.SyncLog{
+ ID: "log-mixed", DataSourceID: ds.ID, TenantID: ds.TenantID,
+ Status: types.SyncLogStatusRunning, StartedAt: time.Now().UTC(),
+ }
+ repo := &keyedDeletionRepo{
+ items: map[string]*types.Knowledge{"file:gone": {ID: "knowledge-gone"}},
+ hardDeleteErr: errors.New("hard delete failed"),
+ }
+ ks := &sweepFakeKS{repo: repo}
+ syncLogRepo := &processSyncSyncLogRepo{logs: map[string]*types.SyncLog{syncLog.ID: syncLog}}
+ registry := datasource.NewConnectorRegistry()
+ require.NoError(t, registry.Register(mixedSyncConnector{}))
+
+ svc := &DataSourceService{
+ dsRepo: newKBDeleteDSRepo(ds.KnowledgeBaseID, ds),
+ syncLogRepo: syncLogRepo,
+ knowledgeService: ks,
+ kbService: &processSyncKBService{kb: &types.KnowledgeBase{ID: ds.KnowledgeBaseID, TenantID: ds.TenantID}},
+ connectorRegistry: registry,
+ tenantRepo: &processSyncTenantRepo{tenant: &types.Tenant{ID: ds.TenantID}},
+ tagService: &processSyncTagService{},
+ }
+
+ payload, err := json.Marshal(types.DataSourceSyncPayload{
+ DataSourceID: ds.ID, TenantID: ds.TenantID, SyncLogID: syncLog.ID, ForceFull: true,
+ })
+ require.NoError(t, err)
+ err = svc.ProcessSync(context.Background(), asynq.NewTask(types.TypeDataSourceSync, payload))
+ require.NoError(t, err, "partial failure must not fail the whole sync")
+
+ updated := syncLogRepo.logs[syncLog.ID]
+ require.NotNil(t, updated)
+ assert.Equal(t, types.SyncLogStatusPartial, updated.Status)
+ assert.Equal(t, 1, updated.ItemsFailed)
+ assert.Equal(t, 1, updated.ItemsCreated)
+ assert.Contains(t, updated.ErrorMessage, "deletion failure(s) will only retry on the next full sync")
+}
+
+func TestIngestItem_URLCreationMetadataAttachFailure(t *testing.T) {
+ ds := &types.DataSource{ID: "ds-1", TenantID: 1, KnowledgeBaseID: "kb-1"}
+ repo := &deletionLookupKnowledgeRepo{metadataUpdateErr: errors.New("db unavailable")}
+ ks := &sweepFakeKS{repo: repo, createURLKnowledge: &types.Knowledge{ID: "url-knowledge-1"}}
+ svc := &DataSourceService{knowledgeService: ks}
+
+ _, err := svc.ingestItem(context.Background(), ds, &types.FetchedItem{
+ ExternalID: "url:1",
+ URL: "https://example.com/doc",
+ }, nil)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "attach datasource metadata")
+}
diff --git a/internal/application/service/datasource_stream_test.go b/internal/application/service/datasource_stream_test.go
index 22eee8369..18ebe23cf 100644
--- a/internal/application/service/datasource_stream_test.go
+++ b/internal/application/service/datasource_stream_test.go
@@ -66,12 +66,19 @@ func newStreamHandler(svc *DataSourceService, ds *types.DataSource, result *type
}
// Emit routes items through the same classification as the batch loop: deleted
-// items are counted, and connector-reported failures (an item carrying only a
-// Metadata["error"]) land in result.Failed with a message — never silently lost.
+// items count into result.Deleted (the actual deletion, scoping and failure
+// counters are covered by the ProcessSync tests) and connector-reported
+// failures (an item carrying only a Metadata["error"]) land in result.Failed
+// with a message — never silently lost.
func TestStreamHandler_EmitClassifiesDeletedAndFailed(t *testing.T) {
- ds := &types.DataSource{ID: "ds-1", Type: types.ConnectorTypeFeishu, SyncDeletions: true}
+ ds := &types.DataSource{
+ ID: "ds-1", TenantID: 1, KnowledgeBaseID: "kb-1",
+ Type: types.ConnectorTypeFeishu, SyncDeletions: true,
+ }
result := &types.SyncResult{}
- h := newStreamHandler(&DataSourceService{}, ds, result, &types.SyncLog{})
+ knowledgeRepo := &deletionLookupKnowledgeRepo{knowledge: &types.Knowledge{ID: "knowledge-gone"}}
+ knowledgeSvc := &sweepFakeKS{repo: knowledgeRepo}
+ h := newStreamHandler(&DataSourceService{knowledgeService: knowledgeSvc}, ds, result, &types.SyncLog{})
require.NoError(t, h.Emit(context.Background(), types.FetchedItem{ExternalID: "gone", IsDeleted: true}))
require.NoError(t, h.Emit(context.Background(), types.FetchedItem{
diff --git a/internal/application/service/datasource_sweep_wiring_test.go b/internal/application/service/datasource_sweep_wiring_test.go
index 02dea3dbb..e9ce5bc0a 100644
--- a/internal/application/service/datasource_sweep_wiring_test.go
+++ b/internal/application/service/datasource_sweep_wiring_test.go
@@ -24,6 +24,20 @@ func (r *sweepFakeRepo) FindByMetadataKey(ctx context.Context, tenantID uint64,
return nil, nil // no existing main item → skip the case-1 update delete
}
+func (r *sweepFakeRepo) FindByDataSourceExternalID(
+ _ context.Context, _ uint64, _, _, _ string,
+) (*types.Knowledge, error) {
+ return nil, nil // no existing main item -> skip the case-1 update delete
+}
+
+func (r *sweepFakeRepo) HardDeleteKnowledge(context.Context, uint64, string) error {
+ return nil
+}
+
+func (r *sweepFakeRepo) HardDeleteKnowledgeList(context.Context, uint64, []string) error {
+ return nil
+}
+
func (r *sweepFakeRepo) FindByMetadataKeyPrefix(ctx context.Context, tenantID uint64, kbID, key, prefix string) ([]*types.Knowledge, error) {
r.prefixCalls = append(r.prefixCalls, key+"|"+prefix)
return r.prefixReturn, nil
@@ -31,18 +45,27 @@ func (r *sweepFakeRepo) FindByMetadataKeyPrefix(ctx context.Context, tenantID ui
type sweepFakeKS struct {
interfaces.KnowledgeService
- repo *sweepFakeRepo
- events []string // ordered log of "delete:<id>" and "create:<fname>"
- deleted []string
- createErr error // if set, CreateKnowledgeFromFile returns it after logging
+ repo interfaces.KnowledgeRepository
+ events []string // ordered log of "delete:<id>" and "create:<fname>"
+ deleted []string
+ createErr error // if set, CreateKnowledgeFromFile returns it after logging
+ deleteErr error // if set, DeleteKnowledge returns it after logging
+ createURLKnowledge *types.Knowledge // if set, CreateKnowledgeFromURL returns it
}
func (k *sweepFakeKS) GetRepository() interfaces.KnowledgeRepository { return k.repo }
+func (k *sweepFakeKS) CreateKnowledgeFromURL(
+ _ context.Context, _ string, _ string, _ string, _ string, _ *bool,
+ _ string, _ []string, _ string, _ *types.KnowledgeProcessOverrides,
+) (*types.Knowledge, error) {
+ return k.createURLKnowledge, nil
+}
+
func (k *sweepFakeKS) DeleteKnowledge(ctx context.Context, id string) error {
k.events = append(k.events, "delete:"+id)
k.deleted = append(k.deleted, id)
- return nil
+ return k.deleteErr
}
// DeleteKnowledgeList is the batched delete the subtree sweep now uses; record
@@ -76,8 +99,8 @@ func (k *sweepFakeKS) CreateKnowledgeFromFile(
// items later in the same sync, so the sweep still precedes their creation).
func TestIngestItem_ReplacesSubtreeSweepsStaleChildrenAfterCreate(t *testing.T) {
repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{
- {ID: "stale-child-1"},
- {ID: "stale-child-2"},
+ childWithExternalID("stale-child-1", "nt-parent#file#1", "ds-1"),
+ childWithExternalID("stale-child-2", "nt-parent#file#2", "ds-1"),
}}
ks := &sweepFakeKS{repo: repo}
s := &DataSourceService{knowledgeService: ks}
@@ -129,12 +152,14 @@ func TestIngestItem_ReplacesSubtreeSweepsStaleChildrenAfterCreate(t *testing.T)
// exists, so children removed from the doc must not linger. Regression guard for
// the "sweep runs only after a *fresh* create" gap.
func TestIngestItem_ReplacesSubtreeSweepsOnDuplicateParent(t *testing.T) {
- repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{{ID: "stale-child-1"}}}
+ repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{
+ childWithExternalID("stale-child-1", "nt-parent#file#1", "ds-1"),
+ }}
// The dedup hit is THIS node's own row (same external_id) — a genuine
// self-dedup where the parent effectively exists, so the sweep must run.
ks := &sweepFakeKS{
repo: repo,
- createErr: types.NewDuplicateFileError(childWithExternalID("existing-parent", "nt-parent")),
+ createErr: types.NewDuplicateFileError(childWithExternalID("existing-parent", "nt-parent", "ds-1")),
}
s := &DataSourceService{knowledgeService: ks}
@@ -170,7 +195,7 @@ func TestIngestItem_NoSweepWhenDuplicateIsDifferentNode(t *testing.T) {
// upload with no external_id at all would behave identically (empty != ours).
ks := &sweepFakeKS{
repo: repo,
- createErr: types.NewDuplicateFileError(childWithExternalID("some-other-doc", "nt-other")),
+ createErr: types.NewDuplicateFileError(childWithExternalID("some-other-doc", "nt-other", "ds-1")),
}
s := &DataSourceService{knowledgeService: ks}
@@ -193,9 +218,12 @@ func TestIngestItem_NoSweepWhenDuplicateIsDifferentNode(t *testing.T) {
}
// childWithExternalID builds a stale-child Knowledge row carrying the external_id
-// metadata the sweep reads to decide whether the child is still present.
-func childWithExternalID(id, externalID string) *types.Knowledge {
- b, _ := json.Marshal(map[string]string{"external_id": externalID})
+// and datasource_id metadata the sweep reads to decide ownership and presence.
+func childWithExternalID(id, externalID, dataSourceID string) *types.Knowledge {
+ b, _ := json.Marshal(map[string]string{
+ "external_id": externalID,
+ "datasource_id": dataSourceID,
+ })
return &types.Knowledge{ID: id, Metadata: types.JSON(b)}
}
@@ -207,8 +235,8 @@ func childWithExternalID(id, externalID string) *types.Knowledge {
// previously-synced good copy instead of being deleted with nothing to replace it.
func TestIngestItem_SubtreeKeepPreservesPresentChild(t *testing.T) {
repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{
- childWithExternalID("child-present", "nt-parent#file#present"),
- childWithExternalID("child-gone", "nt-parent#file#gone"),
+ childWithExternalID("child-present", "nt-parent#file#present", "ds-1"),
+ childWithExternalID("child-gone", "nt-parent#file#gone", "ds-1"),
}}
ks := &sweepFakeKS{repo: repo}
s := &DataSourceService{knowledgeService: ks}
@@ -232,6 +260,30 @@ func TestIngestItem_SubtreeKeepPreservesPresentChild(t *testing.T) {
}
}
+func TestIngestItem_SubtreeSweepSkipsOtherDataSourceChildren(t *testing.T) {
+ repo := &sweepFakeRepo{prefixReturn: []*types.Knowledge{
+ childWithExternalID("own-child", "nt-parent#file#gone", "ds-1"),
+ childWithExternalID("other-ds-child", "nt-parent#file#gone", "ds-other"),
+ }}
+ ks := &sweepFakeKS{repo: repo}
+ s := &DataSourceService{knowledgeService: ks}
+
+ ds := &types.DataSource{ID: "ds-1", Type: "feishu", TenantID: 7, KnowledgeBaseID: "kb-1"}
+ item := &types.FetchedItem{
+ ExternalID: "nt-parent",
+ Content: []byte("# hello\n"),
+ FileName: "parent.md",
+ ReplacesSubtree: true,
+ }
+
+ if _, err := s.ingestItem(context.Background(), ds, item, nil); err != nil {
+ t.Fatalf("ingestItem error: %v", err)
+ }
+ if len(ks.deleted) != 1 || ks.deleted[0] != "own-child" {
+ t.Fatalf("must sweep only this data source's children, deleted = %+v", ks.deleted)
+ }
+}
+
// TestIngestItem_NoSweepWhenFlagUnset verifies a normal item (ReplacesSubtree
// false) never triggers the subtree prefix query — the sweep is opt-in.
func TestIngestItem_NoSweepWhenFlagUnset(t *testing.T) {
diff --git a/internal/types/datasource.go b/internal/types/datasource.go
index 613092cf6..a1ba855cd 100644
--- a/internal/types/datasource.go
+++ b/internal/types/datasource.go
@@ -431,6 +431,10 @@ type SyncResult struct {
// Items that failed
Failed int `json:"failed"`
+ // Deleted items whose KB deletion failed (a subset of Failed). Past the
+ // connector cursor, so normally only a later full sync retries them.
+ DeletionFailed int `json:"deletion_failed,omitempty"`
+
// Per-item failure samples (capped), shown in the sync-log UI.
Errors []SyncItemError `json:"errors,omitempty"`
diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go
index 064002e6f..b8179351c 100644
--- a/internal/types/interfaces/knowledge.go
+++ b/internal/types/interfaces/knowledge.go
@@ -317,6 +317,16 @@ type KnowledgeRepository interface {
// FindByMetadataKeyPrefix finds knowledge items whose metadata[key] starts
// with the given prefix. Used to sweep an external node's attachment sub-items.
FindByMetadataKeyPrefix(ctx context.Context, tenantID uint64, kbID string, key string, prefix string) ([]*types.Knowledge, error)
+ // FindByDataSourceExternalID finds a knowledge item owned by one data source
+ // and identified by the source's external item ID.
+ FindByDataSourceExternalID(
+ ctx context.Context, tenantID uint64, kbID, dataSourceID, externalID string,
+ ) (*types.Knowledge, error)
+ // HardDeleteKnowledge physically removes a row after DeleteKnowledge's soft-delete
+ // cascade. Sync-internal deletions use this so rows never become tombstones.
+ HardDeleteKnowledge(ctx context.Context, tenantID uint64, id string) error
+ // HardDeleteKnowledgeList is the batch counterpart of HardDeleteKnowledge.
+ HardDeleteKnowledgeList(ctx context.Context, tenantID uint64, ids []string) error
// SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (own + shared).
SearchKnowledgeInScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error)
// ListIDsByTagIDs returns all knowledge IDs that have any of the specified tag IDs (OR semantics).
diff --git a/scripts/git-hooks/common.sh b/scripts/git-hooks/common.sh
new file mode 100755
index 000000000..8db8a60ed
--- /dev/null
+++ b/scripts/git-hooks/common.sh
@@ -0,0 +1,229 @@
+#!/usr/bin/env bash
+# Shared helpers for WeKnora git hooks (mirrors .github/workflows and PR checklist).
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+
+hook_skip() {
+ [[ "${SKIP_HOOKS:-}" == "1" ]]
+}
+
+log_step() {
+ printf '→ %s\n' "$*"
+}
+
+log_ok() {
+ printf '✓ %s\n' "$*"
+}
+
+log_fail() {
+ printf '✗ %s\n' "$*" >&2
+}
+
+# File types we expect hand-edited in PRs (skip sample-data / generated blobs).
+WHITESPACE_PATHSPECS=(
+ '*.go'
+ '*.ts' '*.tsx' '*.vue' '*.js' '*.mjs'
+ '*.yaml' '*.yml' '*.json'
+ '*.sh' '*.sql'
+ 'Makefile'
+ 'frontend/package.json'
+ 'frontend/package-lock.json'
+)
+
+# Best-effort fetch so merge-base matches CI (origin/main).
+ensure_origin_main() {
+ git -C "$ROOT" fetch origin main --quiet 2>/dev/null || true
+}
+
+merge_base() {
+ ensure_origin_main
+ local base
+ base="$(git -C "$ROOT" merge-base HEAD origin/main 2>/dev/null || true)"
+ if [[ -n "$base" ]]; then
+ printf '%s\n' "$base"
+ return
+ fi
+ base="$(git -C "$ROOT" merge-base HEAD main 2>/dev/null || true)"
+ if [[ -n "$base" ]]; then
+ printf '%s\n' "$base"
+ return
+ fi
+ git -C "$ROOT" rev-parse HEAD~1
+}
+
+# Prefer the open PR's base SHA (matches GitHub CI diff) when gh is available.
+pr_diff_base_ref() {
+ ensure_origin_main
+ if command -v gh >/dev/null 2>&1; then
+ local base_sha
+ base_sha="$(gh pr view --json baseRefOid --jq .baseRefOid 2>/dev/null || true)"
+ if [[ -n "$base_sha" && "$base_sha" != "null" ]]; then
+ printf '%s\n' "$base_sha"
+ return
+ fi
+ fi
+ if git -C "$ROOT" rev-parse --verify origin/main >/dev/null 2>&1; then
+ printf '%s\n' "origin/main"
+ return
+ fi
+ printf '%s\n' "main"
+}
+
+check_whitespace() {
+ log_step "git diff --check (source files)"
+ if [[ "${1:-}" == "--cached" ]]; then
+ if git -C "$ROOT" diff --cached --quiet -- "${WHITESPACE_PATHSPECS[@]}"; then
+ log_ok "no staged source changes to check"
+ return 0
+ fi
+ git -C "$ROOT" diff --check --cached -- "${WHITESPACE_PATHSPECS[@]}"
+ else
+ if git -C "$ROOT" diff --quiet "$@" -- "${WHITESPACE_PATHSPECS[@]}"; then
+ log_ok "no changed source files to check"
+ return 0
+ fi
+ git -C "$ROOT" diff --check "$@" -- "${WHITESPACE_PATHSPECS[@]}"
+ fi
+ log_ok "no whitespace errors"
+}
+
+check_gofmt_files() {
+ local mode="$1" # check | write
+ shift
+ local -a files=("$@")
+ if [[ ${#files[@]} -gt 0 ]]; then
+ local -a existing=()
+ local f rel
+ for f in "${files[@]}"; do
+ if [[ -f "$f" ]]; then
+ existing+=("$f")
+ continue
+ fi
+ rel="${f#"$ROOT"/}"
+ if [[ -f "$ROOT/$rel" ]]; then
+ existing+=("$ROOT/$rel")
+ fi
+ done
+ files=("${existing[@]}")
+ fi
+ [[ ${#files[@]} -gt 0 ]] || return 0
+
+ local unformatted
+ if [[ "$mode" == "write" ]]; then
+ log_step "gofmt (auto-format staged Go files)"
+ gofmt -w "${files[@]}"
+ # Re-stage formatted files.
+ git -C "$ROOT" add -- "${files[@]}"
+ log_ok "gofmt applied"
+ return 0
+ fi
+
+ log_step "gofmt (check)"
+ unformatted="$(gofmt -l "${files[@]}")"
+ if [[ -n "$unformatted" ]]; then
+ log_fail "the following Go files are not gofmt-formatted:"
+ printf '%s\n' "$unformatted" >&2
+ log_fail "run: gofmt -w <files> (or commit again after pre-commit auto-format)"
+ return 1
+ fi
+ log_ok "gofmt"
+}
+
+collect_go_packages_from_files() {
+ local -a files=("$@")
+ local f dir pkg
+ local -a pkgs=()
+ for f in "${files[@]}"; do
+ [[ "$f" == *.go ]] || continue
+ dir="$(dirname "$f")"
+ pkg="$(cd "$ROOT/$dir" && go list . 2>/dev/null)" || continue
+ pkgs+=("$pkg")
+ done
+ if [[ ${#pkgs[@]} -eq 0 ]]; then
+ return 0
+ fi
+ printf '%s\n' "${pkgs[@]}" | sort -u
+}
+
+run_golangci_if_available() {
+ local from_rev="$1"
+ if ! command -v golangci-lint >/dev/null 2>&1; then
+ log_step "golangci-lint not installed; skip (install: https://golangci-lint.run)"
+ return 0
+ fi
+ log_step "golangci-lint run --new-from-rev=$from_rev ./..."
+ (
+ cd "$ROOT"
+ golangci-lint run --new-from-rev="$from_rev" ./...
+ )
+ log_ok "golangci-lint"
+}
+
+run_full_app_vet() {
+ # Mirrors .github/workflows/app.yml: vet every app package (excl. docreader).
+ log_step "go vet (all app packages, like CI)"
+ (
+ cd "$ROOT"
+ local -a pkgs=()
+ while IFS= read -r line; do
+ [[ -n "$line" ]] && pkgs+=("$line")
+ done < <(go list ./... | grep -v '/docreader/' || true)
+ go vet "${pkgs[@]}"
+ )
+ log_ok "go vet"
+}
+
+run_go_test_packages() {
+ local -a pkgs=("$@")
+ if [[ ${#pkgs[@]} -eq 0 ]]; then
+ log_step "no changed Go packages; skip go test"
+ return 0
+ fi
+ if [[ "${HOOK_SKIP_TEST:-}" == "1" ]]; then
+ log_step "HOOK_SKIP_TEST=1; skip go test"
+ return 0
+ fi
+ log_step "go test (${#pkgs[@]} changed package(s))"
+ (
+ cd "$ROOT"
+ go test -count=1 "${pkgs[@]}"
+ )
+ log_ok "go test"
+}
+
+run_app_vet_test() {
+ run_full_app_vet
+ run_go_test_packages "$@"
+}
+
+run_cli_checks() {
+ log_step "cli: go vet && go test"
+ (
+ cd "$ROOT/cli"
+ go vet ./...
+ if [[ "${HOOK_SKIP_TEST:-}" == "1" ]]; then
+ log_step "HOOK_SKIP_TEST=1; skip cli go test"
+ else
+ go test -count=1 ./...
+ fi
+ )
+ log_ok "cli checks"
+}
+
+run_frontend_checks() {
+ log_step "frontend: verify (test, type-check, build)"
+ "$ROOT/scripts/verify_frontend_pr.sh"
+ log_ok "frontend checks"
+}
+
+paths_match_prefix() {
+ local prefix="$1"
+ shift
+ local p
+ for p in "$@"; do
+ [[ "$p" == "$prefix"* ]] && return 0
+ done
+ return 1
+}
diff --git a/scripts/git-hooks/pre-commit b/scripts/git-hooks/pre-commit
new file mode 100755
index 000000000..cc7ba3a88
--- /dev/null
+++ b/scripts/git-hooks/pre-commit
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# Fast checks on staged files (PR checklist + gofmt). Mirrors app.yml formatting gate.
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+# shellcheck source=scripts/git-hooks/common.sh
+source "$ROOT/scripts/git-hooks/common.sh"
+
+if hook_skip; then
+ exit 0
+fi
+
+cd "$ROOT"
+
+log_step "pre-commit"
+
+check_whitespace --cached
+
+staged_go=()
+while IFS= read -r line; do
+ [[ -n "$line" ]] && staged_go+=("$line")
+done < <(git diff --cached --name-only --diff-filter=ACMR -- '*.go' ':!cli/**' || true)
+
+if [[ ${#staged_go[@]} -gt 0 ]]; then
+ go_files=()
+ for f in "${staged_go[@]}"; do
+ go_files+=("$ROOT/$f")
+ done
+ check_gofmt_files write "${go_files[@]}"
+
+ if command -v golangci-lint >/dev/null 2>&1; then
+ # Lint only what differs from HEAD (staged + unstaged in those packages).
+ run_golangci_if_available HEAD
+ fi
+fi
+
+log_ok "pre-commit passed"
diff --git a/scripts/git-hooks/pre-push b/scripts/git-hooks/pre-push
new file mode 100755
index 000000000..0580687f2
--- /dev/null
+++ b/scripts/git-hooks/pre-push
@@ -0,0 +1,98 @@
+#!/usr/bin/env bash
+# Pre-push checks aligned with CI (.github/workflows/app.yml, frontend.yml, cli.yml).
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+# shellcheck source=scripts/git-hooks/common.sh
+source "$ROOT/scripts/git-hooks/common.sh"
+
+if hook_skip; then
+ exit 0
+fi
+
+cd "$ROOT"
+
+remote="${1:-origin}"
+while read -r _local_ref local_sha remote_ref remote_sha; do
+ if [[ "$local_sha" =~ ^0+$ ]]; then
+ continue
+ fi
+
+ log_step "pre-push ($remote ${remote_ref#refs/heads/})"
+
+ ensure_origin_main
+ pr_ref="$(pr_diff_base_ref)"
+ pr_tip="$local_sha"
+ pr_diff="${pr_ref}...${pr_tip}"
+ lint_from_rev="$pr_ref"
+
+ if [[ "$remote_sha" =~ ^0+$ ]]; then
+ push_start="$(git -C "$ROOT" merge-base "$pr_ref" "$local_sha")"
+ push_range="${push_start}..${local_sha}"
+ log_step "new branch; PR diff ${pr_ref}...${local_sha:0:12}"
+ else
+ if [[ "$remote_sha" == "$local_sha" ]]; then
+ log_ok "pre-push: nothing new to push"
+ continue
+ fi
+ push_range="${remote_sha}..${local_sha}"
+ log_step "pushing ${remote_sha:0:12}..${local_sha:0:12}; PR diff ${pr_ref}...${local_sha:0:12}"
+ fi
+
+ check_whitespace "$push_range"
+
+ pr_changed=()
+ while IFS= read -r line; do
+ [[ -n "$line" ]] && pr_changed+=("$line")
+ done < <(git diff --name-only --diff-filter=ACMR "$pr_diff" || true)
+
+ if [[ ${#pr_changed[@]} -eq 0 ]]; then
+ log_ok "pre-push: no PR diff changes"
+ continue
+ fi
+
+ pr_changed_go=()
+ while IFS= read -r line; do
+ [[ -n "$line" ]] && pr_changed_go+=("$line")
+ done < <(git diff --name-only --diff-filter=ACMR "$pr_diff" -- '*.go' ':!cli/**' || true)
+
+ if [[ ${#pr_changed_go[@]} -gt 0 ]]; then
+ go_files=()
+ for f in "${pr_changed_go[@]}"; do
+ go_files+=("$ROOT/$f")
+ done
+ check_gofmt_files check "${go_files[@]}"
+
+ run_golangci_if_available "$lint_from_rev"
+
+ pkgs=()
+ while IFS= read -r line; do
+ [[ -n "$line" ]] && pkgs+=("$line")
+ done < <(collect_go_packages_from_files "${pr_changed_go[@]}")
+
+ filtered=()
+ for pkg in "${pkgs[@]}"; do
+ [[ "$pkg" == *"/docreader/"* ]] && continue
+ filtered+=("$pkg")
+ done
+
+ run_full_app_vet
+ run_go_test_packages "${filtered[@]}"
+
+ log_step "go build ./cmd/server"
+ go build ./cmd/server
+ log_ok "go build ./cmd/server"
+ fi
+
+ if paths_match_prefix "cli/" "${pr_changed[@]}"; then
+ run_cli_checks
+ fi
+ if paths_match_prefix "frontend/" "${pr_changed[@]}"; then
+ run_frontend_checks
+ fi
+
+ log_ok "pre-push passed"
+done
+
+exit 0
diff --git a/scripts/install-git-hooks.sh b/scripts/install-git-hooks.sh
new file mode 100755
index 000000000..0b2e950ab
--- /dev/null
+++ b/scripts/install-git-hooks.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Install WeKnora git hooks (core.hooksPath -> scripts/git-hooks).
+#
+# Usage (from repo root):
+# ./scripts/install-git-hooks.sh
+#
+# Bypass hooks for one command:
+# SKIP_HOOKS=1 git commit ...
+# SKIP_HOOKS=1 git push ...
+#
+# Skip slow go test on pre-push:
+# HOOK_SKIP_TEST=1 git push ...
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+HOOKS_DIR="$ROOT/scripts/git-hooks"
+
+if [[ ! -d "$HOOKS_DIR" ]]; then
+ echo "hooks directory not found: $HOOKS_DIR" >&2
+ exit 1
+fi
+
+chmod +x "$HOOKS_DIR"/common.sh "$HOOKS_DIR"/pre-commit "$HOOKS_DIR"/pre-push
+
+git -C "$ROOT" config core.hooksPath scripts/git-hooks
+
+echo "Installed git hooks -> scripts/git-hooks"
+echo " pre-commit: whitespace, gofmt (auto-fix), golangci-lint (if installed)"
+echo " pre-push: PR gofmt + full go vet/build (like CI); scoped go test"
+echo ""
+echo "Optional: SKIP_HOOKS=1 or HOOK_SKIP_TEST=1 — see script header."