Files
momentry_core/AGENTS.md
T

46 KiB
Raw Blame History

AGENTS.md - Momentry Core

Rust-based digital asset management system with video analysis and RAG capabilities.


⚠️ CRITICAL: 開發隔離原則

絕對禁止事項

  • 絕對不可修改 /Users/accusys/wordpress/ 目錄下的任何檔案
  • 絕對不可修改 n8n 工作流或設定
  • 絕對不可修改 WordPress 或 n8n 的資料庫 table
  • 除非是 release 作業,絕對不可動 port 3002 (production)
  • 🔴 DELETE / REMOVE / DROP / CLEAR 任何資料前必須先問使用者「要刪嗎?」獲得明確同意後才能執行
  • 🔴 Qdrant collection 刪除、DB truncate、檔案刪除、資料清空 — 一律要先問
  • 🔴 不確定是否該刪 → 先問,不要自己決定
  • 🔴 任何會移除資料的動作(unregister、DELETE、DROP、truncate、rm 檔案)都必須先詢問確認,絕對不可自行執行
  • 🔴 改變議題前必須先存檔紀錄:使用 todowrite 工具或建立紀錄文件(如 docs_v1.0/M4_workspace/YYYY-MM-DD_topic_handoff.md),確保上下文不丟失

開發範圍界定

範圍 狀態 說明
~/momentry_core/ ✅ 可開發 Momentry Core 後端(Rust),Core team 負責
~/momentry_core/portal/ ⚠️ 僅供測試 Tauri Portal 僅用於測試,非正式前端
~/momentry_studio/ ❌ 禁止修改 Momentry Studio 前端,Studio team 負責
/Users/accusys/wordpress/ ❌ 禁止修改 WordPress 網站僅供參考,已被 Studio 取代
n8n 工作流 ❌ 禁止修改 自動化流程,與 dev 無關
WordPress/n8n 資料庫 table ❌ 禁止修改 Marcom 團隊管理,與 dev 無關

團隊職責劃分

團隊 負責專案 目錄
Core team Momentry Core 後端 ~/momentry_core/
Studio team Momentry Studio 前端 ~/momentry_studio/
Marcom team WordPress 網站(已停用) /Users/accusys/wordpress/

開發環境

服務 Port 用途 命令 狀態
Playground 3003 開發環境 (暫停) cargo run --bin momentry_playground -- server 🔴 已暫停 (節省 memory)
Production 3002 開發 + 生產環境 cargo run -- server 🟢 運行中 (debug binary)
Portal (Tauri) 1420 前端開發 npm run tauri dev -

注意 (2026-07-25): Playground (3003) 已暫停服務。Production (3002) 改為直接用於開發測試。新功能可直接部署至 3002。 注意 (2026-07-23): 為節省記憶體,Playground (3003) 已關閉。Production (3002) 目前使用 debug binary 運行(已套用 smart_search 修復)。正式 release 時需重新 build release binary。

日誌與啟動

服務 日誌路徑 啟動方式
Production (3002) logs/momentry_3002.log launchd (com.momentry.server + com.momentry.worker)
Playground (3003) logs/momentry_3003.log ./run-server-3003.sh
Worker / 歷史 logs/worker_3002.log 由 launchd worker 寫入

注意: 所有伺服器日誌統一存放於專案內 logs/ 目錄。 Production (3002) 正式部署由 launchd 管理(~/Library/LaunchAgents/com.momentry.server.plist + com.momentry.worker.plist),兩者皆使用 target/release/momentry,KeepAlive 自動重啟。run-server-3002.sh 僅供開發時臨時手動啟動(會與 launchd 衝突,勿與 launchd 並用)。 ⚠️ 啟動 launchd worker 若未註冊:launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.momentry.worker.plist(不是 load),worker plist 的 VLM 指向 gemma 8080(8091 已停用)。

⚠️ 交叉污染防制 (Cross-Contamination Prevention)

每個執行前必須評估是否會汙染其他獨立作業。

Scope Isolation Matrix

執行內容 允許的 Scope 禁止影響 檢查事項
M4 delivery binary target/release/momentry Playground (3003), Production (3002) 確認舊 process 未被誤殺
Playground server localhost:3003, dev.* schema Production (3002), public.* schema DATABASE_SCHEMA=dev
Production deploy localhost:3002, public.* schema Playground (3003), dev.* schema 先停 production,不影響 playground
Git commit 只包含意圖修改的檔案 無關的 untracked files git status 確認 stage 內容正確
CI / packaged tests 測試環境 正式資料 測試用 DB 不能連到 production
Doc changes 指定文件 其他文件、程式碼 git diff --stat 檢查 scope
SQL migration 目標 schema 其他 schema、無關 table WHERE clause 要精準
sed / grep / mass edit 目標檔案集 非目標檔案 先用 grep -c 確認只有目標檔案匹配

Recent Violations / Near-Misses

事件 問題 防止方式
sed API doc 編號 sed -i '' 's/.../.../g' 改到所有行 先 grep -c 確認匹配,git diff 再提交
亂加 /api/v1/register route 不必要的 API 別名,汙染路由表 角色切換:路由設計不該由實作方決定
API_WORKSPACE/ vs GUIDES/ vs REFERENCE/ vs DESIGN/ vs OPERATIONS/ vs INTEGRATIONS/ 文件放到錯誤分類 API 文件改在 API_WORKSPACE/modules/ 編輯,make deploy 生成到 GUIDES/
Build release binary in plan mode 浪費時間,無意義 嚴格遵守 plan/build mode 規定

⛔ 嚴格測試隔離規則 (Strict Test Isolation)

  • 所有測試 (Test) 必須在 Dev (3003) 進行。
  • 絕對禁止 (ABSOLUTELY FORBIDDEN) 在任何測試指令、Demo 流程或 API 檢查中使用 localhost:3002。
  • 即使是「測試 Unregister」或「檢查版本」,若未明確標示為 "Production Deployment",一律視為違規。
  • 預設行為: 所有 curl, CLI, 或程式碼測試指令,預設 URL 必須為 http://localhost:3003。

違反後果

  • 修改 WordPress/n8n 可能影響 marcom 團隊工作與生產環境
  • 修改 WordPress/n8n 資料庫 table 可能破壞自動化流程與資料完整性
  • 修改 port 3002 可能中斷正在使用的服務 (這是非常嚴重的錯誤)
  • 所有 dev 測試必須在 playground (3003) 進行

AI Coding Principles (Karpathy-Inspired)

Behavioral guidelines to reduce common LLM coding mistakes. Source: andrej-karpathy-skills (94K stars)

Tradeoff: These guidelines bias toward caution over speed. For trivial tasks, use judgment.

1. Think Before Coding

Don't assume. Don't hide confusion. Surface tradeoffs.

  • State your assumptions explicitly. If uncertain, ask.
  • If multiple interpretations exist, present them - don't pick silently.
  • If a simpler approach exists, say so. Push back when warranted.
  • If something is unclear, stop. Name what's confusing. Ask.

2. Simplicity First

Minimum code that solves the problem. Nothing speculative.

  • No features beyond what was asked.
  • No abstractions for single-use code.
  • No "flexibility" or "configurability" that wasn't requested.
  • No error handling for impossible scenarios.
  • If you write 200 lines and it could be 50, rewrite it.

Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.

3. Surgical Changes

Touch only what you must. Clean up only your own mess.

When editing existing code:

  • Don't "improve" adjacent code, comments, or formatting.
  • Don't refactor things that aren't broken.
  • Match existing style, even if you'd do it differently.
  • If you notice unrelated dead code, mention it - don't delete it.

When your changes create orphans:

  • Remove imports/variables/functions that YOUR changes made unused.
  • Don't remove pre-existing dead code unless asked.

The test: Every changed line should trace directly to the user's request.

4. Goal-Driven Execution

Define success criteria. Loop until verified.

Transform tasks into verifiable goals:

  • "Add validation" -> "Write tests for invalid inputs, then make them pass"
  • "Fix the bug" -> "Write a test that reproduces it, then make it pass"
  • "Refactor X" -> "Ensure tests pass before and after"

For multi-step tasks, state a brief plan:

1. [Step] -> verify: [check]
2. [Step] -> verify: [check]
3. [Step] -> verify: [check]

Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.


These guidelines are working if: fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.


Terminology (V4.0)

Term Scope Description Example
file_uuid Video file Video file identifier (renamed from video_uuid) 384b0ff44aaaa1f1
identity_uuid Global identity Global person identity (cross-file) a9a90105-6d6b-46ff-92da-0c3c1a57dff4
face_id Single detection Single face detection (frame-level) face_100
trace_id Face tracking Face tracking ID (Face Tracker output) 2
chunk_id Sentence chunk Sentence chunk (from pre_chunks via rules) chunk_1
speaker_id Speaker segment Speaker ID (from ASRX) SPEAKER_0
person_id ❌ Deprecated Video-local person ID (removed in V4.0) -

Architecture (V4.0)

Face → Identity (Two-layer, direct binding)
  ↓
  person_identities table: REMOVED
  file_identities table: ADDED (N:N relationship)

Key Changes (V3.x → V4.0)

Change V3.x V4.0
video_uuid Used everywhere file_uuid
person_identities Required (303 records) Removed
person_id APIs 28 endpoints Removed (except register/bind)
Face binding Person → Identity Face → Identity (direct)
Chunk binding Manual Auto (time alignment)

Build & Run Commands

# Build project (use debug builds for development/testing)
cargo build
cargo build --bin momentry
cargo build --bin momentry_playground

# Build all binaries
cargo build --bins

# Run CLI
cargo run -- --help
cargo run -- register /path/to/video.mp4
cargo run -- server --host 0.0.0.0 --port 3002

# Run playground (development binary)
cargo run --bin momentry_playground -- server
cargo run --bin momentry_playground -- --help

# Start servers (recommended — production via launchd, dev via scripts)
# Production (3002) is managed by launchd: com.momentry.server + com.momentry.worker
#   launchctl start gui/$(id -u)/com.momentry.server
#   launchctl start gui/$(id -u)/com.momentry.worker
# (run-server-3002.sh is dev-only and conflicts with launchd — do NOT mix)
./run-server-3003.sh

Server Logs

All runtime logs are centralized in logs/:

# View real-time logs
tail -f logs/momentry_3002.log
tail -f logs/momentry_3003.log

# Check recent errors
grep -i "error\|panic\|FAIL" logs/momentry_*.log | tail -20

⚠️ CRITICAL: cargo build --release PROHIBITION

  • NEVER run cargo build --release unless the user explicitly says "release the binary" or "正式 release"
  • cargo build --release is SLOW and only needed when producing a production binary for deployment
  • For all development, testing, debugging, and linting: use cargo build or cargo check
  • If uncertain, ALWAYS ask the user first

Binaries

Binary Purpose Port Redis Prefix Environment
momentry Production 3002 momentry: .env
momentry_playground Development 3003 momentry_dev: .env.development
momentry_player Video player - - -

LLM Services

環境一致性原則

生產環境 (port 3002) 與 Playground (port 3003) 使用相同的 LLM/VLM/Embedding 服務。

LLM Configuration

用途 Model 服務 Port API 格式
Chat / Summary / VLM gemma-4-12b-it llama.cpp 8080 /v1/chat/completions
Embedding embeddinggemma-300m Python 11436 Custom

統一服務:Gemma4 + mmproj 同時支援文字與視覺輸入,簡化配置並節省記憶體。

⚠️ 重要:Gemma4 多模態配置

Gemma 4-12b 是多模態模型,支援視覺輸入,需要正確配置:

  1. mmproj 檔案:

    • 檔案:/Users/accusys/models/mmproj-F16.gguf (167MB)
    • 從 HuggingFace 下載:https://huggingface.co/unsloth/gemma-4-12b-it-GGUF
    • 必須載入才能處理圖片輸入
  2. llama.cpp 版本要求:

    • ✅ 需要最新版本(支援 gemma4uv projector type)
    • ❌ 2026年5月之前的版本不相容
    • 若遇到 "unknown projector type: gemma4uv" 錯誤 → 需更新 llama.cpp
  3. 當前配置狀態(M5Max128,2026-09-25 更新):

    • Chat Server (Port 8080):已載入 mmproj ✅
    • 統一服務:Gemma4 同時處理 Chat/Summary/VLM ✅
    • 舊 VLM Server (Port 8091):已停用(Llava 改為備用)
  4. 思考模式特性:

    • Gemma4 使用思考模式,會先推理再輸出最終答案
    • 文字 Chat:max_tokens=300 即可
    • 多模態 VLM:需要 max_tokens=800-900 才能完成思考
    • 若回應為空 → 增加 max_tokens

LLM 模型切換系統

文檔位置:/Users/accusys/momentry_core/docs_v1.0/OPERATIONS/LLM_SERVICES/

快速切換命令:

# 安裝切換腳本
cd ~/llm-deploy-doc
mkdir -p ~/llm-config ~/bin
cp models.json ~/llm-config/
cp scripts/llm-* ~/bin/
chmod +x ~/bin/llm-*

# 切換模型
llm-7b   # 快速模型(Llava 7B)
llm-12b  # 質量模型(Gemma 4 12B + mmproj)
llm-13b  # 多模態模型(Llava 13B)

# 查看狀態
llms

部署到新機器:

# 一鍵部署到 M5Max48
cd ~/llm-deploy-doc/scripts
./deploy-m5max48.sh user m5max48

詳細文檔:

  • README.md:系統概述與快速開始
  • INSTALL.md:詳細安裝步驟
  • USAGE.md:使用手冊與故障排除
  • README_M5Max48.md:M5Max48 部署指南
  • M5Max48_DEPLOY_CHECKLIST.md:部署檢查清單

Model 檔案位置

/Users/accusys/models/
├── gemma-4-12b-it-Q4_K_M.gguf            (Chat/Summary LLM - 6.6GB)
├── llava-v1.6-vicuna-13b.Q4_K_M.gguf    (VLM model)
├── mmproj-model-f16.gguf                 (VLM mmproj)
└── embeddinggemma-300M-Q8_0.gguf         (Embedding model)

啟動命令

統一 Chat/VLM Server (gemma-4-12b-it + mmproj) - via launchd

# Service managed by launchd
launchctl load ~/Library/LaunchAgents/com.momentry.chat-llamacpp.plist
launchctl unload ~/Library/LaunchAgents/com.momentry.chat-llamacpp.plist

# Manual start (for testing)
/Users/accusys/llama.cpp/build/bin/llama-server \
  -m /Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf \
  --mmproj /Users/accusys/models/mmproj-F16.gguf \
  --host 0.0.0.0 \
  --port 8080 \
  -ngl 99 \
  -c 8192 \
  --temp 0.1 \
  -b 4096 \
  -ub 4096

# API endpoint (supports both text and vision)
curl http://localhost:8080/v1/chat/completions

備用 VLM Server (llava-v1.6-vicuna-13b) - 已停用

# 舊配置(已禁用)
# /Users/accusys/llama/bin/llama-server \
#   -m /Users/accusys/models/llava-v1.6-vicuna-13b.Q4_K_M.gguf \
#   --mmproj /Users/accusys/models/mmproj-model-f16.gguf \
#   --host 0.0.0.0 \
#   --port 8091 \
#   -ngl 99 \
#   -c 4096

Embedding (embeddinggemma-300m)

python3 scripts/embeddinggemma_server.py --port 11436

VLM 用途

  • Face trace VLM: 描述人物外貌(衣著、顏色、配件)
  • Scene VLM: 場景分析
  • Agent analyze_frame: 畫面分析工具

Agent Search 語言

  • 預設使用英文回答(除非用戶明確要求其他語言)
  • System prompt 已明確規範 LLM 必須使用英文回應

環境變數

# .env
MOMENTRY_LLM_CHAT_URL=http://localhost:8080/v1/chat/completions
MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it
MOMENTRY_LLM_VISION_URL=http://localhost:8080/v1/chat/completions
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
MOMENTRY_LLM_SUMMARY_URL=http://localhost:8080/v1/chat/completions
MOMENTRY_LLM_SUMMARY_MODEL=gemma-4-12b-it

Testing

# Run all tests
cargo test

# Run single test by name
cargo test test_name

# Run with output
cargo test -- --nocapture

# Doc tests
cargo test --doc

Linting & Formatting

# Format code (edition=2021, max_width=100, tab_spaces=4)
cargo fmt
cargo fmt -- --check

# Lint
cargo clippy
cargo clippy --all-features

# Check for errors
cargo check
cargo check --all-features

Code Style

General

  • Use Rust 2021 edition
  • Use tracing for logging (not println!)
  • Keep lines under 100 characters
  • Always provide absolute paths when referencing files — use full paths like /Users/accusys/momentry_core/src/main.rs instead of relative paths like src/main.rs
  • All document references MUST include full paths — when listing files to modify, API endpoints, or cross-references in docs, always use absolute paths (e.g., /Users/accusys/momentry_core/docs_v1.0/API_WORKSPACE/modules/19_people_api.md)

Imports (order: std → external → local)

use std::path::Path;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::core::chunk::Chunk;

Error Handling

  • Use anyhow::Result<T> for application code
  • Use thiserror for library code
  • Use .context() for error context
  • Use anyhow::bail!() for early returns
fn example() -> Result<SomeType> {
    let output = Command::new("ffprobe")
        .args([...])
        .output()
        .context("Failed to run ffprobe")?;

    if !output.status.success() {
        anyhow::bail!("Command failed");
    }
    Ok(result)
}

Naming

  • Types/Enums: PascalCase (VideoRecord, ChunkType)
  • Functions/Variables: snake_case (get_video_by_uuid)
  • Traits: PascalCase with -er suffix (Database, ChunkStore)
  • Files: snake_case (postgres_db.rs)

Types

  • Use serde::{Deserialize, Serialize} for serializable types
  • Use #[serde(rename_all = "snake_case")] for enum variants
  • Use explicit numeric types (i64, u32, f64)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoRecord {
    pub id: i64,
    pub uuid: String,
    pub duration: f64,
    pub width: u32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ChunkType {
    TimeBased,
    Sentence,
    Cut,
}

Async Programming

  • Use tokio runtime with full features
  • Use #[async_trait] for async trait methods
#[async_trait]
pub trait Database: Send + Sync {
    async fn init() -> Result<Self>
    where Self: Sized;
}

Code Structure

src/
├── main.rs           # CLI entry point
├── lib.rs            # Library exports
├── core/
│   ├── api_key/     # API key management (anomaly, blacklist, encryption, etc.)
│   ├── chunk/        # Chunking logic
│   ├── config.rs     # Centralized configuration (env vars)
│   ├── db/          # Database (PostgreSQL, MongoDB, Redis, Qdrant)
│   ├── embedding/   # Vector embeddings
│   ├── overlay/     # Video overlay
│   ├── probe/       # ffprobe integration
│   ├── processor/   # ASR, OCR, YOLO, Face, Pose, CUT, ASRX
│   │   └── executor.rs  # Unified Python script executor
│   ├── storage/     # File management
│   └── thumbnail/   # Thumbnail extraction
├── api/              # HTTP API (axum)
├── player/           # Video player
├── ui/               # TUI components
└── watcher/          # File system watcher

Tools Architecture

Directory Structure

tools/
├── cli/                    # Compiled CLI binaries
│   ├── rust/              # Rust CLI tools
│   │   ├── src/
│   │   │   └── bin/       # Binary source files
│   │   │       ├── rust_appearance.rs
│   │   │       ├── rust_face_cluster.rs
│   │   │       ├── rust_pose.rs
│   │   │       └── rust_vad.rs
│   │   ├── Cargo.toml
│   │   └── target/        # Build output
│   │       └── release/   # Release binaries
│   └── swift/             # Swift CLI tools
│       ├── Sources/
│       ├── Package.swift
│       └── .build/        # Build output
│           └── release/
└── script/                # Python scripts (organized by processor)
    ├── asr/               # ASR scripts
    ├── chunk/             # Chunking scripts
    ├── cut/               # Cut detection scripts
    ├── embedding/         # Embedding scripts
    ├── face/              # Face processing scripts
    ├── identity/          # Identity management scripts
    ├── ocr/               # OCR scripts
    ├── pose/              # Pose estimation scripts
    ├── scene/             # Scene detection scripts
    ├── utils/             # Utility scripts
    ├── vlm/               # Vision Language Model scripts
    ├── worker/            # Worker scripts
    └── yolo/              # YOLO detection scripts

Tool Categories

Rust CLI Tools (tools/cli/rust/)

Binary Purpose Status
rust_appearance Face appearance analysis ✅ Working
rust_face_cluster Face clustering ✅ Working
rust_pose Pose interpolation ✅ Working
rust_vad Voice Activity Detection ✅ Working

Build:

cd tools/cli/rust
cargo build --release

Usage:

# Worker automatically finds binaries in tools/cli/rust/target/release/
# Set MOMENTRY_USE_RUST_PROCESSORS=true to enable

Swift CLI Tools (tools/cli/swift/)

Binary Purpose Status
swift_pose Apple Vision Pose ✅ Working
swift_face Apple Vision Face ✅ Working
swift_scene Scene detection ✅ Working
swift_yolo YOLO detection ✅ Working

Build:

cd tools/cli/swift
swift build -c release

Python Scripts (tools/script/)

Organized by processor type. Each directory contains related scripts.

Directory Purpose
asr/ ASR (Automatic Speech Recognition)
chunk/ Sentence chunking
cut/ Cut detection
embedding/ Vector embedding generation
face/ Face detection, tracking, clustering
identity/ Identity management
ocr/ Optical Character Recognition
pose/ Pose estimation (MediaPipe, YOLOv8)
scene/ Scene detection
utils/ Shared utilities
vlm/ Vision Language Model (VLM)
worker/ Worker-specific scripts
yolo/ YOLO object detection

Environment Variables

  • MOMENTRY_SCRIPTS_DIR - Scripts directory (default: tools/script/)
  • MOMENTRY_CLI_DIR - CLI tools directory (default: tools/cli/)
  • MOMENTRY_USE_RUST_PROCESSORS - Enable Rust processors (default: false)

Worker Integration

The Worker (src/core/processor/executor.rs) automatically locates tools:

  1. Python Scripts: tools/script/<processor>/
  2. Rust Binaries: tools/cli/rust/target/release/
  3. Swift Binaries: tools/cli/swift/.build/release/

Priority Order:

  1. Python scripts (default)
  2. Rust binaries (if MOMENTRY_USE_RUST_PROCESSORS=true)
  3. Swift binaries (for Apple Vision processors)

Legacy Locations (To Be Removed)

⚠️ The following locations are deprecated and will be removed:

  • scripts/rust_processors/ → Migrate to tools/cli/rust/
  • scripts/swift_processors/ → Migrate to tools/cli/swift/
  • scripts/*.py (scattered) → Migrate to tools/script/<processor>/

Migration Status

Component Current Location Target Location Status
Rust CLI tools/cli/rust/ tools/cli/rust/ ✅ Done
Swift CLI tools/cli/swift/ tools/cli/swift/ ✅ Done
Python Scripts tools/script/ tools/script/ ✅ Done
Legacy Rust scripts/rust_processors/ Remove ⚠️ Pending
Legacy Swift scripts/swift_processors/ Remove ⚠️ Pending

Processor Configuration (V3)

配置驅動的 Processor 選擇

Momentry Core 使用 配置驅動的 processor 選擇系統,支持動態選擇和優先級排序。

主配置: config/processor_tools_v3.json

Processor 優先級政策

Swift (Apple Vision + ANE) First, Rust Second, Python Backup

Priority Tool 用途 理由
0 Swift CLI 標準實現 Apple Vision + ANE 加速
0-1 Rust CLI 標準實現 性能優秀
2+ Python 備用 靈活性高

當前配置狀態

Swift First (Priority 0): 4 個 (POSE, FACE, ASRX, OCR)

Rust First (Priority 0): 3 個 (FACE_TRACE, CUT, SCENE_VLM)

Python Only: 2 個 (ASR, TKG)

性能基準

Processor Python Rust Swift 最佳
FACE_TRACE ~2s 0.1s - Rust (20x)
CUT ~3s 1s 6s Rust (3x)
POSE ~5s - 3s Swift (ANE)
FACE ~8s - 4s Swift (ANE)

⚠️ 已廢棄配置

  • ❌ MOMENTRY_USE_RUST_PROCESSORS (已由 V3 配置取代)
  • ❌ config/processor_tools.json (V1, 已廢棄)

相關文檔

  • docs_v1.0/OPERATIONS/Processor_Priority_Policy.md - 優先級政策
  • docs_v1.0/OPERATIONS/Processor_Commands_Reference.md - 命令參考
  • docs_v1.0/M4_workspace/2026-09-28_processor_test_report.md - 測試報告

Key Dependencies

  • Error handling: anyhow, thiserror
  • Async: tokio (full features), async-trait
  • CLI: clap (derive)
  • Serialization: serde, serde_json, chrono
  • Database: sqlx, mongodb, redis (1.0), qdrant-client
  • HTTP: axum, tower
  • Logging: tracing, tracing-subscriber
  • Config: once_cell (lazy static config)

Environment Variables

Server

  • MOMENTRY_SERVER_PORT - API server port (default: 3002 for production, 3003 for playground)
  • MOMENTRY_REDIS_PREFIX - Redis key prefix (default: momentry: for production, momentry_dev: for playground)
  • MOMENTRY_API_KEY - API key for Player online mode testing

Testing API Key

export MOMENTRY_API_KEY="muser_68600856036340bcafc01930eb4bd839_1774418104_97221b69"

# Test Player online mode
cargo run --features player --bin momentry_player -- -o

Database

  • DATABASE_URL - PostgreSQL (default: postgres://accusys@localhost:5432/momentry)

Redis

  • REDIS_URL - Redis URL (default: redis://:accusys@localhost:6379)
  • REDIS_PASSWORD - Redis password (default: accusys)

Paths

  • MOMENTRY_OUTPUT_DIR - Output directory (default: /Users/accusys/momentry/output)
  • MOMENTRY_BACKUP_DIR - Backup directory
  • MOMENTRY_SCRIPTS_DIR - Scripts directory (default: tools/script/)
  • MOMENTRY_CLI_DIR - CLI tools directory (default: tools/cli/)
  • MOMENTRY_PYTHON_PATH - Python path (default: /opt/homebrew/bin/python3.11)

Critical Variables for Startup Scripts

IMPORTANT: Startup scripts must explicitly export these variables for Python subprocess inheritance.

Production (3002)

Required exports in run-server-3002.sh and run-worker-3002.sh:

export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output
export DATABASE_SCHEMA=public
export MOMENTRY_REDIS_PREFIX=momentry:
export MOMENTRY_SERVER_PORT=3002

Playground (3003)

Required exports in run-server-3003.sh:

export DATABASE_SCHEMA=dev
export MOMENTRY_SERVER_PORT=3003
export MOMENTRY_REDIS_PREFIX=momentry_dev:
export MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output_dev

Why This Matters

  • Rust process loads .env via dotenv
  • Python subprocess inherits environment from Rust process
  • Without explicit export, dotenv variables are only available inside Rust
  • Python scripts like store_traced_faces.py will use hardcoded defaults if not exported

Config Directory

Environment-specific configuration files:

  • config/production.env - Production-specific variables
  • config/development.env - Development-specific variables
  • config/test.env - Test environment (if needed)

Processor Timeouts

  • MOMENTRY_ASR_TIMEOUT - ASR timeout in seconds (default: 3600)
  • MOMENTRY_CUT_TIMEOUT - CUT timeout in seconds (default: 3600)
  • MOMENTRY_DEFAULT_TIMEOUT - Default timeout (default: 7200)

TMDb Integration (Face Clustering)

  • TMDB_API_KEY - TMDb API key for movie metadata lookup (required for MOMENTRY_TMDB_PROBE_ENABLED=true)
  • MOMENTRY_TMDB_PROBE_ENABLED - Enable TMDb probe during registration (default: false)
    • Register phase: searches TMDb by filename, creates identities with tmdb_id/tmdb_profile
    • Post-process phase: matches detected faces against TMDb identities via cosine similarity

Synonym Expansion

  • MOMENTRY_SYNONYM_FILES - Comma-separated paths to synonym JSON files (e.g., data/english_synonyms.json,data/llm_synonyms.json)
  • MOMENTRY_SYNONYM_FILE - Single synonym JSON file path (deprecated, use above)

Logging

  • RUST_LOG or MOMENTRY_LOG_LEVEL - Log level (default: info)

Notes

  • Unit tests exist (86 library tests)
  • Video processing uses external tools (ffprobe, Python scripts)
  • Multi-database architecture (PostgreSQL, MongoDB, Redis, Qdrant)
  • Monitor directory is a separate system (not Rust)
  • PythonExecutor provides unified script execution with timeout support
  • Redis 1.0.x for improved performance
  • FaceNet CoreML model (models/facenet512.mlpackage) replaces InsightFace for embedding extraction (MIT license, ANE-accelerated)

LLM Synonym Generation

Generate synonym database using llama.cpp (Gemma4):

# Generate full database (162 entries, ~5 minutes)
python3 scripts/generate_synonyms_llamacpp.py

# Quick test
python3 scripts/generate_synonyms_llamacpp.py --test

# Resume from existing file
python3 scripts/generate_synonyms_llamacpp.py --resume

# Output: data/llm_synonyms.json (27 Chinese + 135 English words)

Task Management

使用 todowrite 追蹤任務

# 創建任務清單
/todo 建立配置模組 [in_progress]
/todo 添加單元測試 [pending]

# 更新狀態
/todo 完成標記 [completed]

任務批次建議

  • 一次處理 1-2 個功能
  • 每個功能完成後驗證 (clippy + test)
  • 驗證通過後再繼續下一個

Code Review Checklist

完成任務後檢查:

  • cargo clippy --lib 通過
  • cargo test --lib 通過
  • cargo fmt -- --check 通過
  • 文檔已更新 (如需要)
  • 新功能有單元測試

Commit Guidelines

# feat: 新功能
git commit -m "feat: add monitor_jobs table"

# fix: 錯誤修復
git commit -m "fix: resolve SQL injection in store_vector"

# refactor: 重構
git commit -m "refactor: use parameterized queries"

# docs: 文檔更新
git commit -m "docs: update AGENTS.md with new modules"

Pre-commit Hook

專案已配置 .git/hooks/pre-commit,提交前自動檢查:

# 檢查內容
1. cargo fmt --check    # Rust 格式化檢查
2. cargo clippy --lib   # Rust Lint 檢查
3. cargo test --lib     # Rust 單元測試
4. ruff check           # Python Lint 檢查
5. ruff format --check  # Python 格式化檢查
6. markdownlint         # Markdown 格式檢查
7. shellcheck           # Shell 腳本檢查

# 跳過檢查(不建議)
git commit --no-verify

# 跳過特定檢查
git commit --skip-checks

注意: Hook 僅檢查已暫存的 Rust/Python/Markdown 文件。

Python 環境設置

# 安裝 ruff
pip install ruff==0.11.2

# 格式化 Python 文件
ruff format scripts/

# Lint Python 文件
ruff check scripts/

Markdown 環境設置

# 安裝 markdownlint-cli (使用系統 Node.js)
npm install -g markdownlint-cli

# 檢查 Markdown 文件
markdownlint docs/

# 配置檔案
.markdownlint.json

Shell 環境設置

# 安裝 shellcheck
brew install shellcheck

# 檢查 Shell 腳本
shellcheck scripts/*.sh monitor/**/*.sh

注意: Hook 只檢查 error 等級的 shellcheck 問題,style 警告會顯示但不阻擋提交。

Gitea Sync

主要 sync 管道為 Gitea:http://192.168.110.210:3000/warren/momentry_core.git(m4mini)

2026-11-05 更正:舊文檔記載的 http://192.168.110.200:3000/admin/momentry_core.git 已失效(主機無回應)。本機實際 remote 為 m4mini 的 warren/momentry_core,分支 feature/dynamic-concurrency-* 為進行中工作分支。可用測試: curl -s -u "warren:<TOKEN>" http://192.168.110.210:3000/api/v1/repos/warren/momentry_core

產生 Access Token(首次設定)

# 登入 warren 帳號後於 API 產生 token(scopes: write:repository)
TOKEN=$(curl -s -X POST "http://192.168.110.210:3000/api/v1/users/warren/tokens" \
  -u "warren:<PASSWORD>" \
  -H "Content-Type: application/json" \
  -d '{"name":"m5max128_push","scopes":["write:repository"]}' | jq -r '.sha1')
echo $TOKEN

設定 Remote

# 用 token 取代密碼
git remote add origin http://warren:TOKEN@192.168.110.210:3000/warren/momentry_core.git

# 同步
git pull origin feature/dynamic-concurrency-v1.3.4
git push origin feature/dynamic-concurrency-v1.3.4

Token 記錄

機器 Token
M5Max128 c33768c4cc26c0f4c575dcce832e92e5cf192773 (write:repository + write:user)

注意: Token 有 write:repository scope,勿外洩。如需新增 token 給其他機器,各自產自己的 token。

機器清單

機器名稱 IP 地址 用途
m5max48 (本機) 192.168.110.201 Momentry Core 後端服務 (port 3002)
m4promini 192.168.110.203 Studio 前端服務
m4mini 192.168.110.210 待確認用途

Release Workflow

Release 前準備

每次 release production binary 前,必須:

  1. 建立 Release Tag

    git tag -a v0.X.X -m "Release vX.X.X - YYYY-MM-DD"
    git push origin v0.X.X
    
  2. 備份獨立 Source Code

    # 建立 release 獨立目錄
    RELEASE_DIR="/Users/accusys/momentry_core_releases/v0.X.X"
    mkdir -p "$RELEASE_DIR"
    
    # 複製完整原始碼(排除不必要的檔案)
    rsync -av --exclude='.git' --exclude='target' --exclude='node_modules' \
          /Users/accusys/momentry_core_0.1/ "$RELEASE_DIR/"
    
    # 記錄 release 資訊
    echo "Release: v0.X.X" > "$RELEASE_DIR/RELEASE_INFO.txt"
    echo "Date: $(date)" >> "$RELEASE_DIR/RELEASE_INFO.txt"
    echo "Git Commit: $(git rev-parse HEAD)" >> "$RELEASE_DIR/RELEASE_INFO.txt"
    echo "Binary: $(ls -la target/release/momentry)" >> "$RELEASE_DIR/RELEASE_INFO.txt"
    
  3. 備份 Binary

    cp target/release/momentry "$RELEASE_DIR/momentry_v0.X.X"
    cp target/release/momentry_playground "$RELEASE_DIR/momentry_playground_v0.X.X" 2>/dev/null
    
  4. 記錄資料庫 Schema

    pg_dump -U accusys -d momentry --schema-only > "$RELEASE_DIR/schema_v0.X.X.sql"
    
  5. 驗證環境變數配置

    • ✅ Startup scripts export all required environment variables
    • ✅ Python scripts don't use hardcoded paths
    • ✅ Environment variables consistent across:
      • .env / .env.development
      • Startup script export
      • Python script os.environ.get()
    • ✅ Config directory has environment-specific files
    • ✅ AGENTS.md documents all required exports

重要性

  • 避免 release binary 與 current source code 不一致
  • 方便追蹤特定 release 的程式碼狀態
  • 必要時可快速復原或比對差異
  • 確保資料庫 schema 與程式碼版本對應

Reference Documents

文件 用途
docs/OPENCODE_GUIDE.md OpenCode 使用規範
docs/ARCHITECTURE_EVALUATION.md 架構優化待評估項目 (含 GraphRAG)
docs/PENDING_ISSUES.md 待解決問題追蹤
docs/MOMENTRY_CORE_MONITORING.md 監控系統規範
docs/MOMENTRY_CORE_REDIS_KEYS.md Redis Key 設計規範
docs/PYTHON.md Python 腳本規範
docs/FILE_CHANGE_MANAGEMENT.md 文件修改管理規範
docs/YOLO_RESUME_INTEGRATION.md YOLO Resume 功能整合記錄
docs/DOCUMENT_EMBEDDING_STRATEGY.md Parent-Child 嵌入策略
docs/PROCESSING_PIPELINE.md 處理流程文檔
docs/N8N_DEMO_WORKFLOW.md n8n 工作流文檔
docs/FRESH_MAC_INSTALLATION.md 全新 Mac 安裝指南
docs/SERVICES.md 服務總覽與管理
docs/SFTPGO_DEMO_USER.md SFTPGo 用戶指南

Document Change Workflow

修改文件前請參考 docs/FILE_CHANGE_MANAGEMENT.md,確保:

  1. 修改前:完整閱讀文件、執行預檢清單
  2. 修改中:提供變更計畫、取得確認
  3. 修改後:展示 diff、更新版本歷史
  4. 驗證:執行 lint/test、提交前審查

AI 工具修改規範

AI 工具修改文件時:

  • 必須先完整閱讀文件(不可只讀取部分章節)
  • 修改前先提出變更計畫供確認
  • 修改後展示 diff 內容
  • 更新版本歷史表

PHP Development

WordPress 作為 Momentry Portal,負責 n8n 自動化與 sftpgo 檔案服務的頁面整合。

編輯器設定

編輯器 LSP 方案 安裝方式
VS Code Intelephense Extension Marketplace (推薦)
Cursor Intelephense Extension Marketplace (推薦)
CLI phpactor ~/bin/phpactor

Intelephense (VS Code/Cursor)

  1. 安裝 Extension: 搜尋 "Intelephense"
  2. 設定:
{
  "intelephense.stubs": ["wordpress"]
}

phpactor (CLI)

# 安裝方式
brew install composer
curl -sSL https://github.com/phpactor/phpactor/releases/latest/download/phpactor.phar -o ~/bin/phpactor
chmod +x ~/bin/phpactor

# 安裝 WordPress Stubs
cd /Users/accusys/wordpress/web
composer require --dev php-stubs/wordpress-stubs

# 建立 WordPress 索引
cd /Users/accusys/wordpress/web
~/bin/phpactor index:build --reset

# 常用指令
~/bin/phpactor class:search "WP_User"      # 搜尋類別
~/bin/phpactor index:query WP_User          # 查看類別資訊
~/bin/phpactor navigate /path/to/file.php  # 導航到定義

WordPress 程式碼位置

類型 路徑
主題 /Users/accusys/wordpress/web/wp-content/themes/
插件 /Users/accusys/wordpress/web/wp-content/plugins/

與 marcom 團隊協作

角色 負責
marcom 團隊 Figma 設計 / Elementor 建構
OpenCode 程式碼實作 / 重構

開發時程

Phase 1: marcom 建構 (現在)    → Elementor 頁面建構
Phase 2: 交付審視 (TBD)      → 功能確認 / 重構評估
Phase 3: OpenCode 重構        → 純程式碼實作,交付無 Elementor 依賴版本

M4 通知規範

固定通知方式

通知 M4 的唯一管道:M4_workspace/ 下建立回覆文件 + git commit。不需口頭、即時訊息、郵件。

命名規則

docs_v1.0/M4_workspace/YYYY-MM-DD_<topic>_response.md   (回覆 M4 問題)
docs_v1.0/M4_workspace/YYYY-MM-DD_<topic>.md             (主動通報)
docs_v1.0/M4_workspace/YYYY-MM-DD_<topic>_test_report.md (測試報告)

觸發時機

情境 動作
M4 提交問題報告到 M4_workspace/ 修復後,回覆 *_response.md
完成 M4 要求的任務 回覆 *_response.md
重大變更(模型替換、架構變更) 主動通知 *.md
新測試包產出 *_test_report.md

交付檢查

  1. 文件寫入 docs_v1.0/M4_workspace/
  2. git add 包含該文件
  3. git commit 含相關變更
  4. M4 透過 git log 查看

詳細規範見 docs_v1.0/M4_workspace/M4_NOTIFICATION_PROTOCOL.md。

UUID Naming Rule

Never use bare uuid in API route paths, query params, JSON keys, or code variable names. Always qualify:

Context Must use Never
Video/file resource file_uuid uuid
Identity resource identity_uuid uuid
Query parameter file_uuid=, identity_uuid= uuid=
Route path :file_uuid, :identity_uuid :uuid
JSON key "file_uuid", "identity_uuid" "uuid"

This applies to docs, code, API responses, and curl examples. Exceptions: internal database primary key names (e.g. identities.uuid column).

Document Compliance Checklist

Before creating any file in docs_v1.0/ (API_WORKSPACE, GUIDES, REFERENCE, DESIGN, OPERATIONS, INTEGRATIONS), verify all items below. IMPORTANT: API functional documents are generated from API_WORKSPACE/modules/. Edit modules there, then run make deploy in API_WORKSPACE/ to update GUIDES/. Never edit generated files in GUIDES/ directly. See DESIGN/Modular_Doc_System_V1.0.md for the full system design.

P0 — Mandatory (7 items)

# Check Rule
1 YAML frontmatter title, version, date, author, status present
2 Version history Table at bottom of file tracking changes
3 Top info table scope, status, applicable to, etc.
4 PascalCase filename e.g. DetectorRegistry.md, not detector_registry.md
5 _ separator Within filenames use _, never spaces or other chars
6 English content Entire file in English
7 Correct directory File must reside in appropriate directory: API_WORKSPACE/modules/ (API endpoint modules), GUIDES/ (user docs, generated), REFERENCE/ (data models), DESIGN/ (architecture), OPERATIONS/ (infra/release), INTEGRATIONS/ (n8n/tests)

P0b — UUID Naming

# Check Rule
8 file_uuid not bare uuid All file references use file_uuid (see UUID Naming Rule above)
9 identity_uuid not bare uuid All identity references use identity_uuid

P1 — Suggested (4 items)

# Check Note
1 Cross-references Link to related docs in API_WORKSPACE/, GUIDES/, REFERENCE/, DESIGN/, OPERATIONS/
2 Glossary terms Define non-obvious terms inline or link glossary
3 Diagrams Include Mermaid/ASCII diagram for complex topics
4 Absolute paths All file paths must be absolute, e.g. /Users/accusys/momentry_core/src/...

Exception

M4_workspace/ files are exempt from P0 mandatory checklist items (YAML frontmatter, version history, etc.) as they are free-format reply documents.

However, M4_workspace/ files MUST still use absolute paths for all file references.


Delivery Procedure

完整交付程序(M4_workspace → M5 → Release → Deploy → Public)見:

docs_v1.0/OPERATIONS/DELIVERY_PROCEDURE.md

Session Summary (2026-07-01: Search Mode Fixes)

Goal

Fix search modes: Keyword BM25 ranking + People search migration to Qdrant + Qdrant scroll pagination

Done

  • Keyword/BM25 search (search_bm25): Replaced hardcoded 1.0 score with PostgreSQL FTS (ts_rank + plainto_tsquery). Now ranks results by relevance instead of flat 1.0.
  • Smart search merge: Passes real FTS score through instead of fixed 0.5, so keyword-only results are properly differentiated.
  • Qdrant scroll_points: Added offset parameter for pagination support; new scroll_all_points() method handles multi-page scroll automatically.
  • get_identity_traces: Fixed broken pagination loop (always fetched same first 1000 points) by switching to scroll_all_points.
  • People search (search_persons_internal): Replaced face_detections JOIN in universal search with Qdrant _faces scroll + Rust aggregation (count per identity per file, frame→second via FPS).
  • People search (search_persons_by_query): Same migration for the REST API person search endpoint.
  • Payload field fix: _faces uses frame (integer) not timestamp_secs (float). Fixed both search_persons_internal and search_persons_by_query to read frame and convert via frame / fps.

Key Files Changed

  • src/core/db/qdrant_db.rs: scroll_points → offset pagination, new scroll_all_points
  • src/api/identity_binding.rs: Use scroll_all_points instead of broken loop
  • src/api/universal_search.rs: Rewrote search_persons_internal and search_persons_by_query to use Qdrant
  • src/core/db/postgres_db.rs: search_bm25 → PostgreSQL FTS ranking
  • src/api/search.rs: Pass real FTS scores in merge, removed unused KEYWORD_FIXED_SCORE

Done This Session

  • Qdrant scroll pagination: scroll_points now accepts offset param + returns next_page_offset; new scroll_all_points() handles multi-page scroll automatically
  • get_identity_traces pagination fix: No longer fetches same 1000 points in infinite loop
  • Keyword BM25: search_bm25 replaced hardcoded 1.0 score with PostgreSQL ts_rank + plainto_tsquery; smart_search passes real FTS scores instead of fixed 0.5
  • People search → Qdrant: Both search_persons_internal and search_persons_by_query replaced face_detections JOIN with Qdrant _faces scroll + Rust aggregation (count/group/sort). Fixed timestamp_secs → frame + frame/fps conversion
  • list_face_candidates → Qdrant: identities.rs unbound faces query now scrolls _faces with is_null: identity_id filter, sorts by confidence DESC in Rust
  • list_unassigned_traces → Qdrant: identities.rs unbound traces query now scrolls _faces with is_null: identity_id + trace_id > 0 filter, groups by (file_uuid, trace_id) in Rust, picks best face per trace
  • get_identity_chunks → identity_bindings: Replaced face_detections frame-range JOIN with identity_bindings + chunk.metadata->>'trace_id'
  • postgres_db.rs 5 remaining READs → Qdrant: get_trace_count_by_file, get_trace_frame_count_distribution, get_identity_files, get_identity_faces, get_file_faces all migrated to _faces scroll + Rust aggregation
  • agent/tools.rs fully migrated: exec_find_file, exec_list_files, exec_tkg_query (8 sub-queries), exec_identity_text, exec_identities_search — all face_detections JOINs replaced with Qdrant scroll or identity_bindings
  • job_worker.rs + storage.rs: Remaining face_detections READs migrated to Qdrant scroll

Remaining face_detections references (all inactive/safe)

  • Schema definition (CREATE TABLE/INDEX in postgres_db.rs)
  • store_face_detections_batch — already skipped (Phase 1)
  • workspace_sqlite.rs — local processing DB, separate from PG
  • bin/release.rs — standalone release utility