From fe636432d0fde33027dcf3b830a4b97251f68455 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B0=E6=96=B0?= <15813426+pixelxin@user.noreply.gitee.com> Date: Mon, 27 Apr 2026 17:03:56 +0800 Subject: [PATCH] init --- .env.example | 16 + .gitignore | 75 + EXTERNAL-INTEGRATION-API.md | 423 +++ README.md | 210 ++ backend/Dockerfile | 20 + backend/alembic.ini | 36 + backend/app/__init__.py | 1 + backend/app/api/__init__.py | 1 + backend/app/api/admin.py | 454 +++ backend/app/api/auth.py | 23 + backend/app/api/departments.py | 32 + backend/app/api/files.py | 490 +++ backend/app/api/groups.py | 757 +++++ backend/app/api/integration.py | 378 +++ backend/app/api/jobs.py | 47 + backend/app/config.py | 112 + backend/app/database.py | 31 + backend/app/deps.py | 94 + backend/app/main.py | 50 + backend/app/models.py | 243 ++ backend/app/schemas.py | 105 + backend/app/security.py | 74 + backend/app/serializers.py | 171 ++ backend/app/services/bootstrap_service.py | 84 + backend/app/services/dify_service.py | 442 +++ backend/app/services/queue_service.py | 82 + backend/app/services/storage_service.py | 92 + backend/app/services/watchdog_service.py | 495 +++ backend/app/tasks.py | 462 +++ backend/app/time_utils.py | 7 + backend/app/user_policy.py | 8 + backend/app/watchdog_cli.py | 91 + backend/backend.env.example | 17 + backend/edkb_system/__init__.py | 1 + backend/edkb_system/cli.py | 167 ++ backend/edkb_system/config.py | 53 + backend/edkb_system/contracts.py | 54 + backend/edkb_system/controller.py | 893 ++++++ backend/edkb_system/discovery.py | 22 + backend/edkb_system/skills/__init__.py | 1 + backend/edkb_system/skills/chunk.py | 90 + backend/edkb_system/skills/clean.py | 2017 +++++++++++++ backend/edkb_system/skills/common.py | 244 ++ backend/edkb_system/skills/doc_to_pdf.py | 83 + backend/edkb_system/skills/export.py | 567 ++++ .../edkb_system/skills/flow_reconstruct.py | 142 + backend/edkb_system/skills/intake_router.py | 419 +++ backend/edkb_system/skills/loader_csv.py | 39 + backend/edkb_system/skills/loader_docx.py | 1962 ++++++++++++ backend/edkb_system/skills/loader_excel.py | 89 + backend/edkb_system/skills/loader_pdf.py | 250 ++ backend/edkb_system/skills/loader_pptx.py | 478 +++ backend/edkb_system/skills/ocr.py | 97 + backend/edkb_system/skills/postcheck.py | 192 ++ backend/edkb_system/skills/quality_gate.py | 23 + backend/edkb_system/skills/table_linearize.py | 55 + backend/edkb_system/skills/word_bridge.py | 249 ++ backend/migrations/env.py | 49 + .../versions/20260327_0001_initial.py | 150 + .../20260328_0002_dify_model_defaults.py | 31 + .../20260329_0003_roles_and_group_access.py | 37 + ...0004_departments_and_unique_super_admin.py | 85 + ...20260329_0005_remove_default_department.py | 93 + ...1_0006_group_name_unique_per_department.py | 27 + ...20260401_0007_groups_require_department.py | 41 + backend/requirements.txt | 28 + backend/tests/conftest.py | 114 + backend/tests/test_access_control_api.py | 119 + backend/tests/test_admin_api.py | 699 +++++ backend/tests/test_config_settings.py | 24 + backend/tests/test_files_api.py | 238 ++ backend/tests/test_integration_api.py | 266 ++ backend/tests/test_tasks.py | 937 ++++++ backend/tests/test_uploads.py | 660 ++++ backend/tests/test_watchdog_service.py | 254 ++ backend/worker.py | 14 + docker-compose.yml | 101 + frontend/Dockerfile | 13 + frontend/index.html | 13 + frontend/nginx.conf | 43 + frontend/package-lock.json | 2668 +++++++++++++++++ frontend/package.json | 29 + frontend/postcss.config.js | 7 + frontend/src/App.vue | 5 + frontend/src/components/DifyHealthDialog.vue | 359 +++ .../src/components/DifySettingsDialog.vue | 281 ++ frontend/src/components/LocaleSwitcher.vue | 26 + frontend/src/components/StatusPill.vue | 28 + frontend/src/components/ToastStack.vue | 28 + frontend/src/lib/api.ts | 76 + frontend/src/lib/auth.ts | 39 + frontend/src/lib/i18n.ts | 1038 +++++++ frontend/src/main.ts | 7 + frontend/src/router/index.ts | 45 + frontend/src/style.css | 395 +++ frontend/src/views/AdminView.vue | 769 +++++ frontend/src/views/LoginView.vue | 100 + frontend/src/views/WorkspaceView.vue | 2051 +++++++++++++ frontend/src/vite-env.d.ts | 2 + frontend/tailwind.config.js | 24 + frontend/tsconfig.app.json | 13 + frontend/tsconfig.json | 8 + frontend/tsconfig.node.json | 11 + frontend/vite.config.d.ts | 2 + frontend/vite.config.js | 24 + frontend/vite.config.ts | 26 + ops/watchdog/dify_watchdog.py | 534 ++++ ops/watchdog/install-watchdog-cron.sh | 21 + .../2026-03-28-dify-diff-and-group-ux-plan.md | 61 + ...026-03-28-local-server-integration-plan.md | 82 + ...3-28-product-ui-and-deploy-hygiene-plan.md | 69 + .../2026-03-28-stability-hardening-plan.md | 91 + ...8-workspace-productization-round-2-plan.md | 19 + ...-03-29-access-control-and-admin-ui-plan.md | 39 + ...ment-permission-and-admin-refactor-plan.md | 51 + .../2026-03-29-dify-self-healing-plan.md | 24 + ...on-console-and-department-workflow-plan.md | 55 + ...nvert-watchdog-and-integration-api-plan.md | 24 + project-governance/skills/README.md | 35 + project-governance/skills/install-skills.ps1 | 73 + .../snapshots/frontend-design/LICENSE.txt | 22 + .../skills/snapshots/frontend-design/SKILL.md | 110 + .../nextjs-app-router-starter/README.md | 8 + .../nextjs-app-router-starter/app/globals.css | 69 + .../nextjs-app-router-starter/app/layout.tsx | 18 + .../app/page.module.css | 244 ++ .../nextjs-app-router-starter/app/page.tsx | 99 + .../components/AssistantRail.module.css | 217 ++ .../components/AssistantRail.tsx | 167 ++ .../DesignPanel.module.css | 198 ++ .../react-component-starter/DesignPanel.tsx | 52 + .../assets/vanilla-starter/index.html | 131 + .../assets/vanilla-starter/script.js | 13 + .../assets/vanilla-starter/style.css | 425 +++ .../references/aesthetic-playbook.md | 49 + .../references/ai-native-ui-patterns.md | 42 + .../references/anti-patterns.md | 23 + .../references/implementation-patterns.md | 56 + .../references/react-next-best-practices.md | 25 + .../skills/snapshots/skill-vetter/SKILL.md | 138 + .../skills/snapshots/skill-vetter/_meta.json | 11 + .../skills/snapshots/superpowers/SKILL.md | 978 ++++++ .../skills/snapshots/superpowers/_meta.json | 17 + project-governance/skills/sources.json | 22 + project-governance/skills/vetting-report.md | 47 + .../workflow/DEVELOPMENT-WORKFLOW.md | 32 + .../workflow/smoke-download-source.bin | Bin 0 -> 9728 bytes project-governance/workflow/smoke-download.md | 2 + project-governance/workflow/smoke-input.doc | Bin 0 -> 9728 bytes project-governance/workflow/smoke-input.docx | Bin 0 -> 5232 bytes project-governance/workflow/smoke-input.txt | 6 + start-local-backend.ps1 | 22 + start-local-dev.ps1 | 37 + start-local-frontend.ps1 | 16 + 154 files changed, 30381 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 EXTERNAL-INTEGRATION-API.md create mode 100644 README.md create mode 100644 backend/Dockerfile create mode 100644 backend/alembic.ini create mode 100644 backend/app/__init__.py create mode 100644 backend/app/api/__init__.py create mode 100644 backend/app/api/admin.py create mode 100644 backend/app/api/auth.py create mode 100644 backend/app/api/departments.py create mode 100644 backend/app/api/files.py create mode 100644 backend/app/api/groups.py create mode 100644 backend/app/api/integration.py create mode 100644 backend/app/api/jobs.py create mode 100644 backend/app/config.py create mode 100644 backend/app/database.py create mode 100644 backend/app/deps.py create mode 100644 backend/app/main.py create mode 100644 backend/app/models.py create mode 100644 backend/app/schemas.py create mode 100644 backend/app/security.py create mode 100644 backend/app/serializers.py create mode 100644 backend/app/services/bootstrap_service.py create mode 100644 backend/app/services/dify_service.py create mode 100644 backend/app/services/queue_service.py create mode 100644 backend/app/services/storage_service.py create mode 100644 backend/app/services/watchdog_service.py create mode 100644 backend/app/tasks.py create mode 100644 backend/app/time_utils.py create mode 100644 backend/app/user_policy.py create mode 100644 backend/app/watchdog_cli.py create mode 100644 backend/backend.env.example create mode 100644 backend/edkb_system/__init__.py create mode 100644 backend/edkb_system/cli.py create mode 100644 backend/edkb_system/config.py create mode 100644 backend/edkb_system/contracts.py create mode 100644 backend/edkb_system/controller.py create mode 100644 backend/edkb_system/discovery.py create mode 100644 backend/edkb_system/skills/__init__.py create mode 100644 backend/edkb_system/skills/chunk.py create mode 100644 backend/edkb_system/skills/clean.py create mode 100644 backend/edkb_system/skills/common.py create mode 100644 backend/edkb_system/skills/doc_to_pdf.py create mode 100644 backend/edkb_system/skills/export.py create mode 100644 backend/edkb_system/skills/flow_reconstruct.py create mode 100644 backend/edkb_system/skills/intake_router.py create mode 100644 backend/edkb_system/skills/loader_csv.py create mode 100644 backend/edkb_system/skills/loader_docx.py create mode 100644 backend/edkb_system/skills/loader_excel.py create mode 100644 backend/edkb_system/skills/loader_pdf.py create mode 100644 backend/edkb_system/skills/loader_pptx.py create mode 100644 backend/edkb_system/skills/ocr.py create mode 100644 backend/edkb_system/skills/postcheck.py create mode 100644 backend/edkb_system/skills/quality_gate.py create mode 100644 backend/edkb_system/skills/table_linearize.py create mode 100644 backend/edkb_system/skills/word_bridge.py create mode 100644 backend/migrations/env.py create mode 100644 backend/migrations/versions/20260327_0001_initial.py create mode 100644 backend/migrations/versions/20260328_0002_dify_model_defaults.py create mode 100644 backend/migrations/versions/20260329_0003_roles_and_group_access.py create mode 100644 backend/migrations/versions/20260329_0004_departments_and_unique_super_admin.py create mode 100644 backend/migrations/versions/20260329_0005_remove_default_department.py create mode 100644 backend/migrations/versions/20260401_0006_group_name_unique_per_department.py create mode 100644 backend/migrations/versions/20260401_0007_groups_require_department.py create mode 100644 backend/requirements.txt create mode 100644 backend/tests/conftest.py create mode 100644 backend/tests/test_access_control_api.py create mode 100644 backend/tests/test_admin_api.py create mode 100644 backend/tests/test_config_settings.py create mode 100644 backend/tests/test_files_api.py create mode 100644 backend/tests/test_integration_api.py create mode 100644 backend/tests/test_tasks.py create mode 100644 backend/tests/test_uploads.py create mode 100644 backend/tests/test_watchdog_service.py create mode 100644 backend/worker.py create mode 100644 docker-compose.yml create mode 100644 frontend/Dockerfile create mode 100644 frontend/index.html create mode 100644 frontend/nginx.conf create mode 100644 frontend/package-lock.json create mode 100644 frontend/package.json create mode 100644 frontend/postcss.config.js create mode 100644 frontend/src/App.vue create mode 100644 frontend/src/components/DifyHealthDialog.vue create mode 100644 frontend/src/components/DifySettingsDialog.vue create mode 100644 frontend/src/components/LocaleSwitcher.vue create mode 100644 frontend/src/components/StatusPill.vue create mode 100644 frontend/src/components/ToastStack.vue create mode 100644 frontend/src/lib/api.ts create mode 100644 frontend/src/lib/auth.ts create mode 100644 frontend/src/lib/i18n.ts create mode 100644 frontend/src/main.ts create mode 100644 frontend/src/router/index.ts create mode 100644 frontend/src/style.css create mode 100644 frontend/src/views/AdminView.vue create mode 100644 frontend/src/views/LoginView.vue create mode 100644 frontend/src/views/WorkspaceView.vue create mode 100644 frontend/src/vite-env.d.ts create mode 100644 frontend/tailwind.config.js create mode 100644 frontend/tsconfig.app.json create mode 100644 frontend/tsconfig.json create mode 100644 frontend/tsconfig.node.json create mode 100644 frontend/vite.config.d.ts create mode 100644 frontend/vite.config.js create mode 100644 frontend/vite.config.ts create mode 100644 ops/watchdog/dify_watchdog.py create mode 100644 ops/watchdog/install-watchdog-cron.sh create mode 100644 project-governance/plans/2026-03-28-dify-diff-and-group-ux-plan.md create mode 100644 project-governance/plans/2026-03-28-local-server-integration-plan.md create mode 100644 project-governance/plans/2026-03-28-product-ui-and-deploy-hygiene-plan.md create mode 100644 project-governance/plans/2026-03-28-stability-hardening-plan.md create mode 100644 project-governance/plans/2026-03-28-workspace-productization-round-2-plan.md create mode 100644 project-governance/plans/2026-03-29-access-control-and-admin-ui-plan.md create mode 100644 project-governance/plans/2026-03-29-department-permission-and-admin-refactor-plan.md create mode 100644 project-governance/plans/2026-03-29-dify-self-healing-plan.md create mode 100644 project-governance/plans/2026-03-29-permission-console-and-department-workflow-plan.md create mode 100644 project-governance/plans/2026-04-01-convert-watchdog-and-integration-api-plan.md create mode 100644 project-governance/skills/README.md create mode 100644 project-governance/skills/install-skills.ps1 create mode 100644 project-governance/skills/snapshots/frontend-design/LICENSE.txt create mode 100644 project-governance/skills/snapshots/frontend-design/SKILL.md create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/README.md create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/globals.css create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/layout.tsx create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.module.css create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.tsx create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.module.css create mode 100644 project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.tsx create mode 100644 project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.module.css create mode 100644 project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.tsx create mode 100644 project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/index.html create mode 100644 project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/script.js create mode 100644 project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/style.css create mode 100644 project-governance/skills/snapshots/frontend-design/references/aesthetic-playbook.md create mode 100644 project-governance/skills/snapshots/frontend-design/references/ai-native-ui-patterns.md create mode 100644 project-governance/skills/snapshots/frontend-design/references/anti-patterns.md create mode 100644 project-governance/skills/snapshots/frontend-design/references/implementation-patterns.md create mode 100644 project-governance/skills/snapshots/frontend-design/references/react-next-best-practices.md create mode 100644 project-governance/skills/snapshots/skill-vetter/SKILL.md create mode 100644 project-governance/skills/snapshots/skill-vetter/_meta.json create mode 100644 project-governance/skills/snapshots/superpowers/SKILL.md create mode 100644 project-governance/skills/snapshots/superpowers/_meta.json create mode 100644 project-governance/skills/sources.json create mode 100644 project-governance/skills/vetting-report.md create mode 100644 project-governance/workflow/DEVELOPMENT-WORKFLOW.md create mode 100644 project-governance/workflow/smoke-download-source.bin create mode 100644 project-governance/workflow/smoke-download.md create mode 100644 project-governance/workflow/smoke-input.doc create mode 100644 project-governance/workflow/smoke-input.docx create mode 100644 project-governance/workflow/smoke-input.txt create mode 100644 start-local-backend.ps1 create mode 100644 start-local-dev.ps1 create mode 100644 start-local-frontend.ps1 diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..50a444d2 --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +JWT_SECRET=change-me +DATABASE_BACKEND=postgres +DATABASE_URL= +SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db +POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning +PUBLIC_BASE_URL=http://127.0.0.1:8891 +DIFY_BASE_URL=https://api.dify.ai/v1 +DIFY_API_KEY= +INTEGRATION_API_KEY=change-me-internal +INTEGRATION_DOWNLOAD_SECRET=change-me-download-signing-secret +DEFAULT_ADMIN_USERNAME=admin +DEFAULT_ADMIN_PASSWORD=admin123456 +TASK_EXECUTION_MODE=rq +DIFY_SYNC_MAX_RETRIES=4 +DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300 +DIFY_SYNC_COOLDOWN_SECONDS=60 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..753254da --- /dev/null +++ b/.gitignore @@ -0,0 +1,75 @@ +# ========================= +# Secrets / env +# ========================= +.env +.env.* +!.env.example +backend.env +backend.env.* +!backend.env.example +*.key +*.pem +*secret* +*token* + +# ========================= +# OS / IDE +# ========================= +.DS_Store +Thumbs.db +.idea/ +.vscode/ + +# ========================= +# Python +# ========================= +__pycache__/ +*.pyc +*.pyo +*.pyd +.pytest_cache/ +.venv/ +venv/ +python/ + +# ========================= +# Node +# ========================= +frontend/node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# ========================= +# Build outputs +# ========================= +frontend/dist/ +dist/ +build/ +out/ +target/ + +# ========================= +# Runtime temp/logs +# ========================= +tmp_run/ +*.log + +# ========================= +# Databases (不要提交测试数据/本地库) +# ========================= +*.db +*.sqlite +*.sqlite3 + +# ========================= +# Archives / bundles (不要提交打包产物) +# ========================= +*.zip +*.tar.gz +*.tgz + +# ========================= +# Optional: staging deploy output (如果是生成物就忽略) +# ========================= +.deploy-stage/ \ No newline at end of file diff --git a/EXTERNAL-INTEGRATION-API.md b/EXTERNAL-INTEGRATION-API.md new file mode 100644 index 00000000..1add4124 --- /dev/null +++ b/EXTERNAL-INTEGRATION-API.md @@ -0,0 +1,423 @@ +# 文档清洗系统对外接口文档 + +版本:`v1` + +适用对象:需要根据 Dify 文档信息反查文档清洗系统中的本地原文件,并获取原文件下载地址的外部系统。 + +## 1. 接入目标 + +外部系统通常已经从 Dify 拿到了某条知识库文档的以下信息: + +- `dataset_id` +- `remote_document_id` + +其中: + +- `dataset_id` = Dify 知识库 id +- `remote_document_id` = Dify 文档 id +- `remote_document_id` 应从 Dify 文档接口返回的 `id` 获取,不是 batch id + +外部系统可使用本文档提供的接口,反查这条 Dify 文档在文档清洗系统中的本地映射关系,并获取原文件下载地址。 + +## 2. 接入原则 + +- 外部系统应由服务端调用查询接口,不要在前端浏览器中保存 `INTEGRATION_API_KEY`。 +- 查询接口需要鉴权。 +- 文件下载地址为短期签名链接,前端可直接打开,不需要再附带鉴权 key。 +- 下载链接过期后,应重新调用查询接口获取新的下载链接。 + +## 3. 基础信息 + +- Base URL:`http://192.168.100.230:8891` +- 鉴权方式:HTTP Header +- Header 名称:`X-Integration-Key` + +请求示例: + +```http +X-Integration-Key: <平台分配的对接密钥> +``` + +说明: + +- 该 key 由文档清洗系统平台方提供。 +- 外部系统请将该 key 保存在自身服务端配置中,不要下发到前端页面。 + +## 4. 推荐对接流程 + +### 4.1 外部系统后端流程 + +1. 从 Dify 获取目标文档的: + - `dataset_id` + - `remote_document_id` +2. 调用文档清洗系统查询接口: + - `GET /api/integration/dify-file` +3. 解析返回结果,读取: + - 文件名 + - 所属知识库 + - 所属部门 + - 原文件下载地址 +4. 将需要展示的字段返回给自身前端页面。 +5. 前端用户点击下载时,直接打开 `source_download_url`。 + +### 4.2 外部系统前端流程 + +1. 调用外部系统自己的后端接口。 +2. 展示外部系统后端返回的文件信息。 +3. 用户点击“下载原文件”时,直接访问 `source_download_url`。 +4. 如果下载失败且提示链接失效,由外部系统后端重新查询一次并返回新链接。 + +## 5. 核心接口:按 Dify 文档反查本地文件 + +- 方法:`GET` +- 路径:`/api/integration/dify-file` + +### 5.1 请求参数 + +| 参数名 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `dataset_id` | `string` | 是 | Dify 知识库 id | +| `remote_document_id` | `string` | 是 | Dify 文档 id,应取自 Dify 文档接口返回的 `id` | + +### 5.2 请求头 + +```http +X-Integration-Key: <平台分配的对接密钥> +``` + +### 5.3 请求示例 + +```bash +curl -H "X-Integration-Key: YOUR_KEY" \ + "http://192.168.100.230:8891/api/integration/dify-file?dataset_id=7a9f158c-90f5-478a-8956-2732c72a7546&remote_document_id=abcd1234" +``` + +### 5.4 成功响应示例 + +```json +{ + "queried_at": "2026-04-01T12:00:00+08:00", + "document_id": 14, + "knowledge_base": { + "id": 3, + "name": "03 质量", + "department_id": 2, + "department_name": "质量部", + "dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546" + }, + "title": "假期控制程序1", + "source_filename": "假期控制程序1.doc", + "source_ext": ".doc", + "file_name": "假期控制程序1.doc", + "version_id": 22, + "version_no": 1, + "convert_status": "success", + "sync_status": "synced", + "uploaded_at": "2026-04-01T11:32:10+08:00", + "converted_at": "2026-04-01T11:33:05+08:00", + "download_url_expires_at": "2026-04-01T12:15:00+08:00", + "source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx", + "markdown_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=md&token=yyyyy", + "markdown_download_url_expires_at": "2026-04-01T12:15:00+08:00", + "markdown_public_url": "http://192.168.100.230:8891/storage/markdown/group_0003/document_000014/v001/document.md", + "dify": { + "dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546", + "remote_document_id": "abcd1234", + "status": "synced", + "last_indexing_status": "completed", + "last_synced_at": "2026-04-01T11:34:20+08:00" + } +} +``` + +## 6. 核心接口:批量按 Dify 文档反查本地文件 + +- 方法:`POST` +- 路径:`/api/integration/dify-files/resolve` + +### 6.1 请求头 + +```http +X-Integration-Key: <平台分配的对接密钥> +Content-Type: application/json +``` + +### 6.2 请求体 + +```json +{ + "items": [ + { + "dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546", + "remote_document_id": "abcd1234" + }, + { + "dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546", + "remote_document_id": "efgh5678" + } + ] +} +``` + +说明: + +- `items` 为待查询列表。 +- 建议每次批量查询控制在 `100` 条以内。 +- 返回结果会按请求里的输入顺序返回。 +- `remote_document_id` 应取自 Dify 文档接口返回的 `id`,不是 batch id。 + +### 6.3 请求示例 + +```bash +curl -X POST \ + -H "X-Integration-Key: YOUR_KEY" \ + -H "Content-Type: application/json" \ + -d "{\"items\":[{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"abcd1234\"},{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"efgh5678\"}]}" \ + "http://192.168.100.230:8891/api/integration/dify-files/resolve" +``` + +### 6.4 成功响应示例 + +```json +{ + "data": [ + { + "request": { + "dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546", + "remote_document_id": "abcd1234" + }, + "found": true, + "document": { + "document_id": 14, + "source_filename": "假期控制程序1.doc", + "source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx", + "knowledge_base": { + "id": 3, + "name": "03 质量", + "department_id": 2, + "department_name": "质量部", + "dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546" + }, + "dify": { + "dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546", + "remote_document_id": "abcd1234" + } + } + }, + { + "request": { + "dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546", + "remote_document_id": "efgh5678" + }, + "found": false, + "document": null + } + ] +} +``` + +### 6.5 返回说明 + +- `request` + - 原样回显本次输入的查询条件 +- `found` + - 是否命中文档清洗系统中的本地映射 +- `document` + - 命中时返回完整文档信息 + - 未命中时返回 `null` + +## 6.6 版本映射说明 + +- 反查接口返回的是“命中的同步版本”,不是盲目返回当前最新版本。 +- 如果同一文档本地后来又上传了新版本,但新版本尚未同步到 Dify,接口仍会返回旧的已同步版本。 +- 如果某条文档从未同步到 Dify,则不会存在可用的 `remote_document_id` 映射。 + +## 7. 返回字段说明 + +### 7.1 顶层字段 + +| 字段名 | 类型 | 说明 | +|---|---|---| +| `queried_at` | `string` | 本次查询结果生成时间 | +| `document_id` | `integer` | 文档清洗系统内部文档 id | +| `title` | `string` | 文档清洗系统内部文档标题 | +| `source_filename` | `string` | 原始上传文件名 | +| `source_ext` | `string` | 原文件扩展名 | +| `file_name` | `string` | 与 `source_filename` 相同,便于统一读取 | +| `version_id` | `integer` | 当前版本 id | +| `version_no` | `integer` | 当前版本号 | +| `convert_status` | `string` | 转换状态,如 `queued` `running` `success` `failed` | +| `sync_status` | `string` | 同步状态,如 `unsynced` `syncing` `synced` `sync_failed` | +| `uploaded_at` | `string` | 原文件上传时间 | +| `converted_at` | `string` | Markdown 转换完成时间 | +| `download_url_expires_at` | `string` | 原文件下载链接过期时间 | +| `source_download_url` | `string` | 原文件签名下载链接 | +| `markdown_download_url` | `string` | Markdown 签名下载链接 | +| `markdown_download_url_expires_at` | `string` | Markdown 下载链接过期时间 | +| `markdown_public_url` | `string` | Markdown 在本系统内的访问地址 | +| `knowledge_base` | `object` | 所属知识库信息 | +| `dify` | `object` | Dify 映射信息 | + +### 7.2 `knowledge_base` 字段说明 + +| 字段名 | 类型 | 说明 | +|---|---|---| +| `id` | `integer` | 文档清洗系统内部知识库 id | +| `name` | `string` | 知识库名称 | +| `department_id` | `integer` \| `null` | 所属部门 id | +| `department_name` | `string` \| `null` | 所属部门名称 | +| `dify_dataset_id` | `string` \| `null` | 该知识库在 Dify 对应的 dataset id | + +### 7.3 `dify` 字段说明 + +| 字段名 | 类型 | 说明 | +|---|---|---| +| `dataset_id` | `string` | Dify 知识库 id | +| `remote_document_id` | `string` | Dify 文档 id | +| `status` | `string` | 本地记录的最近同步状态 | +| `last_indexing_status` | `string` | Dify 最近索引状态 | +| `last_synced_at` | `string` \| `null` | 最近同步完成时间 | + +## 8. 下载说明 + +### 8.1 下载接口 + +外部系统通常不需要自己拼下载接口,直接使用查询结果中的: + +- `source_download_url` +- `markdown_download_url` + +即可。 + +### 8.2 下载接口格式 + +- 方法:`GET` +- 路径:`/api/integration/download` + +请求参数: + +| 参数名 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `version_id` | `integer` | 是 | 文档清洗系统内部版本 id | +| `kind` | `string` | 是 | `source` 或 `md` | +| `token` | `string` | 是 | 签名令牌 | + +示例: + +```text +http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx +``` + +### 8.3 下载接口说明 + +- 下载接口不需要再附带 `X-Integration-Key`。 +- 这是一个短期签名链接,可直接在浏览器打开。 +- 链接过期后,请重新调用查询接口获取新的下载链接。 + +## 9. 可选查询接口 + +如果外部系统不是从 Dify 文档开始反查,也可使用以下接口。 + +### 9.1 获取知识库列表 + +- 方法:`GET` +- 路径:`/api/integration/knowledge-bases` + +查询参数: + +| 参数名 | 必填 | 说明 | +|---|---|---| +| `department_id` | 否 | 按部门筛选 | +| `q` | 否 | 按知识库名称模糊搜索 | + +请求示例: + +```bash +curl -H "X-Integration-Key: YOUR_KEY" \ + "http://192.168.100.230:8891/api/integration/knowledge-bases" +``` + +### 9.2 获取文件列表 + +- 方法:`GET` +- 路径:`/api/integration/files` + +查询参数: + +| 参数名 | 必填 | 说明 | +|---|---|---| +| `knowledge_base_id` | 否 | 按知识库筛选 | +| `department_id` | 否 | 按部门筛选 | +| `file_name` | 否 | 按文件名或标题模糊搜索 | + +请求示例: + +```bash +curl -H "X-Integration-Key: YOUR_KEY" \ + "http://192.168.100.230:8891/api/integration/files?knowledge_base_id=3" +``` + +### 9.3 获取单个文件详情 + +- 方法:`GET` +- 路径:`/api/integration/files/{file_id}` + +请求示例: + +```bash +curl -H "X-Integration-Key: YOUR_KEY" \ + "http://192.168.100.230:8891/api/integration/files/14" +``` + +## 10. 状态码说明 + +### 10.1 查询接口 + +| 状态码 | 说明 | +|---|---| +| `200` | 查询成功 | +| `401` | 鉴权失败,`X-Integration-Key` 无效 | +| `404` | 未找到对应的本地文件映射 | +| `503` | 接口未配置完成,通常为平台未配置 `INTEGRATION_API_KEY` | + +### 10.2 下载接口 + +| 状态码 | 说明 | +|---|---| +| `200` | 下载成功 | +| `401` | 签名无效或已过期 | +| `404` | 文件不存在 | +| `409` | 请求 `md`,但 Markdown 尚未生成 | + +## 11. 对接建议 + +- 外部系统前端不要直接调用查询接口。 +- 外部系统后端负责: + - 保存 integration key + - 调用查询接口 + - 将结果整理后返回给自身前端 +- 外部系统前端负责: + - 展示文件信息 + - 使用 `source_download_url` 直接下载原文件 + +## 12. 最小接入流程 + +1. 外部系统从 Dify 获取: + - `dataset_id` + - `remote_document_id` +2. 外部系统后端调用: + - `GET /api/integration/dify-file?dataset_id=...&remote_document_id=...` +3. 从返回结果中读取: + - `source_filename` + - `source_download_url` + - `knowledge_base.name` + - `knowledge_base.department_name` +4. 将上述字段展示给用户。 +5. 用户点击下载时,直接打开 `source_download_url`。 + +## 13. 对接注意事项 + +- `source_download_url` 为短期签名链接,不是永久地址。 +- `source_download_url` 可直接用于下载,无需再次附加鉴权 key。 +- 若链接过期,外部系统应重新调用查询接口获取新链接。 +- 若返回 `404`,表示该 Dify 文档在文档清洗系统中没有本地文件映射。 diff --git a/README.md b/README.md new file mode 100644 index 00000000..61f6acdf --- /dev/null +++ b/README.md @@ -0,0 +1,210 @@ +# Document Cleaning + +Independent internal web system for document cleaning, version tracking, batch download, and manual sync into Dify datasets. + +## Stack + +- Frontend: Vue 3, Vite, Tailwind, Uppy +- Backend: FastAPI, SQLAlchemy, Alembic +- Queue: RQ + Redis +- Worker runtime: Python + LibreOffice +- Database: SQLite or PostgreSQL (configurable) + +## Project Layout + +- `frontend/`: Vue workspace UI +- `backend/`: FastAPI API, RQ worker tasks, vendored `edkb_system` +- `project-governance/`: Codex skill governance, workflow docs, and audit snapshots +- `docker-compose.yml`: full deployment stack for `192.168.100.230` + +## Local Run + +1. Copy `.env.example` to `.env` and fill in `DIFY_API_KEY`. +2. Start services: + +```bash +docker compose up --build -d +``` + +3. Open `http://localhost:8891`. + +Default login comes from `.env`: + +- username: `admin` +- password: `admin123456` + +## Local Direct Run Without Docker + +Use this mode on a workstation that does not have Docker available. + +1. Copy `backend/backend.env.example` to `backend/.env`. +2. Choose a database mode in `backend/.env`: + +```env +# Option A: local SQLite +DATABASE_BACKEND=sqlite +DATABASE_URL= +SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db + +# Option B: local/shared PostgreSQL +DATABASE_BACKEND=postgres +DATABASE_URL= +POSTGRES_DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db +``` + +`DATABASE_URL` remains supported as a direct override. If it is set, it takes priority over `DATABASE_BACKEND`. + +3. Keep `TASK_EXECUTION_MODE=sync` for local smoke tests. +4. You can now use the project-local Python runtime under `python/`. + +5. Start the backend: + +```bash +cd backend +python -m alembic upgrade head +python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 +``` + +6. Start the frontend in another terminal: + +```bash +cd frontend +npm run dev -- --host 127.0.0.1 --port 5174 +``` + +7. Open `http://127.0.0.1:5174`. + +Convenience scripts in the project root: + +```powershell +.\start-local-backend.ps1 +.\start-local-frontend.ps1 +.\start-local-dev.ps1 +``` + +Notes: + +- `start-local-backend.ps1` runs Alembic first, then starts FastAPI. +- `start-local-frontend.ps1` starts the Vite dev server. +- `start-local-dev.ps1` starts both in background and writes logs to `tmp_run/`. + +Notes: + +- In local direct mode, queue tasks run inline through the API process. +- Real Dify sync still requires a valid `DIFY_API_KEY`. +- Server deployment should continue using `docker compose`. + +## Production Deployment + +The compose file is already configured for the planned entrypoint: + +- `http://192.168.100.230:8891` + +Deploy on the target server with: + +```bash +docker compose --env-file .env up --build -d +``` + +Database selection is now configurable through `.env`: + +```env +# Option A: use the compose PostgreSQL service +DATABASE_BACKEND=postgres +DATABASE_URL= +POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning + +# Option B: use SQLite +DATABASE_BACKEND=sqlite +DATABASE_URL= +SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db + +# Option C: explicit override +DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db +``` + +Notes: + +- `DATABASE_URL` has the highest priority. +- When running inside Docker, `localhost` points to the container itself. A host-level PostgreSQL service must use a reachable host name or IP instead of `localhost`. + +Current deployment path on the server: + +- `/home/inspur/tools/document-cleaning` + +## Core Flows + +- Upload one or many files into a group. +- Deduplicate by `SHA-256` within the same group. +- Create a new version when title matches but content changed. +- Convert in the background through RQ workers. +- Download original files or generated markdown individually or in bulk. +- Manually sync selected documents to Dify. +- Auto-create a Dify dataset on first sync for each group. + +## Dify Integration + +- Group name maps to one Dify dataset. +- Sync uses cleaned markdown text, not the raw original file. +- Existing logical documents are updated in Dify instead of duplicated. +- Dataset defaults are managed in the admin console. + +## External Integration API + +Use this when another internal site needs to query knowledge-base/file relationships without direct database access. + +1. Set `INTEGRATION_API_KEY` in `.env`. +2. Optionally set `INTEGRATION_DOWNLOAD_SECRET` to a dedicated signing secret. If omitted, the app falls back to `JWT_SECRET`. +3. Call the query API with `X-Integration-Key: `. + +Recommended pattern: + +- External site backend stores `INTEGRATION_API_KEY` +- Backend calls this system's query API +- Query response returns short-lived signed download URLs +- External site frontend opens those signed URLs directly without carrying the integration key + +Example endpoints: + +- `GET /api/integration/knowledge-bases` +- `GET /api/integration/files?knowledge_base_id=123` +- `GET /api/integration/files?file_name=report` +- `GET /api/integration/files/456` +- `GET /api/integration/dify-file?dataset_id=&remote_document_id=` +- `GET /api/integration/download?version_id=&kind=source&token=` +- `GET /api/integration/download?version_id=&kind=md&token=` + +## Dify Sync Throttling + +To avoid overloading Dify when many files are pushed at once, sync jobs now support retry backoff and a short global cooldown gate. + +Relevant `.env` knobs: + +```env +DIFY_SYNC_MAX_RETRIES=4 +DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300 +DIFY_SYNC_COOLDOWN_SECONDS=60 +``` + +Behavior: + +- Retryable Dify congestion errors such as `too many clients already` are not marked failed immediately. +- The sync job is re-queued with backoff. +- A short global cooldown prevents the next sync jobs from hammering Dify during the same congestion window. + +## Tests + +Backend: + +```bash +cd backend +python -m pytest tests -q +``` + +Frontend: + +```bash +cd frontend +npm install +npm run build +``` diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 00000000..638c1fdc --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,20 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 + +WORKDIR /app + +RUN apt-get update \ + && apt-get install -y --no-install-recommends libreoffice fonts-noto-cjk curl \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt + +COPY . /app + +EXPOSE 8000 + +CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"] + diff --git a/backend/alembic.ini b/backend/alembic.ini new file mode 100644 index 00000000..37bda93a --- /dev/null +++ b/backend/alembic.ini @@ -0,0 +1,36 @@ +[alembic] +script_location = migrations +sqlalchemy.url = sqlite:///./document_cleaning.db + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = console +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s + diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 00000000..996cbda8 --- /dev/null +++ b/backend/app/__init__.py @@ -0,0 +1 @@ +"""Document Cleaning backend package.""" diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 00000000..9111a56a --- /dev/null +++ b/backend/app/api/__init__.py @@ -0,0 +1 @@ +from app.api import admin, auth, files, groups, integration, jobs diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py new file mode 100644 index 00000000..e51b1705 --- /dev/null +++ b/backend/app/api/admin.py @@ -0,0 +1,454 @@ +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy import func, or_ +from sqlalchemy.orm import Session, joinedload + +from app.config import get_settings +from app.database import get_db +from app.deps import require_admin +from app.models import Department, Document, DocumentVersion, Group, Job, SystemSetting, User, UserDepartmentAccess, UserGroupAccess +from app.schemas import ( + DepartmentCreateRequest, + DepartmentDeleteRequest, + DepartmentUpdateRequest, + SettingsUpdateRequest, + UserCreateRequest, + UserUpdateRequest, +) +from app.security import hash_password +from app.serializers import serialize_department, serialize_settings, serialize_user +from app.services.dify_service import DifyError, DifyService +from app.services.watchdog_service import ( + local_convert_health_summary, + local_sync_health_summary, + read_watchdog_snapshot, + recover_stale_converts, + recover_stale_syncs, +) +from app.user_policy import PRIMARY_SUPER_ADMIN_USERNAME, is_primary_super_admin_username + + +router = APIRouter(prefix="/admin", tags=["admin"]) + + +def _replace_user_department_access(db: Session, *, user_id: int, primary_department_id: int | None, department_ids: list[int]) -> None: + existing_accesses = db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user_id).all() + for access in existing_accesses: + db.delete(access) + db.flush() + requested_ids = sorted({item for item in department_ids if item is not None} | ({primary_department_id} if primary_department_id is not None else set())) + if not requested_ids: + return + existing_ids = {row[0] for row in db.query(Department.id).filter(Department.id.in_(requested_ids)).all()} + missing_ids = sorted(set(requested_ids) - existing_ids) + if missing_ids: + raise HTTPException( + status_code=404, + detail=f"Department(s) not found: {', '.join(map(str, missing_ids))}", + ) + for department_id in requested_ids: + if department_id == primary_department_id: + continue + db.add(UserDepartmentAccess(user_id=user_id, department_id=department_id)) + + +def _validate_super_admin_constraints(*, username: str, requested_role: str | None, requested_active: bool | None = None) -> None: + if requested_role == "super_admin" and not is_primary_super_admin_username(username): + raise HTTPException(status_code=400, detail=f"Only {PRIMARY_SUPER_ADMIN_USERNAME} can be a super admin.") + if is_primary_super_admin_username(username): + if requested_role is not None and requested_role != "super_admin": + raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} must remain a super admin.") + if requested_active is False: + raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} cannot be deactivated.") + + +def _department_metrics_query(db: Session): + knowledge_base_counts = ( + db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count")) + .group_by(Group.department_id) + .subquery() + ) + primary_user_counts = ( + db.query( + User.primary_department_id.label("department_id"), + func.count(User.id).label("primary_user_count"), + ) + .group_by(User.primary_department_id) + .subquery() + ) + extra_user_counts = ( + db.query( + UserDepartmentAccess.department_id.label("department_id"), + func.count(UserDepartmentAccess.id).label("extra_user_count"), + ) + .group_by(UserDepartmentAccess.department_id) + .subquery() + ) + return ( + db.query( + Department, + (func.coalesce(primary_user_counts.c.primary_user_count, 0) + func.coalesce(extra_user_counts.c.extra_user_count, 0)).label( + "user_count" + ), + func.coalesce(knowledge_base_counts.c.knowledge_base_count, 0).label("knowledge_base_count"), + ) + .outerjoin(primary_user_counts, primary_user_counts.c.department_id == Department.id) + .outerjoin(extra_user_counts, extra_user_counts.c.department_id == Department.id) + .outerjoin(knowledge_base_counts, knowledge_base_counts.c.department_id == Department.id) + .order_by(Department.name.asc()) + ) + + +def _department_reference_summary(db: Session, department_id: int) -> dict[str, int]: + return { + "knowledge_base_count": db.query(func.count(Group.id)).filter(Group.department_id == department_id).scalar() or 0, + "primary_user_count": db.query(func.count(User.id)).filter(User.primary_department_id == department_id).scalar() or 0, + "extra_user_count": db.query(func.count(UserDepartmentAccess.id)).filter(UserDepartmentAccess.department_id == department_id).scalar() or 0, + } + + +@router.get("/departments") +def list_all_departments(db: Session = Depends(get_db), admin: User = Depends(require_admin)): + rows = _department_metrics_query(db).all() + return { + "data": [ + serialize_department(item, user_count=user_count, knowledge_base_count=knowledge_base_count) + for item, user_count, knowledge_base_count in rows + ] + } + + +@router.post("/departments") +def create_department( + payload: DepartmentCreateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + name = payload.name.strip() + if not name: + raise HTTPException(status_code=400, detail="Department name is required.") + exists = db.query(Department).filter(func.lower(Department.name) == name.lower()).first() + if exists: + raise HTTPException(status_code=409, detail="Department already exists.") + department = Department(name=name, description=payload.description) + db.add(department) + db.commit() + db.refresh(department) + return serialize_department(department) + + +@router.patch("/departments/{department_id}") +def update_department( + department_id: int, + payload: DepartmentUpdateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + department = db.query(Department).filter(Department.id == department_id).first() + if not department: + raise HTTPException(status_code=404, detail="Department not found.") + if payload.name is not None: + name = payload.name.strip() + if not name: + raise HTTPException(status_code=400, detail="Department name is required.") + conflict = ( + db.query(Department) + .filter(func.lower(Department.name) == name.lower(), Department.id != department_id) + .first() + ) + if conflict: + raise HTTPException(status_code=409, detail="Department already exists.") + department.name = name + if payload.description is not None: + department.description = payload.description + db.commit() + db.refresh(department) + return serialize_department(department) + + +@router.delete("/departments/{department_id}") +def delete_department( + department_id: int, + payload: DepartmentDeleteRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + department = db.query(Department).filter(Department.id == department_id).first() + if not department: + raise HTTPException(status_code=404, detail="Department not found.") + + target_department = None + if payload.target_department_id is not None: + if payload.target_department_id == department_id: + raise HTTPException(status_code=400, detail="Migration target must be a different department.") + target_department = db.query(Department).filter(Department.id == payload.target_department_id).first() + if not target_department: + raise HTTPException(status_code=404, detail="Migration target department not found.") + + reference_summary = _department_reference_summary(db, department_id) + has_references = any(reference_summary.values()) + if has_references and target_department is None: + raise HTTPException( + status_code=400, + detail="Department still has knowledge bases or users. Choose another department to migrate first.", + ) + + if target_department is not None: + db.query(Group).filter(Group.department_id == department_id).update( + {Group.department_id: target_department.id}, + synchronize_session=False, + ) + + affected_users = ( + db.query(User) + .options(joinedload(User.department_accesses)) + .filter( + or_( + User.primary_department_id == department_id, + User.department_accesses.any(UserDepartmentAccess.department_id == department_id), + ) + ) + .all() + ) + + for user in affected_users: + if user.primary_department_id == department_id: + user.primary_department_id = target_department.id + migrated_access_ids = [access.department_id for access in user.department_accesses if access.department_id != department_id] + if user.primary_department_id != target_department.id: + migrated_access_ids.append(target_department.id) + _replace_user_department_access( + db, + user_id=user.id, + primary_department_id=user.primary_department_id, + department_ids=migrated_access_ids, + ) + + db.query(Department).filter(Department.id == department_id).delete(synchronize_session=False) + db.commit() + return { + "deleted_department_id": department_id, + "migrated_to_department_id": target_department.id if target_department else None, + **reference_summary, + } + + +@router.get("/users") +def list_users(db: Session = Depends(get_db), admin: User = Depends(require_admin)): + users = ( + db.query(User) + .options(joinedload(User.primary_department), joinedload(User.department_accesses)) + .order_by(User.username.asc()) + .all() + ) + return {"data": [serialize_user(item) for item in users]} + + +@router.post("/users") +def create_user( + payload: UserCreateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + if payload.primary_department_id is None: + raise HTTPException(status_code=400, detail="Primary department is required.") + exists = db.query(User).filter(User.username == payload.username).first() + if exists: + raise HTTPException(status_code=409, detail="Username already exists.") + _validate_super_admin_constraints(username=payload.username, requested_role=payload.role, requested_active=True) + user = User( + username=payload.username, + full_name=payload.full_name, + password_hash=hash_password(payload.password), + role=payload.role, + is_active=True, + primary_department_id=payload.primary_department_id, + ) + db.add(user) + db.flush() + db.refresh(user) + _replace_user_department_access( + db, + user_id=user.id, + primary_department_id=payload.primary_department_id, + department_ids=payload.accessible_department_ids, + ) + db.commit() + db.refresh(user) + return serialize_user(user) + + +@router.patch("/users/{user_id}") +def update_user( + user_id: int, + payload: UserUpdateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + user = db.query(User).options(joinedload(User.department_accesses)).filter(User.id == user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found.") + _validate_super_admin_constraints( + username=user.username, + requested_role=payload.role, + requested_active=payload.is_active, + ) + if payload.full_name is not None: + user.full_name = payload.full_name + if payload.role is not None: + user.role = payload.role + if payload.is_active is not None: + user.is_active = payload.is_active + if payload.password: + user.password_hash = hash_password(payload.password) + + target_primary_department_id = payload.primary_department_id if payload.primary_department_id is not None else user.primary_department_id + if payload.primary_department_id is not None: + user.primary_department_id = payload.primary_department_id + if payload.accessible_department_ids is not None or payload.primary_department_id is not None: + _replace_user_department_access( + db, + user_id=user.id, + primary_department_id=target_primary_department_id, + department_ids=payload.accessible_department_ids or [], + ) + db.commit() + db.refresh(user) + return serialize_user(user) + + +@router.delete("/users/{user_id}") +def delete_user( + user_id: int, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + user = db.query(User).filter(User.id == user_id).first() + if not user: + raise HTTPException(status_code=404, detail="User not found.") + if is_primary_super_admin_username(user.username): + raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} cannot be deleted.") + if user.id == admin.id: + raise HTTPException(status_code=400, detail="You cannot delete your own account.") + + db.query(Group).filter(Group.created_by_id == user_id).update({Group.created_by_id: None}, synchronize_session=False) + db.query(Document).filter(Document.created_by_id == user_id).update({Document.created_by_id: None}, synchronize_session=False) + db.query(DocumentVersion).filter(DocumentVersion.uploader_id == user_id).update( + {DocumentVersion.uploader_id: None}, + synchronize_session=False, + ) + db.query(Job).filter(Job.created_by_id == user_id).update({Job.created_by_id: None}, synchronize_session=False) + db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user_id).delete(synchronize_session=False) + db.query(UserGroupAccess).filter(UserGroupAccess.user_id == user_id).delete(synchronize_session=False) + db.query(User).filter(User.id == user_id).delete(synchronize_session=False) + db.commit() + return {"deleted_user_id": user_id} + + +@router.get("/settings") +def get_settings_row(db: Session = Depends(get_db), admin: User = Depends(require_admin)): + settings_row = db.query(SystemSetting).filter(SystemSetting.id == 1).first() + if not settings_row: + raise HTTPException(status_code=404, detail="Settings not found.") + return serialize_settings(settings_row) + + +@router.get("/dify-models") +def list_dify_models(admin: User = Depends(require_admin)): + try: + dify = DifyService() + embedding_models = dify.list_available_embedding_models() + rerank_models = dify.list_available_rerank_models() + default_embedding_provider, default_embedding_model = dify.resolve_embedding_model_choice() + default_rerank_provider, default_rerank_model = dify.resolve_rerank_model_choice() + except DifyError as exc: + raise HTTPException(status_code=502, detail=str(exc)) from exc + + return { + "embedding_models": [ + {"provider": item.provider, "model": item.model, "label": item.label} + for item in embedding_models + ], + "rerank_models": [ + {"provider": item.provider, "model": item.model, "label": item.label} + for item in rerank_models + ], + "automatic_defaults": { + "embedding_model_provider": default_embedding_provider, + "embedding_model": default_embedding_model, + "reranking_model_provider": default_rerank_provider, + "reranking_model": default_rerank_model, + }, + } + + +@router.get("/dify-health") +def get_dify_health(db: Session = Depends(get_db), admin: User = Depends(require_admin)): + settings = get_settings() + return { + "dify_base_url": settings.dify_base_url, + "dify_api_configured": bool(settings.dify_api_key), + "watchdog_snapshot": read_watchdog_snapshot(settings), + "local_convert_health": local_convert_health_summary( + db, + timeout_seconds=settings.watchdog_stale_convert_timeout_seconds, + orphan_grace_seconds=settings.watchdog_convert_orphan_grace_seconds, + settings=settings, + ), + "local_sync_health": local_sync_health_summary( + db, + timeout_seconds=settings.watchdog_stale_sync_timeout_seconds, + ), + } + + +@router.post("/recover-stale-syncs") +def run_stale_sync_recovery(db: Session = Depends(get_db), admin: User = Depends(require_admin)): + settings = get_settings() + return recover_stale_syncs( + db, + timeout_seconds=settings.watchdog_stale_sync_timeout_seconds, + ) + + +@router.post("/recover-stale-converts") +def run_stale_convert_recovery(db: Session = Depends(get_db), admin: User = Depends(require_admin)): + settings = get_settings() + return recover_stale_converts( + db, + timeout_seconds=settings.watchdog_stale_convert_timeout_seconds, + orphan_grace_seconds=settings.watchdog_convert_orphan_grace_seconds, + settings=settings, + ) + + +@router.patch("/settings") +def update_settings_row( + payload: SettingsUpdateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + settings_row = db.query(SystemSetting).filter(SystemSetting.id == 1).first() + if not settings_row: + raise HTTPException(status_code=404, detail="Settings not found.") + for field in [ + "dify_permission", + "indexing_technique", + "search_method", + "doc_form", + "embedding_model_provider", + "embedding_model", + "reranking_model_provider", + "reranking_model", + "top_k", + "score_threshold_enabled", + ]: + value = getattr(payload, field) + if value is not None: + setattr(settings_row, field, value) + if payload.score_threshold is not None: + settings_row.score_threshold = str(payload.score_threshold) + db.commit() + db.refresh(settings_row) + return serialize_settings(settings_row) diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py new file mode 100644 index 00000000..8e0fc0fb --- /dev/null +++ b/backend/app/api/auth.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.database import get_db +from app.models import User +from app.schemas import LoginRequest, TokenResponse +from app.security import create_access_token, verify_password +from app.serializers import serialize_user + + +router = APIRouter(prefix="/auth", tags=["auth"]) + + +@router.post("/login", response_model=TokenResponse) +def login(payload: LoginRequest, db: Session = Depends(get_db)): + user = db.query(User).filter(User.username == payload.username, User.is_active.is_(True)).first() + if not user or not verify_password(payload.password, user.password_hash): + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials") + token = create_access_token(user.username) + return TokenResponse(access_token=token, user=serialize_user(user)) + diff --git a/backend/app/api/departments.py b/backend/app/api/departments.py new file mode 100644 index 00000000..63f2a245 --- /dev/null +++ b/backend/app/api/departments.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from fastapi import APIRouter, Depends +from sqlalchemy import func +from sqlalchemy.orm import Session + +from app.database import get_db +from app.deps import accessible_department_ids, get_current_user +from app.models import Department, Group, User +from app.serializers import serialize_department + + +router = APIRouter(prefix="/departments", tags=["departments"]) + + +@router.get("") +def list_departments(db: Session = Depends(get_db), user: User = Depends(get_current_user)): + department_ids = accessible_department_ids(db, user) + group_counts = ( + db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count")) + .group_by(Group.department_id) + .subquery() + ) + query = ( + db.query(Department, func.coalesce(group_counts.c.knowledge_base_count, 0).label("knowledge_base_count")) + .outerjoin(group_counts, group_counts.c.department_id == Department.id) + .order_by(Department.name.asc()) + ) + if department_ids is not None: + query = query.filter(Department.id.in_(department_ids or [-1])) + rows = query.all() + return {"data": [serialize_department(item, knowledge_base_count=count) for item, count in rows]} diff --git a/backend/app/api/files.py b/backend/app/api/files.py new file mode 100644 index 00000000..148e8896 --- /dev/null +++ b/backend/app/api/files.py @@ -0,0 +1,490 @@ +from __future__ import annotations + +import shutil +import uuid +from datetime import date +from pathlib import Path + +from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile +from fastapi.responses import FileResponse +from sqlalchemy import func +from sqlalchemy.orm import Session, joinedload + +from app.config import get_settings +from app.database import get_db +from app.deps import accessible_group_ids, ensure_group_access, get_current_user +from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, User +from app.schemas import BatchDownloadRequest, BatchSyncRequest +from app.serializers import current_version, serialize_document, serialize_job, serialize_version +from app.services.queue_service import get_queue +from app.services.storage_service import build_zip, remove_path_if_exists, sha256_file, version_dir + + +router = APIRouter(prefix="/files", tags=["files"]) +settings = get_settings() +MAX_BATCH_UPLOAD_FILES = 500 + + +def _group_scope_filter(db: Session, user: User): + group_ids = accessible_group_ids(db, user) + return None if group_ids is None else (group_ids or [-1]) + + +def _get_document_for_user(db: Session, user: User, file_id: int) -> Document | None: + query = ( + db.query(Document) + .options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + .filter(Document.id == file_id, Document.is_deleted.is_(False)) + ) + group_ids = _group_scope_filter(db, user) + if group_ids is not None: + query = query.filter(Document.group_id.in_(group_ids)) + return query.first() + + +def _create_job( + db: Session, + *, + job_type: str, + created_by_id: int, + group_id: int, + document_id: int, + version_id: int, + payload: dict | None = None, +) -> Job: + job = Job( + id=str(uuid.uuid4()), + job_type=job_type, + status="queued", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=created_by_id, + payload=payload or {}, + ) + db.add(job) + db.commit() + db.refresh(job) + return job + + +def _enqueue(job: Job, task_name: str, version_id: int, db: Session) -> Job: + return _enqueue_args(job, task_name, db, version_id) + + +def _enqueue_args(job: Job, task_name: str, db: Session, *task_args) -> Job: + queue = get_queue() + rq_job = queue.enqueue(task_name, job.id, *task_args) + job.queue_job_id = rq_job.id + db.commit() + db.refresh(job) + return job + + +def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None: + if not path_value: + return None + raw_target = Path(path_value) + data_root = settings.data_root.resolve(strict=False) + if raw_target.is_absolute(): + target = raw_target + else: + resolved_raw = raw_target.resolve(strict=False) + target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target + if parent: + target = target.parent + resolved = target.resolve(strict=False) + if not resolved.is_relative_to(data_root): + return None + return resolved + + +def _cleanup_document_storage(document: Document) -> None: + targets: set[Path] = set() + for version in document.versions: + for candidate in ( + _resolve_storage_target(version.source_path, parent=True), + _resolve_storage_target(version.md_path, parent=True), + _resolve_storage_target(version.asset_dir), + ): + if candidate is not None: + targets.add(candidate) + + for target in sorted(targets, key=lambda item: len(item.parts), reverse=True): + remove_path_if_exists(target) + + +@router.post("/upload") +async def upload_files( + group_id: int = Form(...), + files: list[UploadFile] = File(default_factory=list), + file: UploadFile | None = File(None), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + ensure_group_access(db, user, group_id) + group = db.query(Group).filter(Group.id == group_id).first() + if not group: + raise HTTPException(status_code=404, detail="Group not found.") + + incoming = list(files) + if file is not None: + incoming.append(file) + if not incoming: + raise HTTPException(status_code=400, detail="No files uploaded.") + if len(incoming) > MAX_BATCH_UPLOAD_FILES: + raise HTTPException( + status_code=400, + detail=f"Batch upload accepts at most {MAX_BATCH_UPLOAD_FILES} files at a time.", + ) + + created: list[dict] = [] + duplicates: list[dict] = [] + + for upload in incoming: + tmp_dir = settings.data_root / "tmp" / "uploads" + tmp_dir.mkdir(parents=True, exist_ok=True) + tmp_path = tmp_dir / f"{uuid.uuid4()}_{Path(upload.filename).name}" + with tmp_path.open("wb") as handle: + while True: + chunk = await upload.read(1024 * 1024) + if not chunk: + break + handle.write(chunk) + digest = sha256_file(tmp_path) + ext = Path(upload.filename).suffix.lower() + title = Path(upload.filename).stem + + duplicate_version = ( + db.query(DocumentVersion) + .join(Document, Document.id == DocumentVersion.document_id) + .filter( + Document.group_id == group.id, + Document.is_deleted.is_(False), + DocumentVersion.source_sha256 == digest, + ) + .first() + ) + if duplicate_version: + duplicates.append( + { + "filename": upload.filename, + "document_id": duplicate_version.document_id, + "version_id": duplicate_version.id, + "reason": "same_sha256_in_group", + } + ) + tmp_path.unlink(missing_ok=True) + continue + + document = ( + db.query(Document) + .options(joinedload(Document.versions)) + .filter( + Document.group_id == group.id, + func.lower(Document.title) == title.lower(), + Document.is_deleted.is_(False), + ) + .first() + ) + if document is None: + document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + version_no = 1 + else: + for item in document.versions: + if item.is_current: + item.is_current = False + db.commit() + version_no = (document.versions[0].version_no + 1) if document.versions else 1 + + sync_status = "unsynced" + prior_sync = ( + db.query(DifySyncRecord) + .join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id) + .filter(DocumentVersion.document_id == document.id, DifySyncRecord.status == "synced") + .first() + ) + if prior_sync: + sync_status = "stale" + + source_dir = version_dir("original", group.id, document.id, version_no) + source_dir.mkdir(parents=True, exist_ok=True) + final_source = source_dir / Path(upload.filename).name + shutil.move(str(tmp_path), str(final_source)) + + version = DocumentVersion( + document_id=document.id, + version_no=version_no, + is_current=True, + source_filename=Path(upload.filename).name, + source_ext=ext, + source_path=str(final_source), + source_sha256=digest, + file_size=final_source.stat().st_size, + uploader_id=user.id, + convert_status="queued", + sync_status=sync_status, + ) + db.add(version) + db.commit() + db.refresh(version) + + job = _create_job( + db, + job_type="convert", + created_by_id=user.id, + group_id=group.id, + document_id=document.id, + version_id=version.id, + payload={"filename": upload.filename}, + ) + _enqueue(job, "app.tasks.run_convert_job", version.id, db) + created.append( + { + "document_id": document.id, + "version_id": version.id, + "job": serialize_job(job), + } + ) + + return {"created": created, "duplicates": duplicates} + + +@router.get("/group/{group_id}") +def list_group_files( + group_id: int, + q: str | None = None, + status: str | None = None, + sync_status: str | None = None, + file_type: str | None = None, + uploaded_from: str | None = None, + uploaded_to: str | None = None, + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + ensure_group_access(db, user, group_id) + query = ( + db.query(Document) + .options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + .filter(Document.group_id == group_id, Document.is_deleted.is_(False)) + .order_by(Document.updated_at.desc()) + ) + documents = query.all() + filtered: list[Document] = [] + uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None + uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None + for document in documents: + version = current_version(document) + if version is None: + continue + version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None + if q and q.lower() not in document.title.lower(): + continue + if status and version.convert_status != status: + continue + if sync_status and version.sync_status != sync_status: + continue + if file_type and version.source_ext != file_type: + continue + if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date): + continue + if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date): + continue + filtered.append(document) + return {"data": [serialize_document(document) for document in filtered]} + + +@router.get("/{file_id}") +def get_file(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)): + document = _get_document_for_user(db, user, file_id) + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + payload = serialize_document(document) + payload["versions"] = [serialize_version(item) for item in document.versions] + return payload + + +@router.get("/{file_id}/download") +def download_file( + file_id: int, + kind: str = Query("md"), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + document = _get_document_for_user(db, user, file_id) + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + version = current_version(document) + if not version: + raise HTTPException(status_code=404, detail="No version found.") + + if kind == "source": + path = Path(version.source_path) + filename = version.source_filename + else: + if not version.md_path: + raise HTTPException(status_code=409, detail="Markdown not ready.") + path = Path(version.md_path) + filename = f"{document.title}.md" + if not path.exists(): + raise HTTPException(status_code=404, detail="File missing on disk.") + return FileResponse(path, filename=filename) + + +@router.post("/download-batch") +def batch_download( + payload: BatchDownloadRequest, + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + query = ( + db.query(Document) + .options(joinedload(Document.versions)) + .filter(Document.id.in_(payload.document_ids), Document.is_deleted.is_(False)) + ) + group_ids = _group_scope_filter(db, user) + if group_ids is not None: + query = query.filter(Document.group_id.in_(group_ids)) + documents = query.all() + if not documents: + raise HTTPException(status_code=404, detail="No documents found.") + bundle_id = str(uuid.uuid4()) + bundle_dir = settings.data_root / "tmp" / "downloads" + bundle_path = bundle_dir / f"download_{bundle_id}.zip" + entries: list[tuple[Path, str]] = [] + for document in documents: + version = current_version(document) + if not version: + continue + if payload.kind == "source": + entries.append((Path(version.source_path), version.source_filename)) + else: + if version.md_path: + entries.append((Path(version.md_path), f"{document.title}.md")) + if not entries: + raise HTTPException(status_code=409, detail="No downloadable files available.") + build_zip(entries, bundle_path) + download_date = date.today().strftime("%Y%m%d") + return FileResponse(bundle_path, filename=f"文件下载_{download_date}.zip") + + +@router.post("/{file_id}/retry-convert") +def retry_convert(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)): + document = _get_document_for_user(db, user, file_id) + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + version = current_version(document) + if not version: + raise HTTPException(status_code=404, detail="Version not found.") + job = _create_job( + db, + job_type="convert", + created_by_id=user.id, + group_id=document.group_id, + document_id=document.id, + version_id=version.id, + payload={"retry": True}, + ) + _enqueue(job, "app.tasks.run_convert_job", version.id, db) + return serialize_job(job) + + +@router.post("/{file_id}/sync-dify") +def sync_dify(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)): + document = _get_document_for_user(db, user, file_id) + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + version = current_version(document) + if not version or version.convert_status != "success": + raise HTTPException(status_code=409, detail="Document is not ready for sync.") + if version.sync_status == "synced": + raise HTTPException(status_code=409, detail="Current version is already synced to Dify.") + if version.sync_status == "syncing": + raise HTTPException(status_code=409, detail="Current version is already syncing to Dify.") + version.sync_status = "syncing" + db.commit() + job = _create_job( + db, + job_type="sync", + created_by_id=user.id, + group_id=document.group_id, + document_id=document.id, + version_id=version.id, + payload={"single": True}, + ) + _enqueue(job, "app.tasks.run_sync_job", version.id, db) + return serialize_job(job) + + +@router.post("/sync-dify-batch") +def batch_sync( + payload: BatchSyncRequest, + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + query = db.query(Document).options(joinedload(Document.versions)).filter(Document.id.in_(payload.document_ids)) + group_ids = _group_scope_filter(db, user) + if group_ids is not None: + query = query.filter(Document.group_id.in_(group_ids)) + documents = query.all() + jobs: list[dict] = [] + for document in documents: + if document.is_deleted: + continue + version = current_version(document) + if not version or version.convert_status != "success": + continue + if version.sync_status in {"synced", "syncing"}: + continue + version.sync_status = "syncing" + db.commit() + job = _create_job( + db, + job_type="sync", + created_by_id=user.id, + group_id=document.group_id, + document_id=document.id, + version_id=version.id, + payload={"batch": True}, + ) + _enqueue(job, "app.tasks.run_sync_job", version.id, db) + jobs.append(serialize_job(job)) + return {"data": jobs} + + +@router.delete("/{file_id}") +def delete_file( + file_id: int, + delete_dify: bool = Query(False), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + document = _get_document_for_user(db, user, file_id) + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + + version = current_version(document) + original_title = document.title + document.is_deleted = True + document.title = f"{document.title}__deleted__{document.id}" + db.commit() + try: + job = _create_job( + db, + job_type="delete", + created_by_id=user.id, + group_id=document.group_id, + document_id=document.id, + version_id=version.id if version else None, + payload={"delete_dify": delete_dify}, + ) + _enqueue_args(job, "app.tasks.run_delete_document_job", db, document.id) + except Exception: + document.is_deleted = False + document.title = original_title + db.commit() + raise + return {"deleted": True} diff --git a/backend/app/api/groups.py b/backend/app/api/groups.py new file mode 100644 index 00000000..3a0f40a7 --- /dev/null +++ b/backend/app/api/groups.py @@ -0,0 +1,757 @@ +from __future__ import annotations + +from datetime import date +from pathlib import Path + +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy import func, or_ +from sqlalchemy.orm import Session, joinedload + +from app.config import get_settings +from app.database import get_db +from app.deps import ( + accessible_department_ids, + accessible_group_ids, + ensure_department_access, + ensure_group_access, + get_current_user, + require_admin, +) +from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, SystemSetting, User +from app.schemas import DifyImportRequest, GroupCreateRequest, GroupUpdateRequest +from app.serializers import current_version, serialize_document, serialize_group +from app.services.dify_service import DifyError, DifyService +from app.services.storage_service import public_storage_url, remove_path_if_exists, sha256_file, version_dir +from app.time_utils import utc_now +import requests + + +router = APIRouter(prefix="/groups", tags=["groups"]) +settings = get_settings() + + +def _scoped_group_ids(db: Session, user: User) -> list[int] | None: + return accessible_group_ids(db, user) + + +def _scoped_department_ids(db: Session, user: User) -> list[int] | None: + return accessible_department_ids(db, user) + + +def _scoped_groups_query(db: Session, user: User, *, department_id: int | None = None): + query = db.query(Group) + group_ids = _scoped_group_ids(db, user) + if group_ids is not None: + query = query.filter(Group.id.in_(group_ids or [-1])) + if department_id is not None: + query = query.filter(Group.department_id == department_id) + return query + + +def _document_name_key(name: str) -> str: + trimmed = (name or "").strip().lower() + candidate = Path(trimmed) + return candidate.stem if candidate.suffix else trimmed + + +def _normalized_document_title(name: str) -> str: + candidate = Path((name or "").strip()) + return candidate.stem if candidate.suffix else candidate.name + + +def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None: + if not path_value: + return None + raw_target = Path(path_value) + data_root = settings.data_root.resolve(strict=False) + if raw_target.is_absolute(): + target = raw_target + else: + resolved_raw = raw_target.resolve(strict=False) + target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target + if parent: + target = target.parent + resolved = target.resolve(strict=False) + if not resolved.is_relative_to(data_root): + return None + return resolved + + +def _cleanup_document_storage(document: Document) -> None: + targets: set[Path] = set() + for version in document.versions: + for candidate in ( + _resolve_storage_target(version.source_path, parent=True), + _resolve_storage_target(version.md_path, parent=True), + _resolve_storage_target(version.asset_dir), + ): + if candidate is not None: + targets.add(candidate) + + for target in sorted(targets, key=lambda item: len(item.parts), reverse=True): + remove_path_if_exists(target) + + +def _local_documents_for_group(group: Group) -> dict[str, list[dict]]: + local_docs: dict[str, list[dict]] = {} + for document in group.documents: + if document.is_deleted: + continue + version = current_version(document) + if version is None: + continue + local_docs.setdefault(_document_name_key(document.title), []).append( + { + "document_id": document.id, + "title": document.title, + "source_ext": version.source_ext, + "convert_status": version.convert_status, + "sync_status": version.sync_status, + "remote_document_id": version.sync_records[0].remote_document_id if version.sync_records else None, + } + ) + return local_docs + + +def _remote_documents_for_dataset(dify: DifyService, dataset_id: str | None) -> dict[str, list[dict]]: + if not dataset_id: + return {} + remote_docs: dict[str, list[dict]] = {} + for remote in dify.list_documents(dataset_id=dataset_id): + remote_docs.setdefault(_document_name_key(remote.name), []).append( + { + "document_id": remote.id, + "name": remote.name, + "indexing_status": remote.indexing_status, + "display_status": remote.display_status, + "enabled": remote.enabled, + } + ) + return remote_docs + + +def _diff_status(local_entry: dict | None, remote_entry: dict | None) -> str: + if local_entry and not remote_entry: + return "local_only" + if remote_entry and not local_entry: + return "dify_only" + if ( + (local_entry or {}).get("sync_status") != "synced" + or (remote_entry or {}).get("indexing_status") not in {"completed", "completed_with_warning"} + ): + return "attention" + return "matched" + + +def _build_diff_rows( + *, + knowledge_base_name: str, + dataset_id: str | None, + local_docs: dict[str, list[dict]], + remote_docs: dict[str, list[dict]], + group: Group | None = None, + term: str = "", + include_knowledge_base: bool = False, +) -> list[dict]: + rows: list[dict] = [] + for key in sorted(set(local_docs) | set(remote_docs)): + local_entries = list(local_docs.get(key, [])) + remote_entries = list(remote_docs.get(key, [])) + + local_entries.sort( + key=lambda item: ( + f"{item.get('title') or ''}{item.get('source_ext') or ''}".lower(), + int(item.get("document_id") or 0), + ) + ) + remote_entries.sort( + key=lambda item: ( + (item.get("name") or "").lower(), + str(item.get("document_id") or ""), + ) + ) + + paired_rows: list[tuple[dict | None, dict | None]] = [] + remaining_remote = remote_entries.copy() + + for local_entry in local_entries: + local_full_name = f"{local_entry.get('title') or ''}{local_entry.get('source_ext') or ''}".lower() + match_index = next( + ( + index + for index, remote_entry in enumerate(remaining_remote) + if (remote_entry.get("name") or "").strip().lower() == local_full_name + ), + None, + ) + if match_index is None and remaining_remote: + match_index = 0 + + if match_index is None: + paired_rows.append((local_entry, None)) + else: + paired_rows.append((local_entry, remaining_remote.pop(match_index))) + + paired_rows.extend((None, remote_entry) for remote_entry in remaining_remote) + + for index, (local_entry, remote_entry) in enumerate(paired_rows, start=1): + display_name = (local_entry or {}).get("title") or (remote_entry or {}).get("name") or key + haystacks = [display_name.lower(), knowledge_base_name.lower()] + if term and not any(term in item for item in haystacks): + continue + + row = { + "key": f"{knowledge_base_name}:{key}:{index}" if include_knowledge_base else f"{key}:{index}", + "status": _diff_status(local_entry, remote_entry), + "local": local_entry, + "remote": remote_entry, + "display_name": display_name, + } + if include_knowledge_base: + row["knowledge_base"] = { + "group_id": group.id if group else None, + "name": knowledge_base_name, + "dataset_id": dataset_id, + } + rows.append(row) + return rows + + +def _summarize_diff_rows(rows: list[dict]) -> dict[str, int]: + return { + "matched": sum(1 for row in rows if row["status"] == "matched"), + "local_only": sum(1 for row in rows if row["status"] == "local_only"), + "dify_only": sum(1 for row in rows if row["status"] == "dify_only"), + "attention": sum(1 for row in rows if row["status"] == "attention"), + } + + +def _create_group_from_remote_name(*, db: Session, admin: User, group_name: str) -> Group: + if admin.primary_department_id is None: + raise HTTPException(status_code=400, detail="Admin must belong to a department before importing Dify documents.") + return _create_group_from_remote_name_in_department( + db=db, + admin=admin, + group_name=group_name, + department_id=admin.primary_department_id, + ) + + +def _create_group_from_remote_name_in_department( + *, + db: Session, + admin: User, + group_name: str, + department_id: int, +) -> Group: + defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first() + existing = ( + db.query(Group) + .filter(Group.department_id == department_id, Group.name == group_name) + .first() + ) + if existing: + return existing + group = Group( + name=group_name, + description=None, + department_id=department_id, + created_by_id=admin.id, + indexing_technique=defaults.indexing_technique if defaults else "high_quality", + search_method=defaults.search_method if defaults else "hybrid_search", + doc_form=defaults.doc_form if defaults else "text_model", + top_k=defaults.top_k if defaults else 5, + score_threshold_enabled=defaults.score_threshold_enabled if defaults else True, + score_threshold=defaults.score_threshold if defaults else "0.35", + ) + db.add(group) + db.commit() + db.refresh(group) + return group + + +def _download_remote_upload(upload_file: dict | None) -> tuple[str, bytes] | None: + if not upload_file: + return None + download_url = upload_file.get("download_url") or upload_file.get("url") + if not download_url: + return None + response = requests.get(download_url, timeout=60) + response.raise_for_status() + filename = upload_file.get("name") or "remote-file" + return filename, response.content + + +def _import_dify_document_to_local( + *, + db: Session, + user: User, + dataset_id: str, + remote_document_id: str, + group: Group, +) -> Document: + dify = DifyService() + detail = dify.get_document_detail(dataset_id=dataset_id, document_id=remote_document_id) + remote_name = (detail.get("name") or "").strip() or remote_document_id + title = _normalized_document_title(remote_name) + + existing = ( + db.query(Document) + .options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + .filter( + Document.group_id == group.id, + func.lower(Document.title) == title.lower(), + Document.is_deleted.is_(False), + ) + .first() + ) + if existing: + raise HTTPException(status_code=409, detail="Document already exists locally. Refresh diff and retry.") + + segments = dify.list_document_segments(dataset_id=dataset_id, document_id=remote_document_id) + markdown_text = "\n\n".join(item.content.strip() for item in segments if item.content and item.content.strip()).strip() + if not markdown_text: + raise HTTPException(status_code=409, detail="Remote Dify document has no importable content.") + + document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + version_no = 1 + source_dir = version_dir("original", group.id, document.id, version_no) + markdown_dir = version_dir("markdown", group.id, document.id, version_no) + source_dir.mkdir(parents=True, exist_ok=True) + markdown_dir.mkdir(parents=True, exist_ok=True) + markdown_target = markdown_dir / "document.md" + markdown_target.write_text(markdown_text, encoding="utf-8") + + source_filename = remote_name if Path(remote_name).suffix else f"{remote_name}.md" + source_ext = Path(source_filename).suffix.lower() or ".md" + source_target = source_dir / source_filename + + upload_file = None + try: + upload_file = dify.get_upload_file(dataset_id=dataset_id, document_id=remote_document_id) + except DifyError: + upload_file = None + + downloaded = None + if upload_file: + try: + downloaded = _download_remote_upload(upload_file) + except Exception: + downloaded = None + + if downloaded: + source_filename, source_bytes = downloaded + source_ext = Path(source_filename).suffix.lower() or ".bin" + source_target = source_dir / source_filename + source_target.write_bytes(source_bytes) + else: + source_target.write_text(markdown_text, encoding="utf-8") + source_filename = source_target.name + source_ext = ".md" + + version = DocumentVersion( + document_id=document.id, + version_no=version_no, + is_current=True, + source_filename=source_filename, + source_ext=source_ext, + source_path=str(source_target), + source_sha256=sha256_file(source_target), + md_path=str(markdown_target), + md_public_url=public_storage_url(markdown_target), + asset_dir=None, + file_size=source_target.stat().st_size, + word_count=len(markdown_text.split()), + convert_status="success", + sync_status="synced", + uploader_id=user.id, + uploaded_at=utc_now(), + converted_at=utc_now(), + warnings_json=[{"message": "imported_from_dify"}], + ) + db.add(version) + db.commit() + db.refresh(version) + + sync_record = DifySyncRecord( + version_id=version.id, + dataset_id=dataset_id, + remote_document_id=remote_document_id, + status="synced", + last_indexing_status=detail.get("indexing_status"), + last_synced_at=utc_now(), + error=None, + ) + db.add(sync_record) + if group.dify_dataset_id != dataset_id: + group.dify_dataset_id = dataset_id + db.commit() + db.refresh(document) + return document + + +def _group_name_conflict( + db: Session, + *, + department_id: int | None, + name: str, + exclude_group_id: int | None = None, +) -> bool: + query = db.query(Group).filter(Group.department_id == department_id, Group.name == name) + if exclude_group_id is not None: + query = query.filter(Group.id != exclude_group_id) + return db.query(query.exists()).scalar() + + +@router.get("") +def list_groups( + department_id: int | None = Query(None), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + if department_id is not None: + ensure_department_access(db, user, department_id) + group_ids = _scoped_group_ids(db, user) + document_counts_query = ( + db.query( + Document.group_id.label("group_id"), + func.count(Document.id).label("document_count"), + ) + .filter(Document.is_deleted.is_(False)) + .group_by(Document.group_id) + ) + if group_ids is not None: + document_counts_query = document_counts_query.filter(Document.group_id.in_(group_ids or [-1])) + document_counts = document_counts_query.subquery() + query = db.query( + Group, + func.coalesce(document_counts.c.document_count, 0).label("document_count"), + ).options(joinedload(Group.department)).outerjoin(document_counts, document_counts.c.group_id == Group.id) + if group_ids is not None: + query = query.filter(Group.id.in_(group_ids or [-1])) + if department_id is not None: + query = query.filter(Group.department_id == department_id) + groups = query.order_by(Group.name.asc()).all() + return { + "data": [serialize_group(group, document_count=document_count) for group, document_count in groups] + } + + +@router.get("/summary") +def get_dashboard_summary( + department_id: int | None = Query(None), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + if department_id is not None: + ensure_department_access(db, user, department_id) + group_ids = _scoped_group_ids(db, user) + knowledge_base_query = db.query(Group) + file_query = db.query(Document).filter(Document.is_deleted.is_(False)) + if group_ids is not None: + scoped_filter = group_ids or [-1] + knowledge_base_query = knowledge_base_query.filter(Group.id.in_(scoped_filter)) + file_query = file_query.filter(Document.group_id.in_(scoped_filter)) + if department_id is not None: + knowledge_base_query = knowledge_base_query.filter(Group.department_id == department_id) + file_query = file_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id) + knowledge_base_count = knowledge_base_query.count() + file_count = file_query.count() + running_query = ( + db.query(DocumentVersion) + .join(Document, Document.id == DocumentVersion.document_id) + .filter(Document.is_deleted.is_(False), DocumentVersion.is_current.is_(True)) + .filter( + or_( + DocumentVersion.convert_status.in_(["queued", "running"]), + DocumentVersion.sync_status == "syncing", + ) + ) + ) + if group_ids is not None: + running_query = running_query.filter(Document.group_id.in_(group_ids or [-1])) + if department_id is not None: + running_query = running_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id) + running_count = running_query.count() + return { + "knowledge_base_count": knowledge_base_count, + "file_count": file_count, + "running_count": running_count, + } + + +@router.get("/dify-diff-global") +def get_global_dify_diff( + q: str | None = Query(None), + department_id: int | None = Query(None), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + if department_id is not None: + ensure_department_access(db, user, department_id) + groups_query = ( + db.query(Group) + .options(joinedload(Group.department)) + .options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + ) + group_ids = _scoped_group_ids(db, user) + if group_ids is not None: + groups_query = groups_query.filter(Group.id.in_(group_ids or [-1])) + if department_id is not None: + groups_query = groups_query.filter(Group.department_id == department_id) + groups = groups_query.order_by(Group.name.asc()).all() + dify = DifyService() + datasets = dify.list_datasets() + datasets_by_id = {item.id: item for item in datasets} + datasets_by_name = {item.name: item for item in datasets} + used_dataset_ids: set[str] = set() + term = (q or "").strip().lower() + rows: list[dict] = [] + + for group in groups: + dataset = datasets_by_id.get(group.dify_dataset_id or "") or datasets_by_name.get(group.name) + dataset_id = dataset.id if dataset else group.dify_dataset_id + if dataset: + used_dataset_ids.add(dataset.id) + rows.extend( + _build_diff_rows( + knowledge_base_name=group.name, + dataset_id=dataset_id, + local_docs=_local_documents_for_group(group), + remote_docs=_remote_documents_for_dataset(dify, dataset.id if dataset else group.dify_dataset_id), + group=group, + term=term, + include_knowledge_base=True, + ) + ) + + return {"summary": _summarize_diff_rows(rows), "rows": rows} + + +@router.post("/import-dify-document") +def import_dify_document( + payload: DifyImportRequest, + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + target_group: Group | None = None + if payload.group_id is not None: + ensure_group_access(db, user, payload.group_id) + target_group = db.query(Group).filter(Group.id == payload.group_id).first() + if not target_group: + raise HTTPException(status_code=404, detail="Knowledge base not found.") + else: + if user.role not in {"admin", "super_admin"}: + raise HTTPException(status_code=403, detail="Admin permission required.") + knowledge_base_name = (payload.knowledge_base_name or "").strip() + if not knowledge_base_name: + raise HTTPException(status_code=400, detail="Knowledge base name is required for Dify import.") + department_id = payload.department_id or user.primary_department_id + if department_id is None: + raise HTTPException(status_code=400, detail="Department is required for Dify import.") + ensure_department_access(db, user, department_id) + target_group = _create_group_from_remote_name_in_department( + db=db, + admin=user, + group_name=knowledge_base_name, + department_id=department_id, + ) + + document = _import_dify_document_to_local( + db=db, + user=user, + dataset_id=payload.dataset_id, + remote_document_id=payload.remote_document_id, + group=target_group, + ) + return { + "group_id": target_group.id, + "group_name": target_group.name, + "document": serialize_document(document), + } + + +@router.post("") +def create_group( + payload: GroupCreateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + ensure_department_access(db, admin, payload.department_id) + if _group_name_conflict(db, department_id=payload.department_id, name=payload.name): + raise HTTPException(status_code=409, detail="Group already exists.") + defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first() + group = Group( + name=payload.name, + description=payload.description, + department_id=payload.department_id, + created_by_id=admin.id, + indexing_technique=defaults.indexing_technique if defaults else "high_quality", + search_method=defaults.search_method if defaults else "hybrid_search", + doc_form=defaults.doc_form if defaults else "text_model", + top_k=defaults.top_k if defaults else 5, + score_threshold_enabled=defaults.score_threshold_enabled if defaults else True, + score_threshold=defaults.score_threshold if defaults else "0.35", + ) + db.add(group) + db.commit() + db.refresh(group) + return serialize_group(group) + + +@router.patch("/{group_id}") +def update_group( + group_id: int, + payload: GroupUpdateRequest, + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + ensure_group_access(db, admin, group_id) + group = db.query(Group).filter(Group.id == group_id).first() + if not group: + raise HTTPException(status_code=404, detail="Group not found.") + old_name = group.name + target_name = payload.name or group.name + target_department_id = payload.department_id if payload.department_id is not None else group.department_id + if payload.department_id is not None and payload.department_id != group.department_id: + ensure_department_access(db, admin, payload.department_id) + if payload.name or payload.department_id is not None: + if _group_name_conflict( + db, + department_id=target_department_id, + name=target_name, + exclude_group_id=group.id, + ): + raise HTTPException(status_code=409, detail="Group already exists.") + if payload.name: + group.name = payload.name + if payload.description is not None: + group.description = payload.description + if payload.department_id is not None and payload.department_id != group.department_id: + group.department_id = payload.department_id + db.commit() + if payload.rename_dify and group.dify_dataset_id and payload.name and payload.name != old_name: + dify = DifyService() + dify.update_dataset(dataset_id=group.dify_dataset_id, name=payload.name) + db.refresh(group) + return serialize_group(group) + + +@router.delete("/{group_id}") +def delete_group( + group_id: int, + delete_dify: bool = Query(False), + db: Session = Depends(get_db), + admin: User = Depends(require_admin), +): + ensure_group_access(db, admin, group_id) + group = ( + db.query(Group) + .options(joinedload(Group.department)) + .options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + .filter(Group.id == group_id) + .first() + ) + if not group: + raise HTTPException(status_code=404, detail="Group not found.") + + running_job = ( + db.query(Job) + .filter(Job.group_id == group.id, Job.status.in_(["queued", "running"])) + .first() + ) + if running_job: + raise HTTPException(status_code=409, detail="Group has running jobs and cannot be deleted.") + + if delete_dify and group.dify_dataset_id: + dify = DifyService() + dify.delete_dataset(dataset_id=group.dify_dataset_id) + + for document in group.documents: + _cleanup_document_storage(document) + + db.query(Job).filter(Job.group_id == group.id).delete(synchronize_session=False) + for document in list(group.documents): + db.delete(document) + db.delete(group) + db.commit() + return {"deleted": True} + + +@router.get("/{group_id}/files") +def list_group_files( + group_id: int, + q: str | None = Query(None), + status: str | None = Query(None), + sync_status: str | None = Query(None), + file_type: str | None = Query(None), + uploaded_from: str | None = Query(None), + uploaded_to: str | None = Query(None), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + ensure_group_access(db, user, group_id) + query = ( + db.query(Document) + .options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + .filter(Document.group_id == group_id, Document.is_deleted.is_(False)) + .order_by(Document.updated_at.desc()) + ) + documents = query.all() + filtered: list[Document] = [] + uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None + uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None + for document in documents: + version = current_version(document) + if version is None: + continue + version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None + if q and q.lower() not in document.title.lower(): + continue + if status and version.convert_status != status: + continue + if sync_status and version.sync_status != sync_status: + continue + if file_type and version.source_ext != file_type: + continue + if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date): + continue + if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date): + continue + filtered.append(document) + return {"data": [serialize_document(document) for document in filtered]} + + +@router.get("/{group_id}/dify-diff") +def get_group_dify_diff( + group_id: int, + q: str | None = Query(None), + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + ensure_group_access(db, user, group_id) + group = ( + db.query(Group) + .options(joinedload(Group.department)) + .options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records)) + .filter(Group.id == group_id) + .first() + ) + if not group: + raise HTTPException(status_code=404, detail="Group not found.") + + term = (q or "").strip().lower() + dify = DifyService() if group.dify_dataset_id else None + rows = _build_diff_rows( + knowledge_base_name=group.name, + dataset_id=group.dify_dataset_id, + local_docs=_local_documents_for_group(group), + remote_docs=_remote_documents_for_dataset(dify, group.dify_dataset_id) if dify else {}, + group=group, + term=term, + ) + return {"group": serialize_group(group), "summary": _summarize_diff_rows(rows), "rows": rows} diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py new file mode 100644 index 00000000..5fe51f4f --- /dev/null +++ b/backend/app/api/integration.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +from pathlib import Path + +from pydantic import BaseModel +from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi.responses import FileResponse +from sqlalchemy import func +from sqlalchemy.orm import Session, joinedload + +from app.config import get_settings +from app.database import get_db +from app.deps import require_integration_key +from app.models import DifySyncRecord, Document, DocumentVersion, Group +from app.security import create_integration_download_token, decode_integration_download_token +from app.serializers import current_version, serialize_group +from app.time_utils import utc_now + + +router = APIRouter(prefix="/integration", tags=["integration"]) +settings = get_settings() + + +class DifyResolveItem(BaseModel): + remote_document_id: str + dataset_id: str | None = None + + +class DifyResolveRequest(BaseModel): + items: list[DifyResolveItem] + + +def _document_query(db: Session): + return ( + db.query(Document) + .options( + joinedload(Document.group).joinedload(Group.department), + joinedload(Document.versions).joinedload(DocumentVersion.sync_records), + ) + .filter(Document.is_deleted.is_(False)) + ) + + +def _knowledge_base_summary(group: Group, *, document_count: int) -> dict: + payload = serialize_group(group, document_count=document_count) + payload["knowledge_base_id"] = payload["id"] + return payload + + +def _integration_document_payload( + document: Document, + *, + version: DocumentVersion | None = None, + sync_record: DifySyncRecord | None = None, +) -> dict: + version = version or current_version(document) + if version is None: + raise HTTPException(status_code=404, detail="No current version found.") + sync_record = sync_record or (version.sync_records[0] if version.sync_records else None) + try: + source_token, source_expires_at = create_integration_download_token( + file_id=document.id, + version_id=version.id, + kind="source", + ) + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + md_token = None + md_expires_at = None + if version.md_path: + try: + md_token, md_expires_at = create_integration_download_token( + file_id=document.id, + version_id=version.id, + kind="md", + ) + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + return { + "queried_at": utc_now().isoformat(), + "document_id": document.id, + "knowledge_base": { + "id": document.group.id, + "name": document.group.name, + "department_id": document.group.department_id, + "department_name": document.group.department.name if document.group.department else None, + "dify_dataset_id": document.group.dify_dataset_id, + }, + "title": document.title, + "source_filename": version.source_filename, + "source_ext": version.source_ext, + "file_name": version.source_filename, + "version_id": version.id, + "version_no": version.version_no, + "convert_status": version.convert_status, + "sync_status": version.sync_status, + "uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None, + "converted_at": version.converted_at.isoformat() if version.converted_at else None, + "download_url_expires_at": source_expires_at.isoformat(), + "source_download_url": ( + f"{settings.public_base_url}{settings.api_prefix}/integration/download" + f"?version_id={version.id}&kind=source&token={source_token}" + ), + "markdown_download_url": ( + f"{settings.public_base_url}{settings.api_prefix}/integration/download" + f"?version_id={version.id}&kind=md&token={md_token}" + if version.md_path and md_token + else None + ), + "markdown_download_url_expires_at": md_expires_at.isoformat() if md_expires_at else None, + "markdown_public_url": version.md_public_url, + "dify": { + "dataset_id": sync_record.dataset_id if sync_record else document.group.dify_dataset_id, + "remote_document_id": sync_record.remote_document_id if sync_record else None, + "status": sync_record.status if sync_record else None, + "last_indexing_status": sync_record.last_indexing_status if sync_record else None, + "last_synced_at": sync_record.last_synced_at.isoformat() if sync_record and sync_record.last_synced_at else None, + }, + } + + +@router.get("/knowledge-bases") +def list_knowledge_bases( + department_id: int | None = None, + q: str | None = None, + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + document_counts = ( + db.query(Document.group_id.label("group_id"), func.count(Document.id).label("document_count")) + .filter(Document.is_deleted.is_(False)) + .group_by(Document.group_id) + .subquery() + ) + query = ( + db.query(Group, func.coalesce(document_counts.c.document_count, 0).label("document_count")) + .outerjoin(document_counts, document_counts.c.group_id == Group.id) + .options(joinedload(Group.department)) + .order_by(Group.name.asc()) + ) + if department_id is not None: + query = query.filter(Group.department_id == department_id) + if q: + query = query.filter(Group.name.ilike(f"%{q.strip()}%")) + rows = query.all() + return {"data": [_knowledge_base_summary(group, document_count=document_count) for group, document_count in rows]} + + +@router.get("/files") +def list_files( + knowledge_base_id: int | None = None, + department_id: int | None = None, + file_name: str | None = Query(default=None, description="Filter by source filename or title."), + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + query = _document_query(db) + if knowledge_base_id is not None: + query = query.filter(Document.group_id == knowledge_base_id) + if department_id is not None: + query = query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id) + documents = query.order_by(Document.updated_at.desc()).all() + normalized = file_name.strip().lower() if file_name else None + + payload: list[dict] = [] + for document in documents: + version = current_version(document) + if version is None: + continue + if normalized and normalized not in version.source_filename.lower() and normalized not in document.title.lower(): + continue + payload.append(_integration_document_payload(document)) + return {"data": payload} + + +@router.get("/knowledge-bases/{knowledge_base_id}/files") +def list_files_for_knowledge_base( + knowledge_base_id: int, + file_name: str | None = Query(default=None, description="Filter by source filename or title."), + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + return list_files( + knowledge_base_id=knowledge_base_id, + file_name=file_name, + db=db, + _="integration", + ) + + +@router.get("/files/{file_id}") +def get_file_detail( + file_id: int, + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + document = _document_query(db).filter(Document.id == file_id).first() + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + return _integration_document_payload(document) + + +@router.get("/dify-file") +def get_file_detail_by_dify( + remote_document_id: str = Query(..., description="Dify document id."), + dataset_id: str | None = Query(default=None, description="Optional Dify dataset id."), + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + record_query = ( + db.query(DifySyncRecord) + .join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id) + .join(Document, Document.id == DocumentVersion.document_id) + .options( + joinedload(DifySyncRecord.version) + .joinedload(DocumentVersion.document) + .joinedload(Document.group) + .joinedload(Group.department), + joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records), + ) + .filter( + Document.is_deleted.is_(False), + DifySyncRecord.remote_document_id == remote_document_id, + ) + .order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc()) + ) + if dataset_id: + record_query = record_query.filter(DifySyncRecord.dataset_id == dataset_id) + record = record_query.first() + if not record or not record.version or not record.version.document: + raise HTTPException(status_code=404, detail="No local file mapping found for the given Dify document.") + return _integration_document_payload(record.version.document, version=record.version, sync_record=record) + + +@router.post("/dify-files/resolve") +def resolve_files_by_dify( + payload: DifyResolveRequest, + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + if not payload.items: + return {"data": []} + + remote_ids = sorted({item.remote_document_id for item in payload.items if item.remote_document_id}) + dataset_ids = sorted({item.dataset_id for item in payload.items if item.dataset_id}) + + record_query = ( + db.query(DifySyncRecord) + .join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id) + .join(Document, Document.id == DocumentVersion.document_id) + .options( + joinedload(DifySyncRecord.version) + .joinedload(DocumentVersion.document) + .joinedload(Document.group) + .joinedload(Group.department), + joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records), + ) + .filter( + Document.is_deleted.is_(False), + DifySyncRecord.remote_document_id.in_(remote_ids), + ) + .order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc()) + ) + if dataset_ids: + record_query = record_query.filter( + (DifySyncRecord.dataset_id.in_(dataset_ids)) | (DifySyncRecord.dataset_id.is_(None)) + ) + records = record_query.all() + + records_by_key: dict[tuple[str | None, str], DifySyncRecord] = {} + records_by_remote: dict[str, DifySyncRecord] = {} + for record in records: + key = (record.dataset_id, record.remote_document_id) + records_by_key.setdefault(key, record) + records_by_remote.setdefault(record.remote_document_id, record) + + data: list[dict] = [] + for item in payload.items: + record = records_by_key.get((item.dataset_id, item.remote_document_id)) + if record is None and item.dataset_id is None: + record = records_by_remote.get(item.remote_document_id) + data.append( + { + "request": { + "dataset_id": item.dataset_id, + "remote_document_id": item.remote_document_id, + }, + "found": bool(record and record.version and record.version.document), + "document": ( + _integration_document_payload(record.version.document, version=record.version, sync_record=record) + if record and record.version and record.version.document + else None + ), + } + ) + return {"data": data} + + +@router.get("/files/{file_id}/download") +def download_file( + file_id: int, + kind: str = Query(default="md"), + db: Session = Depends(get_db), + _: str = Depends(require_integration_key), +): + document = _document_query(db).filter(Document.id == file_id).first() + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + version = current_version(document) + if not version: + raise HTTPException(status_code=404, detail="No version found.") + + if kind == "source": + path = Path(version.source_path) + filename = version.source_filename + else: + if not version.md_path: + raise HTTPException(status_code=409, detail="Markdown not ready.") + path = Path(version.md_path) + filename = f"{document.title}.md" + + if not path.exists(): + raise HTTPException(status_code=404, detail="File missing on disk.") + + return FileResponse(path, filename=filename) + + +@router.get("/download") +def download_file_from_signed_url( + file_id: int | None = Query(default=None), + version_id: int | None = Query(default=None), + kind: str = Query(default="source"), + token: str = Query(...), + db: Session = Depends(get_db), +): + try: + payload = decode_integration_download_token(token) + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + if not payload: + raise HTTPException(status_code=401, detail="Invalid or expired download token.") + expected_kind = payload.get("kind") + expected_version_id = payload.get("version_id") + expected_file_id = payload.get("file_id") + if expected_kind != kind: + raise HTTPException(status_code=401, detail="Download token does not match the requested file.") + if expected_version_id is not None: + if version_id != int(expected_version_id): + raise HTTPException(status_code=401, detail="Download token does not match the requested file.") + version = db.query(DocumentVersion).join(Document).filter( + DocumentVersion.id == version_id, + Document.is_deleted.is_(False), + ).first() + if not version or not version.document: + raise HTTPException(status_code=404, detail="Version not found.") + document = version.document + else: + if file_id is None or expected_file_id is None or int(expected_file_id) != file_id: + raise HTTPException(status_code=401, detail="Download token does not match the requested file.") + document = _document_query(db).filter(Document.id == file_id).first() + if not document: + raise HTTPException(status_code=404, detail="Document not found.") + version = current_version(document) + if not version: + raise HTTPException(status_code=404, detail="No version found.") + + if kind == "source": + path = Path(version.source_path) + filename = version.source_filename + else: + if not version.md_path: + raise HTTPException(status_code=409, detail="Markdown not ready.") + path = Path(version.md_path) + filename = f"{document.title}.md" + + if not path.exists(): + raise HTTPException(status_code=404, detail="File missing on disk.") + return FileResponse(path, filename=filename) diff --git a/backend/app/api/jobs.py b/backend/app/api/jobs.py new file mode 100644 index 00000000..4e9ef306 --- /dev/null +++ b/backend/app/api/jobs.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy import or_ +from sqlalchemy.orm import Session + +from app.database import get_db +from app.deps import accessible_group_ids, get_current_user, is_super_admin +from app.models import Job, User +from app.serializers import serialize_job + + +router = APIRouter(prefix="/jobs", tags=["jobs"]) + + +@router.get("") +def list_jobs( + limit: int = 50, + db: Session = Depends(get_db), + user: User = Depends(get_current_user), +): + query = db.query(Job).order_by(Job.created_at.desc()) + if not is_super_admin(user): + group_ids = accessible_group_ids(db, user) + if user.role == "admin": + query = query.filter(or_(Job.created_by_id == user.id, Job.group_id.in_(group_ids or [-1]))) + else: + query = query.filter(Job.created_by_id == user.id) + jobs = query.limit(min(limit, 200)).all() + return {"data": [serialize_job(job) for job in jobs]} + + +@router.get("/{job_id}") +def get_job(job_id: str, db: Session = Depends(get_db), user: User = Depends(get_current_user)): + job = db.query(Job).filter(Job.id == job_id).first() + if not job: + raise HTTPException(status_code=404, detail="Job not found.") + if is_super_admin(user): + return serialize_job(job) + if user.role == "admin": + group_ids = accessible_group_ids(db, user) + if job.created_by_id != user.id and job.group_id not in (group_ids or []): + raise HTTPException(status_code=403, detail="Forbidden") + return serialize_job(job) + if job.created_by_id != user.id: + raise HTTPException(status_code=403, detail="Forbidden") + return serialize_job(job) diff --git a/backend/app/config.py b/backend/app/config.py new file mode 100644 index 00000000..27eb873f --- /dev/null +++ b/backend/app/config.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import Literal + +from pydantic import Field, model_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + extra="ignore", + ) + + app_name: str = "Document Cleaning" + api_prefix: str = "/api" + jwt_secret: str = "change-me-in-production" + jwt_algorithm: str = "HS256" + access_token_expire_minutes: int = 720 + + database_backend: Literal["sqlite", "postgres"] = "sqlite" + database_url: str = "" + sqlite_database_url: str = "sqlite:///./document_cleaning.db" + postgres_database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/document_cleaning" + redis_url: str = "redis://redis:6379/0" + + data_root: Path = Field(default=Path("./data")) + public_base_url: str = "http://192.168.100.230:8891" + allowed_origins: str = "http://192.168.100.230:8891,http://localhost:5173" + + dify_base_url: str = "https://api.dify.ai/v1" + dify_api_key: str = "" + dify_permission: str = "all_team_members" + + default_indexing_technique: str = "high_quality" + default_search_method: str = "hybrid_search" + default_doc_form: str = "text_model" + default_embedding_model_provider: str = "" + default_embedding_model: str = "" + default_reranking_model_provider: str = "" + default_reranking_model: str = "" + default_top_k: int = 5 + default_score_threshold_enabled: bool = True + default_score_threshold: float = 0.35 + + default_admin_username: str = "admin" + default_admin_password: str = "admin123456" + default_admin_name: str = "System Admin" + integration_api_key: str = "" + integration_download_secret: str = "" + integration_download_expire_minutes: int = 15 + + rq_queue_name: str = "document-cleaning" + rq_default_timeout: int = 3600 + task_execution_mode: Literal["rq", "sync"] = "rq" + dify_sync_max_retries: int = 4 + dify_sync_retry_schedule: str = "30,60,120,300" + dify_sync_cooldown_seconds: int = 60 + watchdog_stale_sync_timeout_seconds: int = 900 + watchdog_stale_convert_timeout_seconds: int = 900 + watchdog_convert_orphan_grace_seconds: int = 120 + + edkb_word_timeout_sec: int = 120 + edkb_file_timeout_sec: int = 900 + + def origins_list(self) -> list[str]: + return [item.strip() for item in self.allowed_origins.split(",") if item.strip()] + + def dify_sync_retry_delays(self) -> list[int]: + values: list[int] = [] + for raw in self.dify_sync_retry_schedule.split(","): + token = raw.strip() + if not token: + continue + try: + parsed = int(token) + except ValueError: + continue + if parsed > 0: + values.append(parsed) + return values or [30, 60, 120, 300] + + @staticmethod + def _normalize_database_url(url: str) -> str: + normalized = url.strip() + if normalized.startswith("postgresql://"): + return normalized.replace("postgresql://", "postgresql+psycopg://", 1) + return normalized + + @model_validator(mode="after") + def resolve_database_url(self) -> "Settings": + if self.database_url: + self.database_url = self._normalize_database_url(self.database_url) + return self + + selected = self.sqlite_database_url if self.database_backend == "sqlite" else self.postgres_database_url + self.database_url = self._normalize_database_url(selected) + return self + + def ensure_data_dirs(self) -> None: + for name in ["original", "markdown", "assets", "jobs", "tmp"]: + (self.data_root / name).mkdir(parents=True, exist_ok=True) + + +@lru_cache +def get_settings() -> Settings: + settings = Settings() + settings.ensure_data_dirs() + return settings diff --git a/backend/app/database.py b/backend/app/database.py new file mode 100644 index 00000000..b034bbcd --- /dev/null +++ b/backend/app/database.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from sqlalchemy import create_engine +from sqlalchemy.orm import declarative_base, sessionmaker + +from app.config import get_settings + + +settings = get_settings() + +connect_args: dict[str, object] = {} +if settings.database_url.startswith("sqlite"): + connect_args["check_same_thread"] = False + +engine = create_engine( + settings.database_url, + future=True, + pool_pre_ping=True, + connect_args=connect_args, +) +SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True) +Base = declarative_base() + + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() + diff --git a/backend/app/deps.py b/backend/app/deps.py new file mode 100644 index 00000000..629bbdba --- /dev/null +++ b/backend/app/deps.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +from fastapi import Depends, Header, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from sqlalchemy.orm import Session + +from app.config import get_settings +from app.database import get_db +from app.models import Group, User, UserDepartmentAccess +from app.security import decode_access_token + + +settings = get_settings() +oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.api_prefix}/auth/login") + + +def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User: + username = decode_access_token(token) + if not username: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") + user = db.query(User).filter(User.username == username, User.is_active.is_(True)).first() + if not user: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found") + return user + + +def is_super_admin(user: User) -> bool: + return user.role == "super_admin" + + +def is_admin(user: User) -> bool: + return user.role in {"super_admin", "admin"} + + +def accessible_department_ids(db: Session, user: User) -> list[int] | None: + department_ids = set() + if user.primary_department_id is not None: + department_ids.add(user.primary_department_id) + department_ids.update( + item.department_id + for item in db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user.id).all() + if item.department_id is not None + ) + return sorted(department_ids) + + +def accessible_group_ids(db: Session, user: User) -> list[int] | None: + department_ids = accessible_department_ids(db, user) or [-1] + return [item[0] for item in db.query(Group.id).filter(Group.department_id.in_(department_ids)).all()] + + +def require_super_admin(user: User = Depends(get_current_user)) -> User: + if not is_super_admin(user): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin only") + return user + + +def require_admin(user: User = Depends(get_current_user)) -> User: + if not is_admin(user): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin only") + return user + + +def ensure_department_access(db: Session, user: User, department_id: int) -> None: + if department_id not in (accessible_department_ids(db, user) or []): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") + + +def ensure_group_access(db: Session, user: User, group_id: int) -> None: + group = db.query(Group.id, Group.department_id).filter(Group.id == group_id).first() + if not group: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Knowledge base not found.") + if group.department_id not in (accessible_department_ids(db, user) or []): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") + + +def require_integration_key( + x_integration_key: str | None = Header(default=None, alias="X-Integration-Key"), + authorization: str | None = Header(default=None), +) -> str: + configured_key = settings.integration_api_key + if not configured_key: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Integration API is not configured.") + + token = x_integration_key + if not token and authorization: + scheme, _, credentials = authorization.partition(" ") + if scheme.lower() == "bearer" and credentials: + token = credentials + + if token != configured_key: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid integration key") + + return token diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 00000000..32d2ab37 --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles + +from app.api import admin, auth, departments, files, groups, integration, jobs +from app.config import get_settings +from app.database import SessionLocal +from app.services.bootstrap_service import ensure_defaults + + +settings = get_settings() + + +@asynccontextmanager +async def lifespan(_: FastAPI): + db = SessionLocal() + try: + ensure_defaults(db) + yield + finally: + db.close() + + +app = FastAPI(title=settings.app_name, lifespan=lifespan) + +app.add_middleware( + CORSMiddleware, + allow_origins=settings.origins_list(), + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(auth.router, prefix=settings.api_prefix) +app.include_router(departments.router, prefix=settings.api_prefix) +app.include_router(groups.router, prefix=settings.api_prefix) +app.include_router(files.router, prefix=settings.api_prefix) +app.include_router(integration.router, prefix=settings.api_prefix) +app.include_router(jobs.router, prefix=settings.api_prefix) +app.include_router(admin.router, prefix=settings.api_prefix) +app.mount("/storage", StaticFiles(directory=settings.data_root), name="storage") + + +@app.get("/health") +def health() -> dict: + return {"status": "ok"} diff --git a/backend/app/models.py b/backend/app/models.py new file mode 100644 index 00000000..8ad58896 --- /dev/null +++ b/backend/app/models.py @@ -0,0 +1,243 @@ +from __future__ import annotations + +from datetime import datetime + +from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.database import Base +from app.time_utils import utc_now + + +class Department(Base): + __tablename__ = "departments" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(128), unique=True, index=True) + description: Mapped[str | None] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now() + ) + + users: Mapped[list["User"]] = relationship(back_populates="primary_department") + user_accesses: Mapped[list["UserDepartmentAccess"]] = relationship( + back_populates="department", cascade="all, delete-orphan" + ) + groups: Mapped[list["Group"]] = relationship(back_populates="department") + + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + username: Mapped[str] = mapped_column(String(64), unique=True, index=True) + full_name: Mapped[str | None] = mapped_column(String(128), nullable=True) + password_hash: Mapped[str] = mapped_column(String(255)) + role: Mapped[str] = mapped_column(String(16), default="user") + is_active: Mapped[bool] = mapped_column(Boolean, default=True) + primary_department_id: Mapped[int | None] = mapped_column(ForeignKey("departments.id"), index=True, nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + + primary_department: Mapped[Department | None] = relationship(back_populates="users") + department_accesses: Mapped[list["UserDepartmentAccess"]] = relationship( + back_populates="user", cascade="all, delete-orphan" + ) + groups_created: Mapped[list["Group"]] = relationship(back_populates="created_by") + group_accesses: Mapped[list["UserGroupAccess"]] = relationship( + back_populates="user", cascade="all, delete-orphan" + ) + documents_created: Mapped[list["Document"]] = relationship(back_populates="created_by") + versions_uploaded: Mapped[list["DocumentVersion"]] = relationship(back_populates="uploaded_by") + jobs_created: Mapped[list["Job"]] = relationship(back_populates="created_by") + + +class SystemSetting(Base): + __tablename__ = "system_settings" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1) + dify_permission: Mapped[str] = mapped_column(String(32), default="all_team_members") + indexing_technique: Mapped[str] = mapped_column(String(32), default="high_quality") + search_method: Mapped[str] = mapped_column(String(32), default="hybrid_search") + doc_form: Mapped[str] = mapped_column(String(32), default="text_model") + embedding_model_provider: Mapped[str | None] = mapped_column(String(128), nullable=True) + embedding_model: Mapped[str | None] = mapped_column(String(128), nullable=True) + reranking_model_provider: Mapped[str | None] = mapped_column(String(128), nullable=True) + reranking_model: Mapped[str | None] = mapped_column(String(128), nullable=True) + top_k: Mapped[int] = mapped_column(Integer, default=5) + score_threshold_enabled: Mapped[bool] = mapped_column(Boolean, default=True) + score_threshold: Mapped[str] = mapped_column(String(32), default="0.35") + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now() + ) + + +class Group(Base): + __tablename__ = "groups" + __table_args__ = (UniqueConstraint("department_id", "name", name="uq_groups_department_name"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + name: Mapped[str] = mapped_column(String(128), index=True) + description: Mapped[str | None] = mapped_column(Text, nullable=True) + department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False) + dify_dataset_id: Mapped[str | None] = mapped_column(String(128), nullable=True) + dify_sync_policy: Mapped[str] = mapped_column(String(32), default="manual") + indexing_technique: Mapped[str] = mapped_column(String(32), default="high_quality") + search_method: Mapped[str] = mapped_column(String(32), default="hybrid_search") + doc_form: Mapped[str] = mapped_column(String(32), default="text_model") + top_k: Mapped[int] = mapped_column(Integer, default=5) + score_threshold_enabled: Mapped[bool] = mapped_column(Boolean, default=True) + score_threshold: Mapped[str] = mapped_column(String(32), default="0.35") + created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now() + ) + + department: Mapped[Department] = relationship(back_populates="groups") + created_by: Mapped[User | None] = relationship(back_populates="groups_created") + user_accesses: Mapped[list["UserGroupAccess"]] = relationship( + back_populates="group", cascade="all, delete-orphan" + ) + documents: Mapped[list["Document"]] = relationship(back_populates="group") + + +class UserDepartmentAccess(Base): + __tablename__ = "user_department_access" + __table_args__ = (UniqueConstraint("user_id", "department_id", name="uq_user_department_access"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True) + department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + + user: Mapped[User] = relationship(back_populates="department_accesses") + department: Mapped[Department] = relationship(back_populates="user_accesses") + + +class UserGroupAccess(Base): + __tablename__ = "user_group_access" + __table_args__ = (UniqueConstraint("user_id", "group_id", name="uq_user_group_access"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True) + group_id: Mapped[int] = mapped_column(ForeignKey("groups.id"), index=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + + user: Mapped[User] = relationship(back_populates="group_accesses") + group: Mapped[Group] = relationship(back_populates="user_accesses") + + +class Document(Base): + __tablename__ = "documents" + __table_args__ = (UniqueConstraint("group_id", "title", name="uq_documents_group_title"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + group_id: Mapped[int] = mapped_column(ForeignKey("groups.id"), index=True) + title: Mapped[str] = mapped_column(String(255)) + is_deleted: Mapped[bool] = mapped_column(Boolean, default=False) + created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now() + ) + + group: Mapped[Group] = relationship(back_populates="documents") + created_by: Mapped[User | None] = relationship(back_populates="documents_created") + versions: Mapped[list["DocumentVersion"]] = relationship( + back_populates="document", cascade="all, delete-orphan", order_by="DocumentVersion.version_no.desc()" + ) + + +class DocumentVersion(Base): + __tablename__ = "document_versions" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + document_id: Mapped[int] = mapped_column(ForeignKey("documents.id"), index=True) + version_no: Mapped[int] = mapped_column(Integer) + is_current: Mapped[bool] = mapped_column(Boolean, default=True) + source_filename: Mapped[str] = mapped_column(String(255)) + source_ext: Mapped[str] = mapped_column(String(16)) + source_path: Mapped[str] = mapped_column(Text) + source_sha256: Mapped[str] = mapped_column(String(64), index=True) + md_path: Mapped[str | None] = mapped_column(Text, nullable=True) + md_public_url: Mapped[str | None] = mapped_column(Text, nullable=True) + asset_dir: Mapped[str | None] = mapped_column(Text, nullable=True) + file_size: Mapped[int] = mapped_column(Integer) + word_count: Mapped[int] = mapped_column(Integer, default=0) + convert_status: Mapped[str] = mapped_column(String(32), default="queued") + sync_status: Mapped[str] = mapped_column(String(32), default="unsynced") + uploader_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True) + uploaded_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + converted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + failed_reason: Mapped[str | None] = mapped_column(Text, nullable=True) + warnings_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + + document: Mapped[Document] = relationship(back_populates="versions") + uploaded_by: Mapped[User | None] = relationship(back_populates="versions_uploaded") + jobs: Mapped[list["Job"]] = relationship(back_populates="version") + sync_records: Mapped[list["DifySyncRecord"]] = relationship( + back_populates="version", cascade="all, delete-orphan", order_by="DifySyncRecord.updated_at.desc()" + ) + + +class Job(Base): + __tablename__ = "jobs" + + id: Mapped[str] = mapped_column(String(36), primary_key=True) + job_type: Mapped[str] = mapped_column(String(32), index=True) + status: Mapped[str] = mapped_column(String(32), default="queued", index=True) + queue_job_id: Mapped[str | None] = mapped_column(String(64), nullable=True) + group_id: Mapped[int | None] = mapped_column(ForeignKey("groups.id"), nullable=True) + document_id: Mapped[int | None] = mapped_column(ForeignKey("documents.id"), nullable=True) + version_id: Mapped[int | None] = mapped_column(ForeignKey("document_versions.id"), nullable=True) + created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True) + progress: Mapped[int] = mapped_column(Integer, default=0) + message: Mapped[str | None] = mapped_column(Text, nullable=True) + error: Mapped[str | None] = mapped_column(Text, nullable=True) + payload: Mapped[dict | None] = mapped_column(JSON, nullable=True) + result: Mapped[dict | None] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + version: Mapped[DocumentVersion | None] = relationship(back_populates="jobs") + created_by: Mapped[User | None] = relationship(back_populates="jobs_created") + + +class DifySyncRecord(Base): + __tablename__ = "dify_sync_records" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + version_id: Mapped[int] = mapped_column(ForeignKey("document_versions.id"), index=True) + dataset_id: Mapped[str] = mapped_column(String(128)) + remote_document_id: Mapped[str] = mapped_column(String(128)) + batch: Mapped[str | None] = mapped_column(String(128), nullable=True) + status: Mapped[str] = mapped_column(String(32), default="syncing") + last_indexing_status: Mapped[str | None] = mapped_column(String(64), nullable=True) + error: Mapped[str | None] = mapped_column(Text, nullable=True) + last_synced_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, server_default=func.now() + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utc_now, onupdate=utc_now, server_default=func.now() + ) + + version: Mapped[DocumentVersion] = relationship(back_populates="sync_records") diff --git a/backend/app/schemas.py b/backend/app/schemas.py new file mode 100644 index 00000000..c1b0ef6c --- /dev/null +++ b/backend/app/schemas.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +from datetime import datetime + +from pydantic import BaseModel, Field + + +class LoginRequest(BaseModel): + username: str + password: str + + +class TokenResponse(BaseModel): + access_token: str + token_type: str = "bearer" + user: dict + + +class GroupCreateRequest(BaseModel): + name: str + description: str | None = None + department_id: int + + +class GroupUpdateRequest(BaseModel): + name: str | None = None + description: str | None = None + department_id: int | None = None + rename_dify: bool = False + + +class BatchDownloadRequest(BaseModel): + document_ids: list[int] = Field(default_factory=list) + kind: str = "md" + + +class BatchSyncRequest(BaseModel): + document_ids: list[int] = Field(default_factory=list) + + +class UserCreateRequest(BaseModel): + username: str + password: str + full_name: str | None = None + role: str = "user" + primary_department_id: int + accessible_department_ids: list[int] = Field(default_factory=list) + + +class UserUpdateRequest(BaseModel): + full_name: str | None = None + role: str | None = None + password: str | None = None + is_active: bool | None = None + primary_department_id: int | None = None + accessible_department_ids: list[int] | None = None + + +class DifyImportRequest(BaseModel): + dataset_id: str + remote_document_id: str + group_id: int | None = None + department_id: int | None = None + knowledge_base_name: str | None = None + + +class DepartmentCreateRequest(BaseModel): + name: str + description: str | None = None + + +class DepartmentUpdateRequest(BaseModel): + name: str | None = None + description: str | None = None + + +class DepartmentDeleteRequest(BaseModel): + target_department_id: int | None = None + + +class SettingsUpdateRequest(BaseModel): + dify_permission: str | None = None + indexing_technique: str | None = None + search_method: str | None = None + doc_form: str | None = None + embedding_model_provider: str | None = None + embedding_model: str | None = None + reranking_model_provider: str | None = None + reranking_model: str | None = None + top_k: int | None = None + score_threshold_enabled: bool | None = None + score_threshold: float | None = None + + +class JobResponse(BaseModel): + id: str + job_type: str + status: str + progress: int + message: str | None = None + error: str | None = None + created_at: datetime | None = None + started_at: datetime | None = None + finished_at: datetime | None = None + result: dict | None = None diff --git a/backend/app/security.py b/backend/app/security.py new file mode 100644 index 00000000..ec9a0e84 --- /dev/null +++ b/backend/app/security.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +from jose import JWTError, jwt +from passlib.context import CryptContext + +from app.config import get_settings + + +pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto") + + +def verify_password(plain_password: str, password_hash: str) -> bool: + return pwd_context.verify(plain_password, password_hash) + + +def hash_password(password: str) -> str: + return pwd_context.hash(password) + + +def create_access_token(subject: str) -> str: + settings = get_settings() + expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes) + payload = {"sub": subject, "exp": expire} + return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm) + + +def decode_access_token(token: str) -> str | None: + settings = get_settings() + try: + payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm]) + except JWTError: + return None + return payload.get("sub") + + +def _integration_download_secret() -> str: + settings = get_settings() + if settings.integration_download_secret: + return settings.integration_download_secret + raise RuntimeError("Integration download secret is not configured.") + + +def create_integration_download_token( + *, + file_id: int | None = None, + version_id: int | None = None, + kind: str, +) -> tuple[str, datetime]: + settings = get_settings() + expire = datetime.now(timezone.utc) + timedelta(minutes=settings.integration_download_expire_minutes) + payload = { + "typ": "integration_download", + "kind": kind, + "exp": expire, + } + if file_id is not None: + payload["file_id"] = file_id + if version_id is not None: + payload["version_id"] = version_id + token = jwt.encode(payload, _integration_download_secret(), algorithm=settings.jwt_algorithm) + return token, expire + + +def decode_integration_download_token(token: str) -> dict | None: + settings = get_settings() + try: + payload = jwt.decode(token, _integration_download_secret(), algorithms=[settings.jwt_algorithm]) + except JWTError: + return None + if payload.get("typ") != "integration_download": + return None + return payload diff --git a/backend/app/serializers.py b/backend/app/serializers.py new file mode 100644 index 00000000..ca25cf0e --- /dev/null +++ b/backend/app/serializers.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +from app.models import Department, Document, DocumentVersion, DifySyncRecord, Group, Job, SystemSetting, User +from app.user_policy import is_primary_super_admin_username + + +def current_version(document: Document) -> DocumentVersion | None: + for version in document.versions: + if version.is_current: + return version + return document.versions[0] if document.versions else None + + +def serialize_user(user: User) -> dict: + visible_department_ids = set() + if user.primary_department_id is not None: + visible_department_ids.add(user.primary_department_id) + visible_department_ids.update(item.department_id for item in user.department_accesses) + return { + "id": user.id, + "username": user.username, + "full_name": user.full_name, + "role": user.role, + "is_primary_super_admin": is_primary_super_admin_username(user.username), + "is_active": user.is_active, + "primary_department_id": user.primary_department_id, + "primary_department_name": user.primary_department.name if user.primary_department else None, + "accessible_department_ids": sorted(visible_department_ids), + "extra_department_ids": sorted(item.department_id for item in user.department_accesses), + "created_at": user.created_at.isoformat() if user.created_at else None, + } + + +def serialize_department( + department: Department, + *, + user_count: int | None = None, + knowledge_base_count: int | None = None, +) -> dict: + return { + "id": department.id, + "name": department.name, + "description": department.description, + "user_count": int(user_count or 0), + "knowledge_base_count": int(knowledge_base_count or 0), + "created_at": department.created_at.isoformat() if department.created_at else None, + "updated_at": department.updated_at.isoformat() if department.updated_at else None, + } + + +def serialize_user_brief(user: User | None) -> dict | None: + if user is None: + return None + return { + "id": user.id, + "username": user.username, + "full_name": user.full_name, + } + + +def serialize_group(group: Group, *, document_count: int | None = None) -> dict: + return { + "id": group.id, + "name": group.name, + "description": group.description, + "department_id": group.department_id, + "department_name": group.department.name if group.department else None, + "dify_dataset_id": group.dify_dataset_id, + "dify_sync_policy": group.dify_sync_policy, + "indexing_technique": group.indexing_technique, + "search_method": group.search_method, + "doc_form": group.doc_form, + "top_k": group.top_k, + "score_threshold_enabled": group.score_threshold_enabled, + "score_threshold": float(group.score_threshold), + "document_count": int(document_count or 0), + "created_at": group.created_at.isoformat() if group.created_at else None, + "updated_at": group.updated_at.isoformat() if group.updated_at else None, + } + + +def serialize_sync_record(record: DifySyncRecord) -> dict: + return { + "id": record.id, + "dataset_id": record.dataset_id, + "remote_document_id": record.remote_document_id, + "batch": record.batch, + "status": record.status, + "last_indexing_status": record.last_indexing_status, + "error": record.error, + "last_synced_at": record.last_synced_at.isoformat() if record.last_synced_at else None, + } + + +def serialize_version(version: DocumentVersion | None) -> dict | None: + if version is None: + return None + return { + "id": version.id, + "document_id": version.document_id, + "version_no": version.version_no, + "is_current": version.is_current, + "source_filename": version.source_filename, + "source_ext": version.source_ext, + "source_path": version.source_path, + "md_path": version.md_path, + "md_public_url": version.md_public_url, + "asset_dir": version.asset_dir, + "file_size": version.file_size, + "word_count": version.word_count, + "convert_status": version.convert_status, + "sync_status": version.sync_status, + "uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None, + "uploaded_by": serialize_user_brief(version.uploaded_by), + "converted_at": version.converted_at.isoformat() if version.converted_at else None, + "failed_reason": version.failed_reason, + "warnings": version.warnings_json or [], + } + + +def serialize_document(document: Document) -> dict: + version = current_version(document) + sync = version.sync_records[0] if version and version.sync_records else None + return { + "id": document.id, + "group_id": document.group_id, + "title": document.title, + "is_deleted": document.is_deleted, + "created_at": document.created_at.isoformat() if document.created_at else None, + "updated_at": document.updated_at.isoformat() if document.updated_at else None, + "current_version": serialize_version(version), + "sync_record": serialize_sync_record(sync) if sync else None, + "version_count": len(document.versions), + } + + +def serialize_job(job: Job) -> dict: + return { + "id": job.id, + "job_type": job.job_type, + "status": job.status, + "queue_job_id": job.queue_job_id, + "group_id": job.group_id, + "document_id": job.document_id, + "version_id": job.version_id, + "progress": job.progress, + "message": job.message, + "error": job.error, + "payload": job.payload, + "result": job.result, + "created_at": job.created_at.isoformat() if job.created_at else None, + "started_at": job.started_at.isoformat() if job.started_at else None, + "finished_at": job.finished_at.isoformat() if job.finished_at else None, + } + + +def serialize_settings(settings: SystemSetting) -> dict: + return { + "dify_permission": settings.dify_permission, + "indexing_technique": settings.indexing_technique, + "search_method": settings.search_method, + "doc_form": settings.doc_form, + "embedding_model_provider": settings.embedding_model_provider, + "embedding_model": settings.embedding_model, + "reranking_model_provider": settings.reranking_model_provider, + "reranking_model": settings.reranking_model, + "top_k": settings.top_k, + "score_threshold_enabled": settings.score_threshold_enabled, + "score_threshold": float(settings.score_threshold), + "updated_at": settings.updated_at.isoformat() if settings.updated_at else None, + } diff --git a/backend/app/services/bootstrap_service.py b/backend/app/services/bootstrap_service.py new file mode 100644 index 00000000..c38833fb --- /dev/null +++ b/backend/app/services/bootstrap_service.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from sqlalchemy.orm import Session + +from app.config import get_settings +from app.models import SystemSetting, User, UserDepartmentAccess +from app.security import hash_password +from app.user_policy import PRIMARY_SUPER_ADMIN_USERNAME + + +def ensure_defaults(db: Session) -> None: + settings = get_settings() + + system = db.query(SystemSetting).filter(SystemSetting.id == 1).first() + if system is None: + system = SystemSetting( + id=1, + dify_permission=settings.dify_permission, + indexing_technique=settings.default_indexing_technique, + search_method=settings.default_search_method, + doc_form=settings.default_doc_form, + embedding_model_provider=settings.default_embedding_model_provider or None, + embedding_model=settings.default_embedding_model or None, + reranking_model_provider=settings.default_reranking_model_provider or None, + reranking_model=settings.default_reranking_model or None, + top_k=settings.default_top_k, + score_threshold_enabled=settings.default_score_threshold_enabled, + score_threshold=str(settings.default_score_threshold), + ) + db.add(system) + + primary_super_admin = db.query(User).filter(User.username == PRIMARY_SUPER_ADMIN_USERNAME).first() + if primary_super_admin is None: + primary_super_admin = User( + username=PRIMARY_SUPER_ADMIN_USERNAME, + full_name=settings.default_admin_name, + password_hash=hash_password(settings.default_admin_password), + role="super_admin", + is_active=True, + primary_department_id=None, + ) + db.add(primary_super_admin) + else: + primary_super_admin.role = "super_admin" + primary_super_admin.is_active = True + + legacy_adam = db.query(User).filter(User.username == "adam").first() + if legacy_adam is not None: + legacy_adam.role = "admin" + + if settings.default_admin_username and settings.default_admin_username != PRIMARY_SUPER_ADMIN_USERNAME: + secondary_admin = db.query(User).filter(User.username == settings.default_admin_username).first() + if secondary_admin is None: + secondary_admin = User( + username=settings.default_admin_username, + full_name=settings.default_admin_name, + password_hash=hash_password(settings.default_admin_password), + role="admin", + is_active=True, + primary_department_id=None, + ) + db.add(secondary_admin) + elif secondary_admin.role == "super_admin": + secondary_admin.role = "admin" + + other_super_admins = ( + db.query(User) + .filter(User.role == "super_admin", User.username != PRIMARY_SUPER_ADMIN_USERNAME) + .all() + ) + for user in other_super_admins: + user.role = "admin" + + db.flush() + + existing_access = { + (row.user_id, row.department_id) + for row in db.query(UserDepartmentAccess.user_id, UserDepartmentAccess.department_id).all() + } + for user in db.query(User).all(): + if user.primary_department_id is not None and (user.id, user.primary_department_id) not in existing_access: + db.add(UserDepartmentAccess(user_id=user.id, department_id=user.primary_department_id)) + + db.commit() diff --git a/backend/app/services/dify_service.py b/backend/app/services/dify_service.py new file mode 100644 index 00000000..d81e393f --- /dev/null +++ b/backend/app/services/dify_service.py @@ -0,0 +1,442 @@ +from __future__ import annotations + +import time +from dataclasses import dataclass +from typing import Any + +import requests + +from app.config import get_settings + + +class DifyError(RuntimeError): + pass + + +@dataclass +class DatasetRef: + id: str + name: str + + +@dataclass +class ModelRef: + provider: str + model: str + label: str + + +@dataclass +class RemoteDocumentRef: + id: str + name: str + indexing_status: str | None + display_status: str | None + enabled: bool + + +@dataclass +class RemoteDocumentSegment: + id: str + position: int + content: str + + +class DifyService: + preferred_embedding_models = ( + ("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Embedding-8B"), + ("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Embedding-4B"), + ("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Embedding-0.6B"), + ) + preferred_rerank_models = ( + ("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Reranker-8B"), + ("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Reranker-4B"), + ("langgenius/siliconflow/siliconflow", "Qwen/Qwen3-Reranker-0.6B"), + ) + + def __init__(self) -> None: + settings = get_settings() + self.base_url = settings.dify_base_url.rstrip("/") + self.api_key = settings.dify_api_key + self.permission = settings.dify_permission + self.timeout = 60 + + def _headers(self) -> dict[str, str]: + if not self.api_key: + raise DifyError("Dify API key is not configured.") + return {"Authorization": f"Bearer {self.api_key}"} + + def _request(self, method: str, path: str, **kwargs): + url = f"{self.base_url}{path}" + headers = kwargs.pop("headers", {}) + merged = self._headers() + merged.update(headers) + response = requests.request(method, url, headers=merged, timeout=self.timeout, **kwargs) + if response.status_code >= 400: + raise DifyError(f"Dify API {method} {path} failed: {response.status_code} {response.text}") + if response.status_code == 204: + return None + return response.json() + + def list_datasets(self) -> list[DatasetRef]: + payload = self._request("GET", "/datasets") + return [DatasetRef(id=item["id"], name=item["name"]) for item in payload.get("data", [])] + + def list_documents(self, *, dataset_id: str, limit: int = 100) -> list[RemoteDocumentRef]: + documents: list[RemoteDocumentRef] = [] + page = 1 + while True: + payload = self._request("GET", f"/datasets/{dataset_id}/documents", params={"page": page, "limit": limit}) + documents.extend( + [ + RemoteDocumentRef( + id=item["id"], + name=item.get("name") or "", + indexing_status=item.get("indexing_status"), + display_status=item.get("display_status"), + enabled=bool(item.get("enabled", True)), + ) + for item in payload.get("data", []) + ] + ) + if not payload.get("has_more"): + break + page += 1 + return documents + + def _list_models(self, *, model_type: str) -> list[ModelRef]: + payload = self._request("GET", f"/workspaces/current/models/model-types/{model_type}") + items: list[ModelRef] = [] + for provider_entry in payload.get("data", []): + if provider_entry.get("status") not in {None, "active"}: + continue + provider = provider_entry.get("provider") + provider_label = ( + provider_entry.get("label", {}).get("en_US") + or provider_entry.get("label", {}).get("zh_Hans") + or provider + ) + if not provider: + continue + for model_entry in provider_entry.get("models", []): + if model_entry.get("status") not in {None, "active"}: + continue + model = model_entry.get("model") + if not model: + continue + model_label = model_entry.get("label", {}).get("en_US") or model_entry.get("label", {}).get("zh_Hans") or model + items.append(ModelRef(provider=provider, model=model, label=f"{provider_label} / {model_label}")) + return items + + def list_available_embedding_models(self) -> list[ModelRef]: + return self._list_models(model_type="text-embedding") + + def list_available_rerank_models(self) -> list[ModelRef]: + return self._list_models(model_type="rerank") + + def _resolve_model_choice( + self, + *, + requested_provider: str | None, + requested_model: str | None, + available: list[ModelRef], + preferred: tuple[tuple[str, str], ...], + ) -> tuple[str | None, str | None]: + if requested_provider and requested_model: + return requested_provider, requested_model + if not available: + return None, None + available_keys = {(item.provider, item.model) for item in available} + for candidate in preferred: + if candidate in available_keys: + return candidate + first = available[0] + return first.provider, first.model + + def resolve_embedding_model_choice( + self, + *, + provider: str | None = None, + model: str | None = None, + ) -> tuple[str | None, str | None]: + return self._resolve_model_choice( + requested_provider=provider, + requested_model=model, + available=self.list_available_embedding_models(), + preferred=self.preferred_embedding_models, + ) + + def resolve_rerank_model_choice( + self, + *, + provider: str | None = None, + model: str | None = None, + ) -> tuple[str | None, str | None]: + return self._resolve_model_choice( + requested_provider=provider, + requested_model=model, + available=self.list_available_rerank_models(), + preferred=self.preferred_rerank_models, + ) + + def ensure_dataset( + self, + *, + dataset_name: str, + description: str | None, + permission: str | None, + indexing_technique: str, + search_method: str, + top_k: int, + score_threshold_enabled: bool, + score_threshold: float, + doc_form: str, + embedding_model_provider: str | None = None, + embedding_model: str | None = None, + reranking_model_provider: str | None = None, + reranking_model: str | None = None, + ) -> str: + resolved_embedding_provider, resolved_embedding_model = self.resolve_embedding_model_choice( + provider=embedding_model_provider, + model=embedding_model, + ) + resolved_rerank_provider, resolved_rerank_model = (None, None) + if search_method == "hybrid_search": + resolved_rerank_provider, resolved_rerank_model = self.resolve_rerank_model_choice( + provider=reranking_model_provider, + model=reranking_model, + ) + + existing = next((item for item in self.list_datasets() if item.name == dataset_name), None) + if existing: + self.update_dataset( + dataset_id=existing.id, + name=dataset_name, + description=description, + indexing_technique=indexing_technique, + search_method=search_method, + top_k=top_k, + score_threshold_enabled=score_threshold_enabled, + score_threshold=score_threshold, + doc_form=doc_form, + embedding_model_provider=resolved_embedding_provider, + embedding_model=resolved_embedding_model, + reranking_model_provider=resolved_rerank_provider, + reranking_model=resolved_rerank_model, + ) + return existing.id + + payload = { + "name": dataset_name, + "description": description or "", + "permission": permission or self.permission, + "indexing_technique": indexing_technique, + "doc_form": doc_form, + "retrieval_model": { + "search_method": search_method, + "reranking_enable": bool(resolved_rerank_provider and resolved_rerank_model), + "top_k": top_k, + "score_threshold_enabled": score_threshold_enabled, + "score_threshold": score_threshold, + }, + } + if resolved_embedding_provider and resolved_embedding_model: + payload["embedding_model_provider"] = resolved_embedding_provider + payload["embedding_model"] = resolved_embedding_model + if resolved_rerank_provider and resolved_rerank_model: + payload["retrieval_model"]["reranking_mode"] = "reranking_model" + payload["retrieval_model"]["reranking_model"] = { + "reranking_provider_name": resolved_rerank_provider, + "reranking_model_name": resolved_rerank_model, + } + created = self._request("POST", "/datasets", json=payload) + dataset_id = created["id"] + self.update_dataset( + dataset_id=dataset_id, + name=dataset_name, + description=description, + indexing_technique=indexing_technique, + search_method=search_method, + top_k=top_k, + score_threshold_enabled=score_threshold_enabled, + score_threshold=score_threshold, + doc_form=doc_form, + embedding_model_provider=resolved_embedding_provider, + embedding_model=resolved_embedding_model, + reranking_model_provider=resolved_rerank_provider, + reranking_model=resolved_rerank_model, + ) + return dataset_id + + def update_dataset( + self, + *, + dataset_id: str, + name: str | None = None, + description: str | None = None, + indexing_technique: str | None = None, + search_method: str | None = None, + top_k: int | None = None, + score_threshold_enabled: bool | None = None, + score_threshold: float | None = None, + doc_form: str | None = None, + embedding_model_provider: str | None = None, + embedding_model: str | None = None, + reranking_model_provider: str | None = None, + reranking_model: str | None = None, + ) -> dict: + payload: dict[str, object] = {} + if name is not None: + payload["name"] = name + if description is not None: + payload["description"] = description + if indexing_technique is not None: + payload["indexing_technique"] = indexing_technique + if doc_form is not None: + payload["doc_form"] = doc_form + if embedding_model_provider is not None and embedding_model is not None: + payload["embedding_model_provider"] = embedding_model_provider + payload["embedding_model"] = embedding_model + if ( + search_method is not None + or top_k is not None + or score_threshold_enabled is not None + or score_threshold is not None + or reranking_model_provider is not None + or reranking_model is not None + ): + reranking_enabled = bool(reranking_model_provider and reranking_model and (search_method or "hybrid_search") == "hybrid_search") + payload["retrieval_model"] = { + "search_method": search_method or "hybrid_search", + "reranking_enable": reranking_enabled, + "top_k": top_k if top_k is not None else 5, + "score_threshold_enabled": bool(score_threshold_enabled), + "score_threshold": score_threshold if score_threshold_enabled else None, + } + if reranking_enabled: + payload["retrieval_model"]["reranking_mode"] = "reranking_model" + payload["retrieval_model"]["reranking_model"] = { + "reranking_provider_name": reranking_model_provider, + "reranking_model_name": reranking_model, + } + return self._request("PATCH", f"/datasets/{dataset_id}", json=payload) + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + payload = { + "name": name, + "text": text, + "indexing_technique": indexing_technique, + "doc_form": doc_form, + "process_rule": {"mode": "automatic"}, + } + return self._request("POST", f"/datasets/{dataset_id}/document/create-by-text", json=payload) + + def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict: + payload = { + "name": name, + "text": text, + "process_rule": {"mode": "automatic"}, + } + return self._request( + "POST", + f"/datasets/{dataset_id}/documents/{document_id}/update-by-text", + json=payload, + ) + + def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict: + return self._request("GET", f"/datasets/{dataset_id}/documents/{document_id}") + + def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100) -> list[RemoteDocumentSegment]: + segments: list[RemoteDocumentSegment] = [] + page = 1 + while True: + payload = self._request( + "GET", + f"/datasets/{dataset_id}/documents/{document_id}/segments", + params={"page": page, "limit": limit}, + ) + items = payload.get("data", []) if isinstance(payload, dict) else [] + segments.extend( + [ + RemoteDocumentSegment( + id=item.get("id") or "", + position=int(item.get("position") or 0), + content=item.get("content") or "", + ) + for item in items + ] + ) + if not payload.get("has_more"): + break + page += 1 + segments.sort(key=lambda item: item.position) + return segments + + def get_upload_file(self, *, dataset_id: str, document_id: str) -> dict[str, Any] | None: + try: + payload = self._request("GET", f"/datasets/{dataset_id}/documents/{document_id}/upload-file") + except DifyError as exc: + message = str(exc) + if " 404 " in message or '"status":404' in message: + return None + raise + return payload if isinstance(payload, dict) else None + + def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]: + payload = self._request("GET", f"/datasets/{dataset_id}/documents/{batch}/indexing-status") + return payload.get("data", []) + + def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict: + deadline = time.time() + timeout_seconds + latest: dict | None = None + while time.time() < deadline: + data = self.get_indexing_status(dataset_id=dataset_id, batch=batch) + latest = data[0] if data else None + status = (latest or {}).get("indexing_status") + if status in {"completed", "completed_with_warning"}: + return latest or {} + if status in {"error", "failed", "stopped"}: + raise DifyError((latest or {}).get("error") or f"Indexing failed with status={status}") + time.sleep(5) + last_status = (latest or {}).get("indexing_status") or "unknown" + last_display_status = (latest or {}).get("display_status") or "unknown" + raise DifyError( + f"Timed out waiting for Dify indexing. Last indexing_status={last_status}, display_status={last_display_status}." + ) + + def wait_for_document_indexing( + self, + *, + dataset_id: str, + document_id: str, + timeout_seconds: int = 300, + ) -> dict: + deadline = time.time() + timeout_seconds + latest: dict | None = None + while time.time() < deadline: + latest = self.get_document_detail(dataset_id=dataset_id, document_id=document_id) + status = (latest or {}).get("indexing_status") + if status in {"completed", "completed_with_warning"}: + return latest or {} + if status in {"error", "failed", "stopped"}: + raise DifyError((latest or {}).get("error") or f"Indexing failed with status={status}") + time.sleep(5) + last_status = (latest or {}).get("indexing_status") or "unknown" + last_display_status = (latest or {}).get("display_status") or "unknown" + raise DifyError( + f"Timed out waiting for Dify indexing. Last indexing_status={last_status}, display_status={last_display_status}." + ) + + def delete_document(self, *, dataset_id: str, document_id: str) -> None: + self._request("DELETE", f"/datasets/{dataset_id}/documents/{document_id}") + + def delete_dataset(self, *, dataset_id: str) -> None: + self._request("DELETE", f"/datasets/{dataset_id}") diff --git a/backend/app/services/queue_service.py b/backend/app/services/queue_service.py new file mode 100644 index 00000000..dbf51be9 --- /dev/null +++ b/backend/app/services/queue_service.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import importlib +import traceback +from datetime import timedelta + +from app.config import get_settings + + +DIFY_SYNC_COOLDOWN_GATE = "dify-sync-cooldown" + + +class InlineJobRef: + def __init__(self, job_id: str) -> None: + self.id = job_id + + +class InlineQueue: + def enqueue(self, task_name: str, *args, **kwargs) -> InlineJobRef: + job_id = str(args[0]) if args else f"inline:{task_name}" + module_name, function_name = task_name.rsplit(".", 1) + task = getattr(importlib.import_module(module_name), function_name) + try: + task(*args, **kwargs) + except Exception: + traceback.print_exc() + return InlineJobRef(f"inline:{job_id}") + + def enqueue_in(self, delay: timedelta, task_name: str, *args, **kwargs) -> InlineJobRef: + if delay.total_seconds() <= 0: + return self.enqueue(task_name, *args, **kwargs) + job_id = str(args[0]) if args else f"inline:{task_name}" + return InlineJobRef(f"inline-delayed:{job_id}") + + +def get_redis_connection(): + settings = get_settings() + if settings.task_execution_mode == "sync": + return None + + from redis import Redis + + return Redis.from_url(settings.redis_url) + + +def _gate_key(name: str) -> str: + settings = get_settings() + return f"{settings.rq_queue_name}:{name}" + + +def set_delay_gate(name: str, ttl_seconds: int) -> None: + redis = get_redis_connection() + if redis is None or ttl_seconds <= 0: + return + try: + redis.setex(_gate_key(name), ttl_seconds, "1") + except Exception: + return + + +def get_delay_gate_ttl(name: str) -> int: + redis = get_redis_connection() + if redis is None: + return 0 + try: + ttl = redis.ttl(_gate_key(name)) + except Exception: + return 0 + if ttl is None or ttl < 0: + return 0 + return int(ttl) + + +def get_queue(): + settings = get_settings() + if settings.task_execution_mode == "sync": + return InlineQueue() + + from rq import Queue + + redis = get_redis_connection() + return Queue(name=settings.rq_queue_name, connection=redis, default_timeout=settings.rq_default_timeout) diff --git a/backend/app/services/storage_service.py b/backend/app/services/storage_service.py new file mode 100644 index 00000000..2d394cae --- /dev/null +++ b/backend/app/services/storage_service.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import base64 +import hashlib +import mimetypes +import re +import shutil +import zipfile +from pathlib import Path + +from app.config import get_settings + + +settings = get_settings() + +DATA_IMAGE_RE = re.compile( + r"!\[(?P[^\]]*)\]\((?Pdata:image/(?P[a-zA-Z0-9.+-]+);base64,(?P[^)]+))\)", + re.IGNORECASE | re.DOTALL, +) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while True: + chunk = handle.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) + return digest.hexdigest() + + +def group_dir(group_id: int, category: str) -> Path: + return settings.data_root / category / f"group_{group_id:04d}" + + +def version_dir(category: str, group_id: int, document_id: int, version_no: int) -> Path: + return group_dir(group_id, category) / f"document_{document_id:06d}" / f"v{version_no:03d}" + + +def public_storage_url(path: Path) -> str: + relative = path.relative_to(settings.data_root).as_posix() + return f"{settings.public_base_url.rstrip('/')}/storage/{relative}" + + +def guess_image_ext(fmt: str) -> str: + fmt = fmt.lower().strip() + if fmt in {"jpeg", "jpg"}: + return "jpg" + if fmt in {"png", "gif", "bmp", "webp"}: + return fmt + return "png" + + +def rewrite_embedded_images(markdown_text: str, assets_dir: Path) -> tuple[str, int]: + assets_dir.mkdir(parents=True, exist_ok=True) + seen: dict[str, str] = {} + count = 0 + + def repl(match: re.Match[str]) -> str: + nonlocal count + alt = match.group("alt") or "image" + fmt = guess_image_ext(match.group("fmt") or "png") + raw = base64.b64decode(match.group("b64")) + digest = hashlib.sha256(raw).hexdigest() + existing = seen.get(digest) + if existing is None: + count += 1 + filename = f"img_{count:03d}_{digest[:8]}.{fmt}" + target = assets_dir / filename + target.write_bytes(raw) + existing = filename + seen[digest] = existing + return f"![{alt}]({existing})" + + return DATA_IMAGE_RE.sub(repl, markdown_text), len(seen) + + +def remove_path_if_exists(path: Path) -> None: + if path.is_dir(): + shutil.rmtree(path, ignore_errors=True) + elif path.exists(): + path.unlink(missing_ok=True) + + +def build_zip(source_paths: list[tuple[Path, str]], output_path: Path) -> Path: + output_path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as archive: + for path, archive_name in source_paths: + if path.exists(): + archive.write(path, arcname=archive_name) + return output_path diff --git a/backend/app/services/watchdog_service.py b/backend/app/services/watchdog_service.py new file mode 100644 index 00000000..cacf11f3 --- /dev/null +++ b/backend/app/services/watchdog_service.py @@ -0,0 +1,495 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from datetime import timedelta, timezone +from pathlib import Path +from typing import Any + +from redis import Redis +from sqlalchemy.orm import Session + +from app.config import Settings, get_settings +from app.models import DifySyncRecord, DocumentVersion, Job +from app.time_utils import utc_now + + +SNAPSHOT_RELATIVE_PATH = Path("watchdog/dify-health.json") + + +@dataclass +class StaleSyncCandidate: + version: DocumentVersion + active_job: Job | None + sync_record: DifySyncRecord | None + reason: str + age_seconds: int + + +@dataclass +class StaleConvertCandidate: + version: DocumentVersion + active_job: Job | None + reason: str + age_seconds: int + + +def _as_aware_utc(value): + if value is None: + return None + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc) + + +def _live_queue_job_ids(settings: Settings | None = None) -> set[str] | None: + resolved = settings or get_settings() + try: + redis = Redis.from_url(resolved.redis_url) + raw_ids = redis.lrange(f"rq:queue:{resolved.rq_queue_name}", 0, -1) + return {item.decode("utf-8") if isinstance(item, bytes) else str(item) for item in raw_ids} + except Exception: + return None + + +def watchdog_snapshot_path(settings: Settings | None = None) -> Path: + resolved = settings or get_settings() + path = resolved.data_root / SNAPSHOT_RELATIVE_PATH + path.parent.mkdir(parents=True, exist_ok=True) + return path + + +def read_watchdog_snapshot(settings: Settings | None = None) -> dict[str, Any] | None: + path = watchdog_snapshot_path(settings) + if not path.exists(): + return None + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + return { + "available": False, + "status": "invalid_snapshot", + "path": str(path), + "error": str(exc), + } + + if isinstance(payload, dict): + payload.setdefault("available", True) + payload.setdefault("path", str(path)) + return payload + + return { + "available": False, + "status": "invalid_snapshot", + "path": str(path), + "error": "Snapshot must be a JSON object.", + } + + +def local_sync_health_summary(db: Session, *, timeout_seconds: int) -> dict[str, Any]: + stale_candidates = find_stale_sync_candidates(db, timeout_seconds=timeout_seconds) + recent_failures = ( + db.query(Job) + .filter(Job.job_type == "sync", Job.status == "failed") + .order_by(Job.created_at.desc()) + .limit(5) + .all() + ) + active_jobs = ( + db.query(Job) + .filter(Job.job_type == "sync", Job.status.in_(("queued", "running"))) + .order_by(Job.created_at.desc()) + .all() + ) + syncing_versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "syncing").count() + sync_failed_versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "sync_failed").count() + + return { + "timeout_seconds": timeout_seconds, + "syncing_versions": syncing_versions, + "sync_failed_versions": sync_failed_versions, + "active_sync_jobs": len(active_jobs), + "stale_candidates": len(stale_candidates), + "active_jobs": [ + { + "id": job.id, + "document_id": job.document_id, + "version_id": job.version_id, + "status": job.status, + "created_at": job.created_at.isoformat() if job.created_at else None, + "started_at": job.started_at.isoformat() if job.started_at else None, + "message": job.message, + } + for job in active_jobs[:10] + ], + "recent_failures": [ + { + "id": job.id, + "document_id": job.document_id, + "version_id": job.version_id, + "created_at": job.created_at.isoformat() if job.created_at else None, + "finished_at": job.finished_at.isoformat() if job.finished_at else None, + "error": job.error, + } + for job in recent_failures + ], + "stale_versions": [ + { + "document_id": candidate.version.document_id, + "version_id": candidate.version.id, + "active_job_id": candidate.active_job.id if candidate.active_job else None, + "sync_record_id": candidate.sync_record.id if candidate.sync_record else None, + "remote_document_id": candidate.sync_record.remote_document_id if candidate.sync_record else None, + "age_seconds": candidate.age_seconds, + "reason": candidate.reason, + } + for candidate in stale_candidates[:20] + ], + } + + +def local_convert_health_summary( + db: Session, + *, + timeout_seconds: int, + orphan_grace_seconds: int, + settings: Settings | None = None, +) -> dict[str, Any]: + stale_candidates = find_stale_convert_candidates( + db, + timeout_seconds=timeout_seconds, + orphan_grace_seconds=orphan_grace_seconds, + settings=settings, + ) + recent_failures = ( + db.query(Job) + .filter(Job.job_type == "convert", Job.status == "failed") + .order_by(Job.created_at.desc()) + .limit(5) + .all() + ) + active_jobs = ( + db.query(Job) + .filter(Job.job_type == "convert", Job.status.in_(("queued", "running"))) + .order_by(Job.created_at.desc()) + .all() + ) + pending_versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status.in_(("queued", "running"))).count() + failed_versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status == "failed").count() + + return { + "timeout_seconds": timeout_seconds, + "orphan_grace_seconds": orphan_grace_seconds, + "pending_versions": pending_versions, + "failed_versions": failed_versions, + "active_convert_jobs": len(active_jobs), + "stale_candidates": len(stale_candidates), + "active_jobs": [ + { + "id": job.id, + "document_id": job.document_id, + "version_id": job.version_id, + "status": job.status, + "queue_job_id": job.queue_job_id, + "created_at": job.created_at.isoformat() if job.created_at else None, + "started_at": job.started_at.isoformat() if job.started_at else None, + "message": job.message, + } + for job in active_jobs[:10] + ], + "recent_failures": [ + { + "id": job.id, + "document_id": job.document_id, + "version_id": job.version_id, + "created_at": job.created_at.isoformat() if job.created_at else None, + "finished_at": job.finished_at.isoformat() if job.finished_at else None, + "error": job.error, + } + for job in recent_failures + ], + "stale_versions": [ + { + "document_id": candidate.version.document_id, + "version_id": candidate.version.id, + "active_job_id": candidate.active_job.id if candidate.active_job else None, + "age_seconds": candidate.age_seconds, + "reason": candidate.reason, + } + for candidate in stale_candidates[:20] + ], + } + + +def find_stale_sync_candidates(db: Session, *, timeout_seconds: int) -> list[StaleSyncCandidate]: + cutoff = utc_now() - timedelta(seconds=timeout_seconds) + versions = db.query(DocumentVersion).filter(DocumentVersion.sync_status == "syncing").all() + candidates: list[StaleSyncCandidate] = [] + + for version in versions: + active_job = ( + db.query(Job) + .filter( + Job.version_id == version.id, + Job.job_type == "sync", + Job.status.in_(("queued", "running")), + ) + .order_by(Job.created_at.desc()) + .first() + ) + sync_record = ( + db.query(DifySyncRecord) + .filter( + DifySyncRecord.version_id == version.id, + DifySyncRecord.status == "syncing", + ) + .order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc()) + .first() + ) + + candidate: StaleSyncCandidate | None = None + active_job_created_at = _as_aware_utc(active_job.created_at) if active_job else None + sync_record_updated_at = _as_aware_utc(sync_record.updated_at) if sync_record else None + sync_record_created_at = _as_aware_utc(sync_record.created_at) if sync_record else None + uploaded_at = _as_aware_utc(version.uploaded_at) + + if active_job and active_job_created_at and active_job_created_at <= cutoff: + age_seconds = int((utc_now() - active_job_created_at).total_seconds()) + candidate = StaleSyncCandidate( + version=version, + active_job=active_job, + sync_record=sync_record, + reason="Sync job exceeded watchdog timeout.", + age_seconds=age_seconds, + ) + elif sync_record and sync_record_updated_at and sync_record_updated_at <= cutoff: + age_seconds = int((utc_now() - sync_record_updated_at).total_seconds()) + candidate = StaleSyncCandidate( + version=version, + active_job=active_job, + sync_record=sync_record, + reason="Sync record exceeded watchdog timeout without completion.", + age_seconds=age_seconds, + ) + elif not active_job: + baseline = None + if sync_record_created_at: + baseline = sync_record_created_at + elif uploaded_at: + baseline = uploaded_at + + if baseline and baseline <= cutoff: + age_seconds = int((utc_now() - baseline).total_seconds()) + candidate = StaleSyncCandidate( + version=version, + active_job=None, + sync_record=sync_record, + reason="Sync status has no active job and exceeded watchdog timeout.", + age_seconds=age_seconds, + ) + + if candidate is not None: + candidates.append(candidate) + + return candidates + + +def find_stale_convert_candidates( + db: Session, + *, + timeout_seconds: int, + orphan_grace_seconds: int, + settings: Settings | None = None, +) -> list[StaleConvertCandidate]: + cutoff = utc_now() - timedelta(seconds=timeout_seconds) + orphan_cutoff = utc_now() - timedelta(seconds=orphan_grace_seconds) + live_queue_job_ids = _live_queue_job_ids(settings) + versions = db.query(DocumentVersion).filter(DocumentVersion.convert_status.in_(("queued", "running"))).all() + candidates: list[StaleConvertCandidate] = [] + + for version in versions: + active_job = ( + db.query(Job) + .filter( + Job.version_id == version.id, + Job.job_type == "convert", + Job.status.in_(("queued", "running")), + ) + .order_by(Job.created_at.desc()) + .first() + ) + + candidate: StaleConvertCandidate | None = None + active_job_created_at = _as_aware_utc(active_job.created_at) if active_job else None + active_job_started_at = _as_aware_utc(active_job.started_at) if active_job else None + uploaded_at = _as_aware_utc(version.uploaded_at) + queue_job_present = ( + bool(active_job and active_job.queue_job_id) + and live_queue_job_ids is not None + and active_job.queue_job_id in live_queue_job_ids + ) + + if active_job and active_job.status == "running": + baseline = active_job_started_at or active_job_created_at + if baseline and baseline <= cutoff: + age_seconds = int((utc_now() - baseline).total_seconds()) + candidate = StaleConvertCandidate( + version=version, + active_job=active_job, + reason="Convert job exceeded watchdog timeout while running.", + age_seconds=age_seconds, + ) + elif active_job and active_job.status == "queued": + if active_job.queue_job_id and live_queue_job_ids is not None and not queue_job_present and active_job_created_at and active_job_created_at <= orphan_cutoff: + age_seconds = int((utc_now() - active_job_created_at).total_seconds()) + candidate = StaleConvertCandidate( + version=version, + active_job=active_job, + reason="Convert job is missing from Redis queue beyond watchdog grace period.", + age_seconds=age_seconds, + ) + elif not active_job.queue_job_id and active_job_created_at and active_job_created_at <= orphan_cutoff: + age_seconds = int((utc_now() - active_job_created_at).total_seconds()) + candidate = StaleConvertCandidate( + version=version, + active_job=active_job, + reason="Convert job has no queue id and exceeded watchdog grace period.", + age_seconds=age_seconds, + ) + elif not active_job and uploaded_at and uploaded_at <= orphan_cutoff: + age_seconds = int((utc_now() - uploaded_at).total_seconds()) + candidate = StaleConvertCandidate( + version=version, + active_job=None, + reason="Convert status has no active job and exceeded watchdog grace period.", + age_seconds=age_seconds, + ) + + if candidate is not None: + candidates.append(candidate) + + return candidates + + +def recover_stale_syncs( + db: Session, + *, + timeout_seconds: int, + reason_prefix: str = "Marked stale by watchdog after timeout.", +) -> dict[str, Any]: + candidates = find_stale_sync_candidates(db, timeout_seconds=timeout_seconds) + now = utc_now() + recovered_versions = 0 + recovered_jobs = 0 + recovered_records = 0 + documents: list[dict[str, Any]] = [] + seen_versions: set[int] = set() + + for candidate in candidates: + version = candidate.version + if version.id in seen_versions: + continue + seen_versions.add(version.id) + + if version.sync_status == "syncing": + version.sync_status = "sync_failed" + recovered_versions += 1 + + if candidate.active_job and candidate.active_job.status in {"queued", "running"}: + candidate.active_job.status = "failed" + candidate.active_job.message = "Dify sync failed" + candidate.active_job.error = f"{reason_prefix} {candidate.reason}" + candidate.active_job.finished_at = now + recovered_jobs += 1 + + syncing_records = db.query(DifySyncRecord).filter( + DifySyncRecord.version_id == version.id, + DifySyncRecord.status == "syncing", + ) + for record in syncing_records: + record.status = "sync_failed" + record.error = record.error or f"{reason_prefix} {candidate.reason}" + recovered_records += 1 + + documents.append( + { + "document_id": version.document_id, + "version_id": version.id, + "active_job_id": candidate.active_job.id if candidate.active_job else None, + "sync_record_id": candidate.sync_record.id if candidate.sync_record else None, + "remote_document_id": candidate.sync_record.remote_document_id if candidate.sync_record else None, + "age_seconds": candidate.age_seconds, + "reason": candidate.reason, + } + ) + + if recovered_versions or recovered_jobs or recovered_records: + db.commit() + + return { + "timeout_seconds": timeout_seconds, + "recovered_versions": recovered_versions, + "recovered_jobs": recovered_jobs, + "recovered_records": recovered_records, + "documents": documents, + } + + +def recover_stale_converts( + db: Session, + *, + timeout_seconds: int, + orphan_grace_seconds: int, + reason_prefix: str = "Marked convert as failed by watchdog.", + settings: Settings | None = None, +) -> dict[str, Any]: + candidates = find_stale_convert_candidates( + db, + timeout_seconds=timeout_seconds, + orphan_grace_seconds=orphan_grace_seconds, + settings=settings, + ) + now = utc_now() + recovered_versions = 0 + recovered_jobs = 0 + documents: list[dict[str, Any]] = [] + seen_versions: set[int] = set() + + for candidate in candidates: + version = candidate.version + if version.id in seen_versions: + continue + seen_versions.add(version.id) + + if version.convert_status in {"queued", "running"}: + version.convert_status = "failed" + version.failed_reason = f"{reason_prefix} {candidate.reason}" + recovered_versions += 1 + + if candidate.active_job and candidate.active_job.status in {"queued", "running"}: + candidate.active_job.status = "failed" + candidate.active_job.message = "Conversion failed" + candidate.active_job.error = f"{reason_prefix} {candidate.reason}" + candidate.active_job.finished_at = now + recovered_jobs += 1 + + documents.append( + { + "document_id": version.document_id, + "version_id": version.id, + "active_job_id": candidate.active_job.id if candidate.active_job else None, + "age_seconds": candidate.age_seconds, + "reason": candidate.reason, + } + ) + + if recovered_versions or recovered_jobs: + db.commit() + + return { + "timeout_seconds": timeout_seconds, + "orphan_grace_seconds": orphan_grace_seconds, + "recovered_versions": recovered_versions, + "recovered_jobs": recovered_jobs, + "documents": documents, + } diff --git a/backend/app/tasks.py b/backend/app/tasks.py new file mode 100644 index 00000000..f782e824 --- /dev/null +++ b/backend/app/tasks.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import os +import shutil +from datetime import timedelta +from pathlib import Path + +from sqlalchemy.orm import Session + +from app.config import get_settings +from app.database import SessionLocal +from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, SystemSetting +from app.services.dify_service import DifyError, DifyService +from app.services.queue_service import ( + DIFY_SYNC_COOLDOWN_GATE, + get_delay_gate_ttl, + get_queue, + set_delay_gate, +) +from app.services.storage_service import ( + public_storage_url, + rewrite_embedded_images, + version_dir, +) +from app.time_utils import utc_now +from edkb_system.config import SystemConfig +from edkb_system.controller import build_knowledge + + +def _db() -> Session: + return SessionLocal() + + +def _find_generated_markdown(output_root: Path) -> Path: + candidates = [path for path in output_root.rglob("*.md") if not path.name.startswith("_")] + if not candidates: + raise RuntimeError("No markdown output produced by edkb_system.") + candidates.sort(key=lambda item: len(item.parts)) + return candidates[0] + + +def _set_job_running(db: Session, job: Job, message: str) -> None: + job.status = "running" + job.progress = 10 + job.message = message + job.started_at = utc_now() + db.commit() + + +def _payload_dict(job: Job) -> dict: + return dict(job.payload or {}) + + +def _is_retryable_dify_error(exc: Exception) -> bool: + message = str(exc).lower() + if "too many clients already" in message: + return True + if "timed out waiting for dify indexing" in message and ("waiting" in message or "queuing" in message): + return True + return False + + +def _retry_delay_seconds(attempt: int) -> int: + settings = get_settings() + delays = settings.dify_sync_retry_delays() + index = max(0, min(attempt - 1, len(delays) - 1)) + return delays[index] + + +def _requeue_sync_job( + db: Session, + *, + job: Job, + version: DocumentVersion, + retry_count: int, + delay_seconds: int, + message: str, + last_error: str | None = None, +) -> None: + queue = get_queue() + rq_job = queue.enqueue_in(timedelta(seconds=delay_seconds), "app.tasks.run_sync_job", job.id, version.id) + payload = _payload_dict(job) + payload["sync_retry_count"] = retry_count + payload["sync_retry_after_seconds"] = delay_seconds + if last_error: + payload["sync_last_error"] = last_error + job.payload = payload + job.queue_job_id = rq_job.id + job.status = "queued" + job.progress = 0 + job.message = message + job.error = None + job.started_at = None + job.finished_at = None + version.sync_status = "syncing" + db.commit() + + +def _schedule_retryable_sync( + db: Session, + *, + job: Job, + version: DocumentVersion, + exc: Exception, +) -> bool: + settings = get_settings() + if settings.task_execution_mode == "sync": + # Sync mode has no delayed executor, so fail visibly instead of leaving the job queued forever. + return False + payload = _payload_dict(job) + current_retry_count = int(payload.get("sync_retry_count") or 0) + if current_retry_count >= settings.dify_sync_max_retries: + return False + + next_retry_count = current_retry_count + 1 + delay_seconds = _retry_delay_seconds(next_retry_count) + cooldown_seconds = max(delay_seconds, settings.dify_sync_cooldown_seconds) + set_delay_gate(DIFY_SYNC_COOLDOWN_GATE, cooldown_seconds) + _requeue_sync_job( + db, + job=job, + version=version, + retry_count=next_retry_count, + delay_seconds=delay_seconds, + message=f"Dify busy, retrying in {delay_seconds}s (attempt {next_retry_count}/{settings.dify_sync_max_retries}).", + last_error=str(exc), + ) + return True + + +def _defer_sync_for_cooldown( + db: Session, + *, + job: Job, + version: DocumentVersion, + cooldown_ttl: int, +) -> None: + retry_count = int(_payload_dict(job).get("sync_retry_count") or 0) + delay_seconds = max(5, cooldown_ttl) + _requeue_sync_job( + db, + job=job, + version=version, + retry_count=retry_count, + delay_seconds=delay_seconds, + message=f"Dify cooldown active, retrying in {delay_seconds}s.", + ) + + +def run_convert_job(job_id: str, version_id: int) -> None: + settings = get_settings() + os.environ["EDKB_WORD_TIMEOUT_SEC"] = str(settings.edkb_word_timeout_sec) + os.environ["EDKB_FILE_TIMEOUT_SEC"] = str(settings.edkb_file_timeout_sec) + # Keep image extraction inside this system. The bundled converter + # defaults to external image-hosting unless explicitly disabled. + os.environ["MINIO_UPLOAD_ENABLED"] = "false" + os.environ["MINIO_ALLOW_EMBED_FALLBACK"] = "true" + + db = _db() + try: + job = db.query(Job).filter(Job.id == job_id).first() + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + if not job or not version: + return + _set_job_running(db, job, "Converting source document") + version.convert_status = "running" + version.failed_reason = None + db.commit() + + document = db.query(Document).filter(Document.id == version.document_id).first() + if not document: + raise RuntimeError("Document not found.") + + work_root = settings.data_root / "jobs" / job.id + input_dir = work_root / "input" + output_dir = work_root / "output" + cache_dir = work_root / "cache" + input_dir.mkdir(parents=True, exist_ok=True) + output_dir.mkdir(parents=True, exist_ok=True) + cache_dir.mkdir(parents=True, exist_ok=True) + + staged_source = input_dir / version.source_filename + shutil.copy2(version.source_path, staged_source) + + config = SystemConfig.load(None) + result = build_knowledge(staged_source, output_dir, config, cache_dir) + failures = [item for item in result if item.get("status") == "failed"] + if failures: + raise RuntimeError(failures[0].get("error") or "Conversion failed.") + markdown_source = _find_generated_markdown(output_dir) + raw_markdown = markdown_source.read_text(encoding="utf-8") + + markdown_target_dir = version_dir("markdown", document.group_id, document.id, version.version_no) + assets_target_dir = version_dir("assets", document.group_id, document.id, version.version_no) + markdown_target_dir.mkdir(parents=True, exist_ok=True) + markdown_target = markdown_target_dir / "document.md" + rewritten_markdown, image_count = rewrite_embedded_images(raw_markdown, assets_target_dir) + asset_prefix = public_storage_url(assets_target_dir) + rewritten_markdown = rewritten_markdown.replace("](img_", f"]({asset_prefix}/img_") + asset_dir_value = str(assets_target_dir.relative_to(settings.data_root)) + markdown_target.write_text(rewritten_markdown, encoding="utf-8") + + previous_synced = ( + db.query(DifySyncRecord) + .join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id) + .filter(DocumentVersion.document_id == document.id, DifySyncRecord.status == "synced") + .first() + ) + + version.md_path = str(markdown_target) + version.md_public_url = public_storage_url(markdown_target) + version.asset_dir = asset_dir_value + version.word_count = len(rewritten_markdown.split()) + version.convert_status = "success" + version.sync_status = "stale" if previous_synced else "unsynced" + version.converted_at = utc_now() + version.warnings_json = [{"message": f"embedded_images={image_count}"}] + + job.status = "success" + job.progress = 100 + job.message = "Conversion completed" + job.result = { + "md_path": version.md_path, + "md_public_url": version.md_public_url, + "image_count": image_count, + } + job.finished_at = utc_now() + db.commit() + shutil.rmtree(work_root, ignore_errors=True) + except Exception as exc: + if "job" in locals() and job is not None: + job.status = "failed" + job.error = str(exc) + job.message = "Conversion failed" + job.finished_at = utc_now() + if "version" in locals() and version is not None: + version.convert_status = "failed" + version.failed_reason = str(exc) + db.commit() + raise + finally: + db.close() + + +def run_sync_job(job_id: str, version_id: int) -> None: + settings = get_settings() + db = _db() + sync_record = None + try: + job = db.query(Job).filter(Job.id == job_id).first() + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + if not job or not version: + return + cooldown_ttl = get_delay_gate_ttl(DIFY_SYNC_COOLDOWN_GATE) + if cooldown_ttl > 0: + _defer_sync_for_cooldown(db, job=job, version=version, cooldown_ttl=cooldown_ttl) + return + _set_job_running(db, job, "Syncing document to Dify") + if version.convert_status != "success" or not version.md_path: + raise RuntimeError("Document is not ready for Dify sync.") + + document = db.query(Document).filter(Document.id == version.document_id).first() + group = db.query(Group).filter(Group.id == document.group_id).first() if document else None + if not document or not group: + raise RuntimeError("Document group not found.") + + version.sync_status = "syncing" + db.commit() + + dify = DifyService() + system = db.query(SystemSetting).filter(SystemSetting.id == 1).first() + dataset_id = dify.ensure_dataset( + dataset_name=group.name, + description=group.description, + permission=system.dify_permission if system else None, + indexing_technique=group.indexing_technique, + search_method=group.search_method, + top_k=group.top_k, + score_threshold_enabled=group.score_threshold_enabled, + score_threshold=float(group.score_threshold), + doc_form=group.doc_form, + embedding_model_provider=system.embedding_model_provider if system else None, + embedding_model=system.embedding_model if system else None, + reranking_model_provider=system.reranking_model_provider if system else None, + reranking_model=system.reranking_model if system else None, + ) + if group.dify_dataset_id != dataset_id: + group.dify_dataset_id = dataset_id + db.commit() + + sync_record = ( + db.query(DifySyncRecord) + .filter(DifySyncRecord.version_id == version.id, DifySyncRecord.status == "syncing") + .order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc()) + .first() + ) + + if sync_record and sync_record.dataset_id == dataset_id and sync_record.remote_document_id: + if sync_record.batch: + indexing = dify.wait_for_indexing(dataset_id=dataset_id, batch=sync_record.batch) + else: + indexing = dify.wait_for_document_indexing( + dataset_id=dataset_id, + document_id=sync_record.remote_document_id, + ) + + sync_record.status = "synced" + sync_record.last_indexing_status = indexing.get("indexing_status", "completed") + sync_record.last_synced_at = utc_now() + sync_record.error = None + version.sync_status = "synced" + job.status = "success" + job.progress = 100 + job.message = "Dify sync completed" + job.error = None + job.result = { + "dataset_id": dataset_id, + "remote_document_id": sync_record.remote_document_id, + "batch": sync_record.batch, + "indexing_status": sync_record.last_indexing_status, + } + job.finished_at = utc_now() + db.commit() + return + + markdown_text = Path(version.md_path).read_text(encoding="utf-8") + existing_record = ( + db.query(DifySyncRecord) + .join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id) + .filter(DocumentVersion.document_id == document.id) + .order_by(DifySyncRecord.updated_at.desc()) + .first() + ) + + previous_remote_document_id = existing_record.remote_document_id if existing_record else None + if previous_remote_document_id: + try: + dify.delete_document(dataset_id=dataset_id, document_id=previous_remote_document_id) + except DifyError: + # Failed or stale remote documents should not block a fresh resync. + pass + + response = dify.create_document_by_text( + dataset_id=dataset_id, + name=document.title, + text=markdown_text, + doc_form=group.doc_form, + indexing_technique=group.indexing_technique, + ) + sync_record = DifySyncRecord( + version_id=version.id, + dataset_id=dataset_id, + remote_document_id=response["document"]["id"], + batch=response.get("batch"), + status="syncing", + ) + db.add(sync_record) + db.commit() + + batch = sync_record.batch + if batch: + indexing = dify.wait_for_indexing(dataset_id=dataset_id, batch=batch) + else: + indexing = dify.wait_for_document_indexing( + dataset_id=dataset_id, + document_id=sync_record.remote_document_id, + ) + + sync_record.status = "synced" + sync_record.last_indexing_status = indexing.get("indexing_status", "completed") + sync_record.last_synced_at = utc_now() + sync_record.error = None + version.sync_status = "synced" + job.status = "success" + job.progress = 100 + job.message = "Dify sync completed" + job.result = { + "dataset_id": dataset_id, + "remote_document_id": sync_record.remote_document_id, + "batch": sync_record.batch, + "indexing_status": sync_record.last_indexing_status, + } + job.finished_at = utc_now() + db.commit() + except (Exception, DifyError) as exc: + if "job" in locals() and job is not None and "version" in locals() and version is not None and _is_retryable_dify_error(exc): + if sync_record is not None: + sync_record.error = str(exc) + if _schedule_retryable_sync(db, job=job, version=version, exc=exc): + return + if "job" in locals() and job is not None: + job.status = "failed" + job.error = str(exc) + job.message = "Dify sync failed" + job.finished_at = utc_now() + if "version" in locals() and version is not None: + version.sync_status = "sync_failed" + if sync_record is not None: + sync_record.status = "sync_failed" + sync_record.error = str(exc) + if "dify" in locals() and "dataset_id" in locals() and sync_record.batch: + try: + latest = dify.get_indexing_status(dataset_id=dataset_id, batch=sync_record.batch) + sync_record.last_indexing_status = (latest[0] if latest else {}).get("indexing_status") + except Exception: + pass + db.commit() + raise + finally: + db.close() + + +def run_delete_document_job(job_id: str, document_id: int) -> None: + db = _db() + try: + from app.api.files import _cleanup_document_storage + + job = db.query(Job).filter(Job.id == job_id).first() + document = db.query(Document).filter(Document.id == document_id).first() + if not job: + return + + _set_job_running(db, job, "Deleting document assets") + payload = _payload_dict(job) + delete_dify = bool(payload.get("delete_dify")) + remote_keys: set[tuple[str, str]] = set() + + if document: + for version in document.versions: + for record in version.sync_records: + if record.dataset_id and record.remote_document_id: + remote_keys.add((record.dataset_id, record.remote_document_id)) + + if delete_dify and remote_keys: + dify = DifyService() + for dataset_id, remote_document_id in remote_keys: + dify.delete_document(dataset_id=dataset_id, document_id=remote_document_id) + + if document: + _cleanup_document_storage(document) + + job.status = "success" + job.progress = 100 + job.message = "Document delete completed" + job.error = None + job.result = { + "deleted": True, + "delete_dify": delete_dify, + "remote_document_count": len(remote_keys), + } + job.finished_at = utc_now() + db.commit() + except Exception as exc: + if "job" in locals() and job is not None: + job.status = "failed" + job.error = str(exc) + job.message = "Document delete failed" + job.finished_at = utc_now() + db.commit() + raise + finally: + db.close() diff --git a/backend/app/time_utils.py b/backend/app/time_utils.py new file mode 100644 index 00000000..b6bae85b --- /dev/null +++ b/backend/app/time_utils.py @@ -0,0 +1,7 @@ +from __future__ import annotations + +from datetime import datetime, timezone + + +def utc_now() -> datetime: + return datetime.now(timezone.utc) diff --git a/backend/app/user_policy.py b/backend/app/user_policy.py new file mode 100644 index 00000000..b307328b --- /dev/null +++ b/backend/app/user_policy.py @@ -0,0 +1,8 @@ +from __future__ import annotations + + +PRIMARY_SUPER_ADMIN_USERNAME = "admin" + + +def is_primary_super_admin_username(username: str | None) -> bool: + return (username or "").strip().lower() == PRIMARY_SUPER_ADMIN_USERNAME diff --git a/backend/app/watchdog_cli.py b/backend/app/watchdog_cli.py new file mode 100644 index 00000000..9a6af543 --- /dev/null +++ b/backend/app/watchdog_cli.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import argparse +import json + +from app.config import get_settings +from app.database import SessionLocal +from app.services.watchdog_service import ( + local_convert_health_summary, + local_sync_health_summary, + recover_stale_converts, + recover_stale_syncs, +) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Document Cleaning watchdog helpers") + subparsers = parser.add_subparsers(dest="command", required=True) + + summary = subparsers.add_parser("summary", help="Print local sync health summary") + summary.add_argument("--timeout-seconds", type=int, default=None) + + convert_summary = subparsers.add_parser("convert-summary", help="Print local convert health summary") + convert_summary.add_argument("--timeout-seconds", type=int, default=None) + convert_summary.add_argument("--orphan-grace-seconds", type=int, default=None) + + recover = subparsers.add_parser("recover-stale-syncs", help="Recover stale syncing records") + recover.add_argument("--timeout-seconds", type=int, default=None) + recover.add_argument( + "--reason-prefix", + default="Marked stale by watchdog after timeout.", + ) + + recover_convert = subparsers.add_parser("recover-stale-converts", help="Recover stale convert records") + recover_convert.add_argument("--timeout-seconds", type=int, default=None) + recover_convert.add_argument("--orphan-grace-seconds", type=int, default=None) + recover_convert.add_argument( + "--reason-prefix", + default="Marked convert as failed by watchdog.", + ) + + return parser + + +def main() -> None: + parser = build_parser() + args = parser.parse_args() + settings = get_settings() + + db = SessionLocal() + try: + if args.command == "summary": + timeout_seconds = args.timeout_seconds or settings.watchdog_stale_sync_timeout_seconds + payload = local_sync_health_summary(db, timeout_seconds=timeout_seconds) + elif args.command == "convert-summary": + timeout_seconds = args.timeout_seconds or settings.watchdog_stale_convert_timeout_seconds + orphan_grace_seconds = args.orphan_grace_seconds or settings.watchdog_convert_orphan_grace_seconds + payload = local_convert_health_summary( + db, + timeout_seconds=timeout_seconds, + orphan_grace_seconds=orphan_grace_seconds, + settings=settings, + ) + elif args.command == "recover-stale-syncs": + timeout_seconds = args.timeout_seconds or settings.watchdog_stale_sync_timeout_seconds + payload = recover_stale_syncs( + db, + timeout_seconds=timeout_seconds, + reason_prefix=args.reason_prefix, + ) + elif args.command == "recover-stale-converts": + timeout_seconds = args.timeout_seconds or settings.watchdog_stale_convert_timeout_seconds + orphan_grace_seconds = args.orphan_grace_seconds or settings.watchdog_convert_orphan_grace_seconds + payload = recover_stale_converts( + db, + timeout_seconds=timeout_seconds, + orphan_grace_seconds=orphan_grace_seconds, + reason_prefix=args.reason_prefix, + settings=settings, + ) + else: + parser.error(f"Unsupported command: {args.command}") + return + finally: + db.close() + + print(json.dumps(payload, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/backend/backend.env.example b/backend/backend.env.example new file mode 100644 index 00000000..b9f7d466 --- /dev/null +++ b/backend/backend.env.example @@ -0,0 +1,17 @@ +JWT_SECRET=change-me +DATABASE_BACKEND=sqlite +DATABASE_URL= +SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db +POSTGRES_DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db +REDIS_URL=redis://127.0.0.1:6379/0 +PUBLIC_BASE_URL=http://127.0.0.1:8000 +DIFY_BASE_URL=https://api.dify.ai/v1 +DIFY_API_KEY= +INTEGRATION_API_KEY=change-me-internal +INTEGRATION_DOWNLOAD_SECRET=change-me-download-signing-secret +DEFAULT_ADMIN_USERNAME=admin +DEFAULT_ADMIN_PASSWORD=admin123456 +TASK_EXECUTION_MODE=sync +DIFY_SYNC_MAX_RETRIES=4 +DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300 +DIFY_SYNC_COOLDOWN_SECONDS=60 diff --git a/backend/edkb_system/__init__.py b/backend/edkb_system/__init__.py new file mode 100644 index 00000000..96607c16 --- /dev/null +++ b/backend/edkb_system/__init__.py @@ -0,0 +1 @@ +"""Enterprise KB Skill System orchestrator package.""" diff --git a/backend/edkb_system/cli.py b/backend/edkb_system/cli.py new file mode 100644 index 00000000..cc7fbc01 --- /dev/null +++ b/backend/edkb_system/cli.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import typer + +from edkb_system.config import SystemConfig +from edkb_system.contracts import Context +from edkb_system.controller import build_knowledge +from edkb_system.skills import ( + flow_reconstruct, + loader_excel, + loader_pdf, + table_linearize, +) + +app = typer.Typer(help="Enterprise KB multi-skill orchestrator") + + +def _write_failed_files_report(out_dir: Path, failed: list[dict]) -> tuple[Path, Path]: + txt_path = out_dir / "_failed_files.txt" + json_path = out_dir / "_failed_files.json" + if not failed: + for p in [txt_path, json_path]: + if p.exists(): + p.unlink() + return txt_path, json_path + + out_dir.mkdir(parents=True, exist_ok=True) + lines: list[str] = [] + payload: list[dict] = [] + for idx, item in enumerate(failed, start=1): + file_name = str(item.get("file") or "unknown").strip() or "unknown" + reason = str(item.get("error") or "unknown error") + elapsed_ms = int(item.get("elapsed_ms") or 0) + elapsed_s = f"{elapsed_ms / 1000:.3f}s" + is_timeout = "timed out" in reason.lower() + payload.append( + { + "index": idx, + "file": file_name, + "reason": reason, + "elapsed_ms": elapsed_ms, + "timed_out": is_timeout, + } + ) + lines.extend( + [ + f"[{idx}] {file_name}", + f"reason: {reason}", + f"elapsed: {elapsed_s}", + f"timed_out: {'true' if is_timeout else 'false'}", + "", + ] + ) + + txt_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8") + json_path.write_text( + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return txt_path, json_path + + +@app.command("build") +def build_cmd( + input_path: str = typer.Argument(..., metavar="PATH"), + out: str = typer.Option(..., "--out"), + config: str | None = typer.Option(None, "--config"), + skip: list[str] | None = typer.Option( + None, + "--skip", + help="Skip files by glob pattern (match name or relative path, repeatable)", + ), + resume: bool = typer.Option( + False, + "--resume/--no-resume", + help="Skip files whose target markdown already exists", + ), + prune_stale: bool = typer.Option( + False, + "--prune-stale/--keep-stale", + help="Remove stale markdown/intermediate leftovers in output before build", + ), +) -> None: + cfg = SystemConfig.load(config) + root = Path(__file__).resolve().parents[2] + temp_dir = root / "work" / "cache" + in_path = Path(input_path) + if not in_path.exists(): + typer.echo(f"Input path not found: {in_path}") + typer.echo("Create the folder and put documents in it, e.g. work/input") + raise typer.Exit(code=2) + results = build_knowledge( + in_path, + Path(out), + cfg, + temp_dir, + skip_patterns=skip or [], + resume=resume, + prune_stale_output=prune_stale, + ) + ok = [r for r in results if r.get("status") == "success"] + failed = [r for r in results if r.get("status") == "failed"] + skipped = [r for r in results if r.get("status") == "skipped"] + typer.echo( + "Completed files: " + f"{len(results)} (success={len(ok)}, failed={len(failed)}, skipped={len(skipped)})" + ) + if failed: + txt_path, json_path = _write_failed_files_report(Path(out), failed) + for r in failed: + file_name = str(r.get("file", "")).strip() or "unknown" + reason = str(r.get("error") or "unknown error") + typer.echo(f"- Failed: {file_name}") + typer.echo(f" - reason: {reason}") + typer.echo(f"- Failed list: {txt_path}") + typer.echo(f"- Failed json: {json_path}") + else: + _write_failed_files_report(Path(out), []) + typer.echo(f"- Output dir: {Path(out)}") + + +@app.command("inspect-flow") +def inspect_flow_cmd( + file: str = typer.Argument(..., metavar="FILE"), + out: str = typer.Option(..., "--out"), +) -> None: + ctx = Context(file_type="pdf") + blocks = loader_pdf.run({"file_path": file}, ctx) + data = flow_reconstruct.run(blocks, ctx) + out_dir = Path(out) + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "inspect_flow.md").write_text( + "\n\n".join(data.get("flow_markdowns", [])), encoding="utf-8" + ) + (out_dir / "inspect_flow_debug.json").write_text( + json.dumps(data.get("debug", []), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + typer.echo("inspect-flow done") + + +@app.command("inspect-excel") +def inspect_excel_cmd( + file: str = typer.Argument(..., metavar="FILE"), + out: str = typer.Option(..., "--out"), +) -> None: + ctx = Context(file_type="xlsx") + tables = loader_excel.run({"file_path": file, "work_dir": str(Path(out))}, ctx) + md = table_linearize.run(tables, ctx) + out_dir = Path(out) + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "inspect_excel.md").write_text(md, encoding="utf-8") + (out_dir / "inspect_excel_schema.json").write_text( + json.dumps( + [{"sheet": t.get("sheet"), "headers": t.get("headers")} for t in tables], + ensure_ascii=False, + indent=2, + ), + encoding="utf-8", + ) + typer.echo("inspect-excel done") + + +if __name__ == "__main__": + app() diff --git a/backend/edkb_system/config.py b/backend/edkb_system/config.py new file mode 100644 index 00000000..6c84687d --- /dev/null +++ b/backend/edkb_system/config.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from pydantic import BaseModel, Field + + +class RouterConfig(BaseModel): + scan_likelihood_threshold: float = 0.6 + flow_likelihood_threshold: float = 0.5 + table_likelihood_threshold: float = 0.5 + + +class OCRConfig(BaseModel): + enable: bool = True + engine: str = "rapidocr" + min_confidence: float = 0.3 + + +class ChunkConfig(BaseModel): + enable: bool = True + max_chars: int = 1200 + overlap_chars: int = 150 + add_heading_path_prefix: bool = True + + +class CleanConfig(BaseModel): + dedup_min_repeats: int = 3 + merge_short_line_chars: int = 15 + + +class SystemConfig(BaseModel): + router: RouterConfig = Field(default_factory=RouterConfig) + ocr: OCRConfig = Field(default_factory=OCRConfig) + chunk: ChunkConfig = Field(default_factory=ChunkConfig) + clean: CleanConfig = Field(default_factory=CleanConfig) + + @classmethod + def load(cls, path: str | None) -> "SystemConfig": + if not path: + return cls() + p = Path(path) + raw = p.read_text(encoding="utf-8") + if p.suffix.lower() in {".yaml", ".yml"}: + import yaml + + data = yaml.safe_load(raw) or {} + elif p.suffix.lower() == ".json": + data = json.loads(raw) + else: + raise ValueError("config only supports yaml/yml/json") + return cls.model_validate(data) diff --git a/backend/edkb_system/contracts.py b/backend/edkb_system/contracts.py new file mode 100644 index 00000000..4c2bdcac --- /dev/null +++ b/backend/edkb_system/contracts.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class Block: + id: str + page: int + type: str + text: str + bbox: tuple[float, float, float, float] + meta: dict[str, Any] = field(default_factory=dict) + + def cx(self) -> float: + return (self.bbox[0] + self.bbox[2]) / 2.0 + + def cy(self) -> float: + return (self.bbox[1] + self.bbox[3]) / 2.0 + + +@dataclass +class Chunk: + id: str + heading_path: str + text: str + index: int + source: str + + +@dataclass +class Context: + file_type: str = "" + pages: int = 0 + images: int = 0 + ocr_characters: int = 0 + flows_detected: int = 0 + warnings: list[str] = field(default_factory=list) + confidence: float = 1.0 + extras: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class DocumentProfile: + file_type: str + text_density: float + has_images: bool + has_tables: bool + flow_likelihood: float + scan_likelihood: float + table_likelihood: float + language_hint: str + recommended_pipeline: list[str] diff --git a/backend/edkb_system/controller.py b/backend/edkb_system/controller.py new file mode 100644 index 00000000..2e9b2b83 --- /dev/null +++ b/backend/edkb_system/controller.py @@ -0,0 +1,893 @@ +from __future__ import annotations + +import json +import fnmatch +import multiprocessing as mp +import os +import re +import shutil +import time +import traceback +from pathlib import Path + +from edkb_system.config import SystemConfig +from edkb_system.contracts import Context +from edkb_system.discovery import discover +from edkb_system.skills import ( + chunk, + clean, + doc_to_pdf, + export, + flow_reconstruct, + intake_router, + loader_csv, + loader_docx, + loader_excel, + loader_pdf, + loader_pptx, + ocr, + postcheck, + quality_gate, + table_linearize, +) +from edkb_system.skills.common import blocks_to_plain_markdown +from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids + + +_STEP_ALIAS = { + "edkb-intake-router": "route", + "edkb-loader-docx": "docx", + "edkb-doc-to-pdf": "doc2pdf", + "edkb-loader-pdf": "pdf", + "edkb-loader-pptx": "pptx", + "edkb-loader-excel": "excel", + "edkb-loader-csv": "csv", + "edkb-ocr": "ocr", + "edkb-flow-reconstruct": "flow", + "edkb-table-linearize": "table", + "edkb-clean": "clean", + "edkb-chunk": "chunk", + "edkb-quality-gate": "qgate", + "edkb-export": "export", + "edkb-postcheck": "check", +} + + +def _step_alias(step: str) -> str: + return _STEP_ALIAS.get(step, step.replace("edkb-", "")) + + +def _extract_doc_header_from_flow(flow_mds: list[str]) -> str | None: + if not flow_mds: + return None + for line in "\n".join(flow_mds).splitlines(): + if "文件编号" not in line or "文件级别" not in line or "版本" not in line: + continue + s = " ".join(line.split()) + m = re.search(r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", s) + if m: + return f"文件编号 {m.group(1)} 文件级别 {m.group(2)} 版本 {m.group(3)}" + return None + + +def _inject_doc_header_from_flow(text: str, flow_mds: list[str]) -> str: + if "文件编号" in text: + return text + meta = _extract_doc_header_from_flow(flow_mds) + if not meta: + return text + if text.startswith("制定部门"): + i = text.find("\n") + if i >= 0: + return text[: i + 1] + meta + "\n" + text[i + 1 :] + return meta + "\n" + text + + +def _inject_source_title_if_missing(text: str, source_stem: str) -> str: + if not source_stem: + return text + preview = "\n".join(text.splitlines()[:20]) + norm_preview = re.sub(r"\s+", "", preview) + norm_source = re.sub(r"\s+", "", source_stem) + if norm_source in norm_preview: + return text + return source_stem + "\n" + text + + +def _promote_title_above_meta(text: str) -> str: + lines = text.splitlines() + if len(lines) < 2: + return text + + first_idx = next((i for i, x in enumerate(lines) if x.strip()), None) + if first_idx is None: + return text + second_idx = next( + (i for i in range(first_idx + 1, len(lines)) if lines[i].strip()), None + ) + if second_idx is None: + return text + + first = lines[first_idx].strip() + second = lines[second_idx].strip() + if "文件编号" not in first: + return text + if ( + re.match(r"^[一二三四五六七八九十]+、", second) + or second.startswith("制定部门") + or second.startswith("文件修订履历") + or "文件编号" in second + ): + return text + if len(second) > 80: + return text + + lines[first_idx], lines[second_idx] = lines[second_idx], lines[first_idx] + return "\n".join(lines) + + +def _promote_dept_header_near_top(text: str) -> str: + lines = text.splitlines() + pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+") + idx = next( + (i for i, ln in enumerate(lines) if pat.search(" ".join(ln.split()))), None + ) + if idx is None or idx <= 4: + return text + + line = lines.pop(idx) + insert_at = 1 + for i, ln in enumerate(lines[:6]): + if ln.strip().startswith("文件编号"): + insert_at = i + 1 + break + lines.insert(insert_at, line) + return "\n".join(lines) + + +def _ocr_payload_map(blocks: list) -> dict[str, str]: + out: dict[str, str] = {} + for b in blocks: + if getattr(b, "type", "") != "ocr_text" or not str( + getattr(b, "id", "") + ).startswith("ocr-"): + continue + txt = (getattr(b, "text", "") or "").strip() + if txt.startswith("OCR_TEXT:"): + txt = txt[len("OCR_TEXT:") :].strip() + txt = re.sub(r"(?m)^\s*-\s*", "", txt) + txt = " ".join(x.strip() for x in txt.splitlines() if x.strip()) + if txt and txt != "": + out[str(b.id)[len("ocr-") :]] = txt + return out + + +def _has_non_flow_image_content(blocks: list) -> bool: + img_ids = [str(b.id) for b in blocks if getattr(b, "type", "") == "image"] + if not img_ids: + return False + ocr_map = _ocr_payload_map(blocks) + info_kw = re.compile(r"分数值|频繁程度|严重性|LEC|评分基准|风险积分|事故发生") + flow_kw = re.compile(r"备料|取样|资料确认|品质检验|判定|产品出货|NG|OK|不合格品") + + for iid in img_ids: + payload = ocr_map.get(iid, "") + if not payload: + continue + if info_kw.search(payload): + return True + if len(payload) >= 80 and len(flow_kw.findall(payload)) <= 2: + return True + return False + + +def _derive_source_category(file_path: Path, input_path: Path) -> str: + if input_path.is_dir(): + try: + rel = file_path.relative_to(input_path) + if len(rel.parts) >= 2: + return rel.parts[0] + return input_path.name or "uncategorized" + except Exception: + return file_path.parent.name or "uncategorized" + return input_path.parent.name or "uncategorized" + + +def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path: + if input_path.is_dir(): + try: + rel = file_path.relative_to(input_path) + except Exception: + rel = Path(file_path.name) + if len(rel.parts) == 1: + root_name = input_path.name + if root_name and root_name.lower() not in {"input", "work"}: + rel = Path(root_name) / rel + else: + parent_name = file_path.parent.name + if parent_name and parent_name.lower() not in {"input", "work"}: + rel = Path(parent_name) / file_path.name + else: + rel = Path(file_path.name) + return rel.with_suffix(".md") + + +def _normalize_path_for_match(p: Path | str) -> str: + return str(p).replace("\\", "/") + + +def _file_timeout_sec() -> int | None: + raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip() + try: + value = int(raw) + except ValueError: + value = 0 + return value if value > 0 else None + + +def _cleanup_input_temp_files(input_path: Path) -> list[Path]: + if input_path.is_file(): + candidates = [input_path] + elif input_path.exists(): + candidates = [p for p in input_path.rglob("*") if p.is_file()] + else: + return [] + + removed: list[Path] = [] + for file in candidates: + name = file.name + if not (name.startswith("~$") or name.startswith("~WRL")): + continue + try: + file.unlink() + except Exception: + continue + removed.append(file) + return removed + + +def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None: + if not patterns: + return None + lowered_candidates = [c.lower() for c in candidates if c] + for pat in patterns: + norm_pat = _normalize_path_for_match(pat).strip().lower() + if not norm_pat: + continue + for cand in lowered_candidates: + if fnmatch.fnmatch(cand, norm_pat): + return pat + return None + + +def _prune_stale_markdowns(output_dir: Path, expected: set[Path]) -> None: + keep_names = {"INDEX.md", "POSTCHECK_ISSUES.md"} + expected_resolved = {p.resolve() for p in expected} + + for md in output_dir.rglob("*.md"): + if md.name in keep_names: + continue + try: + resolved = md.resolve() + except Exception: + resolved = md + if resolved in expected_resolved: + continue + try: + md.unlink() + except Exception: + continue + + +def _run_one_worker(payload: dict, queue: mp.Queue) -> None: + try: + cfg = SystemConfig.model_validate(payload["config"]) + res = _run_one( + Path(payload["file_path"]), + Path(payload["out_root"]), + Path(payload["temp_dir"]), + cfg, + source_root=Path(payload["source_root"]) + if payload.get("source_root") + else None, + source_category=payload.get("source_category"), + final_md_path=( + Path(payload["final_md_path"]) if payload.get("final_md_path") else None + ), + progress_label=payload.get("progress_label"), + ) + queue.put({"ok": True, "result": res}) + except Exception as exc: + queue.put({"ok": False, "error": str(exc), "detail": traceback.format_exc()}) + + +def _run_one_with_timeout( + file_path: Path, + out_root: Path, + temp_dir: Path, + cfg: SystemConfig, + source_root: Path | None = None, + source_category: str | None = None, + final_md_path: Path | None = None, + progress_label: str | None = None, +) -> dict: + timeout = _file_timeout_sec() + if not timeout: + return _run_one( + file_path, + out_root, + temp_dir, + cfg, + source_root=source_root, + source_category=source_category, + final_md_path=final_md_path, + progress_label=progress_label, + ) + + ctx = mp.get_context("spawn") + queue: mp.Queue = ctx.Queue() + before_pids = _list_winword_pids() + payload = { + "file_path": str(file_path), + "out_root": str(out_root), + "temp_dir": str(temp_dir), + "config": cfg.model_dump(), + "source_root": str(source_root) if source_root else None, + "source_category": source_category, + "final_md_path": str(final_md_path) if final_md_path else None, + "progress_label": progress_label, + } + proc = ctx.Process(target=_run_one_worker, args=(payload, queue)) + proc.start() + proc.join(timeout) + if proc.is_alive(): + proc.terminate() + proc.join(5) + after_pids = _list_winword_pids() + _kill_winword_pids(after_pids - before_pids) + raise TimeoutError( + f"file processing timed out after {timeout}s: {file_path.name}" + ) + if queue.empty(): + if proc.exitcode not in {0, None}: + raise RuntimeError( + f"file worker exited unexpectedly (code={proc.exitcode}): {file_path.name}" + ) + raise RuntimeError(f"file worker returned no result: {file_path.name}") + message = queue.get() + if message.get("ok"): + return message["result"] + detail = str(message.get("detail") or "") + raise RuntimeError(str(message.get("error") or detail or "unknown worker error")) + + marker_files = { + "01_raw_layout.json", + "02_flow_procedure.md", + "03_clean.md", + "04_chunks.jsonl", + "report.md", + "trace_pipeline.json", + "postcheck.json", + } + for d in list(output_dir.iterdir()): + if not d.is_dir(): + continue + try: + names = {p.name for p in d.iterdir()} + except Exception: + continue + if names & marker_files: + shutil.rmtree(d, ignore_errors=True) + + for d in sorted(output_dir.rglob("*"), key=lambda x: len(x.parts), reverse=True): + if not d.is_dir(): + continue + try: + if d == output_dir: + continue + next(d.iterdir()) + except StopIteration: + try: + d.rmdir() + except Exception: + pass + except Exception: + continue + + +def _run_one( + file_path: Path, + out_root: Path, + temp_dir: Path, + cfg: SystemConfig, + source_root: Path | None = None, + source_category: str | None = None, + final_md_path: Path | None = None, + progress_label: str | None = None, +) -> dict: + ctx = Context() + trace_steps: list[str] = [] + timings_ms: dict[str, int] = {} + + def _mark(step: str, started: float) -> None: + timings_ms[step] = int((time.perf_counter() - started) * 1000) + + def _announce(stage: str) -> None: + if not progress_label: + return + print(f"{progress_label} stage: {stage}", flush=True) + + out_dir = out_root / file_path.stem + out_dir.mkdir(parents=True, exist_ok=True) + for stale in [ + out_dir / "inspect_flow_debug.json", + out_dir / "trace_pipeline.json", + out_dir / "postcheck.json", + ]: + if stale.exists(): + stale.unlink() + + t0 = time.perf_counter() + profile = intake_router.run({"file_path": str(file_path)}, ctx, cfg.router) + _mark("edkb-intake-router", t0) + trace_steps.append("edkb-intake-router") + + blocks = [] + tables = None + text = "" + flow_mds: list[str] = [] + + if profile.file_type in {"doc", "docx"}: + _announce("doc/docx parse") + t0 = time.perf_counter() + docx_blocks = loader_docx.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-loader-docx", t0) + trace_steps.append("edkb-loader-docx") + + table_blocks = sum(1 for b in docx_blocks if b.type == "table") + prefer_docx = table_blocks > 0 + docx_images = [b for b in docx_blocks if b.type == "image"] + docx_non_images = [b for b in docx_blocks if b.type != "image"] + pdf_blocks = None + + if "edkb-doc-to-pdf" in profile.recommended_pipeline and ( + (profile.file_type == "doc" and not prefer_docx) or not docx_blocks + ): + _announce("doc to pdf") + t0 = time.perf_counter() + conv = doc_to_pdf.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-doc-to-pdf", t0) + trace_steps.append("edkb-doc-to-pdf") + pdf_path = conv.get("pdf_path") + if pdf_path: + _announce("pdf load") + t0 = time.perf_counter() + pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx) + _mark("edkb-loader-pdf", t0) + trace_steps.append("edkb-loader-pdf") + blocks = pdf_blocks + else: + blocks = docx_blocks + else: + blocks = docx_blocks + + if ( + profile.file_type == "doc" + and "edkb-doc-to-pdf" in profile.recommended_pipeline + and (not prefer_docx or not docx_blocks) + ): + if pdf_blocks is None: + _announce("doc to pdf") + t0 = time.perf_counter() + conv = doc_to_pdf.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-doc-to-pdf", t0) + trace_steps.append("edkb-doc-to-pdf") + pdf_path = conv.get("pdf_path") + if pdf_path: + _announce("pdf load") + t0 = time.perf_counter() + pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx) + _mark("edkb-loader-pdf", t0) + trace_steps.append("edkb-loader-pdf") + if pdf_blocks is not None: + pdf_images = [b for b in pdf_blocks if b.type == "image"] + if pdf_images and len(pdf_images) > len(docx_images): + blocks = docx_non_images + pdf_images + ctx.warnings.append( + f"doc image source switched to pdf: {len(docx_images)} -> {len(pdf_images)}" + ) + elif not blocks: + blocks = pdf_blocks + elif profile.file_type == "pdf": + _announce("pdf load") + t0 = time.perf_counter() + blocks = loader_pdf.run({"file_path": str(file_path)}, ctx) + _mark("edkb-loader-pdf", t0) + trace_steps.append("edkb-loader-pdf") + elif profile.file_type in {"ppt", "pptx"}: + _announce("ppt/pptx load") + t0 = time.perf_counter() + blocks = loader_pptx.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-loader-pptx", t0) + trace_steps.append("edkb-loader-pptx") + elif profile.file_type in {"xls", "xlsx"}: + _announce("excel load") + t0 = time.perf_counter() + tables = loader_excel.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-loader-excel", t0) + trace_steps.append("edkb-loader-excel") + elif profile.file_type == "csv": + t0 = time.perf_counter() + tables = loader_csv.run({"file_path": str(file_path)}, ctx) + _mark("edkb-loader-csv", t0) + trace_steps.append("edkb-loader-csv") + else: + ctx.warnings.append(f"unsupported file type: {profile.file_type}") + + if blocks: + ctx.images = sum(1 for b in blocks if b.type == "image") + should_ocr = cfg.ocr.enable and ( + "edkb-ocr" in profile.recommended_pipeline + or any(b.type == "image" for b in blocks) + ) + if profile.file_type in {"ppt", "pptx"}: + should_ocr = False + if should_ocr: + _announce("ocr") + t0 = time.perf_counter() + blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence) + _mark("edkb-ocr", t0) + trace_steps.append("edkb-ocr") + + doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind") + policy_text = doc_kind == "policy_text" + has_non_flow_info = _has_non_flow_image_content(blocks) + has_page_image_mode = bool(ctx.extras.get("pdf_page_image_mode_pages")) + has_figure_anchor = any( + (b.text or "") + and re.search( + r"^\s*\d+(?:\.\d+){1,3}\s*[^\n]{0,40}(?:示意图|图示)\s*$", + b.text, + ) + for b in blocks + if b.type in {"heading", "paragraph"} + ) + suppress_images = False + if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor: + if policy_text and not has_non_flow_info and not has_page_image_mode: + suppress_images = True + elif ( + doc_kind == "flow_procedure" + and not has_non_flow_info + and not has_page_image_mode + ): + suppress_images = True + if suppress_images: + blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}] + trace_steps.append("edkb-image-suppress(no_figure_anchor)") + + flow_info = {} + if "edkb-flow-reconstruct" in profile.recommended_pipeline: + _announce("flow reconstruct") + t0 = time.perf_counter() + flow_info = flow_reconstruct.run(blocks, ctx) + _mark("edkb-flow-reconstruct", t0) + trace_steps.append("edkb-flow-reconstruct") + flow_mds = flow_info.get("flow_markdowns", []) + if flow_info.get("debug"): + (out_dir / "inspect_flow_debug.json").write_text( + json.dumps(flow_info["debug"], ensure_ascii=False, indent=2), + encoding="utf-8", + ) + + text = blocks_to_plain_markdown(blocks) + text = _inject_doc_header_from_flow(text, flow_mds) + elif tables is not None: + _announce("table linearize") + t0 = time.perf_counter() + text = table_linearize.run(tables, ctx) + _mark("edkb-table-linearize", t0) + trace_steps.append("edkb-table-linearize") + + _announce("clean") + t0 = time.perf_counter() + clean_md = clean.run( + text, ctx, cfg.clean.dedup_min_repeats, cfg.clean.merge_short_line_chars + ) + _mark("edkb-clean", t0) + clean_md = _inject_source_title_if_missing(clean_md, file_path.stem) + clean_md = _promote_title_above_meta(clean_md) + meta = _extract_doc_header_from_flow(flow_mds) + has_meta_line = bool( + re.search(r"文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S+", clean_md) + or ("| 文件编号 |" in clean_md and "| 文件级别 |" in clean_md) + ) + if meta and not has_meta_line: + if clean_md.startswith("制定部门"): + i = clean_md.find("\n") + if i >= 0: + clean_md = clean_md[: i + 1] + meta + "\n" + clean_md[i + 1 :] + else: + clean_md = clean_md + "\n" + meta + "\n" + else: + clean_md = meta + "\n" + clean_md + clean_md = _promote_title_above_meta(clean_md) + clean_md = _promote_dept_header_near_top(clean_md) + trace_steps.append("edkb-clean") + + chunks = [] + if cfg.chunk.enable: + _announce("chunk") + t0 = time.perf_counter() + chunks = chunk.run( + {"source": file_path.name, "text": clean_md}, + ctx, + max_chars=cfg.chunk.max_chars, + overlap_chars=cfg.chunk.overlap_chars, + add_heading_path_prefix=cfg.chunk.add_heading_path_prefix, + ) + _mark("edkb-chunk", t0) + trace_steps.append("edkb-chunk") + t0 = time.perf_counter() + chunks = quality_gate.run(chunks, ctx) + _mark("edkb-quality-gate", t0) + trace_steps.append("edkb-quality-gate") + else: + ctx.warnings.append( + "chunk disabled by config: skip edkb-chunk/edkb-quality-gate" + ) + trace_steps.append("edkb-chunk(skipped)") + trace_steps.append("edkb-quality-gate(skipped)") + + source_rel_path = file_path.name + if source_root is not None: + try: + source_rel_path = str(file_path.relative_to(source_root)) + except Exception: + source_rel_path = file_path.name + + target_md_path = final_md_path + if target_md_path is None: + target_md_path = out_root / f"{file_path.stem}.md" + + _announce("export") + t0 = time.perf_counter() + export.run( + { + "out_dir": str(out_dir), + "source_file": file_path.name, + "source_rel_path": source_rel_path, + "source_category": source_category or "", + "flat_md_path": str(target_md_path), + "clean_md": clean_md, + "chunks": chunks, + "blocks": blocks, + "flow_markdowns": flow_mds, + }, + ctx, + ) + _mark("edkb-export", t0) + trace_steps.append("edkb-export") + + exported_clean_md = clean_md + exported_clean_path = out_dir / "03_clean.md" + if exported_clean_path.exists(): + try: + exported_clean_md = exported_clean_path.read_text(encoding="utf-8") + except Exception: + exported_clean_md = clean_md + + _announce("postcheck") + t0 = time.perf_counter() + check = postcheck.run({"out_dir": str(out_dir), "clean_md": exported_clean_md}, ctx) + _mark("edkb-postcheck", t0) + (out_dir / "postcheck.json").write_text( + json.dumps(check, ensure_ascii=False, indent=2), encoding="utf-8" + ) + if check.get("status") != "pass": + failed = ", ".join(check.get("failed_required", [])) + ctx.warnings.append(f"postcheck failed: {failed}") + if check.get("issue_count", 0) > 0: + issue_codes: list[str] = [] + for it in check.get("issues", [])[:3]: + code = str(it.get("code", "")).strip() + if code and code not in issue_codes: + issue_codes.append(code) + if issue_codes: + ctx.warnings.append( + f"postcheck issues: {check.get('issue_count', 0)} ({', '.join(issue_codes)})" + ) + else: + ctx.warnings.append(f"postcheck issues: {check.get('issue_count', 0)}") + trace_steps.append("edkb-postcheck") + + (out_dir / "trace_pipeline.json").write_text( + json.dumps( + { + "file": file_path.name, + "recommended_pipeline": profile.recommended_pipeline, + "executed_steps": trace_steps, + "timings_ms": timings_ms, + "intake": ctx.extras.get("intake", {}), + }, + ensure_ascii=False, + indent=2, + ), + encoding="utf-8", + ) + + return { + "file": file_path.name, + "out_dir": str(out_dir), + "warnings": ctx.warnings, + "timings_ms": timings_ms, + } + + +def build_knowledge( + input_path: Path, + output_dir: Path, + config: SystemConfig, + temp_dir: Path, + skip_patterns: list[str] | None = None, + resume: bool = False, + prune_stale_output: bool = False, +) -> list[dict]: + removed_temp_files = _cleanup_input_temp_files(input_path) + if removed_temp_files: + for removed in removed_temp_files: + print(f"cleanup-temp: {removed}", flush=True) + + files = discover(input_path) + output_dir.mkdir(parents=True, exist_ok=True) + temp_dir.mkdir(parents=True, exist_ok=True) + + patterns = [p for p in (skip_patterns or []) if str(p).strip()] + + for stale in [output_dir / "INDEX.md", output_dir / "POSTCHECK_ISSUES.md"]: + if stale.exists(): + stale.unlink() + for lock_md in output_dir.glob("~$*.md"): + if lock_md.is_file(): + lock_md.unlink() + + if prune_stale_output: + expected_paths = { + (output_dir / _derive_output_rel_md(file, input_path)).resolve() + for file in files + } + _prune_stale_markdowns(output_dir, expected_paths) + + source_root = input_path if input_path.is_dir() else input_path.parent + + results: list[dict] = [] + total = len(files) + for idx, file in enumerate(files, start=1): + flat_out = output_dir / f"{file.stem}.md" + mirror_out = output_dir / _derive_output_rel_md(file, input_path) + + source_rel_path = file.name + try: + source_rel_path = _normalize_path_for_match(file.relative_to(source_root)) + except Exception: + source_rel_path = _normalize_path_for_match(file) + + matched_pattern = _matches_pattern( + [ + _normalize_path_for_match(file), + source_rel_path, + file.name, + ], + patterns, + ) + if matched_pattern: + print( + f"[{idx}/{total}] skipped(pattern): {source_rel_path} ({matched_pattern})", + flush=True, + ) + results.append( + { + "file": file.name, + "out_dir": str(output_dir / file.stem), + "warnings": [], + "status": "skipped", + "skip_reason": f"pattern:{matched_pattern}", + "elapsed_ms": 0, + } + ) + continue + + if resume and mirror_out.exists() and mirror_out.stat().st_size > 0: + print(f"[{idx}/{total}] skipped(resume): {source_rel_path}", flush=True) + results.append( + { + "file": file.name, + "out_dir": str(output_dir / file.stem), + "warnings": [], + "status": "skipped", + "skip_reason": "resume-existing-output", + "elapsed_ms": 0, + } + ) + continue + + print(f"[{idx}/{total}] processing: {file.name}", flush=True) + if flat_out.exists(): + flat_out.unlink() + if mirror_out != flat_out and mirror_out.exists(): + mirror_out.unlink() + started = time.perf_counter() + try: + source_category = _derive_source_category(file, input_path) + res = _run_one_with_timeout( + file, + output_dir, + temp_dir, + config, + source_root=source_root, + source_category=source_category, + final_md_path=mirror_out, + progress_label=f"[{idx}/{total}] {file.name}", + ) + elapsed_ms = int((time.perf_counter() - started) * 1000) + res["status"] = "success" + res["elapsed_ms"] = elapsed_ms + results.append(res) + print( + f"[{idx}/{total}] success: {file.name} ({elapsed_ms / 1000:.3f}s)", + flush=True, + ) + timings = res.get("timings_ms", {}) or {} + if timings: + top = sorted(timings.items(), key=lambda x: x[1], reverse=True)[:3] + top_text = ", ".join( + f"{_step_alias(k)}={v / 1000:.3f}s" for k, v in top + ) + print(f"[{idx}/{total}] time: {top_text}", flush=True) + + out_dir_str = str(res.get("out_dir", "")).strip() + doc_artifact_dir = Path(out_dir_str) if out_dir_str else None + if ( + doc_artifact_dir is not None + and doc_artifact_dir.exists() + and doc_artifact_dir.parent == output_dir + ): + shutil.rmtree(doc_artifact_dir) + except Exception as exc: + elapsed_ms = int((time.perf_counter() - started) * 1000) + detail = traceback.format_exc() + doc_artifact_dir = output_dir / file.stem + if doc_artifact_dir.exists(): + shutil.rmtree(doc_artifact_dir) + if flat_out.exists(): + flat_out.unlink() + if mirror_out.exists() and mirror_out != flat_out: + mirror_out.unlink() + results.append( + { + "file": file.name, + "out_dir": str(output_dir / file.stem), + "warnings": [str(exc)], + "status": "failed", + "elapsed_ms": elapsed_ms, + "error": str(exc), + "error_detail": detail, + } + ) + print( + f"[{idx}/{total}] failed: {file.name} ({elapsed_ms / 1000:.3f}s)", + flush=True, + ) + print(f"[{idx}/{total}] reason: {exc}", flush=True) + print(detail.rstrip(), flush=True) + return results diff --git a/backend/edkb_system/discovery.py b/backend/edkb_system/discovery.py new file mode 100644 index 00000000..7c0faea8 --- /dev/null +++ b/backend/edkb_system/discovery.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from pathlib import Path + +SUPPORTED_EXTS = {".doc", ".docx", ".pdf", ".xls", ".xlsx", ".csv", ".ppt", ".pptx"} + + +def discover(path: Path) -> list[Path]: + if path.is_file(): + if path.name.startswith("~$"): + return [] + return [path] if path.suffix.lower() in SUPPORTED_EXTS else [] + if not path.exists(): + raise FileNotFoundError(path) + files = [ + p + for p in path.rglob("*") + if p.is_file() + and not p.name.startswith("~$") + and p.suffix.lower() in SUPPORTED_EXTS + ] + return sorted(files, key=lambda x: str(x)) diff --git a/backend/edkb_system/skills/__init__.py b/backend/edkb_system/skills/__init__.py new file mode 100644 index 00000000..69c566ff --- /dev/null +++ b/backend/edkb_system/skills/__init__.py @@ -0,0 +1 @@ +"""Atomic skills for enterprise KB pipeline.""" diff --git a/backend/edkb_system/skills/chunk.py b/backend/edkb_system/skills/chunk.py new file mode 100644 index 00000000..2b24c038 --- /dev/null +++ b/backend/edkb_system/skills/chunk.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import hashlib +import re + +from edkb_system.contracts import Chunk, Context + + +HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$") + + +def _chunk_id(source: str, heading: str, index: int, text: str) -> str: + raw = f"{source}|{heading}|{index}|{text}" + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def run( + input_data: dict, + context: Context, + max_chars: int = 1200, + overlap_chars: int = 150, + add_heading_path_prefix: bool = True, +) -> list[Chunk]: + source = input_data["source"] + md = input_data["text"] + lines = md.splitlines() + + stack: list[str] = [] + sections: list[tuple[str, str]] = [] + buf: list[str] = [] + + def heading() -> str: + return " > ".join(stack) if stack else "ROOT" + + for ln in lines: + m = HEAD_RE.match(ln.strip()) + if m: + if buf: + sections.append((heading(), "\n".join(buf).strip())) + buf = [] + level = len(m.group(1)) + text = m.group(2).strip() + while len(stack) >= level: + stack.pop() + stack.append(text) + else: + buf.append(ln) + if buf: + sections.append((heading(), "\n".join(buf).strip())) + + out: list[Chunk] = [] + idx = 0 + for hp, body in sections: + paras = [p.strip() for p in body.split("\n\n") if p.strip()] + acc = "" + for p in paras: + cand = (acc + "\n\n" + p).strip() if acc else p + if len(cand) <= max_chars: + acc = cand + continue + if acc: + txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc + out.append( + Chunk( + id=_chunk_id(source, hp, idx, txt), + heading_path=hp, + text=txt, + index=idx, + source=source, + ) + ) + idx += 1 + overlap = txt[-overlap_chars:] if overlap_chars > 0 else "" + acc = (overlap + "\n\n" + p).strip() + else: + acc = p[:max_chars] + if acc: + txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc + out.append( + Chunk( + id=_chunk_id(source, hp, idx, txt), + heading_path=hp, + text=txt, + index=idx, + source=source, + ) + ) + idx += 1 + + return out diff --git a/backend/edkb_system/skills/clean.py b/backend/edkb_system/skills/clean.py new file mode 100644 index 00000000..35f79d2a --- /dev/null +++ b/backend/edkb_system/skills/clean.py @@ -0,0 +1,2017 @@ +from __future__ import annotations + +import base64 +import re +from collections import Counter + +from edkb_system.contracts import Context + + +def _dedupe_repeated_headers(lines: list[str]) -> list[str]: + header_patterns = [ + re.compile( + r"^(?P\s*制定部门.+?制/修订日期.+?页码\s*\d+\s*/\s*\d+)(?P.*)$" + ), + re.compile( + r"^(?P\s*文件编号\s+.+?文件级别\s+.+?版本\s+.+?)(?P.*)$" + ), + re.compile(r"^(?P\s*注:文件在系统签核完成日即为生效日\s*)(?P.*)$"), + ] + + seen: dict[int, bool] = {} + out: list[str] = [] + for ln in lines: + s = ln.rstrip("\n") + handled = False + for i, p in enumerate(header_patterns): + m = p.match(s) + if not m: + continue + rest = (m.group("rest") or "").strip() + if seen.get(i): + if rest: + out.append(rest) + handled = True + break + seen[i] = True + if m.group("head"): + out.append(m.group("head").strip()) + if rest: + out.append(rest) + handled = True + break + if not handled: + out.append(ln) + return out + + +def _join_cross_page_broken_lines(lines: list[str]) -> list[str]: + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i] + if i + 2 < len(lines): + nxt = lines[i + 1] + nxt2 = lines[i + 2] + if ( + not nxt.strip() + and cur.strip() + and nxt2.strip() + and re.search(r"[\u4e00-\u9fff]$", cur.strip()) + and re.match(r"^[\u4e00-\u9fff]", nxt2.strip()) + and not re.match(r"^\d+\.\d", nxt2.strip()) + ): + out.append(cur.rstrip() + nxt2.lstrip()) + i += 3 + continue + out.append(cur) + i += 1 + return out + + +def _split_inline_headings(text: str) -> str: + out_lines: list[str] = [] + for ln in text.splitlines(): + s = ln.strip() + if not s or s.startswith("|"): + out_lines.append(ln) + continue + + ln = re.sub(r"\s+(?=[一二三四五六七八九十]+、)", "\n", ln) + ln = re.sub(r"(? str: + m_start = re.search(r"五、作业流程图", text) + if not m_start: + return text + start = m_start.start() + + m_end = re.search(r"(?:\n|\s)六、作业内容", text[start:]) + if not m_end: + return text + end = start + m_end.start() + if end <= start: + return text + + section = text[start:end] + row_hits = re.findall(r"(?m)^\s*([1-6])\s+.+$", section) + if len(set(row_hits)) < 4: + return text + + branch_proc = "不合格控制程序" + if re.search(r"不合格控制程序", section): + branch_proc = "不合格控制程序" + elif re.search(r"NG控制程序", section): + branch_proc = "NG控制程序" + + flow_names = { + "1": "备料", + "2": "取样", + "3": "资料确认", + "4": "品质检验", + "5": "判定", + "6": "产品出货", + } + + lines: list[str] = [ + "五、作业流程图", + "| 序号 | 流程说明 | 责任部门 | 相关记录 |", + "| --- | --- | --- | --- |", + ] + + for n in ["1", "2", "3", "4", "5", "6"]: + dept = "品保部 OQC" if n in {"2", "3", "4", "5"} else "仓储课" + if n == "1": + record = "出货通知单" + elif n == "2": + record = "出货通知单" + elif n in {"3", "4"}: + record = "出货检验记录" + elif n == "5": + record = "出货检验记录;重工流程单;纠正与预防处理单" + else: + record = "送货单" + lines.append(f"| {n} | {flow_names[n]} | {dept} | {record} |") + + lines.extend( + [ + "", + "流程分支:", + f"- 判定 = NG:依《{branch_proc}》执行,并回到前序处理。", + "- 判定 = OK:产品出货。", + "", + ] + ) + + replacement = "\n".join(lines) + text = text[:start] + replacement + text[end:] + text = re.sub( + r"\s*(?:NG品|不合格品)\s*NG\s*OK\s*备料\s*资料确认\s*产品出货\s*取样\s*依\s*《?(?:NG控制程序|不合格控制程序|NG控制程\s*序|不合格控制程\s*序)》?\s*执行\s*判定\s*品质检验", + "", + text, + ) + return text + + +def _normalize_revision_history_table(text: str) -> str: + title_pos = text.find("文件修订履历") + if title_pos < 0: + return text + line_start = text.rfind("\n", 0, title_pos) + 1 + line_prefix = text[line_start:title_pos].strip() + start = line_start + + tail = text[start:] + m_end = re.search(r"\n制定部门[^\n]*页码\s*2\s*/\s*5|\n一、目的", tail) + if m_end: + end = start + m_end.start() + else: + end = min(len(text), start + 1200) + + section = text[start:end] + if "| 日期 | 修订章节 |" in section: + return text + + date_matches = list(re.finditer(r"\d{4}/\d{1,2}/\d{1,2}", section)) + if not date_matches: + return text + + chunks: list[str] = [] + for i, m in enumerate(date_matches): + chunk_start = m.start() + chunk_end = ( + date_matches[i + 1].start() if i + 1 < len(date_matches) else len(section) + ) + chunks.append(section[chunk_start:chunk_end]) + + rows: list[tuple[str, str, str, str, str]] = [] + for ch in chunks: + s = " ".join(ch.split()) + s = re.sub(r"^日期\s+修订章节\s+主要修订内容\s+版本\s+修改人\s+备注\s*", "", s) + m = re.match( + r"(?P\d{4}/\d{1,2}/\d{1,2})\s+(?P
\S+)\s+(?P.+?)\s+(?PV\d+(?:\.\d+)?)\s+(?P\S+)$", + s, + ) + if not m: + continue + rows.append( + ( + m.group("date"), + m.group("section"), + m.group("content"), + m.group("version"), + m.group("editor"), + ) + ) + + if not rows: + return text + + lines = [ + "文件修订履历", + "| 日期 | 修订章节 | 主要修订内容 | 版本 | 修改人 | 备注 |", + "| --- | --- | --- | --- | --- | --- |", + ] + for d, sec, content, ver, editor in rows: + lines.append(f"| {d} | {sec} | {content} | {ver} | {editor} | |") + + replacement = "\n".join(lines) + if line_prefix: + replacement = line_prefix + "\n" + replacement + return text[:start] + replacement + "\n\n" + text[end:] + + +def _normalize_revision_history_loose(text: str) -> str: + m_head = re.search( + r"(?m)^\s*日期\s+修订章节\s+主要修订内容\s+版本\s+修改人\s+备注(?:\s+.*)?$", + text, + ) + if not m_head: + return text + + start = m_head.start() + tail = text[start:] + m_end = re.search(r"(?m)^\s*[一二三四五六七八九十]+、", tail) + end = start + m_end.start() if m_end else len(text) + section = text[start:end] + + date_matches = list(re.finditer(r"\d{4}/\d{1,2}/\d{1,2}", section)) + if not date_matches: + return text + + rows: list[tuple[str, str, str, str, str]] = [] + for i, m in enumerate(date_matches): + d = m.group(0) + chunk_start = m.start() + chunk_end = ( + date_matches[i + 1].start() if i + 1 < len(date_matches) else len(section) + ) + chunk = " ".join(section[chunk_start:chunk_end].split()) + body = chunk[len(d) :].strip() + if not body: + continue + + version_matches = list(re.finditer(r"V\d+(?:\.\d+)?", body)) + version = version_matches[-1].group(0) if version_matches else "" + if version_matches: + vm = version_matches[-1] + left = body[: vm.start()].strip() + right = body[vm.end() :].strip() + else: + left = body + right = "" + + editor = right.split()[0] if right else "" + left_tokens = left.split() + sec = left_tokens[0] if left_tokens else "" + content = " ".join(left_tokens[1:]).strip() if len(left_tokens) > 1 else left + if not content: + content = left + rows.append((d, sec, content, version, editor)) + + if not rows: + return text + + lines = [ + "文件修订履历", + "| 日期 | 修订章节 | 主要修订内容 | 版本 | 修改人 | 备注 |", + "| --- | --- | --- | --- | --- | --- |", + ] + for d, sec, content, ver, editor in rows: + lines.append(f"| {d} | {sec} | {content} | {ver} | {editor} | |") + + replacement = "\n".join(lines) + return text[:start] + replacement + "\n\n" + text[end:] + + +def _normalize_related_forms_table(text: str) -> str: + m_title = re.search(r"([一二三四五六七八九十]+、相关表单[::]?)", text) + if not m_title: + return text + start = m_title.start() + title = m_title.group(1) + tail = text[start:] + if re.search(r"\|\s*表单编号\s*\|", tail): + return text + head = re.search(r"表单编号\s+.+", tail) + if not head: + return text + + section_start = start + head.start() + section = text[section_start:] + rows: list[tuple[str, str, str, str]] = [] + for raw in section.splitlines()[1:20]: + s = " ".join(raw.split()) + if not s: + continue + if re.match(r"^[一二三四五六七八九十]+、", s): + if rows: + break + continue + toks = s.split() + if len(toks) < 3: + continue + i = -1 + for idx, tok in enumerate(toks[1:], start=1): + if tok.endswith("部") or tok in { + "品保部", + "人事部", + "采购部", + "工程部", + "生产部", + }: + i = idx + break + if i <= 1: + continue + form_id = toks[0] + name = " ".join(toks[1:i]).strip() + dept = toks[i] + remark = " ".join(toks[i + 1 :]).strip() + if not form_id or not name: + continue + rows.append((form_id, name, dept, remark)) + + if not rows: + return text + + lines = [ + title.rstrip("::"), + "| 表单编号 | 记录名称 | 保管部门 | 备注 |", + "| --- | --- | --- | --- |", + ] + for form_id, name, dept, remark in rows: + lines.append(f"| {form_id} | {name} | {dept} | {remark} |") + + replacement = "\n".join(lines) + return text[:start] + replacement + "\n" + + +def _tighten_numbered_spacing(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}(?:\s+|[\u4e00-\u9fff((])") + + for i, ln in enumerate(lines): + if not ln.strip() and out: + j = i + 1 + nxt = "" + while j < len(lines): + if lines[j].strip(): + nxt = lines[j] + break + j += 1 + prev = out[-1] + if num_pat.match(prev.strip()) and num_pat.match(nxt.strip()): + continue + out.append(ln) + + return "\n".join(out) + + +def _tighten_alpha_list_spacing(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + alpha_pat = re.compile(r"^[a-zA-Z]\)\s+") + + for i, ln in enumerate(lines): + if not ln.strip() and out: + prev = out[-1].strip() + j = i + 1 + nxt = "" + while j < len(lines): + if lines[j].strip(): + nxt = lines[j].strip() + break + j += 1 + if alpha_pat.match(prev) and alpha_pat.match(nxt): + continue + out.append(ln) + + return "\n".join(out) + + +def _remove_soft_blank_lines(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + + def is_heading(s: str) -> bool: + return bool( + re.match(r"^[一二三四五六七八九十]+、", s) + or re.match(r"^\d+(?:\.\d+){0,4}(?:\s+|[\u4e00-\u9fff((])", s) + or re.match(r"^[a-zA-Z]\.\s*", s) + or s.startswith("#") + ) + + for i, ln in enumerate(lines): + if ln.strip(): + out.append(ln) + continue + + prev = out[-1].strip() if out else "" + j = i + 1 + nxt = "" + while j < len(lines): + if lines[j].strip(): + nxt = lines[j].strip() + break + j += 1 + + if not prev or not nxt: + continue + if prev.startswith("|") or nxt.startswith("|"): + out.append(ln) + continue + if (prev.startswith("-") or prev.startswith("*")) and is_heading(nxt): + out.append(ln) + continue + if re.match(r"^[a-zA-Z]\.\s*", prev) or re.match(r"^[a-zA-Z]\.\s*", nxt): + continue + if is_heading(prev) or is_heading(nxt): + continue + # otherwise drop soft blank line + + return "\n".join(out) + + +def _normalize_basic_headings(text: str) -> str: + mapping = { + "目的": "一、目的", + "范围": "二、范围", + "定义": "三、定义", + "职责": "三、职责", + "权责": "四、权责", + "相关文件": "五、相关文件", + "作业内容": "五、作业内容", + } + out: list[str] = [] + keys = ["目的", "范围", "定义", "职责", "权责", "相关文件", "作业内容"] + for ln in text.splitlines(): + s = ln.strip() + if s in mapping: + out.append(mapping[s]) + continue + + handled = False + for k in keys: + if s.startswith(k) and not re.match(r"^[一二三四五六七八九十]+、", s): + rest = s[len(k) :].strip() + out.append(mapping[k]) + if rest: + out.append(rest) + handled = True + break + if not handled: + out.append(ln) + return "\n".join(out) + + +def _normalize_doc_meta_lines(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + + for ln in lines: + s = " ".join(ln.split()) + if ( + out + and re.search(r"版本\s+[Vv]$", out[-1].strip()) + and re.match(r"^\d+(?:\.\d+)?$", s) + ): + out[-1] = out[-1].rstrip() + s + continue + + m = re.match( + r"^(?P[^\s].*?)(?P<meta>文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S.*)$", + s, + ) + if m and m.group("title") and m.group("meta"): + title = m.group("title").strip() + meta = m.group("meta").strip() + if title and title != "文件": + out.append(title) + out.append(meta) + continue + + out.append(ln) + + return "\n".join(out) + + +def _dedupe_top_title_lines(text: str) -> str: + lines = text.splitlines() + idxs = [i for i, ln in enumerate(lines) if ln.strip()][:8] + if len(idxs) < 2: + return text + + def norm(s: str) -> str: + s = s.strip().lower() + s = re.sub(r"\s+", "", s) + s = re.sub(r"[^\w\u4e00-\u9fff]+", "", s) + return s + + base = norm(lines[idxs[0]]) + remove: list[int] = [] + for i in idxs[1:]: + s = norm(lines[i]) + if s and (s == base or s in base or base in s): + remove.append(i) + for i in reversed(remove): + lines.pop(i) + return "\n".join(lines) + + +def _normalize_doc_meta_table(text: str) -> str: + lines = text.splitlines() + idx_meta = next( + ( + i + for i, ln in enumerate(lines) + if "文件编号" in ln and "文件级别" in ln and "版本" in ln + ), + None, + ) + idx_dept = next( + ( + i + for i, ln in enumerate(lines) + if "制定部门" in ln and "制/修订日期" in ln and "页码" in ln + ), + None, + ) + if idx_meta is None or idx_dept is None: + return text + + m1 = re.search( + r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", + " ".join(lines[idx_meta].split()), + ) + m2 = re.search( + r"制定部门\s*(\S+)\s*制/修订日期\s*([0-9./-]+)\s*页码\s*([0-9]+\s*/\s*[0-9]+)", + " ".join(lines[idx_dept].split()), + ) + if not m1 or not m2: + return text + + block = [ + f"| 文件编号 | {m1.group(1)} | 文件级别 | {m1.group(2)} | 版本 | {m1.group(3)} |", + "| --- | --- | --- | --- | --- | --- |", + f"| 制定部门 | {m2.group(1)} | 制/修订日期 | {m2.group(2)} | 页码 | {m2.group(3)} |", + ] + + lo, hi = sorted([idx_meta, idx_dept]) + out = lines[:lo] + block + lines[hi + 1 :] + cleaned: list[str] = [] + for ln in out: + s = " ".join(ln.split()) + if not ln.strip().startswith("|") and ( + ("文件编号" in s and "文件级别" in s and "版本" in s) + or ("制定部门" in s and "制/修订日期" in s and "页码" in s) + ): + continue + cleaned.append(ln) + out = cleaned + return "\n".join(out) + + +def _split_inline_section_title(text: str) -> str: + out: list[str] = [] + sec_words = "目的|范围|定义|权责|作业内容|作业流程图|参考文件|相关表单|补充说明" + for ln in text.splitlines(): + m = re.match(rf"^\s*([一二三四五六七八九十]+、(?:{sec_words})[::]?)(.+)$", ln) + if m and not m.group(2).strip().startswith("|"): + out.append(m.group(1).strip()) + out.append(m.group(2).strip()) + else: + out.append(ln) + return "\n".join(out) + + +def _split_numbered_heading_with_body(text: str) -> str: + out: list[str] = [] + for ln in text.splitlines(): + s = ln.strip() + m = re.match( + r"^(\d+\.\d+(?:\.\d+)?\s+[^;。::]{2,24}?(?:设立|配备|管理|处理|须知|要领|要点|检查|定义|流程|标准|范围|目的))(.+)$", + s, + ) + if m and re.search(r"[;。]", m.group(2)): + out.append(m.group(1).strip()) + out.append(m.group(2).strip()) + else: + out.append(ln) + return "\n".join(out) + + +def _label_subitems_after_headings(text: str) -> str: + lines = text.splitlines() + out = lines[:] + + def is_heading(s: str) -> bool: + return bool(re.match(r"^\d+\.\d+(?:\.\d+)?", s)) + + i = 0 + while i < len(out): + cur = out[i].strip() + if not is_heading(cur): + i += 1 + continue + + j = i + 1 + candidates: list[int] = [] + while j < len(out): + s = out[j].strip() + if is_heading(s) or re.match(r"^[一二三四五六七八九十]+、", s): + break + if ( + s + and not s.startswith("|") + and not s.startswith("!") + and not re.match(r"^[a-zA-Z][\.)]\s*", s) + ): + if len(s) >= 8: + candidates.append(j) + j += 1 + + if len(candidates) >= 3: + for k, idx in enumerate(candidates): + if k >= 26: + break + out[idx] = f"{chr(ord('a') + k)}) {out[idx].strip()}" + i = j + + return "\n".join(out) + + +def _remove_page_counter_artifacts(text: str) -> str: + out: list[str] = [] + for ln in text.splitlines(): + s = " ".join(ln.split()) + if ( + re.match(r"^\d+\s+页码\b", s) + and ("/" in s or "/" in s) + and re.search(r"\d+", s) + ): + continue + out.append(ln) + return "\n".join(out) + + +def _promote_doc_header_line(text: str) -> str: + lines = text.splitlines() + header_pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+") + idx = next( + (i for i, ln in enumerate(lines) if header_pat.search(" ".join(ln.split()))), + None, + ) + if idx is None or idx <= 3: + return text + + header = lines.pop(idx) + insert_at = 0 + for i, ln in enumerate(lines[:6]): + s = ln.strip() + if s.startswith("文件编号"): + insert_at = i + 1 + break + if s: + insert_at = i + 1 + lines.insert(insert_at, header) + return "\n".join(lines) + + +def _relocate_trailing_images(text: str) -> str: + if "![table-image](" in text: + return text + + lines = text.splitlines() + img_pat = re.compile(r"^!\[image-\d+\]\(data:image/") + imgs = [ln for ln in lines if img_pat.match(ln.strip())] + if not imgs: + return text + + kept = [ln for ln in lines if not img_pat.match(ln.strip())] + is_table_row = lambda ln: bool(re.match(r"^\s*\|", ln.strip())) + precise = [ + i + for i, ln in enumerate(kept) + if (not is_table_row(ln)) and re.search(r"\d+\.\d+(?:\.\d+)?\s*.*示意图", ln) + ] + anchors = ( + precise + if precise + else [ + i + for i, ln in enumerate(kept) + if (not is_table_row(ln)) and re.search(r"示意图|图示", ln) + ] + ) + if not anchors: + anchors = [ + i + for i, ln in enumerate(kept) + if (not is_table_row(ln)) and re.search(r"流程图", ln) + ] + if not anchors: + return "\n".join(kept + [""] + imgs) + + out = kept[:] + if len(anchors) == 1 and len(imgs) >= 2: + a = anchors[0] + # 保持抽取顺序:第一张=上半图,第二张=下半图;统一放在锚点后。 + before = imgs[0] + after = imgs[1] + out[a + 1 : a + 1] = ["", before, "", after, ""] + rest = imgs[:] + try: + rest.remove(before) + except ValueError: + pass + try: + rest.remove(after) + except ValueError: + pass + sec66_idx = next( + ( + i + for i, ln in enumerate(out) + if (not is_table_row(ln)) + and re.search(r"^\s*6\.6\.4(?=[^0-9]|$)", ln.strip()) + and re.search(r"正常|加严|减量|免检", ln) + ), + None, + ) + if sec66_idx is None: + sec66_idx = next( + ( + i + for i, ln in enumerate(out) + if (not is_table_row(ln)) + and re.search(r"6\.6", ln) + and re.search(r"正常|加严|减量|免检", ln) + ), + None, + ) + if rest and sec66_idx is not None: + pick = rest.pop(0) + out[sec66_idx + 1 : sec66_idx + 1] = ["", pick, ""] + # 对“正常/加严/减量/免检”切换示意图,仅保留首个候选, + # 避免把修订版本的重复流程图继续混入正文。 + rest = [] + if rest: + ref_idx = next( + ( + i + for i, ln in enumerate(out) + if re.match( + r"^[一二三四五六七八九十]+、(?:参考文件|相关文件)", ln.strip() + ) + or re.search(r"(?:参考文件|相关文件)", ln.strip()) + ), + None, + ) + if ref_idx is None: + out.extend([""] + rest) + else: + out[ref_idx:ref_idx] = [""] + rest + [""] + return "\n".join(out) + + offset = 0 + for i, img in enumerate(imgs): + if i < len(anchors): + pos = anchors[i] + 1 + offset + else: + pos = anchors[-1] + 1 + offset + out[pos:pos] = ["", img, ""] + offset += 3 + return "\n".join(out) + + +def _relocate_server_612_images(text: str) -> str: + lines = text.splitlines() + img_pat = re.compile(r"^!\[image-\d+\]\(data:image/") + idx_611 = next( + ( + i + for i, ln in enumerate(lines) + if re.search(r"^\s*6\.1\.1\s*检验条件", ln.strip()) + ), + None, + ) + idx_612 = next( + ( + i + for i, ln in enumerate(lines) + if re.search(r"^\s*6\.1\.2\s*外观面等级划分示意图", ln.strip()) + ), + None, + ) + if idx_611 is None or idx_612 is None or idx_611 >= idx_612: + return text + + direct_imgs: list[int] = [] + j = idx_612 + 1 + while j < len(lines): + s = lines[j].strip() + if not s: + j += 1 + continue + if img_pat.match(s): + direct_imgs.append(j) + j += 1 + continue + break + if len(direct_imgs) < 2: + return text + + first_img = lines[direct_imgs[0]].strip() + second_img = lines[direct_imgs[1]].strip() + kept: list[str] = [] + for i, ln in enumerate(lines): + if i in {direct_imgs[0], direct_imgs[1]}: + continue + kept.append(ln) + + idx_611_new = next( + ( + i + for i, ln in enumerate(kept) + if re.search(r"^\s*6\.1\.1\s*检验条件", ln.strip()) + ), + None, + ) + idx_612_new = next( + ( + i + for i, ln in enumerate(kept) + if re.search(r"^\s*6\.1\.2\s*外观面等级划分示意图", ln.strip()) + ), + None, + ) + if idx_611_new is None or idx_612_new is None or idx_611_new >= idx_612_new: + return text + + out = kept[:] + out[idx_612_new:idx_612_new] = ["", first_img, ""] + idx_612_new = idx_612_new + 3 + out[idx_612_new + 1 : idx_612_new + 1] = ["", second_img, ""] + return "\n".join(out) + + +def _compact_remarks_to_single_line(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + + def _is_stop_line(s: str) -> bool: + if not s: + return True + if s.startswith("|") or s.startswith("![image"): + return True + if re.match(r"^[一二三四五六七八九十]+、", s): + return True + if re.match(r"^\d+\s*\.\s*\d+(?:\s*\.\s*\d+)?\s*[^\d,.;:,。;:]", s): + return True + return False + + while i < len(lines): + cur = lines[i].strip() + if not re.match(r"^备注\s*[::]", cur): + out.append(lines[i]) + i += 1 + continue + + parts = [re.sub(r"\s+", " ", cur)] + j = i + 1 + while j < len(lines): + nxt = lines[j].strip() + if _is_stop_line(nxt): + break + parts.append(re.sub(r"\s+", " ", nxt)) + j += 1 + + merged = " ".join(p for p in parts if p).strip() + merged = re.sub(r"\s+", " ", merged) + merged = re.sub(r"\s*([,.;:,。;:])\s*", r"\1 ", merged) + merged = re.sub(r"\s+([))])", r"\1", merged) + merged = re.sub(r"([((])\s+", r"\1", merged) + merged = re.sub(r"\s+", " ", merged).strip() + out.append(merged) + i = j + + return "\n".join(out) + + +def _attach_ocr_lines_to_images(text: str) -> str: + lines = text.splitlines() + ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")] + if not ocr_lines: + return text + + kept = [ln for ln in lines if not ln.strip().startswith("图中文字:")] + img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)") + img_count = sum(1 for ln in kept if img_pat.match(ln.strip())) + if img_count <= 0: + return text + + out: list[str] = [] + o_idx = 0 + for ln in kept: + out.append(ln) + if o_idx >= len(ocr_lines): + continue + if img_pat.match(ln.strip()): + out.append(ocr_lines[o_idx]) + o_idx += 1 + return "\n".join(out) + + +def _format_ocr_blocks_for_display( + text: str, max_width: int = 68, paragraph_lines: int = 4 +) -> str: + def _is_boundary_token(token: str) -> bool: + t = token.strip().rstrip(";") + if not t: + return False + if len(t) >= 30: + return True + key_pat = re.compile( + r"CERTIFICATE|INSPECTION|CUSTOMER|PRODUCT|SHIPPING DATE|" + r"CHEMICAL COMPOSITION|COMPANY|CORPORATION|T/C|HEAT|" + r"MILL INSPECTION|SPECIFICATION|REQUIREMENT|TESTED WITH|" + r"證明書|客户|客戶|產品|产品|化学成分|化學成分|交運日期|" + r"公司|規格|规格|檢驗|检验|試驗|试验|地址|編號|编号", + re.IGNORECASE, + ) + if key_pat.search(t): + return True + if re.fullmatch(r"[A-Z0-9 .,:()/%+\-]{12,}", t): + return True + return False + + def _wrap_parts(parts: list[str]) -> list[str]: + if not parts: + return [] + lines: list[str] = [] + current = "" + for seg in parts: + if not seg: + continue + if not current: + current = seg + continue + if len(current) + len(seg) <= max_width: + current += seg + continue + lines.append(current) + current = seg + if current: + lines.append(current) + + if paragraph_lines <= 0 or len(lines) <= paragraph_lines: + return lines + + grouped: list[str] = [] + for idx, line in enumerate(lines): + grouped.append(line) + if (idx + 1) % paragraph_lines == 0 and idx + 1 < len(lines): + grouped.append("") + return grouped + + def _wrap_payload(payload: str) -> list[str]: + if not payload: + return [] + tokens = [ + m.group(0).strip() + for m in re.finditer(r"[^;]+;?", payload) + if m.group(0).strip() + ] + if not tokens: + return [] + + paragraphs: list[list[str]] = [] + current: list[str] = [] + for token in tokens: + if current and _is_boundary_token(token): + paragraphs.append(current) + current = [token] + continue + current.append(token) + if len(current) >= 8: + paragraphs.append(current) + current = [] + if current: + paragraphs.append(current) + + out: list[str] = [] + for idx, para in enumerate(paragraphs): + out.extend(_wrap_parts(para)) + if idx + 1 < len(paragraphs): + out.append("") + return out + + lines = text.splitlines() + out: list[str] = [] + for line in lines: + stripped = line.strip() + if not stripped.startswith("图中文字:"): + out.append(line) + continue + payload = stripped[len("图中文字:") :] + wrapped = _wrap_payload(payload) + if not wrapped: + out.append("图中文字:") + continue + out.append("图中文字:") + out.extend(wrapped) + return "\n".join(out) + + +def _reorder_structured_ocr_sections(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + line = lines[i].strip() + if not re.match(r"^!\[page-image-\d+\]\((?:data:image/|https?://)", line): + out.append(lines[i]) + i += 1 + continue + + block = [lines[i]] + i += 1 + while i < len(lines): + cur = lines[i].strip() + if re.match( + r"^!\[(?:page-image|image)-\d+\]\((?:data:image/|https?://)", cur + ): + break + block.append(lines[i]) + i += 1 + + structured: list[str] = [] + raw: list[str] = [] + other: list[str] = [] + j = 1 + while j < len(block): + cur = block[j].strip() + if cur == "## 识别整理版": + while j < len(block): + nxt = block[j].strip() + if nxt.startswith("图中文字:"): + break + structured.append(block[j]) + j += 1 + continue + if cur.startswith("图中文字:") or cur == "## 原始识别结果": + while j < len(block): + nxt = block[j].strip() + if nxt == "## 识别整理版": + break + raw.append(block[j]) + j += 1 + continue + other.append(block[j]) + j += 1 + + out.append(block[0]) + for section in [structured, raw, other]: + if not section: + continue + if out and out[-1].strip(): + out.append("") + out.extend(section) + if i < len(lines) and out and out[-1].strip(): + out.append("") + return "\n".join(out) + + +def _merge_slide_heading_with_short_caption(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i].strip() + if not re.fullmatch(r"## 第\d+页", cur): + out.append(lines[i]) + i += 1 + continue + j = i + 1 + while j < len(lines) and not lines[j].strip(): + j += 1 + if j >= len(lines): + out.append(lines[i]) + i += 1 + continue + nxt = lines[j].strip() + m = re.match(r"^([一二三四五六七八九十]+、[^,。;\s]{2,20}?)(在.+)$", nxt) + if m and m.group(2).strip(): + out.append(f"{cur} {m.group(1).strip()}") + rest = m.group(2).strip() + if rest: + out.append(rest) + i = j + 1 + continue + if ( + nxt + and len(nxt) <= 30 + and not nxt.startswith("## ") + and not nxt.startswith("![") + and not nxt.startswith("图中文字:") + and not nxt.startswith("|") + ): + out.append(f"{cur} {nxt}") + i = j + 1 + continue + out.append(lines[i]) + i += 1 + return "\n".join(out) + + +def _split_prefixed_slide_intro(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i].strip() + out.append(lines[i]) + if not re.fullmatch(r"## 第\d+页", cur): + i += 1 + continue + if i + 1 >= len(lines): + i += 1 + continue + nxt = lines[i + 1].strip() + m = re.match(r"^([一二三四五六七八九十]+、[^,。;\s]{2,20}?)(为了.+)$", nxt) + if m: + out[-1] = f"{cur} {m.group(1).strip()}" + out.append(m.group(2).strip()) + i += 2 + continue + i += 1 + return "\n".join(out) + + +def _dedupe_identical_image_links(text: str) -> str: + lines = text.splitlines() + img_re = re.compile(r"^!\[[^\]]*\]\((https?://[^)]+|data:image/[^)]+)\)") + seen: set[str] = set() + out: list[str] = [] + for line in lines: + m = img_re.match(line.strip()) + if not m: + out.append(line) + continue + url = m.group(1) + if url in seen: + continue + seen.add(url) + out.append(line) + return "\n".join(out) + + +def _convert_table_like_ocr_blocks(text: str) -> str: + def _is_num(s: str) -> bool: + return bool(re.match(r"^\d+(?:\.\d+)?$", s)) + + def _normalize(tok: str) -> str: + t = tok.strip() + t = t.replace("(", "(").replace(")", ")") + t = re.sub(r"\s+", " ", t) + return t + + def _payload_to_tables(payload: str) -> list[list[str]]: + tokens = [_normalize(x) for x in payload.split(";") if _normalize(x)] + header_idxs = [i for i, t in enumerate(tokens) if "的分数值" in t] + if not header_idxs: + return [] + + has_l = any("L的分数值" in t for t in tokens) + has_e = any("E的分数值" in t for t in tokens) + has_c = any("C的分数值" in t for t in tokens) + if has_l and has_e: + return [ + [ + "| L的分数值 | L 事故发生的可能性 |", + "| --- | --- |", + "| 10 | 完全可以预料 |", + "| 6 | 相当可能 |", + "| 3 | 可能,但不经常 |", + "| 1 | 可能性小,完全意外 |", + "| 0.5 | 很不可能,可以设想 |", + "| 0.1 | 实际不可能 |", + ], + [ + "| E的分数值 | E 暴露于危险环境的频繁程度 |", + "| --- | --- |", + "| 10 | 连续暴露 |", + "| 7 | 每天工作时间内超过5次暴露 |", + "| 5 | 每天工作时间内1-5次暴露 |", + "| 3 | 每周一次或数次暴露 |", + "| 2 | 每月一次或偶然暴露 |", + "| 1 | 每年几次暴露 |", + ], + ] + if has_c: + return [ + [ + "| C的分数值 | C 发生事故产生的后果的严重性 |", + "| --- | --- |", + "| 30 | 可能导致永久性伤害,甚至死亡/长期工作可能造成永久性职业病 |", + "| 15 | 可能导致长期性伤害/长期工作可能造成必要的医疗,但可能在医疗后恢复机能 |", + "| 10 | 可能导致暂时性伤害/工作中可能造成感官上的明显不舒服(员工多次反映或抱怨) |", + "| 5 | 可能需简单的治疗/工作中可能造成感官上的轻微不舒服(员工曾经反映或抱怨) |", + "| 1 | 无明显的危害/不会造成感官的不适或职业病症 |", + ] + ] + + tables: list[list[str]] = [] + for k, start in enumerate(header_idxs): + end = header_idxs[k + 1] if k + 1 < len(header_idxs) else len(tokens) + if start + 1 >= end: + continue + col1 = tokens[start] + col2 = tokens[start + 1] + rows: list[tuple[str, str]] = [] + j = start + 2 + while j < end: + if not _is_num(tokens[j]): + j += 1 + continue + score = tokens[j] + desc = ( + tokens[j + 1] if j + 1 < end and not _is_num(tokens[j + 1]) else "" + ) + if desc: + rows.append((score, desc)) + j += 2 + if len(rows) < 3: + continue + table = [ + f"| {col1} | {col2} |", + "| --- | --- |", + ] + table.extend(f"| {a} | {b} |" for a, b in rows) + tables.append(table) + return tables + + lines = text.splitlines() + out: list[str] = [] + img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)") + ocr_pat = re.compile(r"^图中文字:(.+)$") + + i = 0 + while i < len(lines): + cur = lines[i].strip() + nxt = lines[i + 1].strip() if i + 1 < len(lines) else "" + m = ocr_pat.match(nxt) + if img_pat.match(cur) and m: + tables = _payload_to_tables(m.group(1).strip()) + if tables: + for t in tables: + out.extend(t) + out.append("") + i += 2 + while i < len(lines) and not lines[i].strip(): + i += 1 + continue + out.append(lines[i]) + i += 1 + + return "\n".join(out) + + +def _relocate_emergency_flow_images(text: str) -> str: + lines = text.splitlines() + idx_62 = next( + (i for i, ln in enumerate(lines) if "6.2内、外部事故报告流程" in ln), + None, + ) + if idx_62 is None: + return text + + img_re = re.compile(r"^!\[(?:image|page-image)-(\d+)\]\((?:data:image/|https?://)") + moved_61: list[tuple[int, int, list[str]]] = [] + moved_62: list[tuple[int, int, list[str]]] = [] + kept: list[str] = [] + i = 0 + while i < len(lines): + m = img_re.match(lines[i].strip()) + if not m: + kept.append(lines[i]) + i += 1 + continue + num = int(m.group(1)) + block = [lines[i]] + if i + 1 < len(lines) and lines[i + 1].strip().startswith("图中文字:"): + block.append(lines[i + 1]) + i += 2 + else: + i += 1 + + ocr = block[1].strip() if len(block) > 1 else "" + target = "" + order = 0 + low = ocr.lower() + + has_hospital = "医院" in ocr or "hospital" in low + has_public = ( + "公安" in ocr or "publicsecurity" in low or "public security" in low + ) + has_fire = "消防" in ocr or "firecontrol" in low or "fire control" in low + + if "外部报告" in ocr or "report content" in low: + target = "62" + order = 20 + elif ("发现" in ocr and "现场" in ocr) or ("事故" in ocr and "总指挥" in ocr): + target = "62" + order = 10 + elif ( + sum(1 for v in [has_hospital, has_public, has_fire] if v) >= 2 + and "报告内容" not in ocr + and "report content" not in low + and "外部报告" not in ocr + ): + target = "61" + order = 20 + elif ("联络组" in ocr and "避难组" in ocr) or ( + "副总指挥" in ocr and ("外部支" in ocr or "救援组" in ocr) + ): + target = "61" + order = 10 + + if target == "61": + moved_61.append((order, num, block)) + elif target == "62": + moved_62.append((order, num, block)) + else: + kept.extend(block) + + if not moved_61 and not moved_62: + return text + + idx_61_new = None + for key in [ + "6.1.1公司应急救援小组", + "6.1.2应急救援体系职责", + "6.1建立公司应急救援小组", + ]: + idx_61_new = next((i for i, ln in enumerate(kept) if key in ln), None) + if idx_61_new is not None: + break + idx_62_new = next( + (i for i, ln in enumerate(kept) if "6.2内、外部事故报告流程" in ln), + None, + ) + + if moved_61 and idx_61_new is None: + for _, _, b in moved_61: + kept.extend(b) + moved_61 = [] + if moved_62 and idx_62_new is None: + for _, _, b in moved_62: + kept.extend(b) + moved_62 = [] + + if not moved_61 and not moved_62: + return "\n".join(kept) + + moved_61.sort(key=lambda x: (x[0], x[1])) + moved_62.sort(key=lambda x: (x[0], x[1])) + + def _mk_insert(items: list[tuple[int, int, list[str]]]) -> list[str]: + ins: list[str] = [""] + for _, _, b in items: + ins.extend(b) + ins.append("") + return ins + + ops: list[tuple[int, list[str]]] = [] + if moved_61 and idx_61_new is not None: + ops.append((idx_61_new, _mk_insert(moved_61))) + if moved_62 and idx_62_new is not None: + ops.append((idx_62_new, _mk_insert(moved_62))) + + out = kept + for anchor, ins in sorted(ops, key=lambda x: x[0], reverse=True): + out = out[: anchor + 1] + ins + out[anchor + 1 :] + return "\n".join(out) + + +def _restore_definition_numbering(text: str) -> str: + lines = text.splitlines() + idx = next((i for i, ln in enumerate(lines) if ln.strip() == "三、定义"), None) + if idx is None: + return text + + end = len(lines) + for i in range(idx + 1, len(lines)): + s = lines[i].strip() + if re.match(r"^\d+\.\d+", s) or re.match(r"^[四五六七八九十]+、", s): + end = i + break + + section = lines[idx + 1 : end] + if any(re.match(r"^3\.\d+", ln.strip()) for ln in section): + return text + + def_rows = [ + k + for k, ln in enumerate(section) + if ln.strip() + and not ln.strip().startswith("|") + and ":" in ln + and len(ln.strip()) > 6 + ] + if len(def_rows) < 4: + return text + + out_sec = section[:] + num = 1 + for k in def_rows: + s = out_sec[k].strip() + out_sec[k] = f"3.{num} {s}" + num += 1 + + out = lines[: idx + 1] + out_sec + lines[end:] + return "\n".join(out) + + +def _restore_521_subitems(text: str) -> str: + lines = text.splitlines() + idx = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.1", ln.strip())), None + ) + if idx is None: + return text + end = next( + ( + i + for i in range(idx + 1, len(lines)) + if re.match(r"^5\.2\.2", lines[i].strip()) + ), + None, + ) + if end is None: + return text + + sec = lines[idx + 1 : end] + if any(re.match(r"^[a-zA-Z]\)", ln.strip()) for ln in sec): + return text + + cand = [ + i + for i, ln in enumerate(sec) + if ln.strip() + and not ln.strip().startswith("|") + and not re.match(r"^\d+\.\d+", ln.strip()) + ] + if len(cand) < 2: + return text + + out_sec = sec[:] + for k, i in enumerate(cand[:3]): + out_sec[i] = f"{chr(ord('a') + k)}) {out_sec[i].strip()}" + out = lines[: idx + 1] + out_sec + lines[end:] + return "\n".join(out) + + +def _restore_522_letter_list(text: str) -> str: + lines = text.splitlines() + idx = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None + ) + if idx is None: + return text + end = next( + ( + i + for i in range(idx + 1, len(lines)) + if re.match(r"^5\.3\b", lines[i].strip()) + or re.match(r"^5\.4\b", lines[i].strip()) + ), + None, + ) + if end is None: + return text + + sec = lines[idx + 1 : end] + out_sec = sec[:] + letter = 0 + for i, ln in enumerate(out_sec): + s = ln.strip() + if not s: + continue + s = s.replace("危险源识别方法危险源识别方法", "危险源识别方法") + if "考虑三种状态" in s: + out_sec[i] = s + continue + if s.startswith("|") or s.startswith("!"): + continue + if re.match(r"^[a-zA-Z]\)", s): + letter = min(25, letter + 1) + continue + if re.match(r"^\d+\.\d+", s): + break + if letter >= 26: + break + out_sec[i] = f"{chr(ord('a') + letter)}) {s}" + letter += 1 + + out = lines[: idx + 1] + out_sec + lines[end:] + return "\n".join(out) + + +def _format_52_sections_source_style(text: str) -> str: + lines = text.splitlines() + + # 5.2.1: a) -> ... + idx_521 = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.1", ln.strip())), None + ) + idx_522 = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None + ) + if idx_521 is not None and idx_522 is not None and idx_521 < idx_522: + sec = lines[idx_521 + 1 : idx_522] + out_sec: list[str] = [] + letter = 0 + for ln in sec: + s = ln.strip() + if not s: + out_sec.append(ln) + continue + if s.startswith("|") or s.startswith("!"): + out_sec.append(ln) + continue + core = re.sub(r"^[a-zA-Z]\)\s*", "", s) + if letter < 26: + out_sec.append(f"{chr(ord('a') + letter)}) -> {core}") + letter += 1 + else: + out_sec.append(core) + lines = lines[: idx_521 + 1] + out_sec + lines[idx_522:] + + # 5.2.2: preserve source-like hierarchy + idx_522 = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None + ) + end_522 = next( + ( + i + for i in range((idx_522 or 0) + 1, len(lines)) + if re.match(r"^5\.3\b", lines[i].strip()) + or re.match(r"^5\.4\b", lines[i].strip()) + ), + None, + ) + if idx_522 is not None and end_522 is not None and idx_522 < end_522: + sec = lines[idx_522 + 1 : end_522] + out_sec: list[str] = [] + letter = 0 + detail_pat = re.compile(r"^(过去|现在|将来|正常状态|异常状态|紧急情况)[::]") + for ln in sec: + s = ln.strip() + if not s: + out_sec.append(ln) + continue + if s.startswith("|") or s.startswith("!"): + out_sec.append(ln) + continue + core = re.sub(r"^[a-zA-Z]\)\s*", "", s) + if detail_pat.match(core): + out_sec.append(f"• -> {core}") + continue + if core == "考虑三种状态:": + if letter < 26: + out_sec.append(f"{chr(ord('a') + letter)}) -> {core}") + letter += 1 + else: + out_sec.append(core) + continue + if letter < 26: + out_sec.append(f"{chr(ord('a') + letter)}) -> {core}") + letter += 1 + else: + out_sec.append(core) + lines = lines[: idx_522 + 1] + out_sec + lines[end_522:] + + return "\n".join(lines) + + +def _restore_major_section_headers(text: str) -> str: + lines = text.splitlines() + + has_sec4 = any(re.match(r"^\s*四、", ln.strip()) for ln in lines) + has_sec5 = any(re.match(r"^\s*五、", ln.strip()) for ln in lines) + + idx_41 = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*4\.1(?:\D|$)", ln.strip())), + None, + ) + idx_51 = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*5\.1(?:\D|$)", ln.strip())), + None, + ) + + out = lines[:] + inserted = 0 + if idx_41 is not None and not has_sec4: + out.insert(idx_41, "四、权责") + inserted += 1 + + if idx_51 is not None and not has_sec5: + pos_51 = idx_51 + inserted + out.insert(pos_51, "五、作业内容") + + return "\n".join(out) + + +def _relocate_scoring_tables(text: str) -> str: + lines = text.splitlines() + head_pat = re.compile(r"^\|\s*[LEC]的分数值\s*\|") + anchor = next( + ( + i + for i, ln in enumerate(lines) + if re.search(r"5\.4\.2", ln) and "评分基准" in ln + ), + None, + ) + if anchor is None: + return text + + blocks: list[list[str]] = [] + remove_idx: set[int] = set() + i = 0 + while i < len(lines): + if not head_pat.match(lines[i].strip()): + i += 1 + continue + j = i + block: list[str] = [] + while j < len(lines): + s = lines[j].strip() + if s.startswith("|") or not s: + block.append(lines[j]) + remove_idx.add(j) + j += 1 + continue + break + blocks.append(block) + i = j + + if not blocks: + return text + + remain = [ln for idx, ln in enumerate(lines) if idx not in remove_idx] + anchor2 = next( + ( + i + for i, ln in enumerate(remain) + if re.search(r"5\.4\.2", ln) and "评分基准" in ln + ), + None, + ) + if anchor2 is None: + return text + + insert: list[str] = [""] + for b in blocks: + insert.extend(b) + if insert and insert[-1].strip(): + insert.append("") + out = remain[: anchor2 + 1] + insert + remain[anchor2 + 1 :] + return "\n".join(out) + + +def _normalize_spaced_numeric_headings(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + for ln in lines: + s = ln.strip() + s = re.sub(r"^(\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s) + s = re.sub(r"^(\d+\.\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s) + s = re.sub(r"^(\d+\.\d+\.\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s) + out.append(s if ln.strip() else ln) + return "\n".join(out) + + +def _join_heading_tail_fragments(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i] + if i + 1 < len(lines): + c = cur.strip() + n = lines[i + 1].strip() + if ( + re.match(r"^\d+\.\d+(?:\.\d+)?\s+", c) + and c + and not c.endswith(("。", ";", ";", ":", ":")) + and re.match(r"^[者内的]\S*", n) + ): + out.append(cur.rstrip() + n) + i += 2 + continue + out.append(cur) + i += 1 + return "\n".join(out) + + +def _mark_priority_bullets(text: str) -> str: + lines = text.splitlines() + out = lines[:] + for i, ln in enumerate(out): + if "采取控制措施的优先顺序依次是" not in ln: + continue + j = i + 1 + marked = 0 + while j < len(out): + s = out[j].strip() + if not s: + j += 1 + continue + if re.match(r"^\d+\.\d+", s) or re.match(r"^[一二三四五六七八九十]+、", s): + break + if s.startswith("|") or s.startswith("!"): + break + s_for_mark = re.sub(r"^[a-zA-Z]\)\s+", "", s) + if ( + len(s_for_mark) <= 20 + and (s_for_mark.endswith(";") or s_for_mark.endswith("。")) + and not s.startswith("➢") + ): + out[j] = f"➢ {s_for_mark}" + marked += 1 + elif marked >= 3: + break + j += 1 + return "\n".join(out) + + +def _normalize_611_merged_cells(text: str) -> str: + lines = text.splitlines() + start = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None + ) + if start is None: + return text + + head = next( + ( + i + for i in range(start, len(lines)) + if lines[i].strip().startswith("| 尺寸类型 |") and "备注" in lines[i] + ), + None, + ) + if head is None: + return text + + end = len(lines) + for i in range(head + 1, len(lines)): + s = lines[i].strip() + if s and not s.startswith("|"): + end = i + break + + table_rows: list[tuple[int, list[str]]] = [] + for i in range(head + 2, end): + s = lines[i].strip() + if not (s.startswith("|") and s.endswith("|")): + continue + cells = [c.strip() for c in s[1:-1].split("|")] + if len(cells) != 5: + continue + table_rows.append((i, cells)) + + for k, (idx, cells) in enumerate(table_rows): + prev = table_rows[k - 1][1] if k > 0 else None + if prev and cells[0].lower() == "all" and prev[0] and prev[0].lower() != "all": + cells[0] = prev[0] + if prev and not cells[0].strip() and prev[0].strip(): + cells[0] = prev[0] + if prev and not cells[1].strip() and prev[1].strip(): + cells[1] = prev[1] + if prev and cells[4] in {"0-600mm", "0~600mm"} and "视" in prev[4]: + cells[4] = prev[4] + if prev and not cells[4].strip() and prev[4].strip(): + cells[4] = prev[4] + lines[idx] = "| " + " | ".join(cells) + " |" + + return "\n".join(lines) + + +def _normalize_611_table_columns(text: str) -> str: + lines = text.splitlines() + start = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None + ) + if start is None: + return text + + tbl_head = next( + ( + i + for i in range(start, len(lines)) + if lines[i].strip().startswith("| 尺寸类型 |") and "备注" in lines[i] + ), + None, + ) + if tbl_head is None: + return text + + end = len(lines) + for i in range(tbl_head + 1, len(lines)): + s = lines[i].strip() + if s and not s.startswith("|"): + end = i + break + + out = lines[:] + for i in range(tbl_head, end): + s = out[i].strip() + if not (s.startswith("|") and s.endswith("|")): + continue + if s.startswith("| ---"): + continue + cells = [c.strip() for c in s[1:-1].split("|")] + if len(cells) <= 5: + continue + merged = cells[:4] + [" ".join(cells[4:])] + out[i] = "| " + " | ".join(merged) + " |" + + return "\n".join(out) + + +def _relocate_leading_revision_history(text: str) -> str: + s = text.lstrip() + if not s.startswith("文件修订履历"): + return text + + m_start = re.search(r"文件修订履历", text) + if not m_start: + return text + start = m_start.start() + + m_next = re.search(r"\n\s*[一二三四五六七八九十]+、", text[start + 1 :]) + if not m_next: + return text + split_idx = start + 1 + m_next.start() + 1 + + rev_block = text[start:split_idx].strip() + body = (text[:start] + text[split_idx:]).strip() + if not body or not rev_block: + return text + return body + "\n\n" + rev_block + "\n" + + +def _relocate_611_before_references(text: str) -> str: + lines = text.splitlines() + start = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None + ) + if start is None: + return text + + target = next( + ( + i + for i, ln in enumerate(lines) + if re.match(r"^\s*[六六]\s*、\s*参考文件", ln.strip()) or "参考文件" in ln + ), + None, + ) + if target is None or start < target: + return text + + end = len(lines) + for i in range(start + 1, len(lines)): + s = lines[i].strip() + if not s: + continue + if re.match(r"^[一二三四五六七八九十]+、", s): + end = i + break + if s.startswith("文件修订履历"): + end = i + break + + block = lines[start:end] + remain = lines[:start] + lines[end:] + target2 = next( + ( + i + for i, ln in enumerate(remain) + if re.match(r"^\s*[六六]\s*、\s*参考文件", ln.strip()) or "参考文件" in ln + ), + None, + ) + if target2 is None: + return text + + while block and not block[-1].strip(): + block.pop() + moved = remain[:target2] + [""] + block + [""] + remain[target2:] + return "\n".join(moved) + + +def run( + input_data: str, + context: Context, + dedup_min_repeats: int = 3, + merge_short_line_chars: int = 15, +) -> str: + lines = input_data.splitlines() + cnt = Counter([x.strip() for x in lines if x.strip()]) + + filtered: list[str] = [] + for ln in lines: + s = ln.strip() + if s.startswith("|"): + filtered.append(ln) + continue + if s and len(s) >= 6 and cnt[s] >= dedup_min_repeats: + continue + filtered.append(ln) + + normalized: list[str] = [] + for ln in filtered: + ln = re.sub(r"^\s*\((\d+)\)\s+", r"\1. ", ln) + ln = re.sub(r"^\s*((\d+))\s+", r"\1. ", ln) + ln = re.sub(r"^\s*(\d+)\)\s+", r"\1. ", ln) + normalized.append(ln) + + merged: list[str] = [] + for ln in normalized: + s = ln.strip() + if merged and s and len(s) < merge_short_line_chars: + if ( + not merged[-1].strip().startswith("|") + and not s.startswith("|") + and not s.startswith("![image") + and s + not in { + "目的", + "范围", + "定义", + "职责", + "权责", + "作业内容", + "文件修订履历", + } + ): + merged[-1] = merged[-1].rstrip() + " " + s + continue + merged.append(ln) + + merged = _dedupe_repeated_headers(merged) + merged = _join_cross_page_broken_lines(merged) + + text = "\n".join(merged) + text = _normalize_basic_headings(text) + text = _normalize_doc_meta_lines(text) + text = _dedupe_top_title_lines(text) + text = _normalize_doc_meta_table(text) + text = _remove_page_counter_artifacts(text) + text = _promote_doc_header_line(text) + text = _split_inline_headings(text) + text = _split_inline_section_title(text) + text = _split_numbered_heading_with_body(text) + text = _join_heading_tail_fragments(text) + text = _mark_priority_bullets(text) + text = re.sub(r"\s+([七八]、相关表单)", r"\n\1", text) + text = _normalize_revision_history_table(text) + text = _normalize_revision_history_loose(text) + text = _normalize_shipping_flow_section(text) + text = _normalize_related_forms_table(text) + text = _tighten_numbered_spacing(text) + text = _tighten_alpha_list_spacing(text) + text = _remove_soft_blank_lines(text) + text = re.sub(r"([^\n])文件修订履历", r"\1\n文件修订履历", text) + if context.file_type not in {"ppt", "pptx"}: + text = _relocate_trailing_images(text) + text = _normalize_611_table_columns(text) + text = _normalize_611_merged_cells(text) + text = _relocate_611_before_references(text) + text = _normalize_spaced_numeric_headings(text) + text = _compact_remarks_to_single_line(text) + text = re.sub(r"(\n\d+\.\d+[^\n]*)\n\s*\n(\d+\.\d+\.\d+\s)", r"\1\n\2", text) + text = re.sub(r"\n\s*\n+", "\n\n", text) + text = _relocate_server_612_images(text) + text = _attach_ocr_lines_to_images(text) + text = _relocate_emergency_flow_images(text) + text = _convert_table_like_ocr_blocks(text) + text = _relocate_scoring_tables(text) + text = _format_ocr_blocks_for_display(text) + text = _reorder_structured_ocr_sections(text) + text = _merge_slide_heading_with_short_caption(text) + text = _split_prefixed_slide_intro(text) + text = _dedupe_identical_image_links(text) + return text.strip() + "\n" diff --git a/backend/edkb_system/skills/common.py b/backend/edkb_system/skills/common.py new file mode 100644 index 00000000..97bebaa5 --- /dev/null +++ b/backend/edkb_system/skills/common.py @@ -0,0 +1,244 @@ +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import asdict +from pathlib import Path +from typing import Any + +from edkb_system.contracts import Block + + +def hash_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def hash_file(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as f: + while True: + chunk = f.read(1024 * 1024) + if not chunk: + break + h.update(chunk) + return h.hexdigest() + + +def _page_image_structured_lines(payload: str) -> list[str]: + tokens = [x.strip() for x in payload.split(";") if x.strip()] + if not tokens: + return [] + cert_context_hits = 0 + cert_context_pat = re.compile( + r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|" + r"检测报告|測試報告|材质证明|物性表", + re.IGNORECASE, + ) + for tok in tokens: + if cert_context_pat.search(tok): + cert_context_hits += 1 + if cert_context_hits < 2: + return [] + + def _find(pattern: str) -> str: + rx = re.compile(pattern, re.IGNORECASE) + for tok in tokens: + if rx.search(tok): + return tok + return "" + + def _find_match(pattern: str) -> str: + rx = re.compile(pattern, re.IGNORECASE) + for tok in tokens: + m = rx.search(tok) + if m: + return m.group(0) + return "" + + def _find_after(anchor_pat: str, value_pat: str = r".+") -> str: + anchor_rx = re.compile(anchor_pat, re.IGNORECASE) + value_rx = re.compile(value_pat, re.IGNORECASE) + for idx, tok in enumerate(tokens): + if not anchor_rx.search(tok): + continue + for cand in tokens[idx + 1 : idx + 8]: + if value_rx.search(cand) and not anchor_rx.search(cand): + return cand + return "" + + def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]: + out: list[tuple[str, str]] = [] + seen: set[str] = set() + for key, value in values: + v = value.strip() + if not v: + continue + marker = f"{key}:{v.lower()}" + if marker in seen: + continue + seen.add(marker) + out.append((key, v)) + return out + + certificate_no = "" + cert_anchor = re.compile( + r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE + ) + cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE) + for idx, tok in enumerate(tokens): + if not cert_anchor.search(tok): + continue + for cand in tokens[idx + 1 : idx + 8]: + if re.search(r"fax|tel|date", cand, re.IGNORECASE): + continue + if cert_value.fullmatch(cand): + certificate_no = cand + break + if certificate_no: + break + if not certificate_no: + certificate_no = _find_match( + r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b" + ) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b") + issue_date = _find( + r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}" + ) + spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+") + product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find( + r"HDG[-A-Z0-9 ]*COIL" + ) + customer = _find(r"CORPORATION|COMPANY|STEEL") + order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find( + r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*" + ) + weight = "" + for idx, tok in enumerate(tokens): + if tok.lower() == "kg" and idx > 0: + m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1]) + weight = (m.group(0) if m else tokens[idx - 1]) + " kg" + break + m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE) + if m: + weight = m.group(0) + break + + tensile: list[tuple[str, str]] = [] + for idx, tok in enumerate(tokens): + if tok in {"降伏", "抗拉", "硬度"}: + for cand in tokens[idx + 1 : idx + 4]: + if re.fullmatch(r"\d+(?:\.\d+)?", cand): + tensile.append((tok, cand)) + break + + fields = _uniq( + [ + ("证书编号", certificate_no), + ("日期", issue_date), + ("客户", customer), + ("产品", product), + ("规格", spec), + ("订单/追踪号", order_no), + ("重量", weight), + ] + ) + + if not fields and not tensile: + return [] + + lines = ["## 识别整理版", ""] + for key, value in fields: + lines.append(f"- {key}:{value}") + if tensile: + if fields: + lines.append("") + lines.append("### 关键数值") + lines.append("") + lines.append("| 项目 | 数值 |") + lines.append("| --- | --- |") + for key, value in _uniq(tensile): + lines.append(f"| {key} | {value} |") + lines.extend(["", "## 原始识别结果", ""]) + return lines + + +def blocks_to_plain_markdown(blocks: list[Block]) -> str: + def _ocr_payload(txt: str) -> str: + payload = txt + if payload.startswith("OCR_TEXT:"): + payload = payload[len("OCR_TEXT:") :].strip() + if not payload or payload == "<empty>": + return "" + payload = re.sub(r"(?m)^\s*-\s*", "", payload) + payload = ";".join(x.strip() for x in payload.splitlines() if x.strip()) + return payload + + ocr_by_image: dict[str, str] = {} + for b in blocks: + if b.type != "ocr_text" or not b.id.startswith("ocr-"): + continue + payload = _ocr_payload((b.text or "").strip()) + if payload: + ocr_by_image[b.id[len("ocr-") :]] = payload + + page_text_chars: dict[int, int] = {} + page_body_chars: dict[int, int] = {} + for b in blocks: + if b.type in {"ocr_text", "image"}: + continue + txt = (b.text or "").strip() + if not txt: + continue + page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt) + if b.type != "heading": + page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt) + + lines: list[str] = [] + image_idx = 0 + for b in sorted( + [x for x in blocks if x.type != "ocr_text"], + key=lambda x: (x.page, x.cy(), x.cx()), + ): + txt = (b.text or "").strip() + if not txt and b.type != "image": + continue + if b.type == "heading": + lines.append(f"## {txt}") + elif b.type == "image": + data_uri = b.meta.get("data_uri") if b.meta else None + if data_uri: + image_idx += 1 + if b.meta and b.meta.get("page_image"): + lines.append(f"![page-image-{b.page}]({data_uri})") + else: + lines.append(f"![image-{image_idx}]({data_uri})") + ocr_text = ocr_by_image.get(b.id) + if ocr_text: + suppress_pptx_ocr = bool( + b.meta and b.meta.get("page_image_source") == "pptx" + ) and ( + page_body_chars.get(b.page, 0) >= 15 + or page_text_chars.get(b.page, 0) >= 40 + ) + if ( + b.meta + and b.meta.get("page_image") + and b.meta.get("page_image_source") != "pptx" + ): + lines.extend(_page_image_structured_lines(ocr_text)) + if not suppress_pptx_ocr: + lines.append(f"图中文字:{ocr_text}") + else: + lines.append("![image]") + else: + lines.append(txt) + return "\n\n".join(lines).strip() + "\n" + + +def dump_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") + + +def block_to_dict(block: Block) -> dict[str, Any]: + return asdict(block) diff --git a/backend/edkb_system/skills/doc_to_pdf.py b/backend/edkb_system/skills/doc_to_pdf.py new file mode 100644 index 00000000..2b94c433 --- /dev/null +++ b/backend/edkb_system/skills/doc_to_pdf.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from edkb_system.contracts import Context +from edkb_system.skills.word_bridge import convert_with_word + + +def _find_soffice() -> str | None: + candidates = [ + os.environ.get("EDKB_SOFFICE"), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + for c in candidates: + if not c: + continue + if c == "soffice": + return c + if Path(c).exists(): + return c + return None + + +def _convert_with_word(path: Path, out_dir: Path) -> Path: + output = out_dir / f"{path.stem}.pdf" + return convert_with_word(path.resolve(), output.resolve(), 17) + + +def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path: + output = out_dir / f"{path.stem}.pdf" + cmd = [ + soffice, + "--headless", + "--convert-to", + "pdf", + str(path), + "--outdir", + str(out_dir), + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + stderr = (proc.stderr or "").strip() or "no stderr" + raise RuntimeError( + f"soffice conversion failed (code={proc.returncode}): {stderr}" + ) + if not output.exists(): + raise RuntimeError(f"soffice conversion produced no output: {output}") + return output + + +def run(input_data: dict, context: Context) -> dict: + file_path = Path(input_data["file_path"]) + work_dir = Path(input_data["work_dir"]) + out_dir = work_dir / "flow_pdf" + out_dir.mkdir(parents=True, exist_ok=True) + + errors: list[str] = [] + if os.name == "nt": + try: + pdf = _convert_with_word(file_path, out_dir) + return {"pdf_path": str(pdf), "converter": "word"} + except Exception as exc: + errors.append(f"word: {exc}") + + soffice = _find_soffice() + if soffice: + try: + pdf = _convert_with_soffice(file_path, out_dir, soffice) + return {"pdf_path": str(pdf), "converter": "soffice"} + except Exception as exc: + errors.append(f"soffice: {exc}") + else: + errors.append("soffice: not found") + + context.warnings.append( + "doc->pdf conversion unavailable; fallback to docx text parser" + ) + context.warnings.append("doc->pdf details: " + "; ".join(errors)) + return {"pdf_path": None, "converter": None} diff --git a/backend/edkb_system/skills/export.py b/backend/edkb_system/skills/export.py new file mode 100644 index 00000000..0ee2ea54 --- /dev/null +++ b/backend/edkb_system/skills/export.py @@ -0,0 +1,567 @@ +from __future__ import annotations + +import base64 +import hashlib +import io +import json +import os +import re +import shutil +from dataclasses import asdict, replace +from pathlib import Path +from urllib.parse import quote, urlparse + +from edkb_system.contracts import Block, Chunk, Context + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +_EMBEDDED_IMG_RE = re.compile( + r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)", + re.IGNORECASE | re.DOTALL, +) +_EMBEDDED_IMG_LOOSE_RE = re.compile( + r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)", + re.IGNORECASE | re.DOTALL, +) +_EMBEDDED_IMG_ANY_RE = re.compile( + r"!\[[^\]]*\]\(data:image/.*?\)", + re.IGNORECASE | re.DOTALL, +) + +_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__" +_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__" + + +def _bool_env(name: str, default: bool) -> bool: + raw = os.getenv(name) + if raw is None: + return default + return raw.strip().lower() in {"1", "true", "yes", "on"} + + +def _sanitize_segment(raw: str) -> str: + s = (raw or "").strip() + if not s: + return "untitled" + s = re.sub(r"\s+", "_", s) + s = s.replace("/", "_").replace("\\", "_") + s = re.sub(r"[:*?\"<>|]", "_", s) + s = re.sub(r"_+", "_", s).strip("._") + return s or "untitled" + + +def _build_object_prefix( + source_category: str, source_rel_path: str, source_file: str +) -> str: + rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/") + parts = [p for p in rel.split("/") if p and p not in {".", ".."}] + + category = _sanitize_segment(source_category) + if not category: + if len(parts) >= 2: + category = _sanitize_segment(parts[0]) + else: + category = "uncategorized" + + if parts and _sanitize_segment(parts[0]) == category: + parts = parts[1:] + + if parts: + doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"] + else: + doc_parts = [Path(source_file or "document").stem or "document"] + + normalized = [category] + [_sanitize_segment(p) for p in doc_parts] + normalized = [p for p in normalized if p] + return "/".join(normalized) + + +def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]: + endpoint = (raw_endpoint or "").strip() + secure_default = False + if "://" in endpoint: + parsed = urlparse(endpoint) + secure_default = parsed.scheme.lower() == "https" + endpoint = parsed.netloc or parsed.path + endpoint = endpoint.strip().rstrip("/") + return endpoint, secure_default + + +def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str: + base = (raw_base or "").strip().rstrip("/") + if not base: + scheme = "https" if secure else "http" + return f"{scheme}://{endpoint}".rstrip("/") + if "://" not in base: + scheme = "https" if secure else "http" + return f"{scheme}://{base}".rstrip("/") + return base.rstrip("/") + + +def _quote_object_name(object_name: str) -> str: + return "/".join(quote(seg, safe="") for seg in object_name.split("/")) + + +def _ext_from_blob(blob: bytes) -> str | None: + if blob.startswith(b"\x89PNG\r\n\x1a\n"): + return "png" + if blob.startswith(b"\xff\xd8\xff"): + return "jpg" + if blob.startswith((b"GIF87a", b"GIF89a")): + return "gif" + if blob.startswith(b"BM"): + return "bmp" + if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP": + return "webp" + return None + + +def _normalize_ext(fmt: str, blob: bytes) -> str: + f = (fmt or "").lower().strip() + if f in {"jpeg", "jpg"}: + return "jpg" + if f in {"png", "gif", "bmp", "webp"}: + return f + guessed = _ext_from_blob(blob) + return guessed or "png" + + +def _content_type_for_ext(ext: str) -> str: + if ext == "jpg": + return "image/jpeg" + if ext == "png": + return "image/png" + if ext == "gif": + return "image/gif" + if ext == "bmp": + return "image/bmp" + if ext == "webp": + return "image/webp" + return "application/octet-stream" + + +def _is_valid_image_blob(blob: bytes) -> bool: + if len(blob) < 8: + return False + if _ext_from_blob(blob): + return True + # Unknown format fallback: keep only if not tiny garbage. + return len(blob) >= 64 + + +class _MinioStorage: + def __init__( + self, + *, + endpoint: str, + bucket_name: str, + access_key: str, + secret_key: str, + secure: bool, + public_base: str, + ) -> None: + import importlib + + minio_mod = importlib.import_module("minio") + minio_ctor = getattr(minio_mod, "Minio") + + self.bucket_name = bucket_name + self.public_base = public_base.rstrip("/") + self.client = minio_ctor( + endpoint, + access_key=access_key, + secret_key=secret_key, + secure=secure, + ) + if not self.client.bucket_exists(bucket_name): + self.client.make_bucket(bucket_name) + + def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None: + stream = io.BytesIO(blob) + self.client.put_object( + self.bucket_name, + object_name, + stream, + len(blob), + content_type=content_type, + ) + + def list_prefix(self, prefix: str) -> list[str]: + return [ + obj.object_name + for obj in self.client.list_objects( + self.bucket_name, + prefix=prefix, + recursive=True, + ) + ] + + def remove_object(self, object_name: str) -> None: + self.client.remove_object(self.bucket_name, object_name) + + def build_url(self, object_name: str) -> str: + return ( + f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}" + ) + + +class _RemoteImageRewriter: + def __init__( + self, + *, + context: Context, + source_file: str, + source_rel_path: str, + source_category: str, + ) -> None: + self.context = context + self.source_file = source_file + self.source_rel_path = source_rel_path + self.source_category = source_category + self.object_prefix = _build_object_prefix( + source_category, source_rel_path, source_file + ) + self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False) + + self.storage: _MinioStorage | None = None + self._storage_initialized = False + self.uri_cache: dict[str, str] = {} + self.sha_cache: dict[str, tuple[str, str]] = {} + self.referenced_objects: set[str] = set() + + self.uploaded_count = 0 + self.reused_count = 0 + self.invalid_removed_count = 0 + self.kept_embedded_count = 0 + self.stale_removed_count = 0 + self._upload_error_warn_count = 0 + self._saw_embedded_image = False + self._next_image_index = 1 + + def _build_storage(self) -> _MinioStorage | None: + if not _bool_env("MINIO_UPLOAD_ENABLED", True): + if self.allow_embed_fallback: + self.context.warnings.append( + "image-hosting disabled by MINIO_UPLOAD_ENABLED" + ) + return None + raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED") + + endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000") + endpoint, secure_default = _normalize_endpoint(endpoint_raw) + secure = _bool_env("MINIO_SECURE", secure_default) + + if not endpoint: + if self.allow_embed_fallback: + self.context.warnings.append( + "image-hosting disabled: MINIO_ENDPOINT is empty" + ) + return None + raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty") + + bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service") + access_key = os.getenv("MINIO_ACCESS_KEY", "admin") + secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456") + public_base = _normalize_public_base( + os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure + ) + + try: + return _MinioStorage( + endpoint=endpoint, + bucket_name=bucket_name, + access_key=access_key, + secret_key=secret_key, + secure=secure, + public_base=public_base, + ) + except Exception as exc: + if self.allow_embed_fallback: + self.context.warnings.append( + f"image-hosting unavailable, keep embedded image: {exc}" + ) + return None + raise RuntimeError(f"image-hosting unavailable: {exc}") + + def _warn_upload_error(self, msg: str) -> None: + if self._upload_error_warn_count < 5: + self.context.warnings.append(msg) + self._upload_error_warn_count += 1 + + def _ensure_storage(self) -> None: + if self._storage_initialized: + return + self.storage = self._build_storage() + self._storage_initialized = True + + def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str: + cached = self.uri_cache.get(uri) + if cached is not None: + return cached + + fmt = (fmt or "png").lower() + b64_clean = re.sub(r"\s+", "", b64_raw) + try: + blob = base64.b64decode(b64_clean, validate=False) + except Exception: + self.invalid_removed_count += 1 + self.uri_cache[uri] = _DROP_IMAGE + return _DROP_IMAGE + + if not _is_valid_image_blob(blob): + self.invalid_removed_count += 1 + self.uri_cache[uri] = _DROP_IMAGE + return _DROP_IMAGE + + self._ensure_storage() + if self.storage is None: + if not self.allow_embed_fallback: + raise RuntimeError( + "image-hosting unavailable: embedded fallback is disabled" + ) + self.kept_embedded_count += 1 + self.uri_cache[uri] = _KEEP_IMAGE + return _KEEP_IMAGE + + sha = hashlib.sha256(blob).hexdigest() + cached_sha = self.sha_cache.get(sha) + if cached_sha is not None: + url, object_name = cached_sha + self.referenced_objects.add(object_name) + self.reused_count += 1 + self.uri_cache[uri] = url + return url + + ext = _normalize_ext(fmt, blob) + content_type = _content_type_for_ext(ext) + file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}" + self._next_image_index += 1 + object_name = ( + f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name + ) + + try: + self.storage.put_bytes(object_name, blob, content_type) + url = self.storage.build_url(object_name) + self.sha_cache[sha] = (url, object_name) + self.referenced_objects.add(object_name) + self.uploaded_count += 1 + self.uri_cache[uri] = url + return url + except Exception as exc: + if not self.allow_embed_fallback: + raise RuntimeError( + f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})" + ) from exc + self.kept_embedded_count += 1 + self.uri_cache[uri] = _KEEP_IMAGE + self._warn_upload_error( + f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})" + ) + return _KEEP_IMAGE + + def _process_match(self, m: re.Match[str]) -> str: + return self._process_embedded_uri( + m.group("uri"), + m.group("fmt") or "png", + m.group("b64") or "", + ) + + def _process_loose_uri(self, uri: str) -> str: + cached = self.uri_cache.get(uri) + if cached is not None: + return cached + + head, sep, b64_raw = uri.partition(",") + if not sep: + self.invalid_removed_count += 1 + self.uri_cache[uri] = _DROP_IMAGE + return _DROP_IMAGE + + fmt = "png" + m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE) + if m: + fmt = (m.group("fmt") or "png").lower() + + return self._process_embedded_uri(uri, fmt, b64_raw) + + def replace_text(self, text: str) -> str: + if not text or "data:image/" not in text: + return text + self._saw_embedded_image = True + + def repl(m: re.Match[str]) -> str: + alt = m.group("alt") or "image" + decision = self._process_match(m) + if decision == _DROP_IMAGE: + return "" + if decision == _KEEP_IMAGE: + return m.group(0) + return f"![{alt}]({decision})" + + out = _EMBEDDED_IMG_RE.sub(repl, text) + if "data:image/" in out: + + def loose_repl(m: re.Match[str]) -> str: + alt = m.group("alt") or "image" + decision = self._process_loose_uri(m.group("uri") or "") + if decision == _DROP_IMAGE: + return "" + if decision == _KEEP_IMAGE: + return m.group(0) + return f"![{alt}]({decision})" + + out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out) + if not self.allow_embed_fallback and "data:image/" in out: + dropped_before = self.invalid_removed_count + out = _EMBEDDED_IMG_LOOSE_RE.sub("", out) + out = _EMBEDDED_IMG_ANY_RE.sub("", out) + removed = self.invalid_removed_count - dropped_before + if "data:image/" in out: + self.context.warnings.append( + "image-hosting left non-markdown data:image content; kept as-is" + ) + else: + self.context.warnings.append( + "image-hosting removed unsupported embedded images" + + (f": {removed}" if removed > 0 else "") + ) + out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out) + return out + + def finalize(self) -> None: + if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True): + self._ensure_storage() + + if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True): + prefix = f"{self.object_prefix}/" + try: + for object_name in self.storage.list_prefix(prefix): + if object_name in self.referenced_objects: + continue + self.storage.remove_object(object_name) + self.stale_removed_count += 1 + except Exception as exc: + self.context.warnings.append( + f"image-hosting cleanup failed ({self.source_file}): {exc}" + ) + + if self.invalid_removed_count > 0: + self.context.warnings.append( + f"image-hosting removed invalid images: {self.invalid_removed_count}" + ) + + if self.kept_embedded_count > 0 and self.storage is None: + self.context.warnings.append( + "image-hosting unavailable: keep legacy data:image embeds" + ) + + if ( + self.uploaded_count > 0 + or self.reused_count > 0 + or self.stale_removed_count > 0 + ): + self.context.warnings.append( + "image-hosting synced " + f"(uploaded={self.uploaded_count}, reused={self.reused_count}, " + f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})" + ) + + +def run(input_data: dict, context: Context) -> dict: + out_dir = Path(input_data["out_dir"]) + out_dir.mkdir(parents=True, exist_ok=True) + source_file = input_data.get("source_file", "") + source_rel_path = input_data.get("source_rel_path", source_file) + source_category = input_data.get("source_category", "") + source_stem = Path(source_file).stem if source_file else out_dir.name + flat_clean_path = Path( + input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md") + ) + view_clean_path = out_dir / "03_clean_view.md" + view_images_dir = out_dir / "images_view" + + for p in [ + out_dir / "01_raw_layout.json", + out_dir / "02_flow_procedure.md", + out_dir / "03_clean.md", + out_dir / "04_chunks.jsonl", + out_dir / "report.md", + view_clean_path, + flat_clean_path, + ]: + if p.exists(): + p.unlink() + chunks_dir = out_dir / "chunks" + if chunks_dir.exists(): + shutil.rmtree(chunks_dir) + if view_images_dir.exists(): + shutil.rmtree(view_images_dir) + + clean_md: str = input_data.get("clean_md", "") + chunks: list[Chunk] = input_data.get("chunks", []) + blocks: list[Block] = input_data.get("blocks", []) + flow_markdowns: list[str] = input_data.get("flow_markdowns", []) + + rewriter = _RemoteImageRewriter( + context=context, + source_file=source_file, + source_rel_path=source_rel_path, + source_category=source_category, + ) + + clean_md = rewriter.replace_text(clean_md) + exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks] + rewriter.finalize() + + _write(out_dir / "03_clean.md", clean_md) + _write(flat_clean_path, clean_md) + + lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks] + _write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else "")) + + chunks_dir.mkdir(parents=True, exist_ok=True) + for c in exported_chunks: + _write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n") + + if flow_markdowns: + _write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n") + + _write( + out_dir / "01_raw_layout.json", + json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n", + ) + + report_lines = [ + f"# Report: {input_data.get('source_file', '')}", + "", + f"- pages: {context.pages}", + f"- images: {context.images}", + f"- ocr_characters: {context.ocr_characters}", + f"- flows_detected: {context.flows_detected}", + f"- confidence: {context.confidence:.2f}", + "", + "## warnings", + ] + if context.warnings: + report_lines.extend([f"- {w}" for w in context.warnings]) + else: + report_lines.append("- none") + + report_lines.extend( + [ + "", + "## recommended_dify_settings", + "- Index: High Quality", + "- Retrieval: Hybrid", + "- Chunking: General", + "", + ] + ) + _write(out_dir / "report.md", "\n".join(report_lines)) + + return {"out_dir": str(out_dir)} diff --git a/backend/edkb_system/skills/flow_reconstruct.py b/backend/edkb_system/skills/flow_reconstruct.py new file mode 100644 index 00000000..745dbf0b --- /dev/null +++ b/backend/edkb_system/skills/flow_reconstruct.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import networkx as nx + +from edkb_system.contracts import Block, Context + + +@dataclass +class Node: + id: str + text: str + page: int + kind: str + bbox: tuple[float, float, float, float] + + +def _is_decision(text: str) -> bool: + kws = ["判定", "判断", "是否", "if", "check"] + s = text.lower() + return any(k in s for k in kws) + + +def _dist(a: Node, b: Node) -> float: + ax = (a.bbox[0] + a.bbox[2]) / 2.0 + ay = (a.bbox[1] + a.bbox[3]) / 2.0 + bx = (b.bbox[0] + b.bbox[2]) / 2.0 + by = (b.bbox[1] + b.bbox[3]) / 2.0 + return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5 + + +def run(input_data: list[Block], context: Context) -> dict: + blocks = [ + b + for b in input_data + if b.type in {"textbox", "shape", "diamond", "arrow_label", "paragraph"} + and b.text.strip() + ] + by_page: dict[int, list[Block]] = {} + for b in blocks: + by_page.setdefault(b.page, []).append(b) + + page_markdowns: list[str] = [] + debug: list[dict] = [] + + for page in sorted(by_page): + cands = by_page[page] + nodes: list[Node] = [] + labels: list[Node] = [] + for b in cands: + text = b.text.strip() + if b.type == "arrow_label" or text.upper() in { + "NG", + "OK", + "Y", + "N", + "YES", + "NO", + }: + labels.append(Node(b.id, text, b.page, "label", b.bbox)) + continue + kind = "decision" if (_is_decision(text) or b.type == "diamond") else "step" + nodes.append(Node(b.id, text, b.page, kind, b.bbox)) + nodes = sorted( + nodes, + key=lambda n: ( + (n.bbox[1] + n.bbox[3]) / 2.0, + (n.bbox[0] + n.bbox[2]) / 2.0, + ), + ) + if not nodes: + continue + + g = nx.DiGraph() + for n in nodes: + g.add_node(n.id, node=n) + + for i, src in enumerate(nodes[:-1]): + dst = nodes[i + 1] + g.add_edge(src.id, dst.id, label=None) + + for dec in [n for n in nodes if n.kind == "decision"]: + right_steps = [ + n + for n in nodes + if ((n.bbox[0] + n.bbox[2]) / 2.0) > ((dec.bbox[0] + dec.bbox[2]) / 2.0) + ] + if right_steps: + target = min(right_steps, key=lambda x: _dist(dec, x)) + label_node = None + right_labels = [ + l + for l in labels + if ((l.bbox[0] + l.bbox[2]) / 2.0) + > ((dec.bbox[0] + dec.bbox[2]) / 2.0) + ] + if right_labels: + label_node = min(right_labels, key=lambda x: _dist(dec, x)) + g.add_edge( + dec.id, target.id, label=(label_node.text if label_node else "分支") + ) + + ordered = nodes + idx_map = {n.id: i + 1 for i, n in enumerate(ordered)} + cycles = list(nx.simple_cycles(g)) + cyc_nodes = {nid for cyc in cycles for nid in cyc} + + lines = [f"## Page {page} Procedure"] + for n in ordered: + title = n.text + if n.kind == "decision" and not title.startswith("判定"): + title = f"判定:{title}" + lines.append(f"{idx_map[n.id]}. {title}") + if n.kind == "decision": + for _, dst, data in g.out_edges(n.id, data=True): + if data.get("label") is None: + continue + label = data.get("label") or "分支" + if dst in cyc_nodes: + lines.append(f"- {label} -> 返回到步骤{idx_map.get(dst, '?')}") + else: + dst_text = g.nodes[dst]["node"].text + lines.append(f"- {label} -> {dst_text}") + + page_markdowns.append("\n".join(lines)) + debug.append( + { + "page": page, + "nodes": [ + {"id": n.id, "text": n.text, "kind": n.kind, "bbox": list(n.bbox)} + for n in nodes + ], + "edges": [ + {"src": s, "dst": d, "label": data.get("label")} + for s, d, data in g.edges(data=True) + ], + } + ) + + context.flows_detected = len(page_markdowns) + return {"flow_markdowns": page_markdowns, "debug": debug} diff --git a/backend/edkb_system/skills/intake_router.py b/backend/edkb_system/skills/intake_router.py new file mode 100644 index 00000000..c32b274f --- /dev/null +++ b/backend/edkb_system/skills/intake_router.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import re +import zipfile +from pathlib import Path + +from edkb_system.config import RouterConfig +from edkb_system.contracts import Context, DocumentProfile + + +_DOC_KIND_STRATEGY = { + "flow_procedure": { + "enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + "disable": set(), + }, + "policy_text": { + "enable": set(), + "disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + }, + "tabular_record": { + "enable": set(), + "disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + }, + "mixed": { + "enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + "disable": set(), + }, +} + + +def _keyword_score(name: str, keywords: dict[str, float]) -> float: + score = 0.0 + for k, w in keywords.items(): + if k in name: + score += w + return score + + +def _score_text_keywords(text: str, keywords: dict[str, float]) -> float: + score = 0.0 + for k, w in keywords.items(): + if k in text: + score += w + return score + + +def _has_flow_evidence(stem: str, content: dict) -> bool: + name = stem.lower() + strong_name_hit = any( + k in name for k in ["流程", "流程图", "判定", "作业标准", "检验作业"] + ) + flow_hits = int(content.get("flow_hits", 0) or 0) + shape_hits = int(content.get("shape_hits", 0) or 0) + if flow_hits >= 6: + return True + if flow_hits >= 3 and shape_hits >= 1: + return True + return strong_name_hit + + +def _probe_docx_xml(path: Path) -> dict: + signals = { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + try: + with zipfile.ZipFile(path) as zf: + xml_parts = [ + n for n in zf.namelist() if n.startswith("word/") and n.endswith(".xml") + ] + xml_blob = "" + for n in xml_parts[:12]: + try: + xml_blob += zf.read(n).decode("utf-8", errors="ignore") + except Exception: + continue + except Exception: + return signals + + if not xml_blob: + return signals + + text = xml_blob.lower() + signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text)) + signals["table_hits"] = text.count("<w:tbl") + signals["image_hits"] = text.count("<a:blip") + text.count("<v:imagedata") + signals["shape_hits"] = ( + text.count("<w:drawing") + text.count("<v:shape") + text.count("<wps:wsp") + ) + flow_kw = { + "流程": 0.3, + "流程图": 0.4, + "判定": 0.25, + "检验": 0.2, + "作业": 0.15, + } + signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10) + return signals + + +def _probe_pdf(path: Path) -> dict: + signals = { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + try: + blob = path.read_bytes()[: 2 * 1024 * 1024] + except Exception: + return signals + + text = blob.decode("latin-1", errors="ignore") + signals["image_hits"] = text.count("/Subtype /Image") + text.count("/Image") + text_ops = text.count(" BT") + text.count(" ET") + signals["has_text"] = text_ops >= 10 + return signals + + +def _probe_pptx(path: Path) -> dict: + signals = { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + try: + with zipfile.ZipFile(path) as zf: + xml_parts = [ + n + for n in zf.namelist() + if n.startswith("ppt/slides/") and n.endswith(".xml") + ] + xml_blob = "" + for n in xml_parts[:20]: + try: + xml_blob += zf.read(n).decode("utf-8", errors="ignore") + except Exception: + continue + except Exception: + return signals + + if not xml_blob: + return signals + text = xml_blob.lower() + signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text)) + signals["table_hits"] = text.count("<a:tbl") + signals["image_hits"] = text.count("<a:blip") + signals["shape_hits"] = text.count("<p:sp") + text.count("<p:cxnsp") + flow_kw = {"流程": 0.4, "流程图": 0.5, "送样": 0.3, "承认": 0.3, "判定": 0.25} + signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10) + return signals + + +def _probe_content(file_path: Path, ext: str) -> dict: + if ext == ".docx": + return _probe_docx_xml(file_path) + if ext == ".doc": + cache_docx = file_path.parents[1] / "cache" / f"{file_path.stem}.docx" + if cache_docx.exists(): + return _probe_docx_xml(cache_docx) + return { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + if ext == ".pdf": + return _probe_pdf(file_path) + if ext == ".pptx": + return _probe_pptx(file_path) + if ext == ".ppt": + cache_pptx = file_path.parents[1] / "cache" / f"{file_path.stem}.pptx" + if cache_pptx.exists(): + return _probe_pptx(cache_pptx) + return { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + if ext in {".xls", ".xlsx", ".csv"}: + return { + "has_text": True, + "table_hits": 8, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + return { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + + +def _build_pipeline( + ext: str, + doc_kind: str, + scan_likelihood: float, + cfg: RouterConfig, +) -> list[str]: + strategy = _DOC_KIND_STRATEGY.get(doc_kind, _DOC_KIND_STRATEGY["mixed"]) + enable = set(strategy["enable"]) + disable = set(strategy["disable"]) + + pipeline: list[str] = [] + if ext in {".doc", ".docx"}: + pipeline.append("edkb-loader-docx") + if "edkb-doc-to-pdf" in enable and "edkb-doc-to-pdf" not in disable: + pipeline.append("edkb-doc-to-pdf") + elif ext == ".pdf": + pipeline.append("edkb-loader-pdf") + elif ext in {".ppt", ".pptx"}: + pipeline.append("edkb-loader-pptx") + elif ext in {".xls", ".xlsx"}: + pipeline.extend(["edkb-loader-excel", "edkb-table-linearize"]) + elif ext == ".csv": + pipeline.extend(["edkb-loader-csv", "edkb-table-linearize"]) + + if ext in {".doc", ".docx", ".pdf", ".ppt", ".pptx"}: + if scan_likelihood >= cfg.scan_likelihood_threshold: + pipeline.append("edkb-ocr") + if "edkb-flow-reconstruct" in enable and "edkb-flow-reconstruct" not in disable: + pipeline.append("edkb-flow-reconstruct") + + pipeline.extend( + [ + "edkb-clean", + "edkb-chunk", + "edkb-quality-gate", + "edkb-export", + "edkb-postcheck", + ] + ) + return pipeline + + +def _decide_doc_kind( + stem: str, ext: str, content: dict +) -> tuple[str, float, float, float, list[str]]: + s = stem.lower() + reasons: list[str] = [] + + flow_pos = { + "流程图": 0.5, + "作业流程": 0.45, + "流程": 0.25, + "检验": 0.25, + "作业标准": 0.35, + "sop": 0.35, + "判定": 0.2, + "oqc": 0.2, + "iqc": 0.2, + } + flow_neg = { + "管理办法": 0.35, + "制度": 0.3, + "守则": 0.3, + "规定": 0.25, + "手册": 0.2, + } + table_pos = { + "台账": 0.45, + "清单": 0.35, + "记录": 0.25, + "表单": 0.4, + "excel": 0.4, + } + + flow_raw = 0.35 + _keyword_score(s, flow_pos) - _keyword_score(s, flow_neg) + table_raw = 0.15 + _keyword_score(s, table_pos) + + if ext in {".xls", ".xlsx", ".csv"}: + table_raw += 0.55 + if ext == ".pdf": + flow_raw += 0.05 + if ext in {".ppt", ".pptx"}: + flow_raw += 0.1 + + flow_raw += min(0.45, 0.04 * content.get("flow_hits", 0)) + flow_raw += min(0.25, 0.02 * content.get("shape_hits", 0)) + table_raw += min(0.55, 0.08 * content.get("table_hits", 0)) + if content.get("image_hits", 0) >= 2 and ext in { + ".doc", + ".docx", + ".pdf", + ".ppt", + ".pptx", + }: + flow_raw += 0.05 + + flow_likelihood = max(0.05, min(0.95, flow_raw)) + table_likelihood = max(0.05, min(0.95, table_raw)) + text_density = 0.55 + flow_evidence = _has_flow_evidence(stem, content) + + if not flow_evidence: + flow_likelihood = min(flow_likelihood, 0.59) + if content.get("table_hits", 0) >= 1: + table_likelihood = max(table_likelihood, 0.65) + + if ( + flow_evidence + and flow_likelihood >= 0.65 + and (table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1) + ): + doc_kind = "mixed" + reasons.append("content indicates mixed flow+table document") + elif table_likelihood >= 0.75 and (flow_likelihood < 0.6 or not flow_evidence): + doc_kind = "tabular_record" + reasons.append("content indicates table-like document") + elif not flow_evidence and ( + table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1 + ): + doc_kind = "tabular_record" + reasons.append("content indicates text+table document without flow") + elif flow_evidence and flow_likelihood >= 0.65: + doc_kind = "flow_procedure" + reasons.append("content indicates flow/procedure document") + elif flow_likelihood <= 0.35 or not flow_evidence: + doc_kind = "policy_text" + reasons.append("content indicates policy/management text") + else: + doc_kind = "mixed" + reasons.append("content indicates mixed document") + + return doc_kind, flow_likelihood, table_likelihood, text_density, reasons + + +def _derive_content_modes( + ext: str, + stem: str, + content: dict, + flow_likelihood: float, + table_likelihood: float, +) -> list[str]: + modes: set[str] = set() + if content.get("has_text") or ext in { + ".doc", + ".docx", + ".pdf", + ".ppt", + ".pptx", + ".xls", + ".xlsx", + ".csv", + }: + modes.add("text") + if content.get("image_hits", 0) > 0: + modes.add("image") + if table_likelihood >= 0.65 or content.get("table_hits", 0) >= 1: + modes.add("table") + if _has_flow_evidence(stem, content) and flow_likelihood >= 0.6: + modes.add("flow") + return sorted(modes) + + +def run(input_data: dict, context: Context, cfg: RouterConfig) -> DocumentProfile: + file_path = Path(input_data["file_path"]) + ext = file_path.suffix.lower() + file_type = ext.lstrip(".") + + size = file_path.stat().st_size if file_path.exists() else 0 + has_tables = ext in {".xls", ".xlsx", ".csv"} + content_signals = _probe_content(file_path, ext) + doc_kind, flow_likelihood, table_likelihood, text_density, reasons = ( + _decide_doc_kind(file_path.stem, ext, content_signals) + ) + content_modes = _derive_content_modes( + ext, file_path.stem, content_signals, flow_likelihood, table_likelihood + ) + + scan_likelihood = 0.2 + if ext == ".pdf" and size > 3 * 1024 * 1024: + scan_likelihood = 0.65 + + has_images = ext in {".pdf", ".doc", ".docx", ".ppt", ".pptx"} + + pipeline = _build_pipeline(ext, doc_kind, scan_likelihood, cfg) + + context.file_type = file_type + context.extras["intake"] = { + "doc_kind": doc_kind, + "content_modes": content_modes, + "route_reasons": reasons, + "strategy": { + "enable": sorted(_DOC_KIND_STRATEGY.get(doc_kind, {}).get("enable", set())), + "disable": sorted( + _DOC_KIND_STRATEGY.get(doc_kind, {}).get("disable", set()) + ), + }, + "content_signals": content_signals, + "flow_likelihood": round(flow_likelihood, 3), + "table_likelihood": round(table_likelihood, 3), + "scan_likelihood": round(scan_likelihood, 3), + "pipeline": pipeline, + } + + return DocumentProfile( + file_type=file_type, + text_density=text_density, + has_images=has_images, + has_tables=has_tables, + flow_likelihood=flow_likelihood, + scan_likelihood=scan_likelihood, + table_likelihood=table_likelihood, + language_hint="zh", + recommended_pipeline=pipeline, + ) diff --git a/backend/edkb_system/skills/loader_csv.py b/backend/edkb_system/skills/loader_csv.py new file mode 100644 index 00000000..300dec4a --- /dev/null +++ b/backend/edkb_system/skills/loader_csv.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import csv +from pathlib import Path + +from edkb_system.contracts import Context + + +def run(input_data: dict, context: Context) -> dict: + file_path = Path(input_data["file_path"]) + raw = None + for enc in ("utf-8-sig", "utf-8", "gb18030"): + try: + raw = file_path.read_text(encoding=enc) + break + except UnicodeDecodeError: + continue + if raw is None: + raw = file_path.read_text(errors="ignore") + + sample = raw[:4096] + try: + dialect = csv.Sniffer().sniff(sample, delimiters=",;\t") + delim = dialect.delimiter + except Exception: + delim = "," + + rows = [ + r + for r in csv.reader(raw.splitlines(), delimiter=delim) + if any(c.strip() for c in r) + ] + table = { + "sheet": "csv", + "headers": rows[0] if rows else [], + "rows": rows[1:] if len(rows) > 1 else [], + } + context.extras["tables_count"] = 1 + return table diff --git a/backend/edkb_system/skills/loader_docx.py b/backend/edkb_system/skills/loader_docx.py new file mode 100644 index 00000000..d9f59133 --- /dev/null +++ b/backend/edkb_system/skills/loader_docx.py @@ -0,0 +1,1962 @@ +from __future__ import annotations + +import base64 +import hashlib +import io +import struct +import mimetypes +import os +import re +import shutil +import subprocess +import zipfile +import xml.etree.ElementTree as ET +from pathlib import Path + +from edkb_system.contracts import Block, Context +from edkb_system.skills.word_bridge import convert_with_word + + +def _to_data_uri(blob: bytes, content_type: str | None = None) -> str: + ct = content_type or "image/png" + b64 = base64.b64encode(blob).decode("ascii") + return f"data:{ct};base64,{b64}" + + +def _to_preferred_image_data_uri(blob: bytes, content_type: str | None = None) -> str: + try: + from PIL import Image + + with Image.open(io.BytesIO(blob)) as im: + rgb = Image.new("RGB", im.size, (255, 255, 255)) + rgba = im.convert("RGBA") + rgb.paste(rgba, mask=rgba.split()[3]) + out = io.BytesIO() + rgb.save(out, format="JPEG", quality=90) + return _to_data_uri(out.getvalue(), "image/jpeg") + except Exception: + return _to_data_uri(blob, content_type) + + +def _image_dimensions(blob: bytes, ext: str) -> tuple[int, int]: + e = (ext or "").lower().lstrip(".") + if e == "png" and len(blob) >= 24 and blob.startswith(b"\x89PNG"): + return int.from_bytes(blob[16:20], "big"), int.from_bytes(blob[20:24], "big") + if e in {"jpg", "jpeg"} and blob.startswith(b"\xff\xd8"): + i = 2 + n = len(blob) + while i + 9 < n: + if blob[i] != 0xFF: + i += 1 + continue + marker = blob[i + 1] + if marker in {0xC0, 0xC2}: + h = struct.unpack(">H", blob[i + 5 : i + 7])[0] + w = struct.unpack(">H", blob[i + 7 : i + 9])[0] + return w, h + if i + 4 > n: + break + seg_len = struct.unpack(">H", blob[i + 2 : i + 4])[0] + if seg_len <= 2: + break + i += 2 + seg_len + return 0, 0 + + +def _is_sparse_line_artifact(blob: bytes, ext: str) -> bool: + e = (ext or "").lower().lstrip(".") + if e not in {"png", "jpg", "jpeg"}: + return False + + try: + from PIL import Image + import numpy as np + + with Image.open(io.BytesIO(blob)) as im: + g = im.convert("L") + w, h = g.size + if w <= 0 or h <= 0 or (w * h) < 60000: + return False + + hist = g.histogram() + total = max(w * h, 1) + dominant_ratio = max(hist) / total + uniq = sum(1 for c in hist if c) + if dominant_ratio < 0.99 or uniq > 3: + return False + + if max(w, h) > 1200: + scale = max(w, h) / 1200.0 + nw = max(1, int(w / scale)) + nh = max(1, int(h / scale)) + g = g.resize((nw, nh)) + + a = np.asarray(g, dtype=np.int16) + gx = np.abs(np.diff(a, axis=1)) + gy = np.abs(np.diff(a, axis=0)) + edge_ratio = (np.count_nonzero(gx > 12) + np.count_nonzero(gy > 12)) / max( + a.shape[0] * a.shape[1], 1 + ) + return edge_ratio < 0.02 + except Exception: + return False + + +def _split_tall_image(blob: bytes, ext: str) -> list[bytes]: + e = (ext or "").lower().lstrip(".") + if e not in {"png", "jpg", "jpeg"}: + return [blob] + try: + from PIL import Image + + with Image.open(io.BytesIO(blob)) as im: + w, h = im.size + if w <= 0 or h <= 0 or (h / max(w, 1)) < 1.8: + return [blob] + + g = im.convert("L") + + def _pix(x: int, y: int) -> int: + v = g.getpixel((x, y)) + if isinstance(v, tuple): + return int(v[0]) + return int(v if v is not None else 255) + + corners = [ + _pix(0, 0), + _pix(w - 1, 0), + _pix(0, h - 1), + _pix(w - 1, h - 1), + ] + bg = sorted(corners)[len(corners) // 2] + + row_content: list[float] = [] + for y in range(h): + hist = g.crop((0, y, w, y + 1)).histogram() + near_bg = 0 + lo_bg = max(0, bg - 8) + hi_bg = min(255, bg + 8) + for i in range(lo_bg, hi_bg + 1): + near_bg += hist[i] + row_content.append((w - near_bg) / max(w, 1)) + + lo = int(h * 0.30) + hi = int(h * 0.80) + if hi <= lo: + return [blob] + + best_len = 0 + best_mid = None + cur_start = None + for y in range(lo, hi): + if row_content[y] < 0.03: + if cur_start is None: + cur_start = y + else: + if cur_start is not None: + ln = y - cur_start + if ln > best_len: + best_len = ln + best_mid = (cur_start + y) // 2 + cur_start = None + if cur_start is not None: + ln = hi - cur_start + if ln > best_len: + best_len = ln + best_mid = (cur_start + hi) // 2 + + if best_mid is None or best_len < 10: + return [blob] + cut = best_mid + + def _row_non_bg(y: int) -> int: + hist = g.crop((0, y, w, y + 1)).histogram() + near_bg = 0 + lo_bg = max(0, bg - 8) + hi_bg = min(255, bg + 8) + for i in range(lo_bg, hi_bg + 1): + near_bg += hist[i] + return w - near_bg + + top_end = cut + for y in range(max(0, cut - 60), min(h, cut + 1)): + if _row_non_bg(y) > 2: + top_end = y + top_end = min(h, top_end + 6) + + bot_start = cut + for y in range(cut, min(h, cut + 80)): + if _row_non_bg(y) > 2: + bot_start = y + break + bot_start = max(0, bot_start - 6) + + if bot_start <= top_end: + top = im.crop((0, 0, w, max(1, cut))) + bot = im.crop((0, min(h - 1, cut), w, h)) + else: + top = im.crop((0, 0, w, max(1, top_end))) + bot = im.crop((0, min(h - 1, bot_start), w, h)) + + out: list[bytes] = [] + for part in [top, bot]: + b = io.BytesIO() + part.save(b, format="PNG") + out.append(b.getvalue()) + return out if len(out) == 2 else [blob] + except Exception: + return [blob] + + +def _extract_image_uris_from_paragraph(para, doc) -> list[str]: + uris: list[str] = [] + try: + rids = para._element.xpath(".//a:blip/@r:embed") + except Exception: + return uris + for rid in rids: + try: + part = doc.part.related_parts[rid] + blob = part.blob + content_type = getattr(part, "content_type", None) + uris.append(_to_preferred_image_data_uri(blob, content_type)) + except Exception: + continue + return uris + + +def _extract_all_image_uris_from_doc(doc) -> list[str]: + uris: list[str] = [] + seen: set[str] = set() + rel_items = list(doc.part.rels.items()) + rel_items.sort( + key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0) + if (kv[0] or "").startswith("rId") + else 0 + ) + for _, rel in rel_items: + reltype = getattr(rel, "reltype", "") or "" + if "image" not in reltype: + continue + try: + part = rel.target_part + blob = part.blob + content_type = getattr(part, "content_type", None) + uri = _to_preferred_image_data_uri(blob, content_type) + key = hashlib.sha1(blob).hexdigest() + if key in seen: + continue + seen.add(key) + uris.append(uri) + except Exception: + continue + return uris + + +def _extract_image_uris_from_table(table, doc) -> list[str]: + uris: list[str] = [] + seen: set[str] = set() + try: + for row in table.rows: + for cell in row.cells: + for para in cell.paragraphs: + for uri in _extract_image_uris_from_paragraph(para, doc): + if uri in seen: + continue + seen.add(uri) + uris.append(uri) + except Exception: + return uris + return uris + + +def _load_numbering_schema( + docx_path: Path, +) -> tuple[dict[str, str], dict[tuple[str, int], dict]]: + ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"} + num_to_abs: dict[str, str] = {} + levels: dict[tuple[str, int], dict] = {} + try: + with zipfile.ZipFile(docx_path) as zf: + xml = zf.read("word/numbering.xml") + root = ET.fromstring(xml) + except Exception: + return num_to_abs, levels + + for num in root.findall("w:num", ns): + nid = num.attrib.get("{%s}numId" % ns["w"]) + aid_elem = num.find("w:abstractNumId", ns) + aid = aid_elem.attrib.get("{%s}val" % ns["w"]) if aid_elem is not None else None + if nid and aid: + num_to_abs[nid] = aid + + for absn in root.findall("w:abstractNum", ns): + aid = absn.attrib.get("{%s}abstractNumId" % ns["w"]) + if not aid: + continue + for lvl in absn.findall("w:lvl", ns): + ilvl_s = lvl.attrib.get("{%s}ilvl" % ns["w"], "0") + try: + ilvl = int(ilvl_s) + except Exception: + ilvl = 0 + fmt_elem = lvl.find("w:numFmt", ns) + txt_elem = lvl.find("w:lvlText", ns) + start_elem = lvl.find("w:start", ns) + num_fmt = ( + fmt_elem.attrib.get("{%s}val" % ns["w"], "decimal") + if fmt_elem is not None + else "decimal" + ) + lvl_text = ( + txt_elem.attrib.get("{%s}val" % ns["w"], f"%{ilvl + 1}") + if txt_elem is not None + else f"%{ilvl + 1}" + ) + start = ( + int(start_elem.attrib.get("{%s}val" % ns["w"], "1")) + if start_elem is not None + else 1 + ) + levels[(aid, ilvl)] = { + "num_fmt": num_fmt, + "lvl_text": lvl_text, + "start": start, + } + + return num_to_abs, levels + + +def _to_roman(n: int) -> str: + vals = [ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ] + out = [] + x = max(1, n) + for v, s in vals: + while x >= v: + out.append(s) + x -= v + return "".join(out) + + +def _to_chinese_num(n: int) -> str: + digits = "零一二三四五六七八九" + if n <= 0: + return str(n) + if n < 10: + return digits[n] + if n < 20: + return "十" + (digits[n % 10] if n % 10 else "") + if n < 100: + tens, ones = divmod(n, 10) + return digits[tens] + "十" + (digits[ones] if ones else "") + return str(n) + + +def _format_counter(n: int, fmt: str) -> str: + f = (fmt or "decimal").lower() + if f in {"decimal", "decimalzero"}: + return str(n) + if f == "lowerletter": + return chr(ord("a") + max(0, (n - 1) % 26)) + if f == "upperletter": + return chr(ord("A") + max(0, (n - 1) % 26)) + if f == "lowerroman": + return _to_roman(n).lower() + if f == "upperroman": + return _to_roman(n) + if "chinese" in f: + return _to_chinese_num(n) + if f == "bullet": + return "•" + return str(n) + + +def _next_list_marker( + num_id: str, + ilvl: int, + num_to_abs: dict[str, str], + levels: dict[tuple[str, int], dict], + states: dict[str, dict[int, int]], +) -> str: + abs_id = num_to_abs.get(str(num_id)) + if not abs_id: + return "" + lvl_cfg = levels.get( + (abs_id, ilvl), {"num_fmt": "decimal", "lvl_text": f"%{ilvl + 1}", "start": 1} + ) + state = states.setdefault(str(num_id), {}) + + for k in list(state.keys()): + if k > ilvl: + state.pop(k, None) + + for lv in range(ilvl): + if lv not in state: + state[lv] = int(levels.get((abs_id, lv), {}).get("start", 1)) + + start = int(lvl_cfg.get("start", 1)) + if ilvl not in state: + state[ilvl] = start - 1 + state[ilvl] += 1 + + if (lvl_cfg.get("num_fmt") or "").lower() == "bullet": + return "•" + + tmpl = str(lvl_cfg.get("lvl_text") or f"%{ilvl + 1}") + for n in range(1, 10): + token = f"%{n}" + if token not in tmpl: + continue + lv = n - 1 + val = state.get(lv, int(levels.get((abs_id, lv), {}).get("start", 1))) + fmt = str(levels.get((abs_id, lv), {}).get("num_fmt", "decimal")) + tmpl = tmpl.replace(token, _format_counter(val, fmt)) + + if any(ord(c) >= 0xF000 for c in tmpl): + return "•" + return tmpl.strip() + + +_WORD_EXPORT_IMAGE_NAME_RE = re.compile( + r"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", re.IGNORECASE +) + + +def _word_export_source_stem_from_html(html_path: Path) -> str: + suffix = ".word_export.html" + name = html_path.name + if name.lower().endswith(suffix): + return name[: -len(suffix)] + return html_path.stem + + +def _word_export_candidate_dirs(source_stem: str, out_dir: Path) -> list[Path]: + candidate_dirs: list[Path] = [] + for d in [ + out_dir / f"{source_stem}.word_export_files", + out_dir / f"{source_stem}.word_export.files", + ]: + if d.exists() and d.is_dir(): + candidate_dirs.append(d) + for d in sorted(out_dir.glob(f"{source_stem}.word_export*")): + if d.exists() and d.is_dir() and d not in candidate_dirs: + candidate_dirs.append(d) + return candidate_dirs + + +def _collect_word_export_image_files( + source_stem: str, out_dir: Path +) -> dict[str, Path]: + files_by_name: dict[str, Path] = {} + for d in _word_export_candidate_dirs(source_stem, out_dir): + for p in sorted(d.glob("*")): + if not p.is_file(): + continue + if p.suffix.lower() not in { + ".png", + ".jpg", + ".jpeg", + ".gif", + ".bmp", + ".webp", + }: + continue + files_by_name.setdefault(p.name.lower(), p) + return files_by_name + + +def _image_file_to_uris(image_file: Path) -> list[str]: + if not image_file.is_file(): + return [] + ct = mimetypes.guess_type(str(image_file))[0] or "image/png" + uris: list[str] = [] + try: + blob = image_file.read_bytes() + parts = _split_tall_image(blob, image_file.suffix) + for part in parts: + w, h = _image_dimensions(part, image_file.suffix) + if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000): + continue + if _is_sparse_line_artifact(part, image_file.suffix): + continue + uris.append(_to_preferred_image_data_uri(part, ct)) + except Exception: + return uris + return uris + + +def _ordered_image_names_from_word_html(html_path: Path) -> list[str]: + ordered_names: list[str] = [] + if not html_path.exists(): + return ordered_names + + try: + from bs4 import BeautifulSoup + + html = _decode_word_html(html_path.read_bytes()) + soup = BeautifulSoup(html, "html.parser") + + def _node_is_deleted_change(node) -> bool: + if node is None: + return False + try: + if str(getattr(node, "name", "") or "").lower() == "del": + return True + classes = node.get("class") or [] + for c in classes: + if str(c).lower() in {"msodel"}: + return True + except Exception: + return False + return False + + def _img_in_deleted_context(img) -> bool: + cur = img + hops = 0 + while cur is not None and hops < 8: + hops += 1 + if _node_is_deleted_change(cur): + return True + cur = getattr(cur, "parent", None) + return False + + for img in soup.find_all("img"): + src_attr = img.get("src") + src = str(src_attr or "").strip() + if not src: + continue + name = src.replace("\\", "/").split("/")[-1].lower() + if not _WORD_EXPORT_IMAGE_NAME_RE.fullmatch(name): + continue + + style = " ".join( + [ + str(img.get("style") or ""), + str( + getattr(getattr(img, "parent", None), "get", lambda *_: "")( + "style" + ) + or "" + ), + ] + ).lower() + has_change_ctx = _img_in_deleted_context(img) + w = int(str(img.get("width") or "0").strip() or 0) + h = int(str(img.get("height") or "0").strip() or 0) + if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000): + continue + + if has_change_ctx: + continue + if "position:absolute" in style and w > 0 and h > 0 and (w * h) < 60000: + continue + + if name not in ordered_names: + ordered_names.append(name) + except Exception: + try: + html_bytes = html_path.read_bytes() + for m in re.finditer( + rb"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", + html_bytes, + re.IGNORECASE, + ): + name = m.group(0).decode("ascii", "ignore").lower() + if name and name not in ordered_names: + ordered_names.append(name) + except Exception: + pass + + return ordered_names + + +def _ordered_word_export_files( + files_by_name: dict[str, Path], ordered_names: list[str] +) -> list[Path]: + ordered_files: list[Path] = [] + if ordered_names: + for name in ordered_names: + p = files_by_name.get(name) + if p is None: + continue + ordered_files.append(p) + else: + for name in sorted(files_by_name.keys()): + ordered_files.append(files_by_name[name]) + return ordered_files + + +def _word_html_has_standard_image_refs(html_path: Path) -> bool: + if not html_path.exists(): + return False + try: + raw = html_path.read_bytes() + except Exception: + return False + return ( + re.search( + rb"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", + raw, + re.IGNORECASE, + ) + is not None + ) + + +def _select_word_export_files( + files_by_name: dict[str, Path], + ordered_names: list[str], + html_path: Path, +) -> list[Path]: + has_refs = _word_html_has_standard_image_refs(html_path) + if has_refs and not ordered_names: + return [] + return _ordered_word_export_files(files_by_name, ordered_names) + + +def _extract_images_with_word(source_path: Path, out_dir: Path) -> list[str]: + html_path = out_dir / f"{source_path.stem}.word_export.html" + assets_dir = out_dir / f"{source_path.stem}.word_export_files" + assets_dir_dot = out_dir / f"{source_path.stem}.word_export.files" + out_dir.mkdir(parents=True, exist_ok=True) + + cached_files_by_name = _collect_word_export_image_files(source_path.stem, out_dir) + if html_path.exists(): + ordered_names = _ordered_image_names_from_word_html(html_path) + has_refs = _word_html_has_standard_image_refs(html_path) + + # Cached negative result: html has no refs (or refs all filtered), and no asset files. + # Avoid reopening Word on every run for no-image docs. + if not cached_files_by_name: + if (not has_refs) or (has_refs and not ordered_names): + return [] + + if cached_files_by_name: + ordered_files = _select_word_export_files( + cached_files_by_name, + ordered_names, + html_path, + ) + cached_uris: list[str] = [] + for p in ordered_files: + cached_uris.extend(_image_file_to_uris(p)) + if cached_uris: + return cached_uris + if (not has_refs) or (has_refs and not ordered_names): + return [] + + if html_path.exists(): + html_path.unlink() + if assets_dir.exists(): + shutil.rmtree(assets_dir) + if assets_dir_dot.exists(): + shutil.rmtree(assets_dir_dot) + + convert_with_word(source_path.resolve(), html_path.resolve(), 10) + + files_by_name = _collect_word_export_image_files(source_path.stem, out_dir) + if not files_by_name: + return [] + + ordered_names = _ordered_image_names_from_word_html(html_path) + + ordered_files = _select_word_export_files(files_by_name, ordered_names, html_path) + + uris: list[str] = [] + for p in ordered_files: + uris.extend(_image_file_to_uris(p)) + return uris + + +def _decode_word_html(raw: bytes) -> str: + for enc in ("utf-8", "gb18030", "cp936", "latin1"): + try: + return raw.decode(enc) + except Exception: + continue + return raw.decode("latin1", "ignore") + + +def _norm_text(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").replace("\xa0", " ")).strip() + + +def _xml_local_name(tag: str) -> str: + if not tag: + return "" + if "}" in tag: + return tag.rsplit("}", 1)[-1] + if ":" in tag: + return tag.rsplit(":", 1)[-1] + return tag + + +def _extract_text_from_ooxml_node(node) -> str: + parts: list[str] = [] + + def walk(el) -> None: + name = _xml_local_name(getattr(el, "tag", "")) + + if name in { + "del", + "moveFrom", + "moveFromRangeStart", + "moveFromRangeEnd", + "commentRangeStart", + "commentRangeEnd", + "drawing", + "pict", + "object", + "txbxContent", + "instrText", + }: + return + + if name == "t": + txt = getattr(el, "text", None) + if txt: + parts.append(str(txt)) + elif name == "tab": + parts.append("\t") + elif name in {"br", "cr"}: + parts.append("\n") + + for ch in list(el): + walk(ch) + + try: + walk(node) + except Exception: + return "" + return "".join(parts) + + +def _paragraph_text_without_revisions(para) -> str: + try: + txt = _extract_text_from_ooxml_node(para._p) + except Exception: + txt = para.text or "" + return " ".join((txt or "").split()) + + +def _cell_paragraph_texts_without_revisions(cell) -> list[str]: + chunks: list[str] = [] + try: + for para in cell.paragraphs: + t = _paragraph_text_without_revisions(para) + if t: + chunks.append(t) + except Exception: + fallback = " ".join((cell.text or "").split()) + return [fallback] if fallback else [] + return chunks + + +def _cell_text_without_revisions(cell) -> str: + return "\n".join(_cell_paragraph_texts_without_revisions(cell)).strip() + + +def _drop_deleted_revision_nodes(root) -> None: + try: + for n in root.find_all("del"): + n.decompose() + except Exception: + pass + + try: + for n in root.find_all( + class_=lambda c: c + and any( + str(x).lower() == "msodel" for x in (c if isinstance(c, list) else [c]) + ) + ): + n.decompose() + except Exception: + pass + + +def _extract_word_html_items(html_path: Path) -> list[tuple[str, str]]: + if not html_path.exists(): + return [] + try: + from bs4 import BeautifulSoup + except Exception: + return [] + + try: + html = _decode_word_html(html_path.read_bytes()) + except Exception: + return [] + + soup = BeautifulSoup(html, "html.parser") + body = soup.body or soup + _drop_deleted_revision_nodes(body) + items: list[tuple[str, str]] = [] + + for el in body.find_all(["p", "table"]): + if el.name == "p": + txt = _norm_text(el.get_text(" ", strip=True)) + if txt: + items.append(("paragraph", txt)) + continue + + rows: list[list[str]] = [] + for tr in el.find_all("tr"): + row = [ + _norm_text(td.get_text(" ", strip=True)) + for td in tr.find_all(["th", "td"]) + ] + while row and not row[-1]: + row.pop() + if any(row): + rows.append(row) + if not rows: + continue + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + lines = [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + for r in norm[1:]: + lines.append("| " + " | ".join(r) + " |") + items.append(("table", "\n".join(lines))) + + return items + + +def _extract_workflow_table_from_word_html(html_path: Path) -> tuple[str, list[str]]: + if not html_path.exists(): + return "", [] + try: + from bs4 import BeautifulSoup + except Exception: + return "", [] + + try: + html = _decode_word_html(html_path.read_bytes()) + except Exception: + return "", [] + + source_stem = _word_export_source_stem_from_html(html_path) + files_by_name = _collect_word_export_image_files(source_stem, html_path.parent) + if not files_by_name: + return "", [] + + soup = BeautifulSoup(html, "html.parser") + body = soup.body or soup + _drop_deleted_revision_nodes(body) + uri_cache: dict[str, list[str]] = {} + + for table in body.find_all("table"): + rows: list[list[str]] = [] + used_uris: list[str] = [] + has_images = False + + for tr in table.find_all("tr"): + row: list[str] = [] + for td in tr.find_all(["th", "td"]): + txt = _norm_text(td.get_text(" ", strip=True)) + cell_uris: list[str] = [] + + for img in td.find_all("img"): + src = str(img.get("src") or "").strip() + if not src: + continue + name = src.replace("\\", "/").split("/")[-1].lower() + if not _WORD_EXPORT_IMAGE_NAME_RE.fullmatch(name): + continue + + style = " ".join( + [ + str(img.get("style") or ""), + str( + getattr( + getattr(img, "parent", None), "get", lambda *_: "" + )("style") + or "" + ), + ] + ).lower() + w = int(str(img.get("width") or "0").strip() or 0) + h = int(str(img.get("height") or "0").strip() or 0) + if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000): + continue + if ( + "position:absolute" in style + and w > 0 + and h > 0 + and w < 80 + and h > 260 + ): + continue + + image_file = files_by_name.get(name) + if image_file is None: + continue + if name not in uri_cache: + uri_cache[name] = _image_file_to_uris(image_file) + for uri in uri_cache[name]: + if uri not in cell_uris: + cell_uris.append(uri) + + if cell_uris: + has_images = True + used_uris.extend(cell_uris) + imgs_md = " <br> ".join(f"![table-image]({u})" for u in cell_uris) + row.append((txt + " <br> " if txt else "") + imgs_md) + else: + row.append(txt) + + while row and not row[-1]: + row.pop() + if any(row): + rows.append(row) + + if not rows or not has_images: + continue + + header_text = " ".join(_norm_text(c) for c in rows[0] if c) + header_low = header_text.lower() + if "workflow" not in header_low and "工作流程" not in header_text: + continue + if "operation requirements" not in header_low and "作业要求" not in header_text: + continue + + workflow_idx = next( + ( + i + for i, c in enumerate(rows[0]) + if "workflow" in c.lower() or "工作流程" in c + ), + None, + ) + if workflow_idx is not None: + img_md_pat = re.compile( + r"!\[table-image\]\(data:image/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+\)" + ) + for ridx in range(1, len(rows)): + row = rows[ridx] + while len(row) <= workflow_idx: + row.append("") + if row[workflow_idx].strip(): + continue + for cidx, cell in enumerate(row): + if cidx == workflow_idx or "![table-image](" not in cell: + continue + imgs = img_md_pat.findall(cell) + if not imgs: + continue + cleaned = cell + for imd in imgs: + cleaned = cleaned.replace(imd, "") + cleaned = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", cleaned).strip() + cleaned = re.sub( + r"^(?:<br>\s*)+|(?:\s*<br>)+$", "", cleaned + ).strip() + row[cidx] = cleaned + row[workflow_idx] = " <br> ".join(imgs) + break + + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + lines = [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + for r in norm[1:]: + lines.append("| " + " | ".join(r) + " |") + return "\n".join(lines), used_uris + + return "", [] + + +def _remove_consumed_uris(all_uris: list[str], consumed_uris: list[str]) -> list[str]: + if not consumed_uris: + return all_uris + counts: dict[str, int] = {} + for uri in consumed_uris: + counts[uri] = counts.get(uri, 0) + 1 + + kept: list[str] = [] + for uri in all_uris: + remain = counts.get(uri, 0) + if remain > 0: + counts[uri] = remain - 1 + continue + kept.append(uri) + return kept + + +def _extract_org_side_nodes_from_word_html(html_path: Path) -> str: + if not html_path.exists(): + return "" + try: + from bs4 import BeautifulSoup + except Exception: + return "" + + try: + html = _decode_word_html(html_path.read_bytes()) + except Exception: + return "" + + soup = BeautifulSoup(html, "html.parser") + _drop_deleted_revision_nodes(soup) + + labels: dict[str, str] = {} + for td in soup.find_all("td"): + txt = _norm_text(td.get_text(" ", strip=True)) + if not txt: + continue + low = txt.lower() + + if "report content" in low or "external report" in low or "外部报告" in txt: + continue + if re.search(r"\b(?:120|110|119)\b", txt): + continue + + if "hospital" in low or "医院" in txt: + labels["hospital"] = txt + if "fire control" in low or "firecontrol" in low or "消防" in txt: + labels["fire"] = txt + if "public security" in low or "publicsecurity" in low or "公安" in txt: + labels["public"] = txt + + if not labels: + return "" + + ordered = [ + labels.get("hospital", "医院 hospital"), + labels.get("fire", "消防 fire control"), + labels.get("public", "公安 Public Security"), + ] + ordered = [re.sub(r"\s+", " ", x).strip(" ;;") for x in ordered if x] + if not ordered: + return "" + return "外部支援补充节点:" + ";".join(ordered) + + +def _inject_org_side_nodes_after_612(parsed: list[Block], text: str, idx: int) -> int: + if not text: + return idx + + joined = "\n".join( + b.text for b in parsed if b.type in {"paragraph", "heading", "table"} and b.text + ) + low = joined.lower() + if all(k in low for k in ["hospital", "fire control", "public security"]): + return idx + + anchor = next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and b.text + and ( + "6.1.1公司应急救援小组" in b.text + or re.match(r"^\s*6\.1\.1", b.text.strip()) + ) + ), + None, + ) + if anchor is None: + anchor = next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and b.text + and ( + "6.1.2应急救援体系职责" in b.text + or re.match(r"^\s*6\.1\.2", b.text.strip()) + ) + ), + None, + ) + if anchor is None: + return idx + + idx += 1 + ay = float(parsed[anchor].bbox[3]) if parsed[anchor].bbox else float(anchor) + y = ay + 0.001 + block = Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=text, + bbox=(0.0, y, 100.0, y + 0.001), + ) + parsed.insert(anchor + 1, block) + return idx + + +def _inject_word_workflow_table_images( + parsed: list[Block], html_path: Path +) -> list[str]: + table_md, consumed_uris = _extract_workflow_table_from_word_html(html_path) + if not table_md: + return [] + + target_idx = next( + ( + i + for i, b in enumerate(parsed) + if b.type == "table" + and "![table-image]" not in (b.text or "") + and ("工作流程" in (b.text or "") or "workflow" in (b.text or "").lower()) + and ( + "作业要求" in (b.text or "") + or "operation requirements" in (b.text or "").lower() + ) + ), + None, + ) + if target_idx is None: + return [] + + parsed[target_idx].text = table_md + return consumed_uris + + +def _extract_missing_611_blocks_from_word_html( + html_path: Path, + existing_text: str, + start_idx: int, +) -> list[Block]: + if "6.11" in existing_text: + return [] + + items = _extract_word_html_items(html_path) + if not items: + return [] + + paras = [v for k, v in items if k == "paragraph"] + cand = [i for i, p in enumerate(paras) if "6.11" in p] + if not cand: + return [] + + sec_start = None + for i in cand: + lo = max(0, i - 20) + if any("6.10" in paras[k] for k in range(lo, i)): + sec_start = i + break + if sec_start is None: + sec_start = cand[-1] + + section: list[str] = [] + j = sec_start + while j < len(paras): + nxt = paras[j] + if j > sec_start and re.match(r"^[一二三四五六七八九十]+、", nxt): + break + if j > sec_start and ("参考文件" in nxt or "相关表单" in nxt): + break + if ( + j > sec_start + and re.match(r"^6\.\d{1,2}(?:\.\d+)?", nxt) + and not nxt.startswith("6.11") + ): + break + section.append(nxt) + j += 1 + + section = [ + ln + for ln in section + if ln + and not re.fullmatch(r"\d{4}/\d{1,2}/\d{1,2}(?:\s+\d{4}/\d{1,2}/\d{1,2})*", ln) + and not re.fullmatch(r"V\d+(?:\.\d+)?(?:\s+V\d+(?:\.\d+)?)*", ln) + ] + + out: list[Block] = [] + idx = start_idx + + heading = section[0] if section else "" + body = section[1:] if len(section) >= 2 else [] + + if heading and heading not in existing_text: + idx += 1 + out.append( + Block( + id=f"docx-611-{idx}", + page=1, + type="paragraph", + text=heading, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + header_i = None + for i in range(0, max(0, len(body) - 4)): + h = body[i : i + 5] + if len(h) < 5: + continue + if "备注" in h[4] and ("设备" in h[2] or "设备" in h[3]): + header_i = i + break + + if header_i is not None: + cells = body[header_i:] + header = cells[:5] + rows_raw = cells[5:] + rows: list[list[str]] = [] + for i in range(0, len(rows_raw), 5): + chunk = rows_raw[i : i + 5] + if len(chunk) == 5: + rows.append(chunk) + + if rows: + lines = [ + "| " + " | ".join(header) + " |", + "| " + " | ".join(["---"] * 5) + " |", + ] + for r in rows: + lines.append("| " + " | ".join(r) + " |") + table_md = "\n".join(lines) + if table_md not in existing_text: + idx += 1 + out.append( + Block( + id=f"docx-611-table-{idx}", + page=1, + type="table", + text=table_md, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + elif body: + for p in body: + if p and p not in existing_text: + idx += 1 + out.append( + Block( + id=f"docx-611-{idx}", + page=1, + type="paragraph", + text=p, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + return out + + +def _extract_missing_634_badge_table_from_word_html( + html_path: Path, + existing_text: str, + start_idx: int, +) -> list[Block]: + if "站别" in existing_text and "佩戴袖章标示" in existing_text: + return [] + + items = _extract_word_html_items(html_path) + if not items: + return [] + + anchors = [i for i, (k, v) in enumerate(items) if k == "paragraph" and "6.3.4" in v] + if not anchors: + return [] + anchor_idx = anchors[-1] + + table_md = None + for k, v in items[anchor_idx + 1 : anchor_idx + 40]: + if k != "table": + continue + if "站别" in v and "上岗证名称" in v and "佩戴袖章标示" in v: + table_md = v + break + if not table_md: + return [] + + idx = start_idx + 1 + return [ + Block( + id=f"docx-634-{idx}", + page=1, + type="table", + text=table_md, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ] + + +def _table_to_markdown(table, doc) -> str: + rows: list[list[str]] = [] + seen_img_uri: set[str] = set() + for r in table.rows: + vals: list[str] = [] + for c in r.cells: + txt = _cell_text_without_revisions(c) + img_uris: list[str] = [] + try: + for para in c.paragraphs: + for uri in _extract_image_uris_from_paragraph(para, doc): + if uri in seen_img_uri: + continue + seen_img_uri.add(uri) + img_uris.append(uri) + except Exception: + img_uris = [] + + if img_uris: + imgs_md = " <br> ".join(f"![table-image]({u})" for u in img_uris) + vals.append((txt + " <br> " if txt else "") + imgs_md) + else: + vals.append(txt) + if any(v for v in vals): + rows.append(vals) + if not rows: + return "" + + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + + for i, r in enumerate(norm): + vals = [v for v in r if v] + if not vals: + continue + if vals[0].startswith("备注"): + uniq = list(dict.fromkeys(vals)) + if len(uniq) == 1: + norm[i] = [uniq[0]] + [""] * (width - 1) + continue + if len(set(vals)) == 1 and len(vals) >= 2: + norm[i] = [vals[0]] + [""] * (width - 1) + + header = norm[0] + lines = [ + "| " + " | ".join(header) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + note_blocks: list[str] = [] + for r in norm[1:]: + first = (r[0] or "").strip() + if first.startswith("备注") and not any((c or "").strip() for c in r[1:]): + note = re.sub(r"\s+", " ", first) + note = re.sub(r"\s*(\d+)\.", r"\n\1.", note) + note_blocks.append(note.strip()) + continue + lines.append("| " + " | ".join(r) + " |") + + if note_blocks: + lines.append("") + lines.extend(note_blocks) + return "\n".join(lines) + + +def _looks_like_form_metadata_table(md: str) -> bool: + flat = " ".join(md.split()) + score = 0 + for token in [ + "文件类别", + "File category", + "文件编号", + "Document No", + "页 数 Page", + "制/修订日期", + "Issued/Revised Date", + ]: + if token in flat: + score += 1 + return score >= 3 + + +def _table_markdown_to_paragraph_blocks(md: str, start_idx: int) -> list[Block]: + lines = [ln.strip() for ln in md.splitlines() if ln.strip()] + out: list[Block] = [] + idx = start_idx + for line in lines: + if not line.startswith("|"): + continue + cells = [c.strip() for c in line.strip("|").split("|")] + cells = [c for c in cells if c and c != "---"] + if not cells: + continue + text = "\n".join(cells) + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=text, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + return out + + +def _form_table_to_blocks(table, start_idx: int) -> list[Block]: + out: list[Block] = [] + idx = start_idx + metadata_rows: list[list[str]] = [] + for row in table.rows: + row_cells: list[list[str]] = [] + for cell in row.cells: + parts = _cell_paragraph_texts_without_revisions(cell) + if parts: + row_cells.append(parts) + if not row_cells: + continue + + flattened = [p for parts in row_cells for p in parts if p] + if not flattened: + continue + + unique_flat = list(dict.fromkeys(flattened)) + row_patterns = {tuple(parts) for parts in row_cells} + if len(row_patterns) == 1 and len(row_cells) >= 2: + first = (unique_flat[0] if unique_flat else "").strip() + if "文件修订履历" in first or "Document revision history" in first: + if metadata_rows: + width = max(len(r) for r in metadata_rows) + norm = [r + [""] * (width - len(r)) for r in metadata_rows] + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text="\n".join( + [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + + ["| " + " | ".join(r) + " |" for r in norm[1:]] + ), + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + metadata_rows = [] + for para in unique_flat: + para = para.strip() + if not para: + continue + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=para, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + continue + if first and not re.search( + r"^(?:[一二三四五六七八九十]+、|\d+\.\d+|[A-Za-z]+、)", first + ): + metadata_rows.append(unique_flat) + continue + if metadata_rows: + width = max(len(r) for r in metadata_rows) + norm = [r + [""] * (width - len(r)) for r in metadata_rows] + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text="\n".join( + [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + + ["| " + " | ".join(r) + " |" for r in norm[1:]] + ), + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + metadata_rows = [] + for para in unique_flat: + para = para.strip() + if not para: + continue + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=para, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + continue + + compact = [" / ".join(parts) for parts in row_cells if parts] + text = "\n".join(compact).strip() + if not text: + continue + metadata_rows.append(compact) + if metadata_rows: + width = max(len(r) for r in metadata_rows) + norm = [r + [""] * (width - len(r)) for r in metadata_rows] + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text="\n".join( + [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + + ["| " + " | ".join(r) + " |" for r in norm[1:]] + ), + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + return out + + +def _extract_header_lines(doc) -> list[str]: + out: list[str] = [] + seen: set[str] = set() + for section in doc.sections: + header = section.header + for p in header.paragraphs: + s = _paragraph_text_without_revisions(p) + if s and s not in seen: + seen.add(s) + out.append(s) + for t in header.tables: + for r in t.rows: + vals = [_cell_text_without_revisions(c) for c in r.cells] + vals = [v for v in vals if v] + if not vals: + continue + s = " ".join(vals) + if s and s not in seen: + seen.add(s) + out.append(s) + return out + + +def _drop_cover_header_duplicates(blocks: list[Block]) -> list[Block]: + first_table_idx = next( + (i for i, b in enumerate(blocks[:12]) if b.type == "table"), None + ) + if first_table_idx is None: + return blocks + table_text = blocks[first_table_idx].text or "" + if "文件类别" not in table_text and "File category" not in table_text: + return blocks + meta_pat = re.compile( + r"文件编号|Document No|文件名称|File name|制定部门|Preparation department|页 数|Page", + re.IGNORECASE, + ) + kept: list[Block] = [] + for i, block in enumerate(blocks): + if ( + i < first_table_idx + and block.type == "paragraph" + and meta_pat.search(block.text or "") + ): + continue + kept.append(block) + return kept + + +def _convert_doc_with_word(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + output = out_dir / f"{path.stem}.docx" + return convert_with_word(path.resolve(), output.resolve(), 16) + + +def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + output = out_dir / f"{path.stem}.docx" + force_reconvert = str( + os.environ.get("EDKB_FORCE_DOC_RECONVERT", "") + ).strip().lower() in { + "1", + "true", + "yes", + } + try: + if not force_reconvert and output.exists() and output.stat().st_size > 0: + return output + except Exception: + pass + + errors: list[str] = [] + + if os.name == "nt": + try: + return _convert_doc_with_word(path, out_dir) + except Exception as exc: + errors.append(f"Word COM conversion failed: {exc}") + + soffice_candidates = [ + os.environ.get("EDKB_SOFFICE"), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + for soffice in soffice_candidates: + if not soffice: + continue + cmd = [ + soffice, + "--headless", + "--convert-to", + "docx", + str(path), + "--outdir", + str(out_dir), + ] + try: + proc = subprocess.run(cmd, capture_output=True, text=True) + except FileNotFoundError: + errors.append(f"soffice not found: {soffice}") + continue + + if proc.returncode == 0 and output.exists(): + return output + + stderr = (proc.stderr or "").strip() + errors.append( + f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}" + ) + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError( + ".doc 转 .docx 失败。请安装 LibreOffice(soffice)或本机 Microsoft Word。" + f" details: {joined}" + ) + + +def run(input_data: dict, context: Context) -> list[Block]: + source_path = Path(input_data["file_path"]).resolve() + file_path = source_path + work_dir = Path(input_data["work_dir"]).resolve() + source_ext = source_path.suffix.lower() + + if source_ext == ".doc": + file_path = _convert_doc_to_docx(file_path, work_dir) + + def _parse_docx(docx_path: Path) -> list[Block]: + from docx import Document + from docx.oxml.table import CT_Tbl + from docx.oxml.text.paragraph import CT_P + from docx.table import Table + from docx.text.paragraph import Paragraph + + parsed: list[Block] = [] + doc = Document(str(docx_path)) + num_to_abs, levels = _load_numbering_schema(docx_path) + list_states: dict[str, dict[int, int]] = {} + context.pages = 1 + idx = 0 + + for line in _extract_header_lines(doc): + idx += 1 + parsed.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=line, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + for child in doc.element.body.iterchildren(): + if isinstance(child, CT_P): + para = Paragraph(child, doc) + text = _paragraph_text_without_revisions(para).strip() + marker = "" + try: + ppr = para._p.pPr + if ppr is not None and ppr.numPr is not None: + ilvl = ( + int(ppr.numPr.ilvl.val) if ppr.numPr.ilvl is not None else 0 + ) + num_id = ( + str(ppr.numPr.numId.val) + if ppr.numPr.numId is not None + else "" + ) + if num_id: + marker = _next_list_marker( + num_id, ilvl, num_to_abs, levels, list_states + ) + except Exception: + marker = "" + + if marker and text and not text.startswith(marker): + text = f"{marker} {text}" + image_uris = _extract_image_uris_from_paragraph(para, doc) + if text: + idx += 1 + typ = ( + "heading" + if para.style and "heading" in para.style.name.lower() + else "paragraph" + ) + parsed.append( + Block( + id=f"docx-{idx}", + page=1, + type=typ, + text=text, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + for uri in image_uris: + idx += 1 + context.images += 1 + parsed.append( + Block( + id=f"docx-img-{idx}", + page=1, + type="image", + text="", + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + meta={"data_uri": uri}, + ) + ) + elif isinstance(child, CT_Tbl): + table = Table(child, doc) + md = _table_to_markdown(table, doc) + if md: + if _looks_like_form_metadata_table(md): + blocks = _form_table_to_blocks(table, idx) + if blocks: + idx += len(blocks) + parsed.extend(blocks) + else: + idx += 1 + parsed.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text=md, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + # 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。 + + if not any(b.type == "image" for b in parsed): + for uri in _extract_all_image_uris_from_doc(doc): + idx += 1 + context.images += 1 + parsed.append( + Block( + id=f"docx-img-{idx}", + page=1, + type="image", + text="", + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + meta={"data_uri": uri}, + ) + ) + if source_ext == ".doc": + try: + word_export_dir = work_dir / "word_export" + word_images = _extract_images_with_word(source_path, word_export_dir) + html_path = word_export_dir / f"{source_path.stem}.word_export.html" + org_side_nodes = _extract_org_side_nodes_from_word_html(html_path) + + consumed_uris = _inject_word_workflow_table_images(parsed, html_path) + if consumed_uris: + word_images = _remove_consumed_uris(word_images, consumed_uris) + + current_imgs = [b for b in parsed if b.type == "image"] + if len(word_images) > len(current_imgs): + image_slots = [i for i, b in enumerate(parsed) if b.type == "image"] + replaced: list[Block] = [] + used = 0 + for b in parsed: + if b.type != "image": + replaced.append(b) + continue + if used < len(word_images): + uri = word_images[used] + used += 1 + context.images += 1 + replaced.append( + Block( + id=f"docx-img-{len(replaced) + 1}", + page=b.page, + type="image", + text="", + bbox=b.bbox, + meta={"data_uri": uri}, + ) + ) + insert_at = image_slots[-1] + 1 if image_slots else len(replaced) + while used < len(word_images): + uri = word_images[used] + used += 1 + context.images += 1 + replaced.insert( + insert_at, + Block( + id=f"docx-img-{insert_at + 1}", + page=1, + type="image", + text="", + bbox=( + 0.0, + float(insert_at + 1), + 100.0, + float(insert_at + 2), + ), + meta={"data_uri": uri}, + ), + ) + insert_at += 1 + parsed = replaced + + if org_side_nodes: + idx = _inject_org_side_nodes_after_612(parsed, org_side_nodes, idx) + + existing_text = "\n".join( + b.text + for b in parsed + if b.type in {"paragraph", "heading", "table"} and b.text + ) + added = _extract_missing_611_blocks_from_word_html( + html_path, + existing_text, + len(parsed), + ) + if added: + insert_at = next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and ( + "参考文件" in (b.text or "") + or "相关表单" in (b.text or "") + ) + ), + len(parsed), + ) + parsed = parsed[:insert_at] + added + parsed[insert_at:] + + added_634 = _extract_missing_634_badge_table_from_word_html( + html_path, + "\n".join( + b.text + for b in parsed + if b.type in {"paragraph", "heading", "table"} and b.text + ), + len(parsed), + ) + if added_634: + anchor_y = None + for b in parsed: + if b.type in {"paragraph", "heading"} and "6.3.4" in ( + b.text or "" + ): + anchor_y = b.bbox[1] + break + if anchor_y is None: + anchor_y = float(len(parsed)) + for n, blk in enumerate(added_634, start=1): + y = float(anchor_y) + 0.9 + 0.05 * n + blk.bbox = (0.0, y, 100.0, y + 0.01) + + insert_at_634 = next( + ( + i + 1 + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and "6.3.4" in (b.text or "") + ), + next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and re.match(r"^\s*[七七]、", (b.text or "").strip()) + ), + len(parsed), + ), + ) + parsed = parsed[:insert_at_634] + added_634 + parsed[insert_at_634:] + + if word_images: + final_imgs = [b for b in parsed if b.type == "image"] + if len(final_imgs) < len(word_images): + seen = { + hashlib.sha1( + (b.meta or {}).get("data_uri", "").encode("utf-8") + ).hexdigest() + for b in final_imgs + if (b.meta or {}).get("data_uri") + } + insert_at = len(parsed) + for uri in word_images: + key = hashlib.sha1(uri.encode("utf-8")).hexdigest() + if key in seen: + continue + seen.add(key) + insert_at += 1 + context.images += 1 + parsed.append( + Block( + id=f"docx-img-{insert_at}", + page=1, + type="image", + text="", + bbox=( + 0.0, + float(insert_at), + 100.0, + float(insert_at) + 1, + ), + meta={"data_uri": uri}, + ) + ) + except Exception: + pass + + parsed = _drop_cover_header_duplicates(parsed) + return parsed + + try: + return _parse_docx(file_path) + except Exception as exc: + if file_path.suffix.lower() == ".docx": + try: + repaired = _convert_doc_with_word(file_path, work_dir) + return _parse_docx(repaired) + except Exception as fix_exc: + try: + legacy = work_dir / f"{file_path.stem}.legacy.doc" + shutil.copyfile(file_path, legacy) + repaired = _convert_doc_with_word(legacy, work_dir) + return _parse_docx(repaired) + except Exception as legacy_exc: + context.warnings.append( + "DOCX fallback parser failed: " + f"{exc}; repair failed: {fix_exc}; legacy-doc repair failed: {legacy_exc}" + ) + return [] + context.warnings.append(f"DOCX fallback parser failed: {exc}") + return [] diff --git a/backend/edkb_system/skills/loader_excel.py b/backend/edkb_system/skills/loader_excel.py new file mode 100644 index 00000000..588c1427 --- /dev/null +++ b/backend/edkb_system/skills/loader_excel.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from openpyxl import load_workbook + +from edkb_system.contracts import Context + + +def _soffice_candidates() -> list[str]: + return [ + os.environ.get("EDKB_SOFFICE", "").strip(), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + + +def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + output = out_dir / f"{path.stem}.xlsx" + errors: list[str] = [] + for soffice in _soffice_candidates(): + if not soffice: + continue + cmd = [ + soffice, + "--headless", + "--convert-to", + "xlsx", + str(path), + "--outdir", + str(out_dir), + ] + try: + proc = subprocess.run(cmd, capture_output=True, text=True) + except FileNotFoundError: + errors.append(f"soffice not found: {soffice}") + continue + if proc.returncode == 0 and output.exists(): + return output + stderr = (proc.stderr or "").strip() + errors.append( + f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}" + ) + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError( + ".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。" + f" details: {joined}" + ) + + +def _norm(v) -> str: + return "" if v is None else str(v).strip() + + +def _trim_trailing_empty(vals: list[str]) -> list[str]: + end = len(vals) + while end > 0 and not vals[end - 1]: + end -= 1 + return vals[:end] + + +def run(input_data: dict, context: Context) -> list[dict]: + file_path = Path(input_data["file_path"]) + work_dir = Path(input_data["work_dir"]) + if file_path.suffix.lower() == ".xls": + file_path = _convert_xls_to_xlsx(file_path, work_dir) + + wb = load_workbook(str(file_path), data_only=True) + tables: list[dict] = [] + for ws in wb.worksheets: + rows: list[list[str]] = [] + for row in ws.iter_rows(values_only=True): + vals = _trim_trailing_empty([_norm(v) for v in row]) + if any(vals): + rows.append(vals) + if not rows: + continue + width = max(len(r) for r in rows) + normalized = [r + [""] * (width - len(r)) for r in rows] + tables.append( + {"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]} + ) + context.extras["tables_count"] = len(tables) + return tables diff --git a/backend/edkb_system/skills/loader_pdf.py b/backend/edkb_system/skills/loader_pdf.py new file mode 100644 index 00000000..039f6a1f --- /dev/null +++ b/backend/edkb_system/skills/loader_pdf.py @@ -0,0 +1,250 @@ +from __future__ import annotations + +import base64 +import io +from pathlib import Path + +from edkb_system.contracts import Block, Context + + +def _is_scanned(text_chars: int, pages: int) -> bool: + return text_chars < int(300 * max(pages, 1) / 10) + + +def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str: + b64 = base64.b64encode(blob).decode("ascii") + return f"data:{content_type};base64,{b64}" + + +def _normalize_box( + bounds: tuple[float, float, float, float], +) -> tuple[float, float, float, float]: + x0, y0, x1, y1 = bounds + left = min(x0, x1) + right = max(x0, x1) + top = min(y0, y1) + bottom = max(y0, y1) + return (left, top, right, bottom) + + +def _page_image_stats( + page_width: float, + page_height: float, + image_boxes: list[tuple[float, float, float, float]], +) -> dict[str, float]: + if page_width <= 0 or page_height <= 0 or not image_boxes: + return { + "count": float(len(image_boxes)), + "largest_ratio": 0.0, + "total_ratio": 0.0, + } + + page_area = max(page_width * page_height, 1.0) + largest_ratio = 0.0 + total_ratio = 0.0 + for raw in image_boxes: + x0, y0, x1, y1 = _normalize_box(raw) + width = max(x1 - x0, 0.0) + height = max(y1 - y0, 0.0) + ratio = min((width * height) / page_area, 1.0) + largest_ratio = max(largest_ratio, ratio) + total_ratio += ratio + return { + "count": float(len(image_boxes)), + "largest_ratio": largest_ratio, + "total_ratio": min(total_ratio, 1.5), + } + + +def _should_use_page_image_mode( + *, + scan_likely: bool, + text_chars: int, + image_count: int, + largest_ratio: float, + total_ratio: float, +) -> bool: + if scan_likely: + if image_count == 0: + return True + if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3: + return True + if text_chars <= 120 and ( + largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45) + ): + return True + return False + + +def _collect_image_boxes( + file_path: Path, page_count: int +) -> dict[int, list[tuple[float, float, float, float]]]: + try: + import pypdfium2 as pdfium + import pypdfium2.raw as pdfium_c + except Exception: + return {} + + out: dict[int, list[tuple[float, float, float, float]]] = {} + doc = None + try: + doc = pdfium.PdfDocument(str(file_path)) + for page_idx in range(page_count): + page = doc[page_idx] + boxes: list[tuple[float, float, float, float]] = [] + try: + for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]): + try: + bounds = obj.get_bounds() + except Exception: + bounds = obj.get_pos() + boxes.append(tuple(float(v) for v in bounds)) + except Exception: + boxes = [] + out[page_idx + 1] = boxes + except Exception: + return {} + finally: + try: + if doc is not None: + doc.close() + except Exception: + pass + return out + + +def _render_page_png( + file_path: Path, page_number: int, scale: float = 2.0 +) -> bytes | None: + try: + import pypdfium2 as pdfium + except Exception: + return None + + doc = None + try: + doc = pdfium.PdfDocument(str(file_path)) + page = doc[page_number - 1] + bitmap = page.render(scale=scale) + pil_image = bitmap.to_pil() + buf = io.BytesIO() + pil_image.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + finally: + try: + if doc is not None: + doc.close() + except Exception: + pass + + +def run(input_data: dict, context: Context) -> list[Block]: + file_path = Path(input_data["file_path"]) + blocks: list[Block] = [] + + try: + from pypdf import PdfReader + + reader = PdfReader(str(file_path)) + context.pages = len(reader.pages) + text_chars = 0 + page_payloads: list[dict] = [] + for page_idx, p in enumerate(reader.pages, start=1): + text = (p.extract_text() or "").strip() + images: list[dict] = [] + if text: + text_chars += len(text) + + try: + for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1): + data = getattr(img, "data", None) + if not data: + continue + ext = (getattr(img, "image_format", "") or "").lower() + ct = f"image/{ext}" if ext else "image/png" + images.append({"id": img_idx, "data": data, "content_type": ct}) + except Exception: + pass + page_payloads.append({"page": page_idx, "text": text, "images": images}) + + scan_likely = _is_scanned(text_chars, context.pages) + image_boxes_by_page = _collect_image_boxes(file_path, context.pages) + page_image_mode_pages: list[int] = [] + + for payload in page_payloads: + page_idx = int(payload["page"]) + text = str(payload["text"] or "") + page_images = list(payload["images"]) + image_boxes = image_boxes_by_page.get(page_idx, []) + stats = _page_image_stats(1000.0, 1000.0, image_boxes) + use_page_image_mode = _should_use_page_image_mode( + scan_likely=scan_likely, + text_chars=len(text), + image_count=len(page_images) or int(stats["count"]), + largest_ratio=float(stats["largest_ratio"]), + total_ratio=float(stats["total_ratio"]), + ) + + if text: + blocks.append( + Block( + id=f"pdf-{page_idx}", + page=page_idx, + type="paragraph", + text=text, + bbox=(0.0, 0.0, 1000.0, 1000.0), + ) + ) + + if use_page_image_mode: + rendered = _render_page_png(file_path, page_idx) + if rendered: + blocks.append( + Block( + id=f"pdf-page-{page_idx}", + page=page_idx, + type="image", + text="", + bbox=(0.0, 0.0, 1000.0, 1000.0), + meta={ + "data_uri": _to_data_uri(rendered, "image/png"), + "page_image": True, + }, + ) + ) + context.images += 1 + page_image_mode_pages.append(page_idx) + continue + + for item in page_images: + blocks.append( + Block( + id=f"pdf-{page_idx}-img-{item['id']}", + page=page_idx, + type="image", + text="", + bbox=(0.0, 0.0, 1000.0, 1000.0), + meta={ + "data_uri": _to_data_uri( + item["data"], str(item["content_type"]) + ) + }, + ) + ) + context.images += 1 + + if scan_likely: + context.warnings.append("pdf likely scanned; OCR recommended") + context.extras["scan_likely"] = True + if page_image_mode_pages: + context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages + context.warnings.append( + "pdf page-image mode pages: " + + ", ".join(str(x) for x in page_image_mode_pages) + ) + except Exception as exc: + context.warnings.append(f"PDF parse failed: {exc}") + + return blocks diff --git a/backend/edkb_system/skills/loader_pptx.py b/backend/edkb_system/skills/loader_pptx.py new file mode 100644 index 00000000..c9566696 --- /dev/null +++ b/backend/edkb_system/skills/loader_pptx.py @@ -0,0 +1,478 @@ +from __future__ import annotations + +import base64 +import hashlib +import io +import re +import subprocess +from pathlib import Path + +from edkb_system.contracts import Block, Context + + +def _to_data_uri(blob: bytes, content_type: str) -> str: + return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}" + + +def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + "soffice", + "--headless", + "--convert-to", + "pptx", + str(path), + "--outdir", + str(out_dir), + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + raise RuntimeError("Install LibreOffice to convert .ppt to .pptx") + output = out_dir / f"{path.stem}.pptx" + if not output.exists(): + raise RuntimeError("Install LibreOffice to convert .ppt to .pptx") + return output + + +def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None: + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + "soffice", + "--headless", + "--convert-to", + "pdf", + str(path), + "--outdir", + str(out_dir), + ] + try: + proc = subprocess.run(cmd, capture_output=True, text=True) + except FileNotFoundError: + return None + if proc.returncode != 0: + return None + output = out_dir / f"{path.stem}.pdf" + return output if output.exists() else None + + +def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]: + out_dir.mkdir(parents=True, exist_ok=True) + app = None + pres = None + output: dict[int, bytes] = {} + try: + from win32com.client import DispatchEx + + app = DispatchEx("PowerPoint.Application") + pres = app.Presentations.Open(str(path), WithWindow=False) + for idx, slide in enumerate(pres.Slides, start=1): + target = out_dir / f"slide_{idx:03d}.png" + slide.Export(str(target), "PNG") + if target.exists(): + output[idx] = target.read_bytes() + except Exception: + return {} + finally: + if pres is not None: + try: + pres.Close() + except Exception: + pass + if app is not None: + try: + app.Quit() + except Exception: + pass + return output + + +def _norm_text(text: str) -> str: + return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip() + + +def _shape_bbox(shape) -> tuple[float, float, float, float]: + left = float(getattr(shape, "left", 0)) + top = float(getattr(shape, "top", 0)) + width = float(getattr(shape, "width", 0)) + height = float(getattr(shape, "height", 0)) + return (left, top, left + width, top + height) + + +def _image_pixel_size(blob: bytes) -> tuple[int, int]: + try: + from PIL import Image + + with Image.open(io.BytesIO(blob)) as im: + return int(im.width), int(im.height) + except Exception: + return (0, 0) + + +def _is_small_decorative_image( + blob: bytes, bbox: tuple[float, float, float, float], slide_area: float +) -> bool: + width_px, height_px = _image_pixel_size(blob) + pixel_area = max(width_px, 0) * max(height_px, 0) + box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0) + if ( + width_px + and height_px + and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400) + ): + return True + if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000: + return True + return False + + +def _is_dominant_picture( + bbox: tuple[float, float, float, float], slide_area: float +) -> bool: + box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0) + if slide_area <= 0: + return False + return box_area / slide_area >= 0.45 + + +def _table_to_markdown(table) -> str: + rows: list[list[str]] = [] + for row in table.rows: + vals = [ + " ".join( + p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip() + ) + for cell in row.cells + ] + vals = [v.strip() for v in vals] + if any(vals): + rows.append(vals) + if not rows: + return "" + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + header = norm[0] + body = norm[1:] + lines = [ + "| " + " | ".join(header) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + lines.extend("| " + " | ".join(r) + " |" for r in body) + return "\n".join(lines) + + +def _render_pdf_page_png( + pdf_path: Path, page_number: int, scale: float = 2.0 +) -> bytes | None: + try: + import pypdfium2 as pdfium + except Exception: + return None + + doc = None + try: + doc = pdfium.PdfDocument(str(pdf_path)) + page = doc[page_number - 1] + bitmap = page.render(scale=scale) + pil_image = bitmap.to_pil() + buf = io.BytesIO() + pil_image.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + finally: + try: + if doc is not None: + doc.close() + except Exception: + pass + + +def _crop_rendered_region( + rendered: bytes, + *, + crop_bbox: tuple[float, float, float, float], + slide_width: float, + slide_height: float, + padding: float = 0.03, +) -> bytes | None: + try: + from PIL import Image + + with Image.open(io.BytesIO(rendered)) as im: + x0, y0, x1, y1 = crop_bbox + pad_x = slide_width * padding + pad_y = slide_height * padding + x0 = max(0.0, x0 - pad_x) + y0 = max(0.0, y0 - pad_y) + x1 = min(slide_width, x1 + pad_x) + y1 = min(slide_height, y1 + pad_y) + if x1 <= x0 or y1 <= y0: + return None + scale_x = im.width / max(slide_width, 1.0) + scale_y = im.height / max(slide_height, 1.0) + box = ( + int(x0 * scale_x), + int(y0 * scale_y), + int(x1 * scale_x), + int(y1 * scale_y), + ) + cropped = im.crop(box) + buf = io.BytesIO() + cropped.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + + +def _union_bboxes( + boxes: list[tuple[float, float, float, float]], +) -> tuple[float, float, float, float] | None: + if not boxes: + return None + x0 = min(b[0] for b in boxes) + y0 = min(b[1] for b in boxes) + x1 = max(b[2] for b in boxes) + y1 = max(b[3] for b in boxes) + return (x0, y0, x1, y1) + + +def _bbox_overlap_ratio( + a: tuple[float, float, float, float], b: tuple[float, float, float, float] +) -> float: + ax0, ay0, ax1, ay1 = a + bx0, by0, bx1, by1 = b + ix0 = max(ax0, bx0) + iy0 = max(ay0, by0) + ix1 = min(ax1, bx1) + iy1 = min(ay1, by1) + if ix1 <= ix0 or iy1 <= iy0: + return 0.0 + inter = (ix1 - ix0) * (iy1 - iy0) + area = max((ax1 - ax0) * (ay1 - ay0), 1.0) + return inter / area + + +def _pick_slide_title(flat_shapes) -> str: + candidates: list[tuple[float, float, str]] = [] + for shape in flat_shapes: + if not getattr(shape, "has_text_frame", False): + continue + txt = _norm_text(getattr(shape, "text", "")) + if not txt: + continue + top = float(getattr(shape, "top", 0)) + left = float(getattr(shape, "left", 0)) + candidates.append((top, left, txt)) + if not candidates: + return "" + candidates.sort(key=lambda x: (x[0], x[1])) + preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})") + for top, left, txt in candidates[:6]: + first_line = txt.splitlines()[0].strip() + if preferred_pat.match(first_line) and top <= 1200000: + return first_line + for top, left, txt in candidates[:6]: + first_line = txt.splitlines()[0].strip() + if 2 <= len(first_line) <= 30 and top <= 1800000: + return first_line + return candidates[0][2].splitlines()[0].strip() + + +def _iter_shapes(shapes): + from pptx.enum.shapes import MSO_SHAPE_TYPE + + for shape in shapes: + yield shape + if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP: + for child in _iter_shapes(shape.shapes): + yield child + + +def run(input_data: dict, context: Context) -> list[Block]: + file_path = Path(input_data["file_path"]) + work_dir = Path(input_data["work_dir"]) + if file_path.suffix.lower() == ".ppt": + file_path = _convert_ppt_to_pptx(file_path, work_dir) + + from pptx import Presentation + from pptx.enum.shapes import MSO_SHAPE_TYPE + + prs = Presentation(str(file_path)) + slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides") + pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir) + context.pages = len(prs.slides) + blocks: list[Block] = [] + img_idx = 0 + blk_idx = 0 + slide_area = float(prs.slide_width) * float(prs.slide_height) + + for slide_no, slide in enumerate(prs.slides, start=1): + flat_shapes = list(_iter_shapes(slide.shapes)) + title_text = _norm_text( + getattr(getattr(slide.shapes, "title", None), "text", "") + ) + if not title_text: + title_text = _pick_slide_title(flat_shapes) + heading_text = f"第{slide_no}页" + if title_text: + heading_text = f"第{slide_no}页 {title_text}" + blk_idx += 1 + blocks.append( + Block( + id=f"pptx-{slide_no}-heading-{blk_idx}", + page=slide_no, + type="heading", + text=heading_text, + bbox=(0.0, 0.0, 0.0, 0.0), + ) + ) + + seen_image_hashes: set[str] = set() + dominant_pictures = 0 + shape_heavy = 0 + flow_boxes: list[tuple[float, float, float, float]] = [] + suppress_all_images = title_text == "目录" + + for shape in flat_shapes: + try: + if shape.shape_type == MSO_SHAPE_TYPE.PICTURE: + image = shape.image + bbox = _shape_bbox(shape) + blob_hash = hashlib.sha1(image.blob).hexdigest() + if blob_hash in seen_image_hashes: + continue + seen_image_hashes.add(blob_hash) + if _is_small_decorative_image(image.blob, bbox, slide_area): + continue + if _is_dominant_picture(bbox, slide_area): + dominant_pictures += 1 + elif shape.shape_type in { + MSO_SHAPE_TYPE.AUTO_SHAPE, + MSO_SHAPE_TYPE.LINE, + MSO_SHAPE_TYPE.FREEFORM, + }: + shape_heavy += 1 + bbox = _shape_bbox(shape) + mid_x = (bbox[0] + bbox[2]) / 2.0 + if ( + bbox[2] > bbox[0] + and bbox[3] > bbox[1] + and mid_x >= float(prs.slide_width) * 0.18 + ): + flow_boxes.append(bbox) + except Exception as exc: + context.warnings.append(f"pptx picture skipped: {exc}") + + seen_image_hashes.clear() + render_flow_focus = ( + (not suppress_all_images) + and bool(slide_pngs or pdf_path) + and shape_heavy >= 8 + and dominant_pictures == 0 + ) + flow_crop: tuple[float, float, float, float] | None = None + if render_flow_focus: + rendered = slide_pngs.get(slide_no) + if rendered is None and pdf_path is not None: + rendered = _render_pdf_page_png(pdf_path, slide_no) + if rendered: + flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height)) + img_idx += 1 + blocks.append( + Block( + id=f"pptx-flow-{slide_no}-{img_idx}", + page=slide_no, + type="image", + text="", + bbox=flow_crop, + meta={ + "data_uri": _to_data_uri(rendered, "image/png"), + "flow_focus": True, + "flow_focus_source": "pptx", + "rendered_slide": True, + }, + ) + ) + + for shape in flat_shapes: + try: + if getattr(shape, "has_table", False): + table_md = _table_to_markdown(shape.table) + if table_md: + blk_idx += 1 + blocks.append( + Block( + id=f"pptx-{slide_no}-table-{blk_idx}", + page=slide_no, + type="table", + text=table_md, + bbox=_shape_bbox(shape), + ) + ) + continue + + if shape.shape_type == MSO_SHAPE_TYPE.PICTURE: + if render_flow_focus or suppress_all_images: + continue + is_dominant = False + image = shape.image + bbox = _shape_bbox(shape) + blob_hash = hashlib.sha1(image.blob).hexdigest() + if blob_hash in seen_image_hashes: + continue + seen_image_hashes.add(blob_hash) + if _is_small_decorative_image(image.blob, bbox, slide_area): + continue + is_dominant = _is_dominant_picture(bbox, slide_area) + img_idx += 1 + ext = (getattr(image, "ext", "png") or "png").lower() + ct = f"image/{'jpeg' if ext == 'jpg' else ext}" + meta: dict[str, object] = { + "data_uri": _to_data_uri(image.blob, ct), + "blob_sha1": blob_hash, + } + if is_dominant: + meta["page_image"] = True + meta["page_image_source"] = "pptx" + blocks.append( + Block( + id=f"pptx-img-{slide_no}-{img_idx}", + page=slide_no, + type="image", + text="", + bbox=bbox, + meta=meta, + ) + ) + continue + + if getattr(shape, "has_text_frame", False): + txt = _norm_text(shape.text) + bbox = _shape_bbox(shape) + if not txt or txt == title_text: + continue + if title_text and txt.startswith(title_text): + txt = txt[len(title_text) :].lstrip("\n ::;;,,") + txt = _norm_text(txt) + if not txt: + continue + if re.fullmatch(r"\d+", txt): + continue + if flow_crop is not None and len(txt) <= 28: + continue + if txt and txt != title_text: + blk_idx += 1 + blocks.append( + Block( + id=f"pptx-{slide_no}-text-{blk_idx}", + page=slide_no, + type="paragraph", + text=txt, + bbox=bbox, + ) + ) + except Exception as exc: + context.warnings.append(f"pptx shape skipped: {exc}") + + context.extras["slides_count"] = len(prs.slides) + return blocks diff --git a/backend/edkb_system/skills/ocr.py b/backend/edkb_system/skills/ocr.py new file mode 100644 index 00000000..955d58c0 --- /dev/null +++ b/backend/edkb_system/skills/ocr.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import base64 +import io +import re + +from edkb_system.contracts import Block, Context + + +def _decode_data_uri_image(data_uri: str): + m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL) + if not m: + return None + try: + raw = base64.b64decode(m.group(1), validate=False) + except Exception: + return None + + try: + import numpy as np + from PIL import Image + + with Image.open(io.BytesIO(raw)) as im: + return np.array(im.convert("RGB")) + except Exception: + return None + + +def run( + input_data: list[Block], context: Context, min_confidence: float = 0.3 +) -> list[Block]: + blocks = input_data + try: + from rapidocr_onnxruntime import RapidOCR # type: ignore + except Exception: + context.warnings.append("RapidOCR unavailable; skip OCR") + return blocks + + engine = RapidOCR() + out: list[Block] = [] + for b in blocks: + out.append(b) + if b.type != "image": + continue + context.images += 1 + image_obj = b.meta.get("image") + if image_obj is None and b.meta and b.meta.get("data_uri"): + image_obj = _decode_data_uri_image(str(b.meta.get("data_uri"))) + if image_obj is None: + out.append( + Block( + id=f"ocr-{b.id}", + page=b.page, + type="ocr_text", + text="OCR_TEXT: <empty>", + bbox=b.bbox, + ) + ) + continue + + try: + result, _ = engine(image_obj) + lines = [] + for it in result or []: + if len(it) < 3: + continue + txt = str(it[1]).strip() + conf = float(it[2]) + if txt and conf >= min_confidence: + lines.append(txt) + if lines: + text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines) + context.ocr_characters += sum(len(x) for x in lines) + else: + text = "OCR_TEXT: <empty>" + out.append( + Block( + id=f"ocr-{b.id}", + page=b.page, + type="ocr_text", + text=text, + bbox=b.bbox, + ) + ) + except Exception as exc: + context.warnings.append(f"OCR failed: {exc}") + out.append( + Block( + id=f"ocr-{b.id}", + page=b.page, + type="ocr_text", + text="OCR_TEXT: <empty>", + bbox=b.bbox, + ) + ) + + return out diff --git a/backend/edkb_system/skills/postcheck.py b/backend/edkb_system/skills/postcheck.py new file mode 100644 index 00000000..92a249d3 --- /dev/null +++ b/backend/edkb_system/skills/postcheck.py @@ -0,0 +1,192 @@ +from __future__ import annotations + +import json +import re +from pathlib import Path + +from edkb_system.contracts import Context + + +def _has_doc_meta(text: str) -> bool: + flat = " ".join(text.split()) + has_header = bool( + re.search(r"制定部门.+制/修订日期.+页码", flat) + or re.search(r"Created Dept\..+Date.+Page", flat) + ) + has_meta = bool( + re.search(r"文件编号.+文件级别.+版本", flat) + or re.search(r"Doc\.\s*No\..+File\s*Level.+Rev\.?", flat) + ) + return has_header or has_meta + + +def _expect_doc_meta(text: str) -> bool: + keys = ["文件编号", "文件级别", "制/修订日期", "制定部门", "页码"] + return any(k in text for k in keys) + + +def _expect_flow_artifacts(text: str) -> bool: + if "作业流程图" not in text: + return False + hints = ["序号", "流程说明", "责任", "相关记录"] + return sum(1 for h in hints if h in text) >= 2 + + +def _expect_related_forms_table(text: str) -> bool: + if "相关表单" not in text: + return False + return ("表单编号" in text) or bool(re.search(r"PB-\d{2,}", text)) + + +def _has_source_images(out_dir: Path) -> bool: + raw = out_dir / "01_raw_layout.json" + if not raw.exists(): + return False + try: + data = json.loads(raw.read_text(encoding="utf-8")) + if isinstance(data, list): + for b in data: + if isinstance(b, dict) and b.get("type") == "image": + return True + except Exception: + return False + return False + + +def _has_markdown_image_reference(text: str) -> bool: + for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text): + target = (m.group(1) or "").strip() + if target.startswith("data:image/"): + return True + if target.startswith("http://") or target.startswith("https://"): + return True + return False + + +def _has_remote_image_url(text: str) -> bool: + for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text): + target = (m.group(1) or "").strip() + if target.startswith("http://") or target.startswith("https://"): + return True + return False + + +def _expect_revision_table(text: str) -> bool: + if "文件修订履历" in text: + return True + hint = ["日期", "修订章节", "主要修订内容", "版本", "修改人"] + return sum(1 for h in hint if h in text) >= 4 + + +def _collect_issues(text: str) -> list[dict]: + issues: list[dict] = [] + lines = text.splitlines() + num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}\s+") + + non_empty = [(i + 1, ln.strip()) for i, ln in enumerate(lines) if ln.strip()] + if len(non_empty) >= 2: + l1, s1 = non_empty[0] + l2, s2 = non_empty[1] + if "文件编号" in s1 and "文件编号" not in s2 and not s2.startswith("制定部门"): + if not re.match(r"^[一二三四五六七八九十]+、", s2): + issues.append( + { + "code": "title_below_meta", + "line": l1, + "text": f"meta before title: {s1[:80]}", + } + ) + + for i, ln in enumerate(lines, start=1): + s = ln.strip() + if not s: + continue + if s.startswith("|"): + continue + + if re.search(r"\d+\.\d+(?:\.\d+)?\s+.+\s+\d+\.\d+(?:\.\d+)?\s+", s): + issues.append( + {"code": "inline_numbered_sections", "line": i, "text": s[:180]} + ) + + if re.search(r"[七八]、参考文件\s+[七八]、相关表单", s): + issues.append({"code": "inline_section_titles", "line": i, "text": s[:180]}) + + for i in range(1, len(lines) - 1): + if lines[i].strip(): + continue + prev = lines[i - 1].strip() + nxt = lines[i + 1].strip() + if num_pat.match(prev) and num_pat.match(nxt): + issues.append( + { + "code": "blank_between_numbered_sections", + "line": i + 1, + "text": f"{prev[:70]} / {nxt[:70]}", + } + ) + + return issues + + +def run(input_data: dict, context: Context) -> dict: + out_dir = Path(input_data["out_dir"]) + clean_md = input_data.get("clean_md", "") + + checks = { + "has_doc_meta": _has_doc_meta(clean_md), + "has_revision_table": bool( + (re.search(r"\|\s*(?:日期|文件日期)\b", clean_md) is not None) + and re.search(r"\|\s*.*修订章节", clean_md) + and re.search(r"\|\s*版本\b", clean_md) + ), + "has_flow_table": "| 序号 | 流程说明 | 责任部门 | 相关记录 |" in clean_md, + "has_related_forms_table": bool( + re.search(r"\|\s*表单编号\s*\|", clean_md) + and re.search(r"\|\s*[-:]{3,}\s*\|", clean_md) + ), + "has_flow_file": (out_dir / "02_flow_procedure.md").exists(), + "has_embedded_images": _has_markdown_image_reference(clean_md), + "has_remote_image_urls": _has_remote_image_url(clean_md), + } + + flow_expected = _expect_flow_artifacts(clean_md) + expected = { + "has_doc_meta": _expect_doc_meta(clean_md), + "has_revision_table": _expect_revision_table(clean_md), + "has_flow_table": flow_expected, + "has_related_forms_table": _expect_related_forms_table(clean_md), + "has_flow_file": flow_expected, + "has_embedded_images": _has_source_images(out_dir), + } + + failed_required = [k for k, v in expected.items() if v and not checks.get(k, False)] + status = "pass" if not failed_required else "fail" + issues = _collect_issues(clean_md) + if expected["has_embedded_images"] and not checks["has_embedded_images"]: + issues.append( + { + "code": "image_not_embedded", + "line": 0, + "text": "source has image blocks but markdown has no image references", + } + ) + + if "data:image/" in clean_md: + issues.append( + { + "code": "legacy_base64_image", + "line": 0, + "text": "markdown still contains legacy data:image base64 payload", + } + ) + + return { + "status": status, + "checks": checks, + "expected": expected, + "failed_required": failed_required, + "issues": issues, + "issue_count": len(issues), + "warnings_count": len(context.warnings), + } diff --git a/backend/edkb_system/skills/quality_gate.py b/backend/edkb_system/skills/quality_gate.py new file mode 100644 index 00000000..627fae79 --- /dev/null +++ b/backend/edkb_system/skills/quality_gate.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from edkb_system.contracts import Chunk, Context + + +def run(input_data: list[Chunk], context: Context) -> list[Chunk]: + chunks = input_data + if not chunks: + context.warnings.append("quality_gate: no chunks generated") + context.confidence = min(context.confidence, 0.5) + return chunks + + short_count = sum(1 for c in chunks if len(c.text.strip()) < 60) + if short_count: + context.warnings.append(f"quality_gate: {short_count} short chunks") + context.confidence = min(context.confidence, 0.8) + + unique_texts = len({c.text for c in chunks}) + if unique_texts < len(chunks): + context.warnings.append("quality_gate: duplicate chunks detected") + context.confidence = min(context.confidence, 0.75) + + return chunks diff --git a/backend/edkb_system/skills/table_linearize.py b/backend/edkb_system/skills/table_linearize.py new file mode 100644 index 00000000..307f12d5 --- /dev/null +++ b/backend/edkb_system/skills/table_linearize.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from edkb_system.contracts import Context + + +COND_KWS = ["条件", "判定", "if", "IF"] +ACT_KWS = ["处理", "动作", "措施", "结果", "输出"] +OWN_KWS = ["责任", "负责人", "部门", "岗位"] + + +def _find_col(headers: list[str], kws: list[str]) -> int | None: + for i, h in enumerate(headers): + s = (h or "").lower() + if any(k.lower() in s for k in kws): + return i + return None + + +def _to_table_md(headers: list[str], rows: list[list[str]]) -> str: + hs = [h or "-" for h in headers] + out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"] + for r in rows: + vals = [r[i] if i < len(r) else "" for i in range(len(hs))] + out.append("| " + " | ".join(vals) + " |") + return "\n".join(out) + + +def run(input_data: list[dict] | dict, context: Context) -> str: + tables = input_data if isinstance(input_data, list) else [input_data] + parts: list[str] = [] + + for t in tables: + headers = [str(x).strip() for x in t.get("headers", [])] + rows = [[str(c).strip() for c in row] for row in t.get("rows", [])] + parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}") + + cidx = _find_col(headers, COND_KWS) + aidx = _find_col(headers, ACT_KWS) + oidx = _find_col(headers, OWN_KWS) + if cidx is not None and aidx is not None: + for row in rows: + cond = row[cidx] if cidx < len(row) else "满足条件" + act = row[aidx] if aidx < len(row) else "执行处理" + owner = ( + row[oidx] if oidx is not None and oidx < len(row) else "相关责任方" + ) + parts.append( + f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。" + ) + else: + parts.append(_to_table_md(headers, rows)) + + parts.append("") + + return "\n".join(parts).strip() + "\n" diff --git a/backend/edkb_system/skills/word_bridge.py b/backend/edkb_system/skills/word_bridge.py new file mode 100644 index 00000000..13cc1396 --- /dev/null +++ b/backend/edkb_system/skills/word_bridge.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import os +import subprocess +import sys +import threading +import time +import ctypes +from pathlib import Path + + +def _list_winword_pids() -> set[int]: + if os.name != "nt": + return set() + try: + proc = subprocess.run( + ["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"], + capture_output=True, + text=True, + check=False, + ) + except Exception: + return set() + + out: set[int] = set() + for line in (proc.stdout or "").splitlines(): + line = line.strip() + if not line or line.startswith("INFO:"): + continue + cols = [part.strip().strip('"') for part in line.split('","')] + if len(cols) < 2: + cols = [part.strip().strip('"') for part in line.split(",")] + if len(cols) < 2: + continue + try: + out.add(int(cols[1])) + except ValueError: + continue + return out + + +def _kill_winword_pids(pids: set[int]) -> None: + if os.name != "nt": + return + for pid in sorted(pids): + try: + subprocess.run( + ["taskkill", "/PID", str(pid), "/F"], + capture_output=True, + text=True, + check=False, + ) + except Exception: + continue + + +def _word_timeout_sec() -> int: + raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip() + try: + value = int(raw) + except ValueError: + value = 120 + return max(value, 10) + + +def _should_accept_word_dialog( + window_title: str, child_texts: list[str], button_texts: list[str] +) -> bool: + text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip()) + if not text_blob: + return False + + has_repair_prompt = any( + token in text_blob + for token in [ + "出现严重错误", + "是否仍要打开", + "serious error", + "do you still want to open", + ] + ) + if not has_repair_prompt: + return False + + return any( + text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower() + for text in button_texts + ) + + +def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]: + stop_event = threading.Event() + if os.name != "nt": + return stop_event, None + + def _window_text(user32, hwnd: int) -> str: + length = user32.GetWindowTextLengthW(hwnd) + if length <= 0: + return "" + buf = ctypes.create_unicode_buffer(length + 1) + user32.GetWindowTextW(hwnd, buf, length + 1) + return buf.value + + def _class_name(user32, hwnd: int) -> str: + buf = ctypes.create_unicode_buffer(256) + user32.GetClassNameW(hwnd, buf, 255) + return buf.value + + def _click_yes_if_needed() -> None: + user32 = ctypes.windll.user32 + bm_click = 0x00F5 + vk_return = 0x0D + wm_keydown = 0x0100 + wm_keyup = 0x0101 + + while not stop_event.is_set(): + windows: list[int] = [] + + @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + def enum_windows(hwnd, lparam): + windows.append(int(hwnd)) + return True + + user32.EnumWindows(enum_windows, 0) + for hwnd in windows: + title = _window_text(user32, hwnd) + cls = _class_name(user32, hwnd).lower() + if "Microsoft Word" not in title and cls != "#32770": + continue + + child_hwnds: list[int] = [] + + @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + def enum_children(child_hwnd, lparam): + child_hwnds.append(int(child_hwnd)) + return True + + user32.EnumChildWindows(hwnd, enum_children, 0) + child_texts = [_window_text(user32, child) for child in child_hwnds] + button_hwnds = [ + child + for child in child_hwnds + if _class_name(user32, child).lower() == "button" + ] + button_texts = [_window_text(user32, child) for child in button_hwnds] + if not _should_accept_word_dialog(title, child_texts, button_texts): + continue + user32.SetForegroundWindow(hwnd) + for child, text in zip(button_hwnds, button_texts): + normalized = text.strip().lower() + if normalized.startswith(("是", "yes")) or "&y" in normalized: + user32.SendMessageW(child, bm_click, 0, 0) + break + else: + user32.PostMessageW(hwnd, wm_keydown, vk_return, 0) + user32.PostMessageW(hwnd, wm_keyup, vk_return, 0) + stop_event.wait(0.5) + + thread = threading.Thread(target=_click_yes_if_needed, daemon=True) + thread.start() + return stop_event, thread + + +def convert_with_word(path: Path, output: Path, file_format: int) -> Path: + timeout = _word_timeout_sec() + before_pids = _list_winword_pids() + cmd = [ + sys.executable, + "-m", + "edkb_system.skills.word_bridge", + str(path), + str(output), + str(file_format), + ] + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except subprocess.TimeoutExpired as exc: + after_pids = _list_winword_pids() + _kill_winword_pids(after_pids - before_pids) + raise RuntimeError( + f"Word conversion timed out after {timeout}s: {path.name}" + ) from exc + + if proc.returncode != 0: + err = (proc.stderr or proc.stdout or "unknown error").strip() + raise RuntimeError(f"Word conversion failed: {err}") + + if not output.exists() or output.stat().st_size <= 0: + raise RuntimeError(f"Word conversion produced no output: {output}") + return output + + +def _child_main(argv: list[str]) -> int: + if len(argv) != 4: + print("usage: word_bridge <input> <output> <file_format>", file=sys.stderr) + return 2 + + src = Path(argv[1]).resolve() + out = Path(argv[2]).resolve() + file_format = int(argv[3]) + out.parent.mkdir(parents=True, exist_ok=True) + stop_event, watcher = _start_word_dialog_watcher() + + word = None + doc = None + try: + from win32com.client import DispatchEx + + word = DispatchEx("Word.Application") + word.Visible = False + word.DisplayAlerts = 0 + try: + word.Options.SaveNormalPrompt = False + except Exception: + pass + doc = word.Documents.Open( + FileName=str(src), + ReadOnly=True, + AddToRecentFiles=False, + ConfirmConversions=False, + NoEncodingDialog=True, + OpenAndRepair=True, + ) + doc.SaveAs(str(out), FileFormat=file_format) + finally: + stop_event.set() + if watcher is not None: + watcher.join(timeout=1) + if doc is not None: + try: + doc.Close(False) + except Exception: + pass + if word is not None: + try: + word.Quit() + except Exception: + pass + return 0 + + +if __name__ == "__main__": + raise SystemExit(_child_main(sys.argv)) diff --git a/backend/migrations/env.py b/backend/migrations/env.py new file mode 100644 index 00000000..07899e67 --- /dev/null +++ b/backend/migrations/env.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from logging.config import fileConfig +from pathlib import Path +import sys + +from alembic import context +from sqlalchemy import engine_from_config, pool + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.config import get_settings +from app.database import Base +from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, SystemSetting, User + + +config = context.config +settings = get_settings() +config.set_main_option("sqlalchemy.url", settings.database_url) + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + url = config.get_main_option("sqlalchemy.url") + context.configure(url=url, target_metadata=target_metadata, literal_binds=True) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/migrations/versions/20260327_0001_initial.py b/backend/migrations/versions/20260327_0001_initial.py new file mode 100644 index 00000000..5306d9f1 --- /dev/null +++ b/backend/migrations/versions/20260327_0001_initial.py @@ -0,0 +1,150 @@ +"""initial schema + +Revision ID: 20260327_0001 +Revises: +Create Date: 2026-03-27 23:30:00 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "20260327_0001" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "users", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("username", sa.String(length=64), nullable=False), + sa.Column("full_name", sa.String(length=128), nullable=True), + sa.Column("password_hash", sa.String(length=255), nullable=False), + sa.Column("role", sa.String(length=16), nullable=False, server_default="user"), + sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + ) + op.create_index("ix_users_username", "users", ["username"], unique=True) + + op.create_table( + "system_settings", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("dify_permission", sa.String(length=32), nullable=False, server_default="all_team_members"), + sa.Column("indexing_technique", sa.String(length=32), nullable=False, server_default="high_quality"), + sa.Column("search_method", sa.String(length=32), nullable=False, server_default="hybrid_search"), + sa.Column("doc_form", sa.String(length=32), nullable=False, server_default="text_model"), + sa.Column("top_k", sa.Integer(), nullable=False, server_default="5"), + sa.Column("score_threshold_enabled", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("score_threshold", sa.String(length=32), nullable=False, server_default="0.35"), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + ) + + op.create_table( + "groups", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("name", sa.String(length=128), nullable=False), + sa.Column("description", sa.Text(), nullable=True), + sa.Column("dify_dataset_id", sa.String(length=128), nullable=True), + sa.Column("dify_sync_policy", sa.String(length=32), nullable=False, server_default="manual"), + sa.Column("indexing_technique", sa.String(length=32), nullable=False, server_default="high_quality"), + sa.Column("search_method", sa.String(length=32), nullable=False, server_default="hybrid_search"), + sa.Column("doc_form", sa.String(length=32), nullable=False, server_default="text_model"), + sa.Column("top_k", sa.Integer(), nullable=False, server_default="5"), + sa.Column("score_threshold_enabled", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("score_threshold", sa.String(length=32), nullable=False, server_default="0.35"), + sa.Column("created_by_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + ) + op.create_index("ix_groups_name", "groups", ["name"], unique=True) + + op.create_table( + "documents", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("group_id", sa.Integer(), sa.ForeignKey("groups.id"), nullable=False), + sa.Column("title", sa.String(length=255), nullable=False), + sa.Column("is_deleted", sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column("created_by_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.UniqueConstraint("group_id", "title", name="uq_documents_group_title"), + ) + + op.create_table( + "document_versions", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("document_id", sa.Integer(), sa.ForeignKey("documents.id"), nullable=False), + sa.Column("version_no", sa.Integer(), nullable=False), + sa.Column("is_current", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("source_filename", sa.String(length=255), nullable=False), + sa.Column("source_ext", sa.String(length=16), nullable=False), + sa.Column("source_path", sa.Text(), nullable=False), + sa.Column("source_sha256", sa.String(length=64), nullable=False), + sa.Column("md_path", sa.Text(), nullable=True), + sa.Column("md_public_url", sa.Text(), nullable=True), + sa.Column("asset_dir", sa.Text(), nullable=True), + sa.Column("file_size", sa.Integer(), nullable=False), + sa.Column("word_count", sa.Integer(), nullable=False, server_default="0"), + sa.Column("convert_status", sa.String(length=32), nullable=False, server_default="queued"), + sa.Column("sync_status", sa.String(length=32), nullable=False, server_default="unsynced"), + sa.Column("uploader_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True), + sa.Column("uploaded_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.Column("converted_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("failed_reason", sa.Text(), nullable=True), + sa.Column("warnings_json", sa.JSON(), nullable=True), + ) + op.create_index("ix_document_versions_source_sha256", "document_versions", ["source_sha256"], unique=False) + + op.create_table( + "jobs", + sa.Column("id", sa.String(length=36), primary_key=True), + sa.Column("job_type", sa.String(length=32), nullable=False), + sa.Column("status", sa.String(length=32), nullable=False, server_default="queued"), + sa.Column("queue_job_id", sa.String(length=64), nullable=True), + sa.Column("group_id", sa.Integer(), sa.ForeignKey("groups.id"), nullable=True), + sa.Column("document_id", sa.Integer(), sa.ForeignKey("documents.id"), nullable=True), + sa.Column("version_id", sa.Integer(), sa.ForeignKey("document_versions.id"), nullable=True), + sa.Column("created_by_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True), + sa.Column("progress", sa.Integer(), nullable=False, server_default="0"), + sa.Column("message", sa.Text(), nullable=True), + sa.Column("error", sa.Text(), nullable=True), + sa.Column("payload", sa.JSON(), nullable=True), + sa.Column("result", sa.JSON(), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.Column("started_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True), + ) + op.create_index("ix_jobs_status", "jobs", ["status"], unique=False) + op.create_index("ix_jobs_job_type", "jobs", ["job_type"], unique=False) + + op.create_table( + "dify_sync_records", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("version_id", sa.Integer(), sa.ForeignKey("document_versions.id"), nullable=False), + sa.Column("dataset_id", sa.String(length=128), nullable=False), + sa.Column("remote_document_id", sa.String(length=128), nullable=False), + sa.Column("batch", sa.String(length=128), nullable=True), + sa.Column("status", sa.String(length=32), nullable=False, server_default="syncing"), + sa.Column("last_indexing_status", sa.String(length=64), nullable=True), + sa.Column("error", sa.Text(), nullable=True), + sa.Column("last_synced_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + ) + + +def downgrade() -> None: + op.drop_table("dify_sync_records") + op.drop_index("ix_jobs_job_type", table_name="jobs") + op.drop_index("ix_jobs_status", table_name="jobs") + op.drop_table("jobs") + op.drop_index("ix_document_versions_source_sha256", table_name="document_versions") + op.drop_table("document_versions") + op.drop_table("documents") + op.drop_index("ix_groups_name", table_name="groups") + op.drop_table("groups") + op.drop_table("system_settings") + op.drop_index("ix_users_username", table_name="users") + op.drop_table("users") diff --git a/backend/migrations/versions/20260328_0002_dify_model_defaults.py b/backend/migrations/versions/20260328_0002_dify_model_defaults.py new file mode 100644 index 00000000..38c9e6d9 --- /dev/null +++ b/backend/migrations/versions/20260328_0002_dify_model_defaults.py @@ -0,0 +1,31 @@ +"""add dify model defaults to system settings + +Revision ID: 20260328_0002 +Revises: 20260327_0001 +Create Date: 2026-03-28 09:30:00 +""" + +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + + +revision = "20260328_0002" +down_revision = "20260327_0001" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column("system_settings", sa.Column("embedding_model_provider", sa.String(length=128), nullable=True)) + op.add_column("system_settings", sa.Column("embedding_model", sa.String(length=128), nullable=True)) + op.add_column("system_settings", sa.Column("reranking_model_provider", sa.String(length=128), nullable=True)) + op.add_column("system_settings", sa.Column("reranking_model", sa.String(length=128), nullable=True)) + + +def downgrade() -> None: + op.drop_column("system_settings", "reranking_model") + op.drop_column("system_settings", "reranking_model_provider") + op.drop_column("system_settings", "embedding_model") + op.drop_column("system_settings", "embedding_model_provider") diff --git a/backend/migrations/versions/20260329_0003_roles_and_group_access.py b/backend/migrations/versions/20260329_0003_roles_and_group_access.py new file mode 100644 index 00000000..ec1658a2 --- /dev/null +++ b/backend/migrations/versions/20260329_0003_roles_and_group_access.py @@ -0,0 +1,37 @@ +"""roles and group access + +Revision ID: 20260329_0003 +Revises: 20260328_0002 +Create Date: 2026-03-29 09:30:00 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "20260329_0003" +down_revision = "20260328_0002" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "user_group_access", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False), + sa.Column("group_id", sa.Integer(), sa.ForeignKey("groups.id"), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.UniqueConstraint("user_id", "group_id", name="uq_user_group_access"), + ) + op.create_index("ix_user_group_access_user_id", "user_group_access", ["user_id"], unique=False) + op.create_index("ix_user_group_access_group_id", "user_group_access", ["group_id"], unique=False) + + op.execute("UPDATE users SET role = 'super_admin' WHERE role = 'admin'") + + +def downgrade() -> None: + op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin'") + op.drop_index("ix_user_group_access_group_id", table_name="user_group_access") + op.drop_index("ix_user_group_access_user_id", table_name="user_group_access") + op.drop_table("user_group_access") diff --git a/backend/migrations/versions/20260329_0004_departments_and_unique_super_admin.py b/backend/migrations/versions/20260329_0004_departments_and_unique_super_admin.py new file mode 100644 index 00000000..d07e32f3 --- /dev/null +++ b/backend/migrations/versions/20260329_0004_departments_and_unique_super_admin.py @@ -0,0 +1,85 @@ +"""departments and unique super admin + +Revision ID: 20260329_0004 +Revises: 20260329_0003 +Create Date: 2026-03-29 15:40:00 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "20260329_0004" +down_revision = "20260329_0003" +branch_labels = None +depends_on = None + + +DEFAULT_DEPARTMENT_NAME = "默认部门" + + +def upgrade() -> None: + op.create_table( + "departments", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("name", sa.String(length=128), nullable=False), + sa.Column("description", sa.Text(), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + ) + op.create_index("ix_departments_name", "departments", ["name"], unique=True) + + op.add_column("users", sa.Column("primary_department_id", sa.Integer(), nullable=True)) + op.create_index("ix_users_primary_department_id", "users", ["primary_department_id"], unique=False) + op.add_column("groups", sa.Column("department_id", sa.Integer(), nullable=True)) + op.create_index("ix_groups_department_id", "groups", ["department_id"], unique=False) + + op.create_table( + "user_department_access", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=False), + sa.Column("department_id", sa.Integer(), sa.ForeignKey("departments.id"), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False), + sa.UniqueConstraint("user_id", "department_id", name="uq_user_department_access"), + ) + op.create_index("ix_user_department_access_user_id", "user_department_access", ["user_id"], unique=False) + op.create_index("ix_user_department_access_department_id", "user_department_access", ["department_id"], unique=False) + + op.execute( + sa.text( + "INSERT INTO departments (name, description) VALUES (:name, :description)" + ).bindparams(name=DEFAULT_DEPARTMENT_NAME, description="系统默认部门") + ) + op.execute("UPDATE users SET primary_department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1)") + op.execute("UPDATE groups SET department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1)") + op.execute( + """ + INSERT INTO user_department_access (user_id, department_id) + SELECT id, primary_department_id FROM users + WHERE primary_department_id IS NOT NULL + """ + ) + + op.create_foreign_key("fk_users_primary_department_id", "users", "departments", ["primary_department_id"], ["id"]) + op.create_foreign_key("fk_groups_department_id", "groups", "departments", ["department_id"], ["id"]) + + op.alter_column("users", "primary_department_id", nullable=False) + op.alter_column("groups", "department_id", nullable=False) + + op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin' AND lower(username) <> 'admin'") + op.execute("UPDATE users SET role = 'super_admin' WHERE lower(username) = 'admin'") + + +def downgrade() -> None: + op.execute("UPDATE users SET role = 'admin' WHERE role = 'super_admin'") + op.drop_constraint("fk_groups_department_id", "groups", type_="foreignkey") + op.drop_constraint("fk_users_primary_department_id", "users", type_="foreignkey") + op.drop_index("ix_user_department_access_department_id", table_name="user_department_access") + op.drop_index("ix_user_department_access_user_id", table_name="user_department_access") + op.drop_table("user_department_access") + op.drop_index("ix_groups_department_id", table_name="groups") + op.drop_column("groups", "department_id") + op.drop_index("ix_users_primary_department_id", table_name="users") + op.drop_column("users", "primary_department_id") + op.drop_index("ix_departments_name", table_name="departments") + op.drop_table("departments") diff --git a/backend/migrations/versions/20260329_0005_remove_default_department.py b/backend/migrations/versions/20260329_0005_remove_default_department.py new file mode 100644 index 00000000..04d0df33 --- /dev/null +++ b/backend/migrations/versions/20260329_0005_remove_default_department.py @@ -0,0 +1,93 @@ +"""remove default department bootstrap + +Revision ID: 20260329_0005 +Revises: 20260329_0004 +Create Date: 2026-03-29 17:10:00 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "20260329_0005" +down_revision = "20260329_0004" +branch_labels = None +depends_on = None + + +LEGACY_DEFAULT_DEPARTMENT_NAMES = ("默认部门", "榛樿閮ㄩ棬") + + +def upgrade() -> None: + op.alter_column("users", "primary_department_id", nullable=True) + op.alter_column("groups", "department_id", nullable=True) + + for name in LEGACY_DEFAULT_DEPARTMENT_NAMES: + op.execute( + sa.text( + """ + DELETE FROM user_department_access + WHERE department_id IN (SELECT id FROM departments WHERE name = :name) + """ + ).bindparams(name=name) + ) + op.execute( + sa.text( + """ + UPDATE users + SET primary_department_id = NULL + WHERE primary_department_id IN (SELECT id FROM departments WHERE name = :name) + """ + ).bindparams(name=name) + ) + op.execute( + sa.text( + """ + UPDATE groups + SET department_id = NULL + WHERE department_id IN (SELECT id FROM departments WHERE name = :name) + """ + ).bindparams(name=name) + ) + op.execute(sa.text("DELETE FROM departments WHERE name = :name").bindparams(name=name)) + + +def downgrade() -> None: + op.execute( + sa.text( + """ + INSERT INTO departments (name, description) + SELECT :name, :description + WHERE NOT EXISTS (SELECT 1 FROM departments WHERE name = :name) + """ + ).bindparams(name="默认部门", description="系统默认部门") + ) + op.execute( + """ + UPDATE users + SET primary_department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1) + WHERE primary_department_id IS NULL + """ + ) + op.execute( + """ + UPDATE groups + SET department_id = (SELECT id FROM departments WHERE name = '默认部门' LIMIT 1) + WHERE department_id IS NULL + """ + ) + op.execute( + """ + INSERT INTO user_department_access (user_id, department_id) + SELECT id, primary_department_id + FROM users + WHERE primary_department_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 + FROM user_department_access uda + WHERE uda.user_id = users.id AND uda.department_id = users.primary_department_id + ) + """ + ) + op.alter_column("groups", "department_id", nullable=False) + op.alter_column("users", "primary_department_id", nullable=False) diff --git a/backend/migrations/versions/20260401_0006_group_name_unique_per_department.py b/backend/migrations/versions/20260401_0006_group_name_unique_per_department.py new file mode 100644 index 00000000..81ca8c3d --- /dev/null +++ b/backend/migrations/versions/20260401_0006_group_name_unique_per_department.py @@ -0,0 +1,27 @@ +"""make group names unique per department + +Revision ID: 20260401_0006 +Revises: 20260329_0005 +Create Date: 2026-04-01 18:40:00 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "20260401_0006" +down_revision = "20260329_0005" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.drop_index("ix_groups_name", table_name="groups") + op.create_index("ix_groups_name", "groups", ["name"], unique=False) + op.create_unique_constraint("uq_groups_department_name", "groups", ["department_id", "name"]) + + +def downgrade() -> None: + op.drop_constraint("uq_groups_department_name", "groups", type_="unique") + op.drop_index("ix_groups_name", table_name="groups") + op.create_index("ix_groups_name", "groups", ["name"], unique=True) diff --git a/backend/migrations/versions/20260401_0007_groups_require_department.py b/backend/migrations/versions/20260401_0007_groups_require_department.py new file mode 100644 index 00000000..6012df6f --- /dev/null +++ b/backend/migrations/versions/20260401_0007_groups_require_department.py @@ -0,0 +1,41 @@ +"""require a department on groups + +Revision ID: 20260401_0007 +Revises: 20260401_0006 +Create Date: 2026-04-01 21:10:00 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "20260401_0007" +down_revision = "20260401_0006" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + bind = op.get_bind() + bind.execute( + sa.text( + """ + UPDATE groups + SET department_id = users.primary_department_id + FROM users + WHERE groups.department_id IS NULL + AND groups.created_by_id = users.id + AND users.primary_department_id IS NOT NULL + """ + ) + ) + null_group_count = bind.execute(sa.text("SELECT COUNT(*) FROM groups WHERE department_id IS NULL")).scalar_one() + if null_group_count: + raise RuntimeError( + f"Cannot require group departments while {null_group_count} knowledge base(s) still have no department." + ) + op.alter_column("groups", "department_id", existing_type=sa.Integer(), nullable=False) + + +def downgrade() -> None: + op.alter_column("groups", "department_id", existing_type=sa.Integer(), nullable=True) diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 00000000..5fd5a349 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,28 @@ +fastapi==0.116.1 +uvicorn[standard]==0.35.0 +sqlalchemy==2.0.43 +alembic==1.16.5 +pydantic==2.11.9 +pydantic-settings==2.10.1 +python-multipart==0.0.20 +python-jose[cryptography]==3.5.0 +passlib[bcrypt]==1.7.4 +requests==2.32.5 +rq==2.6.0 +redis==6.4.0 +psycopg[binary]==3.2.11 +PyYAML==6.0.2 +networkx==3.5 +openpyxl==3.1.5 +python-docx==1.2.0 +rapidocr-onnxruntime==1.4.4 +pillow==11.3.0 +numpy==2.3.3 +pypdf==6.1.0 +pypdfium2==5.0.0 +python-pptx==1.0.2 +beautifulsoup4==4.14.2 +lxml==6.0.2 +typer==0.17.4 +pytest==8.4.2 +httpx==0.28.1 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 00000000..14bd8ab3 --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import os +import shutil +import sys +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +os.environ["DATABASE_URL"] = "sqlite:///./test_document_cleaning.db" +os.environ["DATA_ROOT"] = "./test_data" +os.environ["PUBLIC_BASE_URL"] = "http://testserver" +os.environ["INTEGRATION_API_KEY"] = "integration-secret" +os.environ["INTEGRATION_DOWNLOAD_SECRET"] = "integration-download-secret" +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.config import get_settings # noqa: E402 +from app.database import Base, get_db # noqa: E402 +from app.main import app # noqa: E402 +from app.models import Department, SystemSetting, User # noqa: E402 +from app.security import hash_password # noqa: E402 + + +TEST_DB = Path("./test_document_cleaning.db") +TEST_DATA_ROOT = Path("./test_data") +if TEST_DB.exists(): + TEST_DB.unlink() +if TEST_DATA_ROOT.exists(): + shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True) +TEST_DATA_ROOT.mkdir(parents=True, exist_ok=True) + +engine = create_engine("sqlite:///./test_document_cleaning.db", connect_args={"check_same_thread": False}) +TestingSessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True) + + +def override_get_db(): + db = TestingSessionLocal() + try: + yield db + finally: + db.close() + + +app.dependency_overrides[get_db] = override_get_db + + +@pytest.fixture +def initialized_db(): + Base.metadata.drop_all(bind=engine) + Base.metadata.create_all(bind=engine) + shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True) + get_settings().ensure_data_dirs() + db = TestingSessionLocal() + db.add( + Department( + id=1, + name="测试部门", + description="测试部门", + ) + ) + db.add( + SystemSetting( + id=1, + dify_permission="all_team_members", + indexing_technique="high_quality", + search_method="hybrid_search", + doc_form="text_model", + top_k=5, + score_threshold_enabled=True, + score_threshold="0.35", + ) + ) + db.add( + User( + username="admin", + full_name="System Admin", + password_hash=hash_password("admin123456"), + role="super_admin", + is_active=True, + primary_department_id=1, + ) + ) + db.add( + User( + username="adam", + full_name="Adam", + password_hash=hash_password("admin123456"), + role="admin", + is_active=True, + primary_department_id=1, + ) + ) + db.commit() + db.close() + yield + shutil.rmtree(TEST_DATA_ROOT, ignore_errors=True) + + +@pytest.fixture +def client(initialized_db): + with TestClient(app) as test_client: + yield test_client + + +@pytest.fixture +def db_session(initialized_db): + db = TestingSessionLocal() + try: + yield db + finally: + db.close() diff --git a/backend/tests/test_access_control_api.py b/backend/tests/test_access_control_api.py new file mode 100644 index 00000000..f5f58f30 --- /dev/null +++ b/backend/tests/test_access_control_api.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import uuid +from pathlib import Path + +from app.database import SessionLocal +from app.models import Department, Document, DocumentVersion, Group, User, UserDepartmentAccess +from app.security import hash_password + + +def _token(client, username: str, password: str): + response = client.post("/api/auth/login", json={"username": username, "password": password}) + return response.json()["access_token"] + + +def _headers(client, username: str, password: str): + return {"Authorization": f"Bearer {_token(client, username, password)}"} + + +def _seed_access_fixture() -> tuple[int, int]: + db = SessionLocal() + try: + super_admin = db.query(User).filter(User.username == "admin").first() + assert super_admin is not None + + blocked_department = Department(name=f"blocked-dept-{uuid.uuid4().hex[:6]}", description="blocked") + db.add(blocked_department) + db.commit() + db.refresh(blocked_department) + + scoped_user = User( + username="scoped-user", + full_name="Scoped User", + password_hash=hash_password("scoped123"), + role="user", + is_active=True, + primary_department_id=1, + ) + db.add(scoped_user) + db.commit() + db.refresh(scoped_user) + + allowed_group = Group(name=f"allowed-{uuid.uuid4().hex[:8]}", created_by_id=super_admin.id, department_id=1) + blocked_group = Group( + name=f"blocked-{uuid.uuid4().hex[:8]}", + created_by_id=super_admin.id, + department_id=blocked_department.id, + ) + db.add_all([allowed_group, blocked_group]) + db.commit() + db.refresh(allowed_group) + db.refresh(blocked_group) + + db.add(UserDepartmentAccess(user_id=scoped_user.id, department_id=1)) + db.commit() + + allowed_document = Document(group_id=allowed_group.id, title="allowed-doc", created_by_id=super_admin.id, is_deleted=False) + blocked_document = Document(group_id=blocked_group.id, title="blocked-doc", created_by_id=super_admin.id, is_deleted=False) + db.add_all([allowed_document, blocked_document]) + db.commit() + db.refresh(allowed_document) + db.refresh(blocked_document) + + db.add_all( + [ + DocumentVersion( + document_id=allowed_document.id, + version_no=1, + is_current=True, + source_filename="allowed.docx", + source_ext=".docx", + source_path=str(Path("allowed.docx")), + source_sha256=uuid.uuid4().hex, + file_size=12, + uploader_id=super_admin.id, + convert_status="success", + sync_status="unsynced", + ), + DocumentVersion( + document_id=blocked_document.id, + version_no=1, + is_current=True, + source_filename="blocked.docx", + source_ext=".docx", + source_path=str(Path("blocked.docx")), + source_sha256=uuid.uuid4().hex, + file_size=12, + uploader_id=super_admin.id, + convert_status="success", + sync_status="unsynced", + ), + ] + ) + db.commit() + return allowed_group.id, blocked_group.id + finally: + db.close() + + +def test_groups_and_files_are_scoped_by_user_access(client): + allowed_group_id, blocked_group_id = _seed_access_fixture() + headers = _headers(client, "scoped-user", "scoped123") + + groups_response = client.get("/api/groups", headers=headers) + assert groups_response.status_code == 200 + groups = groups_response.json()["data"] + assert len(groups) == 1 + assert groups[0]["id"] == allowed_group_id + + summary_response = client.get("/api/groups/summary", headers=headers) + assert summary_response.status_code == 200 + assert summary_response.json()["knowledge_base_count"] == 1 + assert summary_response.json()["file_count"] == 1 + + allowed_files = client.get(f"/api/groups/{allowed_group_id}/files", headers=headers) + blocked_files = client.get(f"/api/groups/{blocked_group_id}/files", headers=headers) + assert allowed_files.status_code == 200 + assert len(allowed_files.json()["data"]) == 1 + assert blocked_files.status_code == 403 diff --git a/backend/tests/test_admin_api.py b/backend/tests/test_admin_api.py new file mode 100644 index 00000000..403eee25 --- /dev/null +++ b/backend/tests/test_admin_api.py @@ -0,0 +1,699 @@ +from __future__ import annotations + +import json +import uuid +from datetime import timedelta + +from app.config import get_settings +from app.database import SessionLocal +from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess +from app.security import hash_password +from app.services.bootstrap_service import ensure_defaults +from app.time_utils import utc_now + + +def _token(client, username: str = "admin", password: str = "admin123456"): + response = client.post("/api/auth/login", json={"username": username, "password": password}) + return response.json()["access_token"] + + +def _headers(client, username: str = "admin", password: str = "admin123456"): + return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"} + + +def _create_user(*, username: str, password: str, role: str = "user", full_name: str = "User") -> int: + db = SessionLocal() + try: + user = User( + username=username, + full_name=full_name, + password_hash=hash_password(password), + role=role, + is_active=True, + primary_department_id=1, + ) + db.add(user) + db.commit() + db.refresh(user) + return user.id + finally: + db.close() + + +def _create_group(*, name: str) -> int: + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + group = Group(name=name, created_by_id=admin.id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + return group.id + finally: + db.close() + + +def _create_department(*, name: str, description: str = "test department") -> int: + db = SessionLocal() + try: + department = Department(name=name, description=description) + db.add(department) + db.commit() + db.refresh(department) + return department.id + finally: + db.close() + + +def _create_stale_syncing_document() -> tuple[int, str]: + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + admin_id = admin.id + + group = Group(name=f"health-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="stale-health", created_by_id=admin_id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="stale.docx", + source_ext=".docx", + source_path="/tmp/stale.docx", + source_sha256=uuid.uuid4().hex, + file_size=128, + uploader_id=admin_id, + convert_status="success", + sync_status="syncing", + ) + db.add(version) + db.commit() + db.refresh(version) + + old_time = utc_now() - timedelta(minutes=20) + job = Job( + id=str(uuid.uuid4()), + job_type="sync", + status="running", + group_id=group.id, + document_id=document.id, + version_id=version.id, + created_by_id=admin_id, + created_at=old_time, + started_at=old_time, + ) + db.add(job) + db.commit() + + record = DifySyncRecord( + version_id=version.id, + dataset_id="dataset-health", + remote_document_id="remote-health", + batch="batch-health", + status="syncing", + created_at=old_time, + updated_at=old_time, + ) + db.add(record) + db.commit() + return version.id, job.id + finally: + db.close() + + +def _create_stale_convert_document() -> tuple[int, str]: + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + admin_id = admin.id + + group = Group(name=f"convert-health-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="convert-stale-health", created_by_id=admin_id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + old_time = utc_now() - timedelta(minutes=20) + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="convert-stale.docx", + source_ext=".docx", + source_path="/tmp/convert-stale.docx", + source_sha256=uuid.uuid4().hex, + file_size=128, + uploader_id=admin_id, + convert_status="queued", + sync_status="unsynced", + uploaded_at=old_time, + ) + db.add(version) + db.commit() + db.refresh(version) + + job = Job( + id=str(uuid.uuid4()), + job_type="convert", + status="queued", + queue_job_id="missing-convert-job", + group_id=group.id, + document_id=document.id, + version_id=version.id, + created_by_id=admin_id, + created_at=old_time, + ) + db.add(job) + db.commit() + return version.id, job.id + finally: + db.close() + + +def test_admin_can_create_and_update_users(client): + group_id = _create_group(name=f"access-{uuid.uuid4().hex[:8]}") + create_response = client.post( + "/api/admin/users", + json={ + "username": "operator", + "password": "operator123", + "full_name": "Ops User", + "role": "user", + "primary_department_id": 1, + "accessible_department_ids": [1], + }, + headers=_headers(client), + ) + assert create_response.status_code == 200 + assert create_response.json()["username"] == "operator" + assert create_response.json()["accessible_department_ids"] == [1] + + db = SessionLocal() + try: + user = db.query(User).filter(User.username == "operator").first() + assert user is not None + user_id = user.id + finally: + db.close() + + update_response = client.patch( + f"/api/admin/users/{user_id}", + json={ + "full_name": "Operations User", + "role": "admin", + "is_active": False, + "primary_department_id": 1, + "accessible_department_ids": [1], + }, + headers=_headers(client), + ) + assert update_response.status_code == 200 + body = update_response.json() + assert body["full_name"] == "Operations User" + assert body["role"] == "admin" + assert body["is_active"] is False + assert body["accessible_department_ids"] == [1] + + +def test_admin_can_delete_user_and_clear_created_by_references(client): + user_id = _create_user(username=f"delete-user-{uuid.uuid4().hex[:8]}", password="delete123", role="user", full_name="Delete User") + + db = SessionLocal() + try: + user = db.query(User).filter(User.id == user_id).first() + admin = db.query(User).filter(User.username == "admin").first() + assert user is not None + assert admin is not None + + group = Group(name=f"delete-user-group-{uuid.uuid4().hex[:8]}", created_by_id=user_id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title=f"delete-user-doc-{uuid.uuid4().hex[:8]}", created_by_id=user_id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="delete-user.docx", + source_ext=".docx", + source_path="/tmp/delete-user.docx", + source_sha256=uuid.uuid4().hex, + file_size=128, + uploader_id=user_id, + convert_status="success", + sync_status="unsynced", + ) + db.add(version) + db.add(Job(id=str(uuid.uuid4()), job_type="convert", status="success", created_by_id=user_id, document_id=document.id, version_id=version.id)) + db.commit() + + group_id = group.id + document_id = document.id + version_id = version.id + finally: + db.close() + + response = client.delete(f"/api/admin/users/{user_id}", headers=_headers(client)) + assert response.status_code == 200 + assert response.json()["deleted_user_id"] == user_id + + db = SessionLocal() + try: + assert db.query(User).filter(User.id == user_id).first() is None + + group = db.query(Group).filter(Group.id == group_id).first() + document = db.query(Document).filter(Document.id == document_id).first() + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.document_id == document_id).first() + + assert group is not None and group.created_by_id is None + assert document is not None and document.created_by_id is None + assert version is not None and version.uploader_id is None + assert job is not None and job.created_by_id is None + finally: + db.close() + + +def test_admin_delete_protects_primary_super_admin_and_self(client): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + admin_id = admin.id + finally: + db.close() + + delete_admin = client.delete(f"/api/admin/users/{admin_id}", headers=_headers(client)) + assert delete_admin.status_code == 400 + assert "cannot be deleted" in delete_admin.json()["detail"] + + username = f"self-delete-{uuid.uuid4().hex[:8]}" + user_id = _create_user(username=username, password="self123", role="admin", full_name="Self Delete") + self_delete = client.delete( + f"/api/admin/users/{user_id}", + headers=_headers(client, username=username, password="self123"), + ) + assert self_delete.status_code == 400 + assert "cannot delete your own account" in self_delete.json()["detail"].lower() + + +def test_only_admin_can_hold_super_admin_role(client): + create_response = client.post( + "/api/admin/users", + json={ + "username": "other-super", + "password": "operator123", + "full_name": "Other Super", + "role": "super_admin", + "primary_department_id": 1, + "accessible_department_ids": [], + }, + headers=_headers(client), + ) + assert create_response.status_code == 400 + assert "Only admin can be a super admin" in create_response.json()["detail"] + + db = SessionLocal() + try: + admin_user = db.query(User).filter(User.username == "admin").first() + operator = User( + username="operator-promote", + full_name="Operator Promote", + password_hash=hash_password("operator123"), + role="admin", + is_active=True, + primary_department_id=1, + ) + db.add(operator) + db.commit() + db.refresh(operator) + assert admin_user is not None + operator_id = operator.id + admin_id = admin_user.id + finally: + db.close() + + promote_response = client.patch( + f"/api/admin/users/{operator_id}", + json={"role": "super_admin"}, + headers=_headers(client), + ) + assert promote_response.status_code == 400 + assert "Only admin can be a super admin" in promote_response.json()["detail"] + + demote_admin = client.patch( + f"/api/admin/users/{admin_id}", + json={"role": "admin"}, + headers=_headers(client), + ) + assert demote_admin.status_code == 400 + assert "admin must remain a super admin" in demote_admin.json()["detail"] + + +def test_bootstrap_keeps_admin_as_unique_super_admin(): + db = SessionLocal() + try: + rogue = User( + username="legacy-super", + full_name="Legacy Super", + password_hash=hash_password("legacy123"), + role="super_admin", + is_active=True, + primary_department_id=None, + ) + db.add(rogue) + db.commit() + + ensure_defaults(db) + + admin = db.query(User).filter(User.username == "admin").first() + legacy = db.query(User).filter(User.username == "legacy-super").first() + adam = db.query(User).filter(User.username == "adam").first() + assert admin is not None + assert admin.role == "super_admin" + assert legacy is not None + assert legacy.role == "admin" + assert legacy.primary_department_id is None + assert adam is not None + assert adam.role == "admin" + finally: + db.close() + + +def test_admin_can_read_and_update_settings(client): + initial = client.get("/api/admin/settings", headers=_headers(client)) + assert initial.status_code == 200 + assert initial.json()["search_method"] == "hybrid_search" + + updated = client.patch( + "/api/admin/settings", + json={ + "search_method": "semantic_search", + "top_k": 8, + "score_threshold_enabled": False, + "score_threshold": 0.4, + "embedding_model_provider": "langgenius/siliconflow/siliconflow", + "embedding_model": "Qwen/Qwen3-Embedding-8B", + "reranking_model_provider": "langgenius/siliconflow/siliconflow", + "reranking_model": "Qwen/Qwen3-Reranker-8B", + }, + headers=_headers(client), + ) + assert updated.status_code == 200 + body = updated.json() + assert body["search_method"] == "semantic_search" + assert body["top_k"] == 8 + assert body["score_threshold_enabled"] is False + assert body["score_threshold"] == 0.4 + assert body["embedding_model_provider"] == "langgenius/siliconflow/siliconflow" + assert body["embedding_model"] == "Qwen/Qwen3-Embedding-8B" + assert body["reranking_model_provider"] == "langgenius/siliconflow/siliconflow" + assert body["reranking_model"] == "Qwen/Qwen3-Reranker-8B" + + +def test_empty_department_can_be_deleted(client): + department_id = _create_department(name=f"empty-dept-{uuid.uuid4().hex[:8]}") + + response = client.request( + "DELETE", + f"/api/admin/departments/{department_id}", + headers=_headers(client), + json={"target_department_id": None}, + ) + assert response.status_code == 200 + assert response.json()["deleted_department_id"] == department_id + + db = SessionLocal() + try: + assert db.query(Department).filter(Department.id == department_id).first() is None + finally: + db.close() + + +def test_department_delete_requires_migration_when_department_is_in_use(client): + source_department_id = _create_department(name=f"source-dept-{uuid.uuid4().hex[:8]}") + + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + group = Group(name=f"in-use-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id) + db.add(group) + db.commit() + finally: + db.close() + + response = client.request( + "DELETE", + f"/api/admin/departments/{source_department_id}", + headers=_headers(client), + json={"target_department_id": None}, + ) + assert response.status_code == 400 + assert "Choose another department to migrate first" in response.json()["detail"] + + +def test_department_delete_can_migrate_knowledge_bases_and_user_access(client): + source_department_id = _create_department(name=f"source-migrate-{uuid.uuid4().hex[:8]}") + target_department_id = _create_department(name=f"target-migrate-{uuid.uuid4().hex[:8]}") + operator_id = _create_user(username=f"dept-user-{uuid.uuid4().hex[:8]}", password="operator123", role="user", full_name="Dept User") + + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + operator = db.query(User).filter(User.id == operator_id).first() + assert admin is not None + assert operator is not None + + admin.primary_department_id = target_department_id + operator.primary_department_id = source_department_id + db.add(UserDepartmentAccess(user_id=admin.id, department_id=source_department_id)) + + group = Group(name=f"migrate-group-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=source_department_id) + db.add(group) + db.commit() + db.refresh(group) + group_id = group.id + admin_id = admin.id + finally: + db.close() + + response = client.request( + "DELETE", + f"/api/admin/departments/{source_department_id}", + headers=_headers(client), + json={"target_department_id": target_department_id}, + ) + assert response.status_code == 200 + payload = response.json() + assert payload["migrated_to_department_id"] == target_department_id + assert payload["knowledge_base_count"] == 1 + assert payload["primary_user_count"] == 1 + assert payload["extra_user_count"] == 1 + + db = SessionLocal() + try: + assert db.query(Department).filter(Department.id == source_department_id).first() is None + + group = db.query(Group).filter(Group.id == group_id).first() + operator = db.query(User).filter(User.id == operator_id).first() + admin = db.query(User).filter(User.id == admin_id).first() + assert group is not None + assert operator is not None + assert admin is not None + assert group.department_id == target_department_id + assert operator.primary_department_id == target_department_id + assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == source_department_id).first() is None + assert db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id, UserDepartmentAccess.department_id == target_department_id).first() is None + finally: + db.close() + + +def test_admin_can_read_available_dify_models(client, monkeypatch): + class FakeDifyService: + def list_available_embedding_models(self): + return [ + type("Model", (), {"provider": "provider-a", "model": "embed-a", "label": "Provider A / embed-a"})() + ] + + def list_available_rerank_models(self): + return [ + type("Model", (), {"provider": "provider-b", "model": "rerank-b", "label": "Provider B / rerank-b"})() + ] + + def resolve_embedding_model_choice(self, *, provider=None, model=None): + return ("provider-a", "embed-a") + + def resolve_rerank_model_choice(self, *, provider=None, model=None): + return ("provider-b", "rerank-b") + + monkeypatch.setattr("app.api.admin.DifyService", FakeDifyService) + + response = client.get("/api/admin/dify-models", headers=_headers(client)) + assert response.status_code == 200 + payload = response.json() + assert payload["embedding_models"][0]["model"] == "embed-a" + assert payload["rerank_models"][0]["model"] == "rerank-b" + assert payload["automatic_defaults"] == { + "embedding_model_provider": "provider-a", + "embedding_model": "embed-a", + "reranking_model_provider": "provider-b", + "reranking_model": "rerank-b", + } + + +def test_admin_endpoints_require_admin_and_job_list_scopes_by_user(client): + user_id = _create_user(username="viewer", password="viewer123", role="user", full_name="Viewer") + admin_id = _create_user(username="ops-admin", password="ops123456", role="admin", full_name="Ops Admin") + admin_headers = _headers(client) + user_headers = _headers(client, username="viewer", password="viewer123") + ops_headers = _headers(client, username="ops-admin", password="ops123456") + + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + group = Group(name=f"ops-scope-{uuid.uuid4().hex[:8]}", created_by_id=admin.id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + db.add(UserDepartmentAccess(user_id=admin_id, department_id=1)) + db.add_all( + [ + Job( + id=str(uuid.uuid4()), + job_type="convert", + status="success", + created_by_id=admin.id, + group_id=group.id, + payload={"owner": "admin"}, + ), + Job( + id=str(uuid.uuid4()), + job_type="sync", + status="queued", + created_by_id=user_id, + payload={"owner": "viewer"}, + ), + Job( + id=str(uuid.uuid4()), + job_type="sync", + status="queued", + created_by_id=admin_id, + group_id=group.id, + payload={"owner": "ops-admin"}, + ), + ] + ) + db.commit() + finally: + db.close() + + forbidden_users = client.get("/api/admin/users", headers=user_headers) + forbidden_settings = client.get("/api/admin/settings", headers=user_headers) + allowed_user_admin = client.get("/api/admin/users", headers=ops_headers) + allowed_health_admin = client.get("/api/admin/dify-health", headers=ops_headers) + assert forbidden_users.status_code == 403 + assert forbidden_settings.status_code == 403 + assert allowed_user_admin.status_code == 200 + assert allowed_health_admin.status_code == 200 + + admin_jobs = client.get("/api/jobs", headers=admin_headers) + assert admin_jobs.status_code == 200 + assert len(admin_jobs.json()["data"]) == 3 + + user_jobs = client.get("/api/jobs", headers=user_headers) + assert user_jobs.status_code == 200 + assert len(user_jobs.json()["data"]) == 1 + assert user_jobs.json()["data"][0]["payload"] == {"owner": "viewer"} + + ops_jobs = client.get("/api/jobs", headers=ops_headers) + assert ops_jobs.status_code == 200 + assert len(ops_jobs.json()["data"]) == 2 + + +def test_admin_dify_health_reads_snapshot_and_local_summary(client): + path = get_settings().data_root / "watchdog" / "dify-health.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps( + { + "status": "ok", + "queue_lengths": {"priority_dataset": 1}, + "worker": {"concurrency": 2}, + } + ), + encoding="utf-8", + ) + _create_stale_syncing_document() + + response = client.get("/api/admin/dify-health", headers=_headers(client)) + assert response.status_code == 200 + payload = response.json() + assert payload["watchdog_snapshot"]["worker"]["concurrency"] == 2 + assert payload["local_convert_health"]["pending_versions"] == 0 + assert payload["local_sync_health"]["stale_candidates"] == 1 + assert payload["dify_api_configured"] is False + + +def test_admin_can_recover_stale_syncs(client): + version_id, job_id = _create_stale_syncing_document() + + response = client.post("/api/admin/recover-stale-syncs", headers=_headers(client)) + assert response.status_code == 200 + payload = response.json() + assert payload["recovered_versions"] == 1 + assert payload["recovered_jobs"] == 1 + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + assert version is not None + assert job is not None + assert version.sync_status == "sync_failed" + assert job.status == "failed" + finally: + db.close() + + +def test_admin_can_recover_stale_converts(client, monkeypatch): + version_id, job_id = _create_stale_convert_document() + monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set()) + + response = client.post("/api/admin/recover-stale-converts", headers=_headers(client)) + assert response.status_code == 200 + payload = response.json() + assert payload["recovered_versions"] == 1 + assert payload["recovered_jobs"] == 1 + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + assert version is not None + assert job is not None + assert version.convert_status == "failed" + assert job.status == "failed" + finally: + db.close() diff --git a/backend/tests/test_config_settings.py b/backend/tests/test_config_settings.py new file mode 100644 index 00000000..b1bed619 --- /dev/null +++ b/backend/tests/test_config_settings.py @@ -0,0 +1,24 @@ +from app.config import Settings + + +def test_settings_default_to_sqlite_when_no_database_url_override(): + settings = Settings(database_url="", database_backend="sqlite") + assert settings.database_url == "sqlite:///./document_cleaning.db" + + +def test_settings_select_postgres_url_from_backend_choice(): + settings = Settings( + database_url="", + database_backend="postgres", + postgres_database_url="postgresql://postgres:difyai123456@localhost:5432/doccleaning_db", + ) + assert settings.database_url == "postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db" + + +def test_settings_keep_database_url_override_highest_priority(): + settings = Settings( + database_backend="sqlite", + database_url="postgresql://postgres:difyai123456@localhost:5432/doccleaning_db", + sqlite_database_url="sqlite:///./other.db", + ) + assert settings.database_url == "postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db" diff --git a/backend/tests/test_files_api.py b/backend/tests/test_files_api.py new file mode 100644 index 00000000..b8d9da83 --- /dev/null +++ b/backend/tests/test_files_api.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +import uuid +from pathlib import Path +from types import SimpleNamespace + +from app.config import get_settings +from app.database import SessionLocal +from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User +from app.services.storage_service import version_dir + + +def _token(client, username: str = "admin", password: str = "admin123456"): + response = client.post("/api/auth/login", json={"username": username, "password": password}) + return response.json()["access_token"] + + +def _headers(client, username: str = "admin", password: str = "admin123456"): + return {"Authorization": f"Bearer {_token(client, username=username, password=password)}"} + + +def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, Path, Path, Path]: + settings = get_settings() + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + + group = Group(name=f"delete-{uuid.uuid4().hex[:8]}", description="Delete coverage", created_by_id=admin.id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + source_root = version_dir("original", group.id, document.id, 1) + markdown_root = version_dir("markdown", group.id, document.id, 1) + assets_root = version_dir("assets", group.id, document.id, 1) + source_root.mkdir(parents=True, exist_ok=True) + markdown_root.mkdir(parents=True, exist_ok=True) + assets_root.mkdir(parents=True, exist_ok=True) + + source_path = source_root / "manual.docx" + markdown_path = markdown_root / "document.md" + asset_path = assets_root / "img_001.png" + source_path.write_bytes(b"source") + markdown_path.write_text("# Manual", encoding="utf-8") + asset_path.write_bytes(b"png") + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="manual.docx", + source_ext=".docx", + source_path=str(source_path), + source_sha256=uuid.uuid4().hex, + md_path=str(markdown_path), + md_public_url="http://testserver/storage/markdown/document.md", + asset_dir=str(assets_root.relative_to(settings.data_root)), + file_size=source_path.stat().st_size, + uploader_id=admin.id, + convert_status="success", + sync_status="synced" if with_remote_sync else "unsynced", + ) + db.add(version) + db.commit() + db.refresh(version) + + if with_remote_sync: + db.add( + DifySyncRecord( + version_id=version.id, + dataset_id="dataset-001", + remote_document_id="remote-001", + status="synced", + ) + ) + db.commit() + + return document.id, source_root, markdown_root, assets_root + finally: + db.close() + + +def test_delete_file_marks_document_deleted_and_enqueues_cleanup(client, monkeypatch): + document_id, source_root, markdown_root, assets_root = _seed_document_for_delete(with_remote_sync=False) + enqueue_calls: list[tuple[str, tuple[object, ...]]] = [] + + class FakeQueue: + def enqueue(self, task_name: str, *args, **kwargs): + enqueue_calls.append((task_name, args)) + return SimpleNamespace(id="queued-delete-job") + + monkeypatch.setattr("app.api.files.get_queue", lambda: FakeQueue()) + + response = client.delete(f"/api/files/{document_id}?delete_dify=false", headers=_headers(client)) + assert response.status_code == 200 + assert response.json() == {"deleted": True} + + db = SessionLocal() + try: + document = db.query(Document).filter(Document.id == document_id).first() + job = db.query(Job).filter(Job.document_id == document_id, Job.job_type == "delete").first() + assert document is not None + assert job is not None + assert document.is_deleted is True + assert "__deleted__" in document.title + finally: + db.close() + + assert enqueue_calls + assert enqueue_calls[0][0] == "app.tasks.run_delete_document_job" + assert enqueue_calls[0][1][1] == document_id + assert source_root.exists() + assert markdown_root.exists() + assert assets_root.exists() + + +def test_batch_markdown_download_returns_zip_file(client): + document_id, source_root, markdown_root, assets_root = _seed_document_for_delete(with_remote_sync=False) + + response = client.post( + "/api/files/download-batch", + json={"document_ids": [document_id], "kind": "md"}, + headers=_headers(client), + ) + + assert response.status_code == 200 + assert "zip" in response.headers["content-type"] + assert len(response.content) > 0 + + +def test_sync_endpoint_rejects_already_synced_current_version(client): + settings = get_settings() + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + group = Group(name=f"sync-{uuid.uuid4().hex[:8]}", description="Sync coverage", created_by_id=admin.id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="already-synced", created_by_id=admin.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + markdown_root = version_dir("markdown", group.id, document.id, 1) + markdown_root.mkdir(parents=True, exist_ok=True) + markdown_path = markdown_root / "document.md" + markdown_path.write_text("# Synced", encoding="utf-8") + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="already-synced.docx", + source_ext=".docx", + source_path=str(settings.data_root / "tmp" / "already-synced.docx"), + source_sha256=uuid.uuid4().hex, + md_path=str(markdown_path), + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="synced", + ) + db.add(version) + db.commit() + db.refresh(version) + + db.add( + DifySyncRecord( + version_id=version.id, + dataset_id="dataset-001", + remote_document_id="remote-001", + status="synced", + ) + ) + db.commit() + file_id = document.id + finally: + db.close() + + response = client.post(f"/api/files/{file_id}/sync-dify", headers=_headers(client)) + assert response.status_code == 409 + assert response.json()["detail"] == "Current version is already synced to Dify." + + +def test_sync_endpoint_rejects_current_version_already_syncing(client): + settings = get_settings() + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + group = Group(name=f"syncing-{uuid.uuid4().hex[:8]}", description="Sync coverage", created_by_id=admin.id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="already-syncing", created_by_id=admin.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + markdown_root = version_dir("markdown", group.id, document.id, 1) + markdown_root.mkdir(parents=True, exist_ok=True) + markdown_path = markdown_root / "document.md" + markdown_path.write_text("# Syncing", encoding="utf-8") + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="already-syncing.docx", + source_ext=".docx", + source_path=str(settings.data_root / "tmp" / "already-syncing.docx"), + source_sha256=uuid.uuid4().hex, + md_path=str(markdown_path), + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="syncing", + ) + db.add(version) + db.commit() + db.refresh(version) + file_id = document.id + finally: + db.close() + + response = client.post(f"/api/files/{file_id}/sync-dify", headers=_headers(client)) + assert response.status_code == 409 + assert response.json()["detail"] == "Current version is already syncing to Dify." diff --git a/backend/tests/test_integration_api.py b/backend/tests/test_integration_api.py new file mode 100644 index 00000000..fa80ee67 --- /dev/null +++ b/backend/tests/test_integration_api.py @@ -0,0 +1,266 @@ +from __future__ import annotations + +import uuid + +from app.config import get_settings +from app.database import Base, SessionLocal +from app.models import DifySyncRecord, Document, DocumentVersion, Group, User +from app.services.storage_service import version_dir + + +def _integration_headers() -> dict[str, str]: + return {"X-Integration-Key": "integration-secret"} + + +def _seed_integration_document() -> tuple[int, int]: + settings = get_settings() + db = SessionLocal() + try: + Base.metadata.create_all(bind=db.get_bind()) + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + + group = Group( + name=f"integration-group-{uuid.uuid4().hex[:8]}", + description="Integration coverage", + created_by_id=admin.id, + department_id=1, + dify_dataset_id="dataset-integration", + ) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="integration-file", created_by_id=admin.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + source_root = version_dir("original", group.id, document.id, 1) + markdown_root = version_dir("markdown", group.id, document.id, 1) + assets_root = version_dir("assets", group.id, document.id, 1) + source_root.mkdir(parents=True, exist_ok=True) + markdown_root.mkdir(parents=True, exist_ok=True) + assets_root.mkdir(parents=True, exist_ok=True) + + source_path = source_root / "integration-file.docx" + markdown_path = markdown_root / "document.md" + source_path.write_bytes(b"source") + markdown_path.write_text("# Integration", encoding="utf-8") + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="integration-file.docx", + source_ext=".docx", + source_path=str(source_path), + source_sha256=uuid.uuid4().hex, + md_path=str(markdown_path), + md_public_url=f"{settings.public_base_url}/storage/{markdown_path.relative_to(settings.data_root).as_posix()}", + asset_dir=str(assets_root.relative_to(settings.data_root)), + file_size=source_path.stat().st_size, + uploader_id=admin.id, + convert_status="success", + sync_status="synced", + ) + db.add(version) + db.commit() + db.refresh(version) + + db.add( + DifySyncRecord( + version_id=version.id, + dataset_id="dataset-integration", + remote_document_id="remote-integration", + status="synced", + ) + ) + db.commit() + + return group.id, document.id + finally: + db.close() + + +def test_integration_api_requires_service_key(client): + response = client.get("/api/integration/knowledge-bases") + assert response.status_code == 401 + + +def test_integration_api_requires_download_secret(client): + settings = get_settings() + previous_key = settings.integration_api_key + previous_secret = settings.integration_download_secret + settings.integration_api_key = "integration-secret" + settings.integration_download_secret = "" + try: + _seed_integration_document() + response = client.get("/api/integration/files/1", headers=_integration_headers()) + assert response.status_code == 503 + assert response.json()["detail"] == "Integration download secret is not configured." + finally: + settings.integration_api_key = previous_key + settings.integration_download_secret = previous_secret + + +def test_integration_api_lists_knowledge_bases_and_files(client, monkeypatch): + settings = get_settings() + previous_key = settings.integration_api_key + settings.integration_api_key = "integration-secret" + try: + group_id, document_id = _seed_integration_document() + + knowledge_bases = client.get("/api/integration/knowledge-bases", headers=_integration_headers()) + assert knowledge_bases.status_code == 200 + kb_payload = knowledge_bases.json()["data"] + assert len(kb_payload) == 1 + assert kb_payload[0]["id"] == group_id + assert kb_payload[0]["dify_dataset_id"] == "dataset-integration" + + files = client.get(f"/api/integration/knowledge-bases/{group_id}/files", headers=_integration_headers()) + assert files.status_code == 200 + file_payload = files.json()["data"] + assert len(file_payload) == 1 + assert file_payload[0]["document_id"] == document_id + assert file_payload[0]["source_filename"] == "integration-file.docx" + assert "/api/integration/download?version_id=" in file_payload[0]["source_download_url"] + assert file_payload[0]["markdown_download_url"] is not None + assert file_payload[0]["queried_at"] is not None + assert file_payload[0]["download_url_expires_at"] is not None + + detail = client.get(f"/api/integration/files/{document_id}", headers=_integration_headers()) + assert detail.status_code == 200 + detail_payload = detail.json() + assert detail_payload["knowledge_base"]["id"] == group_id + assert detail_payload["dify"]["remote_document_id"] == "remote-integration" + finally: + settings.integration_api_key = previous_key + + +def test_integration_api_downloads_source_and_markdown(client): + settings = get_settings() + previous_key = settings.integration_api_key + settings.integration_api_key = "integration-secret" + try: + _, document_id = _seed_integration_document() + + detail = client.get(f"/api/integration/files/{document_id}", headers=_integration_headers()) + assert detail.status_code == 200 + payload = detail.json() + + source_download = client.get(payload["source_download_url"].replace("http://testserver", "")) + assert source_download.status_code == 200 + assert "integration-file.docx" in source_download.headers["content-disposition"] + + markdown_download = client.get(payload["markdown_download_url"].replace("http://testserver", "")) + assert markdown_download.status_code == 200 + assert "integration-file.md" in markdown_download.headers["content-disposition"] + finally: + settings.integration_api_key = previous_key + + +def test_integration_api_can_lookup_local_file_by_dify_ids(client): + settings = get_settings() + previous_key = settings.integration_api_key + settings.integration_api_key = "integration-secret" + try: + group_id, document_id = _seed_integration_document() + + response = client.get( + "/api/integration/dify-file?dataset_id=dataset-integration&remote_document_id=remote-integration", + headers=_integration_headers(), + ) + assert response.status_code == 200 + payload = response.json() + assert payload["document_id"] == document_id + assert payload["knowledge_base"]["id"] == group_id + assert payload["dify"]["dataset_id"] == "dataset-integration" + assert payload["dify"]["remote_document_id"] == "remote-integration" + assert "version_id=" in payload["source_download_url"] + finally: + settings.integration_api_key = previous_key + + +def test_integration_api_lookup_by_dify_ids_uses_matched_version_not_unsynced_current_version(client): + settings = get_settings() + previous_key = settings.integration_api_key + settings.integration_api_key = "integration-secret" + try: + _, document_id = _seed_integration_document() + db = SessionLocal() + try: + document = db.query(Document).filter(Document.id == document_id).first() + assert document is not None + current_version = document.versions[0] + current_version.is_current = False + new_root = version_dir("original", document.group_id, document.id, 2) + new_root.mkdir(parents=True, exist_ok=True) + new_source = new_root / "integration-file-v2.docx" + new_source.write_bytes(b"new-source") + new_version = DocumentVersion( + document_id=document.id, + version_no=2, + is_current=True, + source_filename="integration-file-v2.docx", + source_ext=".docx", + source_path=str(new_source), + source_sha256=uuid.uuid4().hex, + file_size=new_source.stat().st_size, + uploader_id=document.created_by_id, + convert_status="success", + sync_status="unsynced", + ) + db.add(new_version) + db.commit() + finally: + db.close() + + response = client.get( + "/api/integration/dify-file?dataset_id=dataset-integration&remote_document_id=remote-integration", + headers=_integration_headers(), + ) + assert response.status_code == 200 + payload = response.json() + assert payload["source_filename"] == "integration-file.docx" + assert payload["dify"]["remote_document_id"] == "remote-integration" + assert "version_id=1" in payload["source_download_url"] + finally: + settings.integration_api_key = previous_key + + +def test_integration_api_can_batch_resolve_by_dify_ids(client): + settings = get_settings() + previous_key = settings.integration_api_key + settings.integration_api_key = "integration-secret" + try: + _, document_id = _seed_integration_document() + + response = client.post( + "/api/integration/dify-files/resolve", + headers=_integration_headers(), + json={ + "items": [ + {"dataset_id": "dataset-integration", "remote_document_id": "remote-integration"}, + {"dataset_id": "dataset-integration", "remote_document_id": "remote-missing"}, + {"remote_document_id": "remote-integration"}, + ] + }, + ) + assert response.status_code == 200 + payload = response.json()["data"] + assert len(payload) == 3 + + assert payload[0]["request"]["remote_document_id"] == "remote-integration" + assert payload[0]["found"] is True + assert payload[0]["document"]["document_id"] == document_id + + assert payload[1]["request"]["remote_document_id"] == "remote-missing" + assert payload[1]["found"] is False + assert payload[1]["document"] is None + + assert payload[2]["request"]["dataset_id"] is None + assert payload[2]["found"] is True + assert payload[2]["document"]["dify"]["remote_document_id"] == "remote-integration" + finally: + settings.integration_api_key = previous_key diff --git a/backend/tests/test_tasks.py b/backend/tests/test_tasks.py new file mode 100644 index 00000000..965cef6f --- /dev/null +++ b/backend/tests/test_tasks.py @@ -0,0 +1,937 @@ +from __future__ import annotations + +import base64 +import uuid +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import app.tasks as task_module +from app.config import get_settings +from app.database import SessionLocal +from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User +from app.services.dify_service import DifyError +from app.services.storage_service import version_dir + + +def _seed_document_version( + *, + source_filename: str = "policy.docx", + title: str = "policy", + convert_status: str = "queued", + sync_status: str = "unsynced", + markdown_text: str | None = None, +) -> tuple[int, int, int, int]: + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + + group = Group(name=f"group-{uuid.uuid4().hex[:8]}", description="Task coverage", created_by_id=admin.id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title=title, created_by_id=admin.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + source_root = version_dir("original", group.id, document.id, 1) + source_root.mkdir(parents=True, exist_ok=True) + source_path = source_root / source_filename + source_path.write_bytes(b"source document") + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename=source_filename, + source_ext=Path(source_filename).suffix.lower(), + source_path=str(source_path), + source_sha256=uuid.uuid4().hex, + file_size=source_path.stat().st_size, + uploader_id=admin.id, + convert_status=convert_status, + sync_status=sync_status, + ) + db.add(version) + db.commit() + db.refresh(version) + + if markdown_text is not None: + markdown_root = version_dir("markdown", group.id, document.id, version.version_no) + markdown_root.mkdir(parents=True, exist_ok=True) + markdown_path = markdown_root / "document.md" + markdown_path.write_text(markdown_text, encoding="utf-8") + version.md_path = str(markdown_path) + db.commit() + + return group.id, document.id, version.id, admin.id + finally: + db.close() + + +def _seed_job( + *, + job_type: str, + group_id: int, + document_id: int, + version_id: int, + created_by_id: int, +) -> str: + db = SessionLocal() + try: + job = Job( + id=str(uuid.uuid4()), + job_type=job_type, + status="queued", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=created_by_id, + payload={}, + ) + db.add(job) + db.commit() + return job.id + finally: + db.close() + + +def _seed_document_for_delete(*, with_remote_sync: bool) -> tuple[int, int, int, int, Path, Path, Path]: + settings = get_settings() + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + + group = Group( + name=f"delete-{uuid.uuid4().hex[:8]}", + description="Delete coverage", + created_by_id=admin.id, + department_id=1, + ) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="manual", created_by_id=admin.id, is_deleted=True) + db.add(document) + db.commit() + db.refresh(document) + + source_root = version_dir("original", group.id, document.id, 1) + markdown_root = version_dir("markdown", group.id, document.id, 1) + assets_root = version_dir("assets", group.id, document.id, 1) + source_root.mkdir(parents=True, exist_ok=True) + markdown_root.mkdir(parents=True, exist_ok=True) + assets_root.mkdir(parents=True, exist_ok=True) + + source_path = source_root / "manual.docx" + markdown_path = markdown_root / "document.md" + asset_path = assets_root / "img_001.png" + source_path.write_bytes(b"source") + markdown_path.write_text("# Manual", encoding="utf-8") + asset_path.write_bytes(b"png") + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="manual.docx", + source_ext=".docx", + source_path=str(source_path), + source_sha256=uuid.uuid4().hex, + md_path=str(markdown_path), + md_public_url="http://testserver/storage/markdown/document.md", + asset_dir=str(assets_root.relative_to(settings.data_root)), + file_size=source_path.stat().st_size, + uploader_id=admin.id, + convert_status="success", + sync_status="synced" if with_remote_sync else "unsynced", + ) + db.add(version) + db.commit() + db.refresh(version) + + if with_remote_sync: + db.add( + DifySyncRecord( + version_id=version.id, + dataset_id="dataset-001", + remote_document_id="remote-001", + status="synced", + ) + ) + db.commit() + + return group.id, document.id, version.id, admin.id, source_root, markdown_root, assets_root + finally: + db.close() + + +def test_convert_job_success_updates_version_and_job(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version() + job_id = _seed_job( + job_type="convert", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object())) + + def fake_build_knowledge(source_path, output_dir, config, cache_dir): + generated_dir = output_dir / "generated" + generated_dir.mkdir(parents=True, exist_ok=True) + (generated_dir / "document.md").write_text("# Policy\n\nConverted content", encoding="utf-8") + return [{"status": "success"}] + + monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge) + + task_module.run_convert_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + assert version is not None + assert job is not None + assert version.convert_status == "success" + assert version.sync_status == "unsynced" + assert version.md_path is not None + assert Path(version.md_path).exists() + assert Path(version.md_path).read_text(encoding="utf-8") == "# Policy\n\nConverted content" + assert version.word_count == 4 + assert version.warnings_json == [{"message": "embedded_images=0"}] + assert job.status == "success" + assert job.message == "Conversion completed" + assert job.result == { + "md_path": version.md_path, + "md_public_url": version.md_public_url, + "image_count": 0, + } + finally: + db.close() + + +def test_convert_job_success_rewrites_embedded_images_to_local_asset_urls(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version() + job_id = _seed_job( + job_type="convert", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object())) + + def fake_build_knowledge(source_path, output_dir, config, cache_dir): + generated_dir = output_dir / "generated" + generated_dir.mkdir(parents=True, exist_ok=True) + image_bytes = base64.b64encode(b"fake-image").decode("ascii") + markdown = f"# Policy\n\n![image-1](data:image/png;base64,{image_bytes})" + (generated_dir / "document.md").write_text(markdown, encoding="utf-8") + return [{"status": "success"}] + + monkeypatch.setattr(task_module, "build_knowledge", fake_build_knowledge) + + task_module.run_convert_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + assert version is not None + assert version.asset_dir is not None + assert version.md_path is not None + markdown = Path(version.md_path).read_text(encoding="utf-8") + assert "http://testserver/storage/assets/" in markdown + assert "data:image" not in markdown + finally: + db.close() + + +def test_convert_job_failure_marks_job_and_version_failed(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version() + job_id = _seed_job( + job_type="convert", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + monkeypatch.setattr(task_module.SystemConfig, "load", staticmethod(lambda _: object())) + monkeypatch.setattr( + task_module, + "build_knowledge", + lambda source_path, output_dir, config, cache_dir: [{"status": "failed", "error": "converter exploded"}], + ) + + with pytest.raises(RuntimeError, match="converter exploded"): + task_module.run_convert_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + assert version is not None + assert job is not None + assert version.convert_status == "failed" + assert version.failed_reason == "converter exploded" + assert job.status == "failed" + assert job.message == "Conversion failed" + assert job.error == "converter exploded" + finally: + db.close() + + +def test_sync_job_success_creates_sync_record_and_marks_document_synced(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="unsynced", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + assert dataset_id == "dataset-001" + assert name == "policy" + assert "Ready for sync" in text + assert indexing_technique == "high_quality" + return {"document": {"id": "remote-001"}, "batch": "batch-001"} + + def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict: + raise AssertionError("update_document_by_text should not be called for a first sync") + + def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict: + assert dataset_id == "dataset-001" + assert batch == "batch-001" + return {"indexing_status": "completed"} + + def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict: + raise AssertionError("get_document_detail should not be called when batch exists") + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + + task_module.run_sync_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + group = db.query(Group).filter(Group.id == group_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all() + assert version is not None + assert group is not None + assert job is not None + assert group.dify_dataset_id == "dataset-001" + assert version.sync_status == "synced" + assert len(records) == 1 + assert records[0].remote_document_id == "remote-001" + assert records[0].status == "synced" + assert records[0].last_indexing_status == "completed" + assert job.status == "success" + assert job.message == "Dify sync completed" + assert job.result == { + "dataset_id": "dataset-001", + "remote_document_id": "remote-001", + "batch": "batch-001", + "indexing_status": "completed", + } + finally: + db.close() + + +def test_sync_job_success_without_batch_waits_for_document_completion(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="unsynced", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + assert dataset_id == "dataset-001" + assert name == "policy" + return {"document": {"id": "remote-001"}} + + def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict: + assert dataset_id == "dataset-001" + assert document_id == "remote-001" + return {"indexing_status": "completed"} + + def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict: + raise AssertionError("get_document_detail should not be called directly in no-batch mode") + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + + task_module.run_sync_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + record = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).first() + assert version is not None + assert job is not None + assert record is not None + assert version.sync_status == "synced" + assert record.status == "synced" + assert record.batch is None + assert record.last_indexing_status == "completed" + assert job.status == "success" + finally: + db.close() + + +def test_sync_job_reuses_existing_no_batch_sync_record_and_waits_for_completion(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="syncing", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + db = SessionLocal() + try: + db.add( + DifySyncRecord( + version_id=version_id, + dataset_id="dataset-001", + remote_document_id="remote-existing", + batch=None, + status="syncing", + ) + ) + db.commit() + finally: + db.close() + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text(self, **kwargs) -> dict: + raise AssertionError("create_document_by_text should not be called when an in-flight sync record exists") + + def wait_for_document_indexing(self, *, dataset_id: str, document_id: str, timeout_seconds: int = 300) -> dict: + assert dataset_id == "dataset-001" + assert document_id == "remote-existing" + return {"indexing_status": "completed_with_warning"} + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + + task_module.run_sync_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + record = ( + db.query(DifySyncRecord) + .filter(DifySyncRecord.version_id == version_id) + .order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc()) + .first() + ) + assert version is not None + assert job is not None + assert record is not None + assert version.sync_status == "synced" + assert record.status == "synced" + assert record.last_indexing_status == "completed_with_warning" + assert job.status == "success" + assert job.result["remote_document_id"] == "remote-existing" + finally: + db.close() + + +def test_delete_document_job_removes_local_storage_and_remote_dify_document(db_session, monkeypatch): + group_id, document_id, version_id, admin_id, source_root, markdown_root, assets_root = _seed_document_for_delete( + with_remote_sync=True + ) + job_id = _seed_job( + job_type="delete", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + db = SessionLocal() + try: + job = db.query(Job).filter(Job.id == job_id).first() + assert job is not None + job.payload = {"delete_dify": True} + db.commit() + finally: + db.close() + + delete_calls: list[tuple[str, str]] = [] + + class FakeDifyService: + def delete_document(self, *, dataset_id: str, document_id: str) -> None: + delete_calls.append((dataset_id, document_id)) + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + + task_module.run_delete_document_job(job_id, document_id) + + db = SessionLocal() + try: + job = db.query(Job).filter(Job.id == job_id).first() + assert job is not None + assert job.status == "success" + assert job.message == "Document delete completed" + assert job.result == {"deleted": True, "delete_dify": True, "remote_document_count": 1} + finally: + db.close() + + assert delete_calls == [("dataset-001", "remote-001")] + assert not source_root.exists() + assert not markdown_root.exists() + assert not assets_root.exists() + + +def test_sync_job_failure_marks_existing_sync_record_failed(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="unsynced", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + return {"document": {"id": "remote-001"}, "batch": "batch-001"} + + def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict: + raise AssertionError("update_document_by_text should not be called for a first sync") + + def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict: + raise DifyError("Indexing failed with status=failed") + + def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]: + assert dataset_id == "dataset-001" + assert batch == "batch-001" + return [{"indexing_status": "failed", "display_status": "error"}] + + def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict: + raise AssertionError("get_document_detail should not be called when batch exists") + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + + with pytest.raises(DifyError, match="status=failed"): + task_module.run_sync_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all() + assert version is not None + assert job is not None + assert version.sync_status == "sync_failed" + assert job.status == "failed" + assert job.message == "Dify sync failed" + assert "status=failed" in job.error + assert len(records) == 1 + assert records[0].status == "sync_failed" + assert "status=failed" in records[0].error + assert records[0].last_indexing_status == "failed" + finally: + db.close() + + +def test_sync_job_keeps_local_asset_urls_when_syncing_to_dify(db_session, monkeypatch): + local_asset_url = ( + f"http://testserver/storage/assets/group_{1:04d}/document_{1:06d}/v001/img_001_deadbeef.jpg" + ) + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="unsynced", + markdown_text=f"# Policy\n\n![image-1]({local_asset_url})", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text(self, *, dataset_id, name, text, doc_form, indexing_technique): + assert local_asset_url in text + return {"document": {"id": "remote-001"}, "batch": "batch-001"} + + def wait_for_indexing(self, *, dataset_id, batch, timeout_seconds=300): + return {"indexing_status": "completed"} + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + + task_module.run_sync_job(job_id, version_id) + + +def test_sync_job_recreates_remote_document_when_previous_sync_record_exists(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="sync_failed", + markdown_text="# Policy\n\nReady for resync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + db = SessionLocal() + try: + db.add( + DifySyncRecord( + version_id=version_id, + dataset_id="dataset-001", + remote_document_id="remote-old", + status="sync_failed", + ) + ) + db.commit() + finally: + db.close() + + class FakeDifyService: + def __init__(self): + self.deleted: list[tuple[str, str]] = [] + + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def delete_document(self, *, dataset_id: str, document_id: str) -> None: + self.deleted.append((dataset_id, document_id)) + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + assert dataset_id == "dataset-001" + assert name == "policy" + assert "Ready for resync" in text + return {"document": {"id": "remote-new"}, "batch": "batch-new"} + + def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict: + raise AssertionError("update_document_by_text should not be called during resync") + + def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict: + assert dataset_id == "dataset-001" + assert batch == "batch-new" + return {"indexing_status": "completed"} + + def get_document_detail(self, *, dataset_id: str, document_id: str) -> dict: + raise AssertionError("get_document_detail should not be called when batch exists") + + service = FakeDifyService() + monkeypatch.setattr(task_module, "DifyService", lambda: service) + + task_module.run_sync_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).order_by(DifySyncRecord.id).all() + assert version is not None + assert job is not None + assert version.sync_status == "synced" + assert service.deleted == [("dataset-001", "remote-old")] + assert len(records) == 2 + assert records[-1].remote_document_id == "remote-new" + assert records[-1].status == "synced" + assert job.status == "success" + assert job.result == { + "dataset_id": "dataset-001", + "remote_document_id": "remote-new", + "batch": "batch-new", + "indexing_status": "completed", + } + finally: + db.close() + + +def test_sync_job_retryable_dify_error_requeues_instead_of_failing(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="unsynced", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class SettingsStub: + task_execution_mode = "rq" + dify_sync_max_retries = 4 + dify_sync_cooldown_seconds = 20 + + @staticmethod + def dify_sync_retry_delays(): + return [15, 30, 60] + + class FakeQueue: + def __init__(self): + self.calls: list[tuple[int, str, tuple]] = [] + + def enqueue_in(self, delay, task_name, *args, **kwargs): + self.calls.append((int(delay.total_seconds()), task_name, args)) + return SimpleNamespace(id="rq-retry-1") + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + return {"document": {"id": "remote-001"}, "batch": "batch-001"} + + def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict: + raise DifyError("FATAL: sorry, too many clients already") + + def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]: + return [{"indexing_status": "waiting", "display_status": "queuing"}] + + queue = FakeQueue() + cooldowns: list[tuple[str, int]] = [] + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + monkeypatch.setattr(task_module, "get_queue", lambda: queue) + monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub()) + monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0) + monkeypatch.setattr(task_module, "set_delay_gate", lambda name, ttl: cooldowns.append((name, ttl))) + + task_module.run_sync_job(job_id, version_id) + + assert queue.calls == [(15, "app.tasks.run_sync_job", (job_id, version_id))] + assert cooldowns == [(task_module.DIFY_SYNC_COOLDOWN_GATE, 20)] + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all() + assert version is not None + assert job is not None + assert version.sync_status == "syncing" + assert job.status == "queued" + assert job.queue_job_id == "rq-retry-1" + assert job.payload["sync_retry_count"] == 1 + assert job.payload["sync_retry_after_seconds"] == 15 + assert "too many clients already" in job.payload["sync_last_error"] + assert job.message == "Dify busy, retrying in 15s (attempt 1/4)." + assert job.error is None + assert len(records) == 1 + assert records[0].status == "syncing" + assert "too many clients already" in records[0].error + finally: + db.close() + + +def test_sync_job_retryable_dify_error_fails_cleanly_in_sync_mode(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="unsynced", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class SettingsStub: + task_execution_mode = "sync" + dify_sync_max_retries = 4 + dify_sync_cooldown_seconds = 20 + + @staticmethod + def dify_sync_retry_delays(): + return [15, 30, 60] + + class FakeDifyService: + def ensure_dataset(self, **kwargs): + return "dataset-001" + + def create_document_by_text( + self, + *, + dataset_id: str, + name: str, + text: str, + doc_form: str, + indexing_technique: str, + ) -> dict: + return {"document": {"id": "remote-001"}, "batch": "batch-001"} + + def wait_for_indexing(self, *, dataset_id: str, batch: str, timeout_seconds: int = 300) -> dict: + raise DifyError("FATAL: sorry, too many clients already") + + def get_indexing_status(self, *, dataset_id: str, batch: str) -> list[dict]: + return [{"indexing_status": "waiting", "display_status": "queuing"}] + + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + monkeypatch.setattr(task_module, "get_settings", lambda: SettingsStub()) + monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 0) + + with pytest.raises(DifyError, match="too many clients already"): + task_module.run_sync_job(job_id, version_id) + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + records = db.query(DifySyncRecord).filter(DifySyncRecord.version_id == version_id).all() + assert version is not None + assert job is not None + assert version.sync_status == "sync_failed" + assert job.status == "failed" + assert job.queue_job_id is None + assert job.error is not None and "too many clients already" in job.error + assert len(records) == 1 + assert records[0].status == "sync_failed" + finally: + db.close() + + +def test_sync_job_defers_during_dify_cooldown_without_calling_dify(db_session, monkeypatch): + group_id, document_id, version_id, admin_id = _seed_document_version( + convert_status="success", + sync_status="syncing", + markdown_text="# Policy\n\nReady for sync", + ) + job_id = _seed_job( + job_type="sync", + group_id=group_id, + document_id=document_id, + version_id=version_id, + created_by_id=admin_id, + ) + + class FakeQueue: + def __init__(self): + self.calls: list[tuple[int, str, tuple]] = [] + + def enqueue_in(self, delay, task_name, *args, **kwargs): + self.calls.append((int(delay.total_seconds()), task_name, args)) + return SimpleNamespace(id="rq-retry-2") + + invoked = {"count": 0} + + class FakeDifyService: + def __init__(self): + invoked["count"] += 1 + + queue = FakeQueue() + monkeypatch.setattr(task_module, "DifyService", FakeDifyService) + monkeypatch.setattr(task_module, "get_queue", lambda: queue) + monkeypatch.setattr(task_module, "get_delay_gate_ttl", lambda name: 45) + + task_module.run_sync_job(job_id, version_id) + + assert invoked["count"] == 0 + assert queue.calls == [(45, "app.tasks.run_sync_job", (job_id, version_id))] + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + assert version is not None + assert job is not None + assert version.sync_status == "syncing" + assert job.status == "queued" + assert job.queue_job_id == "rq-retry-2" + assert job.message == "Dify cooldown active, retrying in 45s." + finally: + db.close() diff --git a/backend/tests/test_uploads.py b/backend/tests/test_uploads.py new file mode 100644 index 00000000..d5ea25cb --- /dev/null +++ b/backend/tests/test_uploads.py @@ -0,0 +1,660 @@ +from __future__ import annotations + +from datetime import date, timedelta + +from app.database import SessionLocal +from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, User, UserDepartmentAccess + + +def _token(client): + response = client.post("/api/auth/login", json={"username": "admin", "password": "admin123456"}) + return response.json()["access_token"] + + +def _headers(client): + return {"Authorization": f"Bearer {_token(client)}"} + + +def test_duplicate_upload_is_detected(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + client.post("/api/groups", json={"name": "quality", "description": "", "department_id": 1}, headers=_headers(client)) + payload = {"group_id": "1"} + files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] + first = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + assert len(first.json()["created"]) == 1 + second = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + assert len(second.json()["duplicates"]) == 1 + + +def test_upload_rejects_more_than_500_files(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + client.post("/api/groups", json={"name": "bulk-limit", "description": "", "department_id": 1}, headers=_headers(client)) + payload = {"group_id": "1"} + files = [("files", (f"sample-{index}.pdf", b"pdf", "application/pdf")) for index in range(501)] + + response = client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + + assert response.status_code == 400 + assert response.json()["detail"] == "Batch upload accepts at most 500 files at a time." + + +def test_same_title_creates_new_version(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + client.post("/api/groups", json={"name": "risk", "description": "", "department_id": 1}, headers=_headers(client)) + payload = {"group_id": "1"} + first_file = [("files", ("policy.docx", b"abc", "application/octet-stream"))] + second_file = [("files", ("policy.docx", b"abcd", "application/octet-stream"))] + client.post("/api/files/upload", data=payload, files=first_file, headers=_headers(client)) + client.post("/api/files/upload", data=payload, files=second_file, headers=_headers(client)) + db = SessionLocal() + try: + document = db.query(Document).filter(Document.group_id == 1, Document.title == "policy").first() + assert document is not None + versions = db.query(DocumentVersion).filter(DocumentVersion.document_id == document.id).all() + assert len(versions) == 2 + finally: + db.close() + + +def test_group_rename_endpoint(client): + client.post("/api/groups", json={"name": "safety", "description": "", "department_id": 1}, headers=_headers(client)) + response = client.patch("/api/groups/1", json={"name": "EHS", "rename_dify": False}, headers=_headers(client)) + assert response.status_code == 200 + assert response.json()["name"] == "EHS" + + +def test_group_name_can_repeat_in_different_departments(client): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + department = Department(name="second-dept", description="secondary") + db.add(department) + db.commit() + db.refresh(department) + db.add(UserDepartmentAccess(user_id=admin.id, department_id=department.id)) + db.commit() + finally: + db.close() + + first = client.post( + "/api/groups", + json={"name": "shared-name", "description": "", "department_id": 1}, + headers=_headers(client), + ) + assert first.status_code == 200 + + second = client.post( + "/api/groups", + json={"name": "shared-name", "description": "", "department_id": 2}, + headers=_headers(client), + ) + assert second.status_code == 200 + assert second.json()["department_id"] == 2 + + +def test_group_rename_returns_conflict_within_same_department(client): + first = client.post("/api/groups", json={"name": "dept-a", "description": "", "department_id": 1}, headers=_headers(client)) + second = client.post("/api/groups", json={"name": "dept-b", "description": "", "department_id": 1}, headers=_headers(client)) + assert first.status_code == 200 + assert second.status_code == 200 + + response = client.patch("/api/groups/2", json={"name": "dept-a", "rename_dify": False}, headers=_headers(client)) + assert response.status_code == 409 + assert response.json()["detail"] == "Group already exists." + + +def test_group_delete_endpoint(client): + client.post("/api/groups", json={"name": "archive", "description": "", "department_id": 1}, headers=_headers(client)) + response = client.delete("/api/groups/1", headers=_headers(client)) + assert response.status_code == 200 + listed = client.get("/api/groups", headers=_headers(client)) + assert listed.status_code == 200 + assert listed.json()["data"] == [] + + +def test_group_delete_with_documents_and_dify(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + deleted = {} + + def fake_delete_dataset(self, *, dataset_id: str): + deleted["dataset_id"] = dataset_id + + monkeypatch.setattr("app.api.groups.DifyService.delete_dataset", fake_delete_dataset) + + client.post("/api/groups", json={"name": "cleanup", "description": "", "department_id": 1}, headers=_headers(client)) + payload = {"group_id": "1"} + files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] + client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + + db = SessionLocal() + try: + group = db.query(Document).filter(Document.group_id == 1).first().group + group.dify_dataset_id = "dataset-123" + job = db.query(Job).filter(Job.group_id == 1).first() + job.status = "success" + db.commit() + finally: + db.close() + + response = client.delete("/api/groups/1?delete_dify=true", headers=_headers(client)) + assert response.status_code == 200 + assert deleted["dataset_id"] == "dataset-123" + + db = SessionLocal() + try: + assert db.query(Document).count() == 0 + finally: + db.close() + + +def test_group_delete_rejects_running_jobs(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + client.post("/api/groups", json={"name": "active", "description": "", "department_id": 1}, headers=_headers(client)) + payload = {"group_id": "1"} + files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] + client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + + response = client.delete("/api/groups/1", headers=_headers(client)) + assert response.status_code == 409 + + +def test_group_list_includes_document_count(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + client.post("/api/groups", json={"name": "filled", "description": "", "department_id": 1}, headers=_headers(client)) + client.post("/api/groups", json={"name": "empty", "description": "", "department_id": 1}, headers=_headers(client)) + + payload = {"group_id": "1"} + files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] + client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + + response = client.get("/api/groups", headers=_headers(client)) + assert response.status_code == 200 + counts = {item["name"]: item["document_count"] for item in response.json()["data"]} + assert counts["filled"] == 1 + assert counts["empty"] == 0 + + +def test_group_dify_diff_reports_local_remote_and_attention(client, monkeypatch): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + + group = Group(name="diff-group", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-123") + db.add(group) + db.commit() + db.refresh(group) + + local_only = Document(group_id=group.id, title="local only", created_by_id=admin.id, is_deleted=False) + attention = Document(group_id=group.id, title="attention", created_by_id=admin.id, is_deleted=False) + synced = Document(group_id=group.id, title="matched", created_by_id=admin.id, is_deleted=False) + db.add_all([local_only, attention, synced]) + db.commit() + db.refresh(local_only) + db.refresh(attention) + db.refresh(synced) + + local_only_version = DocumentVersion( + document_id=local_only.id, + version_no=1, + is_current=True, + source_filename="local only.docx", + source_ext=".docx", + source_path="local-only.docx", + source_sha256="hash-local", + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="unsynced", + ) + attention_version = DocumentVersion( + document_id=attention.id, + version_no=1, + is_current=True, + source_filename="attention.docx", + source_ext=".docx", + source_path="attention.docx", + source_sha256="hash-attention", + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="sync_failed", + ) + synced_version = DocumentVersion( + document_id=synced.id, + version_no=1, + is_current=True, + source_filename="matched.docx", + source_ext=".docx", + source_path="matched.docx", + source_sha256="hash-matched", + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="synced", + ) + db.add_all([local_only_version, attention_version, synced_version]) + db.commit() + db.refresh(attention_version) + db.refresh(synced_version) + + db.add_all( + [ + DifySyncRecord( + version_id=attention_version.id, + dataset_id="dataset-123", + remote_document_id="remote-attention", + status="sync_failed", + ), + DifySyncRecord( + version_id=synced_version.id, + dataset_id="dataset-123", + remote_document_id="remote-matched", + status="synced", + ), + ] + ) + db.commit() + finally: + db.close() + + class FakeRemote: + def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True): + self.id = document_id + self.name = name + self.indexing_status = indexing_status + self.display_status = display_status + self.enabled = enabled + + class FakeDifyService: + def list_documents(self, *, dataset_id: str, limit: int = 100): + assert dataset_id == "dataset-123" + assert limit == 100 + return [ + FakeRemote("remote-attention", "attention", "indexing"), + FakeRemote("remote-matched", "matched", "completed"), + FakeRemote("remote-only", "remote only", "completed"), + ] + + monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) + + response = client.get("/api/groups/1/dify-diff", headers=_headers(client)) + assert response.status_code == 200 + payload = response.json() + assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 1, "attention": 1} + + rows = {row["display_name"]: row for row in payload["rows"]} + assert rows["local only"]["status"] == "local_only" + assert rows["remote only"]["status"] == "dify_only" + assert rows["attention"]["status"] == "attention" + assert rows["matched"]["status"] == "matched" + + +def test_group_dify_diff_keeps_multiple_remote_documents_with_same_stem(client, monkeypatch): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + + group = Group(name="duplicate-stem", description="Compare me", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-stem") + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="policy", created_by_id=admin.id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="policy.docx", + source_ext=".docx", + source_path="policy.docx", + source_sha256="hash-policy", + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="synced", + ) + db.add(version) + db.commit() + db.refresh(version) + + db.add( + DifySyncRecord( + version_id=version.id, + dataset_id="dataset-stem", + remote_document_id="remote-policy-docx", + status="synced", + ) + ) + db.commit() + finally: + db.close() + + class FakeRemote: + def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True): + self.id = document_id + self.name = name + self.indexing_status = indexing_status + self.display_status = display_status + self.enabled = enabled + + class FakeDifyService: + def list_documents(self, *, dataset_id: str, limit: int = 100): + assert dataset_id == "dataset-stem" + return [ + FakeRemote("remote-policy-docx", "policy.docx", "completed"), + FakeRemote("remote-policy-pdf", "policy.pdf", "completed"), + ] + + monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) + + response = client.get("/api/groups/1/dify-diff", headers=_headers(client)) + assert response.status_code == 200 + payload = response.json() + assert payload["summary"] == {"matched": 1, "local_only": 0, "dify_only": 1, "attention": 0} + assert len(payload["rows"]) == 2 + rows = {(row["display_name"], row["status"]) for row in payload["rows"]} + assert ("policy", "matched") in rows + assert ("policy.pdf", "dify_only") in rows + + +def test_global_dashboard_summary_and_dify_diff(client, monkeypatch): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + blocked_department = Department(name="blocked-global", description="hidden") + db.add(blocked_department) + db.commit() + db.refresh(blocked_department) + + linked_group = Group(name="kb-linked", description="", created_by_id=admin.id, department_id=1, dify_dataset_id="dataset-linked") + local_only_group = Group(name="kb-local", description="", created_by_id=admin.id, department_id=1) + hidden_group = Group( + name="kb-hidden", + description="", + created_by_id=admin.id, + department_id=blocked_department.id, + dify_dataset_id="dataset-hidden", + ) + db.add_all([linked_group, local_only_group, hidden_group]) + db.commit() + db.refresh(linked_group) + db.refresh(local_only_group) + db.refresh(hidden_group) + + linked_document = Document(group_id=linked_group.id, title="alpha", created_by_id=admin.id, is_deleted=False) + running_document = Document(group_id=local_only_group.id, title="beta", created_by_id=admin.id, is_deleted=False) + hidden_document = Document(group_id=hidden_group.id, title="secret", created_by_id=admin.id, is_deleted=False) + db.add_all([linked_document, running_document, hidden_document]) + db.commit() + db.refresh(linked_document) + db.refresh(running_document) + db.refresh(hidden_document) + + linked_version = DocumentVersion( + document_id=linked_document.id, + version_no=1, + is_current=True, + source_filename="alpha.docx", + source_ext=".docx", + source_path="alpha.docx", + source_sha256="hash-alpha", + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="synced", + ) + running_version = DocumentVersion( + document_id=running_document.id, + version_no=1, + is_current=True, + source_filename="beta.docx", + source_ext=".docx", + source_path="beta.docx", + source_sha256="hash-beta", + file_size=1, + uploader_id=admin.id, + convert_status="running", + sync_status="unsynced", + ) + hidden_version = DocumentVersion( + document_id=hidden_document.id, + version_no=1, + is_current=True, + source_filename="secret.docx", + source_ext=".docx", + source_path="secret.docx", + source_sha256="hash-secret", + file_size=1, + uploader_id=admin.id, + convert_status="success", + sync_status="synced", + ) + db.add_all([linked_version, running_version, hidden_version]) + db.commit() + db.refresh(linked_version) + db.refresh(hidden_version) + + db.add_all( + [ + DifySyncRecord( + version_id=linked_version.id, + dataset_id="dataset-linked", + remote_document_id="remote-alpha", + status="synced", + ), + DifySyncRecord( + version_id=hidden_version.id, + dataset_id="dataset-hidden", + remote_document_id="remote-secret", + status="synced", + ), + ] + ) + db.commit() + finally: + db.close() + + class FakeDataset: + def __init__(self, dataset_id: str, name: str): + self.id = dataset_id + self.name = name + + class FakeRemote: + def __init__(self, document_id, name, indexing_status, display_status="available", enabled=True): + self.id = document_id + self.name = name + self.indexing_status = indexing_status + self.display_status = display_status + self.enabled = enabled + + class FakeDifyService: + def list_datasets(self): + return [ + FakeDataset("dataset-linked", "kb-linked"), + FakeDataset("dataset-hidden", "kb-hidden"), + FakeDataset("dataset-remote", "kb-remote"), + ] + + def list_documents(self, *, dataset_id: str, limit: int = 100): + if dataset_id == "dataset-linked": + return [FakeRemote("remote-alpha", "alpha", "completed")] + if dataset_id == "dataset-hidden": + return [FakeRemote("remote-secret", "secret", "completed")] + if dataset_id == "dataset-remote": + return [FakeRemote("remote-gamma", "gamma", "completed")] + return [] + + monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) + + summary_response = client.get("/api/groups/summary", headers=_headers(client)) + assert summary_response.status_code == 200 + assert summary_response.json() == { + "knowledge_base_count": 2, + "file_count": 2, + "running_count": 1, + } + + diff_response = client.get("/api/groups/dify-diff-global", headers=_headers(client)) + assert diff_response.status_code == 200 + payload = diff_response.json() + assert payload["summary"] == {"matched": 1, "local_only": 1, "dify_only": 0, "attention": 0} + rows = {(row["knowledge_base"]["name"], row["display_name"]): row for row in payload["rows"]} + assert rows[("kb-linked", "alpha")]["status"] == "matched" + assert rows[("kb-local", "beta")]["status"] == "local_only" + assert ("kb-remote", "gamma") not in rows + assert ("kb-hidden", "secret") not in rows + + +def test_import_dify_document_into_existing_group(client, monkeypatch): + client.post("/api/groups", json={"name": "imports", "description": "", "department_id": 1}, headers=_headers(client)) + + class FakeSegment: + def __init__(self, content: str, position: int): + self.content = content + self.position = position + + class FakeDifyService: + def get_document_detail(self, *, dataset_id: str, document_id: str): + assert dataset_id == "dataset-import" + assert document_id == "remote-1" + return {"name": "policy.docx", "indexing_status": "completed"} + + def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100): + assert limit == 100 + return [FakeSegment("hello world", 1), FakeSegment("from dify", 2)] + + def get_upload_file(self, *, dataset_id: str, document_id: str): + return None + + monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) + + response = client.post( + "/api/groups/import-dify-document", + json={ + "group_id": 1, + "dataset_id": "dataset-import", + "remote_document_id": "remote-1", + "knowledge_base_name": "imports", + }, + headers=_headers(client), + ) + assert response.status_code == 200 + payload = response.json() + assert payload["group_id"] == 1 + assert payload["document"]["title"] == "policy" + assert payload["document"]["current_version"]["sync_status"] == "synced" + assert payload["document"]["current_version"]["convert_status"] == "success" + assert payload["document"]["current_version"]["source_ext"] == ".md" + + db = SessionLocal() + try: + group = db.query(Group).filter(Group.id == 1).first() + assert group is not None + assert group.dify_dataset_id == "dataset-import" + sync_record = db.query(DifySyncRecord).first() + assert sync_record is not None + assert sync_record.remote_document_id == "remote-1" + assert sync_record.status == "synced" + finally: + db.close() + + +def test_import_dify_document_creates_group_for_remote_only_dataset(client, monkeypatch): + class FakeSegment: + def __init__(self, content: str, position: int): + self.content = content + self.position = position + + class FakeDifyService: + def get_document_detail(self, *, dataset_id: str, document_id: str): + assert dataset_id == "dataset-remote-only" + return {"name": "remote-only.md", "indexing_status": "completed"} + + def list_document_segments(self, *, dataset_id: str, document_id: str, limit: int = 100): + return [FakeSegment("# Remote\n\nbody", 1)] + + def get_upload_file(self, *, dataset_id: str, document_id: str): + return None + + monkeypatch.setattr("app.api.groups.DifyService", FakeDifyService) + + response = client.post( + "/api/groups/import-dify-document", + json={ + "dataset_id": "dataset-remote-only", + "remote_document_id": "remote-doc", + "knowledge_base_name": "remote-only-kb", + }, + headers=_headers(client), + ) + assert response.status_code == 200 + payload = response.json() + assert payload["group_name"] == "remote-only-kb" + assert payload["document"]["title"] == "remote-only" + + db = SessionLocal() + try: + group = db.query(Group).filter(Group.name == "remote-only-kb").first() + assert group is not None + document = db.query(Document).filter(Document.group_id == group.id, Document.title == "remote-only").first() + assert document is not None + finally: + db.close() + + +def test_import_dify_document_requires_department_when_admin_has_no_primary_department(client): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + admin.primary_department_id = None + db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == admin.id).delete() + db.commit() + finally: + db.close() + + response = client.post( + "/api/groups/import-dify-document", + json={ + "dataset_id": "dataset-remote-only", + "remote_document_id": "remote-doc", + "knowledge_base_name": "remote-only-kb", + }, + headers=_headers(client), + ) + assert response.status_code == 400 + assert response.json()["detail"] == "Department is required for Dify import." + + +def test_group_files_include_uploader_and_date_filter(client, monkeypatch): + monkeypatch.setattr("app.api.files._enqueue", lambda job, task_name, version_id, db: job) + client.post("/api/groups", json={"name": "ops", "description": "", "department_id": 1}, headers=_headers(client)) + payload = {"group_id": "1"} + files = [("files", ("sample.docx", b"abc", "application/octet-stream"))] + client.post("/api/files/upload", data=payload, files=files, headers=_headers(client)) + + baseline = client.get("/api/groups/1/files", headers=_headers(client)) + assert baseline.status_code == 200 + uploaded_at = baseline.json()["data"][0]["current_version"]["uploaded_at"] + actual_date = uploaded_at.split("T")[0] + tomorrow = (date.fromisoformat(actual_date) + timedelta(days=1)).isoformat() + + listed = client.get( + f"/api/groups/1/files?uploaded_from={actual_date}&uploaded_to={actual_date}&file_type=.docx", + headers=_headers(client), + ) + assert listed.status_code == 200 + row = listed.json()["data"][0] + assert row["current_version"]["uploaded_by"]["username"] == "admin" + + future = client.get(f"/api/groups/1/files?uploaded_from={tomorrow}", headers=_headers(client)) + assert future.status_code == 200 + assert future.json()["data"] == [] diff --git a/backend/tests/test_watchdog_service.py b/backend/tests/test_watchdog_service.py new file mode 100644 index 00000000..5fd6db2c --- /dev/null +++ b/backend/tests/test_watchdog_service.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +import json +import uuid +from datetime import timedelta + +from app.config import get_settings +from app.database import SessionLocal +from app.models import DifySyncRecord, Document, DocumentVersion, Group, Job, User +from app.services.watchdog_service import ( + local_convert_health_summary, + local_sync_health_summary, + read_watchdog_snapshot, + recover_stale_converts, + recover_stale_syncs, +) +from app.time_utils import utc_now + + +def _seed_stale_sync_version(): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + admin_id = admin.id + + group = Group(name=f"watchdog-group-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="watchdog-policy", created_by_id=admin_id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="watchdog.docx", + source_ext=".docx", + source_path="/tmp/watchdog.docx", + source_sha256=uuid.uuid4().hex, + file_size=2048, + uploader_id=admin_id, + convert_status="success", + sync_status="syncing", + ) + db.add(version) + db.commit() + db.refresh(version) + + old_time = utc_now() - timedelta(minutes=20) + job = Job( + id=str(uuid.uuid4()), + job_type="sync", + status="running", + group_id=group.id, + document_id=document.id, + version_id=version.id, + created_by_id=admin_id, + created_at=old_time, + started_at=old_time, + message="Syncing document to Dify", + ) + db.add(job) + db.commit() + + record = DifySyncRecord( + version_id=version.id, + dataset_id="dataset-watchdog", + remote_document_id="remote-watchdog", + batch="batch-watchdog", + status="syncing", + created_at=old_time, + updated_at=old_time, + ) + db.add(record) + db.commit() + + return version.id, job.id, record.id + finally: + db.close() + + +def _seed_stale_convert_version(*, queue_job_id: str | None = "rq-convert-stale", status: str = "queued"): + db = SessionLocal() + try: + admin = db.query(User).filter(User.username == "admin").first() + assert admin is not None + admin_id = admin.id + + group = Group(name=f"convert-watchdog-{uuid.uuid4().hex[:8]}", created_by_id=admin_id, department_id=1) + db.add(group) + db.commit() + db.refresh(group) + + document = Document(group_id=group.id, title="convert-watchdog", created_by_id=admin_id, is_deleted=False) + db.add(document) + db.commit() + db.refresh(document) + + old_time = utc_now() - timedelta(minutes=20) + version = DocumentVersion( + document_id=document.id, + version_no=1, + is_current=True, + source_filename="convert-watchdog.docx", + source_ext=".docx", + source_path="/tmp/convert-watchdog.docx", + source_sha256=uuid.uuid4().hex, + file_size=1024, + uploader_id=admin_id, + convert_status=status, + sync_status="unsynced", + uploaded_at=old_time, + ) + db.add(version) + db.commit() + db.refresh(version) + + job = Job( + id=str(uuid.uuid4()), + job_type="convert", + status=status, + queue_job_id=queue_job_id, + group_id=group.id, + document_id=document.id, + version_id=version.id, + created_by_id=admin_id, + created_at=old_time, + started_at=old_time if status == "running" else None, + message="Converting source document", + ) + db.add(job) + db.commit() + + return version.id, job.id + finally: + db.close() + + +def test_recover_stale_syncs_marks_versions_jobs_and_records_failed(db_session): + version_id, job_id, record_id = _seed_stale_sync_version() + + db = SessionLocal() + try: + result = recover_stale_syncs(db, timeout_seconds=900) + assert result["recovered_versions"] == 1 + assert result["recovered_jobs"] == 1 + assert result["recovered_records"] == 1 + finally: + db.close() + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + record = db.query(DifySyncRecord).filter(DifySyncRecord.id == record_id).first() + assert version is not None + assert job is not None + assert record is not None + assert version.sync_status == "sync_failed" + assert job.status == "failed" + assert "watchdog timeout" in (job.error or "") + assert record.status == "sync_failed" + assert "watchdog timeout" in (record.error or "") + finally: + db.close() + + +def test_local_sync_health_summary_reports_stale_candidates(db_session): + _seed_stale_sync_version() + + db = SessionLocal() + try: + payload = local_sync_health_summary(db, timeout_seconds=900) + assert payload["syncing_versions"] == 1 + assert payload["active_sync_jobs"] == 1 + assert payload["stale_candidates"] == 1 + assert payload["stale_versions"][0]["remote_document_id"] == "remote-watchdog" + finally: + db.close() + + +def test_recover_stale_converts_marks_versions_and_jobs_failed_when_queue_job_is_missing(db_session, monkeypatch): + version_id, job_id = _seed_stale_convert_version() + monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set()) + + db = SessionLocal() + try: + result = recover_stale_converts(db, timeout_seconds=900, orphan_grace_seconds=120) + assert result["recovered_versions"] == 1 + assert result["recovered_jobs"] == 1 + finally: + db.close() + + db = SessionLocal() + try: + version = db.query(DocumentVersion).filter(DocumentVersion.id == version_id).first() + job = db.query(Job).filter(Job.id == job_id).first() + assert version is not None + assert job is not None + assert version.convert_status == "failed" + assert "watchdog" in (version.failed_reason or "") + assert job.status == "failed" + assert "missing from Redis queue" in (job.error or "") + finally: + db.close() + + +def test_local_convert_health_summary_reports_stale_candidates(db_session, monkeypatch): + _seed_stale_convert_version() + monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: set()) + + db = SessionLocal() + try: + payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120) + assert payload["pending_versions"] == 1 + assert payload["active_convert_jobs"] == 1 + assert payload["stale_candidates"] == 1 + assert payload["stale_versions"][0]["reason"].startswith("Convert job is missing") + finally: + db.close() + + +def test_local_convert_health_summary_keeps_live_queue_jobs_out_of_stale_candidates(db_session, monkeypatch): + _seed_stale_convert_version(queue_job_id="rq-convert-live") + monkeypatch.setattr("app.services.watchdog_service._live_queue_job_ids", lambda settings=None: {"rq-convert-live"}) + + db = SessionLocal() + try: + payload = local_convert_health_summary(db, timeout_seconds=900, orphan_grace_seconds=120) + assert payload["pending_versions"] == 1 + assert payload["stale_candidates"] == 0 + finally: + db.close() + + +def test_read_watchdog_snapshot_reads_json_from_data_root(db_session): + path = get_settings().data_root / "watchdog" / "dify-health.json" + path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "status": "ok", + "worker": {"concurrency": 2}, + "queue_lengths": {"priority_dataset": 0}, + } + path.write_text(json.dumps(payload), encoding="utf-8") + + loaded = read_watchdog_snapshot() + assert loaded is not None + assert loaded["available"] is True + assert loaded["worker"]["concurrency"] == 2 diff --git a/backend/worker.py b/backend/worker.py new file mode 100644 index 00000000..606aeb5c --- /dev/null +++ b/backend/worker.py @@ -0,0 +1,14 @@ +from redis import Redis +from rq import Worker + +from app.config import get_settings + + +settings = get_settings() + + +if __name__ == "__main__": + connection = Redis.from_url(settings.redis_url) + worker = Worker([settings.rq_queue_name], connection=connection) + worker.work() + diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..10123a3d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,101 @@ +services: + postgres: + image: postgres:17-alpine + container_name: doc-cleaning-postgres + restart: always + environment: + POSTGRES_DB: document_cleaning + POSTGRES_USER: document_cleaning + POSTGRES_PASSWORD: document_cleaning + volumes: + - doc_cleaning_pg:/var/lib/postgresql/data + networks: + - doc-cleaning + + redis: + image: redis:7-alpine + container_name: doc-cleaning-redis + restart: always + networks: + - doc-cleaning + + api: + build: + context: ./backend + dockerfile: Dockerfile + container_name: doc-cleaning-api + restart: always + environment: + DATABASE_BACKEND: ${DATABASE_BACKEND:-postgres} + DATABASE_URL: ${DATABASE_URL:-} + SQLITE_DATABASE_URL: ${SQLITE_DATABASE_URL:-sqlite:///./document_cleaning.db} + POSTGRES_DATABASE_URL: ${POSTGRES_DATABASE_URL:-postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning} + REDIS_URL: redis://redis:6379/0 + PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://192.168.100.230:8891} + DIFY_BASE_URL: ${DIFY_BASE_URL:-https://api.dify.ai/v1} + DIFY_API_KEY: ${DIFY_API_KEY:-} + INTEGRATION_API_KEY: ${INTEGRATION_API_KEY:-} + INTEGRATION_DOWNLOAD_SECRET: ${INTEGRATION_DOWNLOAD_SECRET:-} + JWT_SECRET: ${JWT_SECRET:-change-me} + DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME:-admin} + DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-admin123456} + TASK_EXECUTION_MODE: ${TASK_EXECUTION_MODE:-rq} + depends_on: + - postgres + - redis + volumes: + - doc_cleaning_data:/app/data + networks: + - doc-cleaning + + worker: + build: + context: ./backend + dockerfile: Dockerfile + container_name: doc-cleaning-worker + restart: always + command: ["python", "worker.py"] + environment: + DATABASE_BACKEND: ${DATABASE_BACKEND:-postgres} + DATABASE_URL: ${DATABASE_URL:-} + SQLITE_DATABASE_URL: ${SQLITE_DATABASE_URL:-sqlite:///./document_cleaning.db} + POSTGRES_DATABASE_URL: ${POSTGRES_DATABASE_URL:-postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning} + REDIS_URL: redis://redis:6379/0 + PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://192.168.100.230:8891} + DIFY_BASE_URL: ${DIFY_BASE_URL:-https://api.dify.ai/v1} + DIFY_API_KEY: ${DIFY_API_KEY:-} + INTEGRATION_API_KEY: ${INTEGRATION_API_KEY:-} + INTEGRATION_DOWNLOAD_SECRET: ${INTEGRATION_DOWNLOAD_SECRET:-} + JWT_SECRET: ${JWT_SECRET:-change-me} + DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME:-admin} + DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-admin123456} + TASK_EXECUTION_MODE: ${TASK_EXECUTION_MODE:-rq} + depends_on: + - postgres + - redis + volumes: + - doc_cleaning_data:/app/data + networks: + - doc-cleaning + + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + container_name: doc-cleaning-frontend + restart: always + depends_on: + - api + ports: + - "8891:80" + networks: + - doc-cleaning + +networks: + doc-cleaning: + name: doc-cleaning + driver: bridge + +volumes: + doc_cleaning_pg: + doc_cleaning_data: diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 00000000..5435e490 --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,13 @@ +FROM node:22-alpine AS build + +WORKDIR /app +COPY package*.json ./ +RUN npm ci +COPY . . +RUN npm run build + +FROM nginx:alpine +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 00000000..f1e514ca --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,13 @@ +<!doctype html> +<html lang="zh-CN"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Document Cleaning + + +
+ + + + diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 00000000..c4b82c3d --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,43 @@ +server { + listen 80; + server_name _; + resolver 127.0.0.11 ipv6=off valid=10s; + client_max_body_size 200m; + + root /usr/share/nginx/html; + index index.html; + + location /api/ { + set $api_upstream api:8000; + proxy_pass http://$api_upstream$request_uri; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location /storage/ { + set $api_upstream api:8000; + proxy_pass http://$api_upstream$request_uri; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location = /index.html { + add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always; + add_header Pragma "no-cache" always; + add_header Expires "0" always; + try_files $uri =404; + } + + location / { + add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always; + add_header Pragma "no-cache" always; + add_header Expires "0" always; + try_files $uri $uri/ /index.html; + } +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 00000000..b2c400db --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,2668 @@ +{ + "name": "document-cleaning-frontend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "document-cleaning-frontend", + "version": "0.1.0", + "dependencies": { + "@uppy/core": "^4.5.2", + "@uppy/dashboard": "^4.4.2", + "@uppy/xhr-upload": "^4.3.3", + "vue": "^3.5.25", + "vue-router": "^4.6.4" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "@vitejs/plugin-vue": "^6.0.2", + "@vue/tsconfig": "^0.8.1", + "autoprefixer": "^10.4.24", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.17", + "typescript": "~5.9.3", + "vite": "^8.0.0-beta.13", + "vue-tsc": "^3.1.5" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", + "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", + "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", + "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz", + "integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@tybys/wasm-util": "^0.10.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.122.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.122.0.tgz", + "integrity": "sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.12.tgz", + "integrity": "sha512-pv1y2Fv0JybcykuiiD3qBOBdz6RteYojRFY1d+b95WVuzx211CRh+ytI/+9iVyWQ6koTh5dawe4S/yRfOFjgaA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.12.tgz", + "integrity": "sha512-cFYr6zTG/3PXXF3pUO+umXxt1wkRK/0AYT8lDwuqvRC+LuKYWSAQAQZjCWDQpAH172ZV6ieYrNnFzVVcnSflAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.12.tgz", + "integrity": "sha512-ZCsYknnHzeXYps0lGBz8JrF37GpE9bFVefrlmDrAQhOEi4IOIlcoU1+FwHEtyXGx2VkYAvhu7dyBf75EJQffBw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.12.tgz", + "integrity": "sha512-dMLeprcVsyJsKolRXyoTH3NL6qtsT0Y2xeuEA8WQJquWFXkEC4bcu1rLZZSnZRMtAqwtrF/Ib9Ddtpa/Gkge9Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.12.tgz", + "integrity": "sha512-YqWjAgGC/9M1lz3GR1r1rP79nMgo3mQiiA+Hfo+pvKFK1fAJ1bCi0ZQVh8noOqNacuY1qIcfyVfP6HoyBRZ85Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.12.tgz", + "integrity": "sha512-/I5AS4cIroLpslsmzXfwbe5OmWvSsrFuEw3mwvbQ1kDxJ822hFHIx+vsN/TAzNVyepI/j/GSzrtCIwQPeKCLIg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.12.tgz", + "integrity": "sha512-V6/wZztnBqlx5hJQqNWwFdxIKN0m38p8Jas+VoSfgH54HSj9tKTt1dZvG6JRHcjh6D7TvrJPWFGaY9UBVOaWPw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.12.tgz", + "integrity": "sha512-AP3E9BpcUYliZCxa3w5Kwj9OtEVDYK6sVoUzy4vTOJsjPOgdaJZKFmN4oOlX0Wp0RPV2ETfmIra9x1xuayFB7g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.12.tgz", + "integrity": "sha512-nWwpvUSPkoFmZo0kQazZYOrT7J5DGOJ/+QHHzjvNlooDZED8oH82Yg67HvehPPLAg5fUff7TfWFHQS8IV1n3og==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.12.tgz", + "integrity": "sha512-RNrafz5bcwRy+O9e6P8Z/OCAJW/A+qtBczIqVYwTs14pf4iV1/+eKEjdOUta93q2TsT/FI0XYDP3TCky38LMAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.12.tgz", + "integrity": "sha512-Jpw/0iwoKWx3LJ2rc1yjFrj+T7iHZn2JDg1Yny1ma0luviFS4mhAIcd1LFNxK3EYu3DHWCps0ydXQ5i/rrJ2ig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.12.tgz", + "integrity": "sha512-vRugONE4yMfVn0+7lUKdKvN4D5YusEiPilaoO2sgUWpCvrncvWgPMzK00ZFFJuiPgLwgFNP5eSiUlv2tfc+lpA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.12.tgz", + "integrity": "sha512-ykGiLr/6kkiHc0XnBfmFJuCjr5ZYKKofkx+chJWDjitX+KsJuAmrzWhwyOMSHzPhzOHOy7u9HlFoa5MoAOJ/Zg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^1.1.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.12.tgz", + "integrity": "sha512-5eOND4duWkwx1AzCxadcOrNeighiLwMInEADT0YM7xeEOOFcovWZCq8dadXgcRHSf3Ulh1kFo/qvzoFiCLOL1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.12.tgz", + "integrity": "sha512-PyqoipaswDLAZtot351MLhrlrh6lcZPo2LSYE+VDxbVk24LVKAGOuE4hb8xZQmrPAuEtTZW8E6D2zc5EUZX4Lw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.2", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz", + "integrity": "sha512-izyXV/v+cHiRfozX62W9htOAvwMo4/bXKDrQ+vom1L1qRuexPock/7VZDAhnpHCLNejd3NJ6hiab+tO0D44Rgw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@transloadit/prettier-bytes": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@transloadit/prettier-bytes/-/prettier-bytes-0.3.5.tgz", + "integrity": "sha512-xF4A3d/ZyX2LJWeQZREZQw+qFX4TGQ8bGVP97OLRt6sPO6T0TNHBFTuRHOJh7RNmYOBmQ9MHxpolD9bXihpuVA==", + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/node": { + "version": "24.12.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.0.tgz", + "integrity": "sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/retry": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.2.tgz", + "integrity": "sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==", + "license": "MIT" + }, + "node_modules/@uppy/companion-client": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/@uppy/companion-client/-/companion-client-4.5.2.tgz", + "integrity": "sha512-hfUsReHM5COhn+5d7CdZgZaG8BtDvtwj7vjXzg8qmgKI901mYUm/Zh420iOKT7eHiofKVTNoa7oijeGrqUEnyg==", + "license": "MIT", + "dependencies": { + "@uppy/utils": "^6.2.2", + "namespace-emitter": "^2.0.1", + "p-retry": "^6.1.0" + }, + "peerDependencies": { + "@uppy/core": "^4.5.2" + } + }, + "node_modules/@uppy/core": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/@uppy/core/-/core-4.5.3.tgz", + "integrity": "sha512-52VLeBUY/j904h48lpPGykuWikkOOS4Lz/qkmalDiBQfNALb6iB1MOZs079IM3o/uMLYxzZRL80C3sKpkBUYcw==", + "license": "MIT", + "dependencies": { + "@transloadit/prettier-bytes": "^0.3.4", + "@uppy/store-default": "^4.3.2", + "@uppy/utils": "^6.2.2", + "lodash": "^4.17.21", + "mime-match": "^1.0.2", + "namespace-emitter": "^2.0.1", + "nanoid": "^5.0.9", + "preact": "^10.5.13" + } + }, + "node_modules/@uppy/core/node_modules/nanoid": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.7.tgz", + "integrity": "sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/@uppy/dashboard": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@uppy/dashboard/-/dashboard-4.4.3.tgz", + "integrity": "sha512-IwgDDTbk9p4OoAJvvvx6sQSemKTIJq9IDSryNVgbbC6NiR9HSyRcu0+WdOZLiR9DOhDg2oYcoNgv7DMlrktI6g==", + "license": "MIT", + "dependencies": { + "@transloadit/prettier-bytes": "^0.3.4", + "@uppy/informer": "^4.3.2", + "@uppy/provider-views": "^4.5.2", + "@uppy/status-bar": "^4.2.3", + "@uppy/thumbnail-generator": "^4.2.2", + "@uppy/utils": "^6.2.2", + "classnames": "^2.2.6", + "lodash": "^4.17.21", + "nanoid": "^5.0.9", + "preact": "^10.5.13", + "shallow-equal": "^3.0.0" + }, + "peerDependencies": { + "@uppy/core": "^4.5.2" + } + }, + "node_modules/@uppy/dashboard/node_modules/nanoid": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.7.tgz", + "integrity": "sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/@uppy/informer": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@uppy/informer/-/informer-4.3.2.tgz", + "integrity": "sha512-7A9X8BfxR/GPtG0MGbQlmj1+G1o9fqeF3qtRh37ZvmZpapnEGtbstQ6Ao2vFm0uxYxOolLOMzFs/xCD27NKAvg==", + "license": "MIT", + "dependencies": { + "@uppy/utils": "^6.2.2", + "preact": "^10.5.13" + }, + "peerDependencies": { + "@uppy/core": "^4.5.2" + } + }, + "node_modules/@uppy/provider-views": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/@uppy/provider-views/-/provider-views-4.5.3.tgz", + "integrity": "sha512-zExJSlkqRPl65KKG+SMTdP0OCawYMpo/FaKE8xjqHhx/rkACe6QNExCahpEGGjLo7Rr2j7FooAuA3UWmYiyWCg==", + "license": "MIT", + "dependencies": { + "@uppy/utils": "^6.2.2", + "classnames": "^2.2.6", + "nanoid": "^5.0.9", + "p-queue": "^8.0.0", + "preact": "^10.5.13" + }, + "peerDependencies": { + "@uppy/core": "^4.5.3" + } + }, + "node_modules/@uppy/provider-views/node_modules/nanoid": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.7.tgz", + "integrity": "sha512-ua3NDgISf6jdwezAheMOk4mbE1LXjm1DfMUDMuJf4AqxLFK3ccGpgWizwa5YV7Yz9EpXwEaWoRXSb/BnV0t5dQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/@uppy/status-bar": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@uppy/status-bar/-/status-bar-4.2.3.tgz", + "integrity": "sha512-0AtKdvNm3HHobuE4N0V8SrC3uWB9MQnjqMEL/gachW/1mi7iZ22V4veHd6Wub/tCBQAQbEklvz7d0hxcz/Fh9g==", + "license": "MIT", + "dependencies": { + "@transloadit/prettier-bytes": "^0.3.4", + "@uppy/utils": "^6.2.2", + "classnames": "^2.2.6", + "preact": "^10.5.13" + }, + "peerDependencies": { + "@uppy/core": "^4.5.2" + } + }, + "node_modules/@uppy/store-default": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@uppy/store-default/-/store-default-4.3.2.tgz", + "integrity": "sha512-dnY9R2o8fwmO1bF89D0b5jijD7DGED2qVST5hI/j18JreLWzLKH7u6HuNmOvzok8msrQ/qWzQd5Gx4LDQKhBbw==", + "license": "MIT" + }, + "node_modules/@uppy/thumbnail-generator": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@uppy/thumbnail-generator/-/thumbnail-generator-4.2.3.tgz", + "integrity": "sha512-qOfJzlHhaD8DmOH/50DMLNN5/E2qCYCJnikFgTZZbuPx6sUOtPGRrHBE8q/ELxVMB5gD3zGi/Fh2SwKGrGoxGA==", + "license": "MIT", + "dependencies": { + "@uppy/utils": "^6.2.2", + "exifr": "^7.0.0" + }, + "peerDependencies": { + "@uppy/core": "^4.5.3" + } + }, + "node_modules/@uppy/utils": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/@uppy/utils/-/utils-6.2.2.tgz", + "integrity": "sha512-9mYJtbcngv2HOJIECkyfmdXTI5dW/ObCyvWP1Iti3E5bKtsa4sMmbx5Yh/tGCj8k/lBNhfvWyZuYnvnjmzNLSQ==", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.21", + "preact": "^10.5.13" + } + }, + "node_modules/@uppy/xhr-upload": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@uppy/xhr-upload/-/xhr-upload-4.4.2.tgz", + "integrity": "sha512-CU66aVn4yghGklEkepCqFPulc6uygznApy2DpD+jCMLNB5q6yT1RPSrQUgRgXsYhpW1YhutZJWsrEnHEDS+Tcw==", + "license": "MIT", + "dependencies": { + "@uppy/companion-client": "^4.5.2", + "@uppy/utils": "^6.2.2" + }, + "peerDependencies": { + "@uppy/core": "^4.5.2" + } + }, + "node_modules/@vitejs/plugin-vue": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.5.tgz", + "integrity": "sha512-bL3AxKuQySfk1iGcBsQnoRVexTPJq0Z/ixFVM8OhVJAP6ZXXXLtM7NFKWhLl30Kg7uTBqIaPXbh+nuQCuBDedg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "1.0.0-rc.2" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz", + "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.28" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz", + "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.28", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz", + "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.31.tgz", + "integrity": "sha512-k/ueL14aNIEy5Onf0OVzR8kiqF/WThgLdFhxwa4e/KF/0qe38IwIdofoSWBTvvxQOesaz6riAFAUaYjoF9fLLQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.2", + "@vue/shared": "3.5.31", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.31.tgz", + "integrity": "sha512-BMY/ozS/xxjYqRFL+tKdRpATJYDTTgWSo0+AJvJNg4ig+Hgb0dOsHPXvloHQ5hmlivUqw1Yt2pPIqp4e0v1GUw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.31", + "@vue/shared": "3.5.31" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.31.tgz", + "integrity": "sha512-M8wpPgR9UJ8MiRGjppvx9uWJfLV7A/T+/rL8s/y3QG3u0c2/YZgff3d6SuimKRIhcYnWg5fTfDMlz2E6seUW8Q==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.2", + "@vue/compiler-core": "3.5.31", + "@vue/compiler-dom": "3.5.31", + "@vue/compiler-ssr": "3.5.31", + "@vue/shared": "3.5.31", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.8", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.31.tgz", + "integrity": "sha512-h0xIMxrt/LHOvJKMri+vdYT92BrK3HFLtDqq9Pr/lVVfE4IyKZKvWf0vJFW10Yr6nX02OR4MkJwI0c1HDa1hog==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.31", + "@vue/shared": "3.5.31" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.2.6.tgz", + "integrity": "sha512-xYYYX3/aVup576tP/23sEUpgiEnujrENaoNRbaozC1/MA9I6EGFQRJb4xrt/MmUCAGlxTKL2RmT8JLTPqagCkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.28", + "@vue/compiler-dom": "^3.5.0", + "@vue/shared": "^3.5.0", + "alien-signals": "^3.0.0", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1", + "picomatch": "^4.0.2" + } + }, + "node_modules/@vue/language-core/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.31.tgz", + "integrity": "sha512-DtKXxk9E/KuVvt8VxWu+6Luc9I9ETNcqR1T1oW1gf02nXaZ1kuAx58oVu7uX9XxJR0iJCro6fqBLw9oSBELo5g==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.31" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.31.tgz", + "integrity": "sha512-AZPmIHXEAyhpkmN7aWlqjSfYynmkWlluDNPHMCZKFHH+lLtxP/30UJmoVhXmbDoP1Ng0jG0fyY2zCj1PnSSA6Q==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.31", + "@vue/shared": "3.5.31" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.31.tgz", + "integrity": "sha512-xQJsNRmGPeDCJq/u813tyonNgWBFjzfVkBwDREdEWndBnGdHLHgkwNBQxLtg4zDrzKTEcnikUy1UUNecb3lJ6g==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.31", + "@vue/runtime-core": "3.5.31", + "@vue/shared": "3.5.31", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.31.tgz", + "integrity": "sha512-GJuwRvMcdZX/CriUnyIIOGkx3rMV3H6sOu0JhdKbduaeCji6zb60iOGMY7tFoN24NfsUYoFBhshZtGxGpxO4iA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.31", + "@vue/shared": "3.5.31" + }, + "peerDependencies": { + "vue": "3.5.31" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.31.tgz", + "integrity": "sha512-nBxuiuS9Lj5bPkPbWogPUnjxxWpkRniX7e5UBQDWl6Fsf4roq9wwV+cR7ezQ4zXswNvPIlsdj1slcLB7XCsRAw==", + "license": "MIT" + }, + "node_modules/@vue/tsconfig": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@vue/tsconfig/-/tsconfig-0.8.1.tgz", + "integrity": "sha512-aK7feIWPXFSUhsCP9PFqPyFOcz4ENkb8hZ2pneL6m2UjCkccvaOhC/5KCKluuBufvp2KzkbdA2W2pk20vLzu3g==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "typescript": "5.x", + "vue": "^3.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "vue": { + "optional": true + } + } + }, + "node_modules/alien-signals": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.1.2.tgz", + "integrity": "sha512-d9dYqZTS90WLiU0I5c6DHj/HcKkF8ZyGN3G5x8wSbslulz70KOxaqCT0hQCo9KOyhVqzqGojvNdJXoTumZOtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/autoprefixer": { + "version": "10.4.27", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.27.tgz", + "integrity": "sha512-NP9APE+tO+LuJGn7/9+cohklunJsXWiaWEfV3si4Gi/XHDwVNgkwr1J3RQYFIvPy76GmJ9/bW8vyoU1LcxwKHA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.1", + "caniuse-lite": "^1.0.30001774", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.11", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.11.tgz", + "integrity": "sha512-DAKrHphkJyiGuau/cFieRYhcTFeK/lBuD++C7cZ6KZHbMhBrisoi+EvhQ5RZrIfV5qwsW8kgQ07JIC+MDJRAhg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001781", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001781.tgz", + "integrity": "sha512-RdwNCyMsNBftLjW6w01z8bKEvT6e/5tpPVEgtn22TiLGlstHOVecsX2KHFkD5e/vRnIE4EGzpuIODb3mtswtkw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/classnames": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", + "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.328", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.328.tgz", + "integrity": "sha512-QNQ5l45DzYytThO21403XN3FvK0hOkWDG8viNf6jqS42msJ8I4tGDSpBCgvDRRPnkffafiwAym2X2eHeGD2V0w==", + "dev": true, + "license": "ISC" + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/exifr": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/exifr/-/exifr-7.1.3.tgz", + "integrity": "sha512-g/aje2noHivrRSLbAUtBPWFbxKdKhgj/xr1vATDdUXPOFYJlQ62Ft0oy+72V6XLIpDJfHs6gXLbBLAolqOXYRw==", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-network-error": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.1.tgz", + "integrity": "sha512-6QCxa49rQbmUWLfk0nuGqzql9U8uaV2H6279bRErPBHe/109hCzsLUBUHfbEtvLIHBd6hyXbgedBSHevm43Edw==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mime-match/-/mime-match-1.0.2.tgz", + "integrity": "sha512-VXp/ugGDVh3eCLOBCiHZMYWQaTNUHv2IJrut+yXA6+JbLPXHglHwfS/5A5L0ll+jkCY7fIzRJcH6OIunF+c6Cg==", + "license": "ISC", + "dependencies": { + "wildcard": "^1.1.0" + } + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/namespace-emitter": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/namespace-emitter/-/namespace-emitter-2.0.1.tgz", + "integrity": "sha512-N/sMKHniSDJBjfrkbS/tpkPj4RAbvW3mr8UAzvlMHyun93XEm83IAvhWtJVHo+RHn/oO8Job5YN4b+wRjSVp5g==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.36", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.36.tgz", + "integrity": "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/p-queue": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-8.1.1.tgz", + "integrity": "sha512-aNZ+VfjobsWryoiPnEApGGmf5WmNsCo9xu8dfaYamG5qaLP7ClhLN6NgsFe6SwJ2UbLEBK5dv9x8Mn5+RVhMWQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.1", + "p-timeout": "^6.1.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-6.2.1.tgz", + "integrity": "sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.2", + "is-network-error": "^1.0.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-6.1.4.tgz", + "integrity": "sha512-MyIV3ZA/PmyBN/ud8vV9XzwTrNtR4jFrObymZYnZqMmW0zA8Z17vnT0rBgFE/TlohB+YCHqXMgZzb3Csp49vqg==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz", + "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/preact": { + "version": "10.29.0", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.0.tgz", + "integrity": "sha512-wSAGyk2bYR1c7t3SZ3jHcM6xy0lcBcDel6lODcs9ME6Th++Dx2KU+6D3HD8wMMKGA8Wpw7OMd3/4RGzYRpzwRg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rolldown": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.12.tgz", + "integrity": "sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.122.0", + "@rolldown/pluginutils": "1.0.0-rc.12" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.12", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.12", + "@rolldown/binding-darwin-x64": "1.0.0-rc.12", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.12", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.12", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.12", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.12", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.12", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.12", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.12", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.12", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.12" + } + }, + "node_modules/rolldown/node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.12.tgz", + "integrity": "sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/shallow-equal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/shallow-equal/-/shallow-equal-3.1.0.tgz", + "integrity": "sha512-pfVOw8QZIXpMbhBWvzBISicvToTiM5WBF1EeAUZDDSb5Dt29yl4AYbyywbJFSEsRUMr7gJaxqCdr4L3tQf9wVg==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.19", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz", + "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.7", + "lilconfig": "^3.1.3", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.3.tgz", + "integrity": "sha512-B9ifbFudT1TFhfltfaIPgjo9Z3mDynBTJSUYxTjOQruf/zHH+ezCQKcoqO+h7a9Pw9Nm/OtlXAiGT1axBgwqrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.8", + "rolldown": "1.0.0-rc.12", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.1.0", + "esbuild": "^0.27.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.31", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.31.tgz", + "integrity": "sha512-iV/sU9SzOlmA/0tygSmjkEN6Jbs3nPoIPFhCMLD2STrjgOU8DX7ZtzMhg4ahVwf5Rp9KoFzcXeB1ZrVbLBp5/Q==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.31", + "@vue/compiler-sfc": "3.5.31", + "@vue/runtime-dom": "3.5.31", + "@vue/server-renderer": "3.5.31", + "@vue/shared": "3.5.31" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.6.4", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", + "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-tsc": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.2.6.tgz", + "integrity": "sha512-gYW/kWI0XrwGzd0PKc7tVB/qpdeAkIZLNZb10/InizkQjHjnT8weZ/vBarZoj4kHKbUTZT/bAVgoOr8x4NsQ/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.28", + "@vue/language-core": "3.2.6" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/wildcard": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-1.1.2.tgz", + "integrity": "sha512-DXukZJxpHA8LuotRwL0pP1+rS6CS7FF2qStDDE1C7DDg2rLud2PXRMuEDYIPhgEezwnlHNL4c+N6MfMTjCGTng==", + "license": "MIT" + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 00000000..42f05413 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,29 @@ +{ + "name": "document-cleaning-frontend", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@uppy/core": "^4.5.2", + "@uppy/dashboard": "^4.4.2", + "@uppy/xhr-upload": "^4.3.3", + "vue": "^3.5.25", + "vue-router": "^4.6.4" + }, + "devDependencies": { + "@types/node": "^24.10.1", + "@vitejs/plugin-vue": "^6.0.2", + "@vue/tsconfig": "^0.8.1", + "autoprefixer": "^10.4.24", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.17", + "typescript": "~5.9.3", + "vite": "^8.0.0-beta.13", + "vue-tsc": "^3.1.5" + } +} diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 00000000..75af5769 --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,7 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {} + } +} + diff --git a/frontend/src/App.vue b/frontend/src/App.vue new file mode 100644 index 00000000..d4622dfc --- /dev/null +++ b/frontend/src/App.vue @@ -0,0 +1,5 @@ + diff --git a/frontend/src/components/DifyHealthDialog.vue b/frontend/src/components/DifyHealthDialog.vue new file mode 100644 index 00000000..0669f6c2 --- /dev/null +++ b/frontend/src/components/DifyHealthDialog.vue @@ -0,0 +1,359 @@ + + + diff --git a/frontend/src/components/DifySettingsDialog.vue b/frontend/src/components/DifySettingsDialog.vue new file mode 100644 index 00000000..1636a182 --- /dev/null +++ b/frontend/src/components/DifySettingsDialog.vue @@ -0,0 +1,281 @@ + + + diff --git a/frontend/src/components/LocaleSwitcher.vue b/frontend/src/components/LocaleSwitcher.vue new file mode 100644 index 00000000..69512d85 --- /dev/null +++ b/frontend/src/components/LocaleSwitcher.vue @@ -0,0 +1,26 @@ + + + diff --git a/frontend/src/components/StatusPill.vue b/frontend/src/components/StatusPill.vue new file mode 100644 index 00000000..8a0bad2a --- /dev/null +++ b/frontend/src/components/StatusPill.vue @@ -0,0 +1,28 @@ + + + diff --git a/frontend/src/components/ToastStack.vue b/frontend/src/components/ToastStack.vue new file mode 100644 index 00000000..c81b1a3e --- /dev/null +++ b/frontend/src/components/ToastStack.vue @@ -0,0 +1,28 @@ + + + diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts new file mode 100644 index 00000000..773a533a --- /dev/null +++ b/frontend/src/lib/api.ts @@ -0,0 +1,76 @@ +import { authState, clearSession } from './auth' + +type RequestOptions = RequestInit & { + skipAuth?: boolean +} + +export async function apiFetch(path: string, options: RequestOptions = {}) { + const headers = new Headers(options.headers || {}) + if (!options.skipAuth && authState.token) { + headers.set('Authorization', `Bearer ${authState.token}`) + } + if (!(options.body instanceof FormData) && !headers.has('Content-Type')) { + headers.set('Content-Type', 'application/json') + } + const response = await fetch(path, { ...options, headers }) + if (response.status === 401) { + clearSession() + window.location.href = '/login' + throw new Error('Unauthorized') + } + if (!response.ok) { + let detail = response.statusText + try { + const data = await response.json() + detail = data.detail || JSON.stringify(data) + } catch { + detail = await response.text() + } + throw new Error(detail) + } + if (response.status === 204) { + return null + } + const contentType = response.headers.get('content-type') || '' + if (contentType.includes('application/json')) { + return response.json() + } + return response +} + +export async function downloadBlob(path: string, options: RequestOptions = {}, filename?: string) { + const headers = new Headers(options.headers || {}) + if (authState.token) { + headers.set('Authorization', `Bearer ${authState.token}`) + } + const response = await fetch(path, { ...options, headers }) + if (!response.ok) { + throw new Error(await response.text()) + } + const blob = await response.blob() + const disposition = response.headers.get('content-disposition') || '' + const utf8Match = disposition.match(/filename\*\s*=\s*UTF-8''([^;]+)/i) + const quotedMatch = disposition.match(/filename\s*=\s*"([^"]+)"/i) + const plainMatch = disposition.match(/filename\s*=\s*([^;]+)/i) + const resolvedFilename = + filename || + (utf8Match?.[1] + ? (() => { + try { + return decodeURIComponent(utf8Match[1].trim()) + } catch { + return utf8Match[1].trim() + } + })() + : quotedMatch?.[1] || plainMatch?.[1]?.trim()) || + 'download.bin' + const url = window.URL.createObjectURL(blob) + const link = document.createElement('a') + link.href = url + link.download = resolvedFilename + link.style.display = 'none' + document.body.appendChild(link) + link.click() + link.remove() + window.URL.revokeObjectURL(url) +} diff --git a/frontend/src/lib/auth.ts b/frontend/src/lib/auth.ts new file mode 100644 index 00000000..a0466280 --- /dev/null +++ b/frontend/src/lib/auth.ts @@ -0,0 +1,39 @@ +import { reactive } from 'vue' + +type SessionUser = { + id: number + username: string + full_name?: string | null + role: string + accessible_group_ids?: number[] + primary_department_id?: number | null + primary_department_name?: string | null + accessible_department_ids?: number[] +} + +type SessionState = { + token: string + user: SessionUser | null +} + +const storedToken = localStorage.getItem('dc_token') || '' +const storedUser = localStorage.getItem('dc_user') + +export const authState = reactive({ + token: storedToken, + user: storedUser ? JSON.parse(storedUser) : null +}) + +export function setSession(token: string, user: SessionUser) { + authState.token = token + authState.user = user + localStorage.setItem('dc_token', token) + localStorage.setItem('dc_user', JSON.stringify(user)) +} + +export function clearSession() { + authState.token = '' + authState.user = null + localStorage.removeItem('dc_token') + localStorage.removeItem('dc_user') +} diff --git a/frontend/src/lib/i18n.ts b/frontend/src/lib/i18n.ts new file mode 100644 index 00000000..dc119034 --- /dev/null +++ b/frontend/src/lib/i18n.ts @@ -0,0 +1,1038 @@ +import { computed, reactive } from 'vue' + +export type Locale = 'en' | 'zh' + +type TranslationParams = Record + +const LOCALE_KEY = 'dc_locale' + +const messages: Record> = { + en: { + common: { + language: 'Language', + settings: 'Settings', + edit: 'Edit', + english: 'EN', + chinese: '中文', + refresh: 'Refresh', + save: 'Save', + cancel: 'Cancel', + signOut: 'Sign Out', + signIn: 'Sign In', + unknown: 'Unknown', + loading: 'Loading...', + none: 'None', + yes: 'Yes', + no: 'No' + }, + roles: { + super_admin: 'Super Admin', + admin: 'Admin', + user: 'User' + }, + status: { + queued: 'Queued', + running: 'Converting', + success: 'Completed', + failed: 'Failed', + unsynced: 'Unsynced', + syncing: 'Syncing', + synced: 'Synced', + sync_failed: 'Sync Failed', + stale: 'Needs Resync' + }, + login: { + productName: 'Document Cleaning', + heading: 'Put document cleaning, version tracking, and Dify sync into one workspace.', + description: + 'Upload into knowledge bases, deduplicate files, queue conversions, download markdown in bulk, and sync curated content into Dify without leaving the internal web app.', + signInLabel: 'Sign In', + enterWorkspace: 'Enter Workspace', + username: 'Username', + password: 'Password', + passwordPlaceholder: 'Enter password', + loginFailed: 'Login failed.', + signingIn: 'Signing in...', + signInContinue: 'Sign in to continue', + cards: { + batchUploadTitle: 'Batch Upload', + batchUploadBody: + 'Upload raw files by knowledge base. The system detects duplicates by SHA-256 and creates versions only when content changed.', + queuedConversionTitle: 'Queued Conversion', + queuedConversionBody: + 'Conversion and Dify sync both run in the background so the workspace stays responsive under larger batches.', + difyMappingTitle: 'Dify Mapping', + difyMappingBody: + 'The first sync auto-creates a dataset for the knowledge base. Later syncs update the same logical document instead of duplicating it.' + } + }, + workspace: { + title: 'Knowledge Workspace', + refreshFiles: 'Refresh Files', + adminConsole: 'Permissions', + groupsTitle: 'Knowledge Bases', + groupsSubtitle: 'Select a knowledge base to work with local documents and Dify.', + createGroupPanel: 'Create Knowledge Base', + createGroupDialogTitle: 'Create Knowledge Base', + editGroupDialogTitle: 'Edit Knowledge Base', + addGroup: 'New Knowledge Base', + editGroup: 'Edit', + noDescriptionYet: 'No description yet.', + datasetLinked: 'Dataset: %{id}', + datasetNotLinkedYet: 'Dataset not linked yet', + difyLinkedStatus: 'Linked to Dify', + difyUnlinkedStatus: 'Not linked to Dify', + noGroupsYet: 'No knowledge base yet. Create one first.', + noGroupSelectedHint: 'Select a knowledge base to edit or delete it.', + currentGroup: 'Current Knowledge Base', + selectGroup: 'Select a knowledge base', + groupDescriptionFallback: 'Knowledge bases hold local documents and optional Dify mappings.', + currentKnowledgeBaseHint: 'Select a knowledge base, then upload files or inspect Dify differences.', + groupNameRequired: 'Knowledge base name is required.', + departmentRequired: 'Department is required.', + globalOverview: 'Global Overview', + allKnowledgeBases: 'All Knowledge Bases', + globalOverviewTitle: 'System Snapshot', + globalOverviewHint: 'Monitor overall knowledge-base volume, document volume, and in-flight processing from one place.', + knowledgeBaseCount: 'Knowledge Bases', + totalFiles: 'All Files', + runningFiles: 'Running Files', + documents: 'Documents', + selected: 'Selected', + running: 'Running', + batchUpload: 'Batch Upload', + uploadSubtitle: + 'Powered by Uppy. Upload one or many files. Duplicate hashes in the same group are skipped with an explicit result summary.', + selectGroupBeforeUploading: 'Select a knowledge base before uploading.', + uploadFiles: 'Upload Files', + uploadFolder: 'Upload Folder', + uploadDialogTitle: 'Batch Upload', + uploadProgressHint: 'Progress and failures are shown in this upload panel after files are added.', + uploadModalHint: 'Upload is opened in a modal. After upload is queued, the server can continue processing even if your browser closes.', + uploadNote: '.doc .docx .pdf .xls .xlsx .csv .ppt .pptx', + searchTitle: 'Search file name', + allConversionStates: 'All conversion states', + allSyncStates: 'All sync states', + formatPlaceholder: 'Format, for example .docx', + applyFilters: 'Query', + clearFilters: 'Reset', + batchSyncToDify: 'Batch Sync Dify', + downloadMarkdown: 'Batch Download Markdown', + downloadOriginals: 'Batch Download Originals', + documentsTableTitle: 'Documents', + documentsTableSubtitle: + 'Columns include title, preview, format, size, convert status, Dify status, upload time, uploader, and actions.', + selectAll: 'Select All', + clearSelection: 'Clear Selection', + knowledgeBaseColumn: 'Knowledge Base', + titleColumn: 'File Name', + fileNameColumn: 'File Name', + formatColumn: 'Format', + sizeColumn: 'Size', + statusColumn: 'Status', + difySyncColumn: 'Dify Status', + uploadedAtColumn: 'Uploaded At', + uploaderColumn: 'Uploader', + versionColumn: 'Version', + actionsColumn: 'Actions', + loadingFiles: 'Loading files...', + noDocumentsFound: 'No documents found for the current filters.', + original: 'Original', + markdown: 'Markdown', + downloadOriginal: 'Download Original', + downloadMd: 'Download Markdown', + syncToDify: 'Sync Dify', + sync: 'Push', + retry: 'Retry', + delete: 'Delete', + deleteGroup: 'Delete Knowledge Base', + deleteGroupDialogEyebrow: 'Delete Knowledge Base', + deleteGroupDialogTitle: 'Confirm Knowledge Base Deletion', + deleteGroupSyncDify: 'Sync delete Dify knowledge base', + deleteGroupSyncDifyHint: 'When checked, the linked Dify dataset will be deleted together with the local group.', + confirmDeleteGroup: 'Delete Knowledge Base', + viewDifyDiff: 'View Dify Diff', + viewCurrentDifyDiff: 'Current Dify Diff', + viewGlobalDifyDiff: 'Global Dify Diff', + refreshDiff: 'Refresh Diff', + queryDiff: 'Query Differences', + diffDialogTitle: 'Current Knowledge Base Differences', + globalDiffDialogTitle: 'Global Dify Differences', + diffSearchPlaceholder: 'Search all files in the current knowledge base by file name', + globalDiffSearchPlaceholder: 'Search current difference results by knowledge base or file name', + diffSearchByKnowledgeBase: 'Knowledge Base', + diffSearchByFileName: 'File Name', + diffSearchByKnowledgeBasePlaceholder: 'Search current difference results by knowledge base', + diffSearchByFileNamePlaceholder: 'Search current difference results by file name', + globalDiffHint: 'Compare local knowledge bases and Dify documents across the whole system.', + diffIssueTitle: 'Action Queue', + diffIssueHint: '%{count} item(s) still need attention.', + diffAllAligned: 'This knowledge base is already aligned with Dify.', + diffMatchedHint: 'All current rows are matched. Expand them only when you need to audit the details.', + diffShowMatched: 'Show Matched (%{count})', + diffHideMatched: 'Hide Matched', + diffActionMatched: 'No action needed', + diffActionPushToDify: 'Push to Dify', + diffActionCheckDify: 'Review in Dify', + diffActionReview: 'Review mapping', + diffExpandDetails: 'Details', + diffCollapseDetails: 'Hide Details', + diffStateColumn: 'Difference', + diffLocalColumn: 'Local', + diffDifyColumn: 'Dify', + diffMatched: 'Bidirectional Sync', + diffLocalOnly: 'Current Only', + diffDifyOnly: 'Dify Only', + diffAttention: 'Needs Attention', + diffQueryPrompt: 'Click "Query Differences" to compare this knowledge base with Dify.', + diffEmpty: 'No difference rows match the current filter.', + diffPaginationSummary: 'Showing %{shown} of %{total} rows', + prevPage: 'Previous', + nextPage: 'Next', + pageIndicator: 'Page %{page} / %{total}', + previewOriginal: 'Preview Original', + previewMarkdown: 'View Markdown', + previewDialogEyebrow: 'Online Preview', + previewUnsupported: 'This file format cannot be previewed directly in the browser yet. Download it instead.', + previewFailed: 'Failed to load preview.', + uploadQueued: 'Upload queued: %{created}. Duplicates skipped: %{duplicates}%{suffix}.', + duplicateSuffix: ' (%{names})', + syncQueued: 'Dify push queued.', + syncCurrent: 'Sync Current', + syncCurrentUnavailable: 'Syncing Dify documents back into the current system is not supported yet.', + syncCurrentImported: 'Imported the Dify document into the current system.', + retryQueued: 'Retry job queued.', + batchSyncQueued: 'Queued Dify push for %{count} document(s).', + documentDeleted: 'Document deleted.', + groupDeleted: 'Knowledge base deleted.', + deleteDocumentPrompt: 'Delete document "%{name}" from this knowledge base?', + deleteDocumentSyncDify: 'Sync delete Dify document', + deleteDocumentSyncDifyHint: 'When checked, the linked Dify document will be deleted together with the local file.', + deletePrompt: + 'Delete the linked Dify document too?\nOK = delete local file and Dify document.\nCancel = delete only the local file.', + deleteGroupPromptLocal: 'Delete knowledge base "%{name}" and all its local documents?', + deleteGroupPromptDify: 'Delete the linked Dify dataset too?', + uploadFailed: 'Upload failed.', + failedToLoadFiles: 'Failed to load files.', + failedToCreateGroup: 'Failed to create group.', + failedToSaveGroup: 'Failed to save group.', + failedToDeleteGroup: 'Failed to delete group.', + failedToLoadDifyDiff: 'Failed to load Dify differences.', + failedToQueueSync: 'Failed to queue sync.', + failedToImportFromDify: 'Failed to import the Dify document into the current system.', + failedToQueueRetry: 'Failed to queue retry.', + failedToQueueBatchSync: 'Failed to queue batch sync.', + failedToDeleteDocument: 'Failed to delete document.' + }, + admin: { + title: 'Permission Management', + heading: 'System Administration', + backToWorkspace: 'Back to Workspace', + users: 'Permission Management', + permissionsHeading: 'Permission Management', + permissionsHint: 'Manage departments, user roles, and knowledge-base visibility.', + permissionsPageTitle: 'User & Access Control', + permissionsPageHint: 'Users can see knowledge bases in their primary department and any extra departments you grant.', + username: 'Username', + fullName: 'Full Name', + password: 'Password', + passwordOptional: 'Leave blank to keep the current password.', + role: 'Role', + active: 'Active', + action: 'Action', + enabled: 'Enabled', + disabled: 'Disabled', + createUser: 'Add User', + editUser: 'Edit User', + saveUser: 'Save', + noUsers: 'No users yet.', + groups: 'Knowledge Bases', + groupName: 'Knowledge base name', + groupDescription: 'Description', + createGroup: 'Create Knowledge Base', + rename: 'Rename', + renameGroupPrompt: 'Enter a new knowledge base name.', + renameDifyPrompt: 'Also rename the linked Dify dataset if it already exists?', + groupNoDescription: 'No description yet.', + groupNotLinked: 'Not linked yet', + departmentsTitle: 'Departments', + createDepartment: 'Add Department', + editDepartment: 'Edit Department', + deleteDepartment: 'Delete Department', + departmentName: 'Department Name', + departmentDescription: 'Department Description', + departmentCreated: 'Department created.', + departmentUpdated: 'Department updated.', + departmentDeleted: 'Department deleted.', + departmentDeletedWithMigration: 'Department deleted and knowledge bases moved.', + failedToSaveDepartment: 'Failed to save department.', + failedToDeleteDepartment: 'Failed to delete department.', + userCount: 'Users', + primaryDepartment: 'Primary Department', + additionalDepartments: 'Additional Departments', + departmentAccessHint: 'Users can see knowledge bases in their primary department and any extra departments you grant here.', + createDepartmentFirst: 'Create a department first before creating users or knowledge bases.', + primaryDepartmentRequired: 'Primary department is required.', + deleteDepartmentNeedsMigration: 'This department still has knowledge bases or users.', + deleteDepartmentNeedsMigrationHint: 'Choose another department first, then the current department can be deleted after migration.', + deleteDepartmentTargetRequired: 'Select a target department before deleting this department.', + deleteDepartmentEmptyHint: 'This department is empty and can be deleted directly.', + selectMigrationDepartment: 'Select migration target department', + difyDefaults: 'Dify Defaults', + openDifySettings: 'Dify Settings', + settingsDialogTitle: 'Dify Settings', + difyModelCatalog: 'Available Dify Models', + difyPermission: 'Dify Permission', + indexingTechnique: 'Indexing Technique', + searchMethod: 'Search Method', + docForm: 'Document Form', + embeddingModel: 'Embedding Model', + rerankModel: 'Rerank Model', + topK: 'Top K', + scoreThreshold: 'Score Threshold', + automaticChoice: 'Automatic (recommended)', + automaticSummary: 'When left on automatic, the system prefers higher-capability Qwen models if available and falls back to the first active model.', + currentAutomaticEmbedding: 'Automatic embedding now resolves to: %{value}', + currentAutomaticRerank: 'Automatic rerank now resolves to: %{value}', + enableScoreThreshold: 'Enable score threshold', + saveDifyDefaults: 'Save Dify Defaults', + difyHealth: 'Dify Health', + difyHealthTitle: 'Queue & Watchdog', + difyHealthHint: 'Check Dify API reachability, worker concurrency, queue pressure, and local stuck-sync cleanup from one panel.', + healthStatus: 'Watchdog Status', + difyApi: 'Dify API', + workerConcurrency: 'Worker Concurrency', + pendingQueue: 'Pending Queue', + staleCandidates: 'Stuck Syncs', + activeSyncJobs: 'Active Sync Jobs', + lastCheckedAt: 'Last Checked', + lastRestartAt: 'Last Restart', + recoverStaleSyncs: 'Recover Stuck Syncs', + recoverStaleSyncsHint: 'Use this only when a sync has been stuck for too long and you want to mark it as failed so it can be retried.', + noStaleSyncsFound: 'No stuck syncs found.', + staleSyncRecovered: 'Recovered %{count} stuck sync(s).', + watchdogSnapshotMissing: 'No watchdog snapshot yet. The host watchdog may not be installed or has not run.', + watchdogIssues: 'Current Issues', + watchdogActions: 'Recent Actions', + noWatchdogIssues: 'No current watchdog issues.', + noWatchdogActions: 'No watchdog actions recorded.', + activeTasks: 'Active / Reserved Tasks', + localSyncHealth: 'Local Sync Health', + noneRunning: 'No Dify tasks are running right now.', + routingKey: 'Queue', + timeoutSeconds: 'Timeout', + noStaleDocuments: 'No stale syncing documents.', + statusOk: 'Healthy', + statusWarning: 'Needs Attention', + statusRestarted: 'Recovered', + statusInvalidSnapshot: 'Snapshot Error', + healthUnavailable: 'Unavailable', + recentJobs: 'Recent Jobs', + noMessage: 'No message', + noJobsYet: 'No jobs yet.', + failedToLoadAdminData: 'Failed to load admin data.', + failedToLoadDifyHealth: 'Failed to load Dify health.', + userCreated: 'User created.', + failedToCreateUser: 'Failed to create user.', + userSaved: 'Saved changes for %{username}.', + failedToUpdateUser: 'Failed to update user.', + userAccess: 'Knowledge Base Access', + accessHint: 'Control which knowledge bases are visible to this user.', + superAdminAllAccess: 'Super admins always have full access to all knowledge bases.', + noKnowledgeBases: 'No knowledge bases yet.', + usersPanelHint: 'Only super admins can change users, roles, and knowledge-base access.', + groupCreated: 'Knowledge base created.', + failedToCreateGroup: 'Failed to create knowledge base.', + groupUpdated: 'Knowledge base updated.', + difyDefaultsSaved: 'Dify defaults saved.', + failedToSaveSettings: 'Failed to save settings.', + failedToRecoverStaleSyncs: 'Failed to recover stale syncs.' + } + }, + zh: { + common: { + edit: '编辑', + settings: '设置', + language: '语言', + english: 'EN', + chinese: '中文', + refresh: '刷新', + save: '保存', + cancel: '取消', + signOut: '退出登录', + signIn: '登录', + unknown: '未知', + loading: '加载中...', + none: '无', + yes: '是', + no: '否' + }, + roles: { + super_admin: '超级管理员', + admin: '管理员', + user: '用户' + }, + status: { + queued: '排队中', + running: '转换中', + success: '已完成', + failed: '失败', + unsynced: '未同步', + syncing: '同步中', + synced: '已同步', + sync_failed: '同步失败', + stale: '需要重新同步' + }, + login: { + productName: '文档清洗系统', + heading: '把文档清洗、版本追踪和 Dify 同步放进同一个工作台。', + description: + '按知识库上传、自动去重、后台排队转换、批量下载 Markdown,并把整理后的知识同步到 Dify,全程都在同一套内网页面里完成。', + signInLabel: '登录', + enterWorkspace: '进入工作台', + username: '用户名', + password: '密码', + passwordPlaceholder: '请输入密码', + loginFailed: '登录失败。', + signingIn: '登录中...', + signInContinue: '登录并继续', + cards: { + batchUploadTitle: '批量上传', + batchUploadBody: '按知识库上传原始文件。系统会用 SHA-256 检测重复内容,只有内容变化时才创建新版本。', + queuedConversionTitle: '后台转换', + queuedConversionBody: '转换和 Dify 同步都在后台执行,大批量文件时页面依然保持可操作。', + difyMappingTitle: 'Dify 映射', + difyMappingBody: '首次同步会自动为知识库创建数据集,后续同步会更新同一逻辑文档,而不是重复新增。' + } + }, + workspace: { + title: '知识工作台', + refreshFiles: '刷新文件', + adminConsole: '权限管理', + groupsTitle: '知识库', + groupsSubtitle: '选择一个知识库后,再继续处理本地文档和 Dify。', + createGroupPanel: '新建知识库', + createGroupDialogTitle: '新建知识库', + editGroupDialogTitle: '编辑知识库', + addGroup: '新增知识库', + editGroup: '编辑', + noDescriptionYet: '暂无描述。', + datasetLinked: '数据集:%{id}', + datasetNotLinkedYet: '尚未关联数据集', + difyLinkedStatus: '已关联 Dify', + difyUnlinkedStatus: '未关联 Dify', + noGroupsYet: '当前还没有知识库,请先创建。', + noGroupSelectedHint: '先选择一个知识库,再编辑或删除它。', + currentGroup: '当前知识库', + selectGroup: '请选择知识库', + groupDescriptionFallback: '知识库用于承载本地文档,并可按需关联到 Dify。', + currentKnowledgeBaseHint: '选择一个知识库后,可上传文件、查看差异并同步到 Dify。', + departmentRequired: '请选择所属部门。', + groupNameRequired: '知识库名称不能为空。', + globalOverview: '全局概览', + allKnowledgeBases: '全量知识库', + globalOverviewTitle: '系统总览', + globalOverviewHint: '在一个视图里查看知识库总量、文件总量和运行中的任务。', + knowledgeBaseCount: '知识库数量', + totalFiles: '所有文件', + runningFiles: '运行中文件', + documents: '文档数', + selected: '已选', + running: '运行中', + batchUpload: '批量上传', + uploadSubtitle: '基于 Uppy。支持一次上传一个或多个文件,同组内重复哈希会被明确标记并跳过。', + selectGroupBeforeUploading: '请先选择知识库再上传。', + uploadFiles: '上传文件', + uploadFolder: '上传文件夹', + uploadDialogTitle: '批量上传', + uploadProgressHint: '文件加入后,进度和失败信息会在这个上传面板里显示。', + uploadModalHint: '上传通过弹窗完成;只要已经加入队列,后续处理由服务器继续执行。', + uploadNote: '支持 .doc .docx .pdf .xls .xlsx .csv .ppt .pptx', + searchTitle: '搜索文件名', + allConversionStates: '全部转换状态', + allSyncStates: '全部同步状态', + formatPlaceholder: '格式,例如 .docx', + applyFilters: '查询', + clearFilters: '重置', + batchSyncToDify: '批量同步Dify', + downloadMarkdown: '批量下载Markdown', + downloadOriginals: '批量下载原文件', + documentsTableTitle: '文件列表', + documentsTableSubtitle: '列包含标题、在线预览、格式、大小、转换状态、Dify 状态、上传时间、上传人和操作。', + selectAll: '全选', + clearSelection: '清空选择', + knowledgeBaseColumn: '知识库', + titleColumn: '文件名', + fileNameColumn: '文件名', + formatColumn: '格式', + sizeColumn: '大小', + statusColumn: '转换状态', + difySyncColumn: 'Dify 状态', + uploadedAtColumn: '上传时间', + uploaderColumn: '上传人', + versionColumn: '版本', + actionsColumn: '操作', + loadingFiles: '正在加载文件...', + noDocumentsFound: '当前筛选条件下没有文档。', + original: '原文件', + markdown: 'Markdown', + downloadOriginal: '下载原文件', + downloadMd: '下载Markdown', + syncToDify: '同步Dify', + sync: '推送', + retry: '重试', + delete: '删除', + deleteGroup: '删除知识库', + deleteGroupDialogEyebrow: '删除知识库', + deleteGroupDialogTitle: '确认删除知识库', + deleteGroupSyncDify: '同步删除Dify知识库', + deleteGroupSyncDifyHint: '勾选后,会同时删除该知识库关联的 Dify 知识库。', + confirmDeleteGroup: '删除知识库', + viewDifyDiff: '查看 Dify 差异', + viewCurrentDifyDiff: '查看当前 Dify 差异', + viewGlobalDifyDiff: '查看全局 Dify 差异', + refreshDiff: '刷新差异', + queryDiff: '查询差异', + diffDialogTitle: '当前知识库差异', + globalDiffDialogTitle: '全局 Dify 差异', + diffSearchPlaceholder: '按文件名搜索当前知识库内所有文件', + globalDiffSearchPlaceholder: '按知识库或文件名搜索当前差异结果', + diffSearchByKnowledgeBase: '知识库', + diffSearchByFileName: '文件名', + diffSearchByKnowledgeBasePlaceholder: '按知识库搜索当前差异结果', + diffSearchByFileNamePlaceholder: '按文件名搜索当前差异结果', + globalDiffHint: '查看整个系统中本地知识库与 Dify 的差异。', + diffIssueTitle: '待处理清单', + diffIssueHint: '还有 %{count} 项需要处理。', + diffAllAligned: '当前知识库已与 Dify 对齐。', + diffMatchedHint: '当前内容都已匹配,只有在需要复核时再展开查看。', + diffShowMatched: '查看已匹配(%{count})', + diffHideMatched: '收起已匹配', + diffActionMatched: '无需处理', + diffActionPushToDify: '推送到 Dify', + diffActionCheckDify: '去 Dify 核对', + diffActionReview: '人工核对', + diffExpandDetails: '查看详情', + diffCollapseDetails: '收起详情', + diffStateColumn: '差异状态', + diffLocalColumn: '本地', + diffDifyColumn: 'Dify', + diffMatched: '双向同步', + diffLocalOnly: '仅当前', + diffDifyOnly: '仅 Dify', + diffAttention: '需处理', + diffQueryPrompt: '点击“查询差异”后再比对当前知识库与 Dify。', + diffEmpty: '当前筛选条件下没有差异项。', + diffPaginationSummary: '当前显示 %{shown} / %{total} 条', + prevPage: '上一页', + nextPage: '下一页', + pageIndicator: '第 %{page} / %{total} 页', + previewOriginal: '查看原文件', + previewMarkdown: '查看Markdown', + previewDialogEyebrow: '在线预览', + previewUnsupported: '当前格式暂不支持浏览器内直接预览,请下载后查看。', + previewFailed: '加载预览失败。', + uploadQueued: '已加入上传队列:%{created}。已跳过重复文件:%{duplicates}%{suffix}。', + duplicateSuffix: '(%{names})', + syncQueued: '已加入 Dify 推送队列。', + syncCurrent: '同步当前', + syncCurrentUnavailable: '暂未支持把 Dify 文档回拉到当前系统。', + syncCurrentImported: '已将 Dify 文档导入当前系统。', + retryQueued: '已加入重试队列。', + batchSyncQueued: '已为 %{count} 个文档加入 Dify 推送队列。', + documentDeleted: '文档已删除。', + groupDeleted: '知识库已删除。', + deleteDocumentPrompt: '确认删除文档“%{name}”吗?', + deleteDocumentSyncDify: '同步删除 Dify 文档', + deleteDocumentSyncDifyHint: '勾选后,会同时删除该文档在 Dify 中的关联文档。', + deletePrompt: + '是否同时删除关联的 Dify 文档?\n确定 = 删除本地文件和 Dify 文档。\n取消 = 只删除本地文件。', + deleteGroupPromptLocal: '确认删除知识库“%{name}”以及其下所有本地文档吗?', + deleteGroupPromptDify: '是否同时删除关联的 Dify 数据集?', + uploadFailed: '上传失败。', + failedToLoadFiles: '加载文件失败。', + failedToCreateGroup: '创建知识库失败。', + failedToSaveGroup: '保存知识库失败。', + failedToDeleteGroup: '删除知识库失败。', + failedToLoadDifyDiff: '加载 Dify 差异失败。', + failedToQueueSync: '加入同步队列失败。', + failedToImportFromDify: '导入 Dify 文档到当前系统失败。', + failedToQueueRetry: '加入重试队列失败。', + failedToQueueBatchSync: '加入批量同步队列失败。', + failedToDeleteDocument: '删除文档失败。' + }, + admin: { + title: '权限管理', + heading: '权限管理', + backToWorkspace: '返回工作台', + users: '权限管理', + permissionsHeading: '权限管理', + permissionsHint: '管理部门、用户角色和知识库可见范围。', + permissionsPageTitle: '用户与权限', + permissionsPageHint: '用户默认可见主部门内的知识库,也可追加其他部门权限。', + username: '用户名', + fullName: '姓名', + password: '密码', + passwordOptional: '留空则保持当前密码不变。', + role: '身份', + active: '启用状态', + action: '操作', + enabled: '已启用', + disabled: '已停用', + createUser: '创建用户', + editUser: '修改用户', + saveUser: '保存', + noUsers: '当前还没有用户。', + groups: '知识库', + groupName: '知识库名称', + groupDescription: '描述', + createGroup: '创建知识库', + rename: '重命名', + renameGroupPrompt: '请输入新的知识库名称。', + renameDifyPrompt: '是否同时重命名已关联的 Dify 知识库?', + groupNoDescription: '暂无描述。', + groupNotLinked: '未关联', + departmentsTitle: '部门管理', + createDepartment: '创建部门', + editDepartment: '修改部门', + departmentName: '部门名称', + departmentDescription: '部门说明', + departmentCreated: '部门已创建。', + departmentUpdated: '部门已更新。', + failedToSaveDepartment: '保存部门失败。', + userCount: '成员数', + primaryDepartment: '主部门', + additionalDepartments: '额外部门权限', + departmentAccessHint: '用户默认可见主部门知识库,这里可以追加其他部门的可见权限。', + createDepartmentFirst: '请先创建部门,再创建用户或知识库。', + primaryDepartmentRequired: '主部门不能为空。', + difyDefaults: 'Dify 设置', + openDifySettings: 'Dify设置', + settingsDialogTitle: 'Dify设置', + difyModelCatalog: '可用 Dify 模型', + difyPermission: 'Dify 权限', + indexingTechnique: '索引策略', + searchMethod: '检索方式', + docForm: '文档形态', + embeddingModel: 'Embedding 模型', + rerankModel: 'Rerank 模型', + topK: 'Top K', + scoreThreshold: '分数阈值', + automaticChoice: '自动选择(推荐)', + automaticSummary: '保持自动时,系统会优先选择能力更强且当前可用的 Qwen 模型,不可用时再回退。', + currentAutomaticEmbedding: '当前自动选择的 embedding:%{value}', + currentAutomaticRerank: '当前自动选择的 rerank:%{value}', + enableScoreThreshold: '启用分数阈值', + saveDifyDefaults: '保存 Dify 设置', + difyHealth: 'Dify健康状态', + difyHealthTitle: '队列与 Watchdog', + difyHealthHint: '查看 Dify API 连通性、worker 并发、队列压力以及本地卡住同步的回收情况。', + healthStatus: 'Watchdog 状态', + difyApi: 'Dify API', + workerConcurrency: 'Worker 并发', + pendingQueue: '待处理队列', + staleCandidates: '卡住同步', + activeSyncJobs: '活动同步任务', + lastCheckedAt: '最近检查', + lastRestartAt: '最近重启', + recoverStaleSyncs: '回收卡住同步', + recoverStaleSyncsHint: '用于把长时间卡住的同步记录回收成失败状态,方便后续重新同步。', + noStaleSyncsFound: '没有发现需要回收的卡住同步。', + staleSyncRecovered: '已回收 %{count} 条卡住同步。', + watchdogSnapshotMissing: '还没有 watchdog 快照,可能是服务器 watchdog 尚未安装或尚未运行。', + watchdogIssues: '当前问题', + watchdogActions: '最近动作', + noWatchdogIssues: '当前没有 watchdog 问题。', + noWatchdogActions: '当前没有 watchdog 动作记录。', + activeTasks: '活动 / 保留任务', + localSyncHealth: '本地同步健康', + noneRunning: '当前没有 Dify 任务在运行。', + routingKey: '队列', + timeoutSeconds: '超时阈值', + noStaleDocuments: '当前没有卡住同步文档。', + statusOk: '健康', + statusWarning: '需要关注', + statusRestarted: '已恢复', + statusInvalidSnapshot: '快照异常', + healthUnavailable: '不可用', + recentJobs: '最近任务', + noMessage: '无信息', + noJobsYet: '当前还没有任务。', + failedToLoadAdminData: '加载权限数据失败。', + failedToLoadDifyHealth: '加载 Dify 健康状态失败。', + userCreated: '用户已创建。', + failedToCreateUser: '创建用户失败。', + userSaved: '已保存 %{username} 的修改。', + failedToUpdateUser: '更新用户失败。', + userAccess: '知识库权限', + accessHint: '控制该用户可见哪些知识库。', + superAdminAllAccess: '超级管理员默认拥有所有知识库权限。', + noKnowledgeBases: '当前还没有知识库。', + usersPanelHint: '只有超级管理员可以调整用户、角色和知识库权限。', + groupCreated: '知识库已创建。', + failedToCreateGroup: '创建知识库失败。', + groupUpdated: '知识库已更新。', + difyDefaultsSaved: 'Dify 设置已保存。', + failedToSaveSettings: '保存设置失败。', + failedToRecoverStaleSyncs: '回收卡住同步失败。' + } + } +} + +Object.assign(messages.zh.common as Record, { + edit: '\u7f16\u8f91' +}) + +Object.assign(messages.en.common as Record, { + clear: 'Clear', +}) + +Object.assign(messages.zh.common as Record, { + clear: '清空', +}) + +Object.assign(messages.en.workspace as Record, { + uploadRejectedListTitle: '%{count} file(s) were not added', + uploadRejectedListHint: 'These files were rejected before upload started. Please check the file type, count limit, or file validity.', + unknownFile: 'Unknown file' +}) + +Object.assign(messages.zh.workspace as Record, { + uploadRejectedListTitle: '有 %{count} 个文件未加入上传列表', + uploadRejectedListHint: '这些文件在上传开始前就被拒绝了,请检查文件格式、数量限制或文件本身是否有效。', + unknownFile: '未知文件' +}) + +Object.assign(messages.zh.admin as Record, { + permissionsHeading: '\u7528\u6237\u6743\u9650', + createUser: '\u65b0\u589e\u7528\u6237', + createDepartment: '\u65b0\u589e\u90e8\u95e8', + permissionsPageTitle: '\u7528\u6237\u6743\u9650', + departmentPermissions: '\u90e8\u95e8\u6743\u9650', + noDepartmentPlaceholder: '\u8bf7\u5148\u65b0\u589e\u90e8\u95e8', + userStatusUpdated: '\u7528\u6237\u542f\u7528\u72b6\u6001\u5df2\u66f4\u65b0\u3002', + failedToToggleUserStatus: '\u66f4\u65b0\u7528\u6237\u542f\u7528\u72b6\u6001\u5931\u8d25\u3002', + deleteDepartment: '\u5220\u9664\u90e8\u95e8', + departmentDeleted: '\u90e8\u95e8\u5df2\u5220\u9664\u3002', + departmentDeletedWithMigration: '\u90e8\u95e8\u5df2\u5220\u9664\uff0c\u5df2\u5c06\u77e5\u8bc6\u5e93\u8fc1\u79fb\u5230\u65b0\u90e8\u95e8\u3002', + failedToDeleteDepartment: '\u5220\u9664\u90e8\u95e8\u5931\u8d25\u3002', + deleteDepartmentNeedsMigration: '\u5f53\u524d\u90e8\u95e8\u4ecd\u6709\u77e5\u8bc6\u5e93\u6216\u7528\u6237\u6743\u9650\u3002', + deleteDepartmentNeedsMigrationHint: '\u8bf7\u5148\u9009\u62e9\u53e6\u4e00\u4e2a\u90e8\u95e8\u8fdb\u884c\u8fc1\u79fb\uff0c\u518d\u5220\u9664\u5f53\u524d\u90e8\u95e8\u3002', + deleteDepartmentTargetRequired: '\u5220\u9664\u90e8\u95e8\u524d\uff0c\u8bf7\u5148\u9009\u62e9\u8fc1\u79fb\u76ee\u6807\u90e8\u95e8\u3002', + deleteDepartmentEmptyHint: '\u5f53\u524d\u90e8\u95e8\u4e0b\u65e0\u77e5\u8bc6\u5e93\u6216\u7528\u6237\uff0c\u53ef\u76f4\u63a5\u5220\u9664\u3002', + selectMigrationDepartment: '\u8bf7\u9009\u62e9\u8fc1\u79fb\u76ee\u6807\u90e8\u95e8' +}) + +Object.assign(messages.en.admin as Record, { + permissionsHeading: 'User Permissions', + permissionsPageTitle: 'User Permissions', + departmentPermissions: 'Department Permissions', + noDepartmentPlaceholder: 'Create a department first', + sharedPostgresUsage: 'Shared PostgreSQL', + sharedPostgresUnavailable: 'Unavailable', + userStatusUpdated: 'User status updated.', + failedToToggleUserStatus: 'Failed to update user status.', + deleteUser: 'Delete User', + deleteUserPrompt: 'Delete user "%{username}"?', + userDeleted: 'User deleted.', + failedToDeleteUser: 'Failed to delete user.', + deleteUserDisabled: 'The current account cannot be deleted.', +}) + +Object.assign(messages.zh.admin as Record, { + sharedPostgresUsage: '\u5171\u4eab PostgreSQL \u5360\u7528', + sharedPostgresUnavailable: '\u4e0d\u53ef\u7528', + deleteUser: '\u5220\u9664\u7528\u6237', + deleteUserPrompt: '\u786e\u8ba4\u5220\u9664\u7528\u6237\u201c%{username}\u201d\uff1f', + userDeleted: '\u7528\u6237\u5df2\u5220\u9664\u3002', + failedToDeleteUser: '\u5220\u9664\u7528\u6237\u5931\u8d25\u3002', + deleteUserDisabled: '\u5f53\u524d\u8d26\u53f7\u4e0d\u80fd\u88ab\u5220\u9664\u3002', +}) + +Object.assign(messages.zh.admin as Record, { + difyDefaults: 'Dify 设置', + openDifySettings: 'Dify 设置', + settingsDialogTitle: 'Dify 设置', + difyModelCatalog: '可用 Dify 模型', + difyPermission: 'Dify 权限', + indexingTechnique: '索引策略', + searchMethod: '检索方式', + docForm: '文档形态', + embeddingModel: 'Embedding 模型', + rerankModel: 'Rerank 模型', + topK: 'Top K', + scoreThreshold: '分数阈值', + automaticChoice: '自动选择(推荐)', + automaticSummary: '保持自动时,系统会优先选择能力更强且当前可用的 Qwen 模型,不可用时再回退。', + currentAutomaticEmbedding: '当前自动选择的 embedding:%{value}', + currentAutomaticRerank: '当前自动选择的 rerank:%{value}', + enableScoreThreshold: '启用分数阈值', + saveDifyDefaults: '保存 Dify 设置', + difyHealth: 'Dify 健康状态', + difyHealthTitle: '队列与 Watchdog', + difyHealthHint: '查看 Dify API 连通性、worker 并发、队列压力以及本地卡住同步的回收情况。', + healthStatus: 'Watchdog 状态', + difyApi: 'Dify API', + workerConcurrency: 'Worker 并发', + pendingQueue: '待处理队列', + staleCandidates: '卡住同步', + activeSyncJobs: '活动同步任务', + lastCheckedAt: '最近检查', + lastRestartAt: '最近重启', + recoverStaleSyncs: '回收卡住同步', + recoverStaleSyncsHint: '用于把长时间卡住的同步记录回收成失败状态,方便后续重新同步。', + noStaleSyncsFound: '没有发现需要回收的卡住同步。', + staleSyncRecovered: '已回收 %{count} 条卡住同步。', + watchdogSnapshotMissing: '还没有 watchdog 快照,可能是服务器 watchdog 尚未安装或尚未运行。', + watchdogIssues: '当前问题', + watchdogActions: '最近动作', + noWatchdogIssues: '当前没有 watchdog 问题。', + noWatchdogActions: '当前没有 watchdog 动作记录。', + activeTasks: '活动 / 保留任务', + localSyncHealth: '本地同步健康', + noneRunning: '当前没有 Dify 任务在运行。', + routingKey: '队列', + timeoutSeconds: '超时阈值', + noStaleDocuments: '当前没有卡住同步文档。', + statusOk: '健康', + statusWarning: '需要关注', + statusRestarted: '已恢复', + statusInvalidSnapshot: '快照异常', + healthUnavailable: '不可用', + recentJobs: '最近任务', + noMessage: '无信息', + noJobsYet: '当前还没有任务。', + failedToLoadAdminData: '加载权限数据失败。', + failedToLoadDifyHealth: '加载 Dify 健康状态失败。', + userCreated: '用户已创建。', + failedToCreateUser: '创建用户失败。', + userSaved: '已保存 %{username} 的修改。', + failedToUpdateUser: '更新用户失败。', + userAccess: '知识库权限', + accessHint: '控制该用户可见哪些知识库。', + superAdminAllAccess: '超级管理员默认拥有所有知识库权限。', + noKnowledgeBases: '当前还没有知识库。', + usersPanelHint: '只有超级管理员可以调整用户、角色和知识库权限。', + groupCreated: '知识库已创建。', + failedToCreateGroup: '创建知识库失败。', + groupUpdated: '知识库已更新。', + difyDefaultsSaved: 'Dify 设置已保存。', + failedToSaveSettings: '保存设置失败。', + failedToRecoverStaleSyncs: '回收卡住同步失败。' +}) + +Object.assign(messages.en.common as Record, { + chinese: '中文', +}) + +Object.assign(messages.en.workspace as Record, { + documentDeleteQueued: 'Delete submitted. Cleanup will continue in the background.', +}) + +Object.assign(messages.zh.admin as Record, { + title: '用户权限', + heading: '系统管理', + backToWorkspace: '返回工作台', + users: '用户权限', + permissionsHeading: '用户权限', + permissionsHint: '管理部门、用户角色和知识库可见范围。', + permissionsPageTitle: '用户权限', + permissionsPageHint: '用户默认可见部门权限内的知识库,也可以追加其他部门权限。', + username: '用户名', + fullName: '姓名', + password: '密码', + passwordOptional: '留空则保持当前密码不变。', + role: '身份', + active: '启用状态', + action: '操作', + enabled: '已启用', + disabled: '已停用', + createUser: '新增用户', + editUser: '编辑用户', + saveUser: '保存', + noUsers: '当前还没有用户。', + groups: '知识库', + groupName: '知识库名称', + groupDescription: '描述', + createGroup: '新增知识库', + rename: '重命名', + renameGroupPrompt: '请输入新的知识库名称。', + renameDifyPrompt: '是否同时重命名已关联的 Dify 知识库?', + groupNoDescription: '暂无描述。', + groupNotLinked: '未关联', + departmentsTitle: '部门管理', + createDepartment: '新增部门', + editDepartment: '编辑部门', + deleteDepartment: '删除部门', + departmentName: '部门名称', + departmentDescription: '部门说明', + departmentCreated: '部门已创建。', + departmentUpdated: '部门已更新。', + departmentDeleted: '部门已删除。', + departmentDeletedWithMigration: '部门已删除,已将知识库迁移到新部门。', + failedToSaveDepartment: '保存部门失败。', + failedToDeleteDepartment: '删除部门失败。', + userCount: '成员数', + primaryDepartment: '主部门', + additionalDepartments: '部门权限', + departmentAccessHint: '控制该用户可以访问哪些部门的知识库。', + createDepartmentFirst: '请先新增部门,再创建用户或知识库。', + primaryDepartmentRequired: '必须选择主部门。', + deleteDepartmentNeedsMigration: '当前部门仍有关联知识库或用户权限。', + deleteDepartmentNeedsMigrationHint: '请选择另一个部门接收迁移后,再删除当前部门。', + deleteDepartmentTargetRequired: '删除部门前,请先选择迁移目标部门。', + deleteDepartmentEmptyHint: '当前部门下没有关联知识库或用户,可直接删除。', + selectMigrationDepartment: '请选择迁移目标部门', + difyDefaults: 'Dify设置', + openDifySettings: 'Dify设置', + settingsDialogTitle: 'Dify设置', + difyModelCatalog: '可用 Dify 模型', + difyPermission: 'Dify 权限', + indexingTechnique: '索引策略', + searchMethod: '检索方式', + docForm: '文档形态', + embeddingModel: 'Embedding 模型', + rerankModel: 'Rerank 模型', + topK: 'Top K', + scoreThreshold: '分数阈值', + automaticChoice: '自动选择(推荐)', + automaticSummary: '保持自动时,系统会优先选择当前可用且能力更强的 Qwen 模型,不可用时再回退。', + currentAutomaticEmbedding: '当前自动选择的 embedding:%{value}', + currentAutomaticRerank: '当前自动选择的 rerank:%{value}', + enableScoreThreshold: '启用分数阈值', + saveDifyDefaults: '保存 Dify 设置', + difyHealth: 'Dify健康状态', + difyHealthTitle: '队列与 Watchdog', + difyHealthHint: '在一个面板里查看 Dify API 连通性、worker 并发、队列压力以及本地卡住同步的回收情况。', + healthStatus: 'Watchdog 状态', + difyApi: 'Dify API', + workerConcurrency: 'Worker 并发', + pendingQueue: '待处理队列', + staleCandidates: '卡住同步', + activeSyncJobs: '活动同步任务', + lastCheckedAt: '最近检查', + lastRestartAt: '最近重启', + recoverStaleSyncs: '回收卡住同步', + recoverStaleSyncsHint: '用于把长时间卡住的同步记录回收成失败状态,方便后续重新同步。', + noStaleSyncsFound: '没有发现需要回收的卡住同步。', + staleSyncRecovered: '已回收 %{count} 条卡住同步。', + watchdogSnapshotMissing: '还没有 watchdog 快照,可能是服务器 watchdog 尚未安装或尚未运行。', + watchdogIssues: '当前问题', + watchdogActions: '最近动作', + noWatchdogIssues: '当前没有 watchdog 问题。', + noWatchdogActions: '当前没有 watchdog 动作记录。', + activeTasks: '活动 / 保留任务', + localSyncHealth: '本地同步健康', + noneRunning: '当前没有 Dify 任务在运行。', + routingKey: '队列', + timeoutSeconds: '超时阈值', + noStaleDocuments: '当前没有卡住同步文档。', + statusOk: '健康', + statusWarning: '需要关注', + statusRestarted: '已恢复', + statusInvalidSnapshot: '快照异常', + healthUnavailable: '不可用', + recentJobs: '最近任务', + noMessage: '无信息', + noJobsYet: '当前还没有任务。', + failedToLoadAdminData: '加载权限数据失败。', + failedToLoadDifyHealth: '加载 Dify 健康状态失败。', + userCreated: '用户已创建。', + failedToCreateUser: '创建用户失败。', + userSaved: '已保存 %{username} 的修改。', + failedToUpdateUser: '更新用户失败。', + userAccess: '知识库权限', + accessHint: '控制该用户可以访问哪些知识库。', + superAdminAllAccess: '超级管理员默认拥有全部知识库权限。', + noKnowledgeBases: '当前还没有知识库。', + usersPanelHint: '只有超级管理员可以调整用户、角色和知识库权限。', + groupCreated: '知识库已创建。', + failedToCreateGroup: '创建知识库失败。', + groupUpdated: '知识库已更新。', + difyDefaultsSaved: 'Dify 设置已保存。', + failedToSaveSettings: '保存设置失败。', + failedToRecoverStaleSyncs: '回收卡住同步失败。', + departmentPermissions: '部门权限', + noDepartmentPlaceholder: '请先新增部门', + userStatusUpdated: '用户启用状态已更新。', + failedToToggleUserStatus: '更新用户启用状态失败。', + sharedPostgresUsage: '共享 PostgreSQL 占用', + sharedPostgresUnavailable: '不可用', + deleteUser: '删除用户', + deleteUserPrompt: '确认删除用户“%{username}”?', + userDeleted: '用户已删除。', + failedToDeleteUser: '删除用户失败。', + deleteUserDisabled: '当前账号不能被删除。', +}) + +Object.assign(messages.zh.workspace as Record, { + documentDeleteQueued: '删除已提交,后台将继续清理文件。', + paginationSummary: '显示第 %{start}-%{end} 条,共 %{total} 个文件', + rowsPerPage: '每页', + rowsPerPageOption: '%{size} / 页', + prevPage: '上一页', + nextPage: '下一页', + pageIndicator: '第 %{page} / %{total} 页', +}) + +Object.assign(messages.en.workspace as Record, { + paginationSummary: 'Showing %{start}-%{end} of %{total} files', + rowsPerPage: 'Rows per page', + rowsPerPageOption: '%{size} / page', +}) + +function resolveInitialLocale(): Locale { + if (typeof window === 'undefined') return 'en' + const stored = window.localStorage.getItem(LOCALE_KEY) + return stored === 'zh' ? 'zh' : 'en' +} + +function readMessage(locale: Locale, key: string): string | undefined { + const resolved = key + .split('.') + .reduce((current, segment) => { + if (!current || typeof current !== 'object') return undefined + return (current as Record)[segment] + }, messages[locale]) + return typeof resolved === 'string' ? resolved : undefined +} + +function interpolate(template: string, params: TranslationParams = {}) { + return template.replace(/%\{(\w+)\}/g, (_, token) => String(params[token] ?? '')) +} + +function applyDocumentLanguage(locale: Locale) { + if (typeof document === 'undefined') return + document.documentElement.lang = locale === 'zh' ? 'zh-CN' : 'en' +} + +export const i18nState = reactive<{ locale: Locale }>({ + locale: resolveInitialLocale() +}) + +applyDocumentLanguage(i18nState.locale) + +export function setLocale(locale: Locale) { + i18nState.locale = locale + if (typeof window !== 'undefined') { + window.localStorage.setItem(LOCALE_KEY, locale) + } + applyDocumentLanguage(locale) +} + +export function translate(key: string, params?: TranslationParams) { + const template = readMessage(i18nState.locale, key) || readMessage('en', key) || key + return interpolate(template, params) +} + +export function localeCode(locale = i18nState.locale) { + return locale === 'zh' ? 'zh-CN' : 'en-US' +} + +export function useI18n() { + return { + locale: computed(() => i18nState.locale), + setLocale, + t: translate + } +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts new file mode 100644 index 00000000..9028cbbd --- /dev/null +++ b/frontend/src/main.ts @@ -0,0 +1,7 @@ +import { createApp } from 'vue' +import App from './App.vue' +import router from './router' +import './style.css' + +createApp(App).use(router).mount('#app') + diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts new file mode 100644 index 00000000..18d29f98 --- /dev/null +++ b/frontend/src/router/index.ts @@ -0,0 +1,45 @@ +import { createRouter, createWebHistory } from 'vue-router' +import { authState } from '@/lib/auth' +import LoginView from '@/views/LoginView.vue' +import WorkspaceView from '@/views/WorkspaceView.vue' +import AdminView from '@/views/AdminView.vue' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { + path: '/', + redirect: '/workspace' + }, + { + path: '/login', + component: LoginView, + meta: { guestOnly: true } + }, + { + path: '/workspace', + component: WorkspaceView, + meta: { requiresAuth: true } + }, + { + path: '/admin', + component: AdminView, + meta: { requiresAuth: true, adminOnly: true } + } + ] +}) + +router.beforeEach((to) => { + if (to.meta.requiresAuth && !authState.token) { + return '/login' + } + if (to.meta.guestOnly && authState.token) { + return '/workspace' + } + if (to.meta.adminOnly && !['super_admin', 'admin'].includes(authState.user?.role || '')) { + return '/workspace' + } + return true +}) + +export default router diff --git a/frontend/src/style.css b/frontend/src/style.css new file mode 100644 index 00000000..224da501 --- /dev/null +++ b/frontend/src/style.css @@ -0,0 +1,395 @@ +@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&family=Noto+Sans+SC:wght@400;500;700&display=swap'); + +@tailwind base; +@tailwind components; +@tailwind utilities; + +:root { + color: #122033; + background: + radial-gradient(circle at 12% 14%, rgba(21, 115, 255, 0.18), transparent 30%), + radial-gradient(circle at 86% 18%, rgba(255, 113, 71, 0.12), transparent 24%), + radial-gradient(circle at 78% 88%, rgba(31, 195, 154, 0.14), transparent 28%), + linear-gradient(180deg, #f6f8fc 0%, #ecf1f7 100%); + font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-width: 320px; + min-height: 100vh; + position: relative; + color: #122033; +} + +body::before { + content: ''; + position: fixed; + inset: 0; + pointer-events: none; + background-image: + linear-gradient(rgba(18, 32, 51, 0.035) 1px, transparent 1px), + linear-gradient(90deg, rgba(18, 32, 51, 0.035) 1px, transparent 1px); + background-size: 32px 32px; + mask-image: linear-gradient(180deg, rgba(0, 0, 0, 0.9), rgba(0, 0, 0, 0.22)); +} + +body::after { + content: ''; + position: fixed; + right: -10rem; + top: 8rem; + width: 28rem; + height: 28rem; + border-radius: 9999px; + pointer-events: none; + background: radial-gradient(circle, rgba(21, 115, 255, 0.18) 0%, rgba(21, 115, 255, 0) 70%); + filter: blur(8px); +} + +#app { + min-height: 100vh; +} + +.app-shell { + min-height: 100vh; +} + +.panel { + @apply rounded-panel border border-slate-300/90 bg-white/80 shadow-soft backdrop-blur-xl; + position: relative; + box-shadow: + 0 18px 50px rgba(18, 32, 51, 0.1), + inset 0 1px 0 rgba(255, 255, 255, 0.72); +} + +.panel::before { + content: ''; + position: absolute; + inset: 0 0 auto 0; + height: 3px; + background: linear-gradient(90deg, rgba(21, 115, 255, 0.92), rgba(31, 195, 154, 0.72), rgba(255, 113, 71, 0.72)); +} + +.input { + @apply w-full rounded-2xl border border-slate-300 bg-white px-4 py-3 text-sm text-ink outline-none transition focus:border-surge focus:ring-4 focus:ring-surge/10; + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.7), + 0 1px 2px rgba(18, 32, 51, 0.04); +} + +.btn { + @apply inline-flex items-center justify-center gap-2 rounded-2xl px-4 py-2.5 text-sm font-medium transition; +} + +.btn-primary { + @apply btn border border-transparent bg-ink text-white hover:-translate-y-0.5 hover:bg-slate-800; + box-shadow: 0 12px 24px rgba(18, 32, 51, 0.18); +} + +.btn-ghost { + @apply btn border border-slate-300 bg-white text-ink hover:-translate-y-0.5 hover:border-surge hover:text-surge; + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.7), + 0 1px 2px rgba(18, 32, 51, 0.05); +} + +.dialog-static-btn, +.dialog-static-btn:hover, +.dialog-static-btn:focus-visible, +.dialog-static-btn:active { + transform: none !important; +} + +.dialog-static-btn { + transition: + border-color 140ms ease, + color 140ms ease, + background-color 140ms ease, + box-shadow 140ms ease !important; +} + +.icon-btn { + @apply inline-flex h-8 w-8 items-center justify-center rounded-full border border-slate-300 bg-white transition hover:-translate-y-0.5 hover:border-surge hover:text-surge disabled:cursor-not-allowed disabled:opacity-60; +} + +.group-card .group-card-actions { + opacity: 0; + pointer-events: none; + transition: + opacity 160ms ease, + transform 160ms ease, + border-color 180ms ease, + background-color 180ms ease, + color 180ms ease; + transform: translateY(-50%) scale(0.96); +} + +.group-card .group-card-status-dot { + opacity: 1; + transition: opacity 160ms ease; +} + +.group-card:hover .group-card-actions, +.group-card .group-card-actions:focus-within { + opacity: 1; + pointer-events: auto; + transform: translateY(-50%) scale(1); +} + +.group-card:hover .group-card-status-dot { + opacity: 0; +} + +@media (hover: none) { + .group-card .group-card-actions { + opacity: 1; + pointer-events: auto; + transform: translateY(-50%) scale(1); + } + + .group-card .group-card-status-dot { + opacity: 0; + } +} + +.tag { + @apply inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold; + letter-spacing: 0.02em; +} + +.select-shell { + @apply inline-flex items-center gap-2 rounded-2xl border border-slate-300 bg-white px-3 py-2 text-sm shadow-soft backdrop-blur-xl; +} + +.select-label { + @apply text-xs font-semibold uppercase tracking-[0.18em] text-dusk; +} + +.select-control { + @apply rounded-xl border-0 bg-transparent py-1 pl-1 pr-7 text-sm font-semibold text-ink outline-none; +} + +.menu-shell { + position: relative; +} + +.menu-trigger { + @apply inline-flex cursor-pointer items-center gap-2 rounded-full px-3 py-2 text-sm font-semibold text-ink transition hover:bg-white/80 hover:text-surge; + list-style: none; + user-select: none; +} + +.menu-trigger::-webkit-details-marker { + display: none; +} + +.menu-trigger-icon { + @apply h-4 w-4 text-dusk transition; +} + +.menu-shell[open] .menu-trigger { + @apply border-surge text-surge; +} + +.menu-shell[open] .menu-trigger-icon { + transform: rotate(180deg); +} + +.menu-popover { + @apply absolute right-0 top-[calc(100%+0.5rem)] z-40 rounded-2xl border border-slate-200 bg-white/95 p-1 shadow-soft backdrop-blur-xl; +} + +.menu-item { + @apply flex w-full items-center justify-center rounded-xl px-4 py-2 text-center text-sm font-medium text-ink transition hover:bg-mist hover:text-surge; +} + +.user-menu { + @apply relative inline-flex items-center outline-none; +} + +.user-menu::after { + content: ''; + position: absolute; + left: -0.5rem; + right: -0.5rem; + top: 100%; + height: 10px; +} + +.user-menu-trigger { + @apply inline-flex items-center gap-1 rounded-xl px-1.5 py-1 text-[15px] font-semibold text-ink transition; +} + +.user-menu:hover .user-menu-trigger, +.user-menu:focus-within .user-menu-trigger { + @apply text-surge; +} + +.user-menu-panel { + @apply absolute left-1/2 top-[calc(100%+0.45rem)] z-50 min-w-[132px] rounded-2xl border border-slate-300 bg-white p-1 shadow-soft backdrop-blur-xl; + opacity: 0; + pointer-events: none; + visibility: hidden; + transform: translate(-50%, 4px); + transition: + opacity 160ms ease, + transform 160ms ease; +} + +.user-menu:hover .user-menu-panel, +.user-menu:focus-within .user-menu-panel { + opacity: 1; + pointer-events: auto; + visibility: visible; + transform: translate(-50%, 0); +} + +.user-menu-name { + @apply max-w-[156px] truncate text-[15px] font-semibold text-current; +} + +.user-menu-icon { + @apply h-3.5 w-3.5 text-dusk transition; +} + +.user-menu:hover .user-menu-icon, +.user-menu:focus-within .user-menu-icon { + @apply text-surge; + transform: rotate(180deg); +} + +.date-range-shell { + @apply flex items-center rounded-2xl border border-slate-300 bg-white px-3 py-2; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7); +} + +.date-range-input { + @apply min-w-0 flex-1 border-0 bg-transparent px-1 py-1 text-sm text-ink outline-none; +} + +.date-range-divider { + @apply px-2 text-sm font-semibold text-dusk; +} + +.file-title-link { + @apply block max-w-[8em] truncate text-left font-semibold text-surge underline decoration-surge/80 underline-offset-4 transition hover:text-blue-700; +} + +.file-title-text { + @apply block max-w-[8em] truncate font-semibold text-ink; +} + +.datetime-stack { + @apply flex flex-col leading-tight text-ink; +} + +.datetime-subtle { + @apply mt-1 text-xs text-dusk; +} + +.table-actions { + @apply flex flex-nowrap items-center gap-2 overflow-x-auto; +} + +.table-actions .btn-ghost { + transform: none !important; + transition: + border-color 140ms ease, + color 140ms ease, + background-color 140ms ease, + box-shadow 140ms ease !important; +} + +.table-actions .btn-ghost:hover, +.table-actions .btn-ghost:focus-visible, +.table-actions .btn-ghost:active { + transform: none !important; +} + +.table-action-btn { + @apply shrink-0 whitespace-nowrap justify-center rounded-xl px-3 py-2 text-xs; + transform: none !important; + transition: + border-color 140ms ease, + color 140ms ease, + background-color 140ms ease, + box-shadow 140ms ease; +} + +.table-action-btn:hover, +.table-action-btn:focus-visible { + transform: none !important; +} + +.status-toggle { + @apply inline-flex min-w-[132px] items-center justify-center gap-3 rounded-full border px-3 py-2 text-sm font-medium transition; +} + +.status-toggle:disabled { + @apply cursor-not-allowed opacity-60; +} + +.status-toggle-track { + @apply relative h-6 w-11 rounded-full border border-transparent transition; +} + +.status-toggle-thumb { + @apply absolute left-0.5 top-0.5 rounded-full bg-white shadow-sm transition; + height: 1.125rem; + width: 1.125rem; +} + +.status-toggle-label { + @apply whitespace-nowrap; +} + +.status-toggle--on { + @apply border-emerald-200 bg-emerald-50 text-emerald-700; +} + +.status-toggle--on .status-toggle-track { + @apply bg-emerald-500; +} + +.status-toggle--on .status-toggle-thumb { + transform: translateX(1.25rem); +} + +.status-toggle--off { + @apply border-slate-200 bg-slate-100 text-slate-600; +} + +.status-toggle--off .status-toggle-track { + @apply bg-slate-300; +} + +.uppy-compact .uppy-Dashboard-inner, +.uppy-compact .uppy-Dashboard-innerWrap { + min-height: 220px !important; +} + +.uppy-compact .uppy-Dashboard-inner { + width: 100% !important; + border: 1px dashed rgba(148, 163, 184, 0.45); + border-radius: 1.5rem; + background: linear-gradient(180deg, rgba(248, 250, 252, 0.82), rgba(255, 255, 255, 0.94)); +} + +.file-table { + table-layout: auto; +} + +.diff-table { + table-layout: fixed; + min-width: 960px; +} + +.file-table th, +.file-table td { + vertical-align: middle; +} diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue new file mode 100644 index 00000000..816835a0 --- /dev/null +++ b/frontend/src/views/AdminView.vue @@ -0,0 +1,769 @@ + + + diff --git a/frontend/src/views/LoginView.vue b/frontend/src/views/LoginView.vue new file mode 100644 index 00000000..8b5f77df --- /dev/null +++ b/frontend/src/views/LoginView.vue @@ -0,0 +1,100 @@ + + + diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue new file mode 100644 index 00000000..245205f6 --- /dev/null +++ b/frontend/src/views/WorkspaceView.vue @@ -0,0 +1,2051 @@ + + + diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts new file mode 100644 index 00000000..ed772106 --- /dev/null +++ b/frontend/src/vite-env.d.ts @@ -0,0 +1,2 @@ +/// + diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js new file mode 100644 index 00000000..cf70ad33 --- /dev/null +++ b/frontend/tailwind.config.js @@ -0,0 +1,24 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], + theme: { + extend: { + colors: { + ink: '#122033', + mist: '#f3f7fb', + surge: '#1573ff', + mint: '#1fc39a', + ember: '#ff7147', + dusk: '#5c6b82' + }, + boxShadow: { + soft: '0 16px 40px rgba(18, 32, 51, 0.08)' + }, + borderRadius: { + panel: '1.5rem' + } + } + }, + plugins: [] +} + diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json new file mode 100644 index 00000000..f7b4d39f --- /dev/null +++ b/frontend/tsconfig.app.json @@ -0,0 +1,13 @@ +{ + "extends": "@vue/tsconfig/tsconfig.dom.json", + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2022", + "types": ["vite/client"], + "baseUrl": ".", + "paths": { + "@/*": ["src/*"] + } + }, + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 00000000..e891e30d --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,8 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} + diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json new file mode 100644 index 00000000..8d33dcc4 --- /dev/null +++ b/frontend/tsconfig.node.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "composite": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "allowSyntheticDefaultImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/frontend/vite.config.d.ts b/frontend/vite.config.d.ts new file mode 100644 index 00000000..340562af --- /dev/null +++ b/frontend/vite.config.d.ts @@ -0,0 +1,2 @@ +declare const _default: import("vite").UserConfig; +export default _default; diff --git a/frontend/vite.config.js b/frontend/vite.config.js new file mode 100644 index 00000000..47673a8c --- /dev/null +++ b/frontend/vite.config.js @@ -0,0 +1,24 @@ +import { defineConfig } from 'vite'; +import vue from '@vitejs/plugin-vue'; +import path from 'node:path'; +export default defineConfig({ + plugins: [vue()], + resolve: { + alias: { + '@': path.resolve(__dirname, './src') + } + }, + server: { + port: 5174, + proxy: { + '/api': { + target: 'http://127.0.0.1:8000', + changeOrigin: true + }, + '/storage': { + target: 'http://127.0.0.1:8000', + changeOrigin: true + } + } + } +}); diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts new file mode 100644 index 00000000..932364ee --- /dev/null +++ b/frontend/vite.config.ts @@ -0,0 +1,26 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import path from 'node:path' + +export default defineConfig({ + plugins: [vue()], + resolve: { + alias: { + '@': path.resolve(__dirname, './src') + } + }, + server: { + port: 5174, + proxy: { + '/api': { + target: 'http://127.0.0.1:8000', + changeOrigin: true + }, + '/storage': { + target: 'http://127.0.0.1:8000', + changeOrigin: true + } + } + } +}) + diff --git a/ops/watchdog/dify_watchdog.py b/ops/watchdog/dify_watchdog.py new file mode 100644 index 00000000..6a7843dc --- /dev/null +++ b/ops/watchdog/dify_watchdog.py @@ -0,0 +1,534 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any +from urllib.error import URLError +from urllib.request import Request, urlopen + + +DEFAULT_QUEUE_KEYS = ("priority_dataset", "dataset", "priority_document", "document") + + +@dataclass +class CommandResult: + stdout: str + stderr: str + returncode: int + + +def utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Host watchdog for Document Cleaning + Dify") + parser.add_argument("--project-root", default="/home/inspur/tools/document-cleaning") + parser.add_argument("--dify-compose-dir", default="/data/ai-platform") + parser.add_argument("--app-api-container", default="doc-cleaning-api") + parser.add_argument("--app-worker-container", default="doc-cleaning-worker") + parser.add_argument("--app-redis-container", default="doc-cleaning-redis") + parser.add_argument("--app-queue-name", default="document-cleaning") + parser.add_argument("--dify-worker-container", default="dify-worker") + parser.add_argument("--shared-postgres-container", default="shared-postgres") + parser.add_argument("--dify-redis-container", default="shared-redis") + parser.add_argument("--dify-redis-password", default="difyai123456") + parser.add_argument("--stale-sync-timeout-seconds", type=int, default=900) + parser.add_argument("--stale-convert-timeout-seconds", type=int, default=900) + parser.add_argument("--convert-orphan-grace-seconds", type=int, default=120) + parser.add_argument("--stuck-task-seconds", type=int, default=600) + parser.add_argument("--restart-cooldown-seconds", type=int, default=300) + parser.add_argument("--local-queue-stuck-seconds", type=int, default=120) + parser.add_argument("--local-worker-restart-cooldown-seconds", type=int, default=300) + parser.add_argument("--shared-postgres-usage-threshold", type=float, default=0.8) + parser.add_argument("--shared-postgres-cooldown-seconds", type=int, default=180) + return parser.parse_args() + + +def run(command: list[str], *, input_text: str | None = None, check: bool = True) -> CommandResult: + completed = subprocess.run( + command, + input=input_text, + capture_output=True, + text=True, + check=False, + cwd=None, + ) + result = CommandResult( + stdout=completed.stdout.strip(), + stderr=completed.stderr.strip(), + returncode=completed.returncode, + ) + if check and completed.returncode != 0: + raise RuntimeError( + f"Command failed ({completed.returncode}): {' '.join(command)}\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" + ) + return result + + +def docker_exec(container: str, *args: str, check: bool = True, input_text: str | None = None) -> CommandResult: + return run(["docker", "exec", *(["-i"] if input_text is not None else []), container, *args], check=check, input_text=input_text) + + +def read_env_file(path: Path) -> dict[str, str]: + values: dict[str, str] = {} + if not path.exists(): + return values + for raw_line in path.read_text(encoding="utf-8").splitlines(): + line = raw_line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, value = line.split("=", 1) + values[key.strip()] = value.strip() + return values + + +def read_json_from_container(container: str, command: str) -> Any: + result = docker_exec(container, "sh", "-lc", command) + raw = result.stdout or "{}" + start = raw.find("{") + if start == -1: + start = raw.find("[") + if start == -1: + raise RuntimeError(f"JSON payload not found in command output: {raw}") + return json.loads(raw[start:]) + + +def inspect_worker_command(container: str) -> dict[str, Any]: + result = run(["docker", "top", container], check=False) + lines = [line for line in result.stdout.splitlines() if line.strip()] + command = lines[1].split(maxsplit=7)[-1] if len(lines) > 1 else "" + match = re.search(r"(?:^|\s)-c\s+(\d+)", command) + concurrency = int(match.group(1)) if match else None + return { + "online": result.returncode == 0 and len(lines) > 1, + "command": command, + "concurrency": concurrency, + } + + +def inspect_celery(container: str, command_name: str) -> dict[str, Any]: + payload = read_json_from_container( + container, + f"cd /app/api && /app/api/.venv/bin/celery -A celery_entrypoint.celery inspect {command_name} --json", + ) + tasks: list[dict[str, Any]] = [] + for worker_name, worker_tasks in payload.items(): + for task in worker_tasks or []: + task_copy = dict(task) + task_copy["worker"] = worker_name + time_start = task_copy.get("time_start") + if isinstance(time_start, (int, float)): + task_copy["runtime_seconds"] = max(0, int(datetime.now(timezone.utc).timestamp() - time_start)) + else: + task_copy["runtime_seconds"] = None + tasks.append(task_copy) + return {"workers": list(payload.keys()), "tasks": tasks} + + +def inspect_queue_lengths(container: str, password: str) -> dict[str, int]: + lengths: dict[str, int] = {} + for key in DEFAULT_QUEUE_KEYS: + result = docker_exec(container, "redis-cli", "-a", password, "LLEN", key) + lengths[key] = int((result.stdout or "0").splitlines()[-1].strip()) + return lengths + + +def inspect_local_queue_length(container: str, queue_name: str) -> int: + result = docker_exec(container, "redis-cli", "LLEN", f"rq:queue:{queue_name}") + return int((result.stdout or "0").splitlines()[-1].strip()) + + +def set_local_delay_gate(container: str, queue_name: str, name: str, ttl_seconds: int) -> None: + if ttl_seconds <= 0: + return + gate_key = f"{queue_name}:{name}" + docker_exec(container, "redis-cli", "SETEX", gate_key, str(ttl_seconds), "1") + + +def inspect_shared_postgres(container: str) -> dict[str, Any]: + max_result = docker_exec( + container, + "psql", + "-U", + "postgres", + "-d", + "postgres", + "-tAc", + "show max_connections;", + check=False, + ) + if max_result.returncode != 0: + return { + "available": False, + "max_connections": None, + "active_connections": None, + "usage_ratio": None, + "error": max_result.stderr or max_result.stdout or "Failed to inspect shared-postgres.", + } + + active_result = docker_exec( + container, + "psql", + "-U", + "postgres", + "-d", + "postgres", + "-tAc", + "select count(*) from pg_stat_activity;", + check=False, + ) + if active_result.returncode != 0: + return { + "available": False, + "max_connections": int((max_result.stdout or "0").strip() or 0), + "active_connections": None, + "usage_ratio": None, + "error": active_result.stderr or active_result.stdout or "Failed to inspect shared-postgres.", + } + + max_connections = int((max_result.stdout or "0").strip() or 0) + active_connections = int((active_result.stdout or "0").strip() or 0) + usage_ratio = (active_connections / max_connections) if max_connections else 0.0 + return { + "available": True, + "max_connections": max_connections, + "active_connections": active_connections, + "usage_ratio": usage_ratio, + "error": None, + } + + +def inspect_container_running(container: str) -> bool: + result = run(["docker", "inspect", "-f", "{{.State.Running}}", container], check=False) + return result.returncode == 0 and result.stdout.strip().lower() == "true" + + +def inspect_dify_api(env_file: Path) -> dict[str, Any]: + env = read_env_file(env_file) + base_url = env.get("DIFY_BASE_URL", "").rstrip("/") + api_key = env.get("DIFY_API_KEY", "") + configured = bool(base_url and api_key) + payload: dict[str, Any] = { + "configured": configured, + "base_url": base_url, + "reachable": False, + "dataset_count": None, + "error": None, + } + if not configured: + payload["error"] = "DIFY_BASE_URL or DIFY_API_KEY is missing." + return payload + + request = Request(f"{base_url}/datasets", headers={"Authorization": f"Bearer {api_key}"}) + try: + with urlopen(request, timeout=30) as response: + body = json.loads(response.read().decode("utf-8")) + except (URLError, OSError, TimeoutError, json.JSONDecodeError) as exc: + payload["error"] = str(exc) + return payload + + payload["reachable"] = True + payload["dataset_count"] = len(body.get("data", [])) + return payload + + +def run_app_cli(container: str, *args: str) -> dict[str, Any]: + result = docker_exec(container, "python", "-m", "app.watchdog_cli", *args) + return json.loads(result.stdout or "{}") + + +def read_state(path: Path) -> dict[str, Any]: + if not path.exists(): + return {} + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + + +def write_state(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + + +def write_snapshot(container: str, payload: dict[str, Any]) -> None: + docker_exec( + container, + "sh", + "-lc", + "mkdir -p /app/data/watchdog && cat > /app/data/watchdog/dify-health.json", + input_text=json.dumps(payload, ensure_ascii=False, indent=2), + ) + + +def should_restart(active_tasks: list[dict[str, Any]], *, stuck_task_seconds: int) -> tuple[bool, str | None]: + for task in active_tasks: + runtime = task.get("runtime_seconds") or 0 + name = task.get("name") or "" + if runtime >= stuck_task_seconds and "document_indexing" in name: + return True, f"{name} exceeded {stuck_task_seconds}s" + return False, None + + +def restart_dify_worker(compose_dir: Path) -> None: + completed = subprocess.run( + ["docker", "compose", "up", "-d", "dify-worker"], + capture_output=True, + text=True, + check=False, + cwd=compose_dir, + ) + if completed.returncode != 0: + raise RuntimeError( + f"Failed to restart dify-worker\nSTDOUT:\n{completed.stdout}\nSTDERR:\n{completed.stderr}" + ) + + +def restart_local_worker(compose_dir: Path) -> None: + completed = subprocess.run( + ["docker", "compose", "up", "-d", "worker"], + capture_output=True, + text=True, + check=False, + cwd=compose_dir, + ) + if completed.returncode != 0: + raise RuntimeError( + f"Failed to restart doc-cleaning worker\nSTDOUT:\n{completed.stdout}\nSTDERR:\n{completed.stderr}" + ) + + +def main() -> int: + args = parse_args() + project_root = Path(args.project_root) + state_path = project_root / "runtime" / "watchdog" / "state.json" + env_file = project_root / ".env" + compose_dir = Path(args.dify_compose_dir) + + worker = inspect_worker_command(args.dify_worker_container) + active = inspect_celery(args.dify_worker_container, "active") + reserved = inspect_celery(args.dify_worker_container, "reserved") + queues = inspect_queue_lengths(args.dify_redis_container, args.dify_redis_password) + local_queue_length = inspect_local_queue_length(args.app_redis_container, args.app_queue_name) + local_worker_online = inspect_container_running(args.app_worker_container) + shared_postgres = inspect_shared_postgres(args.shared_postgres_container) + api = inspect_dify_api(env_file) + stale_recovery = run_app_cli( + args.app_api_container, + "recover-stale-syncs", + "--timeout-seconds", + str(args.stale_sync_timeout_seconds), + ) + convert_recovery = run_app_cli( + args.app_api_container, + "recover-stale-converts", + "--timeout-seconds", + str(args.stale_convert_timeout_seconds), + "--orphan-grace-seconds", + str(args.convert_orphan_grace_seconds), + ) + local_summary = run_app_cli( + args.app_api_container, + "summary", + "--timeout-seconds", + str(args.stale_sync_timeout_seconds), + ) + local_convert_summary = run_app_cli( + args.app_api_container, + "convert-summary", + "--timeout-seconds", + str(args.stale_convert_timeout_seconds), + "--orphan-grace-seconds", + str(args.convert_orphan_grace_seconds), + ) + + issues: list[str] = [] + actions: list[dict[str, Any]] = [] + status = "ok" + + if not api["configured"]: + issues.append("Dify API is not configured.") + status = "warning" + elif not api["reachable"]: + issues.append(f"Dify API is unreachable: {api['error']}") + status = "warning" + + if queues.get("priority_dataset", 0) > 0 and not active["tasks"]: + issues.append(f"priority_dataset queue has {queues['priority_dataset']} pending task(s).") + status = "warning" + + if not shared_postgres["available"]: + issues.append(f"Shared PostgreSQL is unavailable: {shared_postgres['error']}") + status = "warning" + else: + usage_ratio = float(shared_postgres["usage_ratio"] or 0.0) + if usage_ratio >= args.shared_postgres_usage_threshold: + cooldown_seconds = args.shared_postgres_cooldown_seconds + set_local_delay_gate( + args.app_redis_container, + args.app_queue_name, + "dify-sync-cooldown", + cooldown_seconds, + ) + usage_percent = int(round(usage_ratio * 100)) + issues.append( + f"Shared PostgreSQL usage is {usage_percent}% ({shared_postgres['active_connections']}/{shared_postgres['max_connections']}); pausing new Dify syncs for {cooldown_seconds}s." + ) + actions.append( + { + "type": "apply_dify_sync_cooldown", + "at": utc_now_iso(), + "reason": f"shared_postgres_usage={usage_percent}%", + "details": { + "cooldown_seconds": cooldown_seconds, + "active_connections": shared_postgres["active_connections"], + "max_connections": shared_postgres["max_connections"], + }, + } + ) + status = "warning" + + if stale_recovery.get("recovered_versions"): + issues.append( + f"Recovered {stale_recovery['recovered_versions']} stale syncing version(s)." + ) + actions.append( + { + "type": "recover_stale_syncs", + "at": utc_now_iso(), + "details": stale_recovery, + } + ) + status = "warning" + + if convert_recovery.get("recovered_versions"): + issues.append( + f"Recovered {convert_recovery['recovered_versions']} stale convert version(s)." + ) + actions.append( + { + "type": "recover_stale_converts", + "at": utc_now_iso(), + "details": convert_recovery, + } + ) + status = "warning" + + should_restart_worker, restart_reason = should_restart( + active["tasks"], + stuck_task_seconds=args.stuck_task_seconds, + ) + state = read_state(state_path) + last_restart_at = state.get("last_restart_at") + restart_allowed = True + if last_restart_at: + elapsed = datetime.now(timezone.utc) - datetime.fromisoformat(last_restart_at) + restart_allowed = elapsed.total_seconds() >= args.restart_cooldown_seconds + + if should_restart_worker and restart_allowed: + restart_dify_worker(compose_dir) + restarted_at = utc_now_iso() + state["last_restart_at"] = restarted_at + write_state(state_path, state) + actions.append( + { + "type": "restart_dify_worker", + "at": restarted_at, + "reason": restart_reason, + } + ) + status = "restarted" + issues.append(f"Restarted dify-worker because {restart_reason}.") + worker = inspect_worker_command(args.dify_worker_container) + active = inspect_celery(args.dify_worker_container, "active") + reserved = inspect_celery(args.dify_worker_container, "reserved") + queues = inspect_queue_lengths(args.dify_redis_container, args.dify_redis_password) + elif should_restart_worker and not restart_allowed: + issues.append("Detected stuck Dify task, but restart cooldown is still active.") + status = "warning" + + local_queue_stuck_observed_at = state.get("local_queue_stuck_observed_at") + local_worker_restart_allowed = True + last_local_worker_restart_at = state.get("last_local_worker_restart_at") + if last_local_worker_restart_at: + elapsed = datetime.now(timezone.utc) - datetime.fromisoformat(last_local_worker_restart_at) + local_worker_restart_allowed = elapsed.total_seconds() >= args.local_worker_restart_cooldown_seconds + + local_queue_stuck = local_queue_length > 0 and local_convert_summary.get("active_convert_jobs", 0) == 0 + if local_queue_stuck: + if not local_queue_stuck_observed_at: + state["local_queue_stuck_observed_at"] = utc_now_iso() + write_state(state_path, state) + else: + observed_for = datetime.now(timezone.utc) - datetime.fromisoformat(local_queue_stuck_observed_at) + if observed_for.total_seconds() >= args.local_queue_stuck_seconds: + if local_worker_restart_allowed: + restart_local_worker(project_root) + restarted_at = utc_now_iso() + state["last_local_worker_restart_at"] = restarted_at + state.pop("local_queue_stuck_observed_at", None) + write_state(state_path, state) + actions.append( + { + "type": "restart_local_worker", + "at": restarted_at, + "reason": f"Local RQ queue stayed pending at {local_queue_length} with no active convert jobs.", + } + ) + issues.append("Restarted local convert worker after queue backlog stalled.") + status = "warning" + local_queue_length = inspect_local_queue_length(args.app_redis_container, args.app_queue_name) + local_worker_online = inspect_container_running(args.app_worker_container) + local_convert_summary = run_app_cli( + args.app_api_container, + "convert-summary", + "--timeout-seconds", + str(args.stale_convert_timeout_seconds), + "--orphan-grace-seconds", + str(args.convert_orphan_grace_seconds), + ) + else: + issues.append("Detected stalled local convert queue, but local worker restart cooldown is still active.") + status = "warning" + else: + if local_queue_stuck_observed_at: + state.pop("local_queue_stuck_observed_at", None) + write_state(state_path, state) + + snapshot = { + "available": True, + "status": status, + "checked_at": utc_now_iso(), + "worker": worker, + "api": api, + "queue_lengths": queues, + "shared_postgres": shared_postgres, + "local_queue_length": local_queue_length, + "local_worker": {"online": local_worker_online, "container": args.app_worker_container}, + "active_tasks": active["tasks"], + "reserved_tasks": reserved["tasks"], + "local_sync_health": local_summary, + "local_convert_health": local_convert_summary, + "stale_recovery": stale_recovery, + "convert_recovery": convert_recovery, + "actions": actions, + "issues": issues, + "last_restart_at": state.get("last_restart_at"), + "last_local_worker_restart_at": state.get("last_local_worker_restart_at"), + } + write_snapshot(args.app_api_container, snapshot) + print(json.dumps(snapshot, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ops/watchdog/install-watchdog-cron.sh b/ops/watchdog/install-watchdog-cron.sh new file mode 100644 index 00000000..00300f52 --- /dev/null +++ b/ops/watchdog/install-watchdog-cron.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail + +PROJECT_ROOT="${1:-/home/inspur/tools/document-cleaning}" +PYTHON_BIN="${PYTHON_BIN:-/usr/bin/python3}" +LOG_DIR="$PROJECT_ROOT/runtime/watchdog" +SCRIPT_PATH="$PROJECT_ROOT/ops/watchdog/dify_watchdog.py" +MARKER="# document-cleaning-watchdog" +CRON_LINE="* * * * * cd $PROJECT_ROOT && $PYTHON_BIN $SCRIPT_PATH >> $LOG_DIR/watchdog.log 2>&1 $MARKER" + +mkdir -p "$LOG_DIR" + +TMP_CRON="$(mktemp)" +trap 'rm -f "$TMP_CRON"' EXIT + +crontab -l 2>/dev/null | grep -v "$MARKER" > "$TMP_CRON" || true +echo "$CRON_LINE" >> "$TMP_CRON" +crontab "$TMP_CRON" + +echo "Installed watchdog cron:" +echo "$CRON_LINE" diff --git a/project-governance/plans/2026-03-28-dify-diff-and-group-ux-plan.md b/project-governance/plans/2026-03-28-dify-diff-and-group-ux-plan.md new file mode 100644 index 00000000..11516fcc --- /dev/null +++ b/project-governance/plans/2026-03-28-dify-diff-and-group-ux-plan.md @@ -0,0 +1,61 @@ +# Dify Diff And Group UX Plan +> **For agent:** Execute directly against the existing implementation. Keep the current server deployment and avoid rebuilding core business logic. + +**Goal:** Make the group area operationally clean, add a concrete Dify-vs-local diff surface for selected groups, prevent accidental duplicate pushes, and resolve the current stuck sync pair on the server. + +**Architecture:** Keep the current FastAPI + worker + Vue SPA + Docker Compose structure. Add a lightweight comparison endpoint and a focused workspace UI refinement without introducing new dependencies. + +## Current Findings + +- The current sync failure is not caused by missing embedding or rerank model settings. +- The latest failed job timed out while waiting for Dify indexing, and the remote document remained stuck in `indexing`. +- Group cards still expose oversized management controls and the workspace does not yet provide a direct “show me local vs Dify differences” view. +- Current wording around Dify actions still risks reading like bidirectional sync when the implemented behavior is local push plus remote mapping. + +## Execution Tracks + +### Track 1: Group UX refinement +**Files:** +- Modify: `frontend/src/views/WorkspaceView.vue` +- Modify: `frontend/src/style.css` +- Modify: `frontend/src/lib/i18n.ts` + +**Steps:** +1. Replace large group edit/delete buttons with compact icon actions on the group card. +2. Keep inline create only for the empty-state path. +3. Move group management to card-level actions only and keep the selected-group summary informational. +4. Tighten copy so Dify actions read as push/status, not realtime bidirectional sync. + +### Track 2: Dify diff surface +**Files:** +- Modify: `backend/app/services/dify_service.py` +- Modify: `backend/app/api/groups.py` +- Modify: `frontend/src/views/WorkspaceView.vue` +- Modify: `frontend/src/lib/i18n.ts` +- Modify tests under `backend/tests/` + +**Steps:** +1. List remote Dify documents for the selected dataset. +2. Compare local documents and remote documents by normalized document name within the selected group. +3. Return summary buckets and row-level status so the UI can show matched, local-only, Dify-only, and attention items. +4. Add a modal viewer in the workspace with search by file name inside the selected group. + +### Track 3: Duplicate push guard and dirty data cleanup +**Files:** +- Modify: `backend/app/api/files.py` +- Apply one-off server cleanup for the current stuck local/remote record pair + +**Steps:** +1. Reject single-document pushes when the current version is already marked `synced`. +2. Skip already-synced rows during batch push. +3. Delete the currently stuck remote Dify document and clear the corresponding local failed sync state so the next push starts from a clean baseline. +4. Rebuild only affected services and run a real server verification pass. + +## Verification + +1. Run targeted backend tests for diff and push guard behavior. +2. Run frontend `npm run build`. +3. Deploy updated backend and frontend services to `192.168.100.230`. +4. Verify group actions are compact and usable in the browser. +5. Verify the Dify diff modal reflects matched, local-only, Dify-only, and attention states. +6. Re-run a real Dify push after cleanup and confirm it reaches a completed indexing state. diff --git a/project-governance/plans/2026-03-28-local-server-integration-plan.md b/project-governance/plans/2026-03-28-local-server-integration-plan.md new file mode 100644 index 00000000..468854a5 --- /dev/null +++ b/project-governance/plans/2026-03-28-local-server-integration-plan.md @@ -0,0 +1,82 @@ +# Local And Server Integration Plan +> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. +**Goal:** Prepare `D:\Document Cleaning` for local and server integration, then execute real smoke tests for upload, conversion, download, deletion, and Dify sync where credentials allow. +**Architecture:** Keep the existing Docker deployment path for server use, but add a direct local execution path that does not depend on Docker, Redis, or PostgreSQL being installed on the developer workstation. Real conversion should run through the existing `edkb_system` and LibreOffice chain. Dify sync should use the existing production service when a real API key is present. +**Tech Stack:** FastAPI, SQLAlchemy, Alembic, RQ, Redis, PostgreSQL, SQLite, Vue/Vite, LibreOffice + +## Current Environment Findings + +- `docker` and `docker compose` are not installed or not on PATH in the current Windows environment. +- LibreOffice is installed locally at `C:\Program Files\LibreOffice\program\soffice.exe`. +- Python and Node are installed locally. +- Root `.env` is missing. +- `DIFY_API_KEY` is currently empty in `.env.example`, `backend.env.example`, and the current process/user/machine environment. + +## Execution Strategy + +### Track 1: Server Path +**Files:** +- Modify as needed: `docker-compose.yml` +- Modify as needed: `.env.example` +- Modify as needed: `backend/backend.env.example` +**Steps:** +1. Normalize environment variable handling so `PUBLIC_BASE_URL` and the Dify settings are driven by `.env`. +2. Create a real root `.env` file for the current machine. +3. Verify the compose configuration is ready for the target server once Docker is available. + +### Track 2: Local Path +**Files:** +- Modify as needed: `backend/app/config.py` +- Modify as needed: `backend/app/services/queue_service.py` +- Modify as needed: `backend/worker.py` +- Modify as needed: `.env.example` +- Modify as needed: `backend/backend.env.example` +**Steps:** +1. Add a local task execution mode that can run queue tasks inline without Redis. +2. Keep the existing RQ mode unchanged for server deployment. +3. Configure the current workstation to use SQLite plus inline execution for local smoke tests. + +### Task 1: Prepare integration configuration +**Files:** +- Modify: `docker-compose.yml` +- Modify: `.env.example` +- Modify: `backend/backend.env.example` +- Create: `.env` +**Step 1:** Add all required variables for local and server paths, including `PUBLIC_BASE_URL` and a task execution mode switch. +**Step 2:** Keep production defaults intact where possible. +**Step 3:** Verify the resulting configuration files are internally consistent. + +### Task 2: Add local inline task execution mode +**Files:** +- Modify: `backend/app/config.py` +- Modify: `backend/app/services/queue_service.py` +- Modify as needed: `backend/tests/*` +**Step 1:** Add a configuration switch that chooses between `rq` and `sync`. +**Step 2:** In `sync` mode, execute `app.tasks.run_convert_job` and `app.tasks.run_sync_job` inline while preserving persisted job state. +**Step 3:** Verify the existing backend tests still pass after the change. + +### Task 3: Start the local integration stack +**Files:** +- Read: `frontend/vite.config.ts` +- Read: `backend/alembic.ini` +- Read: `backend/migrations/env.py` +**Step 1:** Run Alembic against the local database. +**Step 2:** Start the backend locally. +**Step 3:** Start the frontend locally if needed for manual browser access. +**Step 4:** Confirm health and login endpoints respond over HTTP. + +### Task 4: Run real smoke tests +**Files:** +- Read: `backend/data/original/**/*` +- Use runtime data under `backend/data/` +**Step 1:** Create a real group and upload a real document through the running API. +**Step 2:** Verify conversion completes using the existing document cleaning pipeline and LibreOffice path. +**Step 3:** Verify original download, markdown download, and local delete. +**Step 4:** Attempt real Dify sync if a valid key is available; otherwise capture the exact blocker and the furthest successful precondition. + +### Task 5: Report integration status +**Files:** +- Read: generated runtime output and logs +**Step 1:** Record what was prepared for server deployment. +**Step 2:** Record what was proven locally with real runtime execution. +**Step 3:** Record any remaining blockers, especially around Docker and Dify credentials. diff --git a/project-governance/plans/2026-03-28-product-ui-and-deploy-hygiene-plan.md b/project-governance/plans/2026-03-28-product-ui-and-deploy-hygiene-plan.md new file mode 100644 index 00000000..677fc421 --- /dev/null +++ b/project-governance/plans/2026-03-28-product-ui-and-deploy-hygiene-plan.md @@ -0,0 +1,69 @@ +# Product UI And Deploy Hygiene Plan +> **For agent:** Execute directly against the existing implementation. Do not rebuild the stack from scratch. + +**Goal:** Lift the current document cleaning system from an internal-tool baseline to a more professional product interface, tighten the local-to-server deployment workflow, and make Dify dataset model selection automatic instead of relying on manual console completion. + +**Architecture:** Keep the current FastAPI + worker + Vue SPA + Docker Compose structure. Improve only the frontend experience, Dify integration defaults, and deployment packaging boundaries. + +## Current Findings + +- The core business flow is already usable end to end on the server. +- The frontend still reads as an engineering utility rather than a finished product surface. +- Server deployments were previously syncing non-runtime content such as `project-governance` and test artifacts. +- Dify dataset creation succeeded, but embedding and rerank model assignment was not being written by the API layer. + +## Execution Tracks + +### Track 1: Productize the frontend +**Files:** +- Modify: `frontend/src/style.css` +- Modify: `frontend/src/App.vue` +- Modify: `frontend/src/views/LoginView.vue` +- Modify: `frontend/src/views/WorkspaceView.vue` +- Modify: `frontend/src/views/AdminView.vue` +- Modify as needed: `frontend/src/components/*` +- Modify as needed: `frontend/src/lib/i18n.ts` + +**Steps:** +1. Introduce a clearer visual direction with stronger surfaces, hierarchy, spacing, and global polish. +2. Keep the existing route structure and API contract intact. +3. Add bilingual UI support and a global language switch without introducing new dependencies. +4. Improve the admin configuration experience so Dify defaults feel like product settings, not raw system fields. + +### Track 2: Automate Dify model selection +**Files:** +- Modify: `backend/app/services/dify_service.py` +- Modify: `backend/app/tasks.py` +- Modify: `backend/app/models.py` +- Modify: `backend/app/schemas.py` +- Modify: `backend/app/serializers.py` +- Modify: `backend/app/api/admin.py` +- Modify: `backend/app/services/bootstrap_service.py` +- Modify: `backend/app/config.py` +- Create: `backend/migrations/versions/20260328_0002_dify_model_defaults.py` +- Modify tests under `backend/tests/` + +**Steps:** +1. Query the live Dify model catalog for embedding and rerank providers/models. +2. Apply a deterministic automatic choice when admin settings leave model fields empty. +3. Expose available models and automatic defaults in the admin API. +4. Allow explicit override from the admin UI while keeping automatic selection as the default path. + +### Track 3: Tighten deployment boundaries +**Files:** +- Modify as needed: deployment packaging commands/scripts +- Keep on server only runtime files and secrets + +**Steps:** +1. Exclude governance docs, tests, caches, local databases, and built artifacts from server syncs. +2. Remove already-synced non-runtime directories from the server deployment tree. +3. Rebuild only affected services after frontend/backend changes. + +## Verification + +1. Run targeted backend tests for admin settings and Dify task flows. +2. Run full backend `pytest` once the backend changes settle. +3. Run frontend `npm run build`. +4. Rebuild the changed Docker services on the server. +5. Execute a real server smoke test for login, upload, conversion, markdown download, Dify sync, and delete with `delete_dify=true`. +6. Confirm through the Dify API that new datasets carry embedding/rerank model settings and that remote documents return `404` after delete. diff --git a/project-governance/plans/2026-03-28-stability-hardening-plan.md b/project-governance/plans/2026-03-28-stability-hardening-plan.md new file mode 100644 index 00000000..c6b66b47 --- /dev/null +++ b/project-governance/plans/2026-03-28-stability-hardening-plan.md @@ -0,0 +1,91 @@ +# Stability Hardening Implementation Plan +> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. +**Goal:** Strengthen the existing document cleaning system without redesign by expanding backend coverage for critical workflows and removing known deprecations. +**Architecture:** Keep the current FastAPI + SQLAlchemy + RQ structure intact. Add focused backend tests around task execution and admin APIs, then make the smallest production changes needed to satisfy those tests and remove framework/runtime deprecation warnings. +**Tech Stack:** FastAPI, SQLAlchemy, pytest, Vue/Vite build verification, SQLite test database + +## Constraints + +- Continue from the current implementation. Do not rebuild flows or replace the current architecture. +- Save governance artifacts under `project-governance/`. +- Run targeted verification after each completed block, then run the full backend suite and frontend build at the end. +- Frontend code is out of scope unless backend changes force a UI adjustment. + +### Task 1: Establish plan and baseline +**Files:** +- Create: `project-governance/plans/2026-03-28-stability-hardening-plan.md` +- Read: `backend/tests/conftest.py` +- Read: `backend/app/tasks.py` +- Read: `backend/app/main.py` +- Read: `backend/app/models.py` +**Step 1:** Record the implementation plan in this file. +**Step 2:** Confirm the current backend and frontend verification commands still pass: +- `cd backend && python -m pytest tests -q` +- `cd frontend && npm run build` +**Step 3:** Use the baseline output as the comparison point for later changes. + +### Task 2: Add conversion and Dify task coverage +**Files:** +- Modify: `backend/tests/conftest.py` +- Create or modify: `backend/tests/test_tasks.py` +- Modify as needed: `backend/app/tasks.py` +**Step 1:** Write failing tests covering: +- conversion task success path +- conversion task failure path +- Dify sync success path +- Dify sync failure path +**Step 2:** Run only the new task-focused tests and confirm they fail for the expected reasons. +**Step 3:** Implement the smallest production changes needed to make those tests pass. +**Step 4:** Re-run the task-focused tests and confirm they pass cleanly. + +### Task 3: Add delete flow coverage +**Files:** +- Modify: `backend/tests/test_uploads.py` or create `backend/tests/test_files_api.py` +- Modify as needed: `backend/app/api/files.py` +**Step 1:** Write failing tests for: +- delete local document only +- delete local document and remote Dify document +**Step 2:** Run the delete-focused tests and confirm they fail for the expected reasons. +**Step 3:** Apply the minimum production changes required. +**Step 4:** Re-run the delete-focused tests and confirm they pass. + +### Task 4: Add admin API coverage +**Files:** +- Create: `backend/tests/test_admin_api.py` +- Modify as needed: `backend/app/api/admin.py` +- Modify as needed: `backend/app/api/jobs.py` +- Modify as needed: `backend/app/api/auth.py` +**Step 1:** Write failing tests for the core management endpoints: +- create user +- update user +- fetch settings +- update settings +- list jobs +- enforce admin protection on admin endpoints +**Step 2:** Run the admin-focused tests and confirm they fail for the expected reasons. +**Step 3:** Make the smallest production changes required. +**Step 4:** Re-run the admin-focused tests and confirm they pass. + +### Task 5: Remove known deprecations +**Files:** +- Modify: `backend/app/main.py` +- Modify: `backend/app/models.py` +- Modify: `backend/app/tasks.py` +- Modify as needed: `backend/tests/conftest.py` +**Step 1:** Replace FastAPI startup `on_event` usage with a `lifespan` handler. +**Step 2:** Replace `datetime.utcnow()` defaults and timestamps with timezone-aware UTC helpers. +**Step 3:** Run the backend suite and check that the previously observed deprecation warnings are removed. +**Step 4:** If warnings remain, trace the exact source and make the smallest additional fix. + +### Task 6: Final verification +**Files:** +- Read: `backend/tests/*.py` +- Read: `frontend/package.json` +**Step 1:** Run the full backend suite: +- `cd backend && python -m pytest tests -q` +**Step 2:** Run the frontend build: +- `cd frontend && npm run build` +**Step 3:** Summarize: +- changed behavior +- test evidence +- remaining risks or uncovered areas diff --git a/project-governance/plans/2026-03-28-workspace-productization-round-2-plan.md b/project-governance/plans/2026-03-28-workspace-productization-round-2-plan.md new file mode 100644 index 00000000..1df328b6 --- /dev/null +++ b/project-governance/plans/2026-03-28-workspace-productization-round-2-plan.md @@ -0,0 +1,19 @@ +# Workspace Productization Round 2 Plan +> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. +**Goal:** Tighten the knowledge-base workspace into a compact product-grade operations UI without changing the backend data model. +**Architecture:** Keep the current Vue SPA and FastAPI APIs, but restructure the workspace around three layers: knowledge-base navigation, global system overview, and current knowledge-base actions. Support features such as global Dify diff, modal uploads, and online preview through existing APIs, adding only lightweight summary/diff endpoints where needed. +**Tech Stack:** Vue 3, TypeScript, Tailwind CSS, Uppy, FastAPI, SQLAlchemy, Dify API + +## Scope +- Replace the sidebar “detail cards” with compact knowledge-base navigation items. +- Add global summary metrics and a global Dify diff entry point. +- Move batch upload into a modal and separate file vs folder selection. +- Simplify filters and document actions. +- Add online preview for source/Markdown where browser support allows. +- Keep all user-facing terminology as “知识库 / Knowledge Base”. + +## Verification +- `cd backend && python -m pytest tests/test_uploads.py tests/test_files_api.py -q` +- `cd frontend && npm run build` +- Deploy updated `backend` and `frontend` to `192.168.100.230` +- Verify homepage, login, knowledge-base list, global diff, upload modal, preview actions, and delete flows on server diff --git a/project-governance/plans/2026-03-29-access-control-and-admin-ui-plan.md b/project-governance/plans/2026-03-29-access-control-and-admin-ui-plan.md new file mode 100644 index 00000000..726a5c6f --- /dev/null +++ b/project-governance/plans/2026-03-29-access-control-and-admin-ui-plan.md @@ -0,0 +1,39 @@ +# Access Control And Admin UI Implementation Plan +> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. +**Goal:** Add three-tier roles plus knowledge-base access control, and simplify workspace/admin UI around Dify settings and diff management. +**Architecture:** Backend introduces a user-to-knowledge-base access table and expands role handling from two levels to three. Frontend aligns workspace and admin around a shared account/settings pattern, removes noisy admin panels, and tightens diff/search/delete flows. +**Tech Stack:** FastAPI, SQLAlchemy, Alembic, Vue 3, TypeScript, Tailwind CSS + +## Tasks + +### Task 1: Role and access schema +- Add `super_admin` role handling. +- Add `user_group_access` table and ORM relationships. +- Update bootstrap defaults so the seeded admin becomes `super_admin`. +- Add Alembic migration. + +### Task 2: API authorization +- Restrict knowledge-base and file access by role + assigned knowledge bases. +- Keep `super_admin` global. +- Allow `admin` to access operational admin pages, but require `super_admin` for user management. +- Support storing `accessible_group_ids` on user create/update. + +### Task 3: Workspace header and settings +- Move Dify settings into the account menu. +- Reuse the same account-menu pattern in workspace and admin. +- Keep admin console entry only for admin tiers. + +### Task 4: Diff and delete dialogs +- Global diff search uses explicit search type (`knowledge_base` / `file_name`) with matching placeholder. +- Diff table uses fixed-width layout and stable footer. +- Knowledge-base delete dialog uses top-right `X` and simplified body. + +### Task 5: Admin page simplification +- Remove knowledge-base management and recent jobs panels. +- Keep Dify health and user management. +- Add per-user knowledge-base access controls and three role options. + +### Task 6: Verification and deployment +- Run backend pytest coverage for admin/files/groups access behavior. +- Run frontend build. +- Apply migration on server and rebuild `api`/`frontend`. diff --git a/project-governance/plans/2026-03-29-department-permission-and-admin-refactor-plan.md b/project-governance/plans/2026-03-29-department-permission-and-admin-refactor-plan.md new file mode 100644 index 00000000..19dfd7a8 --- /dev/null +++ b/project-governance/plans/2026-03-29-department-permission-and-admin-refactor-plan.md @@ -0,0 +1,51 @@ +# Department Permission And Admin Refactor Plan + +> For this round, continue based on the existing implementation and do not rebuild from scratch. + +## Goal + +Refactor the admin and permission model so that: + +- the `admin` account is the only `super_admin` +- permissions are centered on departments instead of direct user-to-knowledge-base bindings +- knowledge bases belong to departments +- workspace visibility is filtered by department +- the admin page becomes a focused permission management console +- Dify health moves into a user-menu dialog + +## Scope + +### Backend + +- Add `Department` and `UserDepartmentAccess` models +- Add `primary_department_id` to `users` +- Add `department_id` to `groups` +- Backfill existing users and knowledge bases into a default department +- Enforce `admin` as the only `super_admin` +- Replace group visibility calculation from `UserGroupAccess` to department-based access +- Add department CRUD and user permission management endpoints + +### Frontend + +- Replace admin page with permission management +- Move Dify health to a modal entry under the user menu +- Rename user menu setting entry to `Dify设置` +- Change inline user editing to dialog-driven create/edit flows +- Add department selector to workspace sidebar and group creation flow +- Keep UI feedback lightweight with toast-style transient notices + +### Validation + +- Update backend tests for new department-based access model +- Run full backend pytest +- Run frontend build +- Deploy `api + worker + frontend` +- Verify role enforcement, department visibility, and Dify dialogs on server + +## Implementation Order + +1. Introduce department data model and migration with safe backfill. +2. Update permission helpers, group/file APIs, and admin APIs to use departments. +3. Rebuild the admin page into permission management and move Dify health into a dialog. +4. Update workspace department filter and knowledge-base ownership UX. +5. Run full validation and deploy. diff --git a/project-governance/plans/2026-03-29-dify-self-healing-plan.md b/project-governance/plans/2026-03-29-dify-self-healing-plan.md new file mode 100644 index 00000000..234ff6ad --- /dev/null +++ b/project-governance/plans/2026-03-29-dify-self-healing-plan.md @@ -0,0 +1,24 @@ +# Dify Self-Healing Implementation Plan +> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. +**Goal:** Add automatic Dify sync self-healing so stuck syncs recover cleanly, admins can see Dify health, and the server can restart Dify worker when queue execution stalls. +**Architecture:** The backend gains a watchdog service layer for stale-sync recovery and health snapshot reading, plus admin APIs for inspection and manual recovery. A host-level watchdog script on the deployment server inspects Dify queues/tasks via Docker, persists a JSON health snapshot into the app data volume, and restarts `dify-worker` when stuck-task thresholds are exceeded. +**Tech Stack:** FastAPI, SQLAlchemy, Vue 3, Docker Compose, Redis, PostgreSQL, host-side Python watchdog script. + +## Scope +- Backend stale sync recovery logic +- Admin health/status APIs +- Host watchdog script and server cron installation +- Admin console Dify health panel +- Real server verification + +## Non-Goals +- Replacing Dify’s own queue implementation +- Automatic blind resync loops for failed documents +- Adding Docker socket access into the app containers + +## Task Outline +1. Add watchdog-oriented backend services for stale-sync recovery and persisted health snapshot access. +2. Add admin API endpoints for Dify health visibility and manual stale-sync cleanup. +3. Add host watchdog script and deployment wiring on `192.168.100.230`. +4. Extend admin UI with a compact Dify health panel. +5. Verify locally, deploy to server, run real Dify health and sync smoke checks. diff --git a/project-governance/plans/2026-03-29-permission-console-and-department-workflow-plan.md b/project-governance/plans/2026-03-29-permission-console-and-department-workflow-plan.md new file mode 100644 index 00000000..f49af3c7 --- /dev/null +++ b/project-governance/plans/2026-03-29-permission-console-and-department-workflow-plan.md @@ -0,0 +1,55 @@ +# Permission Console And Department Workflow Plan + +> Continue from the existing implementation. Do not rebuild the system from scratch. + +## Goal + +Make the admin experience coherent around department-based permissions, keep `admin` as the only super admin, and move Dify operational controls into the user menu while keeping workspace behavior department-aware. + +## Outcomes + +- `admin` remains the only `super_admin` +- users are managed through modal create/edit flows +- departments become the primary access boundary for knowledge bases +- workspace exposes a department selector on the left and respects that scope +- Dify settings and Dify health move under the username menu +- stale-sync recovery uses toast feedback only + +## Backend + +1. Re-verify the unique-super-admin policy around `admin` +2. Keep department-based visibility and department ownership on knowledge bases +3. Ensure user payloads expose: + - `primary_department_id` + - `primary_department_name` + - `accessible_department_ids` + - `extra_department_ids` +4. Keep Dify health and stale recovery endpoints, but align wording with “stuck sync” semantics + +## Frontend + +1. Workspace + - show department switcher in the left sidebar + - keep knowledge-base create/edit department ownership in dialogs + - expose `Dify设置` and `Dify健康状态` from the username menu +2. Admin + - use the page as `权限管理` + - left side: department management + - right side: users and department access + - create/edit users via modal only + - remove obsolete knowledge-base-management and recent-jobs sections +3. Dify Health + - render as dialog from the username menu + - replace banner-style feedback with 3-second toast feedback + - explain each health metric in plain language + +## Validation + +- run backend pytest +- run frontend build +- deploy `api + worker + frontend` +- smoke-check: + - `admin` is the only super admin + - department list and user list load + - workspace department switch filters knowledge bases + - Dify health opens from username menu and stale recovery shows toast diff --git a/project-governance/plans/2026-04-01-convert-watchdog-and-integration-api-plan.md b/project-governance/plans/2026-04-01-convert-watchdog-and-integration-api-plan.md new file mode 100644 index 00000000..8ed04f17 --- /dev/null +++ b/project-governance/plans/2026-04-01-convert-watchdog-and-integration-api-plan.md @@ -0,0 +1,24 @@ +# Convert Watchdog And Integration API Plan +> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. +**Goal:** Add self-healing for stuck local conversion jobs, expose a read-only integration API for other internal sites, and finish the server path migration to `/home/inspur/tools/document-cleaning` without leaving old deployment paths behind. +**Architecture:** Extend the existing watchdog service into a shared health/recovery layer for both sync and convert jobs, then wire the host watchdog script to observe the local RQ queue and restart the local worker when it stalls. Add a separate token-protected integration router that exposes knowledge-base, file, version, and download relationships without direct database access. +**Tech Stack:** FastAPI, SQLAlchemy, Redis/RQ, Vue (existing UI untouched for this task), Docker Compose, host-side watchdog Python script. + +## Scope +- Local convert stale detection and recovery +- Host watchdog extension for local RQ queue / worker recovery +- Token-protected external read-only API +- Server cron/path updates from old project root to `/home/inspur/tools/document-cleaning` +- Verification on both local tests and deployed server + +## Non-Goals +- PostgreSQL storage relocation +- New UI surfaces for convert watchdog +- Multi-tenant API key management + +## Task Outline +1. Add convert health summary and stale-recovery services plus tests. +2. Extend watchdog CLI and host watchdog script to monitor the local convert queue and restart the app worker when it stalls. +3. Add integration API settings, auth dependency, endpoints, and tests. +4. Sync the latest code to `/home/inspur/tools/document-cleaning`, update cron/default paths, and remove old deployment paths. +5. Run local tests, rebuild the server, and verify the new endpoints and watchdog behavior. diff --git a/project-governance/skills/README.md b/project-governance/skills/README.md new file mode 100644 index 00000000..b445cf71 --- /dev/null +++ b/project-governance/skills/README.md @@ -0,0 +1,35 @@ +# Codex Skills Governance + +This folder keeps skill governance assets separate from the application code in `backend/` and `frontend/`. + +## Purpose + +- Record which Codex skills are required by this project +- Keep a repeatable install script in the repo +- Preserve a local audit trail for the installed skill versions +- Define when each skill must be used during future development + +## Required Skills + +- `skill-vetter` +- `superpowers` +- `frontend-design` + +## Layout + +- `install-skills.ps1`: reinstalls the required skills into `~/.codex/skills` +- `sources.json`: canonical source URLs and local install targets +- `vetting-report.md`: lightweight security and scope review +- `snapshots/`: local copies of the installed skill folders for audit/reference + +## Rule + +For future work on this repo: + +1. Vet any new external skill with `skill-vetter` before installation. +2. Use `superpowers` for task framing, planning, execution, testing, and review. +3. Use `frontend-design` for any UI or page-level changes. + +## Note + +Skills installed into `~/.codex/skills` require a Codex restart before they become available in a new session. diff --git a/project-governance/skills/install-skills.ps1 b/project-governance/skills/install-skills.ps1 new file mode 100644 index 00000000..64cbada8 --- /dev/null +++ b/project-governance/skills/install-skills.ps1 @@ -0,0 +1,73 @@ +param( + [string]$DestRoot = "$env:USERPROFILE\.codex\skills", + [switch]$Force +) + +$ErrorActionPreference = "Stop" + +$skills = @( + @{ + Name = "skill-vetter" + Owner = "openclaw" + Repo = "skills" + Path = "skills/spclaudehome/skill-vetter" + }, + @{ + Name = "superpowers" + Owner = "openclaw" + Repo = "skills" + Path = "skills/cutd/claw-superpowers" + }, + @{ + Name = "frontend-design" + Owner = "vadimcomanescu" + Repo = "codex-skills" + Path = "skills/.curated/design/frontend-design" + } +) + +function Get-GitHubJson([string]$Url) { + Invoke-RestMethod -Headers @{ "User-Agent" = "document-cleaning-skill-bootstrap" } -Uri $Url +} + +function Download-GitHubFolder( + [string]$Owner, + [string]$Repo, + [string]$Path, + [string]$Dest +) { + New-Item -ItemType Directory -Force -Path $Dest | Out-Null + $api = "https://api.github.com/repos/$Owner/$Repo/contents/$Path" + $items = Get-GitHubJson $api + + foreach ($item in $items) { + if ($item.type -eq "file") { + $target = Join-Path $Dest $item.name + Invoke-WebRequest -Headers @{ "User-Agent" = "document-cleaning-skill-bootstrap" } -Uri $item.download_url -OutFile $target + continue + } + + if ($item.type -eq "dir") { + Download-GitHubFolder -Owner $Owner -Repo $Repo -Path $item.path -Dest (Join-Path $Dest $item.name) + } + } +} + +New-Item -ItemType Directory -Force -Path $DestRoot | Out-Null + +foreach ($skill in $skills) { + $dest = Join-Path $DestRoot $skill.Name + if ((Test-Path $dest) -and -not $Force) { + Write-Host "Skipping $($skill.Name) because it already exists. Use -Force to reinstall." + continue + } + + if (Test-Path $dest) { + Remove-Item -Recurse -Force -LiteralPath $dest + } + + Download-GitHubFolder -Owner $skill.Owner -Repo $skill.Repo -Path $skill.Path -Dest $dest + Write-Host "Installed $($skill.Name) -> $dest" +} + +Write-Host "Restart Codex to pick up new skills." diff --git a/project-governance/skills/snapshots/frontend-design/LICENSE.txt b/project-governance/skills/snapshots/frontend-design/LICENSE.txt new file mode 100644 index 00000000..ddb063de --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/LICENSE.txt @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 Vadim Comanescu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/project-governance/skills/snapshots/frontend-design/SKILL.md b/project-governance/skills/snapshots/frontend-design/SKILL.md new file mode 100644 index 00000000..55642458 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/SKILL.md @@ -0,0 +1,110 @@ +--- +name: frontend-design +description: "Create distinctive, production-grade frontend UI with a bold, intentional aesthetic direction, purposeful layouts, meaningful motion, and strong accessibility. Prefer React + Next.js (TypeScript), but support vanilla HTML/CSS/JS when appropriate." +--- + +# Frontend Design + +Build memorable, functional interfaces with a clear point-of-view (no generic templates). Commit to one aesthetic direction, define tokens, ship accessible + responsive UI, and keep changes scoped. + +## Preferred Targets (choose the best fit) +1) **Next.js (TypeScript)**: preferred for production app/marketing routes and design system work. +2) **React (TypeScript)**: preferred for SPA/component libraries outside Next.js. +3) **Vanilla HTML/CSS/JS**: great for static demos, prototypes, and standalone embeds. + +## Quick Start (do this first) +1) Ask up to 4 questions: + - What user and job-to-be-done (what should feel “easy” after the change)? + - Where does it live (component/route) and what stack? Prefer Next.js/React; vanilla is fine for standalone pages or prototypes. + - In Next.js: assume App Router (`app/`). Any server/client constraints? + - Any hard constraints (brand tokens, light/dark, motion limits, must-keep UI parts, perf budgets)? +2) Pick an aesthetic direction + **one signature move**. If vague, propose 2–3 options from `references/aesthetic-playbook.md`. +3) Define tokens (type, palette, spacing, radius, shadows, motion). Keep accents to 1–2. +4) Build structure first (semantic markup + layout), then motion, then polish + QA. + +## Guardrails (avoid footguns) +- Keep scope tight: redesign only what the user asked for. +- Reuse existing tokens/components if working in an existing repo; do not introduce a new global styling system unless requested. +- Match complexity to the vision: refined minimalism needs restraint; maximalism needs deliberate structure (not random decoration). +- Respect `prefers-reduced-motion` for all animations. +- Avoid “AI slop” defaults. If the repo already uses a generic font, keep it unless the user explicitly wants new typography. +- Enforce token semantics: error/success/warning colors are for meaning, not decoration; keep contrast accessible in light/dark. +- Default to shipping code that is easy to maintain: small components, clear hierarchy, minimal dependencies. +- Don’t add new packages (animation libs, UI kits, icon sets) unless the user explicitly asks or the repo already uses them. +- Default to one primary CTA per view; demote the rest (secondary/tertiary) to avoid competing actions. + +## Workflow + +### 1) Commit to a direction +- Declare: aesthetic direction, palette mood, type pairing, and the signature move. +- Write a 1–2 sentence design thesis that explains the hierarchy and vibe. +- Use `references/anti-patterns.md` to avoid predictable layouts and cliched palettes. + +### 1b) Design system rules (strict vs flexible) +- **Strict**: semantic color meaning, readable type ramp, reduced motion, visible focus, and “human-in-control” for AI actions (undo/apply/confirm). +- **Flexible**: brand accent hue, surface “temperature” in dark mode, and density preset (compact vs comfy). +- **When to read more**: load `references/tokens-and-semantics.md` when defining tokens and `references/ai-native-ui-patterns.md` when adding AI surfaces. + +### 1a) React/Next.js coding guidance (read when implementing) +- **React fundamentals**: keep components pure; prefer event handlers over Effects for user-driven work; follow the Rules of Hooks. +- **Next.js App Router**: keep Client Components small; use Server Components by default; mark `"use client"` only where you need state, effects, or browser APIs. +- **Data fetching**: prefer server-side `fetch` and explicit cache/revalidate controls; avoid unnecessary client-side effects for data. +- **When to read more**: load `references/react-next-best-practices.md` before writing complex React logic or introducing new data fetching patterns. + +### 2) Plan tokens and layout (before details) +- Define CSS variables (or a theme object) for: + - Color: background/surface/ink/muted/accent(+optional accent2) + - Type: display/body/mono, size scale, line-height + - Shape: radius scale and border rules + - Depth: shadow and outline rules + - Motion: durations + easing + reveal stagger step +- Lay out the page/component skeleton and content hierarchy. +- Reference `references/implementation-patterns.md` for patterns and QA. + +### 3) Implement (ship code, not moodboards) +- Start with semantic structure and accessible interactions (keyboard + focus states). +- Build macro layout with Grid; micro layout with Flexbox. +- For Next.js/React, keep components small and composable; prefer CSS Modules or the repo’s existing styling approach. +- Use “link for navigation, button for actions” to keep semantics and keyboard behavior correct. +- Apply the signature move sparingly but decisively (one memorable thing, not ten). +- Add motion as orchestration (one strong page-load + a few micro-interactions), not random flourishes. + +### 3a) Next.js implementation notes (when applicable) +- **App Router only**: assume `app/` routing (not `pages/`). +- **Server vs Client**: default to Server Components; add `"use client"` only for interactive islands. +- **Data + state**: keep data fetching on the server when possible; keep client state local and purposeful. +- **Performance**: avoid layout shift (stable heights, predictable grids); keep blur/shadows paint-friendly on mobile. +- **Platform primitives**: prefer `next/link` for navigation and `next/image` for real images when available. +- **Fonts**: if changing typography in Next.js, prefer `next/font` to avoid FOIT/FOUT surprises. +- **Styling**: keep it consistent—CSS Modules, Tailwind, or the existing system; don’t introduce a new one without asking. + +### 3b) Content + states (don’t ship empty shells) +- Define loading, empty, and error states for any data-driven UI. +- Keep copy tight and purposeful; avoid placeholder lorem unless asked. +- Preserve existing product terminology unless the user requests copy changes. + +### 4) Polish and QA +- Responsive pass: collapse grids, maintain padding, preserve CTA prominence on mobile. +- Accessibility pass: landmarks, one `h1`, labels, contrast, focus order, skip link when relevant. +- Performance pass: avoid expensive shadows on mobile, keep animation paint-friendly, avoid large images. + +## Definition of Done +- Layout looks intentional at mobile + desktop breakpoints (no cramped type, no orphan CTAs). +- Focus states are visible, tab order is logical, and motion respects `prefers-reduced-motion`. +- Tokens are centralized (CSS variables/theme), and the signature move is present but not overused. + +## Deliverables (how to present results) +- List files changed and what they do. +- Explain the aesthetic direction + signature move (1–2 sentences). +- Provide commands to validate (use the repo’s conventions; common ones include `npm run dev`, `npm run lint`, `npm test`). + +## Bundled Resources +- `references/aesthetic-playbook.md`: strong directions, type+color cues, signature moves. +- `references/implementation-patterns.md`: layout/motion/a11y patterns for vanilla + React. +- `references/anti-patterns.md`: quick “don’t do this” checklist to avoid generic output. +- `references/react-next-best-practices.md`: React + Next.js coding guidelines (hooks, effects, server/client, data fetching). +- `references/tokens-and-semantics.md`: token semantics, type ramp, dark mode, and density rules (strict vs flexible). +- `references/ai-native-ui-patterns.md`: copilot panels, citations, disclosures, and human-in-the-loop UI patterns. +- `assets/vanilla-starter/`: runnable vanilla starter you can copy + retheme via CSS variables. +- `assets/react-component-starter/`: small React component + CSS module skeleton to retheme. +- `assets/nextjs-app-router-starter/`: minimal Next.js App Router page + tokens you can copy and retheme. diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/README.md b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/README.md new file mode 100644 index 00000000..4107fcfa --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/README.md @@ -0,0 +1,8 @@ +# Next.js App Router Starter + +Copy these files into an existing Next.js App Router project to bootstrap a strongly-themed, token-driven page. + +- Files assume `app/` routing (not `pages/`). +- Uses CSS variables + CSS Modules (no external styling dependencies). +- Designed to be rethemed by editing `app/globals.css` tokens. +- Includes an “Assistant Rail” component demonstrating AI-native UX patterns (AI disclosure, citations, and human-in-control apply/undo). diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/globals.css b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/globals.css new file mode 100644 index 00000000..81c14595 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/globals.css @@ -0,0 +1,69 @@ +:root { + --bg: #0b0d12; + --surface: rgba(255, 255, 255, 0.06); + --surface-2: rgba(255, 255, 255, 0.1); + --ink: rgba(255, 255, 255, 0.92); + --muted: rgba(255, 255, 255, 0.68); + --accent: #6ee7ff; + --danger: #ff5a7a; + --warning: #ffcc66; + --success: #55f2b1; + --info: #6ea8ff; + + --radius-sm: 10px; + --radius-md: 16px; + --radius-lg: 22px; + + --shadow-sm: 0 10px 30px rgba(0, 0, 0, 0.28); + --shadow-md: 0 22px 70px rgba(0, 0, 0, 0.4); + + --container: 1120px; + --gutter: clamp(16px, 3vw, 28px); + --grid-gap: clamp(14px, 2vw, 22px); + + --ease-out: cubic-bezier(0.16, 1, 0.3, 1); + --dur-1: 140ms; + --dur-2: 240ms; + --dur-3: 420ms; +} + +* { + box-sizing: border-box; +} + +html, +body { + height: 100%; +} + +body { + margin: 0; + background: radial-gradient(1200px 900px at 18% -10%, rgba(110, 231, 255, 0.18), transparent 55%), + radial-gradient(900px 700px at 78% 10%, rgba(255, 115, 224, 0.14), transparent 60%), + var(--bg); + color: var(--ink); + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, + "Apple Color Emoji", "Segoe UI Emoji"; + line-height: 1.45; +} + +a { + color: inherit; + text-decoration: none; +} + +:focus-visible { + outline: 2px solid color-mix(in oklab, var(--accent), white 10%); + outline-offset: 3px; +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/layout.tsx b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/layout.tsx new file mode 100644 index 00000000..502e38ec --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/layout.tsx @@ -0,0 +1,18 @@ +import type { Metadata } from "next"; +import "./globals.css"; +import type { ReactNode } from "react"; + +export const metadata: Metadata = { + title: "Frontend Design Starter", + description: "Token-driven Next.js starter page for rapid retheming.", +}; + +export default function RootLayout({ + children, +}: Readonly<{ children: ReactNode }>) { + return ( + + {children} + + ); +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.module.css b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.module.css new file mode 100644 index 00000000..ea7ac92d --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.module.css @@ -0,0 +1,244 @@ +.page { + min-height: 100dvh; +} + +.skip { + position: absolute; + left: -999px; + top: 12px; + padding: 10px 12px; + border-radius: 999px; + background: var(--surface-2); +} + +.skip:focus { + left: 12px; +} + +.topbar { + position: sticky; + top: 0; + z-index: 10; + backdrop-filter: blur(18px); + background: color-mix(in oklab, var(--bg), transparent 35%); + border-bottom: 1px solid color-mix(in oklab, white, transparent 90%); +} + +.topbarInner { + max-width: var(--container); + margin: 0 auto; + padding: 14px var(--gutter); + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 10px; + font-weight: 650; + letter-spacing: 0.02em; +} + +.mark { + width: 28px; + height: 28px; + border-radius: 10px; + background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.45), transparent 60%), + linear-gradient(135deg, rgba(110, 231, 255, 0.85), rgba(255, 115, 224, 0.62)); + box-shadow: 0 10px 28px rgba(0, 0, 0, 0.35); +} + +.nav { + display: flex; + gap: 14px; + color: var(--muted); + font-size: 14px; +} + +.nav a { + padding: 8px 10px; + border-radius: 999px; +} + +.nav a:hover { + background: rgba(255, 255, 255, 0.06); + color: var(--ink); +} + +.hero { + max-width: var(--container); + margin: 0 auto; + padding: 54px var(--gutter) 28px; + display: grid; + grid-template-columns: 1.15fr 0.85fr; + gap: clamp(18px, 3vw, 36px); + align-items: start; +} + +.headline { + margin: 0; + font-size: clamp(34px, 4vw, 56px); + line-height: 1.03; + letter-spacing: -0.02em; +} + +.lede { + margin: 14px 0 0; + color: var(--muted); + font-size: clamp(16px, 1.4vw, 18px); + max-width: 58ch; +} + +.ctaRow { + margin-top: 20px; + display: flex; + flex-wrap: wrap; + gap: 12px; +} + +.btn { + display: inline-flex; + align-items: center; + gap: 10px; + padding: 11px 14px; + border-radius: 999px; + border: 1px solid color-mix(in oklab, white, transparent 85%); + background: rgba(255, 255, 255, 0.04); + box-shadow: var(--shadow-sm); + transition: transform var(--dur-2) var(--ease-out), background var(--dur-2) var(--ease-out), + border-color var(--dur-2) var(--ease-out); +} + +.btn:hover { + transform: translateY(-1px); + background: rgba(255, 255, 255, 0.07); + border-color: color-mix(in oklab, var(--accent), white 35%); +} + +.btnPrimary { + border-color: color-mix(in oklab, var(--accent), white 40%); + background: linear-gradient( + 180deg, + rgba(110, 231, 255, 0.22), + rgba(255, 255, 255, 0.06) + ); +} + +.panel { + border-radius: var(--radius-lg); + background: linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.03)); + border: 1px solid color-mix(in oklab, white, transparent 88%); + box-shadow: var(--shadow-md); + padding: 18px; +} + +.rail { + margin-top: 16px; +} + +.panelHeader { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; +} + +.panelTitle { + margin: 0; + font-size: 15px; + letter-spacing: 0.02em; + color: color-mix(in oklab, var(--muted), white 18%); +} + +.badge { + font-size: 12px; + color: color-mix(in oklab, var(--accent), white 20%); + background: rgba(110, 231, 255, 0.12); + border: 1px solid rgba(110, 231, 255, 0.28); + padding: 6px 10px; + border-radius: 999px; +} + +.list { + margin: 14px 0 0; + padding: 0; + list-style: none; + display: grid; + gap: 10px; +} + +.item { + border-radius: var(--radius-md); + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + padding: 12px 12px; +} + +.itemTitle { + font-weight: 620; + margin: 0; + font-size: 14px; +} + +.itemBody { + margin: 6px 0 0; + color: var(--muted); + font-size: 13px; +} + +.content { + max-width: var(--container); + margin: 0 auto; + padding: 28px var(--gutter) 64px; +} + +.grid { + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: var(--grid-gap); +} + +.card { + grid-column: span 4; + border-radius: var(--radius-lg); + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.07); + padding: 18px; + transition: transform var(--dur-2) var(--ease-out), border-color var(--dur-2) var(--ease-out); +} + +.card:hover { + transform: translateY(-2px); + border-color: color-mix(in oklab, var(--accent), white 35%); +} + +.card h2 { + margin: 0 0 8px; + font-size: 16px; + letter-spacing: 0.01em; +} + +.card p { + margin: 0; + color: var(--muted); + font-size: 14px; +} + +@media (max-width: 900px) { + .hero { + grid-template-columns: 1fr; + } + + .card { + grid-column: span 6; + } +} + +@media (max-width: 560px) { + .card { + grid-column: span 12; + } +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.tsx b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.tsx new file mode 100644 index 00000000..53ae619b --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/app/page.tsx @@ -0,0 +1,99 @@ +import styles from "./page.module.css"; +import { AssistantRail } from "../components/AssistantRail"; + +const quickWins = [ + { + title: "Token-first styling", + body: "Retheme fast by editing CSS variables in globals.css (palette, radii, shadows, motion).", + }, + { + title: "One signature move", + body: "Commit to a single memorable gesture (light sweep, stripe, grain, or brutal border logic).", + }, + { + title: "Accessible by default", + body: "Semantic structure, visible focus, and reduced-motion support are built in.", + }, +]; + +export default function Page() { + return ( +
+ + Skip to content + + +
+ +
+ +
+
+
+

+ A token-driven page that looks intentional on day one. +

+

+ Build structure first, then motion, then polish. Keep the UI memorable with one + signature move—not ten random decorations. +

+ +
+ + + +
+ +
+
+ +
+
+
+

Hierarchy

+

Make the primary action obvious, then design the supporting rails.

+
+
+

Texture

+

Use subtle grain/mesh/stripe logic to avoid flat UI without clutter.

+
+
+

Motion

+

Orchestrate a few meaningful reveals and micro-interactions—guarded by settings.

+
+
+
+
+
+ ); +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.module.css b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.module.css new file mode 100644 index 00000000..7cdc0cb4 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.module.css @@ -0,0 +1,217 @@ +.wrap { + display: grid; + gap: 12px; +} + +.panel { + border-radius: var(--radius-lg); + background: linear-gradient( + 180deg, + rgba(255, 255, 255, 0.07), + rgba(255, 255, 255, 0.03) + ); + border: 1px solid color-mix(in oklab, white, transparent 88%); + box-shadow: var(--shadow-md); + padding: 16px; +} + +.header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + margin-bottom: 10px; +} + +.title { + margin: 0; + font-size: 15px; + letter-spacing: 0.02em; + color: color-mix(in oklab, var(--muted), white 18%); +} + +.disclosure { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.badge { + font-size: 12px; + color: color-mix(in oklab, var(--accent), white 18%); + background: rgba(110, 231, 255, 0.12); + border: 1px solid rgba(110, 231, 255, 0.28); + padding: 6px 10px; + border-radius: 999px; +} + +.hint { + font-size: 12px; + color: var(--muted); +} + +.promptRow { + display: flex; + gap: 10px; + margin-top: 10px; +} + +.input { + flex: 1; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(0, 0, 0, 0.12); + color: var(--ink); + padding: 10px 12px; + font: inherit; +} + +.input::placeholder { + color: color-mix(in oklab, var(--muted), transparent 10%); +} + +.btn { + border-radius: 999px; + border: 1px solid color-mix(in oklab, white, transparent 85%); + background: rgba(255, 255, 255, 0.04); + color: var(--ink); + padding: 10px 12px; + font: inherit; + cursor: pointer; + transition: transform var(--dur-2) var(--ease-out), background var(--dur-2) var(--ease-out), + border-color var(--dur-2) var(--ease-out); +} + +.btn:hover { + transform: translateY(-1px); + background: rgba(255, 255, 255, 0.07); + border-color: color-mix(in oklab, var(--accent), white 35%); +} + +.btnPrimary { + border-color: color-mix(in oklab, var(--accent), white 40%); + background: linear-gradient( + 180deg, + rgba(110, 231, 255, 0.2), + rgba(255, 255, 255, 0.06) + ); +} + +.output { + margin-top: 12px; + border-radius: var(--radius-md); + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + padding: 12px; +} + +.typing { + display: inline-flex; + gap: 6px; + align-items: center; + color: var(--muted); + font-size: 13px; +} + +.dot { + width: 6px; + height: 6px; + border-radius: 999px; + background: color-mix(in oklab, var(--accent), white 15%); + opacity: 0.6; + animation: pulse 900ms var(--ease-out) infinite; +} + +.dot:nth-child(2) { + animation-delay: 120ms; +} + +.dot:nth-child(3) { + animation-delay: 240ms; +} + +@keyframes pulse { + 0%, + 100% { + transform: translateY(0); + opacity: 0.45; + } + 50% { + transform: translateY(-1px); + opacity: 0.9; + } +} + +.text { + margin: 0; + color: color-mix(in oklab, var(--ink), white 2%); + font-size: 13px; + line-height: 1.45; +} + +.citations { + margin-top: 10px; + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 7px 10px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: var(--muted); + font-size: 12px; +} + +.chipNumber { + width: 18px; + height: 18px; + border-radius: 999px; + display: inline-flex; + align-items: center; + justify-content: center; + background: rgba(110, 231, 255, 0.14); + border: 1px solid rgba(110, 231, 255, 0.26); + color: color-mix(in oklab, var(--accent), white 20%); + font-weight: 650; + font-size: 11px; +} + +.controls { + margin-top: 12px; + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; + justify-content: space-between; +} + +.controlRow { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.whyRow { + margin-top: 12px; +} + +.status { + font-size: 12px; + color: var(--muted); +} + +.statusStrong { + color: color-mix(in oklab, var(--success), white 18%); +} + +@media (prefers-reduced-motion: reduce) { + .dot { + animation: none; + } +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.tsx b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.tsx new file mode 100644 index 00000000..1e76cdd3 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/nextjs-app-router-starter/components/AssistantRail.tsx @@ -0,0 +1,167 @@ +"use client"; + +import { useMemo, useState } from "react"; +import styles from "./AssistantRail.module.css"; + +type Suggestion = { + id: string; + text: string; + citations: Array<{ title: string; href: string }>; +}; + +const seededSuggestions: Suggestion[] = [ + { + id: "cta", + text: "Reduce competing CTAs: keep one primary action, demote the rest to secondary to sharpen hierarchy.", + citations: [ + { title: "Design System: CTA hierarchy", href: "#" }, + { title: "UX principle: one primary per view", href: "#" }, + ], + }, + { + id: "motion", + text: "Use motion only as feedback (hover, state changes, subtle reveal). Respect reduced-motion automatically.", + citations: [ + { title: "Motion guidelines", href: "#" }, + { title: "Reduced motion support", href: "#" }, + ], + }, +]; + +export function AssistantRail() { + const [prompt, setPrompt] = useState("Summarize how to improve this page’s hierarchy."); + const [isGenerating, setIsGenerating] = useState(false); + const [active, setActive] = useState(seededSuggestions[0]); + const [appliedIds, setAppliedIds] = useState([]); + const [lastAppliedId, setLastAppliedId] = useState(null); + const [showWhy, setShowWhy] = useState(false); + + const appliedSet = useMemo(() => new Set(appliedIds), [appliedIds]); + + function run() { + setIsGenerating(true); + window.setTimeout(() => { + const promptLower = prompt.toLowerCase(); + const keywordMatch = + promptLower.includes("motion") || promptLower.includes("animation") + ? "motion" + : promptLower.includes("cta") || promptLower.includes("button") + ? "cta" + : null; + + const next = + (keywordMatch ? seededSuggestions.find((s) => s.id === keywordMatch) : null) ?? + (() => { + const currentIndex = seededSuggestions.findIndex((s) => s.id === (active?.id ?? seededSuggestions[0].id)); + const nextIndex = (currentIndex + 1) % seededSuggestions.length; + return seededSuggestions[nextIndex]; + })(); + setActive(next); + setShowWhy(false); + setIsGenerating(false); + }, 700); + } + + function apply() { + if (!active || appliedSet.has(active.id)) return; + setAppliedIds((prev) => [...prev, active.id]); + setLastAppliedId(active.id); + } + + function undo() { + if (!lastAppliedId) return; + setAppliedIds((prev) => prev.filter((id) => id !== lastAppliedId)); + setLastAppliedId(null); + } + + function resetApplied() { + if (!appliedIds.length) return; + const ok = window.confirm("Clear applied items? This is just a demo of confirmation UI."); + if (!ok) return; + setAppliedIds([]); + setLastAppliedId(null); + } + + return ( +
+
+

Assistant Rail

+
+ + AI-generated + +
+
+ +

+ Human-in-control: you can apply or undo changes. This is a starter UI pattern, not a full chatbot. +

+ +
+ setPrompt(e.target.value)} + placeholder="Ask for a UI change…" + aria-label="Prompt" + /> + +
+ +
+ {isGenerating ? ( +
+ Thinking + + + +
+ ) : ( + <> +

{active?.text}

+
+ {(active?.citations ?? []).map((c, idx) => ( + + {idx + 1} + {c.title} + + ))} +
+
+ +
+ {showWhy ? ( +

+ This suggestion targets high-leverage UX: clearer hierarchy reduces cognitive load and makes the + primary action obvious. It also reduces regret by keeping changes easy to apply/undo. +

+ ) : null} + + )} +
+ +
+
+ + + +
+ +
+ Applied:{" "} + {appliedIds.length} +
+
+
+ ); +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.module.css b/project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.module.css new file mode 100644 index 00000000..473cdfc3 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.module.css @@ -0,0 +1,198 @@ +:root { + --fd-bg: #0b0d10; + --fd-surface: rgba(255, 255, 255, 0.06); + --fd-ink: rgba(245, 244, 240, 0.96); + --fd-muted: rgba(245, 244, 240, 0.66); + --fd-accent: #d7ff3f; + --fd-accent2: #68e0ff; + --fd-radius: 20px; + --fd-stroke: rgba(245, 244, 240, 0.14); + --fd-shadow: 0 18px 50px rgba(0, 0, 0, 0.45); + --fd-ease: cubic-bezier(0.2, 0.9, 0.2, 1); +} + +.shell { + position: relative; + color: var(--fd-ink); + border: 1px solid var(--fd-stroke); + border-radius: var(--fd-radius); + background: + radial-gradient(1000px 300px at 20% 0%, rgba(104, 224, 255, 0.14), transparent 60%), + radial-gradient(800px 340px at 85% 20%, rgba(215, 255, 63, 0.14), transparent 55%), + linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.03)); + box-shadow: var(--fd-shadow); + overflow: clip; + padding: 22px 20px; +} + +.shell::before { + content: ""; + position: absolute; + inset: 0; + pointer-events: none; + background: + repeating-linear-gradient( + 135deg, + rgba(245, 244, 240, 0.05), + rgba(245, 244, 240, 0.05) 1px, + transparent 1px, + transparent 9px + ); + opacity: 0.35; + mix-blend-mode: soft-light; +} + +.head { + position: relative; + padding-bottom: 14px; + border-bottom: 1px solid var(--fd-stroke); + margin-bottom: 16px; +} + +.kicker { + display: inline-flex; + gap: 10px; + align-items: center; + font-size: 12px; + letter-spacing: 0.14em; + text-transform: uppercase; + color: var(--fd-muted); +} + +.kicker::before { + content: ""; + width: 10px; + height: 10px; + border-radius: 999px; + background: radial-gradient(circle at 35% 35%, var(--fd-accent), rgba(215, 255, 63, 0.2)); + box-shadow: 0 0 0 2px rgba(215, 255, 63, 0.12); +} + +.title { + margin: 10px 0 6px; + font-size: 28px; + line-height: 1.05; + letter-spacing: -0.02em; +} + +.subtitle { + margin: 0; + max-width: 62ch; + color: var(--fd-muted); + line-height: 1.35; + font-size: 14px; +} + +.grid { + position: relative; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; +} + +.card { + border: 1px solid rgba(245, 244, 240, 0.12); + border-radius: 16px; + background: rgba(0, 0, 0, 0.2); + padding: 14px 14px 12px; + transform: translateY(0); + transition: transform 280ms var(--fd-ease), border-color 280ms var(--fd-ease); +} + +.card:hover { + transform: translateY(-2px); + border-color: rgba(215, 255, 63, 0.35); +} + +.cardTop { + display: flex; + justify-content: space-between; + gap: 10px; + align-items: baseline; +} + +.cardLabel { + font-size: 12px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: rgba(245, 244, 240, 0.72); +} + +.cardHint { + font-size: 12px; + color: rgba(104, 224, 255, 0.8); +} + +.cardValue { + margin-top: 12px; + font-size: 24px; + line-height: 1; + letter-spacing: -0.02em; +} + +.foot { + position: relative; + display: flex; + justify-content: flex-end; + margin-top: 16px; +} + +.cta { + appearance: none; + border: 1px solid rgba(245, 244, 240, 0.18); + color: var(--fd-ink); + background: rgba(0, 0, 0, 0.18); + border-radius: 999px; + padding: 12px 14px; + display: inline-flex; + gap: 10px; + align-items: center; + cursor: pointer; + transition: transform 220ms var(--fd-ease), border-color 220ms var(--fd-ease); +} + +.cta:hover { + transform: translateY(-1px); + border-color: rgba(245, 244, 240, 0.34); +} + +.cta:focus-visible { + outline: 3px solid rgba(104, 224, 255, 0.45); + outline-offset: 3px; +} + +.ctaText { + font-size: 13px; + letter-spacing: 0.02em; +} + +.ctaIcon { + color: var(--fd-accent); + transform: translateX(0); + transition: transform 220ms var(--fd-ease); +} + +.cta:hover .ctaIcon { + transform: translateX(2px); +} + +@media (max-width: 720px) { + .grid { + grid-template-columns: 1fr; + } + .title { + font-size: 26px; + } +} + +@media (prefers-reduced-motion: reduce) { + .card, + .cta, + .ctaIcon { + transition: none; + } + .card:hover, + .cta:hover { + transform: none; + } +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.tsx b/project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.tsx new file mode 100644 index 00000000..f1050ad0 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/react-component-starter/DesignPanel.tsx @@ -0,0 +1,52 @@ +import styles from "./DesignPanel.module.css"; + +type Stat = { label: string; value: string; hint?: string }; + +const defaultStats: Stat[] = [ + { label: "Uptime", value: "99.98%", hint: "30d" }, + { label: "Latency", value: "84ms", hint: "p95" }, + { label: "Migrations", value: "12", hint: "this week" }, +]; + +export function DesignPanel({ + title = "System Brief", + subtitle = "A compact panel designed for strong hierarchy and quick scanning.", + stats = defaultStats, + ctaLabel = "View details", +}: { + title?: string; + subtitle?: string; + stats?: Stat[]; + ctaLabel?: string; +}) { + return ( +
+
+
Field Report
+

{title}

+

{subtitle}

+
+ +
+ {stats.map((s) => ( +
+
+
{s.label}
+ {s.hint ?
{s.hint}
: null} +
+
{s.value}
+
+ ))} +
+ +
+ +
+
+ ); +} diff --git a/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/index.html b/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/index.html new file mode 100644 index 00000000..953fb4a8 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/index.html @@ -0,0 +1,131 @@ + + + + + + Avant Studio + + + + + + + +
+
+ + + +
+ +
+
+
+

Design lab

+

Striking, production-ready frontends without the generic glaze.

+

We craft visceral digital spaces that move fast, feel tactile, and stay memorable. Built with intent, tuned for launch.

+
+ + +
+
+
42 shipped sites
+
95% lighthouse perf
+
0 generic templates
+
+
+
+
Now launching
+
+

Neon Observatory

+

A retro-futurist control room with live telemetry, aurora gradients, and glitch hover states.

+
CSS Grid
+
Framer Motion
+
ARIA-first
+
+
+ ETA: 2 weeks + Visual QA locked +
+
+
+
+ +
+
+

01 / Intent

+

Pick a bold narrative, define the signature move, lock the palette.

+

We interrogate purpose, audience, and constraints. Each build commits to one unmistakable gesture—stripe, glow, or grain—and sticks to it.

+
+
+

02 / Build

+

Real code: semantic HTML, layered CSS, purposeful motion.

+

CSS variables for theming, responsive grids, progressive enhancement. Animations gated by prefers-reduced-motion.

+
+
+

03 / Polish

+

Accessibility, performance, and tactile interactions.

+

Contrast checks, keyboard navigation, tuned shadows, intentional hover states. We avoid boilerplate aesthetics at all costs.

+
+
+ +
+
+

Field notes

+

Recent drops

+
+
+
+
+
+
+
+
+

2024

+

Aerial atlas

+

Editorial map portal with split-screen narrative and scroll-synced chapters.

+
+
+

2023

+

Glassfoundry

+

Industrial dashboard with translucent panels, border glows, and live system vitals.

+
+
+

2022

+

Islands

+

Pastel travel companion with hand-drawn dividers, slow float animations, and tactile cards.

+
+
+
+
+ +
+ + +
+ + + + diff --git a/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/script.js b/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/script.js new file mode 100644 index 00000000..1c6affb5 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/script.js @@ -0,0 +1,13 @@ +const observer = new IntersectionObserver( + entries => { + entries.forEach(entry => { + if (entry.isIntersecting) { + entry.target.classList.add('visible'); + observer.unobserve(entry.target); + } + }); + }, + { threshold: 0.2 } +); + +document.querySelectorAll('.reveal').forEach(el => observer.observe(el)); diff --git a/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/style.css b/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/style.css new file mode 100644 index 00000000..ec83815a --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/assets/vanilla-starter/style.css @@ -0,0 +1,425 @@ +@import url('https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:wght@500;700&family=Newsreader:opsz,wght@6..72,400;600&display=swap'); + +:root { + --bg: #0b0c10; + --fg: #f6f1e6; + --muted: #a7acba; + --accent: #ff6b4a; + --accent-2: #6b9bff; + --card: rgba(255, 255, 255, 0.03); + --stroke: rgba(255, 255, 255, 0.12); + --radius: 18px; + --shadow: 0 18px 44px rgba(0, 0, 0, 0.35); + --ease: cubic-bezier(0.22, 1, 0.36, 1); +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +body { + margin: 0; + font-family: 'Newsreader', 'Times New Roman', serif; + color: var(--fg); + background: var(--bg); + min-height: 100vh; + line-height: 1.7; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + background-image: + radial-gradient(1200px at 15% 20%, rgba(107, 155, 255, 0.25), transparent 50%), + radial-gradient(1400px at 80% 0%, rgba(255, 107, 74, 0.2), transparent 50%), + linear-gradient(135deg, rgba(255, 255, 255, 0.03), transparent); +} + +.grain { + position: fixed; + inset: 0; + pointer-events: none; + background: + radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.04), transparent 35%), + repeating-linear-gradient(90deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0.02) 1px, transparent 1px, transparent 3px); + mix-blend-mode: soft-light; + opacity: 0.7; + z-index: 1; +} + +a { + color: inherit; + text-decoration: none; +} + +.skip-link { + position: absolute; + left: -999px; + top: 0; + padding: 12px 16px; + background: var(--accent); + color: #0b0c10; + border-radius: 8px; + font-weight: 700; + z-index: 999; +} + +.skip-link:focus { + left: 16px; + top: 16px; +} + +.top-bar { + position: sticky; + top: 0; + z-index: 10; + display: flex; + align-items: center; + justify-content: space-between; + padding: 18px 36px; + backdrop-filter: blur(10px); + background: rgba(11, 12, 16, 0.75); + border-bottom: 1px solid var(--stroke); +} + +.logo { + font-family: 'Bricolage Grotesque', 'Arial Black', sans-serif; + font-weight: 700; + letter-spacing: -0.02em; +} + +nav { + display: flex; + gap: 18px; + font-size: 0.95rem; +} + +nav a { + padding: 8px 12px; + border-radius: 999px; + border: 1px solid transparent; + transition: border-color 220ms var(--ease), color 220ms var(--ease); +} + +nav a:hover, +nav a:focus-visible { + border-color: var(--stroke); + color: var(--accent); +} + +button { + font-family: 'Bricolage Grotesque', sans-serif; + font-weight: 700; + border: none; + cursor: pointer; +} + +.cta { + padding: 12px 18px; + border-radius: 999px; + background: linear-gradient(120deg, var(--accent), var(--accent-2)); + color: #0b0c10; + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.25); + transition: transform 200ms var(--ease), box-shadow 200ms var(--ease); +} + +.cta:hover { + transform: translateY(-3px); + box-shadow: 0 16px 44px rgba(0, 0, 0, 0.35); +} + +.hero { + display: grid; + grid-template-columns: 1.2fr 0.8fr; + gap: 32px; + padding: 96px 36px 48px; + position: relative; +} + +.hero-copy h1 { + font-family: 'Bricolage Grotesque', sans-serif; + font-size: clamp(2.4rem, 5vw, 3.6rem); + line-height: 1.1; + letter-spacing: -0.03em; + margin: 12px 0; +} + +.hero .lede { + max-width: 56ch; + color: var(--muted); + font-size: 1.05rem; +} + +.eyebrow { + text-transform: uppercase; + letter-spacing: 0.18em; + font-size: 0.78rem; + color: var(--accent); + margin: 0 0 8px; +} + +.actions { + display: flex; + gap: 12px; + margin: 24px 0 18px; +} + +.ghost { + padding: 12px 16px; + border-radius: 999px; + background: transparent; + border: 1.5px solid var(--stroke); + color: var(--fg); + transition: border-color 220ms var(--ease), color 220ms var(--ease), transform 220ms var(--ease); +} + +.ghost:hover { + border-color: var(--accent); + color: var(--accent); + transform: translateY(-2px); +} + +.stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; + margin-top: 20px; + color: var(--muted); + font-size: 0.95rem; +} + +.stats span { + display: block; + font-family: 'Bricolage Grotesque', sans-serif; + font-size: 1.5rem; + color: var(--fg); +} + +.hero-card { + background: var(--card); + border: 1px solid var(--stroke); + border-radius: 22px; + padding: 24px; + box-shadow: var(--shadow); + position: relative; + overflow: hidden; +} + +.hero-card::after { + content: ''; + position: absolute; + inset: -30%; + background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.04), transparent 45%); + transform: rotate(8deg); + opacity: 0.8; +} + +.hero-card .tag { + display: inline-block; + padding: 8px 12px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.07); + color: var(--accent); + font-size: 0.85rem; + position: relative; + z-index: 2; +} + +.hero-card .card-body { + position: relative; + z-index: 2; +} + +.hero-card h2 { + font-family: 'Bricolage Grotesque', sans-serif; + margin: 12px 0 8px; +} + +.hero-card p { + color: var(--muted); + margin-bottom: 12px; +} + +.pill { + display: inline-block; + padding: 8px 12px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.05); + border: 1px solid var(--stroke); + margin: 4px 6px 4px 0; + font-size: 0.85rem; +} + +.line { + margin: 16px 0; + height: 1px; + background: linear-gradient(90deg, transparent, var(--accent), transparent); +} + +.meta { + display: flex; + justify-content: space-between; + color: var(--muted); + font-size: 0.9rem; +} + +.grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 18px; + padding: 48px 36px; +} + +.panel { + border: 1px solid var(--stroke); + border-radius: var(--radius); + padding: 22px; + background: rgba(255, 255, 255, 0.02); + box-shadow: 0 12px 28px rgba(0, 0, 0, 0.22); +} + +.panel h3 { + margin: 6px 0 10px; + font-family: 'Bricolage Grotesque', sans-serif; +} + +.panel p { + color: var(--muted); +} + +.timeline { + padding: 24px 36px 80px; + border-top: 1px solid var(--stroke); +} + +.timeline-head h3 { + font-family: 'Bricolage Grotesque', sans-serif; + margin: 8px 0 16px; +} + +.timeline-rail { + position: relative; + height: 3px; + background: var(--stroke); + border-radius: 999px; + margin: 24px 0 32px; +} + +.timeline-rail .dot { + position: absolute; + top: -6px; + width: 15px; + height: 15px; + background: var(--accent); + border-radius: 50%; + box-shadow: 0 0 0 6px rgba(255, 107, 74, 0.15); +} + +.timeline-rail .dot:nth-child(1) { left: 8%; } +.timeline-rail .dot:nth-child(2) { left: 50%; } +.timeline-rail .dot:nth-child(3) { left: 88%; } + +.timeline-items { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + gap: 16px; +} + +.timeline-card { + border: 1px solid var(--stroke); + border-radius: var(--radius); + padding: 18px; + background: rgba(255, 255, 255, 0.02); + box-shadow: 0 10px 24px rgba(0, 0, 0, 0.2); +} + +.timeline-card .label { + font-size: 0.9rem; + letter-spacing: 0.12em; + color: var(--accent); + text-transform: uppercase; + margin-bottom: 6px; +} + +.timeline-card h4 { + margin: 4px 0 8px; + font-family: 'Bricolage Grotesque', sans-serif; +} + +.timeline-card p { + color: var(--muted); +} + +.footer { + border-top: 1px solid var(--stroke); + padding: 28px 36px 48px; + position: relative; + overflow: hidden; +} + +.marquee { + display: grid; + grid-auto-flow: column; + gap: 16px; + font-family: 'Bricolage Grotesque', sans-serif; + text-transform: uppercase; + letter-spacing: 0.14em; + color: var(--muted); + animation: scroll 18s linear infinite; +} + +@keyframes scroll { + from { transform: translateX(0); } + to { transform: translateX(-50%); } +} + +.footer-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 12px; + margin-top: 24px; +} + +.footer-grid a { + display: block; + color: var(--fg); + text-decoration: underline; + margin-bottom: 4px; +} + +.reveal { + opacity: 0; + transform: translateY(22px); + transition: transform 320ms var(--ease), opacity 320ms var(--ease); +} + +.reveal.visible { + opacity: 1; + transform: translateY(0); +} + +@media (max-width: 960px) { + .hero { + grid-template-columns: 1fr; + padding-top: 72px; + } + + .top-bar { + position: sticky; + } + + nav { + display: none; + } + + .actions { + flex-direction: column; + align-items: flex-start; + } +} + +@media (prefers-reduced-motion: reduce) { + * { + animation: none !important; + transition: none !important; + } +} diff --git a/project-governance/skills/snapshots/frontend-design/references/aesthetic-playbook.md b/project-governance/skills/snapshots/frontend-design/references/aesthetic-playbook.md new file mode 100644 index 00000000..b71fb9f6 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/references/aesthetic-playbook.md @@ -0,0 +1,49 @@ +# Aesthetic Playbook + +Pick ONE direction and commit. Swap colors/fonts if needed, but keep the intent. Choose a single **signature move** that someone will remember. + +## Font Rule (avoid default vibes) +- If the repo already has a font system, stay consistent unless asked to change it. +- Otherwise: pick a characterful display font + a legible body font. Avoid overused “default tech” pairings. + +## Brutalist Raw (high-contrast, rule-heavy) +- Fonts: Display `Bricolage Grotesque` / `Fraunces`; Body `Atkinson Hyperlegible` / `IBM Plex Sans`; Mono `IBM Plex Mono`. +- Colors: Ink/ivory with one acidic accent (e.g. tomato, chartreuse). +- Signature moves: oversized numeric index badges; thick 2px rules; hard invert hover. +- Backgrounds: checkerboard corner, dotted matrix, a single diagonal stripe. + +## Editorial / Magazine (luxury, typographic hierarchy) +- Fonts: Display `Instrument Serif` / `Cormorant Garamond`; Body `Source Serif 4` / `Newsreader`; Mono `DM Mono`. +- Colors: warm off-white, deep ink, one burnt accent (rust/saffron). +- Signature moves: pull-quote rail; hairline rules; “issue number” metadata strip. +- Backgrounds: subtle paper grain, soft vignette. + +## Techno-Gothic (dark, minimal, sharp accents) +- Fonts: Display `Unbounded` / `Syne`; Body `Work Sans` / `Barlow`; Mono `JetBrains Mono`. +- Colors: near-black base with cold accent (cyan/acid green) + muted steel. +- Signature moves: corner ticks, scanline sheen on hover, “system status” chips. +- Backgrounds: diagonal hatch, faint grid, tiny starfield. + +## Neo-Poster (bold blocks, loud hierarchy) +- Fonts: Display `Bebas Neue` / `Archivo Black`; Body `Noto Sans`; Mono `Space Mono` (only if it fits the concept). +- Colors: high-sat primaries on warm neutral, with black rules. +- Signature moves: torn-paper edge (CSS mask vibe); huge headline with tight tracking; sticker CTA. +- Backgrounds: halftone dot field, off-register shadows. + +## Soft Craft (warm, tactile, friendly) +- Fonts: Display `Sora` / `Epilogue`; Body `Alegreya Sans` / `Manrope`; Mono optional. +- Colors: warm cream, terracotta accent, sage secondary. +- Signature moves: stitched borders; stacked cards; gentle floating blobs (reduced-motion safe). +- Backgrounds: irregular gradient blobs + low-opacity noise. + +## Industrial / Utilitarian (labeled panels, measured density) +- Fonts: Display `Archivo` / `Anton`; Body `Barlow` / `IBM Plex Sans`; Mono `JetBrains Mono`. +- Colors: cold neutrals with hazard accent (amber) and a secondary teal. +- Signature moves: panel labels; coordinate tags; “spec table” sectioning. +- Backgrounds: repeating hatch, soft inner glows for depth. + +## How to Choose (fast) +1) Choose the emotional goal (luxe, raw, calm, severe, playful). +2) Pick type first (display sets the tone). +3) Pick one signature move and apply it in 2–3 places max. +4) Keep everything else quiet and supportive. diff --git a/project-governance/skills/snapshots/frontend-design/references/ai-native-ui-patterns.md b/project-governance/skills/snapshots/frontend-design/references/ai-native-ui-patterns.md new file mode 100644 index 00000000..e7b7a252 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/references/ai-native-ui-patterns.md @@ -0,0 +1,42 @@ +# AI-native UI Patterns (trust + control) + +AI UI should feel like a product feature, not a bolt-on chatbot. Prioritize clarity, trust, and user control. + +## Core patterns + +### Copilot side panel (assistive AI) +- Persistent panel (often right rail) with: + - header + **AI disclosure** + - prompt input (or command chips/templates) + - output stream area + - actions (apply, copy, discard) + +### AI-generated labeling (strict) +- AI output must not be visually confused with user-authored content. +- Use a badge/label (“AI-generated”) with tooltip text and/or subtle tinting. + +### Citations / sources (recommended for factual outputs) +- Render as chips or footnotes under the relevant block. +- Make them clickable and scannable (title + optional section anchor). + +### “Why this?” affordance +- Provide a short “why this suggestion?” expansion with neutral language. +- Prefer concrete reasons (policy, data, heuristic) over anthropomorphic phrasing. + +## Human-in-the-loop (strict) +- Provide at least one of: + - **Apply / Undo** + - **Accept / Reject** + - confirmation for destructive actions +- Never silently perform irreversible changes. + +## AI loading and motion +- Use subtle, purposeful indicators: + - typing dots, shimmer skeleton, progressive reveal +- Respect `prefers-reduced-motion` (no endless animated flourish). + +## Signature move ideas (pick one) +- Citation rail (chips aligned to the right edge of the answer) +- Apply stack (queued changes with an “apply all” + per-item undo) +- Confidence capsule (uncertainty/assumptions shown as compact pills) + diff --git a/project-governance/skills/snapshots/frontend-design/references/anti-patterns.md b/project-governance/skills/snapshots/frontend-design/references/anti-patterns.md new file mode 100644 index 00000000..4c19d468 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/references/anti-patterns.md @@ -0,0 +1,23 @@ +# Anti-Patterns (avoid “AI slop”) + +Use this as a quick filter before shipping. + +## Visual clichés +- Generic purple-on-white gradients with soft glass cards everywhere. +- Samey startup landing layout: centered hero, 3 cards, logo wall, FAQ, identical CTA band. +- Indiscriminate glow + blur layers that reduce legibility. + +## Typography defaults +- Unintentional type: no scale, no rhythm, headings too close in size to body. +- Mixing too many fonts “because it looks cool” (unless the direction is explicitly chaotic). +- Defaulting to the same trendy “safe” font pairings (e.g., the usual modern grotesks) when the project calls for a stronger voice. + +## Motion mistakes +- Random micro-animations everywhere instead of one orchestrated sequence. +- No `prefers-reduced-motion` handling. +- Hover-only affordances (mobile users get nothing). + +## UX/a11y misses +- Weak focus states, low contrast, tiny hit targets. +- Buttons styled as links (or vice versa) without correct semantics. +- Missing labels on inputs, icon-only actions without accessible names. diff --git a/project-governance/skills/snapshots/frontend-design/references/implementation-patterns.md b/project-governance/skills/snapshots/frontend-design/references/implementation-patterns.md new file mode 100644 index 00000000..fff76303 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/references/implementation-patterns.md @@ -0,0 +1,56 @@ +# Implementation Patterns + +Use these patterns to move quickly while keeping the aesthetic sharp. Prefer real code and real semantics over “design vibes”. + +## Decision: Vanilla vs React +- Use **vanilla** for quick concepts, single pages, marketing-style layouts. +- Use **React** when the UI lives inside an app, needs state, routes, or reusable components. + +## Vanilla HTML/CSS/JS Workflow +- Start with semantic structure: `header`, `main`, `section`, `article`, `footer`. +- Add skip links when there’s a nav/header: `a.skip-nav` → `#main`. +- Define theme tokens up top: + ```css + :root { + --bg: #0b0c10; + --surface: #10131a; + --fg: #f7f2e9; + --muted: #9aa1b5; + --accent: #ff6b4a; + --radius: 18px; + --shadow: 0 18px 40px rgba(0,0,0,0.35); + --ease: cubic-bezier(.2,.9,.2,1); + } + ``` +- Layout: Grid for macro, Flexbox for clusters. Break the grid deliberately but preserve reading order. +- Motion: prefer CSS keyframes + `transition`. Orchestrate a few moments (load + hover), not everything. +- Reveal animations: use IntersectionObserver to toggle classes (small JS only). + +## React Patterns (TypeScript) +- Keep components small: `Hero`, `FeatureList`, `SpecsRail`, `CTA`. +- Use data arrays for repeated UI (cards/steps/metrics) and map to components. +- Styling: prefer the repo’s existing approach. If unknown, CSS Modules is a safe default. +- Motion: keep durations < 500ms; stagger by 80–140ms; gate everything with reduced-motion. + +## Motion & Reduced Motion +- Always include a reduced-motion fallback: + ```css + @media (prefers-reduced-motion: reduce) { + * { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; scroll-behavior: auto !important; } + } + ``` +- Keep animations paint-friendly (transform/opacity). Avoid animating large blur shadows. + +## Layout & Spacing +- Use a spacing scale (4/8 base). Keep prose line-length ~68–76ch. +- If maximalist: constrain chaos inside frames. If minimal: increase margins and tighten hierarchy. + +## Texture & Backgrounds (CSS-only) +- Use layered gradients and subtle noise-like patterns (no heavy assets by default). +- Prefer subtle grain overlays over full-page blur. + +## QA Checklist +- One `h1`, logical heading order, landmarks present. +- Focus visible, keyboard usable, contrast AA+. +- Tap targets 44px minimum for primary interactions. +- Mobile layout feels intentional (not just “stack everything”). diff --git a/project-governance/skills/snapshots/frontend-design/references/react-next-best-practices.md b/project-governance/skills/snapshots/frontend-design/references/react-next-best-practices.md new file mode 100644 index 00000000..8fca0ff1 --- /dev/null +++ b/project-governance/skills/snapshots/frontend-design/references/react-next-best-practices.md @@ -0,0 +1,25 @@ +# React + Next.js Best Practices (concise) + +## React component design +- Keep components and Hooks pure: compute UI from props/state without side effects in render. +- Run side effects outside render (event handlers or Effects). +- Prefer event handlers for user-driven work; avoid “Effect for everything.” +- Follow the Rules of Hooks (top-level only; consistent call order; only in React functions). +- Don’t call component functions directly; use JSX so React controls rendering. +- Split large components into small, focused pieces; keep props stable and typed. + +## Next.js App Router +- Server Components by default; add `"use client"` only when you need state, effects, or browser APIs. +- Keep Client Components small and isolated (UI islands). +- Use `next/link` for navigation and `next/image` for real images. +- Prefer `next/font` when changing typography to avoid layout shift/FOIT. + +## Data fetching and caching +- Prefer server-side `fetch` and explicit caching with `cache`/`revalidate`. +- Avoid client-side fetch inside `useEffect` unless you truly need client-only data. +- Keep loading/error states explicit and user-friendly. + +## State and performance +- Minimize global state; lift only when necessary. +- Memoize expensive calculations; keep derived state computed, not stored. +- Avoid unnecessary re-renders by splitting components and using stable props. diff --git a/project-governance/skills/snapshots/skill-vetter/SKILL.md b/project-governance/skills/snapshots/skill-vetter/SKILL.md new file mode 100644 index 00000000..6f065bde --- /dev/null +++ b/project-governance/skills/snapshots/skill-vetter/SKILL.md @@ -0,0 +1,138 @@ +--- +name: skill-vetter +version: 1.0.0 +description: Security-first skill vetting for AI agents. Use before installing any skill from ClawdHub, GitHub, or other sources. Checks for red flags, permission scope, and suspicious patterns. +--- + +# Skill Vetter 🔒 + +Security-first vetting protocol for AI agent skills. **Never install a skill without vetting it first.** + +## When to Use + +- Before installing any skill from ClawdHub +- Before running skills from GitHub repos +- When evaluating skills shared by other agents +- Anytime you're asked to install unknown code + +## Vetting Protocol + +### Step 1: Source Check + +``` +Questions to answer: +- [ ] Where did this skill come from? +- [ ] Is the author known/reputable? +- [ ] How many downloads/stars does it have? +- [ ] When was it last updated? +- [ ] Are there reviews from other agents? +``` + +### Step 2: Code Review (MANDATORY) + +Read ALL files in the skill. Check for these **RED FLAGS**: + +``` +🚨 REJECT IMMEDIATELY IF YOU SEE: +───────────────────────────────────────── +• curl/wget to unknown URLs +• Sends data to external servers +• Requests credentials/tokens/API keys +• Reads ~/.ssh, ~/.aws, ~/.config without clear reason +• Accesses MEMORY.md, USER.md, SOUL.md, IDENTITY.md +• Uses base64 decode on anything +• Uses eval() or exec() with external input +• Modifies system files outside workspace +• Installs packages without listing them +• Network calls to IPs instead of domains +• Obfuscated code (compressed, encoded, minified) +• Requests elevated/sudo permissions +• Accesses browser cookies/sessions +• Touches credential files +───────────────────────────────────────── +``` + +### Step 3: Permission Scope + +``` +Evaluate: +- [ ] What files does it need to read? +- [ ] What files does it need to write? +- [ ] What commands does it run? +- [ ] Does it need network access? To where? +- [ ] Is the scope minimal for its stated purpose? +``` + +### Step 4: Risk Classification + +| Risk Level | Examples | Action | +|------------|----------|--------| +| 🟢 LOW | Notes, weather, formatting | Basic review, install OK | +| 🟡 MEDIUM | File ops, browser, APIs | Full code review required | +| 🔴 HIGH | Credentials, trading, system | Human approval required | +| ⛔ EXTREME | Security configs, root access | Do NOT install | + +## Output Format + +After vetting, produce this report: + +``` +SKILL VETTING REPORT +═══════════════════════════════════════ +Skill: [name] +Source: [ClawdHub / GitHub / other] +Author: [username] +Version: [version] +─────────────────────────────────────── +METRICS: +• Downloads/Stars: [count] +• Last Updated: [date] +• Files Reviewed: [count] +─────────────────────────────────────── +RED FLAGS: [None / List them] + +PERMISSIONS NEEDED: +• Files: [list or "None"] +• Network: [list or "None"] +• Commands: [list or "None"] +─────────────────────────────────────── +RISK LEVEL: [🟢 LOW / 🟡 MEDIUM / 🔴 HIGH / ⛔ EXTREME] + +VERDICT: [✅ SAFE TO INSTALL / ⚠️ INSTALL WITH CAUTION / ❌ DO NOT INSTALL] + +NOTES: [Any observations] +═══════════════════════════════════════ +``` + +## Quick Vet Commands + +For GitHub-hosted skills: +```bash +# Check repo stats +curl -s "https://api.github.com/repos/OWNER/REPO" | jq '{stars: .stargazers_count, forks: .forks_count, updated: .updated_at}' + +# List skill files +curl -s "https://api.github.com/repos/OWNER/REPO/contents/skills/SKILL_NAME" | jq '.[].name' + +# Fetch and review SKILL.md +curl -s "https://raw.githubusercontent.com/OWNER/REPO/main/skills/SKILL_NAME/SKILL.md" +``` + +## Trust Hierarchy + +1. **Official OpenClaw skills** → Lower scrutiny (still review) +2. **High-star repos (1000+)** → Moderate scrutiny +3. **Known authors** → Moderate scrutiny +4. **New/unknown sources** → Maximum scrutiny +5. **Skills requesting credentials** → Human approval always + +## Remember + +- No skill is worth compromising security +- When in doubt, don't install +- Ask your human for high-risk decisions +- Document what you vet for future reference + +--- + +*Paranoia is a feature.* 🔒🦀 diff --git a/project-governance/skills/snapshots/skill-vetter/_meta.json b/project-governance/skills/snapshots/skill-vetter/_meta.json new file mode 100644 index 00000000..a5b2e69f --- /dev/null +++ b/project-governance/skills/snapshots/skill-vetter/_meta.json @@ -0,0 +1,11 @@ +{ + "owner": "spclaudehome", + "slug": "skill-vetter", + "displayName": "Skill Vetter", + "latest": { + "version": "1.0.0", + "publishedAt": 1769863429632, + "commit": "https://github.com/clawdbot/skills/commit/c563399ea973b60cb63db5ed84e871750e65939a" + }, + "history": [] +} diff --git a/project-governance/skills/snapshots/superpowers/SKILL.md b/project-governance/skills/snapshots/superpowers/SKILL.md new file mode 100644 index 00000000..769ce8f6 --- /dev/null +++ b/project-governance/skills/snapshots/superpowers/SKILL.md @@ -0,0 +1,978 @@ +--- +name: superpowers +description: > + Agentic software development methodology — 13 integrated skills for + disciplined AI-assisted development covering brainstorming, planning, + TDD, debugging, code review, git worktrees, and branch management. +metadata: + openclaw: + emoji: "⚡" +--- + +# Superpowers + +Disciplined, systematic approach to AI-assisted software development. 13 integrated skills covering the full development lifecycle. + +## The 7-Step Workflow + +1. **Brainstorm** — Design before implementation (Section 2) +2. **Plan** — Write detailed implementation plan (Section 3) +3. **Execute** — Implement with subagents or batches (Sections 4-6) +4. **Test** — TDD throughout: RED-GREEN-REFACTOR (Section 7) +5. **Debug** — Systematic root cause analysis when needed (Section 8) +6. **Review** — Code review after each task (Section 10) +7. **Finish** — Branch completion and integration (Section 12) + +## How to Use + +Apply the relevant section based on your current task: + +| Task | Section | +|------|---------| +| Starting new work | Section 2 (Brainstorming) → Section 3 (Writing Plans) | +| Implementing a plan (this session) | Section 5 (Subagent-Driven Development) | +| Implementing a plan (separate session) | Section 4 (Executing Plans) | +| Multiple independent problems | Section 6 (Dispatching Parallel Agents) | +| Writing or fixing code | Section 7 (Test-Driven Development) | +| Bug, test failure, unexpected behavior | Section 8 (Systematic Debugging) | +| About to claim work is done | Section 9 (Verification Before Completion) | +| After completing work | Section 10 (Code Review) | +| Need isolated workspace | Section 11 (Using Git Worktrees) | +| Ready to merge/integrate | Section 12 (Finishing a Development Branch) | +| Creating new skills | Section 13 (Writing Skills) | + +**Skill priority:** Process skills first (brainstorming, debugging), then implementation skills. + +**Skill types:** +- **Rigid** (TDD, debugging, verification): Follow exactly. Don't adapt away discipline. +- **Flexible** (patterns, worktrees): Adapt principles to context. + +--- + +## 1. Using Superpowers + + +If you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill. + +IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT. + +This is not negotiable. This is not optional. You cannot rationalize your way out of this. + + +**Rule:** Invoke relevant skills BEFORE any response or action. Even a 1% chance a section might apply means you should check. + +**Process:** +1. User message received +2. Check: might any section apply? + - Yes → Follow that section + - No → Respond directly +3. If about to plan: check Section 2 (Brainstorming) first +4. If section has checklist: create todo per checklist item +5. Announce: "Using [skill] to [purpose]" + +**Priority order:** +1. Process sections first (brainstorming, debugging) +2. Implementation sections second + +**User instructions say WHAT, not HOW.** "Add X" or "Fix Y" doesn't mean skip workflows. + +### Red Flags — You're Rationalizing + +| Thought | Reality | +|---------|---------| +| "This is just a simple question" | Questions are tasks. Check for skills. | +| "I need more context first" | Skill check comes BEFORE clarifying questions. | +| "Let me explore the codebase first" | Skills tell you HOW to explore. Check first. | +| "I can check git/files quickly" | Files lack conversation context. Check for skills. | +| "Let me gather information first" | Skills tell you HOW to gather information. | +| "This doesn't need a formal skill" | If a skill exists, use it. | +| "I remember this skill" | Skills evolve. Read current version. | +| "This doesn't count as a task" | Action = task. Check for skills. | +| "The skill is overkill" | Simple things become complex. Use it. | +| "I'll just do this one thing first" | Check BEFORE doing anything. | +| "This feels productive" | Undisciplined action wastes time. Skills prevent this. | +| "I know what that means" | Knowing the concept ≠ using the skill. Invoke it. | + +--- + +## 2. Brainstorming + +**Use before:** Any creative work — creating features, building components, adding functionality, or modifying behavior. + + +Do NOT write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity. + + +### Anti-Pattern: "This Is Too Simple To Need A Design" + +Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval. + +### Checklist + +1. **Explore project context** — check files, docs, recent commits +2. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria +3. **Propose 2-3 approaches** — with trade-offs and your recommendation +4. **Present design** — in sections scaled to complexity, get user approval after each section +5. **Write design doc** — save to `docs/plans/YYYY-MM-DD--design.md` and commit +6. **Transition to implementation** — follow Section 3 (Writing Plans) + +### Process + +- Ask one question at a time. Prefer multiple choice. +- Propose 2-3 approaches with trade-offs. Lead with your recommendation. +- Present design sections incrementally. Get approval after each. +- Cover: architecture, components, data flow, error handling, testing. +- Apply YAGNI ruthlessly. +- Be flexible — go back and clarify when something doesn't make sense. + +### After Design Approval + +Write validated design to `docs/plans/YYYY-MM-DD--design.md`, commit, then follow Section 3 (Writing Plans). + +**The terminal state is invoking writing-plans.** Do NOT invoke any other implementation skill. The ONLY next step after brainstorming is writing-plans. + +### Key Principles + +- **One question at a time** — Don't overwhelm with multiple questions +- **Multiple choice preferred** — Easier to answer than open-ended when possible +- **YAGNI ruthlessly** — Remove unnecessary features from all designs +- **Explore alternatives** — Always propose 2-3 approaches before settling +- **Incremental validation** — Present design, get approval before moving on + +--- + +## 3. Writing Plans + +**Use when:** You have a spec or requirements for a multi-step task, before touching code. + +Write comprehensive implementation plans with bite-sized tasks. Assume the implementer has zero context. Document exact file paths, complete code, exact commands with expected output. + +**Announce at start:** "I'm using the writing-plans skill to create the implementation plan." + +**Save plans to:** `docs/plans/YYYY-MM-DD-.md` + +### Plan Header Template + +Every plan MUST start with: + + # [Feature Name] Implementation Plan + > **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan. + **Goal:** [One sentence] + **Architecture:** [2-3 sentences] + **Tech Stack:** [Key technologies] + +### Task Granularity + +Each step is one action (2-5 minutes): +- "Write the failing test" — step +- "Run it to verify it fails" — step +- "Implement minimal code to pass" — step +- "Run tests to verify pass" — step +- "Commit" — step + +### Task Structure + + ### Task N: [Component Name] + **Files:** + - Create: `exact/path/to/file.py` + - Modify: `exact/path/to/existing.py:123-145` + - Test: `tests/exact/path/to/test.py` + **Step 1:** Write failing test (with complete code) + **Step 2:** Run test, verify fails (exact command + expected output) + **Step 3:** Write minimal implementation (complete code) + **Step 4:** Run test, verify passes (exact command + expected output) + **Step 5:** Commit (exact git commands) + +### Remember + +- Exact file paths always +- Complete code in plan (not "add validation") +- Exact commands with expected output +- DRY, YAGNI, TDD, frequent commits + +### Execution Handoff + +After saving plan, offer: + +**"Plan complete and saved. Two execution options:** + +**1. Subagent-Driven (this session)** — fresh subagent per task, review between tasks, fast iteration → follow Section 5 + +**2. Parallel Session (separate)** — open new session, batch execution with checkpoints → follow Section 4 + +**Which approach?"** + +--- + +## 4. Executing Plans + +**Use when:** You have a written implementation plan to execute in a separate session with review checkpoints. + +**Announce at start:** "I'm using the executing-plans skill to implement this plan." + +### Process + +1. **Load and review plan** — Read critically, raise concerns before starting. If no concerns: create task list and proceed. +2. **Execute batch** — Default first 3 tasks. For each: mark in_progress → follow steps exactly → run verifications → mark completed +3. **Report** — Show what was implemented, verification output. Say: "Ready for feedback." +4. **Continue** — Apply feedback, execute next batch, repeat +5. **Complete** — After all tasks verified, follow Section 12 (Finishing a Development Branch) + +### When to Stop and Ask for Help + +**STOP executing immediately when:** +- Hit a blocker mid-batch (missing dependency, test fails, instruction unclear) +- Plan has critical gaps preventing starting +- You don't understand an instruction +- Verification fails repeatedly + +**Ask for clarification rather than guessing.** + +### When to Revisit Earlier Steps + +**Return to Review (Step 1) when:** +- Partner updates the plan based on your feedback +- Fundamental approach needs rethinking + +**Don't force through blockers** — stop and ask. + +### Rules + +- Follow plan steps exactly +- Don't skip verifications +- Between batches: report and wait +- Stop when blocked, don't guess +- Never start implementation on main/master without explicit consent + +### Integration + +- REQUIRED: Set up workspace with Section 11 (Git Worktrees) before starting +- After all tasks: follow Section 12 (Finishing a Development Branch) + +--- + +## 5. Subagent-Driven Development + +**Use when:** Executing implementation plans with independent tasks in the current session. Fresh subagent per task + two-stage review. + +**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration + +### Process + +1. **Read plan, extract all tasks** with full text and context. Create task list. +2. **Per task:** + a. Dispatch implementer subagent (provide full task text + context, don't make them read plan file) + b. If subagent asks questions → answer clearly before proceeding + c. Subagent implements, tests, commits, self-reviews + d. Dispatch spec reviewer subagent → verify code matches spec + e. If issues → implementer fixes → re-review until ✅ + f. Dispatch code quality reviewer subagent + g. If issues → implementer fixes → re-review until ✅ + h. Mark task complete +3. **After all tasks:** Dispatch final code reviewer for entire implementation +4. **Complete:** Follow Section 12 (Finishing a Development Branch) + +### Implementer Subagent Prompt + +Provide: full task text, context (where it fits), working directory. Tell them: +- Implement exactly what task specifies +- Write tests (TDD if task says to) +- If you have questions about requirements, approach, or anything unclear — **ask them now before starting** +- Commit work +- Self-review: completeness (all requirements?), quality (clean, maintainable?), discipline (YAGNI?), testing (real behavior, not mocks?) +- If you find issues during self-review, fix them now before reporting +- Report: what implemented, test results, files changed, self-review findings, concerns + +### Spec Reviewer Prompt + +Provide: full task requirements, implementer's report. Tell them: +- **CRITICAL: Do NOT trust the implementer's report** — read actual code +- The implementer may be incomplete, inaccurate, or optimistic +- Check by reading code: missing requirements, extra/unneeded work, misunderstandings +- Report: ✅ spec compliant or ❌ issues with file:line references + +### Code Quality Reviewer Prompt + +Use code review template (see Section 10). Provide: BASE_SHA, HEAD_SHA, description. +- Only dispatch after spec compliance passes +- Returns: Strengths, Issues (Critical/Important/Minor), Assessment + +### Rules + +- Never start on main/master without consent +- Never skip reviews (spec OR quality) +- Spec review BEFORE code quality review +- Don't dispatch parallel implementation subagents (conflicts) +- Don't move to next task with open review issues +- If subagent fails → dispatch fix subagent, don't fix manually (context pollution) +- Don't make subagent read plan file (provide full text instead) +- Accept "close enough" on spec compliance → NOT acceptable (spec issues = not done) +- **Start code quality review before spec compliance is ✅** → WRONG ORDER + +--- + +## 6. Dispatching Parallel Agents + +**Use when:** 2+ independent tasks that can be worked on without shared state or sequential dependencies. + +### When to Use + +- 3+ test files failing with different root causes +- Multiple subsystems broken independently +- Each problem can be understood without context from others +- No shared state between investigations + +**Don't use when:** +- Failures are related (fix one might fix others) +- Need full system context to understand +- Agents would interfere (editing same files, shared resources) +- Exploratory debugging (you don't know what's broken yet) + +### Pattern + +1. **Identify independent domains** — group failures by what's broken +2. **Create focused agent tasks** — each gets: specific scope, clear goal, constraints, expected output format +3. **Dispatch in parallel** — one agent per domain +4. **Review and integrate** — read summaries, verify no conflicts, run full test suite + +### Agent Prompt Structure + +Good prompts are: focused (one problem domain), self-contained (all context needed), specific about output (what to return). + +- ❌ Too broad: "Fix all the tests" — agent gets lost +- ✅ Specific: "Fix agent-tool-abort.test.ts — 3 failures listed below" +- ❌ No constraints: agent might refactor everything +- ✅ Constrained: "Do NOT change production code" or "Fix tests only" +- ❌ Vague output: "Fix it" — you don't know what changed +- ✅ Specific: "Return summary of root cause and changes" + +### Real Example + +**Scenario:** 6 test failures across 3 files after major refactoring + +**Dispatch:** +- Agent 1 → Fix agent-tool-abort.test.ts (3 timing issues) +- Agent 2 → Fix batch-completion-behavior.test.ts (2 event structure bugs) +- Agent 3 → Fix tool-approval-race-conditions.test.ts (1 async issue) + +**Results:** All fixes independent, no conflicts, full suite green. 3 problems solved in time of 1. + +--- + +## 7. Test-Driven Development + +**Use when:** Implementing any feature or bugfix, before writing implementation code. + +**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing. + +**Violating the letter of the rules is violating the spirit of the rules.** + +### The Iron Law + + NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST + +Write code before the test? Delete it. Start over. No exceptions: +- Don't keep it as "reference" +- Don't "adapt" it while writing tests +- Don't look at it +- Delete means delete + +Implement fresh from tests. Period. + +### RED — Write Failing Test + +Write one minimal test showing what should happen. + +**Good:** +```typescript +test('retries failed operations 3 times', async () => { + let attempts = 0; + const operation = () => { + attempts++; + if (attempts < 3) throw new Error('fail'); + return 'success'; + }; + const result = await retryOperation(operation); + expect(result).toBe('success'); + expect(attempts).toBe(3); +}); +``` +Clear name, tests real behavior, one thing. + +**Bad:** +```typescript +test('retry works', async () => { + const mock = jest.fn() + .mockRejectedValueOnce(new Error()) + .mockResolvedValueOnce('success'); + await retryOperation(mock); + expect(mock).toHaveBeenCalledTimes(2); +}); +``` +Vague name, tests mock not code. + +**Requirements:** One behavior. Clear name. Real code (no mocks unless unavoidable). + +### Verify RED + +**MANDATORY. Never skip.** + +Run test. Confirm: fails (not errors), expected failure message, fails because feature missing. + +- Test passes? You're testing existing behavior. Fix test. +- Test errors? Fix error, re-run until it fails correctly. + +### GREEN — Minimal Code + +Write simplest code to pass the test. Don't add features, refactor, or "improve" beyond the test. + +**Good:** Just enough to pass. +**Bad:** Over-engineered with options/backoff/callbacks the test doesn't require (YAGNI). + +### Verify GREEN + +**MANDATORY.** + +Run test. Confirm: passes, other tests still pass, output pristine (no errors, warnings). + +- Test fails? Fix code, not test. +- Other tests fail? Fix now. + +### REFACTOR + +After green only: remove duplication, improve names, extract helpers. Keep tests green. Don't add behavior. + +### Why Order Matters + +**"I'll write tests after"** — Tests written after code pass immediately. Passing immediately proves nothing: might test wrong thing, might test implementation not behavior, might miss edge cases. Test-first forces you to see the test fail, proving it actually tests something. + +**"Already manually tested"** — Manual testing is ad-hoc. No record, can't re-run, easy to forget cases. Automated tests are systematic. + +**"Deleting X hours is wasteful"** — Sunk cost fallacy. The time is already gone. Keeping unverified code is technical debt. + +**"TDD is dogmatic"** — TDD IS pragmatic: finds bugs before commit, prevents regressions, documents behavior, enables refactoring. "Pragmatic" shortcuts = debugging in production = slower. + +### Bug Fix Example + +**Bug:** Empty email accepted + +**RED:** +```typescript +test('rejects empty email', async () => { + const result = await submitForm({ email: '' }); + expect(result.error).toBe('Email required'); +}); +``` + +**Verify RED:** FAIL — expected 'Email required', got undefined ✓ + +**GREEN:** +```typescript +function submitForm(data: FormData) { + if (!data.email?.trim()) return { error: 'Email required' }; + // ... +} +``` + +**Verify GREEN:** PASS ✓ → **REFACTOR** → extract validation if needed. + +### Verification Checklist + +Before marking work complete: +- [ ] Every new function/method has a test +- [ ] Watched each test fail before implementing +- [ ] Each test failed for expected reason +- [ ] Wrote minimal code to pass each test +- [ ] All tests pass +- [ ] Output pristine (no errors, warnings) +- [ ] Tests use real code (mocks only if unavoidable) +- [ ] Edge cases and errors covered + +Can't check all boxes? You skipped TDD. Start over. + +### When Stuck + +| Problem | Solution | +|---------|----------| +| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. | +| Test too complicated | Design too complicated. Simplify interface. | +| Must mock everything | Code too coupled. Use dependency injection. | +| Test setup huge | Extract helpers. Still complex? Simplify design. | + +### Testing Anti-Patterns + +When adding mocks or test utilities, avoid these pitfalls: +- **Testing mock behavior instead of real behavior** — Assert on real component output, not mock existence +- **Adding test-only methods to production classes** — Move to test utilities instead +- **Mocking without understanding dependencies** — Understand side effects before mocking; mock at lowest level needed +- **Incomplete mocks** — Mock the COMPLETE data structure as it exists in reality +- **Tests as afterthought** — Testing is part of implementation, not optional follow-up + +### Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Too simple to test" | Simple code breaks. Test takes 30 seconds. | +| "I'll test after" | Tests passing immediately prove nothing. | +| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" | +| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. | +| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is debt. | +| "Keep as reference" | You'll adapt it. That's testing after. Delete means delete. | +| "Need to explore first" | Fine. Throw away exploration, start with TDD. | +| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. | +| "TDD will slow me down" | TDD faster than debugging. | +| "Existing code has no tests" | You're improving it. Add tests for existing code. | +| "It's about spirit not ritual" | Violating the letter IS violating the spirit. | + +### Red Flags — STOP and Start Over + +Code before test. Test after implementation. Test passes immediately. Can't explain why test failed. Rationalizing "just this once." "I already manually tested it." "Keep as reference." "This is different because..." + +**All mean: Delete code. Start over with TDD.** + +--- + +## 8. Systematic Debugging + +**Use when:** Any bug, test failure, or unexpected behavior — before proposing fixes. + +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. + +**Violating the letter of this process is violating the spirit of debugging.** + +### The Iron Law + + NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST + +If you haven't completed Phase 1, you cannot propose fixes. + +**Use this ESPECIALLY when:** +- Under time pressure (emergencies make guessing tempting) +- "Just one quick fix" seems obvious +- You've already tried multiple fixes +- You don't fully understand the issue + +### Phase 1: Root Cause Investigation + +**BEFORE attempting ANY fix:** + +1. **Read error messages carefully** — don't skip. Read stack traces completely. Note line numbers, file paths, error codes. +2. **Reproduce consistently** — exact steps, every time. Not reproducible → gather more data, don't guess. +3. **Check recent changes** — git diff, recent commits, new dependencies, config changes, environmental differences. +4. **Gather evidence in multi-component systems** — Log data at each component boundary. Run once to see WHERE it breaks. Then investigate that component. + + Example: For CI → build → signing pipeline: + ```bash + # Log at each layer boundary: + # Layer 1 (workflow): echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}" + # Layer 2 (build): env | grep IDENTITY + # Layer 3 (signing): security find-identity -v + # Reveals: which layer the propagation fails + ``` + +5. **Trace data flow** — Where does bad value originate? Trace up the call stack to the source. Fix at source, not symptom. + + **Root cause tracing technique:** Observe symptom → find immediate cause → ask "what called this?" → keep tracing up → find original trigger → fix at source. + + Example: `git init` in wrong directory → `cwd: ''` → `createWorktree('')` → `Session.create()` → test accessed `tempDir` before `beforeEach` → **root cause**: top-level variable initialization. + +### Phase 2: Pattern Analysis + +1. Find working examples of similar code in the codebase +2. Compare: what's different between working and broken? +3. List every difference, however small +4. Understand dependencies and assumptions + +### Phase 3: Hypothesis and Testing + +1. Form single hypothesis: "X is root cause because Y" +2. Make SMALLEST possible change to test it +3. One variable at a time +4. Didn't work → new hypothesis. DON'T add more fixes on top. + +### Phase 4: Implementation + +1. Create failing test reproducing the bug (Section 7: TDD) +2. Implement single fix addressing root cause +3. Verify: test passes, no other tests broken +4. **If 3+ fixes failed:** STOP. Question the architecture. Discuss with your human partner. + + **Pattern indicating architectural problem:** + - Each fix reveals new shared state/coupling/problem in different place + - Fixes require "massive refactoring" to implement + - Each fix creates new symptoms elsewhere + + This is NOT a failed hypothesis — this is a wrong architecture. + +### Supporting Techniques + +- **Defense-in-depth:** After finding root cause, validate at EVERY layer data passes through. Entry point → business logic → environment guards → debug instrumentation. Single validation can be bypassed; multiple layers make the bug structurally impossible. +- **Condition-based waiting:** Replace arbitrary timeouts/sleeps with condition polling. Wait for the actual condition, not a guess about timing. `waitFor(() => condition())` instead of `setTimeout(check, 500)`. + +### Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Issue is simple" | Simple issues have root causes too. | +| "Emergency, no time" | Systematic is FASTER than thrashing. | +| "Just try this first" | First fix sets the pattern. Do it right. | +| "I see the problem" | Seeing symptoms ≠ understanding root cause. | +| "Multiple fixes saves time" | Can't isolate what worked. Causes new bugs. | +| "One more fix attempt" (after 2+) | 3+ failures = architectural problem. Question pattern. | +| "Reference too long, I'll adapt" | Partial understanding guarantees bugs. Read completely. | + +### Red Flags — STOP and Follow Process + +- "Quick fix for now, investigate later" +- "Just try changing X and see" +- Proposing solutions before tracing data flow +- "I don't fully understand but this might work" +- Each fix reveals new problem in different place +- 3+ fix attempts failed → **question the architecture** + +**ALL of these mean: STOP. Return to Phase 1.** + +--- + +## 9. Verification Before Completion + +**Use when:** About to claim work is complete, fixed, or passing — before committing or creating PRs. + +**Core principle:** Evidence before claims, always. + +**Violating the letter of this rule is violating the spirit of this rule.** + +### The Iron Law + + NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE + +If you haven't run the verification command in this message, you cannot claim it passes. + +### The Gate + +Before claiming ANY status: + + 1. IDENTIFY: What command proves this claim? + 2. RUN: Execute the FULL command (fresh, complete) + 3. READ: Full output, check exit code, count failures + 4. VERIFY: Does output confirm the claim? + - If NO: State actual status with evidence + - If YES: State claim WITH evidence + 5. ONLY THEN: Make the claim + + Skip any step = lying, not verifying + +### What Counts as Verification + +| Claim | Requires | NOT Sufficient | +|-------|----------|----------------| +| Tests pass | Test output: 0 failures | Previous run, "should pass" | +| Linter clean | Linter output: 0 errors | Partial check, extrapolation | +| Build succeeds | Build: exit 0 | Linter passing | +| Bug fixed | Test original symptom | Code changed, assumed fixed | +| Regression test works | Red-green cycle verified | Test passes once | +| Agent completed | VCS diff shows changes | Agent reports "success" | +| Requirements met | Line-by-line checklist | Tests passing | + +### Key Patterns + +**Tests:** +``` +✅ [Run test command] [See: 34/34 pass] "All tests pass" +❌ "Should pass now" / "Looks correct" +``` + +**Regression tests (TDD Red-Green):** +``` +✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass) +❌ "I've written a regression test" (without red-green verification) +``` + +**Agent delegation:** +``` +✅ Agent reports success → Check VCS diff → Verify changes → Report actual state +❌ Trust agent report +``` + +### Red Flags + +- Using "should", "probably", "seems to" +- Expressing satisfaction before verification ("Great!", "Perfect!", "Done!") +- Trusting agent success reports +- Relying on partial verification +- ANY wording implying success without having run verification + +**Run the command. Read the output. THEN claim the result.** + +### Rationalization Prevention + +| Excuse | Reality | +|--------|---------| +| "Should work now" | RUN the verification | +| "I'm confident" | Confidence ≠ evidence | +| "Just this once" | No exceptions | +| "Agent said success" | Verify independently | +| "Partial check is enough" | Partial proves nothing | +| "Different words so rule doesn't apply" | Spirit over letter | + +--- + +## 10. Code Review + +**Use when:** Completing tasks, implementing major features, before merging, or when receiving review feedback. + +### Part 1: Requesting Review + +**Mandatory after:** each task in subagent-driven development, major features, before merge. + +**How to request:** +1. Get git SHAs: `BASE_SHA=$(git rev-parse HEAD~1)`, `HEAD_SHA=$(git rev-parse HEAD)` +2. Dispatch code-reviewer subagent with the template below +3. Act on feedback: fix Critical immediately, fix Important before proceeding, note Minor for later + +**Code Reviewer Template:** + + You are reviewing code changes for production readiness. + Review {WHAT_WAS_IMPLEMENTED} against {PLAN_OR_REQUIREMENTS}. + Git range: {BASE_SHA}..{HEAD_SHA} + + Check: code quality, architecture, testing, requirements, production readiness. + + Review Checklist: + - Code: separation of concerns, error handling, type safety, DRY, edge cases + - Architecture: design decisions, scalability, performance, security + - Testing: tests test logic not mocks, edge cases, integration tests, all passing + - Requirements: all met, matches spec, no scope creep, breaking changes documented + + Output format: + ### Strengths — what's well done (be specific, file:line) + ### Issues + #### Critical (Must Fix) — bugs, security, data loss + #### Important (Should Fix) — architecture, missing features, test gaps + #### Minor (Nice to Have) — style, optimization + For each: file:line, what's wrong, why it matters, how to fix + ### Assessment — Ready to merge? [Yes/No/With fixes] + +### Part 2: Receiving Feedback + +**Response pattern:** READ → UNDERSTAND → VERIFY → EVALUATE → RESPOND → IMPLEMENT + +**Forbidden responses — NEVER say:** +- "You're absolutely right!" (performative) +- "Great point!" / "Excellent feedback!" (performative) +- "Let me implement that now" (before verification) + +**Instead:** Restate the technical requirement, ask clarifying questions, push back if wrong, or just fix it. + +**Handling unclear feedback:** +``` +IF any item is unclear: + STOP — do not implement anything yet + ASK for clarification on ALL unclear items + WHY: Items may be related. Partial understanding = wrong implementation. +``` + +**Implementation order for multi-item feedback:** +1. Clarify anything unclear FIRST +2. Blocking issues (breaks, security) +3. Simple fixes (typos, imports) +4. Complex fixes (refactoring, logic) +5. Test each fix individually + +**YAGNI check:** If reviewer suggests "implementing properly," grep codebase for actual usage. If unused → "This endpoint isn't called. Remove it (YAGNI)?" + +**When to push back:** +- Suggestion breaks existing functionality +- Reviewer lacks full context +- Violates YAGNI (unused feature) +- Technically incorrect for this stack +- Conflicts with architectural decisions + +**When feedback IS correct:** +``` +✅ "Fixed. [Brief description]" +✅ [Just fix it in code] +❌ "You're absolutely right!" / "Thanks for catching that!" +``` + +Actions speak. Just fix it. + +--- + +## 11. Using Git Worktrees + +**Use when:** Starting feature work that needs isolation or before executing implementation plans. + +**Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace." + +### Directory Selection (priority order) + +1. **Check existing:** `ls -d .worktrees 2>/dev/null` (preferred) or `ls -d worktrees 2>/dev/null` + - If found: use that directory. If both exist, `.worktrees` wins. +2. **Check AGENTS.md:** `grep -i "worktree.*director" AGENTS.md 2>/dev/null` + - If preference specified: use without asking. +3. **Ask user:** `.worktrees/` (project-local, hidden) or `~/.config/superpowers/worktrees//` (global) + +### Safety Verification + +For project-local directories: verify directory is in `.gitignore` before creating worktree. + + git check-ignore -q .worktrees 2>/dev/null + +If NOT ignored: +1. Add appropriate line to `.gitignore` +2. Commit the change +3. Proceed with worktree creation + +**Why critical:** Prevents accidentally committing worktree contents to repository. + +### Creation Steps + +1. **Detect project:** `project=$(basename "$(git rev-parse --show-toplevel)")` +2. **Create worktree:** `git worktree add "$path" -b "$BRANCH_NAME"` +3. **Run project setup** (auto-detect): + ```bash + if [ -f package.json ]; then npm install; fi + if [ -f Cargo.toml ]; then cargo build; fi + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + if [ -f pyproject.toml ]; then poetry install; fi + if [ -f go.mod ]; then go mod download; fi + ``` +4. **Verify clean baseline** — run tests. If tests fail: report failures, ask whether to proceed. +5. **Report:** location, test results, ready status + +### Rules + +- Never create worktree without verifying it's ignored (project-local) +- Never skip baseline test verification +- Never proceed with failing tests without asking +- Follow directory priority: existing → AGENTS.md → ask +- Auto-detect setup commands from project files + +--- + +## 12. Finishing a Development Branch + +**Use when:** Implementation is complete, all tests pass, ready to integrate. + +**Announce at start:** "I'm using the finishing-a-development-branch skill to complete this work." + +### Process + +1. **Verify tests pass** — if failing, stop. Cannot proceed. +2. **Determine base branch** — `git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null` +3. **Present exactly 4 options:** + ``` + Implementation complete. What would you like to do? + 1. Merge back to locally + 2. Push and create a Pull Request + 3. Keep the branch as-is + 4. Discard this work + ``` +4. **Execute choice** +5. **Cleanup worktree** (for options 1, 2, 4 only) + +### Option Details + +| Option | Merge | Push | Keep Worktree | Cleanup Branch | +|--------|-------|------|---------------|----------------| +| 1. Merge locally | Yes | - | - | Yes | +| 2. Create PR | - | Yes | Yes | - | +| 3. Keep as-is | - | - | Yes | - | +| 4. Discard | - | - | - | Yes (force) | + +**Option 1 (Merge):** Checkout base → pull latest → merge feature → verify tests on merged result → delete feature branch → cleanup worktree + +**Option 2 (Push/PR):** Push branch → `gh pr create` with summary and test plan → cleanup worktree + +**Option 4 (Discard):** Require typed "discard" confirmation. Show what will be deleted (branch, commits, worktree). Then: checkout base → `git branch -D` → cleanup worktree + +### Rules + +- Never proceed with failing tests +- Always verify tests on merged result (option 1) +- Require typed "discard" confirmation (option 4) +- Don't force-push without explicit request +- Present exactly 4 options — don't use open-ended questions + +--- + +## 13. Writing Skills + +**Use when:** Creating new skills, editing existing skills, or verifying skills work. + +### What is a Skill? + +A reusable reference guide for proven techniques, patterns, or tools. NOT narratives about how you solved a problem once. + +**Skills are:** Reusable techniques, patterns, tools, reference guides +**Skills are NOT:** One-off solutions, project-specific conventions, mechanical constraints (automate those instead) + +### The Iron Law (Same as TDD) + + NO SKILL WITHOUT A FAILING TEST FIRST + +Test with subagent pressure scenarios. Watch agents fail without skill (RED). Write minimal skill (GREEN). Close loopholes (REFACTOR). + +### SKILL.md Structure + + --- + name: skill-name-with-hyphens + description: "Use when [specific triggering conditions]" + --- + +Sections: Overview → When to Use → Core Pattern → Quick Reference → Common Mistakes + +### Description Field (Critical for Discovery) + +**CRITICAL: Description = When to Use, NOT What the Skill Does** + +Agents read description to decide which skills to load. The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow. + +**Why:** Testing revealed that when a description summarizes workflow, agents follow the description shortcut instead of reading the full skill. A description saying "code review between tasks" caused an agent to do ONE review, even though the skill specified TWO reviews (spec + quality). + +```yaml +# ❌ BAD: Summarizes workflow — agent may follow this instead of reading skill +description: Use when executing plans - dispatches subagent per task with code review + +# ✅ GOOD: Just triggering conditions +description: Use when executing implementation plans with independent tasks +``` + +### Naming + +- Verb-first, active voice: `condition-based-waiting` not `async-test-helpers` +- Gerunds work well: `creating-skills`, `testing-skills` +- Name by what you DO: `root-cause-tracing` not `debugging-techniques` + +### Key Rules + +- One excellent example beats many mediocre ones +- Flowcharts only for non-obvious decisions +- Keep inline unless reference >100 lines +- Test BEFORE deploying. No exceptions. + +### Bulletproofing Against Rationalization + +Skills that enforce discipline need to resist rationalization: + +1. **Close every loophole explicitly** — Don't just state the rule; forbid specific workarounds ("Don't keep it as reference, don't adapt it, delete means delete") +2. **Address "spirit vs letter"** — Add "Violating the letter IS violating the spirit" early +3. **Build rationalization table** — Capture every excuse agents make, add counters +4. **Create red flags list** — Make it easy to self-check when rationalizing + +### Skill Creation Checklist + +**RED:** Create pressure scenarios → run WITHOUT skill → document baseline failures (exact rationalizations agents use) +**GREEN:** Write skill addressing specific failures → run WITH skill → verify compliance +**REFACTOR:** Find new rationalizations → add counters → re-test until bulletproof + +### Common Rationalizations for Skipping Testing + +| Excuse | Reality | +|--------|---------| +| "Skill is obviously clear" | Clear to you ≠ clear to agents. Test it. | +| "It's just a reference" | References can have gaps. Test retrieval. | +| "Testing is overkill" | Untested skills always have issues. 15 min saves hours. | +| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. | +| "No time to test" | Deploying untested skill wastes more time fixing later. | diff --git a/project-governance/skills/snapshots/superpowers/_meta.json b/project-governance/skills/snapshots/superpowers/_meta.json new file mode 100644 index 00000000..2ec39b3c --- /dev/null +++ b/project-governance/skills/snapshots/superpowers/_meta.json @@ -0,0 +1,17 @@ +{ + "owner": "cutd", + "slug": "claw-superpowers", + "displayName": "claw-superpowers", + "latest": { + "version": "1.0.1", + "publishedAt": 1773111136740, + "commit": "https://github.com/openclaw/skills/commit/720aedbd618f70e5d23de7b68f9c0b45a3d7aa55" + }, + "history": [ + { + "version": "1.0.0", + "publishedAt": 1772673651563, + "commit": "https://github.com/openclaw/skills/commit/fa7462f557f358244a2ed1675ec8148ee853ff2c" + } + ] +} diff --git a/project-governance/skills/sources.json b/project-governance/skills/sources.json new file mode 100644 index 00000000..97619b08 --- /dev/null +++ b/project-governance/skills/sources.json @@ -0,0 +1,22 @@ +{ + "skills": [ + { + "name": "skill-vetter", + "source_url": "https://github.com/openclaw/skills/tree/HEAD/skills/spclaudehome/skill-vetter", + "installed_path": "C:/Users/afree/.codex/skills/skill-vetter", + "snapshot_path": "D:/Document Cleaning/project-governance/skills/snapshots/skill-vetter" + }, + { + "name": "superpowers", + "source_url": "https://github.com/openclaw/skills/tree/HEAD/skills/cutd/claw-superpowers", + "installed_path": "C:/Users/afree/.codex/skills/superpowers", + "snapshot_path": "D:/Document Cleaning/project-governance/skills/snapshots/superpowers" + }, + { + "name": "frontend-design", + "source_url": "https://github.com/vadimcomanescu/codex-skills/tree/HEAD/skills/.curated/design/frontend-design", + "installed_path": "C:/Users/afree/.codex/skills/frontend-design", + "snapshot_path": "D:/Document Cleaning/project-governance/skills/snapshots/frontend-design" + } + ] +} diff --git a/project-governance/skills/vetting-report.md b/project-governance/skills/vetting-report.md new file mode 100644 index 00000000..ee655ade --- /dev/null +++ b/project-governance/skills/vetting-report.md @@ -0,0 +1,47 @@ +# Skill Vetting Report + +Review scope: local installed copies under `C:\Users\afree\.codex\skills`. + +## Verdict + +- `skill-vetter`: install approved +- `superpowers`: install approved +- `frontend-design`: install approved + +## skill-vetter + +- Source: `openclaw/skills` +- Files reviewed: `SKILL.md`, `_meta.json` +- Observed behavior: documentation only; no scripts, package installs, or network actions inside the skill body +- Scope: guidance for reviewing third-party skills before installation +- Risk level: Low + +## superpowers + +- Source: `openclaw/skills` +- Files reviewed: `SKILL.md`, `_meta.json` +- Observed behavior: process and methodology guidance only; no executable scripts bundled +- Scope: workflow discipline for planning, execution, testing, debugging, and review +- Risk level: Low + +## frontend-design + +- Source: `vadimcomanescu/codex-skills` +- Files reviewed: `SKILL.md`, `LICENSE.txt`, `references/*`, `assets/*` +- Observed behavior: design guidance plus static starter assets; no credential access, no package install logic, no hidden network calls +- Scope: frontend design direction, tokens, layout, accessibility, and starter templates +- Risk level: Low + +## Red-Flag Check + +The following high-risk patterns were not found in the reviewed local copies: + +- hidden credential access +- external data exfiltration logic +- obfuscated code +- shell commands with elevated permissions +- writes outside intended skill folder + +## Operational Rule + +Any additional external skill introduced to this repo must be reviewed with `skill-vetter` first and then recorded in this folder. diff --git a/project-governance/workflow/DEVELOPMENT-WORKFLOW.md b/project-governance/workflow/DEVELOPMENT-WORKFLOW.md new file mode 100644 index 00000000..4aeef6c8 --- /dev/null +++ b/project-governance/workflow/DEVELOPMENT-WORKFLOW.md @@ -0,0 +1,32 @@ +# Development Workflow + +This project keeps workflow governance separate from product code. + +## Folder Split + +- Application code: `backend/`, `frontend/` +- Governance and AI workflow: `project-governance/` + +## Mandatory Skill Order + +1. `skill-vetter` + - Use before installing any new third-party skill or automation helper. +2. `superpowers` + - Use for brainstorming, planning, execution, test verification, debugging, and review. +3. `frontend-design` + - Use for any page, component, layout, token, or visual interaction change. + +## Default Delivery Flow + +1. Brainstorm the task and identify risks. +2. Write the implementation plan. +3. Implement in small verified steps. +4. Run tests/builds before claiming completion. +5. Review the result and note any remaining risk. + +## Project-Specific Rules + +- Do not mix skill governance files into `backend/` or `frontend/`. +- Keep required skill references in `project-governance/skills/`. +- Keep deployment and runtime configuration in the repo root and service folders only. +- If a new dependency or external tool is introduced, record the reason in this governance area. diff --git a/project-governance/workflow/smoke-download-source.bin b/project-governance/workflow/smoke-download-source.bin new file mode 100644 index 0000000000000000000000000000000000000000..6998751ac54ef75923d6a9a34f5f453602204943 GIT binary patch literal 9728 zcmeI2OKg-?6vyw^PD`hSQd+18C?92{JW6Rn-Y8RAUWL-qBB&MWw9^;Rnc9|DqKQ#N z4Vu)rkQfqUf{BU7RCMcO<<97a1+H*u;sT8>SU~;#zi+;F80d7E01=qm{O6wU-gD2n z=iK+b{q>g_S3doE&hI86Y&6;C#;D)q#-&@(Mcy|=7PQiCjE;_a$&i`w0D0hgtgdQ9 zAB~s;)aFw_9`J*FPynWaX`m2H2P!io7C%5HXQ~?Kfo2osZ^+nYtBDW~m{YW9>Y$1jRF`t%#W8v*@iI^WmV-*L0#t!&uoA2SPlMH94Ok1-f%RYm z*a$X(XTY;yGYEnjum#kDI-4^{xJx9WbGQsScQ>0juN!{T9>&)Q7e# zHI4PzW-q9%pKbbf_OGh4_cdgfW zDHyZfW?UbmKAp765^|<7Z=~jnN=II^rSb1~G$zW*VgB*-=P)j%zunUKoNi8^`~K|5 zt()-w>EmyAR&*zp&1c^7dV|`-PkZ>WdnWCXk39u6`%EMm^BeHF+aPD$XrpwIjgt0G zqQ8aK9!f#H3R#*g6_mil0h_y_+Fm-$7??clqjCCh+8~X)hxi1s7H@TIHQ8$9xWhNO ztQNXYpJ}J0hQq2wscEmFv3g@es25FVH1AIm)a}}xW)6*YEt`o_4c}|JC_R}?wYg}T zM2oUD#D_qLOARSoz$0<>&K@tfLHt?Knmmgf{L9O*pU+QM4eCjNU^pDhen zEAM?)v4$TQ2zzqzdXy$ZCpC|~bAh@P3CZXQ{m3S~L1G9>{p$|Kou=4geh-0dzFg{jtrF;3%|?E4`qblooQM<_M|o zy@l=~3i#V+df?H4wu@M$?AUidhlx)1Eg>fkI~=;ju}QI=G~MRdK-yh;Fiy)5rKP1Z zrbUvw;dMD(o$i70IGpZrRJSU}&?%WA_D&UicR)vs%QHyb^riGL)CuT#URkV~hLI>+ zR0q|!8^{x?j}3a9^Z|55`15?^-iI9LyMuhyyV230+HIhm4qB3YlAI>z$kk7ZN-1|I zlBBO2?)by@alVcsQ-@mbc1JtHyBOH#>Fy&F9!U>a-hJ1lC&nk zF?6HZRAquqJfbvZnfW7cRN5my)hrl^_{zY-;fOB)R+3*m95z+`a@Z=q7OymgRr;9d z{Hp^@)}@~>ov)l*^x;RGe=DwiRYzJ*LYm%G^iE;LP(-Y7KTFb!8O+>fsA_^Zi%;OngJSoyXKBK|RC}EN5lw zW8H1!viPu@cn815w3gb73kdfvKE<-0CJVhrfceFWm~M=vQ6eRmUdeushT4P0t8=``1pQi=Bo0V&?4`T;ALLE=IrJJ#-h7s{Tdr zei;*Xz|j@v?e*q;WGs8qXiggTFF~qz@04?k<~#Gpx-|5+qu;ZCQUg<9a2h`LlLEW* I-t6)H2R5imA^-pY literal 0 HcmV?d00001 diff --git a/project-governance/workflow/smoke-download.md b/project-governance/workflow/smoke-download.md new file mode 100644 index 00000000..d00f77f2 --- /dev/null +++ b/project-governance/workflow/smoke-download.md @@ -0,0 +1,2 @@ +smoke-input + diff --git a/project-governance/workflow/smoke-input.doc b/project-governance/workflow/smoke-input.doc new file mode 100644 index 0000000000000000000000000000000000000000..6998751ac54ef75923d6a9a34f5f453602204943 GIT binary patch literal 9728 zcmeI2OKg-?6vyw^PD`hSQd+18C?92{JW6Rn-Y8RAUWL-qBB&MWw9^;Rnc9|DqKQ#N z4Vu)rkQfqUf{BU7RCMcO<<97a1+H*u;sT8>SU~;#zi+;F80d7E01=qm{O6wU-gD2n z=iK+b{q>g_S3doE&hI86Y&6;C#;D)q#-&@(Mcy|=7PQiCjE;_a$&i`w0D0hgtgdQ9 zAB~s;)aFw_9`J*FPynWaX`m2H2P!io7C%5HXQ~?Kfo2osZ^+nYtBDW~m{YW9>Y$1jRF`t%#W8v*@iI^WmV-*L0#t!&uoA2SPlMH94Ok1-f%RYm z*a$X(XTY;yGYEnjum#kDI-4^{xJx9WbGQsScQ>0juN!{T9>&)Q7e# zHI4PzW-q9%pKbbf_OGh4_cdgfW zDHyZfW?UbmKAp765^|<7Z=~jnN=II^rSb1~G$zW*VgB*-=P)j%zunUKoNi8^`~K|5 zt()-w>EmyAR&*zp&1c^7dV|`-PkZ>WdnWCXk39u6`%EMm^BeHF+aPD$XrpwIjgt0G zqQ8aK9!f#H3R#*g6_mil0h_y_+Fm-$7??clqjCCh+8~X)hxi1s7H@TIHQ8$9xWhNO ztQNXYpJ}J0hQq2wscEmFv3g@es25FVH1AIm)a}}xW)6*YEt`o_4c}|JC_R}?wYg}T zM2oUD#D_qLOARSoz$0<>&K@tfLHt?Knmmgf{L9O*pU+QM4eCjNU^pDhen zEAM?)v4$TQ2zzqzdXy$ZCpC|~bAh@P3CZXQ{m3S~L1G9>{p$|Kou=4geh-0dzFg{jtrF;3%|?E4`qblooQM<_M|o zy@l=~3i#V+df?H4wu@M$?AUidhlx)1Eg>fkI~=;ju}QI=G~MRdK-yh;Fiy)5rKP1Z zrbUvw;dMD(o$i70IGpZrRJSU}&?%WA_D&UicR)vs%QHyb^riGL)CuT#URkV~hLI>+ zR0q|!8^{x?j}3a9^Z|55`15?^-iI9LyMuhyyV230+HIhm4qB3YlAI>z$kk7ZN-1|I zlBBO2?)by@alVcsQ-@mbc1JtHyBOH#>Fy&F9!U>a-hJ1lC&nk zF?6HZRAquqJfbvZnfW7cRN5my)hrl^_{zY-;fOB)R+3*m95z+`a@Z=q7OymgRr;9d z{Hp^@)}@~>ov)l*^x;RGe=DwiRYzJ*LYm%G^iE;LP(-Y7KTFb!8O+>fsA_^Zi%;OngJSoyXKBK|RC}EN5lw zW8H1!viPu@cn815w3gb73kdfvKE<-0CJVhrfceFWm~M=vQ6eRmUdeushT4P0t8=``1pQi=Bo0V&?4`T;ALLE=IrJJ#-h7s{Tdr zei;*Xz|j@v?e*q;WGs8qXiggTFF~qz@04?k<~#Gpx-|5+qu;ZCQUg<9a2h`LlLEW* I-t6)H2R5imA^-pY literal 0 HcmV?d00001 diff --git a/project-governance/workflow/smoke-input.docx b/project-governance/workflow/smoke-input.docx new file mode 100644 index 0000000000000000000000000000000000000000..38fe52fb32ca8e210a5d493b894156b496db833b GIT binary patch literal 5232 zcmaJ_1z1xJ_XnhN)KHL+91Rjqx<-RYNQ1!W7$q$r-6h@KB?2PSBLpNysDOZg0-}I~ zbbOod_x|Pe|Gl0)yU(6IJNNFM^NVw?hRQWe3N&0?T(tYKzD8(Qf)x4L6Xpu#g~BWz zIa)fo^LRNrl<3Sk&G8XFUev|)cUo!Lj2g9>2nW)f)N@NUkZ3r}A}VP>B2EWCiu{xs zJgzq!^fk)ue!n?X2;0t$1sZncXXmiYKr?acLpf7wtOw(#*Y>jHFq4{-XZ6!rL~#e_ z&)|+(X|*)8*jCMe-2K&_Vg9JUKd_wTN|{9c;zXLhL0e&Nhr0`;7Y3C0r4Xm;^P` z1OumHNtvp}@B=L46$L@JBnhUSik)YhxsuUM6Hy*HQ`aiKZ9J|v5$t$Ovw%=Ye|#nx z7%d*izB@20l59WnE-@nlbdS&c_L|{KkIy^?i{ild87!NE5yFeg;wr5WkDOxT7LMul z^aI20;h?77E$WsL0Bu_WCHhvdKhOe5f>Z2IZt-&eVfgOR(7RPZ`ntxJcMOhPErMHk zz4#b?QXA`LK2V#E*>VPsKJ)iJn7pLQ-CUs*xS9l;`2JzUk=Jc^$vDgd%V`z(F<*jD zwVTLe->Iis7dm^Shglc8*KB%vUqq4#0&w;BC~%o0%<7-f?xD4Oo;*=`wq1kurmvlI z>A1-gk?)D_x?_W9_bn{*V{K)FFD=jmJ!T~Ay?QATU* zHH{5JiwEM>;7rf%B)@`QlE74+;_9oF$G<{8LfJm5)Oj)74o zuYJO9bb4=lr|KS>Z*6Kirc*r9&LK!pz)HMDo+C25U{J?(YfO(z=1ocdqp33Nnp!b~ zt?8IeH#@O%s?xVrMYT)S=CQ$|Gw_%WZNNG)e8+EZM{}@d#6v)8;Ry49wN-~t&USQNg5-YeZ zeM(qF#_q!^ANNOTPCk3kpaAt!h~Y}yNy=#44Ewo$S`T%dEOujqCAYqRYJ|hJ++s~k_CTboCVKQ?_=zDuJvxMzhfzyPUzP7kks$E66YCjm5 zBPI{AeD&zO^4zHe;a(t2fUcXSBb-?~K32NRX07wIY=2pfov5&u<$=U@6%VDw%?E6P z_T>#>eZUKfri!Zk*#pY&b@lzUu{!U}RJCXdm~e|fRq$a92zGK3l(}{4-}`((0P^KZ zZpXGMW*Jjqd_zR51IFHU)(AQ4#AHoU$zke|+JtZ9Hi%a-avvtPrxY^7pTdVHdN(>-K`Y$q2u91;QB_bReSC5!ZR~&^|3z&qygx$V}JJOLKhC;Bvr9d+*w@(>!KJ zmJ(sVz@3&4$0tA@-XAP9=Z@(ax+CYp{VVL1JRP~jqmpN$rF3$K2)<}7xKS?MnaC+W zSd=a|8;;!umbgwwODy@gW7112i0X644`tt5pj7yfNytQWo$ z+|rSTL9Ri2yw7)k66SFkY2H4PFwyvbBFz6;ft#hfyRDP;Ps)@eji|%<03q9AkWZqI z4E#e1ODS&xsMNV-mYW|5$A)gkep8e6_5sdvkSZGaJQo)@_2wE&qhGKTjTzJgO}i&m z5e63wg*jH3yp2!u@%?hstC>)W>$u9{AQvb3;F|C61jG_Sx{&8?lY0TmU($3*6emMxrVx zhl!0UYONJ+h?JH+o_mOvO2?LC5so7(5CPL%fr9&qj)7i!HN+#mlwB%o@QQgoYwt@{ zN{+-ZzrkP^#qderwGpS)pKg2O-m9+D~K9b}C zE1cuHjWL~NsEW7M(MgOf6QCsNNUper2^|g18(HOlmn5>kCCLirhrJBTH zryf2450TpW+0)KLeoB%(i=-Fu?R_;FJQ8;@R^xm$f%JGs_Q& z=7QN`Yd;p5_1^%8mUzqs1=O12XpMptb(MpO@%=HEqmSWStCX!$Tuq`w7TsR~nMSyp zLV8NF4qYWip$kI^9sZn*Ck;F0fuIUQrha{4(g$_}W4AA;Z&Y*Ce8id_4I;>iz+sY| z4YZpF+=;$eNWaz(+FygTjt22O<8nuW5*!HpubM42W@uf}|oSYAazuFE{!&g-?Y85SEqdce9Pz1huFIOx(NnF< zzy`gbZGnmj98ds54!z(d2C5Z)4#yA`WGk34|I`Y~zgyvMW9ewg`}4?;>c)JE8Vou6 zgl(Tv25nU>x8O}MsPl6Xc!26h~4oUrqaim417BMUj&tKYTVjcn&r7w z5b8Fa#6R3l^G!{^;J{bkmI4gR%r3z;X{%0h5XpFxfl**f4)bU0cyqhkMQfKWbat8% zn+2TL$}MNfj>z|mGsRGRx5g}~BnEl^G+5>N%B{W3#{l2pn!tTPj(_#wA$`fMF$QuG zJQB;Vl&{bxh+cAu5xqnEVs?_b(D;_dRlFSyZLK4DX$FC@tn{ItyWAx16JTsRfB41z z3Ob2PjQIJ{&?50sXqoTH3tfNVkH_=0ogb74D%18z{iz}Em#%3m7LXL(iL*Wlf|i_# zMU7dJavc!)m+0C1ZFp^pz^5{qu;NQ*d>91Zjg_-*>6u}FaHEewQ&M8N$=jSCB6dQ- zzJzr>di2hoyC4^-0Y8mj$o4%b&TI$W;AS4A!DLx^{f*%jyAUa1ZL{Vuuvm2P_Zdk%xDjT&B6Ecx_>$0lgp-x*r*tw>TtxU}* zJ9@_H7`i7bp_^s(Tp;%bMUT>>@MLG3%)_VtSwqzUchfCj&-04uPHs;#7QG6fx3b9C z+}pgo+j-ujw+0)=rayRYeNK)7*g^eH5FL`|2;4sb?B?G9Gj+9eaQnx2&4c=;MspY+ z$@;caO0#X@ny3iDAB;h|74(3~&1-Ya%vI})G}?_p5#e;!!lDAI!p6p}sX2(_ej9Wp zifghps)%*vE{Vk$s`?@MFT{pQOObUnU-jQ3Or+GHY1zIy7Hp59TpN7sv0s_7);XL? zM27H>nd8d)+U=pD6EV|$wJmk|p+e)ci9mir_hWE{%;@kvqs zwX;{}P{q>;o1xDIeV##7KRA2c$B7d_XO^9zYqNrLM2aN($6*IdU{v;eMb0{7qteC*uFk7 zN&PG|9jM9&btisftjsK#7*wWs$EyhwS6%uEcJPx25J-SNW*vOyn#x+p6d4>!QbYBzwp7E zec9}LhfO2fbX3gxd!Hx?TH-`!6#*}_-hfvi!*KOc-_4;=Mb{2S!fpDl9p?bDXY!Hw z#0SsLUVPp9Y3X*r7$*=?DX7=2#cSKYPMb#%<2dLw$9$OXbhfVFQQ5A#f0RCCMv_I_ZK91IVkRq zHGL{VjOSkiH=29yI|>7>>bf9L@{NO=7v@;{)g8>1d5A4(If66Twq(Ju`Wx6R9|t40 z@fru%Z()VC<8Vv!e8Y+u?fpD@NyQNh9$kC8*^NzC#I5S_iSBxz?hB#Z_?pbX#Dosa zeZ=g2ye&B7ee{O4m$=eL!T2h0^yDc?Ny)LxytR%y1USF%ZWhf8FpJ4l9KEY_(pvlc zHf;pxSXPI8ogjA&nqbL_e^xDBx~Xowao*3bf*9yH)^XHD4j$ z|8Cy|$ZGz@=D!%6q^5FB8tD}0l(Jj%4xACMM-LcfV2nR-LNdN>jgR68*w$PwNaMF^ zMCA{(dGCF{IpH{Zk*}T|9W4#7w3T+@L$vbQdCiIQ(m$N!ZPk@Xm{QI#;;38*DKsNf zijU}1{Z=8!?^2$1%j%xyfS5Vs^Rh&j`R2p)fZO?b{L^pkUK_r`XgXCqyCduaY+w#y zwK6F+s(TLRp;Y&VA|4ibSGXM838oNw8QYxu7JvyyziSC9j7ise@92Z|nqQ=VN(|*a zFKq>3e#3184hWOw=#fJB49$KXsv_&-=u9)n`xXBqzQ~ckFqB0OGsp)ArrO@lmTtx< zh&5@qqae0$N|E@E!(})Spgi{^k5nWXhwp$zh`HI)ROR#_`)Lxo3?rgJu3`IBbS};B zQF#@VM8d`%=#V?2haqoJqW1D3Z`QzmSWW6vKR0&(Sx;vDLqj>wVebUPa>(oIYqBXl zCk71Mj|X!SwhJ-+g|dv@Y>9%pDT=TSR}VEJj6(pk}m3+Es#{y_6%6Ff0_AKL4{XI5pLPWF*1 zT<-=rEcH&u%s{-|s3G31ajo*I>Z&Q3 ztS@?TfdlwGpS2oWR}KOdLoRWhHR)mjd0*w*9ylKp=IqF9va*R^hf5!iN)bo4#)l~ttLH~+bBocn6|JtX2Prf<@|MS`e$W{HXH literal 0 HcmV?d00001 diff --git a/project-governance/workflow/smoke-input.txt b/project-governance/workflow/smoke-input.txt new file mode 100644 index 00000000..79302b05 --- /dev/null +++ b/project-governance/workflow/smoke-input.txt @@ -0,0 +1,6 @@ +Document Cleaning Smoke Test + +This file is prepared for a real local smoke test. +The goal is to verify upload, conversion, download, and delete against the running service. +Owner: Codex +Purpose: Integration validation diff --git a/start-local-backend.ps1 b/start-local-backend.ps1 new file mode 100644 index 00000000..334bda49 --- /dev/null +++ b/start-local-backend.ps1 @@ -0,0 +1,22 @@ +$ErrorActionPreference = 'Stop' + +$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$pythonExe = Join-Path $projectRoot 'python\python.exe' +$backendDir = Join-Path $projectRoot 'backend' + +if (-not (Test-Path $pythonExe)) { + throw "Project Python not found: $pythonExe" +} + +if (-not (Test-Path (Join-Path $backendDir '.env'))) { + throw "Backend config not found: $backendDir\.env" +} + +Push-Location $backendDir +try { + & $pythonExe -m alembic upgrade head + & $pythonExe -m uvicorn app.main:app --host 127.0.0.1 --port 8000 +} +finally { + Pop-Location +} diff --git a/start-local-dev.ps1 b/start-local-dev.ps1 new file mode 100644 index 00000000..a398f17e --- /dev/null +++ b/start-local-dev.ps1 @@ -0,0 +1,37 @@ +$ErrorActionPreference = 'Stop' + +$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$backendScript = Join-Path $projectRoot 'start-local-backend.ps1' +$frontendScript = Join-Path $projectRoot 'start-local-frontend.ps1' +$logDir = Join-Path $projectRoot 'tmp_run' + +New-Item -ItemType Directory -Path $logDir -Force | Out-Null + +$backendOut = Join-Path $logDir 'backend.out.log' +$backendErr = Join-Path $logDir 'backend.err.log' +$frontendOut = Join-Path $logDir 'frontend.out.log' +$frontendErr = Join-Path $logDir 'frontend.err.log' + +$backend = Start-Process -FilePath 'powershell.exe' ` + -ArgumentList '-ExecutionPolicy', 'Bypass', '-File', $backendScript ` + -WorkingDirectory $projectRoot ` + -RedirectStandardOutput $backendOut ` + -RedirectStandardError $backendErr ` + -PassThru + +Start-Sleep -Seconds 3 + +$frontend = Start-Process -FilePath 'powershell.exe' ` + -ArgumentList '-ExecutionPolicy', 'Bypass', '-File', $frontendScript ` + -WorkingDirectory $projectRoot ` + -RedirectStandardOutput $frontendOut ` + -RedirectStandardError $frontendErr ` + -PassThru + +Start-Sleep -Seconds 3 + +Write-Host "Backend PID: $($backend.Id)" +Write-Host "Frontend PID: $($frontend.Id)" +Write-Host 'Backend URL: http://127.0.0.1:8000' +Write-Host 'Frontend URL: http://127.0.0.1:5174' +Write-Host "Logs: $logDir" diff --git a/start-local-frontend.ps1 b/start-local-frontend.ps1 new file mode 100644 index 00000000..048e253a --- /dev/null +++ b/start-local-frontend.ps1 @@ -0,0 +1,16 @@ +$ErrorActionPreference = 'Stop' + +$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path +$frontendDir = Join-Path $projectRoot 'frontend' + +if (-not (Test-Path (Join-Path $frontendDir 'package.json'))) { + throw "Frontend package.json not found: $frontendDir\package.json" +} + +Push-Location $frontendDir +try { + npm run dev -- --host 127.0.0.1 --port 5174 +} +finally { + Pop-Location +}