feat: Face JSON v2 schema - add schema_version, bbox x2/y2/center, keep embeddings, update clustering

This commit is contained in:
Accusys
2026-11-02 14:34:02 +08:00
parent 2fca49b120
commit 5d18183d82
566 changed files with 321788 additions and 1662 deletions
@@ -1,3 +1,11 @@
---
title: people api API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
# People API
**Version**: 2.1
@@ -398,3 +406,11 @@ registered → scanning → keyword_ready → semantic_ready
| `face_mgmt_ready` | Face, FaceCluster | trace_profiles (People Search + Face Management) |
| `agent_ready` | face_mgmt_ready + TKG Edges | tkg_edges |
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
+174
View File
@@ -0,0 +1,174 @@
---
title: Momentry Core Documentation
version: 1.3.5
date: 2026-10-25
author: Core Team
status: Active
---
# Momentry Core Documentation
歡迎來到 Momentry Core API 文檔系統。本系統提供完整的 API 和 CLI 文檔。
---
## API Documentation
### Core APIs (001-099)
| Module | Description | Status |
|--------|-------------|--------|
| <a href="#" onclick="loadDoc('001_Auth_v1.3.5'); return false;"><strong>001 Auth</strong></a> | 認證 - JWT、Session Cookie、API Key | ✅ Active |
| <a href="#" onclick="loadDoc('002_Health_v1.3.5'); return false;"><strong>002 Health</strong></a> | 健康檢查端點 | ✅ Active |
| <a href="#" onclick="loadDoc('011_Register_v1.3.5'); return false;"><strong>011 Register</strong></a> | 文件註冊與處理 | ✅ Active |
| <a href="#" onclick="loadDoc('012_Lookup_v1.3.5'); return false;"><strong>012 Lookup</strong></a> | 文件查詢 | ✅ Active |
| <a href="#" onclick="loadDoc('021_Process_v1.3.5'); return false;"><strong>021 Process</strong></a> | 文件處理流程 | ✅ Active |
| <a href="#" onclick="loadDoc('022_Pipeline_v1.3.5'); return false;"><strong>022 Pipeline</strong></a> | 處理管道配置 | ✅ Active |
| <a href="#" onclick="loadDoc('023_Progress_v1.3.5'); return false;"><strong>023 Progress</strong></a> | 處理進度查詢 | ✅ Active |
| <a href="#" onclick="loadDoc('024_JobManagement_v1.3.5'); return false;"><strong>024 Job Management</strong></a> | 作業管理 | ✅ Active |
| <a href="#" onclick="loadDoc('025_Checkin_v1.3.5'); return false;"><strong>025 Checkin</strong></a> | 服務檢入 | ✅ Active |
| <a href="#" onclick="loadDoc('031_Search_v1.3.5'); return false;"><strong>031 Search</strong></a> | 文件搜索(關鍵字、BM25) | ✅ Active |
| <a href="#" onclick="loadDoc('032_VLMSearch_v1.3.5'); return false;"><strong>032 VLM Search</strong></a> | 視覺語言模型搜索 | ✅ Active |
| <a href="#" onclick="loadDoc('033_SceneVLMStats_v1.3.5'); return false;"><strong>033 Scene VLM Stats</strong></a> | 場景 VLM 統計 | ✅ Active |
| <a href="#" onclick="loadDoc('041_Identity_v1.3.5'); return false;"><strong>041 Identity</strong></a> | 身份管理 | ✅ Active |
| <a href="#" onclick="loadDoc('042_IdentityAgent_v1.3.5'); return false;"><strong>042 Identity Agent</strong></a> | 智能身份綁定 | ✅ Active |
| <a href="#" onclick="loadDoc('043_IdentityHistory_v1.3.5'); return false;"><strong>043 Identity History</strong></a> | 身份歷史記錄 | ✅ Active |
| <a href="#" onclick="loadDoc('044_FaceFilter_v1.3.5'); return false;"><strong>044 Face Filter</strong></a> | 人臉過濾 | ✅ Active |
| <a href="#" onclick="loadDoc('051_Media_v1.3.5'); return false;"><strong>051 Media</strong></a> | 媒體資源管理 | ✅ Active |
| <a href="#" onclick="loadDoc('052_Profile_v1.3.5'); return false;"><strong>052 Profile</strong></a> | 個人資料管理 | ✅ Active |
| <a href="#" onclick="loadDoc('053_PoseAppearance_v1.3.5'); return false;"><strong>053 Pose Appearance</strong></a> | 姿態與外觀分析 | ✅ Active |
| <a href="#" onclick="loadDoc('054_TraceThumbnail_v1.3.5'); return false;"><strong>054 Trace Thumbnail</strong></a> | 軌跡縮略圖 | ✅ Active |
| <a href="#" onclick="loadDoc('061_TMDB_v1.3.5'); return false;"><strong>061 TMDB</strong></a> | TMDb 電影數據庫集成 | ✅ Active |
| <a href="#" onclick="loadDoc('062_Agent_v1.3.5'); return false;"><strong>062 Agent</strong></a> | AI 代理系統 | ✅ Active |
| <a href="#" onclick="loadDoc('063_TKG_v1.3.5'); return false;"><strong>063 TKG</strong></a> | 時間知識圖譜 | ✅ Active |
| <a href="#" onclick="loadDoc('064_TraceAgent_v1.3.5'); return false;"><strong>064 Trace Agent</strong></a> | 軌跡代理 | ✅ Active |
| <a href="#" onclick="loadDoc('065_ClusterAgent_v1.3.5'); return false;"><strong>065 Cluster Agent</strong></a> | 聚類代理 | ✅ Active |
| <a href="#" onclick="loadDoc('071_ErrorCodes_v1.3.5'); return false;"><strong>071 Error Codes</strong></a> | 錯誤代碼參考 | ✅ Active |
| <a href="#" onclick="loadDoc('072_Config_v1.3.5'); return false;"><strong>072 Config</strong></a> | 配置管理 | ✅ Active |
| <a href="#" onclick="loadDoc('073_Workspace_v1.3.5'); return false;"><strong>073 Workspace</strong></a> | 工作空間管理 | ✅ Active |
| <a href="#" onclick="loadDoc('074_ServiceManagement_v1.3.5'); return false;"><strong>074 Service Management</strong></a> | 服務管理 | ✅ Active |
| <a href="#" onclick="loadDoc('075_Monitor_v1.3.5'); return false;"><strong>075 Monitor</strong></a> | 監控端點 | ✅ Active |
| <a href="#" onclick="loadDoc('076_AdminConfig_v1.3.5'); return false;"><strong>076 Admin Config</strong></a> | 管理員配置 | ✅ Active |
| <a href="#" onclick="loadDoc('077_Docs_v1.3.5'); return false;"><strong>077 Docs</strong></a> | 文檔系統 API | ✅ Active |
| <a href="#" onclick="loadDoc('078_MarkbaseCompat_v1.3.5'); return false;"><strong>078 Markbase Compat</strong></a> | Markbase 兼容性 | ✅ Active |
| <a href="#" onclick="loadDoc('081_CLIP_v1.3.5'); return false;"><strong>081 CLIP</strong></a> | CLIP 向量化 | ✅ Active |
| <a href="#" onclick="loadDoc('082_Billing_v1.3.5'); return false;"><strong>082 Billing</strong></a> | 計費系統 | ✅ Active |
| <a href="#" onclick="loadDoc('099_MarkbaseTeam'); return false;"><strong>099 Markbase Team</strong></a> | 儲存與協議層 (SMB/SFTP/WebDAV/S3) | ✅ Active |
---
## CLI Documentation (100-199)
Momentry CLI 提供完整的命令行工具集。
### Quick Start
```bash
# 註冊視頻文件
momentry register /path/to/video.mp4
# 處理視頻文件
momentry process --file-uuid <uuid>
# 搜索文件
momentry search --query "關鍵字"
# 查詢文件信息
momentry lookup --file-uuid <uuid>
```
### CLI Commands
| Command | Description | Status |
|---------|-------------|--------|
| <a href="#" onclick="loadDoc('101_CLI_Register_v1.3.5'); return false;"><strong>101 CLI Register</strong></a> | 文件註冊命令 | ✅ Active |
| <a href="#" onclick="loadDoc('102_CLI_Process_v1.3.5'); return false;"><strong>102 CLI Process</strong></a> | 處理流程命令 | ✅ Active |
| <a href="#" onclick="loadDoc('103_CLI_Chunk_v1.3.5'); return false;"><strong>103 CLI Chunk</strong></a> | 分塊命令 | ✅ Active |
| <a href="#" onclick="loadDoc('104_CLI_StoreAsrx_v1.3.5'); return false;"><strong>104 CLI StoreAsrx</strong></a> | ASR 存儲命令 | ✅ Active |
| <a href="#" onclick="loadDoc('105_CLI_Story_v1.3.5'); return false;"><strong>105 CLI Story</strong></a> | 故事生成命令 | ✅ Active |
| <a href="#" onclick="loadDoc('106_CLI_Detect_v1.3.5'); return false;"><strong>106 CLI Detect</strong></a> | 檢測命令 | ✅ Active |
| <a href="#" onclick="loadDoc('107_CLI_Vision_v1.3.5'); return false;"><strong>107 CLI Vision</strong></a> | 視覺處理命令 | ✅ Active |
| <a href="#" onclick="loadDoc('108_CLI_Vectorize_v1.3.5'); return false;"><strong>108 CLI Vectorize</strong></a> | 向量化命令 | ✅ Active |
| <a href="#" onclick="loadDoc('109_CLI_Phase1_v1.3.5'); return false;"><strong>109 CLI Phase1</strong></a> | Phase 1 完整流程 | ✅ Active |
| <a href="#" onclick="loadDoc('110_CLI_Complete_v1.3.5'); return false;"><strong>110 CLI Complete</strong></a> | 完整處理流程 | ✅ Active |
| <a href="#" onclick="loadDoc('111_CLI_Play_v1.3.5'); return false;"><strong>111 CLI Play</strong></a> | 播放器命令 | ✅ Active |
| <a href="#" onclick="loadDoc('112_CLI_Watch_v1.3.5'); return false;"><strong>112 CLI Watch</strong></a> | 監控命令 | ✅ Active |
| <a href="#" onclick="loadDoc('113_CLI_System_v1.3.5'); return false;"><strong>113 CLI System</strong></a> | 系統管理命令 | ✅ Active |
| <a href="#" onclick="loadDoc('114_CLI_Server_v1.3.5'); return false;"><strong>114 CLI Server</strong></a> | 服務器命令 | ✅ Active |
| <a href="#" onclick="loadDoc('115_CLI_Worker_v1.3.5'); return false;"><strong>115 CLI Worker</strong></a> | 工作進程命令 | ✅ Active |
| <a href="#" onclick="loadDoc('116_CLI_Query_v1.3.5'); return false;"><strong>116 CLI Query</strong></a> | 查詢命令 | ✅ Active |
| <a href="#" onclick="loadDoc('117_CLI_Lookup_v1.3.5'); return false;"><strong>117 CLI Lookup</strong></a> | 查找命令 | ✅ Active |
| <a href="#" onclick="loadDoc('118_CLI_Resolve_v1.3.5'); return false;"><strong>118 CLI Resolve</strong></a> | 解析命令 | ✅ Active |
| <a href="#" onclick="loadDoc('119_CLI_Thumbnails_v1.3.5'); return false;"><strong>119 CLI Thumbnails</strong></a> | 縮略圖命令 | ✅ Active |
| <a href="#" onclick="loadDoc('120_CLI_Status_v1.3.5'); return false;"><strong>120 CLI Status</strong></a> | 狀態查詢命令 | ✅ Active |
| <a href="#" onclick="loadDoc('121_CLI_Backup_v1.3.5'); return false;"><strong>121 CLI Backup</strong></a> | 備份命令 | ✅ Active |
| <a href="#" onclick="loadDoc('122_CLI_ApiKey_v1.3.5'); return false;"><strong>122 CLI ApiKey</strong></a> | API Key 管理命令 | ✅ Active |
| <a href="#" onclick="loadDoc('123_CLI_Gitea_v1.3.5'); return false;"><strong>123 CLI Gitea</strong></a> | Gitea 同步命令 | ✅ Active |
| <a href="#" onclick="loadDoc('124_CLI_Agent_v1.3.5'); return false;"><strong>124 CLI Agent</strong></a> | 代理命令 | ✅ Active |
---
## Studio Team Guides (200-299)
專為 Studio 團隊提供的指南文檔。
| Guide | Description | Status |
|-------|-------------|--------|
| <a href="#" onclick="loadDoc('201_StudioTeamGuide_v1.3.5'); return false;"><strong>201 Studio Team Guide</strong></a> | Studio 團隊完整指南 | ✅ Active |
| <a href="#" onclick="loadDoc('202_StudioPipelineChanges_v1.3.5'); return false;"><strong>202 Studio Pipeline Changes</strong></a> | 管道變更記錄 | ✅ Active |
| <a href="#" onclick="loadDoc('203_StudioFaceGroupFix_v1.3.5'); return false;"><strong>203 Studio Face Group Fix</strong></a> | 人臉分組修復 | ✅ Active |
| <a href="#" onclick="loadDoc('204_StudioTraceProfileBug_v1.3.5'); return false;"><strong>204 Studio Trace Profile Bug</strong></a> | 軌跡資料 Bug | ✅ Active |
---
## Deprecated APIs (000)
已廢棄的 API 端點,僅供參考。
| Module | Description | Status |
|--------|-------------|--------|
| <a href="#" onclick="loadDoc('000_PeopleAPI_v1.0.0'); return false;"><strong>000 People API</strong></a> | person_id 已廢棄(V3.x) | ⚠️ Deprecated |
---
## Work in Progress (900-999)
正在開發中的文檔。
| Module | Description | Status |
|--------|-------------|--------|
| <a href="#" onclick="loadDoc('990_Incomplete_v1.3.5'); return false;"><strong>990 Incomplete</strong></a> | 未完成的 API 端點列表 | 🚧 WIP |
---
## System Information
- **Core API Version**: 1.3.5
- **Documentation Version**: 2026-10-25-v2
- **Total Modules**: 45
- **API Endpoints**: 37
- **CLI Commands**: 24
- **Studio Guides**: 4
---
## Quick Links
- <a href="#" onclick="loadDoc('001_Auth_v1.3.5'); return false;">Authentication</a>
- <a href="#" onclick="loadDoc('011_Register_v1.3.5'); return false;">File Registration</a>
- <a href="#" onclick="loadDoc('031_Search_v1.3.5'); return false;">Search</a>
- <a href="#" onclick="loadDoc('041_Identity_v1.3.5'); return false;">Identity Management</a>
- <a href="#" onclick="loadDoc('101_CLI_Register_v1.3.5'); return false;">CLI Reference</a>
---
## Contact
- **Core Team**: 開發與維護 Core API (001-098)
- **Markbase Team**: 儲存與協議層實現 (099)
- **Studio Team**: 開發與維護前端應用 (200-299)
- **Documentation**: 本文檔系統由 Core Team 維護
---
*Last Updated: 2026-10-25*
@@ -1,3 +1,11 @@
---
title: Auth API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: auth -->
<!-- description: Authentication — login, logout, JWT, session cookie, API key -->
<!-- depends: -->
@@ -281,3 +289,11 @@ Protected Request
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: health API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: health -->
<!-- description: Health check endpoints -->
<!-- depends: 01_auth -->
@@ -188,3 +196,11 @@ curl -s "$API/health/consistency" -H "X-API-Key: $KEY" | jq '.checks[] | {check,
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: register API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: register -->
<!-- description: File registration — register, scan -->
<!-- depends: 01_auth -->
@@ -186,3 +194,11 @@ curl -s "$API/api/v1/files/scan?sort_by=status&page_size=5" -H "X-API-Key: $KEY"
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: lookup API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: lookup -->
<!-- description: File listing, lookup by name, file detail, faces, identities, JSON download, unregistration -->
<!-- depends: 01_auth, 03_register -->
@@ -418,3 +426,11 @@ curl -s -X POST "$API/api/v1/unregister" \
---
*Updated: 2026-06-20 — Added file listing, file detail, file identities, file faces, and JSON download endpoints*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: process API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: process -->
<!-- description: Processing pipeline — trigger, probe, progress, jobs -->
<!-- depends: 01_auth, 03_register -->
@@ -38,22 +46,18 @@ curl -s -X POST "$API/api/v1/file/$FILE_UUID/process" \
```json
{
"success": true,
"job_id": 42,
"file_uuid": "3a6c1865...",
"status": "processing",
"pids": [12345, 12346],
"message": "Processing triggered for video.mp4"
"message": "Processing triggered",
"file_uuid": "3a6c1865..."
}
```
| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Always true on 200 |
| `job_id` | integer | Monitor job ID (for job tracking) |
| `message` | string | Human-readable status message |
| `file_uuid` | string | 32-char hex UUID of the file |
| `status` | string | `"queued"` — file enters the FIFO queue |
| `pids` | integer[] | Process IDs of started processors (empty for queued) |
| `message` | string | Human-readable status |
**Note**: Processing runs asynchronously in the background. Use `/api/v1/job/:uuid` to track job status and `/api/v1/progress/:file_uuid` for real-time progress.
#### Error Responses
@@ -526,3 +530,11 @@ Phase 1 (`/phase1`) combines store-asrx + rule1 + vectorize into one call.
---
*Updated: 2026-06-23 — Added queued status, FIFO queue order, queue_position in job detail, frontend status mapping table*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: pipeline API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: pipeline -->
<!-- description: Pipeline processors, ingestion status, stats endpoints -->
<!-- depends: 01_auth -->
@@ -126,3 +134,11 @@ The following routes are defined in source code but are **NOT** currently mounte
---
*Updated: 2026-05-19 23:21:51*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: progress API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: progress -->
<!-- description: Real-time progress tracking for processing pipeline, TKG build, and identity agent -->
<!-- depends: 01_auth, 03_register, 05_process -->
@@ -543,3 +551,11 @@ curl -s "$API/api/v1/stats/file/$FILE_UUID" \
| `tmdb_matches` | integer | TMDb identity matches |
| `speaker_bindings` | integer | Speaker-to-identity bindings |
| `confirmations` | integer | Confirmed identity bindings |
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,279 @@
---
title: Job Management API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: job_management -->
<!-- description: Job pause/resume and status management -->
<!-- depends: 01_auth, 05_process -->
## Job Management
Control job execution with pause/resume functionality. Useful for managing system load and prioritizing jobs.
### `POST /api/v1/jobs/:uuid/pause`
**Auth**: Required
**Scope**: job-level
Pause a running or pending job. The worker will skip this job during polling until resumed.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `uuid` | string | Job UUID (file_uuid) |
#### Example
```bash
curl -X POST "$API/api/v1/jobs/$JOB_UUID/pause" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Job 3a6c1865... paused",
"uuid": "3a6c1865..."
}
```
#### Error Responses
| HTTP | When |
|------|------|
| `404` | Job not found |
| `400` | Job already completed or failed |
| `401` | Missing or invalid API key |
**Note**: Cannot pause jobs with status `completed` or `failed`.
---
### `POST /api/v1/jobs/:uuid/resume`
**Auth**: Required
**Scope**: job-level
Resume a paused job. The job will be picked up by the worker in the next polling cycle.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `uuid` | string | Job UUID (file_uuid) |
#### Example
```bash
curl -X POST "$API/api/v1/jobs/$JOB_UUID/resume" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Job 3a6c1865... resumed",
"uuid": "3a6c1865..."
}
```
#### Error Responses
| HTTP | When |
|------|------|
| `404` | Job not found |
| `401` | Missing or invalid API key |
---
### `GET /api/v1/jobs/paused`
**Auth**: Required
**Scope**: user-level
List all currently paused jobs with file names and pause timestamps.
#### Example
```bash
curl -s "$API/api/v1/jobs/paused" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"jobs": [
{
"uuid": "3a6c1865...",
"file_name": "video1.mp4",
"status": "paused",
"paused_at": "2026-10-25T10:30:00Z"
},
{
"uuid": "4b7d2976...",
"file_name": "video2.mp4",
"status": "paused",
"paused_at": "2026-10-25T11:15:00Z"
}
],
"total": 2
}
```
| Field | Type | Description |
|-------|------|-------------|
| `jobs` | array | Array of paused job objects |
| `uuid` | string | Job UUID (file_uuid) |
| `file_name` | string | Original file name |
| `status` | string | Always `"paused"` |
| `paused_at` | string \| null | ISO 8601 timestamp when paused |
| `total` | integer | Total number of paused jobs |
---
### `GET /api/v1/jobs/:uuid/status`
**Auth**: Required
**Scope**: job-level
Get the current status of a specific job. Returns detailed status including processor progress.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `uuid` | string | Job UUID (file_uuid) |
#### Example
```bash
curl -s "$API/api/v1/jobs/$JOB_UUID/status" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"uuid": "3a6c1865...",
"status": "paused",
"current_processor": "face",
"progress_current": 1500,
"progress_total": 2892,
"created_at": "2026-10-25T09:00:00Z",
"started_at": "2026-10-25T09:05:00Z",
"paused_at": "2026-10-25T10:30:00Z"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `uuid` | string | Job UUID |
| `status` | string | Current status (pending, running, paused, completed, failed) |
| `current_processor` | string \| null | Currently running processor |
| `progress_current` | integer | Current progress value |
| `progress_total` | integer | Total progress units |
| `created_at` | string | Job creation timestamp |
| `started_at` | string \| null | Job start timestamp |
| `paused_at` | string \| null | Pause timestamp (if paused) |
---
### `POST /api/v1/admin/sync-status`
**Auth**: Required
**Scope**: admin-level
Synchronize job statuses between database and Redis. Used for maintenance and consistency checks.
#### Example
```bash
curl -X POST "$API/api/v1/admin/sync-status" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Status sync completed",
"synced_count": 15
}
```
---
## Job Status Lifecycle
```
pending → running → completed
↓ ↓
paused failed
↓
pending (resumed)
```
| Status | Description | Actions Available |
|--------|-------------|-------------------|
| `pending` | Waiting in queue | Pause |
| `running` | Currently processing | Pause |
| `paused` | Paused by user | Resume |
| `completed` | Finished successfully | None |
| `failed` | Error occurred | None |
---
## Use Cases
### 1. Pause Heavy Processing Job
```bash
# Pause a running job to free up resources
curl -X POST "$API/api/v1/jobs/$UUID/pause" -H "X-API-Key: $KEY"
```
### 2. Resume Previously Paused Job
```bash
# Resume a paused job
curl -X POST "$API/api/v1/jobs/$UUID/resume" -H "X-API-Key: $KEY"
```
### 3. List All Paused Jobs
```bash
# Get all paused jobs
curl -s "$API/api/v1/jobs/paused" -H "X-API-Key: $KEY" | jq '.jobs[]'
```
### 4. Check Job Status
```bash
# Check if a job is paused or running
curl -s "$API/api/v1/jobs/$UUID/status" -H "X-API-Key: $KEY" | jq '.status'
```
---
## Implementation Notes
- **Redis Set**: Paused job UUIDs are stored in a Redis set (`jobs:paused`)
- **Worker Behavior**: Worker checks Redis set before picking up jobs
- **Persistence**: Pause state persists in both database and Redis
- **Resume Priority**: Resumed jobs enter the queue with normal priority
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,226 @@
---
title: Checkin API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: checkin -->
<!-- description: Workspace checkin/checkout for file isolation -->
<!-- depends: 01_auth, 03_register, 16_workspace -->
## Workspace Checkin/Checkout
Manage isolated workspace databases for files. Allows safe concurrent processing without conflicts.
### `POST /api/v1/file/:file_uuid/checkin`
**Auth**: Required
**Scope**: file-level
Check in a file from its isolated workspace database to the main database. Moves pre-chunks, speaker detections, and vectors from workspace to main tables.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/checkin" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"file_uuid": "3a6c1865...",
"pre_chunks_moved": 152,
"speaker_detections_moved": 45,
"vectors_moved": 152,
"status": "completed"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `file_uuid` | string | File UUID |
| `pre_chunks_moved` | integer | Number of pre-chunks moved |
| `speaker_detections_moved` | integer | Number of speaker detections moved |
| `vectors_moved` | integer | Number of vectors moved |
| `status` | string | Always `"completed"` |
#### Error Responses
| HTTP | When |
|------|------|
| `401` | Missing or invalid API key |
| `500` | Checkin failed (database error) |
---
### `POST /api/v1/file/:file_uuid/checkout`
**Auth**: Required
**Scope**: file-level
Check out a file from the main database. Deletes workspace data for the file.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/checkout" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"file_uuid": "3a6c1865...",
"rows_deleted": 197,
"status": "checked_out"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `file_uuid` | string | File UUID |
| `rows_deleted` | integer | Total rows deleted from workspace |
| `status` | string | Always `"checked_out"` |
---
### `GET /api/v1/file/:file_uuid/workspace`
**Auth**: Required
**Scope**: file-level
Check if a workspace database exists for a file.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/workspace" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"file_uuid": "3a6c1865...",
"exists": true
}
```
| Field | Type | Description |
|-------|------|-------------|
| `file_uuid` | string | File UUID |
| `exists` | boolean | Whether workspace database exists |
---
## Workspace Architecture
```
┌─────────────────────────────────────────┐
│ Main Database │
│ (PostgreSQL + Qdrant vectors) │
│ │
│ videos, identities, chunk, ... │
└─────────────────────────────────────────┘
↑ checkin
↓ checkout
┌─────────────────────────────────────────┐
│ Isolated Workspace Database │
│ (SQLite per file) │
│ │
│ pre_chunks, speaker_detections │
│ vectors (Qdrant _workspace collection) │
└─────────────────────────────────────────┘
```
### Workspace Benefits
1. **Concurrent Processing**: Multiple files can be processed simultaneously without lock conflicts
2. **Isolation**: Processing errors don't affect main database
3. **Rollback**: Failed processing can be discarded without cleanup
4. **Performance**: SQLite workspace is faster for bulk inserts
---
## Use Cases
### 1. Complete Processing and Check In
```bash
# After processing completes successfully
curl -X POST "$API/api/v1/file/$FILE_UUID/checkin" -H "X-API-Key: $KEY"
```
### 2. Discard Failed Processing
```bash
# If processing failed, checkout to clean up
curl -X POST "$API/api/v1/file/$FILE_UUID/checkout" -H "X-API-Key: $KEY"
```
### 3. Check Workspace Status
```bash
# Before checkin, verify workspace exists
curl -s "$API/api/v1/file/$FILE_UUID/workspace" -H "X-API-Key: $KEY" | jq '.exists'
```
---
## Workflow
### Normal Processing Flow
```
1. Register file → status: REGISTERED
2. Start processing → workspace created → status: PROCESSING
3. Processing complete → workspace populated
4. Checkin → move to main DB → status: COMPLETED
5. Workspace deleted automatically
```
### Error Recovery Flow
```
1. Processing failed → workspace contains partial data
2. Checkout → delete workspace → status: COMPLETED
3. Re-trigger processing if needed
```
---
## Implementation Notes
- **Workspace Location**: `{output_dir}/{file_uuid}.workspace.db`
- **Vector Collection**: `qdrant://_workspace_{file_uuid}`
- **Auto-cleanup**: Workspace deleted after successful checkin
- **Idempotency**: Checkin/checkout can be called multiple times safely
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: search API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: search -->
<!-- description: Vector search, BM25, smart search, universal search, LLM reranked search, frame search -->
<!-- depends: 01_auth -->
@@ -370,3 +378,11 @@ curl -s "$API/api/v1/search/identity_text?file_uuid=$FILE_UUID&q=love" -H "X-API
---
*Updated: 2026-06-20 — Added llm-smart search, completed frames search documentation, marked visual search as planned*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,347 @@
---
title: VLM Search API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: vlm_search -->
<!-- description: Vision Language Model search for scenes and traces -->
<!-- depends: search, profile -->
# VLM Search API
Search video scenes and traces using Vision Language Model (VLM) descriptions and tags.
## Overview
VLM Search API provides endpoints for:
- **Scene Search**: Search scenes by VLM-generated descriptions and objects
- **Trace Search**: Search face traces by VLM descriptions
- **Debug Search**: Debug VLM search functionality
## Endpoints
### `POST /api/v1/search/vlm/scenes`
**Auth**: Required
**Scope**: file-level or global
Search scenes using VLM-generated content and metadata.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `query` | string | Yes | — | Search query text |
| `file_uuid` | string | No | — | Limit to specific file |
| `filters` | object | No | — | Search filters |
| `page` | number | No | 1 | Page number |
| `page_size` | number | No | 20 | Results per page |
| `min_score` | number | No | 0.0 | Minimum relevance score |
#### Filters Object
| Field | Type | Description |
|-------|------|-------------|
| `vlm_objects` | array | Filter by detected objects |
| `vlm_tags` | array | Filter by VLM tags |
| `time_range` | object | Filter by time range |
#### Example
```bash
# Search scenes for "dog playing"
curl -s -X POST "$API/api/v1/search/vlm/scenes" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "dog playing in the park",
"page": 1,
"page_size": 20,
"min_score": 0.5
}'
```
```bash
# Search scenes with filters
curl -s -X POST "$API/api/v1/search/vlm/scenes" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "outdoor scene",
"file_uuid": "384b0ff44aaaa1f1",
"filters": {
"vlm_objects": ["dog", "tree"],
"time_range": {
"start_sec": 60.0,
"end_sec": 120.0
}
}
}'
```
#### Response (200)
```json
{
"results": [
{
"file_uuid": "384b0ff44aaaa1f1",
"file_name": "video.mp4",
"scene_index": 5,
"timestamp_sec": 125.5,
"frame_number": 3750,
"thumbnail_url": "/api/v1/media/384b0ff44aaaa1f1/scene/5/thumbnail",
"vlm_description": "A dog playing in a sunny park",
"vlm_description_localized": "陽光下的公園裡有隻狗在玩耍",
"vlm_objects": ["dog", "grass", "tree", "park"],
"vlm_tags": [
{"en": "dog", "local": "犬"},
{"en": "outdoor", "local": "戶外"},
{"en": "sunny", "local": "晴天"}
],
"score": 0.92,
"source": "vlm"
}
],
"total": 15,
"page": 1,
"page_size": 20
}
```
| Field | Type | Description |
|-------|------|-------------|
| `results` | array | Search results |
| `results[].file_uuid` | string | File UUID |
| `results[].file_name` | string | File name |
| `results[].scene_index` | number | Scene index |
| `results[].timestamp_sec` | number | Scene timestamp |
| `results[].frame_number` | number | Frame number |
| `results[].thumbnail_url` | string | Thumbnail URL |
| `results[].vlm_description` | string | VLM-generated description |
| `results[].vlm_description_localized` | string | Localized description (optional) |
| `results[].vlm_objects` | array | Detected objects |
| `results[].vlm_tags` | array | VLM tags (bilingual) |
| `results[].score` | number | Relevance score (0-1) |
| `results[].source` | string | Search source (`"vlm"`) |
| `total` | number | Total results |
| `page` | number | Current page |
| `page_size` | number | Page size |
---
### `POST /api/v1/search/vlm/traces`
**Auth**: Required
**Scope**: file-level or global
Search face traces using VLM descriptions.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `query` | string | Yes | — | Search query text |
| `file_uuid` | string | No | — | Limit to specific file |
| `filters` | object | No | — | Search filters |
| `page` | number | No | 1 | Page number |
| `page_size` | number | No | 20 | Results per page |
| `min_score` | number | No | 0.0 | Minimum relevance score |
#### Example
```bash
# Search traces for "person wearing red shirt"
curl -s -X POST "$API/api/v1/search/vlm/traces" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "person wearing red shirt",
"page": 1,
"page_size": 20
}'
```
#### Response (200)
```json
{
"results": [
{
"file_uuid": "384b0ff44aaaa1f1",
"trace_id": 2,
"identity_uuid": "a9a90105-...",
"vlm_description": "A person wearing a red t-shirt and blue jeans",
"vlm_tags": [
{"en": "red shirt", "local": "紅色上衣"},
{"en": "blue jeans", "local": "藍色牛仔褲"}
],
"score": 0.88
}
],
"total": 3,
"page": 1,
"page_size": 20
}
```
---
### `POST /api/v1/search/vlm/debug`
**Auth**: Required
**Scope**: system-level
Debug VLM search functionality (for development).
#### Example
```bash
# Debug VLM search
curl -s -X POST "$API/api/v1/search/vlm/debug" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "test query"
}'
```
---
## Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/vlm_search.rs` (773 lines)
**Data Structures**:
- `SceneSearchRequest` - Scene search parameters
- `TraceSearchRequest` - Trace search parameters
- `VlmTagValue` - Bilingual tag structure
**VLM Tags Structure**:
```json
{
"en": "dog",
"local": "犬"
}
```
**Search Process**:
1. Parse query and filters
2. Generate embedding for query text
3. Search Qdrant for matching scenes/traces
4. Apply filters (objects, tags, time range)
5. Sort by relevance score
6. Return paginated results
---
## VLM Integration
### Description Generation
VLM descriptions are generated during file processing:
- **Scene VLM**: Analyzes scene frames
- **Trace VLM**: Analyzes face trace appearances
### Tag Structure
Bilingual tags enable multilingual search:
- **English tag**: Primary search key
- **Local tag**: Native language display
### Objects vs Tags
- **Objects**: Detected physical objects (dog, car, tree)
- **Tags**: Semantic concepts (outdoor, sunny, daytime)
---
## Search Tips
### Effective Queries
✅ **Good**:
- "dog playing in the park"
- "person wearing red shirt"
- "outdoor sunny scene"
❌ **Less Effective**:
- "video" (too generic)
- "frame 100" (technical reference)
### Filter Usage
Use filters to narrow results:
- `vlm_objects`: Specific objects
- `vlm_tags`: Specific concepts
- `time_range`: Specific time period
### Score Thresholds
- `> 0.8`: Highly relevant
- `0.5-0.8`: Moderately relevant
- `< 0.5`: Low relevance
---
## Error Codes
| Code | HTTP | When |
|------|------|------|
| E401 | 401 | Missing or invalid API key |
| E400 | 400 | Invalid query or parameters |
| E500 | 500 | Search failed |
---
## Related Documentation
- [Search API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/06_search.md)
- [Profile API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/18_profile.md)
- [Scene VLM Stats](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/scene_vlm_stats_api.md)
---
## Common Issues
### No Results Found
**Symptoms**: Empty results array
**Possible Causes**:
1. Query too specific
2. Low `min_score` threshold
3. No matching scenes/traces
**Solution**:
- Simplify query
- Lower `min_score`
- Check file processing status
### Low Relevance Scores
**Symptoms**: All results have low scores (< 0.5)
**Possible Causes**:
1. Query doesn't match content
2. VLM descriptions not generated
3. Embedding quality issue
**Solution**:
- Rephrase query
- Verify VLM processing completed
- Check VLM model configuration
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,218 @@
---
title: Scene VLM Stats API
version: 1.0.0
date: 2026-10-14
author: Core Team
status: active
---
# Scene VLM Stats API
**Endpoint**: `/api/v1/file/{file_uuid}/scene-vlm-stats`
**Method**: `GET`
**Purpose**: 快速获取文件的 Scene VLM 统计数据
---
## Overview
**Scope**: File processing statistics
**Status**: Active
**Applicable to**: All registered files with Scene VLM processing
---
## Request
### Parameters
| Parameter | Type | Location | Required | Description |
|-----------|------|----------|----------|-------------|
| `file_uuid` | String | Path | Yes | File UUID |
### Example
```bash
curl http://localhost:3002/api/v1/file/dac75694ee550ff57d74f26391fcc751/scene-vlm-stats
```
---
## Response
### Success (200 OK)
```json
{
"total_scenes": 2,
"status": "completed",
"vlm_done": 2,
"vlm_total": 2
}
```
### Fields
| Field | Type | Description |
|-------|------|-------------|
| `total_scenes` | i64 | Total number of scenes detected |
| `status` | String | Scene VLM processing status (`pending`, `processing`, `completed`) |
| `vlm_done` | i64 | Number of scenes with VLM descriptions completed |
| `vlm_total` | i64 | Total scenes needing VLM processing |
### Default Response
If the file has no scenes file:
```json
{
"total_scenes": 0,
"status": "",
"vlm_done": 0,
"vlm_total": 0
}
```
---
## Performance
**Response Time**: < 10ms
**Why Fast**:
- Directly reads `{file_uuid}.scenes.json`
- No database queries
- No complex calculations
---
## Use Cases
### 1. UI Display
Display Scene VLM progress in Library view:
```typescript
const stats = await loadSceneVlmStats(fileUuid)
console.log(`${stats.vlm_done}/${stats.vlm_total} scenes completed`)
```
### 2. Performance Optimization
Replace expensive `get_file_stats` call:
- **Old**: `get_file_stats` - 100-500ms
- **New**: `scene-vlm-stats` - < 10ms
- **Improvement**: 10-50x faster
### 3. Real-time Updates
Poll for Scene VLM progress without heavy API load:
```typescript
setInterval(() => {
loadSceneVlmStats(fileUuid)
}, 5000)
```
---
## Implementation Details
### Backend
**File**: `src/api/scan.rs:1647`
**Logic**:
1. Check if `{file_uuid}.scenes.json` exists
2. Read JSON file
3. Parse and count scenes
4. Return statistics
**Code**:
```rust
async fn get_scene_vlm_stats(
Path(file_uuid): Path<String>,
) -> Result<Json<SceneVlmStats>, StatusCode> {
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
if !Path::new(&scenes_path).exists() {
return Ok(Json(SceneVlmStats::default()));
}
let scenes_json = std::fs::read_to_string(&scenes_path)?;
let scenes_data: Value = serde_json::from_str(&scenes_json)?;
// ... parse and return stats
}
```
---
## Error Handling
### File Not Found
**Status**: 200 OK
**Response**: Default values (all zeros)
### Parse Error
**Status**: 500 Internal Server Error
**Note**: Rare case, indicates corrupted JSON file
---
## Related APIs
- `GET /api/v1/file/{file_uuid}` - Full file info (slower)
- `GET /api/v1/file/{file_uuid}/processor-counts` - Processor counts
- `GET /api/v1/stats/file/{file_uuid}` - Detailed stats (slower)
---
## Best Practices
### 1. Use for Scene VLM Progress
**Recommended**: Use this API for Scene VLM progress display
**Avoid**: Using `get_file_stats` for simple Scene VLM stats
### 2. Caching
Frontend should cache results:
```typescript
if (fileStatsCache.value[fileUuid].scene_vlm) {
return fileStatsCache.value[fileUuid].scene_vlm
}
```
### 3. Error Handling
Always handle failures gracefully:
```typescript
try {
const stats = await loadSceneVlmStats(fileUuid)
} catch (e) {
console.warn('Scene VLM stats failed:', e)
// Use cached data or show 'Unknown'
}
```
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0.0 | 2026-10-14 | Initial API endpoint |
---
## Cross-References
- **Frontend Integration**: Studio team commit 3e7eba0
- **Test Script**: `momentry_studio/scripts/test_scene_vlm_api.sh`
- **Backend Code**: `src/api/scan.rs:1647`
---
**Last Updated**: 2026-10-14
@@ -1,3 +1,11 @@
---
title: identity API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: identity -->
<!-- description: Global identities — CRUD, detail, files, faces, bind, unbind, search -->
<!-- depends: 01_auth -->
@@ -1109,3 +1117,11 @@ This **replaces** the entire `aliases` array. To add to existing aliases, includ
*Updated: 2026-08-12 — identity traces include capture_quality fields (avg_capture_quality, best_capture_quality)*
*Updated: 2026-07-21 — Fixed bind/unbind TKG update to match both trace_N and face_track_N external_id formats*
*Updated: 2026-06-20 — Added identity files, chunks, faces, status, and JSON endpoints*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: identity agent API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: identity_agent -->
<!-- description: Identity agent — match from photo, match from trace -->
<!-- depends: 01_auth, 07_identity -->
@@ -125,3 +133,11 @@ curl -s -X POST "$API/api/v1/agents/identity/confirm" \
---
*Updated: 2026-06-26 00:30:00*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: identity history API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: identity_history -->
<!-- description: Identity operation history, undo, and redo (PATCH, bind, unbind, bind_trace, mergeinto) -->
<!-- depends: 01_auth, 07_identity -->
@@ -694,3 +702,11 @@ A new delete after an undo clears the delete redo stack (no redo possible for th
---
*Updated: 2026-05-28*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,343 @@
---
title: Face Filter API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: face_filter -->
<!-- description: Face detection filtering and quality management -->
<!-- depends: 01_auth, 03_register -->
## Face Filter API
Face filtering functionality for Studio frontend to manage face detection quality across multiple detection sources.
### `GET /api/v1/file/:file_uuid/faces`
**Auth**: Required
**Scope**: file-level
Get filtered face detection list for a file with pagination and source filtering.
#### Query Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `source` | string | No | "all" | Detection source: "all", "apple_vision", "mediapipe" |
| `page` | integer | No | 1 | Page number (1-indexed) |
| `page_size` | integer | No | 50 | Items per page |
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces?source=apple_vision&page=1&page_size=50" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"data": {
"faces": [
{
"face_id": "face_001",
"frame": 671,
"primary_source": "apple_vision",
"primary_confidence": 0.84,
"detection_sources": [
{"source_type": "apple_vision", "confidence": 0.84},
{"source_type": "mediapipe", "confidence": 0.92}
]
}
],
"total": 1523,
"page": 1,
"page_size": 50
}
}
```
---
### `GET /api/v1/file/:file_uuid/faces/:face_id/filter`
**Auth**: Required
**Scope**: file-level
Get detailed filter report for a specific face detection.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID |
| `face_id` | string | Face detection ID |
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/face_001/filter" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"data": {
"face_id": "face_001",
"frame": 671,
"passed_filter": true,
"filter_rules": {
"min_confidence": 0.5,
"min_size": 30,
"source_priority": ["apple_vision", "mediapipe"]
},
"quality_metrics": {
"confidence": 0.84,
"size": 120,
"blurriness": 0.15
}
}
}
```
---
### `POST /api/v1/file/:file_uuid/faces/apply-filter`
**Auth**: Required
**Scope**: file-level
Apply filter rules to all faces in a file. Returns statistics on filtered faces.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `min_confidence` | float | No | Minimum confidence threshold (0.0-1.0) |
| `min_size` | integer | No | Minimum face size in pixels |
| `source_priority` | string[] | No | Preferred detection sources in order |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/apply-filter" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"min_confidence": 0.6,
"min_size": 40,
"source_priority": ["apple_vision", "mediapipe"]
}'
```
#### Response (200)
```json
{
"success": true,
"statistics": {
"total_faces": 1523,
"passed_faces": 1245,
"filtered_faces": 278,
"by_source": {
"apple_vision": 985,
"mediapipe": 260
}
}
}
```
---
### `GET /api/v1/file/:file_uuid/faces/filter-stats`
**Auth**: Required
**Scope**: file-level
Get face filter statistics for a file without applying changes.
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/filter-stats" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"data": {
"total_faces": 1523,
"detection_sources": {
"apple_vision": 985,
"mediapipe": 538
},
"confidence_distribution": {
"high": 1245,
"medium": 200,
"low": 78
},
"size_distribution": {
"large": 500,
"medium": 700,
"small": 323
}
}
}
```
---
### `POST /api/v1/file/:file_uuid/faces/rules`
**Auth**: Required
**Scope**: file-level
Create or update face filter rules for a file.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | array | Yes | Array of filter rules |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/rules" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"rules": [
{
"name": "high_quality",
"conditions": {
"min_confidence": 0.7,
"min_size": 50
},
"action": "accept"
}
]
}'
```
---
### `GET /api/v1/file/:file_uuid/faces/rules`
**Auth**: Required
**Scope**: file-level
Get all face filter rules configured for a file.
#### Example
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/rules" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"rules": [
{
"id": 1,
"name": "high_quality",
"conditions": {
"min_confidence": 0.7,
"min_size": 50
},
"action": "accept",
"created_at": "2026-08-09T10:00:00Z"
}
]
}
```
---
### `DELETE /api/v1/file/:file_uuid/faces/rules/:rule_id`
**Auth**: Required
**Scope**: file-level
Delete a specific filter rule.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `rule_id` | integer | Rule ID |
#### Example
```bash
curl -X DELETE "$API/api/v1/file/$FILE_UUID/faces/rules/1" \
-H "X-API-Key: $KEY"
```
---
## Detection Sources
| Source | Description | Quality | Speed |
|--------|-------------|---------|-------|
| `apple_vision` | Apple Vision Framework | High (ANE accelerated) | Fast |
| `mediapipe` | MediaPipe Face Detection | Medium | Medium |
---
## Quality Metrics
| Metric | Description | Range |
|--------|-------------|-------|
| `confidence` | Detection confidence | 0.0-1.0 |
| `size` | Face bounding box diagonal (pixels) | 0-∞ |
| `blurriness` | Laplacian variance (lower = clearer) | 0.0-1.0 |
---
## Use Cases
### 1. Filter Low-Quality Faces
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/apply-filter" \
-H "X-API-Key: $KEY" \
-d '{"min_confidence": 0.7, "min_size": 50}'
```
### 2. Prioritize Apple Vision Detections
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/faces/apply-filter" \
-H "X-API-Key: $KEY" \
-d '{"source_priority": ["apple_vision"]}'
```
### 3. Check Filter Statistics
```bash
curl -s "$API/api/v1/file/$FILE_UUID/faces/filter-stats" \
-H "X-API-Key: $KEY" | jq '.data'
```
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Rewrote documentation in English, added YAML frontmatter |
@@ -1,3 +1,11 @@
---
title: Media API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: media -->
<!-- description: Video streaming & frame extraction -->
<!-- depends: 01_auth -->
@@ -535,3 +543,11 @@ curl -s "$API/api/v1/media-proxy?url=https://image.tmdb.org/t/p/w500/abc123.jpg"
---
*Updated: 2026-06-20 — Added stranger endpoints, chunk thumbnail, and media proxy*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: profile API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: profile -->
<!-- description: Trace profile and file profile management — read/update face trace names, key frames, aliases, and file paths -->
<!-- depends: 01_auth, 07_identity, 15_tkg -->
@@ -474,3 +482,11 @@ curl -s -X PUT "$API/api/v1/file-profile" \
*Updated: 2026-07-25 — Added Merge Groups API (POST /groups/merge), added Terminology section (Face, Face Sequence, Face Group)*
*Updated: 2026-07-21 — Fixed external_id matching (trace_N + face_track_N formats), fixed parameter ordering in UPDATE query*
*Updated: 2026-07-18 — New profile module: trace-profile (GET, PUT, PUT group) and file-profile (GET, PUT)*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: Pose & Appearance API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: pose_appearance -->
<!-- description: Pose skeleton and appearance color endpoints for face detail display -->
<!-- depends: 01_auth -->
@@ -164,4 +172,11 @@ curl -s "$API/api/v1/file/$FILE_UUID/appearance?frame=303" \
| Confidence | `null` | Aggregated confidence score |
---
*Updated: 2026-07-19 — New pose and appearance endpoints for face detail display*
*Updated: 2026-07-19 — New pose and appearance endpoints for face detail display*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,114 @@
# Trace Thumbnail Regenerate API 使用指南 — Studio 團隊參考
**版本**: v1.0
**日期**: 2026-08-12
**狀態**: 已實作(Core)
---
## 概述
修復「key_frame 正常、key_face bbox 正常、但 key_face 縮圖異常」之現象。
**根因**: bbox 部分越過 frame 邊界(如 trace 355b 案例)時,crop 未 clamp 到 frame 尺寸,ffmpeg 靜默 clamp/位移,導致縮圖內容錯位。由於縮圖端點優先回傳 `key_face.jpg` cache,異常內容被持久化顯示。
**修復**: 本端點重新選取該 trace 之 best-confidence face,將 bbox clamp 至影片尺寸後重新裁切,覆寫 `key_face.jpg`,並同步更新 `.faces` cache。
---
## API 端點
### POST `/api/v1/file/{file_uuid}/trace/{trace_id}/regenerate-thumbnail`
**功能**: 重新產生單一 trace 的 face thumbnail(覆寫 cache)
**Auth**: Required
**Body**: 可為空。
**Response 200**:
```json
{
"success": true,
"file_uuid": "...",
"trace_id": 355,
"frame": 1835,
"bbox": { "x": 65, "y": 301, "width": 70, "height": 59 }
}
```
- `frame` / `bbox` 為重新裁切使用的(clamp 後)frame 與 bbox。
**Error Responses**:
| Status | 說明 |
|--------|------|
| 404 | Video not found(該 file_uuid 無影片)或 No face found for this trace(該 trace 無 face 資料) |
| 400 | Video width/height unavailable — 影片未記錄尺寸,無法 clamp,拒絕重切 |
---
## 行為說明
1. 讀取該 trace 最高 confidence 的 frame + bbox(**不**重跑 blur 優化,取既有 best face 復原同一區域)
2. 將 bbox clamp 到影片 width/height 內(`clamp_crop`)
3. ffmpeg 自影片以 decoded frame index 切出該 frame → crop face 區域
4. 覆寫 `{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}/key_face.jpg`
5. 若 `.faces/{file_uuid}/{trace_id}/{frame}.jpg` 已存在則同步覆寫
**不影響**: Qdrant、`trace_profiles` DB、`tkg_nodes`、影片檔 — 僅重寫縮圖 cache。
---
## Studio 整合步驟
### 1. apiCall (`src/api/index.ts`)
新增 case:
```ts
case 'regenerate_trace_thumbnail': {
return { url: `/api/v1/file/${a.fileUuid}/trace/${a.traceId}/regenerate-thumbnail`, method: 'POST' }
}
```
### 2. Face detail modal 加「Re-gen」按鈕 (`src/views/PeopleView.vue`)
於 `ms-face-detail-thumb` 附近加入按鈕,呼叫上方 apiCall,in-flight 時 disabled。
### 3. 觸發後 refresh(重要)
Face detail 縮圖顯示的是 `faceThumbsCache`(key = `${file_uuid}-${trace_id}`)。`loadTraceThumb` 對已有 cache 的 key 會直接 return,**單獨 `bumpThumbCacheBust()` 無法刷新 face detail 縮圖**。正確順序:
```ts
await apiCall('regenerate_trace_thumbnail', { fileUuid, traceId }) // 1. 呼叫 regenerate
delete faceThumbsCache.value[`${fileUuid}-${traceId}`] // 2. 清除該 key 的 blob cache
bumpThumbCacheBust() // 3. bump 版本(避 HTTP cache)
loadTraceThumb({ file_uuid: fileUuid, trace_id: traceId }) // 4. 重新載入縮圖
```
> `candidateThumbs` 即 `faceThumbsCache` 的 alias(PeopleView.vue:722),delete 後無需額外處理。
> 若想一次清空全部縮圖可用 `clearFaceThumbs()`(較重,不建議單一 trace 場景)。
---
## 測試指示
```bash
# 使用已知越界案例(trace 355b 一類)驗證:
# 1) regenerate 前:GET thumbnail 顯示位移內容
# 2) 呼叫 regenerate → 回 success,含 clamp 後 bbox
# 3) 再次 GET thumbnail → 內容正確對齊 bbox
curl -X POST "http://localhost:3002/api/v1/file/<FILE_UUID>/trace/<TRACE_ID>/regenerate-thumbnail" \
-H "X-API-Key: <KEY>"
```
---
## 參考
- 根因 crop 修正:`src/core/thumbnail/validator.rs::clamp_crop`、`src/core/processor/tkg.rs`
- 端點 handler:`src/api/trace_agent_api.rs::regenerate_trace_thumbnail`
---
## 版本歷史
| 版本 | 日期 | 變更 |
|------|------|------|
| v1.0 | 2026-08-12 | 初版 |
@@ -1,3 +1,11 @@
---
title: tmdb API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: tmdb -->
<!-- description: TMDb enrichment endpoints — prefetch, probe, resource, check -->
<!-- depends: 01_auth, 03_register -->
@@ -199,3 +207,11 @@ No manual API call needed if auto-match is enabled.
---
*Updated: 2026-06-20 — Added tmdb/fetch and tmdb/match endpoints*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: agent API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
# Agent Endpoints
Agent endpoints provide AI-powered capabilities including translation, identity analysis, and 5W1H extraction.
@@ -209,3 +217,11 @@ Agent 內部使用 Gemma4 function calling 自動調用以下工具:
---
*Updated: 2026-05-22*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: tkg API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: tkg -->
<!-- description: Temporal Knowledge Graph — rebuild, nodes, edges, processor counts -->
<!-- depends: 05_process, 07_identity -->
@@ -532,3 +540,11 @@ curl -X POST "$API/api/v1/file/$FILE_UUID/trace/16/merge/3" \
*Updated: 2026-07-21 01:00:00*
*Updated: 2026-08-12 — face_track node properties now include capture_quality fields (avg/best) and key_frame/key_face are selected by best capture quality*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,373 @@
---
title: Trace Agent API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: trace_agent -->
<!-- description: Face trace and TKG (Temporal Knowledge Graph) operations -->
<!-- depends: identity, profile -->
# Trace Agent API
Manage face traces, temporal knowledge graphs, and trace-related operations.
## Overview
Trace Agent API provides endpoints for:
- **Trace Management**: List, query, and analyze face traces
- **Face Retrieval**: Get faces from traces, representative faces
- **Thumbnails**: Generate and retrieve trace thumbnails
- **TKG Operations**: Build, query, and manage Temporal Knowledge Graphs
- **Co-occurrence**: Analyze identity co-occurrence in videos
## Endpoints
### `POST /api/v1/file/:file_uuid/traces`
**Auth**: Required
**Scope**: file-level
List all traces for a file, sorted by various criteria.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `file_uuid` | string | Yes | — | File UUID (path parameter) |
#### Example
```bash
# List traces for a file
curl -s -X POST "$API/api/v1/file/$FILE_UUID/traces" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{}'
```
#### Response (200)
```json
{
"traces": [
{
"trace_id": 1,
"face_count": 50,
"first_frame": 100,
"last_frame": 1500,
"identity_uuid": "a9a90105-..."
}
]
}
```
---
### `GET /api/v1/file/:file_uuid/trace/:trace_id/faces`
**Auth**: Required
**Scope**: file-level
Get all faces for a specific trace.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `file_uuid` | string | Yes | File UUID |
| `trace_id` | number | Yes | Trace ID |
#### Example
```bash
# Get faces for trace 1
curl -s "$API/api/v1/file/$FILE_UUID/trace/1/faces" \
-H "X-API-Key: $KEY"
```
---
### `GET /api/v1/file/:file_uuid/trace/:trace_id/representative-face`
**Auth**: Required
**Scope**: file-level
Get the representative (best quality) face for a trace.
#### Example
```bash
# Get representative face
curl -s "$API/api/v1/file/$FILE_UUID/trace/1/representative-face" \
-H "X-API-Key: $KEY"
```
---
### `GET /api/v1/file/:file_uuid/trace/:trace_id/thumbnail`
**Auth**: Required
**Scope**: file-level
Get thumbnail for a trace.
#### Example
```bash
# Get trace thumbnail
curl -s "$API/api/v1/file/$FILE_UUID/trace/1/thumbnail" \
-H "X-API-Key: $KEY"
```
---
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/representative-face`
**Auth**: Required
**Scope**: file-level
Get representative face for a stranger (unidentified person).
#### Example
```bash
# Get stranger representative face
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/representative-face" \
-H "X-API-Key: $KEY"
```
---
### `GET /api/v1/file/:file_uuid/stranger/:stranger_id/thumbnail`
**Auth**: Required
**Scope**: file-level
Get thumbnail for a stranger.
#### Example
```bash
# Get stranger thumbnail
curl -s "$API/api/v1/file/$FILE_UUID/stranger/1/thumbnail" \
-H "X-API-Key: $KEY"
```
---
### `GET /api/v1/file/:file_uuid/identities/:identity_uuid_a/co-occur-with/:identity_uuid_b`
**Auth**: Required
**Scope**: file-level
Get co-occurrence information between two identities in a file.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `file_uuid` | string | Yes | File UUID |
| `identity_uuid_a` | string | Yes | First identity UUID |
| `identity_uuid_b` | string | Yes | Second identity UUID |
#### Example
```bash
# Check co-occurrence
curl -s "$API/api/v1/file/$FILE_UUID/identities/$IDENTITY_UUID_A/co-occur-with/$IDENTITY_UUID_B" \
-H "X-API-Key: $KEY"
```
---
### `POST /api/v1/file/:file_uuid/tkg/rebuild`
**Auth**: Required
**Scope**: file-level
Rebuild Temporal Knowledge Graph for a file.
#### Example
```bash
# Rebuild TKG
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/rebuild" \
-H "X-API-Key: $KEY"
```
---
### `GET /api/v1/file/:file_uuid/tkg`
**Auth**: Required
**Scope**: file-level
Get TKG operations for a file.
#### Example
```bash
# Get TKG operations
curl -s "$API/api/v1/file/$FILE_UUID/tkg" \
-H "X-API-Key: $KEY"
```
---
### `DELETE /api/v1/file/:file_uuid/tkg`
**Auth**: Required
**Scope**: file-level
Delete TKG for a file.
#### Example
```bash
# Delete TKG
curl -s -X DELETE "$API/api/v1/file/$FILE_UUID/tkg" \
-H "X-API-Key: $KEY"
```
---
### `POST /api/v1/file/:file_uuid/rule2`
**Auth**: Required
**Scope**: file-level
Ingest Rule 2 for TKG.
#### Example
```bash
# Ingest Rule 2
curl -s -X POST "$API/api/v1/file/$FILE_UUID/rule2" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{}'
```
---
### `GET /api/v1/file/:file_uuid/representative-frame`
**Auth**: Required
**Scope**: file-level
Get representative frame for a file.
#### Example
```bash
# Get representative frame
curl -s "$API/api/v1/file/$FILE_UUID/representative-frame" \
-H "X-API-Key: $KEY"
```
---
### `POST /api/v1/file/:file_uuid/tkg/nodes`
**Auth**: Required
**Scope**: file-level
Query TKG nodes.
#### Example
```bash
# Query TKG nodes
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/nodes" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{}'
```
---
### `POST /api/v1/file/:file_uuid/tkg/edges`
**Auth**: Required
**Scope**: file-level
Query TKG edges.
#### Example
```bash
# Query TKG edges
curl -s -X POST "$API/api/v1/file/$FILE_UUID/tkg/edges" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{}'
```
---
## Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/trace_agent_api.rs` (2918 lines)
**Data Structures**:
- `Trace` - Face trace object
- `Face` - Single face detection
- `TKG` - Temporal Knowledge Graph
- `Stranger` - Unidentified person
**Database Tables**:
- `face_detections` - Face detection records
- `traces` - Trace metadata
- `tkg_nodes` - TKG nodes
- `tkg_edges` - TKG edges
---
## Related Documentation
- [Identity API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/07_identity.md)
- [Profile API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/18_profile.md)
- [TKG API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/15_tkg.md)
---
## Common Issues
### Trace Not Found
**Symptoms**: 404 error when accessing trace
**Solution**: Check if trace exists in database or re-process the file
### TKG Build Failed
**Symptoms**: TKG rebuild returns error
**Solution**: Check file processing status and logs
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation (summary) |
**Note**: This is a summary documentation. Full endpoint details require additional work.
@@ -0,0 +1,243 @@
---
title: Cluster Agent API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: cluster_agent -->
<!-- description: Asynchronous face clustering agent -->
<!-- depends: 01_auth, 03_register, 07_identity -->
## Cluster Agent
Asynchronous face clustering agent that automatically groups similar faces into identities. Runs as a background job.
### `POST /api/v1/file/:file_uuid/cluster-agent`
**Auth**: Required
**Scope**: file-level
Trigger asynchronous face clustering for a file. Returns immediately with a job ID. Clustering runs in the background.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_uuid` | string | File UUID (32-char hex) |
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `confirm` | boolean | Yes | false | Must be `true` to trigger clustering |
| `min_confidence` | float | No | 0.6 | Minimum face confidence to include |
| `algorithm` | string | No | "dbscan" | Clustering algorithm ("dbscan", "kmeans") |
#### Example
```bash
curl -X POST "$API/api/v1/file/$FILE_UUID/cluster-agent" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{"confirm": true, "min_confidence": 0.6}'
```
#### Response (202 Accepted)
```json
{
"success": true,
"job_id": "cluster_abc123",
"file_uuid": "3a6c1865...",
"status": "queued",
"message": "Cluster job queued for processing"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Always true on 202 |
| `job_id` | string | Job ID for status tracking |
| `file_uuid` | string | File UUID |
| `status` | string | Job status ("queued", "running", "completed", "failed") |
| `message` | string | Human-readable status |
#### Error Responses
| HTTP | When |
|------|------|
| `400` | `confirm` not set to `true` |
| `404` | File not found |
| `409` | Job already running for this file |
| `401` | Missing or invalid API key |
---
### `GET /api/v1/cluster-job/:job_id`
**Auth**: Required
**Scope**: job-level
Get status of a cluster job. Returns progress, statistics, and results if completed.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `job_id` | string | Job ID returned from trigger endpoint |
#### Example
```bash
curl -s "$API/api/v1/cluster-job/cluster_abc123" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"job_id": "cluster_abc123",
"file_uuid": "3a6c1865...",
"status": "completed",
"progress": {
"total_faces": 1523,
"processed": 1523,
"percentage": 100
},
"result": {
"clusters_found": 12,
"identities_created": 8,
"identities_updated": 4
},
"started_at": "2026-10-25T10:00:00Z",
"completed_at": "2026-10-25T10:05:30Z"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `job_id` | string | Job ID |
| `file_uuid` | string | File UUID |
| `status` | string | "running", "completed", "failed", "cancelled" |
| `progress` | object | Progress information |
| `result` | object | Final results (if completed) |
| `error` | string | Error message (if failed) |
| `started_at` | string | ISO 8601 timestamp |
| `completed_at` | string | ISO 8601 timestamp (if completed) |
---
### `DELETE /api/v1/cluster-job/:job_id`
**Auth**: Required
**Scope**: job-level
Cancel a running cluster job. Cannot cancel completed or failed jobs.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `job_id` | string | Job ID |
#### Example
```bash
curl -X DELETE "$API/api/v1/cluster-job/cluster_abc123" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"job_id": "cluster_abc123",
"status": "cancelled",
"message": "Job cancelled successfully"
}
```
---
## Clustering Process
### How It Works
1. **Face Collection**: Gather all face detections from the file
2. **Embedding Extraction**: Get face embeddings (512-dim vectors)
3. **Similarity Clustering**: Group similar faces using DBSCAN
4. **Identity Assignment**: Create or update identities for clusters
5. **Face Binding**: Bind faces to their cluster identity
### Clustering Algorithm
**DBSCAN Parameters**:
- `eps`: 0.3 (distance threshold)
- `min_samples`: 5 (minimum cluster size)
**Quality Metrics**:
- Intra-cluster similarity: Average pairwise similarity within cluster
- Inter-cluster separation: Average distance to nearest cluster
---
## Use Cases
### 1. Automatic Identity Creation
```bash
# After processing, trigger clustering
curl -X POST "$API/api/v1/file/$FILE_UUID/cluster-agent" \
-H "X-API-Key: $KEY" \
-d '{"confirm": true}'
```
### 2. Monitor Clustering Progress
```bash
# Poll job status
curl -s "$API/api/v1/cluster-job/$JOB_ID" -H "X-API-Key: $KEY" | jq '.status'
```
### 3. Cancel Slow Clustering
```bash
# If clustering takes too long
curl -X DELETE "$API/api/v1/cluster-job/$JOB_ID" -H "X-API-Key: $KEY"
```
---
## Performance
| File Size | Face Count | Processing Time |
|-----------|------------|-----------------|
| 10 min video | 500 faces | ~30 seconds |
| 30 min video | 1500 faces | ~2 minutes |
| 90 min video | 4500 faces | ~8 minutes |
**Notes**:
- Processing time scales linearly with face count
- Uses in-memory job registry (cleared on server restart)
- Concurrent jobs are supported but resource-intensive
---
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `400 Bad Request` | `confirm` not set | Add `"confirm": true` to request body |
| `404 Not Found` | File not found | Verify file_uuid |
| `409 Conflict` | Job already running | Wait for current job to complete or cancel it |
| `500 Internal Error` | Clustering failed | Check server logs for details |
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: error codes API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: error_codes -->
<!-- description: Standard API error codes -->
<!-- depends: -->
@@ -58,3 +66,11 @@ All API errors follow this JSON structure:
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: config API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: config -->
<!-- description: System configuration — cache, auto-pipeline, watcher-auto-register toggles -->
<!-- depends: 01_auth -->
@@ -88,3 +96,11 @@ curl -s -X POST "$API/api/v1/config/watcher-auto-register" \
---
*Updated: 2026-05-19 12:49:24*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -1,3 +1,11 @@
---
title: workspace API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: workspace -->
<!-- description: Workspace checkout/checkin — lock, clear, restore file data -->
<!-- depends: 04_lookup, 05_process -->
@@ -146,3 +154,11 @@ curl -s "$API/api/v1/file/$FILE_UUID/workspace" \
---
*Updated: 2026-06-20 12:00:00*
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,387 @@
---
title: Service Management API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: service_management -->
<!-- description: Service lifecycle management endpoints -->
<!-- depends: health -->
# Service Management API
Manage Momentry core services, including start, stop, and health check operations.
## Overview
Service Management API provides endpoints for:
- **Start Service**: Launch inference services (e.g., MBE)
- **Stop Service**: Terminate running services
- **Health Check**: Monitor service status
## Endpoints
### `POST /api/v2/service/start`
**Auth**: Required
**Scope**: system-level
Start a Momentry service.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `name` | string | Yes | — | Service name (e.g., `"mbe"`) |
| `model` | string | No | — | Model path or name |
| `port` | number | No | 8080 | Service port |
#### Example
```bash
# Start MBE service with default model
curl -s -X POST "$API/api/v2/service/start" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe"}'
```
```bash
# Start MBE service with custom model and port
curl -s -X POST "$API/api/v2/service/start" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "mbe",
"model": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
"port": 8080
}'
```
#### Response (200)
```json
{
"result": "started",
"pid": 12345
}
```
| Field | Type | Description |
|-------|------|-------------|
| `result` | string | `"started"` or `"failed"` |
| `pid` | number | Process ID if successful |
| `error` | string | Error message if failed |
#### Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/service_management.rs`
**Process**:
1. Validates service name (currently only `"mbe"` supported)
2. Checks if port is already in use
3. Stops existing process on that port
4. Spawns llama-server with specified model
5. Waits up to 60 seconds for service to be ready
6. Returns process ID on success
**Supported Services**:
- `"mbe"` - MarkBase Engine (llama.cpp server)
---
### `POST /api/v2/service/stop`
**Auth**: Required
**Scope**: system-level
Stop a running service.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `name` | string | Yes | — | Service name (e.g., `"mbe"`) |
#### Example
```bash
# Stop MBE service
curl -s -X POST "$API/api/v2/service/stop" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe"}'
```
#### Response (200)
**Success**:
```json
{
"result": "stopped"
}
```
**Failure**:
```json
{
"result": "failed",
"error": "No service running on port 8080"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `result` | string | `"stopped"` or `"failed"` |
| `error` | string | Error message if failed |
#### Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/service_management.rs`
**Process**:
1. Validates service name
2. Finds process ID by port (8080)
3. Sends kill signal
4. Returns success/failure
---
### `GET /api/v1/mbe/health`
**Auth**: Public
**Scope**: system-level
Check MBE (MarkBase Engine) health status.
#### Request Parameters
None
#### Example
```bash
# Check MBE health
curl -s "$API/api/v1/mbe/health"
```
#### Response (200)
**Online**:
```json
{
"status": "ok",
"model": "gemma-4-12b-it-Q4_K_M.gguf",
"uptime": 3600
}
```
**Offline**:
```json
{
"status": "offline"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `status` | string | `"ok"` or `"offline"` |
| `model` | string | Model name if online |
| `uptime` | number | Uptime in seconds (currently always 0) |
#### Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/service_management.rs`
**Process**:
1. Checks if port 8080 is in use
2. Calls `/v1/models` endpoint
3. Extracts model name from response
4. Returns health status
**Health Check Endpoint**: `http://127.0.0.1:8080/v1/models`
---
## Error Codes
| Code | HTTP | When |
|------|------|------|
| E401 | 401 | Missing or invalid API key |
| E400 | 400 | Invalid service name |
| E500 | 500 | Service start/stop failed |
---
## Usage Patterns
### Start Service → Check Health
```bash
# Start MBE
curl -s -X POST "$API/api/v2/service/start" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe"}'
# Wait a few seconds
sleep 5
# Check health
curl -s "$API/api/v1/mbe/health"
```
### Stop Service → Verify Stopped
```bash
# Stop MBE
curl -s -X POST "$API/api/v2/service/stop" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe"}'
# Check health (should be offline)
curl -s "$API/api/v1/mbe/health"
```
### Restart Service
```bash
# Stop if running
curl -s -X POST "$API/api/v2/service/stop" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe"}'
# Wait for cleanup
sleep 3
# Start with new configuration
curl -s -X POST "$API/api/v2/service/start" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe", "port": 8080}'
```
---
## Configuration
### Default Settings
**MBE (llama-server)**:
- **Port**: 8080
- **Model**: `/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf`
- **mmproj**: `/Users/accusys/models/mmproj-F16.gguf`
- **Binary**: `/Users/accusys/llama.cpp/build/bin/llama-server`
**Launch Parameters**:
```bash
llama-server \
-m <model_path> \
--mmproj <mmproj_path> \
--host 0.0.0.0 \
--port 8080 \
-ngl 99 \
-c 8192 \
--temp 0.1 \
-b 4096 \
-ub 4096
```
### Environment Variables
The start process sets:
- `PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`
---
## Related Documentation
- [Health API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/02_health.md)
- [MarkBase Documentation](/Users/accusys/markbase/README.md)
- [LLM Services Guide](/Users/accusys/momentry_core/docs_v1.0/OPERATIONS/LLM_SERVICES/)
---
## Common Issues
### Service Fails to Start
**Symptoms**: `{"result": "failed", "error": "..."}`
**Possible Causes**:
1. Model file not found
2. Port already in use by another process
3. Insufficient permissions
4. Binary not found
**Solution**:
```bash
# Check model file exists
ls -la /Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf
# Check port availability
lsof -i :8080
# Check binary exists
ls -la /Users/accusys/llama.cpp/build/bin/llama-server
```
### Health Check Returns "offline"
**Symptoms**: `{"status": "offline"}`
**Possible Causes**:
1. Service not started
2. Service crashed after startup
3. Network/firewall issue
**Solution**:
```bash
# Start service
curl -s -X POST "$API/api/v2/service/start" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe"}'
# Check process status
ps aux | grep llama-server
# Check logs
tail -f ~/momentry_core/logs/momentry_3002.log
```
### Service Keeps Restarting
**Symptoms**: PID changes frequently, service unstable
**Possible Causes**:
1. Out of memory
2. Model too large
3. Hardware issue
**Solution**:
```bash
# Check memory usage
top -pid $(pgrep -f llama-server)
# Try smaller model or reduce parameters
curl -s -X POST "$API/api/v2/service/start" \
-H "X-API-Key: $KEY" \
-H "Content-Type: application/json" \
-d '{"name": "mbe", "model": "<smaller_model_path>"}'
```
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,397 @@
---
title: Monitor API
version: 1.0
date: 2026-10-24
author: Core Team
status: Active
---
<!-- module: monitor -->
<!-- description: Queue/Worker/Pipeline monitoring endpoints -->
<!-- depends: health -->
# Monitor API
Monitor Momentry's job queue, worker status, and processing pipeline in real-time.
## Overview
Monitor API provides endpoints for:
- **Queue Statistics**: Job counts by status
- **Running Jobs**: Detailed view of active jobs with processor progress
- **Worker Status**: System resources and worker process health
## Endpoints
### `GET /api/v1/monitor/queue_stats`
**Auth**: Required
**Scope**: system-level
Get job queue statistics grouped by status.
#### Request Parameters
None
#### Example
```bash
# Get queue statistics
curl -s "$API/api/v1/monitor/queue_stats" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"pending": 5,
"running": 2,
"completed": 150,
"failed": 3
}
```
| Field | Type | Description |
|-------|------|-------------|
| `pending` | number | Jobs waiting to be processed |
| `running` | number | Jobs currently being processed |
| `completed` | number | Jobs successfully completed |
| `failed` | number | Jobs that failed |
#### Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/monitor.rs`
**Database Query**:
```sql
SELECT status, COUNT(*) as count
FROM monitor_jobs
GROUP BY status
```
**Status Values**:
- `"pending"` - Queued for processing
- `"running"` - Currently being processed
- `"completed"` - Successfully finished
- `"failed"` - Processing failed
---
### `GET /api/v1/monitor/running_jobs`
**Auth**: Required
**Scope**: system-level
Get detailed information about currently running jobs, including processor progress.
#### Request Parameters
None
#### Example
```bash
# Get running jobs
curl -s "$API/api/v1/monitor/running_jobs" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"jobs": [
{
"job_id": 123,
"file_uuid": "384b0ff44aaaa1f1",
"file_name": "video.mp4",
"status": "running",
"started_at": "2026-10-24T15:30:00Z",
"duration_secs": 120,
"processors": [
{
"name": "asr",
"phase": 2,
"status": "running",
"progress": 75,
"duration": 45.3
},
{
"name": "face",
"phase": 2,
"status": "pending",
"progress": 0
}
]
}
]
}
```
| Field | Type | Description |
|-------|------|-------------|
| `jobs` | array | List of running jobs |
| `jobs[].job_id` | number | Job ID |
| `jobs[].file_uuid` | string | File UUID |
| `jobs[].file_name` | string | File name |
| `jobs[].status` | string | Job status (`"running"`) |
| `jobs[].started_at` | string | ISO 8601 timestamp |
| `jobs[].duration_secs` | number | Duration in seconds |
| `jobs[].processors` | array | List of processors for this job |
| `jobs[].processors[].name` | string | Processor type |
| `jobs[].processors[].phase` | number | Processing phase (1-4) |
| `jobs[].processors[].status` | string | Processor status |
| `jobs[].processors[].progress` | number | Progress percentage (0-100) |
| `jobs[].processors[].duration` | number | Duration in seconds (optional) |
#### Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/monitor.rs`
**Database Query**:
```sql
SELECT j.id, j.uuid, j.status, j.started_at, v.file_name
FROM monitor_jobs j
LEFT JOIN videos v ON v.file_uuid = j.uuid
WHERE j.status = 'running'
ORDER BY j.started_at DESC
```
**Processor Phases**:
| Phase | Processors | Description |
|-------|-----------|-------------|
| 1 | `cut` | Video segmentation |
| 2 | `asr`, `asr_asrx`, `face`, `ocr` | Core processing |
| 3 | `scene`, `face_trace`, `face_cluster` | Analysis & clustering |
| 4 | `tkg` | Knowledge graph |
---
### `GET /api/v1/monitor/worker_status`
**Auth**: Required
**Scope**: system-level
Get worker process status and system resource usage.
#### Request Parameters
None
#### Example
```bash
# Get worker status
curl -s "$API/api/v1/monitor/worker_status" \
-H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"cpu_percent": 45.5,
"gpu_percent": 60.0,
"memory_mb": 8192,
"memory_percent": 52.3,
"active_processors": 3,
"max_processors": 6,
"processors": [
{
"name": "asr",
"job_id": 123,
"status": "running"
},
{
"name": "face",
"job_id": 124,
"status": "running"
}
],
"worker_pid": 12345,
"uptime_secs": 3600,
"last_poll_at": "2026-10-24T15:30:00Z",
"poll_interval_secs": 5,
"is_alive": true
}
```
| Field | Type | Description |
|-------|------|-------------|
| `cpu_percent` | number | CPU usage percentage |
| `gpu_percent` | number | GPU utilization percentage |
| `memory_mb` | number | Memory used in MB |
| `memory_percent` | number | Memory usage percentage |
| `active_processors` | number | Number of active processors |
| `max_processors` | number | Maximum concurrent processors |
| `processors` | array | List of active processors |
| `processors[].name` | string | Processor type |
| `processors[].job_id` | number | Job ID being processed |
| `processors[].status` | string | Processor status |
| `worker_pid` | number | Worker process ID |
| `uptime_secs` | number | Worker uptime in seconds |
| `last_poll_at` | string | Last activity timestamp (optional) |
| `poll_interval_secs` | number | Expected poll interval |
| `is_alive` | boolean | Worker process is running |
#### Implementation Details
**File**: `/Users/accusys/momentry_core/src/api/monitor.rs`
**Data Sources**:
- System resources: `SystemResources::check()`
- Worker PID: `pgrep -f "momentry worker"`
- Active processors: `processor_results` table
- Last activity: `monitor_jobs` table
**Resource Monitoring**:
- CPU: System-wide usage
- GPU: Metal/ANE utilization (macOS)
- Memory: Used vs total memory
---
## Usage Patterns
### Dashboard Monitoring
```bash
# Get all monitoring data
curl -s "$API/api/v1/monitor/queue_stats" -H "X-API-Key: $KEY" | jq
curl -s "$API/api/v1/monitor/running_jobs" -H "X-API-Key: $KEY" | jq
curl -s "$API/api/v1/monitor/worker_status" -H "X-API-Key: $KEY" | jq
```
### Real-time Updates
```bash
# Poll every 5 seconds
watch -n 5 'curl -s "$API/api/v1/monitor/queue_stats" -H "X-API-Key: $KEY" | jq'
```
### Health Check
```bash
# Check if worker is alive
curl -s "$API/api/v1/monitor/worker_status" -H "X-API-Key: $KEY" | jq '.is_alive'
```
---
## Error Codes
| Code | HTTP | When |
|------|------|------|
| E401 | 401 | Missing or invalid API key |
| E500 | 500 | Database query failed |
---
## Database Tables
### `monitor_jobs`
Primary job queue table.
| Column | Type | Description |
|--------|------|-------------|
| `id` | integer | Job ID |
| `uuid` | string | File UUID |
| `status` | string | Job status |
| `started_at` | timestamp | Start time |
| `updated_at` | timestamp | Last update |
### `processor_results`
Processor execution results.
| Column | Type | Description |
|--------|------|-------------|
| `job_id` | integer | Job ID |
| `processor_type` | string | Processor name |
| `status` | string | Processor status |
| `progress_current` | integer | Current progress |
| `progress_total` | integer | Total steps |
| `duration_secs` | float | Duration in seconds |
---
## Related Documentation
- [Health API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/02_health.md)
- [Pipeline API](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/10_pipeline.md)
- [Job Management](/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/17_progress.md)
---
## Common Issues
### Worker Shows as Not Alive
**Symptoms**: `is_alive: false`
**Possible Causes**:
1. Worker process not running
2. Worker crashed
3. `pgrep` command failed
**Solution**:
```bash
# Check worker process
ps aux | grep momentry
# Start worker
momentry worker
# Check logs
tail -f ~/momentry_core/logs/worker_3002.log
```
### Queue Has Stuck Jobs
**Symptoms**: Jobs stuck in "running" status
**Possible Causes**:
1. Worker crashed
2. Processor timeout
3. Database lock
**Solution**:
```bash
# Check running jobs
curl -s "$API/api/v1/monitor/running_jobs" -H "X-API-Key: $KEY"
# Reset stuck jobs (requires database access)
# UPDATE monitor_jobs SET status = 'pending' WHERE status = 'running' AND updated_at < NOW() - INTERVAL '1 hour';
```
### High Resource Usage
**Symptoms**: `cpu_percent` or `memory_percent` very high
**Possible Causes**:
1. Too many concurrent jobs
2. Large video files
3. Memory leak
**Solution**:
```bash
# Check active processors
curl -s "$API/api/v1/monitor/worker_status" -H "X-API-Key: $KEY" | jq '.processors'
# Reduce max_processors if needed
# Restart worker
```
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-24 | Initial documentation |
@@ -0,0 +1,308 @@
---
title: Admin Config API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: admin_config -->
<!-- description: System configuration management -->
<!-- depends: 01_auth -->
## Admin Configuration
Admin configuration management for system-wide settings, VLM prompts, and runtime parameters.
### `GET /api/v1/admin/config`
**Auth**: Required
**Scope**: admin-level
Get the full system configuration. Returns all configuration parameters including VLM prompts, processing settings, and system defaults.
#### Example
```bash
curl -s "$API/api/v1/admin/config" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"vlm_prompts": {
"face_trace": {
"system_prompt": "Analyze the person's appearance...",
"user_prompt_template": "Describe this person..."
}
},
"processing": {
"default_processors": ["cut", "asr", "face"],
"face_min_confidence": 0.5,
"face_min_size": 30
},
"system": {
"max_concurrent_jobs": 3,
"output_dir": "/Users/accusys/momentry/output"
}
}
```
---
### `POST /api/v1/admin/config`
**Auth**: Required
**Scope**: admin-level
Partially update system configuration. Only provided fields are modified; others remain unchanged.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `processing` | object | No | Processing configuration |
| `system` | object | No | System configuration |
#### Example
```bash
curl -X POST "$API/api/v1/admin/config" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"processing": {
"face_min_confidence": 0.6
}
}'
```
#### Response (200)
```json
{
"success": true,
"message": "Config updated"
}
```
---
### `GET /api/v1/admin/config/vlm_prompts`
**Auth**: Required
**Scope**: admin-level
Get all VLM (Vision Language Model) prompts used for image analysis.
#### Example
```bash
curl -s "$API/api/v1/admin/config/vlm_prompts" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"face_trace": {
"system_prompt": "You are an expert in person appearance analysis...",
"user_prompt_template": "Describe the person in this image..."
},
"scene": {
"system_prompt": "You are a scene description expert...",
"user_prompt_template": "Describe the scene..."
}
}
```
---
### `GET /api/v1/admin/config/vlm_prompts/:key`
**Auth**: Required
**Scope**: admin-level
Get a specific VLM prompt by key.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `key` | string | Prompt key (e.g., "face_trace", "scene") |
#### Example
```bash
curl -s "$API/api/v1/admin/config/vlm_prompts/face_trace" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"system_prompt": "You are an expert in person appearance analysis...",
"user_prompt_template": "Describe the person in this image..."
}
```
#### Error Responses
| HTTP | When |
|------|------|
| `404` | Prompt key not found |
| `401` | Missing or invalid API key |
---
### `PUT /api/v1/admin/config/vlm_prompts/:key`
**Auth**: Required
**Scope**: admin-level
Update a specific VLM prompt. This affects all subsequent VLM analysis operations.
#### Request Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `system_prompt` | string | Yes | System prompt for the LLM |
| `user_prompt_template` | string | Yes | User prompt template (may include placeholders) |
#### Example
```bash
curl -X PUT "$API/api/v1/admin/config/vlm_prompts/face_trace" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"system_prompt": "You are an expert in fashion and appearance analysis...",
"user_prompt_template": "Analyze the person'\''s clothing and accessories in detail..."
}'
```
#### Response (200)
```json
{
"success": true,
"message": "Prompt 'face_trace' updated"
}
```
---
### `POST /api/v1/admin/config/reload`
**Auth**: Required
**Scope**: admin-level
Reload configuration from disk. Useful when the configuration file has been manually edited.
#### Example
```bash
curl -X POST "$API/api/v1/admin/config/reload" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"success": true,
"message": "Config reloaded"
}
```
---
### `GET /api/v1/admin/settings`
**Auth**: Required
**Scope**: admin-level
Alias for `/api/v1/admin/config`. Provided for frontend compatibility.
---
## Configuration Structure
### VLM Prompts
VLM prompts control how the system analyzes images and video frames:
| Prompt Key | Purpose | Used By |
|------------|---------|---------|
| `face_trace` | Person appearance description | Face trace processor |
| `scene` | Scene description | Scene VLM processor |
| `appearance` | Detailed appearance analysis | Appearance processor |
### Processing Settings
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `default_processors` | string[] | all | Default processors for new files |
| `face_min_confidence` | float | 0.5 | Minimum face detection confidence |
| `face_min_size` | integer | 30 | Minimum face size in pixels |
### System Settings
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `max_concurrent_jobs` | integer | 3 | Maximum parallel processing jobs |
| `output_dir` | string | - | Output directory path |
---
## Use Cases
### 1. Adjust Face Detection Sensitivity
```bash
curl -X POST "$API/api/v1/admin/config" \
-H "X-API-Key: $KEY" \
-d '{
"processing": {
"face_min_confidence": 0.7,
"face_min_size": 50
}
}'
```
### 2. Customize VLM Prompts
```bash
curl -X PUT "$API/api/v1/admin/config/vlm_prompts/face_trace" \
-H "X-API-Key: $KEY" \
-d '{
"system_prompt": "Focus on clothing colors and patterns",
"user_prompt_template": "Describe the person'\''s outfit..."
}'
```
### 3. Reload Configuration After Manual Edit
```bash
# Edit config file on disk
vim /path/to/config.json
# Reload into running system
curl -X POST "$API/api/v1/admin/config/reload" -H "X-API-Key: $KEY"
```
---
## Security Notes
- **Admin-only access**: All endpoints require admin-level authentication
- **Persistent changes**: Configuration changes persist across server restarts
- **Hot reload**: Changes take effect immediately without server restart
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,118 @@
---
title: Docs API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: docs -->
<!-- description: API documentation web server -->
<!-- depends: 01_auth -->
## Documentation Web Server
Web-based API documentation served by the server. Supports both static HTML and WASM-based interactive documentation.
### `GET /doc`
**Auth**: Not required
Redirect to WASM documentation.
#### Example
```bash
curl -L http://localhost:3002/doc
```
#### Response
301 Redirect → `/doc-wasm`
---
### `GET /doc-wasm`
**Auth**: Not required
Serve WASM-based interactive documentation.
#### Example
```bash
curl http://localhost:3002/doc-wasm
```
#### Response (200)
HTML page with WASM documentation viewer.
---
### `GET /doc-wasm/*file`
**Auth**: Not required
Serve WASM binary files and static assets for documentation.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file` | string | File path (e.g., "pkg/md_wasm_bg.wasm") |
#### Example
```bash
curl http://localhost:3002/doc-wasm/pkg/md_wasm_bg.wasm --output md_wasm_bg.wasm
```
#### Response (200)
Binary file with appropriate MIME type:
- `.wasm` → `application/wasm`
- `.js` → `application/javascript`
- `.css` → `text/css`
- `.md` → `text/markdown`
---
## Documentation Types
### WASM Documentation (Default)
- **Location**: `docs_v1.0/doc_wasm/`
- **Technology**: Rust WASM + pulldown-cmark
- **Features**: Interactive search, Mermaid diagrams, Material Design
- **Authentication**: Optional (configurable)
### Static Documentation
- **Location**: `docs_v1.0/API_WORKSPACE/` and `docs_v1.0/CLI_WORKSPACE/`
- **Format**: Markdown files
- **Served via**: WASM renderer
---
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `MOMENTRY_DOCS_DIR` | `{binary_dir}/docs_v1.0/doc_wasm` | Documentation root directory |
---
## Security
- **Path Traversal Protection**: Rejects paths containing `..` or `//`
- **Directory Restriction**: Only serves files within `MOMENTRY_DOCS_DIR`
- **No Authentication**: Documentation is public (unless protected by reverse proxy)
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,159 @@
---
title: Markbase Compat API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: markbase_compat -->
<!-- description: MarkBase compatibility layer for Studio -->
<!-- depends: 01_auth -->
## MarkBase Compatibility
Compatibility layer for MarkBase API, enabling Studio to access user data folders.
### `GET /api/v1/markbase/folders/:username`
**Auth**: Required
**Scope**: user-level
List all folders for a user.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `username` | string | User name |
#### Example
```bash
curl -s "$API/api/v1/markbase/folders/admin" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
[
{
"name": "Documents",
"parent": ""
},
{
"name": "Media",
"parent": ""
}
]
```
---
### `GET /api/v1/markbase/files/:username/:folder`
**Auth**: Required
**Scope**: user-level
List all files in a user's folder.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `username` | string | User name |
| `folder` | string | Folder name |
#### Example
```bash
curl -s "$API/api/v1/markbase/files/admin/Documents" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
[
{
"name": "video1.mp4",
"type": "file",
"size": 1048576,
"modified": "2026-10-25T10:00:00Z",
"is_dir": false
},
{
"name": "subfolder",
"type": "directory",
"size": 0,
"modified": "2026-10-25T09:00:00Z",
"is_dir": true
}
]
```
---
### `GET /api/v1/markbase/file/:username/:path`
**Auth**: Required
**Scope**: user-level
Get details or download a specific file.
#### Path Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `username` | string | User name |
| `path` | string | File path within user directory |
#### Example
```bash
curl -s "$API/api/v1/markbase/file/admin/Documents/video1.mp4" \
-H "X-API-Key: $KEY" \
--output video1.mp4
```
#### Response (200)
File content with appropriate MIME type.
---
## Directory Structure
```
var/studio/data/
├── {username}/
│ └── files/
│ ├── Documents/
│ │ ├── video1.mp4
│ │ └── video2.mp4
│ └── Media/
│ └── audio.mp3
```
---
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `MOMENTRY_STUDIO_DATA_DIR` | `{binary_dir}/var/studio/data` | Studio data directory |
---
## Compatibility Notes
- **Purpose**: Provides MarkBase-compatible API for Studio integration
- **Backward Compatibility**: Maintains existing Studio functionality
- **Future**: May be deprecated when Studio migrates to new API structure
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,244 @@
---
title: CLIP API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: clip -->
<!-- description: CLIP-based image classification and object detection -->
<!-- depends: 01_auth -->
## CLIP Vision Model
### `POST /api/v1/clip/classify`
**Auth**: Required
**Scope**: system-level
Classify an image against a list of text labels using CLIP (Contrastive Language-Image Pre-training). Returns top-k predictions with confidence scores.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `image_path` | string | Yes | - | Absolute path to the image file |
| `labels` | string | Yes | - | Comma-separated text labels (e.g., "dog,cat,car,person") |
| `top_k` | integer | No | 5 | Number of top predictions to return |
| `model` | string | No | default | CLIP model variant to use |
#### Example
```bash
curl -s -X POST "$API/api/v1/clip/classify" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/path/to/image.jpg",
"labels": "dog,cat,car,person,building",
"top_k": 3
}'
```
#### Response (200)
```json
{
"success": true,
"predictions": [
{
"label": "dog",
"confidence": 0.892
},
{
"label": "person",
"confidence": 0.073
},
{
"label": "cat",
"confidence": 0.021
}
]
}
```
| Field | Type | Description |
|-------|------|-------------|
| `success` | boolean | Operation success status |
| `predictions` | array | Array of label-confidence pairs, sorted by confidence (descending) |
| `label` | string | Text label |
| `confidence` | float | Confidence score (0.0-1.0) |
#### Error Responses
| HTTP | When |
|------|------|
| `400` | Invalid image path or labels |
| `401` | Missing or invalid API key |
| `500` | CLIP model inference error |
---
### `POST /api/v1/clip/detect`
**Auth**: Required
**Scope**: system-level
Detect specific objects in an image using zero-shot object detection. Returns detected objects with confidence scores above the threshold.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `image_path` | string | Yes | - | Absolute path to the image file |
| `objects` | string | Yes | - | Comma-separated object names to detect |
| `threshold` | float | No | 0.15 | Confidence threshold (0.0-1.0) |
| `model` | string | No | default | CLIP model variant to use |
#### Example
```bash
curl -s -X POST "$API/api/v1/clip/detect" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/path/to/scene.jpg",
"objects": "person,car,bicycle",
"threshold": 0.3
}'
```
#### Response (200)
```json
{
"success": true,
"detected": [
{
"label": "person",
"confidence": 0.921
},
{
"label": "car",
"confidence": 0.876
}
]
}
```
**Note**: Only objects with confidence >= `threshold` are returned. If no objects are detected, `detected` will be an empty array.
---
### `POST /api/v1/clip/batch`
**Auth**: Required
**Scope**: system-level
Batch classify multiple images against the same set of labels. Efficient for processing large image sets.
#### Request Parameters
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `image_paths` | string | Yes | - | Comma-separated absolute paths to image files |
| `labels` | string | Yes | - | Comma-separated text labels |
| `top_k` | integer | No | 5 | Number of top predictions per image |
| `model` | string | No | default | CLIP model variant to use |
#### Example
```bash
curl -s -X POST "$API/api/v1/clip/batch" \
-H "Content-Type: application/json" \
-H "X-API-Key: $KEY" \
-d '{
"image_paths": "/path/to/img1.jpg,/path/to/img2.jpg,/path/to/img3.jpg",
"labels": "indoor,outdoor,nature,urban",
"top_k": 2
}'
```
#### Response (200)
```json
{
"success": true,
"results": {
"/path/to/img1.jpg": [
{"label": "indoor", "confidence": 0.945},
{"label": "urban", "confidence": 0.032}
],
"/path/to/img2.jpg": [
{"label": "outdoor", "confidence": 0.876},
{"label": "nature", "confidence": 0.089}
],
"/path/to/img3.jpg": [
{"label": "nature", "confidence": 0.923},
{"label": "outdoor", "confidence": 0.054}
]
}
}
```
---
## Use Cases
### 1. Scene Classification
```bash
# Classify scene type
curl -X POST "$API/api/v1/clip/classify" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/output/video_frame.jpg",
"labels": "indoor,outdoor,day,night",
"top_k": 2
}'
```
### 2. Object Detection
```bash
# Detect people and vehicles
curl -X POST "$API/api/v1/clip/detect" \
-H "X-API-Key: $KEY" \
-d '{
"image_path": "/output/frame_001.jpg",
"objects": "person,car,bicycle,motorcycle",
"threshold": 0.3
}'
```
### 3. Batch Frame Analysis
```bash
# Analyze multiple video frames
curl -X POST "$API/api/v1/clip/batch" \
-H "X-API-Key: $KEY" \
-d '{
"image_paths": "/output/frame_001.jpg,/output/frame_002.jpg,/output/frame_003.jpg",
"labels": "action,dialogue,scenery",
"top_k": 1
}'
```
---
## Implementation Notes
- **Model**: Uses CLIP ViT-B/32 by default
- **Performance**: ~50ms per image on CPU, ~5ms on GPU
- **Supported Formats**: JPEG, PNG, WebP, BMP
- **Max Image Size**: 4K resolution (3840x2160)
- **Batch Limit**: Recommended max 100 images per batch
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,178 @@
---
title: Billing API
version: 1.0
date: 2026-10-25
author: Core Team
status: Active
---
<!-- module: billing -->
<!-- description: Token usage tracking and billing -->
<!-- depends: 01_auth -->
## Billing & Usage Tracking
Track LLM token usage across different services (Agent, VLM, TKG, etc.).
### `GET /api/v1/billing/usage`
**Auth**: Required
**Scope**: user-level
Get token usage for a specific billing period. Returns input/output token counts and service breakdown.
#### Query Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `period` | string | No | Current month | Billing period in YYYY-MM format |
#### Example
```bash
# Get current month usage
curl -s "$API/api/v1/billing/usage" -H "X-API-Key: $KEY"
# Get specific month
curl -s "$API/api/v1/billing/usage?period=2026-09" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"key_id": null,
"period": "2026-10",
"tokens": {
"input": 15234,
"output": 8921,
"total": 24155
},
"services": {
"agent": 8500,
"vlm": 12000,
"tkg": 3655
}
}
```
| Field | Type | Description |
|-------|------|-------------|
| `key_id` | string \| null | API key ID (null for user-level aggregate) |
| `period` | string | Billing period (YYYY-MM) |
| `tokens` | object | Token statistics |
| `tokens.input` | integer | Total input tokens |
| `tokens.output` | integer | Total output tokens |
| `tokens.total` | integer | Total tokens (input + output) |
| `services` | object | Token usage per service |
---
### `GET /api/v1/billing/history`
**Auth**: Required
**Scope**: user-level
Get token usage history for the past N months.
#### Query Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `months` | integer | No | 12 | Number of months to retrieve |
#### Example
```bash
# Get last 12 months
curl -s "$API/api/v1/billing/history" -H "X-API-Key: $KEY"
# Get last 6 months
curl -s "$API/api/v1/billing/history?months=6" -H "X-API-Key: $KEY"
```
#### Response (200)
```json
{
"periods": [
{
"key_id": null,
"period_month": "2026-10",
"total_input_tokens": 15234,
"total_output_tokens": 8921,
"total_tokens": 24155,
"service_breakdown": {
"agent": 8500,
"vlm": 12000,
"tkg": 3655
}
},
{
"key_id": null,
"period_month": "2026-09",
"total_input_tokens": 18234,
"total_output_tokens": 9456,
"total_tokens": 27690,
"service_breakdown": {
"agent": 10200,
"vlm": 13500,
"tkg": 3990
}
}
]
}
```
---
## Service Categories
| Service | Description | Token Type |
|---------|-------------|------------|
| `agent` | Agent chat, search, 5W1H | Input + Output |
| `vlm` | Vision Language Model (image analysis) | Input + Output |
| `tkg` | Temporal Knowledge Graph queries | Input + Output |
| `embedding` | Text embeddings | Input only |
| `chat` | General chat/completions | Input + Output |
---
## Use Cases
### 1. Monitor Current Month Usage
```bash
curl -s "$API/api/v1/billing/usage" -H "X-API-Key: $KEY" | jq '.tokens'
```
### 2. Generate Monthly Report
```bash
curl -s "$API/api/v1/billing/history?months=12" -H "X-API-Key: $KEY" | \
jq -r '.periods[] | "\(.period_month),\(.total_tokens)"'
```
### 3. Check Service Breakdown
```bash
curl -s "$API/api/v1/billing/usage" -H "X-API-Key: $KEY" | \
jq '.services | to_entries | sort_by(.value) | reverse | .[]'
```
---
## Billing Notes
- **Token counting**: Both input and output tokens are counted
- **Aggregation**: Usage is aggregated per user or per API key
- **Persistence**: Billing data persists across server restarts
- **Reset**: Billing periods reset monthly on the 1st
---
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0 | 2026-10-25 | Initial documentation |
@@ -0,0 +1,413 @@
---
title: Markbase Team - Storage & Protocol Layer
version: 1.0
date: 2026-10-25
author: Markbase Team
status: Active
---
# Markbase Team - Storage & Protocol Layer
Markbase team 負責 Momentry 系統的儲存層和協議層實現,提供企業級檔案伺服器和備份解決方案。
---
## 團隊角色
### 在 Core Team 架構中的定位
```
Momentry Core Team
├── Core Team (001-098) # 核心業務邏輯
│ ├── Auth API
│ ├── Health API
│ ├── Register API
│ ├── Identity API
│ ├── Search API
│ └── Media API
├── Markbase Team (099) # 儲存與協議層 ← 本團隊
│ ├── File Server (SMB/SFTP/WebDAV/S3)
│ ├── Protocol Implementation
│ ├── Storage Backend
│ └── Backup System
├── Pipeline Team (021-025) # 處理管線
├── Studio Team (201-204) # 前端工具
└── Tools Team (990-999) # 工具與測試
```
### 核心職責
| 職責領域 | 範圍 | 技術棧 |
|---------|------|--------|
| **協議實現** | SSH, SMB, SFTP, WebDAV, S3, NFS | Rust + Axum |
| **儲存後端** | LocalFS, S3, VFS Abstraction | Rust + SQLite |
| **檔案管理** | 上傳、下載、版本控制、快照 | Rust + ZFS-style |
| **備份系統** | 增量備份、時間機器、快照管理 | Rust + rsync protocol |
| **認證整合** | SQLite, LDAP, PostgreSQL | bcrypt + x25519 |
---
## 技術架構
### 多協議檔案伺服器
#### 協議支援矩陣
| 協議 | 狀態 | 性能 | 用途 |
|------|------|------|------|
| **SMB/CIFS** | ✅ 100% | ~30 MB/s | Windows/macOS 原生掛載 |
| **SFTP/SSH** | ✅ 100% | ~140 MB/s | 安全檔案傳輸 |
| **WebDAV** | ✅ 100% | ~20 MB/s | HTTP 檔案訪問 |
| **S3 API** | ✅ 100% | ~50 MB/s | 雲端儲存兼容 |
| **NFS** | ⏳ 90% | - | Unix/Linux 掛載 |
#### 性能優化
```rust
// Phase 1-4 性能優化
├── AES-256-GCM AEAD 加密 (2x 提升)
├── Rayon 並行加密 (4x 提升)
├── Zero-copy buffer reuse (10% 提升)
└── Vec 預分配 (4% 提升)
// 最終性能
初始: 712 KB/s (AES-128-CTR + HMAC)
優化後: 140 MB/s (AES-256-GCM + AES-NI) ⭐⭐⭐⭐⭐
```
### VFS 抽象層
#### 統一儲存接口
```rust
pub trait VfsBackend: Send + Sync {
// 檔案操作
fn open_file(&self, path: &Path, flags: OpenFlags) -> Result<Box<dyn VfsFile>>;
fn create_dir(&self, path: &Path) -> Result<()>;
fn remove_file(&self, path: &Path) -> Result<()>;
fn rename(&self, from: &Path, to: &Path) -> Result<()>;
// 快照與配額
fn create_snapshot(&self, name: &str) -> Result<VfsSnapshotInfo>;
fn set_quota(&self, quota: VfsQuota) -> Result<()>;
fn get_quota_usage(&self) -> Result<VfsQuotaUsage>;
// 壓縮與去重
fn compress_file(&self, path: &Path) -> Result<()>;
fn dedup_file(&self, path: &Path) -> Result<DedupStats>;
}
```
#### 後端實現
| 後端 | 特性 | 使用場景 |
|------|------|---------|
| **LocalFS** | 原生檔案系統,支援快照、配額、ACL | 本地儲存、NAS |
| **S3Vfs** | AWS S3 兼容,支援 Multipart Upload | 雲端儲存 |
| **SmbVfs** | SMB/CIFS 客戶端,支援 Oplocks | 遠端檔案伺服器 |
### SSH 伺服器實現
#### 完整協議棧
```
SSH-2.0 協議棧 (Phase 1-8 完成)
├── Version Exchange (SSH-2.0-MarkBaseSSH_1.0)
├── KEXINIT Negotiation (Curve25519-SHA256)
├── Curve25519 Key Exchange (x25519-dalek)
├── AES-256-GCM Encryption (AEAD)
├── Ed25519 Host Key (ed25519-dalek)
├── Password + Public Key Authentication
├── Channel Protocol (exec, shell, subsystem)
├── SFTP Protocol (v3)
├── SCP/rsync Protocol
└── Window Control + sshbuf zero-copy
```
#### 安全性
```
加密庫使用 (RustCrypto 官方庫)
├── x25519-dalek ⭐⭐⭐⭐⭐ Curve25519 密鑰交換
├── ed25519-dalek ⭐⭐⭐⭐⭐ Ed25519 伺服器簽名
├── aes ⭐⭐⭐⭐⭐ AES-256 加密 (AES-NI 硬體加速)
├── ctr ⭐⭐⭐⭐⭐ CTR 模式
├── hmac ⭐⭐⭐⭐⭐ HMAC-SHA256 MAC
└── bcrypt ⭐⭐⭐⭐⭐ 密碼雜湊
總體安全性: ⭐⭐⭐⭐⭐ 極高
OpenSSH 兼容性: ✅ 100% (通過 OpenSSH 7.7-10.2 測試)
```
### SMB 伺服器實現
#### SMB 3.x 功能
```
SMB 3.x 協議棧
├── SMB 2.0/2.1/3.0/3.1.1 支援
├── AES-128-CTR + HMAC-SHA256 加密
├── Oplocks + Lease (I/II/R/W)
├── Byte-range Lock
├── DFS Referral
├── Compound Request
└── macOS 兼容性 (Time Machine, AFP_AfpInfo)
ZFS-style 功能
├── Snapshots (copy-on-write)
├── Quotas (space/file limits)
├── Compression (ZSTD)
├── Deduplication (SHA-256)
├── RAID-Z (Reed-Solomon parity)
├── ACLs (NFSv4/SMB)
└── Previous Versions (@GMT- tokens)
```
### WebDAV 伺服器實現
#### RFC 標準支援
```
WebDAV 協議棧
├── RFC 4918 (WebDAV)
│ ├── PROPFIND (目錄列表)
│ ├── GET/PUT (檔案傳輸)
│ ├── MKCOL/DELETE (目錄操作)
│ ├── COPY/MOVE (檔案操作)
│ └── LOCK/UNLOCK (鎖定機制)
├── RFC 7232 (Conditional Requests)
│ ├── If-Match/If-None-Match
│ └── ETag generation
├── RFC 7233 (Range Requests)
│ ├── 206 Partial Content
│ └── Multipart ranges
└── 持久化鎖 + 死屬性持久化
```
---
## 與其他團隊的整合
### 與 Core Team 的整合
```
Markbase ←→ Core Team 整合點
├── 認證整合
│ ├── SqliteProvider (共享 auth.sqlite)
│ ├── LdapProvider (企業目錄服務)
│ └── DataProvider trait 統一接口
├── 檔案處理管線
│ ├── 上傳觸發處理
│ ├── WebDAV Upload Hook
│ └── 事件通知機制
└── 系統配置
├── AppConfig 統一配置
└── 環境變數覆蓋
```
### 與 Pipeline Team 的整合
```rust
// 上傳完成後觸發處理管線
pub struct UploadHook {
pub on_upload_complete: Box<dyn Fn(&Path) -> Result<()>>,
}
// WebDAV 上傳整合
impl VfsDavFs {
fn flush(&mut self) -> Result<()> {
// 1. Flush 到儲存層
// 2. 創建版本快照
// 3. 觸發 upload_hook → Pipeline Team
}
}
```
### 與 Studio Team 的整合
```
Web GUI 整合
├── Tauri 2.x 桌面應用
│ ├── User Management (DataProvider)
│ ├── Share Management (SMB/SFTP/WebDAV)
│ ├── Dashboard (系統統計)
│ └── File Manager (檔案瀏覽)
└── Vue.js 前端
├── Vuetify 組件
├── 動態路由
└── API 整合
```
---
## 部署架構
### 單機部署
```bash
# 標準部署
markbase-core web-start --port 11438
# 自動初始化
├── 自動檢測用戶 home 目錄
├── 自動創建 SQLite 數據庫
├── 預設 demo/demo123 用戶
└── 動態路徑配置
# 數據目錄結構
~/markbase/data/
├── auth.sqlite # 認證數據庫
├── demo/ # demo 用戶數據
├── users/ # 其他用戶數據
└── webdav_versions/ # WebDAV 版本控制
```
### 企業部署
```
企業級功能
├── LDAP 整合
│ ├── Active Directory 支援
│ ├── OpenLDAP 支援
│ └── 群組權限管理
├── NFS 整合
│ ├── NFSv3/NFSv4 協議
│ └── Unix/Linux 掛載
├── HA 叢集 (Phase 7)
│ ├── CTDB 叢集
│ ├── Raft 共識
│ └── 自動故障轉移
└── 監控與日誌
├── Prometheus metrics
├── Grafana dashboards
└── ELK 日誌分析
```
---
## 開發指南
### 快速開始
```bash
# 編譯
cargo build --release
# 運行測試
cargo test
# 啟動服務
./target/release/markbase-core web-start
# 訪問 API
curl http://localhost:11438/api/v2/health
```
### 協議測試
```bash
# SMB 測試
smbclient //localhost/markbase -U demo%demo123
# SFTP 測試
sftp -P 2024 demo@localhost
# WebDAV 測試
cadaver http://localhost:11438/webdav/
# SSH 測試
ssh -p 2024 demo@localhost "echo SSH_OK"
```
---
## 文檔資源
### 內部文檔
| 文檔 | 路徑 | 內容 |
|------|------|------|
| **AGENTS.md** | `/Users/accusys/markbase/AGENTS.md` | 開發指南、Phase 完成記錄 |
| **INSTALLATION.md** | `/Users/accusys/markbase/INSTALLATION.md` | 自動安裝說明 |
| **CoreDoc** | `https://coredoc.momentry.ddns.net` | API 文檔系統 |
### 設計文檔
```
docs/
├── SSH_PHASE1_IMPLEMENTATION.md
├── SSH_PHASE2_IMPLEMENTATION.md
├── SSH_PHASE3_COMPLETE.md
├── SSH_PHASE4_COMPLETE_SUMMARY.md
├── MACOS_COMPAT_DESIGN.md
├── CTDB_ARCHITECTURE_ANALYSIS.md
└── DOWNLOAD_CENTER_DIAGNOSIS.md
```
---
## 性能基準
### 最終性能數據
| 協議 | 傳輸速度 | 測試檔案 | 狀態 |
|------|---------|---------|------|
| **rsync** | 140 MB/s | 100MB | ✅ |
| **SCP** | 140 MB/s | 100MB | ✅ |
| **SFTP** | <1.7 MB/s | 協議開銷 | ⚠️ |
| **SMB** | ~30 MB/s | 100MB | ✅ |
| **WebDAV** | ~20 MB/s | 100MB | ✅ |
### 優化歷程
```
性能提升歷程
├── 初始狀態: 712 KB/s (AES-128-CTR + HMAC)
├── Phase 1: 5 MB/s (AES-256-GCM) ⭐⭐⭐⭐
├── Phase 4: 20 MB/s (並行加密) ⭐⭐⭐⭐⭐
├── Phase 2-3: 25 MB/s (零拷貝 + Buffer Pool)
└── 最終: 140 MB/s (全優化) ⭐⭐⭐⭐⭐
提升倍數: 196x (相較初始狀態)
對比 sftpgo (Go 實現): 140 MB/s vs 30 MB/s (超越 4.6x)
```
---
## 版本歷史
### v1.0 (2026-10-25)
- ✅ SSH 伺服器完整實現 (Phase 1-8)
- ✅ SMB 伺服器完整實現 (Phase 1-6)
- ✅ WebDAV 伺服器完整實現 (Phase 20-22)
- ✅ S3 API 支援 (Phase 1-3)
- ✅ VFS 抽象層
- ✅ ZFS-style 功能
- ✅ macOS 相容性
- ✅ 效能優化 (196x 提升)
- ✅ Web GUI (Phase 1-11)
### 未來計劃
| Phase | 功能 | 優先級 |
|-------|------|--------|
| **Phase 7** | CTDB 叢集 | P1 |
| **Phase 12** | SMB3 加密完整實現 | P0 |
| **Phase 13** | NFS 完整實現 | P1 |
| **Phase 14** | 效能監控與告警 | P2 |
---
## 團隊聯繫
- **項目路徑**: `/Users/accusys/markbase`
- **Git 倉庫**:
- m4minigitea.momentry.ddns.net/warren/markbase.git
- m5max128gitea.momentry.ddns.net/admin/markbase.git
- **服務端口**: 11438
- **API 文檔**: https://coredoc.momentry.ddns.net
---
**Markbase Team - 為 Momentry 提供企業級儲存解決方案** ⭐⭐⭐⭐⭐
@@ -0,0 +1,199 @@
# Studio Team API 變更指南
**Version**: 1.0
**Date**: 2026-07-26
**Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md`
**目標**: 通知 Studio team 後端 API 狀態欄位變更,Momentry Studio 前端需配合更新
---
## 1. 概述
後端已將檔案狀態從技術術語改為**功能導向**名稱。Studio team 的 `~/momentry_studio/` 前端顯示邏輯需要更新。
**影響範圍:**
- 後端 API:`/Users/accusys/momentry_core/src/api/files.rs`(Core team 已修改)
- Studio 前端:`~/momentry_studio/`(需 Studio team 更新)
---
## 2. 團隊職責
| 團隊 | 負責專案 | 目錄 |
|------|---------|------|
| **Core team** | Momentry Core 後端 | `~/momentry_core/` |
| **Studio team** | Momentry Studio 前端 | `~/momentry_studio/` |
| **Marcom team** | WordPress 網站 | `/Users/accusys/wordpress/` |
---
## 3. API 變更
### `/api/v1/file/{file_uuid}/sync-status` 回傳格式
**POST** `/api/v1/file/{file_uuid}/sync-status`
```json
{
"success": true,
"file_uuid": "4655a0ab3c077e30c12b2298c2750650",
"status": "face_mgmt_ready",
"processors_complete": 4,
"processors_total": 5,
"worker": {
"has_job": true,
"job_status": "pending",
"current_processor": null,
"progress_total": 7,
"progress_current": 7,
"completed_processors": ["cut", "asr", "face", "ocr", "pose", "asrx", "face_cluster"],
"failed_processors": [],
"updated_at": "2026-07-24T21:26:06"
}
}
```
**無 job 的檔案:**
```json
{
"success": true,
"file_uuid": "...",
"status": "registered",
"processors_complete": 0,
"processors_total": 5,
"worker": {
"has_job": false
}
}
```
### Worker 狀態說明
| 欄位 | 說明 |
|------|------|
| `has_job` | 是否有 monitor_job 紀錄 |
| `job_status` | pending / running / completed / failed |
| `current_processor` | 目前正在執行的 processor |
| `progress_total` | 總 processor 數量 |
| `progress_current` | 已完成的 processor 數量 |
| `completed_processors` | 已完成的 processor 列表 |
| `failed_processors` | 失敗的 processor 列表 |
| `updated_at` | 最後更新時間 |
### 使用者可區分的情境
| 情境 | `job_status` | `current_processor` | 顯示建議 |
|------|-------------|-------------------|---------|
| **正在處理** | `running` | `face` | 🔄 正在執行 Face |
| **排隊等待** | `pending` | `null` | ⏳ 等待處理 |
| **已完成** | `completed` | `null` | ✅ Processor 完成 |
| **處理失敗** | `failed` | `face` | ❌ Face 失敗 |
| **從未提交** | `has_job=false` | - | 📋 僅註冊 |
### 新狀態清單
| Status | 中文顯示 | 圖示 | 說明 |
|--------|---------|------|------|
| `registered` | 已註冊 | 📋 | 0 processor outputs |
| `scanning` | 掃描中 | 🔍 | 1-4/5 processor outputs |
| `keyword_ready` | 關鍵字可用 | 🔎 | sentence chunks > 0 |
| `semantic_ready` | 語意可用 | 🧠 | embedded chunks > 0 |
| `face_mgmt_ready` | 臉部管理可用 | 🎭 | trace_profiles + tkg_nodes > 0 |
| `agent_ready` | Agent 可用 | 🤖 | tkg_edges > 0 |
| `completed` | 已完成 | ✅ | 全部就緒 |
### 已移除的舊狀態
| 舊狀態 | 新狀態 |
|--------|--------|
| `pending` | `registered` |
| `processing` | `scanning` |
---
## 4. Studio 前端需修改項目
### 4.1 狀態顯示邏輯
**位置:** `~/momentry_studio/` 中處理檔案狀態顯示的元件
**修改前:**
```javascript
switch (file.status) {
case 'completed': return '✅ 已完成';
case 'processing': return '🔄 處理中';
case 'pending': return '⏳ 待處理';
default: return '📦 未註冊';
}
```
**修改後:**
```javascript
const statusMap = {
completed: { label: '已完成', icon: '✅', color: 'green' },
agent_ready: { label: 'Agent 可用', icon: '🤖', color: 'orange' },
face_mgmt_ready: { label: '臉部管理可用', icon: '🎭', color: 'cyan' },
semantic_ready: { label: '語意可用', icon: '🧠', color: 'purple' },
keyword_ready: { label: '關鍵字可用', icon: '🔎', color: 'green' },
scanning: { label: '掃描中', icon: '🔍', color: 'blue' },
registered: { label: '已註冊', icon: '📋', color: 'gray' },
};
const display = statusMap[file.status] || { label: '未註冊', icon: '📦', color: 'gray' };
return `${display.icon} ${display.label}`;
```
### 4.2 狀態過濾選項
**位置:** `~/momentry_studio/` 中檔案列表過濾元件
**移除:** `pending`, `processing`
**新增:** `registered`, `scanning`, `keyword_ready`, `semantic_ready`, `face_mgmt_ready`, `agent_ready`
---
## 5. Face Management Ready 明確定義
`face_mgmt_ready` 表示檔案已具備完整臉部管理功能,需同時滿足以下四個條件:
| 依賴項 | 檢查條件 | 說明 |
|--------|---------|------|
| **Face Qdrant Ready** | `_faces` collection 有 face points | Face embeddings 已存入 Qdrant |
| **Face Trace Ready** | `face_traced.json` 存在且有 traces | Face tracking 已完成 |
| **Face Profile Ready** | `trace_profiles` 有紀錄 | Profile 資料已建立 |
| **Face TKG Node Ready** | `tkg_nodes` 有 `face_track` nodes | TKG 圖譜節點已建立 |
---
## 6. 狀態依賴關係
```
registered → scanning → keyword_ready → semantic_ready
↓
face_mgmt_ready → agent_ready → completed
```
---
## 7. 測試 API
```bash
# 取得所有檔案
curl http://localhost:3002/api/v1/files \
-H "Authorization: Bearer <api_key>"
# 觸發狀態同步
curl -X POST http://localhost:3002/api/v1/file/{file_uuid}/sync-status \
-H "Authorization: Bearer <api_key>"
```
---
## 8. 參考文件
| 文件 | 完整路徑 |
|------|---------|
| People API | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md` |
| Status Unification | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/20_status_unification.md` |
| Studio Team Guide | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md` |
| AGENTS.md | `/Users/accusys/momentry_core/AGENTS.md` |
@@ -0,0 +1,207 @@
# Studio Team 配套修改指南
**Version**: 1.0
**Date**: 2026-07-26
**Doc Path**: `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md`
**目標**: 通知 Studio team 後端 Pipeline 狀態變更,前端需配合更新
---
## 1. 概述
後端已完成以下修改:
1. 移除 `identity_agent`,替換為 `face_dedup`(Face Deduplication)
2. 重構 `sync_file_status` 邏輯:檢查 JSON 存在 + DB 一致性
3. Pipeline 進度階段重新分配
**影響範圍:**
- 檔案狀態顯示(status)
- Pipeline 進度顯示(progress stages)
- 統計 API 回傳格式
---
## 2. 檔案狀態變更
### 新狀態清單
| Status | 中文顯示 | 圖示 | 說明 |
|--------|---------|------|------|
| `registered` | 已註冊 | 📋 | 尚未開始處理 |
| `scanning` | 掃描中 | 🔍 | 處理中(JSON 存在但 DB 不一致) |
| `completed` | 已完成 | ✅ | 所有 processor 完成且 DB 一致 |
| `agent_ready` | Agent 可用 | 🤖 | TKG edges 存在 |
### 已移除的狀態
| 舊狀態 | 新狀態 | 說明 |
|--------|--------|------|
| `processing` | `scanning` | 更明確表示正在處理 |
| `pending` | `registered` | 尚未開始 |
| `face_mgmt_ready` | `completed` | 最終狀態統一為 completed |
### 狀態判斷邏輯
| 條件 | 狀態 |
|------|------|
| 所有 JSON 存在且 DB 一致 | `completed` |
| 部分 JSON 存在但不一致 | `scanning` |
| 無 JSON 存在 | `registered` |
| TKG edges 存在 | `agent_ready` |
---
## 3. Pipeline 進度階段變更
### 修改前(7 個 stage)
```
Processors (30%) → Rule1 (5%) → Face Tracing (5%) → identity_agent (10%) → TKG Nodes (20%) → TKG Edges (15%) → Rule2 (15%)
```
### 修改後(7 個 stage)
```
Processors (30%) → Rule1 (5%) → Face Tracing (5%) → face_dedup (10%) → TKG Nodes (20%) → TKG Edges (15%) → Rule2 (15%)
```
### 需要修改的前端元件
| 元件 | 修改內容 |
|------|---------|
| Pipeline Progress Bar | 移除 `identity_agent`,新增 `face_dedup` |
| Stage Labels | 更新 stage 名稱 |
| Overall Progress | 重新計算權重 |
---
## 4. API 變更
### `/api/v1/file/{file_uuid}/sync-status`
**回傳格式變更:**
**修改前:**
```json
{
"status": "face_mgmt_ready",
"processors_complete": 5,
"processors_total": 5,
"worker": { ... }
}
```
**修改後:**
```json
{
"success": true,
"file_uuid": "...",
"status": "completed",
"processors": {
"asr": { "json_exists": true, "consistent": true },
"asrx": { "json_exists": true, "consistent": true },
"ocr": { "json_exists": true, "consistent": true },
"pose": { "json_exists": true, "consistent": true },
"cut": { "json_exists": true, "consistent": true },
"face": { "json_exists": true, "consistent": true },
"face_cluster": { "json_exists": true, "consistent": true }
},
"worker": { ... }
}
```
### `/api/v1/file/{file_uuid}/stats`
**回傳格式變更:**
**修改前:**
```json
{
"identity_agent": {
"clusters": 0,
"identities_created": 0,
"tmdb_matches": 0,
"speaker_bindings": 0,
"confirmations": 0
}
}
```
**修改後:**
```json
{
"face_dedup": {
"clusters": 5,
"face_tracks": 24,
"consistent": true
}
}
```
---
## 5. Studio 前端需修改項目
### 5.1 狀態顯示邏輯
**位置:** Studio 前端檔案列表元件
**修改前:**
```javascript
const statusLabels = {
'completed': '✅ 已完成',
'processing': '🔄 處理中',
'pending': '⏳ 待處理',
'face_mgmt_ready': '🎭 臉部管理可用',
'agent_ready': '🤖 Agent 可用'
};
```
**修改後:**
```javascript
const statusLabels = {
'completed': '✅ 已完成',
'scanning': '🔍 掃描中',
'registered': '📋 已註冊',
'agent_ready': '🤖 Agent 可用'
};
```
### 5.2 Pipeline 進度顯示
**位置:** Studio 前端 Pipeline Progress 元件
**修改項目:**
1. 移除 `identity_agent` stage
2. 新增 `face_dedup` stage
3. 更新 stage 名稱映射
### 5.3 統計面板
**位置:** Studio 前端檔案統計面板
**修改項目:**
1. 移除 `Identity Agent` 區塊
2. 新增 `Face Deduplication` 區塊
3. 顯示欄位:`clusters`, `face_tracks`, `consistent`
---
## 6. 測試清單
- [ ] 檔案列表狀態顯示正確
- [ ] Pipeline 進度階段正確顯示
- [ ] Overall Progress 計算正確
- [ ] 統計面板 Face Dedup 區塊顯示正確
- [ ] sync-status API 回傳格式解析正確
- [ ] stats API 回傳格式解析正確
---
## 7. 參考文件
| 文件 | 完整路徑 |
|------|---------|
| Studio Team Guide | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/21_studio_team_guide.md` |
| People API | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md` |
| Pipeline Changes | `/Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/22_studio_pipeline_changes.md` |
@@ -0,0 +1,114 @@
# Studio Fix: Face Group Name 讀寫不一致
**Date**: 2026-07-27
**Author**: Studio Team
**Status**: ✅ 已修復並部署
---
## 問題描述
Studio 前端在 Face 頁面 rename group name 後,離開再回來時名稱未更新。但 People Search 可以查到新名稱。
### 根因
**寫入**和**讀取**走了不同的資料來源:
| 操作 | API Endpoint | 實際讀寫欄位 |
|------|-------------|------------|
| **寫入 (rename)** | `PUT /api/v1/trace-profile/group` | `trace_profiles.name` |
| **讀取 (卡片顯示)** | `GET /api/v1/file/:uuid/face-groups` | `tkg_nodes.label` |
`trace_profiles.name` 和 `tkg_nodes.label` 是兩張獨立的表/欄位(見 `19_people_api.md`),rename 只更新了 `trace_profiles.name`,但卡片顯示讀的是 `tkg_nodes.label`。
---
## 修復內容
### 修改檔案
`/Users/accusys/momentry_core/src/api/profile.rs` — `get_face_groups_handler` (line 552-591)
### 改前 SQL
```sql
SELECT label, properties FROM tkg_nodes
WHERE file_uuid = $1 AND node_type = 'face_track'
ORDER BY (properties->>'trace_id')::int
```
### 改後 SQL
```sql
SELECT COALESCE(tp.name, tn.label) as name, tn.properties
FROM tkg_nodes tn
LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid
AND tp.trace_id = (tn.properties->>'trace_id')::int
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'
ORDER BY (tn.properties->>'trace_id')::int
```
### Rust 程式碼變更
```diff
pub async fn get_face_groups_handler(...) {
let tkg_table = schema::table_name("tkg_nodes");
+ let tp_table = schema::table_name("trace_profiles");
let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
- "SELECT label, properties FROM {} \
- WHERE file_uuid = $1 AND node_type = 'face_track' \
- ORDER BY (properties->>'trace_id')::int",
- tkg_table
+ "SELECT COALESCE(tp.name, tn.label) as name, tn.properties \
+ FROM {} tn \
+ LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
+ AND tp.trace_id = (tn.properties->>'trace_id')::int \
+ WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
+ ORDER BY (tn.properties->>'trace_id')::int",
+ tkg_table, tp_table
))
...
- for (label, properties) in rows {
+ for (name, properties) in rows {
...
- if label.starts_with("Face Trace ") || label.starts_with("Trace ") {
+ if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
unassigned.push(trace_id);
} else {
- groups.entry(label).or_default().push(trace_id);
+ groups.entry(name).or_default().push(trace_id);
}
}
}
```
---
## 影響範圍
| 項目 | 影響 |
|------|------|
| **Face 頁面卡片顯示** | ✅ 現在從 `trace_profiles.name` 讀取,rename 後立即生效 |
| **People Search** | 不受影響(本來就查 `trace_profiles.name`) |
| **未命名 traces** | 不受影響(`COALESCE` fallback 到 `tkg_nodes.label`,如 `Person_0`) |
| **Cluster Agent 初始化** | 不受影響(初始化時兩邊都寫入相同值) |
---
## 注意事項(給 Core Team)
1. **未來如果有需要同時更新 `tkg_nodes.label` 的情境**(例如 graph 顯示需要),請注意 `PUT /api/v1/trace-profile/group` 目前只更新 `trace_profiles.name`
2. **建議**:如果 `tkg_nodes.label` 和 `trace_profiles.name` 應該保持一致,可以考慮:
- 方案 A(目前做法):讀取端用 `COALESCE` 優先取 `trace_profiles.name`
- 方案 B:寫入端同時更新兩個欄位(需要改 `update_trace_profile_group_handler`)
3. **`merge_groups_handler`** 目前同時更新 `trace_profiles.name` 和 `tkg_nodes.label`(line 278-310),行為正確,不需要改
---
## 驗證
```bash
# 測試 face-groups endpoint 正確回傳 rename 後的名稱
curl -s "http://localhost:3002/api/v1/file/4655a0ab3c077e30c12b2298c2750650/face-groups" \
-H "X-API-Key: <key>" | jq '.face_groups[] | {name, trace_count}'
# 預期輸出包含 "Susan"(已 rename 的 group)
# { "name": "Susan", "trace_count": 7 }
```
@@ -0,0 +1,138 @@
# Studio Bug Report: `get_trace_profile` 讀寫不一致
**Date**: 2026-07-27
**Author**: Studio Team
**Status**: 🔴 待修復
**Priority**: High
---
## 問題描述
Studio 前端 rename face group 後,離開再回來選同一個檔案,名稱變回舊的。
## 影響
使用者 rename 的變更無法持久顯示。雖然 `trace_profiles.name` 已更新,但 `get_trace_profile` API 回傳的是舊的 `tkg_nodes.label`,導致前端 `loadClusterNames()` 用舊名覆蓋新名。
---
## 測試驗證
### 1. Rename
```bash
curl -X PUT "http://localhost:3002/api/v1/trace-profile/group" \
-H "X-API-Key: $KEY" -H "Content-Type: application/json" \
-d '{"file_uuid": "9cbeb112fcc5452e869755a539478061", "trace_ids": [1], "name": "SusanTest"}'
```
回傳:`{"success": true, "updated_count": 1}` ✅
### 2. 讀取單筆 profile(❌ 仍是舊名)
```bash
GET /api/v1/trace-profile?file_uuid=...&trace_id=1
```
回傳:`{"name": "Person_0"}` ← **錯誤,應為 "SusanTest"**
### 3. 讀取 face groups(✅ 是新名)
```bash
GET /api/v1/file/{uuid}/face-groups
```
回傳:`{"name": "SusanTest", "trace_ids": [1]}` ← **正確**
---
## 根因分析
### 寫入路徑(正確)
`PUT /api/v1/trace-profile/group` → `update_trace_profile_group_handler`(profile.rs:228):
```sql
UPDATE trace_profiles SET name = $1 WHERE file_uuid = $2 AND trace_id = $3
```
寫入 `trace_profiles.name` ✅
### 讀取路徑 — 單筆(❌ 錯誤)
`GET /api/v1/trace-profile` → `get_trace_profile_handler`(profile.rs:78-81):
```sql
SELECT label, external_id, properties FROM tkg_nodes
WHERE file_uuid = $1 AND node_type = 'face_track'
AND (external_id = $2 OR external_id = $3)
```
讀取 `tkg_nodes.label`,**沒有 JOIN `trace_profiles`** ❌
### 讀取路徑 — 群組(✅ 正確)
`GET /api/v1/file/{uuid}/face-groups` → `get_face_groups_handler`(profile.rs:560-566):
```sql
SELECT COALESCE(tp.name, tn.label) as name, tn.properties
FROM tkg_nodes tn
LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid
AND tp.trace_id = (tn.properties->>'trace_id')::int
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track'
```
使用 `COALESCE(tp.name, tn.label)`,優先取 `trace_profiles.name` ✅
---
## 前端影響流程
```
User rename group → updateTraceProfileGroup() → PUT /trace-profile/group
→ trace_profiles.name = "SusanTest" ✅
User refresh → loadClusterResults() → GET /face-groups
→ cluster.name = "SusanTest" ✅
→ loadClusterNames() → GET /trace-profile
→ profile.name = "Person_0" ❌ (tkg_nodes.label)
→ c.name = profile.name → "Person_0" ❌ 覆蓋了新名
```
---
## 建議修復
### 方案:改 `get_trace_profile_handler` 使用 JOIN
```rust
pub async fn get_trace_profile_handler(...) {
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
let row: Option<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, tn.properties \
FROM {} tn \
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
AND tp.trace_id = (tn.properties->>'trace_id')::int \
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
AND (tn.external_id = $2 OR tn.external_id = $3)",
tkg_table, tp_table
))
.bind(&params.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.fetch_optional(state.db.pool())
.await?;
let (name, _ext_id, properties) = row.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(TraceProfile {
file_uuid: params.file_uuid,
trace_id: params.trace_id,
name, // 改為使用 JOIN 後的 name
// ... 其他欄位不變
}))
}
```
### 一致性保證
| API | 讀取欄位 | 修復後 |
|-----|---------|--------|
| `PUT /trace-profile/group` | 寫入 `trace_profiles.name` | 不變 |
| `GET /trace-profile` | ~~`tkg_nodes.label`~~ → `COALESCE(tp.name, tn.label)` | ✅ 一致 |
| `GET /file/{uuid}/face-groups` | `COALESCE(tp.name, tn.label)` | 不變 |
---
## 相關文件
- `18_profile.md` — Profile API 文件
- `19_people_api.md` — People API 文件
- `23_studio_face_group_name_fix.md` — Studio face-groups JOIN 修復
@@ -166,7 +166,7 @@ These endpoints are defined in source code but not mounted in the router:
| Endpoint | Notes |
|----------|-------|
| `/api/v1/search/persons` | Defined but not mounted |
| `/api/v1/search/people` | ✅ Mounted |
| `/api/v1/who` | Defined but not mounted |
| `/api/v1/who/candidates` | Defined but not mounted |
@@ -179,7 +179,7 @@ These endpoints are defined in source code but not mounted in the router:
| Undocumented | 3 (resource management) |
| Partially documented | 5 (5W1H ×3, identity agent ×2) |
| Stub/not functional | 5 (visual search) |
| Defined but unmounted | 3 (persons, who, who/candidates) |
| Defined but unmounted | 2 (who, who/candidates) |
| **Total** | **16** |
---
+7
View File
@@ -0,0 +1,7 @@
# Test
This is a test.
<script>
console.log('=== TEST: This is from markdown file ===');
</script>