Commit Graph

288 Commits

Author SHA1 Message Date
iven
b4e5af7a58 feat(growth): add memory decay + time-weighted scoring + remove dead frontend
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- Add effective_importance() with exponential time decay (30-day half-life)
  and access count boost for fair scoring of stale vs fresh memories
- Add SqliteStorage::decay_memories() for periodic maintenance:
  reduces stored importance per interval, archives (deletes) below threshold
- Update find() scoring to use time-decayed importance in sort
- Add DecayResult type and effective_importance re-export in lib.rs
- Remove dead frontend active-learning.ts (370 lines, zero imports)
2026-04-04 00:45:16 +08:00
iven
276ec3ca94 chore(desktop): remove dead active-learning frontend code
Zero imports across codebase — never wired to any UI or Tauri command.
Rust Growth crate handles memory/summary generation instead.
2026-04-04 00:38:13 +08:00
iven
8faefd6a61 fix(tests): resolve workspace compilation + CJK search failures
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- saas test harness: align WorkerDispatcher::new and AppState::new
  signatures with SpawnLimiter addition and init_db(&DatabaseConfig)
- growth sqlite: add CJK fallback (LIKE-based) when FTS5 unicode61
  tokenizer fails on Chinese queries (unicode61 doesn't index CJK)
2026-04-04 00:34:34 +08:00
iven
5db2907420 test(desktop): add agent-chat comprehensive E2E test spec
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Full E2E test suite for agent chat functionality including:
- Message send/receive flow
- Streaming response verification
- Model switching behavior
- Error handling scenarios
- Multi-turn conversation context

Includes test report documenting coverage and known gaps.
2026-04-03 23:02:00 +08:00
iven
5eeabd1f30 feat(saas): add webhook event notification system (@unplugged)
Webhook infrastructure for external event notifications:
- SQL migration: webhook_subscriptions + webhook_deliveries tables
- Types: CreateWebhookRequest, UpdateWebhookRequest, WebhookDelivery
- Service: CRUD operations + trigger_webhooks + HMAC-SHA256 signing
- Handlers: REST API endpoints (CRUD + delivery logs)
- Worker: WebhookDeliveryWorker with exponential retry (max 3)

NOT YET INTEGRATED: needs mod registration in lib.rs + workers/mod.rs,
hmac crate dependency, and route mounting. Code is ready for future
integration after stabilization phase completes.
2026-04-03 23:01:49 +08:00
iven
1c99e5f3a3 fix(browser): stability enhancements + MCP frontend client
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
S7 Browser Hand:
- Remove dead code: browser/actions.rs (314 lines of unused BrowserAction/ActionResult types)
- Fix browser_scrape_page: log failed selector matches instead of silently swallowing errors
- Fix element_to_info: document known limitation for always-None location/size fields
- Fix browserHandStore: reuse activeSessionId in executeScript/takeScreenshot/executeTemplate
  instead of creating orphan Browser sessions
- Add Browser.connect(sessionId) method for session reuse

MCP Frontend:
- Add desktop/src/lib/mcp-client.ts (77 lines) — typed client for MCP Tauri commands
  (startMcpService, stopMcpService, listMcpServices, callMcpTool)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 22:16:12 +08:00
iven
943afe3b6b feat(protocols): MCP tool adapter + Tauri commands + initialize bug fix
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
S6 MCP Protocol:
- Fix McpTransport::initialize() — store actual server capabilities instead
  of discarding them and storing empty ServerCapabilities::default()
- Add send_notification() method to McpTransport for JSON-RPC notifications
- Send notifications/initialized after MCP handshake (spec requirement)
- Add McpToolAdapter: bridges MCP server tools into the tool execution path
- Add McpServiceManager: lifecycle management for MCP server connections
- Add 4 Tauri commands: mcp_start_service, mcp_stop_service,
  mcp_list_services, mcp_call_tool
- Register zclaw-protocols dependency in desktop Cargo.toml

New files:
- crates/zclaw-protocols/src/mcp_tool_adapter.rs (153 lines)
- desktop/src-tauri/src/kernel_commands/mcp.rs (145 lines)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 22:07:35 +08:00
iven
cc26797faf fix(saas): eliminate 6 compiler warnings + stabilize directive complete
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- Remove unused imports: Utc (billing/service), StatusCode (billing/handlers), Sha256 (billing/handlers)
- Fix unused variables: _db (scheduler), _e (payment WeChat error)
- Fix visibility: RegisterDeviceRequest pub(super) → pub (used in pub handler)
- Update STABILIZATION_DIRECTIVE.md: all 7 criteria met, downgrade to advisory
- Fix TRUTH.md §2.2: mark P0/P1 defects as resolved, update Admin pages count to 14

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 21:57:04 +08:00
iven
264dc75b2c fix(production-readiness): audit fixes — duplicate useState + route mismatch + stale @reserved
Some checks failed
CI / Build Frontend (push) Has been cancelled
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- ChatArea.tsx: remove duplicate useState(searchOpen) declaration on line 70
- scheduled_task/mod.rs: fix route from /api/scheduler/tasks to /api/v1/scheduler/tasks
  (matches admin-v2 service baseURL pattern and all other modules)
- scheduled_task/handlers.rs: remove @reserved annotations (now has Admin V2 frontend)
- scheduled_task/handlers.rs: update doc comments with correct /api/v1/ paths
2026-04-03 21:41:30 +08:00
iven
4281ce35b4 fix(saas): remove hardcoded model fallback — dynamic from available models
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- service.rs: template model passed as-is (Option<String>), no hardcoded fallback
- saas-types.ts: AgentConfigFromTemplate.model → string | null
- agentStore.ts: when model is null, resolve from saasStore.availableModels[0]
- AgentOnboardingWizard.tsx: restore full file (was corrupted), apply assignTemplate try/catch fix
2026-04-03 21:38:15 +08:00
iven
2ceeeaba3d fix(production-readiness): 3-batch production readiness cleanup — 12 tasks
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Batch 1 — User-facing fixes:
- B1-1: Pipeline verified end-to-end (14 Rust commands, 8 frontend invoke, fully connected)
- B1-2: MessageSearch restored to ChatArea with search button in DeerFlow header
- B1-3: Viking cleanup — removed 5 orphan invokes (no Rust impl), added addWithMetadata + storeWithSummaries methods + summary generation UI
- B1-4: api-fallbacks transparency — added _isFallback markers + console.warn to all 6 fallback functions

Batch 2 — System health:
- B2-1: Document drift calibration — TRUTH.md/README.md numbers verified and updated
- B2-2: @reserved annotations on 15 SaaS handler functions with no frontend callers
- B2-3: Scheduled Task Admin V2 — new service + page + route + sidebar navigation
- B2-4: TRUTH.md Pipeline/Viking/ScheduledTask records corrected

Batch 3 — Long-term quality:
- B3-1: hand_run_status/hand_run_list verified as fully implemented (not stubs)
- B3-2: Identity snapshot rollback UI added to RightPanel
- B3-3: P2 code quality — 4 fixes (TODO comments, fire-and-forget notes, design notes, table name validation), 2 verified N/A, 1 upstream
- B3-4: Config PATCH→PUT alignment (admin-v2 config.ts matched to SaaS backend)
2026-04-03 21:34:56 +08:00
iven
305984c982 fix(saas): P2 code quality fixes + config PATCH/PUT alignment
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
P2 code quality (SEC2-P2-01~10):
- P2-04: Replace vague TODO with detailed Phase 2 design note in generate_embedding.rs
- P2-05: Add NOTE(fire-and-forget) annotations to 4 long-running tokio::spawn in main.rs
- P2-07: Add DESIGN NOTE to scheduler explaining sequential execution rationale
- P2-08: Add compile-time table name whitelist + runtime char validation in db.rs
- P2-02: Verified N/A (only zclaw-pipeline uses serde_yaml_bw, no inconsistency)
- P2-06: Verified N/A (bind loop correctly matches 6-column placeholders)
- P2-03: Remains OPEN (requires upstream sqlx release)

Config HTTP method alignment (B3-4):
- Fix admin-v2 config.ts: request.patch -> request.put to match backend .put() route
- Fix backend handler doc comment: PATCH -> PUT
- Add @reserved annotations to 6 config handlers without frontend callers
2026-04-03 21:32:17 +08:00
iven
22b967d2a6 docs(features): v0.10.1/v0.10.2 数字校准 + 行业模板文档更新
Some checks failed
CI / Rust Check (push) Has been cancelled
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- README.md: SKILL 76→75, Tauri 命令 175→171, SaaS API 58→131, Workers 5→7, 数据表 25→34, Admin 11→13 页面
- 00-saas-overview.md: Agent Template 新增 5 个端点文档、种子数据表、端到端数据流图
- roadmap.md: 同步最新数字
- fix(saasStore): toTopRequired → totpRequired 拼写修复
2026-04-03 21:29:44 +08:00
iven
edecd4c81f fix(saas): deep audit round industry template system - critical fixes
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
C1: Use backend createAgentFromTemplate API + tools forwarding
C3: seed source='builtin' instead of 'custom'
C4: immutable clone data handling (return fresh from store) + spread)
H3: assignTemplate error propagation (try/catch)
H4: input validation for name/fields
H5: assign_template account existence check
H6: remove dead route get_full_template
H7: model fallback gpt-4o-mini (hardcoded constant)
H8: logout clears template state
H9: console.warn -> structured logger
C2: restoreSession fetches assignedTemplate
2026-04-03 19:45:25 +08:00
iven
0857a1f608 feat(desktop): wire template welcome_message + quick_commands to chat UI
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- Add welcomeMessage/quickCommands fields to Clone interface
- Persist template welcome/quick data via updateClone after creation
- FirstConversationPrompt: prefer template-provided welcome message
  over dynamically generated one
- FirstConversationPrompt: render template quick_commands as chips
  instead of hardcoded QUICK_ACTIONS when available
- Tighten assign/unassign template endpoint permissions from model:read
  to relay:use (self-service operation for all authenticated users)
2026-04-03 15:20:15 +08:00
iven
1048901665 fix(saas): industry template audit fixes + pgvector optional + relay timeout
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- Fix seed template tools to match actual runtime tool names
  (file_read/file_write/shell_exec/web_fetch)
- Persist system_prompt/temperature/max_tokens via identity system
  in agentStore.createFromTemplate()
- Fire-and-forget assignTemplate() in AgentOnboardingWizard
- Fix saas-relay-client unused variable warning
- Make pgvector extension optional in knowledge_base migration
- Increase StreamBridge timeout from 30s to 90s for thinking models
2026-04-03 15:10:13 +08:00
iven
ea00c32c08 feat(saas): industry agent template assignment system
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Phase 1-8 of industry-agent-delivery plan:

- DB migration: accounts.assigned_template_id (ON DELETE SET NULL)
- SaaS API: 4 new endpoints (assign/get/unassign/create-agent)
- Service layer: assign_template_to_account, get_assigned_template, unassign_template, create_agent_from_template)
- Types: AssignTemplateRequest, AgentConfigFromTemplate (capabilities merged into tools)
- Frontend SaaS Client: assignTemplate, getAssignedTemplate, unassignTemplate, createAgentFromTemplate
- saasStore: assignedTemplate state + login auto-fetch + actions
- saas-relay-client: fix unused import and saasUrl reference error
- connectionStore: fix relayModel undefined error
- capabilities default to glm-4-flash

- Route registration: new template assignment routes

Cospec and handlers consolidated

Build: cargo check --workspace PASS, tsc --noEmit Pass
2026-04-03 13:31:58 +08:00
iven
5b1b747810 fix(desktop): prevent transformCallback crash in browser mode
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Root cause: ChatArea.tsx called listen() from @tauri-apps/api/event
directly on component mount without checking isTauriRuntime(). When
accessed from a regular browser (not Tauri WebView), window.__TAURI_INTERNALS__
is undefined, causing "Cannot read properties of undefined (reading 'transformCallback')".

Solution:
- Created lib/safe-tauri.ts with safe wrappers (safeInvoke, safeListen,
  safeListenEvent, requireInvoke) that gracefully degrade when Tauri
  IPC is unavailable
- Replaced direct listen() call in ChatArea.tsx with safeListenEvent()
2026-04-03 13:00:36 +08:00
iven
564c7ca28f fix(desktop): guard invoke calls with isTauriRuntime check
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Step 5 (embedding config) and Step 5b (summary driver) in App.tsx
bootstrap called invoke() without checking if Tauri IPC is available.
When accessing http://localhost:1420/ in a regular browser, this caused
"Cannot read properties of undefined (reading 'transformCallback')".

Also added __TAURI_INTERNALS__ guard in saasStore kernel config sync.
2026-04-03 12:46:14 +08:00
iven
65b73c547f fix(desktop): resolve Tauri state panic on startup
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
SessionStreamGuard and StreamCancelFlags were type aliases to the same
Arc<DashMap<String, Arc<AtomicBool>>> type. Tauri distinguishes managed
state by Rust type, so registering both caused a runtime panic:
"state for type ... is already being managed".

Changed to newtype structs with Deref impl to the inner Arc<DashMap>,
keeping all call sites compatible without changes.
2026-04-03 12:29:10 +08:00
iven
54764a8bbd docs: enforce commit-push-after-comeliminate-work as mandatory step
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
CLAUDE.md §3.3 闭环工作法: 代码通过→提交→推送→文档同步 三步必须按顺序执行,不允许跳过
CLAUDE.md |8.3 收尾流程: 按步骤 A/B/C/D 强制执行
2026-04-03 00:54:14 +08:00
iven
1c697d0b46 chore: 清理临时管理目录并更新文档索引
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
删除 admin-temp-dir 目录及其内容
更新文档索引以包含 dashmap 相关文件
2026-04-03 00:42:48 +08:00
iven
5a5a4b322d docs: update CLAUDE.md with stabilization rules, security audit, and production checklist
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
2026-04-03 00:29:21 +08:00
iven
d8e2954d73 docs: stabilization directive + TRUTH document + AI session prompts + dockerignore
- STABILIZATION_DIRECTIVE.md: feature freeze rules, banned actions, priorities
- TRUTH.md: single source of truth for system state (crate counts, store counts)
- AI_SESSION_PROMPTS.md: three-layer prompt system for AI sessions
- Industry agent delivery design spec
- Stabilization test suite for regression prevention
- Delete stale ISSUE-TRACKER.md
- Add .dockerignore for container builds
- Add brainstorm session artifacts
2026-04-03 00:29:16 +08:00
iven
5c74e74f2a fix(desktop): component cleanup + dead code removal + DeerFlow ai-elements
- ChatArea: DeerFlow ai-elements annotations for accessibility
- Conversation: remove unused Context, simplify message rendering
- Delete dead modules: audit-logger.ts, gateway-reconnect.ts
- Replace console.log with structured logger across components
- Add idb dependency for IndexedDB persistence
- Fix kernel-skills type safety improvements
2026-04-03 00:28:58 +08:00
iven
15d578c5bc fix(tauri): replace silent let _ = with structured logging across 20 modules
Replace error-swallowing let _ = patterns with tracing::warn! in browser,
classroom, gateway, intelligence, memory, pipeline, secure_storage, and
viking command handlers. Ensures errors are observable in production logs.
2026-04-03 00:28:39 +08:00
iven
52bdafa633 refactor(crates): kernel/generation module split + DeerFlow optimizations + middleware + dead code cleanup
- Split zclaw-kernel/kernel.rs (1486 lines) into 9 domain modules
- Split zclaw-kernel/generation.rs (1080 lines) into 3 modules
- Add DeerFlow-inspired middleware: DanglingTool, SubagentLimit, ToolError, ToolOutputGuard
- Add PromptBuilder for structured system prompt assembly
- Add FactStore (zclaw-memory) for persistent fact extraction
- Add task builtin tool for agent task management
- Driver improvements: Anthropic/OpenAI extended thinking, Gemini safety settings
- Replace let _ = with proper log::warn! across SaaS handlers
- Remove unused dependency (url) from zclaw-hands
2026-04-03 00:28:03 +08:00
iven
0a04b260a4 refactor(desktop): ChatStore structured split + IDB persistence + stream cancel
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Split monolithic chatStore.ts (908 lines) into 4 focused stores:
- chatStore.ts: facade layer, owns messages[], backward-compatible selectors
- conversationStore.ts: conversation CRUD, agent switching, IndexedDB persistence
- streamStore.ts: streaming orchestration, chat mode, suggestions
- messageStore.ts: token tracking

Key fixes from 3-round deep audit:
- C1: Fix Rust serde camelCase vs TS snake_case mismatch (toolStart/toolEnd/iterationStart)
- C2: Fix IDB async rehydration race with persist.hasHydrated() subscribe
- C3: Add sessionKey to partialize to survive page refresh
- H3: Fix IDB migration retry on failure (don't set migrated=true in catch)
- M3: Fix ToolCallStep deduplication (toolStart creates, toolEnd updates)
- M-NEW-2: Clear sessionKey on cancelStream

Also adds:
- Rust backend stream cancellation via AtomicBool + cancel_stream command
- IndexedDB storage adapter with one-time localStorage migration
- HMR cleanup for cross-store subscriptions
2026-04-03 00:24:16 +08:00
iven
da438ad868 fix(billing): resolve all audit findings — CSRF, float precision, TOCTOU, error sanitization
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
- Add CSRF token protection for mock payment (SHA256 + constant-time verify)
- Replace f64 currency conversion with pure integer string parsing (parse_yuan_to_cents)
- Move subscription check inside transaction to prevent TOCTOU race
- Rewrite increment_usage to use atomic SQL (account_id+period_start WHERE)
- Add trade_no format validation in payment callback
- Sanitize error messages to prevent sensitive data leakage
- Use i32::try_from for WeChat amount conversion (prevent truncation)
- Replace window.__ZCLAW_STATS_SYNC_INTERVAL__ with useRef pattern
- Replace eprintln/println with tracing macros in lifecycle
- Remove unused variable in scheduler
- Remove duplicate sha2 and unused hmac from Cargo.toml
2026-04-02 20:04:43 +08:00
iven
8898bb399e docs: audit reports + feature docs + skills + admin-v2 + config sync
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
Update audit tracker, roadmap, architecture docs,
add admin-v2 Roles page + Billing tests,
sync CLAUDE.md, Cargo.toml, docker-compose.yml,
add deep-research / frontend-design / chart-visualization skills

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 19:25:00 +08:00
iven
28299807b6 fix(desktop): DeerFlow UI — ChatArea refactor + ai-elements + dead CSS cleanup
ChatArea retry button uses setInput instead of direct sendToGateway,
fix bootstrap spinner stuck for non-logged-in users,
remove dead CSS (aurora-title/sidebar-open/quick-action-chips),
add ai components (ReasoningBlock/StreamingText/ChatMode/ModelSelector/TaskProgress),
add ClassroomPlayer + ResizableChatLayout + artifact panel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 19:24:44 +08:00
iven
d40c4605b2 fix(knowledge): verification audit — 3 medium issues
- create_item: wrap item + version INSERT in transaction for atomicity
- update_item handler: validate content length (100KB) before DB hit
- KnowledgeChunk: document missing embedding field, safe per explicit SELECT usage
2026-04-02 19:16:32 +08:00
iven
7e4b787d5c fix(knowledge): deep audit — 18 bugs fixed across backend + frontend
CRITICAL:
- Migration permission seed WHERE name → WHERE id (matched 0 rows, all KB APIs broken)

HIGH:
- analytics_quality SQL alias + missing comma fix
- search() duplicate else block compile error
- chunk_content duplicate var declarations + type mismatch
- SQL invalid escape sequences
- delete_category missing rows_affected check

MEDIUM:
- analytics_overview hit_rate vs positive_feedback_rate separation
- analytics_quality GROUP BY kc.id,kc.name (same-name category merge)
- update_category handler trim + empty name validation
- update_item duplicate VALID_STATUSES inside transaction
- page_size max(1) lower bound in list handlers
- batch_create title/content/length validation
- embedding dispatch silent error → tracing::warn
- Version modal close clears detailItem state
- Search empty state distinguishes not-searched vs no-results
- Create modal cancel resets form
2026-04-02 19:07:42 +08:00
iven
837abec48a feat(billing): add usage increment API + wire hand/pipeline execution tracking
Server side:
- POST /api/v1/billing/usage/increment endpoint with dimension whitelist
  (hand_executions, pipeline_runs, relay_requests) and count validation (1-100)
- Returns updated usage quota after increment

Desktop side:
- New saas-billing.ts mixin with incrementUsageDimension() and
  reportUsageFireAndForget() (non-blocking, safe for finally blocks)
- handStore.triggerHand: reports hand_executions after successful run
- PipelinesPanel.handleRunComplete: reports pipeline_runs on completion
- SaaSClient type declarations for new billing methods

Billing pipeline now covers all three dimensions:
  relay_requests  → relay handler (server-side, real-time)
  hand_executions → handStore (client-side, fire-and-forget)
  pipeline_runs   → PipelinesPanel (client-side, fire-and-forget)
2026-04-02 02:02:59 +08:00
iven
11e3d37468 feat(billing): activate real-time quota enforcement pipeline
- Wire relay handler to increment_usage() for JSON responses (tokens + relay_requests)
- Wire relay handler to increment_dimension("relay_requests") for SSE streams
- Add increment_dimension() function for hand_executions/pipeline_runs dimensions
- Schedule AggregateUsageWorker hourly for reconciliation (run_on_start=true)
- Mount mock payment routes in dev mode (ZCLAW_SAAS_DEV=true)

Previously the quota middleware always allowed requests because usage
counters were never incremented. Now relay requests update billing_usage_quotas
in real-time, with the aggregator providing hourly reconciliation.
2026-04-02 01:52:01 +08:00
iven
8263b236fd refactor(desktop): wire PipelineResultPreview into PipelinesPanel
Replace the inline ResultModal with the full-featured
PipelineResultPreview component. This gives users JSON/Markdown/
Classroom mode switching, file download cards, and classroom export
support instead of the previous basic PresentationContainer wrapper.

Remove unused ResultModal component and PresentationContainer import.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 01:32:58 +08:00
iven
08268b32b8 feat(memory): implement FactStore SQLite persistence
Add `facts` table to schema with columns for id, agent_id, content,
category, confidence, source_session, and created_at. Implement
store_facts() and get_top_facts() on MemoryStore using upsert-by-id
and confidence-desc ordering. Facts extracted from conversations are
now durable across sessions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 01:26:57 +08:00
iven
1bf0d3a73d fix(memory): CJK-aware short query threshold + Chinese synonym expansion
1. MemoryMiddleware: replace byte-length check (query.len() < 4) with
   char-count check (query.chars().count() < 2). Single CJK characters
   are 3 UTF-8 bytes but 1 meaningful character — the old threshold
   incorrectly skipped 1-2 char Chinese queries like "你好".

2. QueryAnalyzer: add Chinese synonym mappings for 13 common technical
   terms (错误→bug, 优化→improve, 配置→config, etc.) so CJK queries
   can find relevant English-keyword memories and vice versa.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 01:21:29 +08:00
iven
07099e3ef0 test(hands): expand Slideshow tests (4→34) and fix Clip invalid action test
Slideshow: add navigation edge cases, autoplay/pause/resume, spotlight/
laser/highlight defaults, content block deserialization, Hand trait
dispatch, and add_slide helper tests.

Clip: fix test_execute_invalid_action to expect Err (execute returns
HandError for unknown variants).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 01:13:15 +08:00
iven
dce9035584 test(hands): add 28 unit tests for Twitter Hand
Cover config defaults, 13 action types deserialization, serialization
roundtrip, credential management, and data type parsing. Also add
PartialEq derive to HandStatus for test assertions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 01:01:37 +08:00
iven
c8dc654fd4 feat(admin-v2): add billing management page
- Plan cards with feature comparison and pricing
- Usage progress bars with quota visualization
- Alipay/WeChat Pay method selection modal
- Payment status polling with auto-refresh on success
- Navigation + route registration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 00:48:35 +08:00
iven
b1e3a27043 feat(saas): add payment integration with Alipay/WeChat mock support
- payment.rs: create_payment, handle_payment_callback, query_payment_status
- Mock pay page for development mode with HTML confirm/cancel flow
- Payment callback handler with subscription auto-creation on success
- Alipay form-urlencoded and WeChat JSON callback parsing
- 7 new routes including callback and mock-pay endpoints

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 00:41:35 +08:00
iven
becfda3fbf feat(admin-v2): add Knowledge base management page
- 4 tabs: Items (CRUD + ProTable), Categories (tree management), Search, Analytics
- Knowledge service with full API integration
- Nav item + breadcrumb + route registration
- Analytics overview with 8 KPI statistics

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 00:34:17 +08:00
iven
830e9fa301 feat(saas): add GenerateEmbedding worker for knowledge chunking
- Markdown-aware content splitting (512 token chunks with 64 overlap)
- CJK keyword extraction from chunk content with stop-word filtering
- Full refresh strategy (delete old chunks → re-insert on update)
- Phase 2 placeholder for vector embedding API integration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 00:23:38 +08:00
iven
ef60f9a183 feat(saas): add knowledge base module — categories, items, versions, search, analytics
- 5 knowledge tables (categories, items, chunks, versions, usage) with pgvector + HNSW + GIN indexes
- 23+ API routes covering full CRUD, tree-structured categories, version snapshots
- Keyword-based search with ILIKE + array match (placeholder for vector search)
- Analytics endpoints: overview, trends, top-items, quality, gaps
- Markdown-aware content chunking with overlap strategy
- Worker dispatch for async embedding generation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 00:21:28 +08:00
iven
b66087de0e feat(saas): add quota middleware and usage aggregation worker
B1.3 Quota middleware:
- quota_check_middleware for relay route chain
- Checks monthly relay_requests quota before processing
- Gracefully degrades on billing service failure

B1.5 AggregateUsageWorker:
- Aggregates usage_records into billing_usage_quotas monthly
- Supports single-account and all-accounts modes
- Scheduled hourly via Worker dispatcher (6 workers total)
2026-04-02 00:06:39 +08:00
iven
d06ecded34 feat(saas): add quota check middleware for relay requests
Injects billing quota verification before relay chat completion requests.
Checks monthly relay_requests quota via billing::service::check_quota.
Gracefully degrades on quota service failure (logs warning, allows request).
2026-04-02 00:03:26 +08:00
iven
9487cd7f72 feat(saas): add billing infrastructure — tables, types, service, handlers
B1.1 Billing database:
- 5 tables: billing_plans, billing_subscriptions, billing_invoices,
  billing_payments, billing_usage_quotas
- Seed data: Free(¥0)/Pro(¥49)/Team(¥199) plans
- JSONB limits for flexible plan configuration

Billing module (crates/zclaw-saas/src/billing/):
- types.rs: BillingPlan, Subscription, Invoice, Payment, UsageQuota
- service.rs: plan CRUD, subscription lookup, usage tracking, quota check
- handlers.rs: REST API (plans list/detail, subscription, usage)
- mod.rs: routes registered at /api/v1/billing/*

Cargo.toml: added chrono feature to sqlx for DateTime<Utc> support
2026-04-01 23:59:46 +08:00
iven
c6bd4aea27 feat(pipelines): add 10 industry-specific pipeline templates
Education (3): research-to-quiz, student-analysis, lesson-plan
Healthcare (3): policy-compliance, meeting-minutes, data-report
Design Shantou (4): trend-to-design, competitor-research,
  client-communication, supply-chain-collect
2026-04-01 23:43:45 +08:00
iven
17a2501808 test(hands): add unit tests for BrowserHand + fix requires_approval config
Fix needs_approval field in BrowserHand::new() from false to true to
match the TOML config (hands/browser.HAND.toml says requires_approval = true).
Browser automation has security implications and should require approval.

Add 11 unit tests covering:
- Config id and enabled state
- needs_approval correctness (after fix)
- Action deserialization (Navigate, Click, Type, Scrape, Screenshot)
- Roundtrip serialization for all major action variants
- BrowserSequence builder with stop_on_error()
- Multi-step sequence execution
- FormField deserialization

Also add stop_on_error() builder method to BrowserSequence which was
referenced in the test plan but missing from the struct.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 23:22:18 +08:00