Commit Graph
253 Commits
Author SHA1 Message Date
hmo d5b8bec897 refactor: retire price_events.json completely — DB is the only store
User directive: no JSON, retire it fully, fix all related code.

Changes:
- price_monitor.py: record_event writes DB only; removed EVENTS_PATH/
  load_events/save_events entirely
- strategy_feedback.py: price events read from DB only (removed JSON fallback)
- system_health_check.py: removed price_events.json from file-check list,
  DB-only event stats (was showing 0/0 due to wrong-DB resolution)
- mo_config.py: removed dead price_events_path property (no callers)
- mofin_health.py: price_events freshness reads DB table (authoritative now)
- mofin_db.py: DATA_DIR/DB_PATH now ABSOLUTE (/home/hmo/MoFin/data) —
  was relative __file__.parent, so each hardlinked copy of mofin_db.py
  resolved to a DIFFERENT database (canonical vs web-dashboard vs
  profile-local third DB with 0 rows of everything except market_snapshots).
  This fragmentation was the real cause of health checks reading empty tables.
- Unified all 4 mofin_db copies (root/scripts/deploy/profile) via hardlink
- price_events.json archived to trashbox (fully backfilled: 6353 rows in DB)

Verified:
- record_event lands in DB only, JSON not recreated
- system_health_check: 历史事件 6353 / 今日事件 2965 (was 0/0)
- strategy_feedback + price_monitor full runs clean
2026-07-20 18:10:05 +08:00
hmo efdfaf956a fix(price_events): unify event storage to DB (dual-write + backfill)
User caught the inconsistency: system claims DB-first but price events
only went to price_events.json, leaving DB table stale since Jul 6.

Root cause chain found:
- record_event() only wrote JSON, never called mofin_db.write_price_event
- price_events.code has FK -> stocks(code); events for unregistered stocks
  (new candidates, HK) silently failed INSERT and were lost to DB
- mofin_db.write_price_event swallows errors (returns False silently)

Fixes:
- record_event now dual-writes: DB (authoritative) + JSON (compat for
  legacy readers mo_config/strategy_feedback/system_health_check)
- auto-registers unknown codes into stocks table before event insert
- one-time backfill: 4064 JSON events -> DB (total 6353 rows, last=today)
- verified: record_event TEST99 lands in both DB and JSON
2026-07-20 17:46:57 +08:00
hmo bbc4ebf93d chore: investigation + notification scripts 2026-07-20 17:33:39 +08:00
hmo 17305bed0b fix(pipelines): clear today's real cron errors + kill monitoring false alarms
Real errors fixed (all verified by manual run):
- price_monitor.py: shares None -> TypeError at L584 (now completes 3m7s,
  full 39-stock reassess + zone triggers + Dad push)
- market_insight.py: net_inflow None -> TypeError at L142 (now 0.3s, 5 insights)
- promote_candidates.py: add busy_timeout=30s (DB lock under concurrent writes)
- premarket_full_review.py: 12-dim analysis now detached background launch
  (was doomed by cron 120s script timeout no matter what)

Systemic:
- HERMES_CRON_SCRIPT_TIMEOUT=600 drop-in for both gateway services
  (fixes mofin_health SIGTERM, market_watch timeout, memory_guardian timeout)
- sync_profile_scripts.sh: re-hardlink deploy->profile scripts after every
  deploy (scp replaces files = new inode = broken hardlink = cron silently
  runs stale code; this caused promote to keep failing after my first fix)

Monitoring false-alarm fixes (the '花瓶' problem):
- mofin_health.py: legacy JSONs that migrated to DB (multi_tf_cache/
  macro_context/market/live_prices/price_history/macro_risk_state) no longer
  warn 'no readers'; marked as migrated
- NEW db_freshness section: real pipeline health from DB tables
  (mtf_cache 0.4h / macro_context_log 2h / market_snapshots 2h /
  live_prices 0.4h / price_events.json 0.4h — ALL HEALTHY)
- price_events freshness reads live JSON store (DB table is legacy)
- market.json placeholder created (13+ scripts have fallback paths)

Investigation notes: wiki-self-growth 03:04 key1 429 predates full key6
activation on default gateway; current 8642 verified on key6 and working.
Weekend 'Blocked' jobs verified fixed (vacuum_state_db passes).
2026-07-20 17:30:15 +08:00
hmo a40b97f5ca feat(analysis): systematic daily 12-dim LLM analysis for holdings+watchlist
Gap (reported by user via zhiwei): premarket full review updated technical
params but full_analysis (12-dim LLM matrix) was empty for new holdings
and stale for old ones — batch_reassess existed but was never wired into
the daily pipeline and only covered watchlist.

System fix:
- premarket_full_review.py: new Step 1.5 runs batch_reassess --type
  holding --today every trading day 08:10 (force-refresh today's analysis,
  timeout 3600s, result in summary.json)
- batch_reassess.py:
  - coverage: --type holding|watchlist|all (was watchlist-only)
  - staleness: analysis >20h stale gets refreshed (was: skip if any
    analysis exists = forever stale)
  - --today flag: force re-analyze if not reassessed since 04:00 today
  - cash/total read live from portfolio_summary (was hardcoded 321271/
    952879 from weeks ago)
  - HK stock prefix fix (5-digit codes -> hk, was sending sz00700)
- watchlist_12d_backfill.py: wrapper for hermes cron (no args support)
- cron job '批量补全九维分析-一次性' -> '自选12维分析补全-每日午间'
  (daily 12:30 weekdays, covers 109 watchlist stocks missing analysis)

Verified: 300308 got 1920-char 12-dim analysis written to DB at 08:41,
signal=观望, stop/take-profit updated.
2026-07-20 08:48:08 +08:00
hmo 115292bb96 fix(scripts): promote UNIQUE crash + candidate_filter DB lock (morning readiness)
Pre-open error sweep (all verified by manual run):
- promote_candidates.py: INSERT OR IGNORE + only newly-added stocks count
  toward promotion/XMPP (was crashing on first duplicate, never finishing;
  now completes 40s, promoted 74 with correct skip marking)
- candidate_filter.py: PRAGMA busy_timeout=30s (was dying on transient
  'database is locked' under concurrent cron writes; now completes 9.6s)
- price_monitor.py: verified completes 1m55s (< 120s cron timeout) with
  working LLM reassess via key6
- macro_context_collector.py / divergence_detector.py: previously
  'Blocked' by symlink check, now run fine (8.7s / 1m55s)
- memory_guardian.py: completes 1m55s with key6
- preflight sync diff: historical, files now identical

Production proof: 大脑任务执行 (was 429 every 10min) now status=ok at 01:21
2026-07-20 01:34:37 +08:00
hmo 57377e9dd3 feat(auto_heal): multi-profile key switching + fix two error classes
Error investigation (from restored monitoring) found 2 root causes:

1. 'Blocked: script path resolves outside scripts dir' (5+ cron jobs):
   Jul 17 symlink refactor replaced real scripts with symlinks; the hermes
   cron scheduler's security check (Path.resolve + relative_to) rejects
   symlink escape. ALL no_agent script jobs blocked since Jul 17 23:12.
   FIX: converted 102 symlinks to hardlinks (same inode, resolve() stays
   inside scripts_dir, single-source still works). Permanent structural fix.

2. HTTP 429 on default profile (知识研究/梦境循环/wiki-self-growth/
   evolution-pulse/大脑任务执行): default gateway used ocg-key1 (weekly
   100%). FIX: switched default profile to ocg-key6 + added missing
   provider block. LLM verified working (3.1s).

auto_heal extended to actually cover these automatically next time:
- PROFILES registry: zhiwei (8643, system svc) + default (8642, user svc)
- current_provider/switch_key/_scan_agent_log parameterized by profile
- health() now reports llm_provider_default (agent.log scan)
- auto_heal: per-profile 429 detection -> best_key -> switch_key(profile)
- _ensure_provider_block: injects missing provider credentials from
  zhiwei config (single source of truth) into target config
2026-07-20 01:12:38 +08:00
hmo a05c118cbc feat(dashboard): restore lost monitoring + add 开发原则 tab (AgentsMeeting parity)
Two regressions fixed:

1. RESTORED: original health monitoring (功能树/全部Cron/数据实体/数据流)
   was an iframe to /mofin_health.html — refactor replaced it with a
   minimal services-only panel and lost all of it. mofin_health.json
   (86KB, fresh) was still being generated the whole time.
   - 健康 tab: XMPP panel (native) + restored iframe below

2. ADDED: 开发原则 parent tab replicating AgentsMeeting structure:
   - G 规范: /api/spec renders docs/dev-spec.md + git history
   - K 测试: /api/tests renders agents_health_check report as pass/fail
   - F 健康: iframe to /mofin_health.html + link to 健康 tab
   - H 需求: /api/prd (placeholder — prd.md not yet created)
   - mdRender() ported from AgentsMeeting dashboard
2026-07-20 00:40:32 +08:00
hmo 2de527b883 fix(health): drop live LLM ping — scan agent.log instead (38s -> 0.1s)
Every /api/xmpp/health fetch ran a real LLM call (22k token system prompt
each). Dashboard refreshes every 10s -> thousands of paid LLM calls/day,
plus 38s latency hanging the health tab on '加载中...'.

LLM health is now derived from the gateway's own agent.log (zero cost,
more accurate than synthetic ping — real traffic results):
- last 'API call #N latency=Xs' -> ok
- last 'API call failed ... HTTP 429...' -> error with summary
- health() runtime 38s -> 0.1s; endpoint 38s -> 0.097s
2026-07-20 00:21:49 +08:00
hmo 058c42ce27 feat(health): recent XMPP conversation log panel + stale error fix
User requirement: health tab should show recent XMPP conversations.
- bot hooks log_xmpp on inbound (on_msg) and outbound (_deliver_loop)
  so real chats land in xmpp_messages.jsonl (was: only cron/scanner)
- index.html health tab: new '最近对话' panel (last 10 msgs, dir arrow,
  preview, status, time); refreshHealth updates it incrementally
- last_error now shows age and resolved state: once a successful
  outbound happens after an error, it's shown gray as '已恢复'
  instead of alarming red forever; unresolved errors still red
- health() status no longer degraded by errors that were later
  resolved by successful outbound
2026-07-20 00:07:28 +08:00
hmo bb1529909b feat(bot): screenshot OCR pipeline + ack delay 120s
D fix: screenshots were silently dropped (empty body + OOB url).
- register xep_0066, capture msg['oob']['url'] when body empty
- also handle body-as-URL messages (some clients put URL in body)
- download from upload.yoin.fun, OCR via SenseNova (sensenova-6.7-flash-lite)
- inject OCR text as context into LLM call
- config at /home/hmo/.config/mofin/ocr_config.json (outside repo)
- replaces dead node122 GLM-OCR path (host unreachable)

A+B fix: ACK_DELAY 15s -> 120s. 15s fired on every normal LLM
cold-start (20-100s), now only signals genuine hangs.
2026-07-19 23:23:46 +08:00
hmo e0f47f9349 fix(xmpp_monitor): exclude key7(kimi) from auto-heal switch candidates
zhiwei must stay on ocg-key6 (deepseek-v4-flash) per user decision.
key7 is kimi — different model provider, incompatible model name.
If best_key returns key7, auto_heal logs skip_switch instead of switching.
2026-07-19 22:09:15 +08:00
hmo 9509b80d8b feat(xmpp_monitor): dynamic key switching + coalesce auto-heal
- xmpp_logger.py:
  - Add switch_key(key_id): switch Hermes model.provider via sed + systemctl restart
  - Add current_provider() reading model: block correctly (not just first '  provider:' line)
  - Add KEY_TO_PROVIDER mapping (AgentsMeeting key_id -> Hermes provider name)
  - Add RESTART_COOLDOWN_FILE/SEC = 180s to prevent restart loops
  - auto_heal(): detect HTTP 429 / Weekly usage limit -> call best_key() -> switch_key()
  - auto_heal(): detect timeout/error -> async systemctl restart (Popen, not blocking)
  - _verify_llm(): bump timeout 25s -> 90s (cold-start gateway takes 20-40s)
  - health(): urlopen timeout 8s -> 90s (match verify window)
  - Use sudo NOPASSWD (hmo ALL=(ALL) NOPASSWD: ALL already configured)

- agents_health_check.py:
  - Replace inline pkill+Popen restart logic (caused multiple instances) with systemctl
  - Add RESTART_COOLDOWN_FILE state to skip restart within 3 min of last
  - Call xmpp_logger.auto_heal() at end of every cron cycle
  - Both inline restart and auto_heal restarts share cooldown file

- scripts/key_status.py: Reports weekly/monthly/rolling status of all 6 OCG keys
- scripts/test_llm.py: 90s timeout test (was 15s, gateway cold-start >= 30s)
- scripts/test_production.py: smoke test on /home/hmo/MoFin/ (hardlinked to web-dashboard)

Fixes:
- Old assumption 'Cloudflare blocks Python User-Agent' was WRONG.
  True cause was HTTP 429 Weekly usage limit on key5 (12hr reset window).
  Hermes silently ignored providers.X.headers config keys; only model.default_headers works.
  Config already has model.default_headers: User-Agent: curl/8.5.0 (defense in depth).
- Multiple gateway instances were caused by 3 competing systemd units
  (hermes-gateway@.service template + hermes-gateway-zhiwei.service named).
  Masked the template unit @position-analyst and @zhiwei so only the named one wins.
2026-07-19 20:12:47 +08:00
hmo b41bed7959 feat: XMPP observability — logger, monitor endpoints, clean dead xiaoguo refs 2026-07-19 12:47:15 +08:00
hmo b08bfa5d03 refactor: integrate dashboard into server.py :8899, remove standalone dashboard 2026-07-19 11:06:50 +08:00
hmo 782a914a3c fix: dashboard port 5804→5807 (avoid conflicts with wechat_webhook and zhiwei bot) 2026-07-19 10:56:42 +08:00
知微 90966c63ca chore: 同步运行版本与git一致
- strategy_lifecycle.py: GATE_9D_ANALYSIS → GATE_12D_ANALYSIS(12维交叉验证)
- system_audit.py: 审计策略评估改用holding_strategies.updated_at
- CHANGELOG.md + analyst-knowledge-log.md 日常更新
2026-07-17 23:08:11 +08:00
知微 b4a5020cf5 fix: 暴跌告警仅持仓触发 + 状态立即持久化防重复推送 2026-07-14 15:33:35 +08:00
知微 2c0d6ff587 fix: Gateway看门狗v2 — 新增session健康检查,卡死自动重启 2026-07-14 15:00:56 +08:00
知微 c9ae1e143b fix: cron_to_xmpp取最后一个Response节防误判(parts[1]→parts[-1]) 2026-07-14 12:14:08 +08:00
知微 377bb4d1e4 price_monitor: 5min regenerate_all冷却 + 跳过冗余全量重评 2026-07-14 11:48:34 +08:00
知微 d972553b6e fix: divergence_detector 改用新浪API直接获取指数数据(原mo_data不支持指数代码) 2026-07-14 11:08:07 +08:00
知微 136f3f9fb8 sync scripts/mofin_db.py with root + knowledge log 2026-07-14 11:01:59 +08:00
知微 59e94d135c fix: 盘中脚本统一使用get_conn()替代raw sqlite3.connect防DB死锁
- mofin_health.py, cron_health_monitor.py, intraday_health_check.py,
  self_todo_executor.py: 替换raw sqlite3.connect() → get_conn()
  统一使用WAL模式+busy_timeout=30s连接
- mofin_db.py: get_conn()每次新建连接时WAL checkpoint
  防止被kill进程残留WAL导致后续全部卡死
- 并发测试验证: 3x price_monitor + 3x mofin_health同时运行
  6/6通过,WAL仅32bytes

关联问题: 2026-07-14 SQLite写锁死锁根因诊断
2026-07-14 10:56:38 +08:00
知微 3ee3d9ba6c fix: price_monitor添加os.nice(10)降低优先级减少DB竞争 2026-07-14 10:47:58 +08:00
知微 93dce81413 fix: price_monitor DB写锁死锁根治 + mofin_db.py reassessed_at同步
1. price_monitor.py: 统一BEGIN IMMEDIATE包裹所有DB写操作,
   5次重试+指数退避(1→2→4→8→16s),重试耗尽后自动
   emergency WAL checkpoint,try/finally确保conn释放
2. 补充进程锁:防止cron每2分钟触发但脚本跑3分钟时的并发
3. mofin_db.py: 同步cron版本的reassessed_at列处理逻辑
2026-07-14 10:42:54 +08:00
知微 02d1c93923 fix(price_monitor): DB写锁死锁根治 - 统一BEGIN IMMEDIATE + 5次重试指数退避 + emergency WAL checkpoint
- 统一一个BEGIN IMMEDIATE事务包裹所有写操作,替代独立写函数调用
- 5次重试 + 指数退避 (1s,2s,4s,8s,16s),原3次+固定2s
- 重试耗尽后自动 emergency WAL checkpoint(TRUNCATE)释放死锁
- try/except确保连接始终释放,修复conn泄漏
- 三副本同步:profile/scripts + MoFin/scripts + MoFin/root
2026-07-14 10:30:15 +08:00
知微 9239ab40c0 docs: 更新CHANGELOG + 开发日志记录07/13全部变更
- XMPP Bot非阻塞/本地XMPP/MUC修复
- price_monitor推送冷却持久化
- 深套股规则重构+换股规划swap-plan
- 周月线技术分析增强
- 健康Tab写无读清零
- stale_push_wlin/per_stock_reassess/promote_candidates更新
- static/index.html + mofin_health.json + server.py同步
2026-07-13 12:09:25 +08:00
知微 2109289668 feat: 换股规划 swap-plan — 深套股可替代性排序+资金释放方案
- print_swap_plan(): 五维评分(亏损程度/仓位/技术趋势/流动性/前景)
- 排序输出,明确标注"当前亏损X%深套"而非"深套持有"
- --need 参数模拟指定资金需求,自动计算卖几只够
- 可独立运行:python strategy_lifecycle.py swap-plan [--need 金额]
2026-07-13 12:05:36 +08:00
知微 a6d37c6f30 fix: 删除深套股全部硬编码限制——该加就加,一切根据客观判断
- 删除 is_deep_loss 对止损/止盈/买入区/推荐的全部 guard
- 删除 action_note="深套持有" 覆盖
- 删除 position_advice="不补不割" / time_horizon="长期"
- 深套股回归正常分析流程,stock_category="深套"仅作标签
- "深套持有" 改为 "亏损X%深套" 实际状态描述
2026-07-13 12:02:06 +08:00
知微 be961c6af6 fix: _push_cooldown持久化到文件,避免每2分钟重复推送操作区间通知 2026-07-13 11:17:59 +08:00
知微 ab72288296 fix: stock_weekly/monthly/watchlist_log加manual readers消除写无读警告 2026-07-10 21:12:28 +08:00
知微 e92e4473c8 feat: 周线+月线趋势/MA/支撑阻力注入mtf_context 2026-07-10 21:07:59 +08:00
知微 ea139b05b0 fix: 每日汇总只发一次(16:35)+加sent标记防重复 2026-07-10 17:05:29 +08:00
知微 e2f02ad023 fix: 资金流采集器正常运行(修import+科创板null处理) 2026-07-10 14:06:20 +08:00
知微 ea07d8c8df feat: 买入信号写入时自动推XMPP通知(通过5805桥) 2026-07-10 13:58:23 +08:00
知微 49ef74826a fix: 触发重评推送条件收紧(仅买入/加仓/卖出/止盈信号才推) 2026-07-10 13:43:39 +08:00
知微 b9ba737248 fix: 不构成操作建议不推XMPP+代码降级改报错+LLM失败=None 2026-07-10 13:29:32 +08:00
知微 ba70700e4d fix: 代码降级分析也加时间标注+LLM路径日志改为12维 2026-07-10 13:23:34 +08:00
知微 98d6189b69 feat: 每维数据标注时间窗口(MA日数/资金近5日/消息最近3条/财报最新) 2026-07-10 13:17:40 +08:00
知微 005903af83 fix: 9维→12维(3横×4纵:大盘/行业/个股×基本面/消息面/技术面/资金面) 2026-07-10 12:47:05 +08:00
知微 c79fb53722 feat: 盘前全量重评(08:10)+自选退出机制+进出日志 2026-07-10 12:20:18 +08:00
知微 8d733ca16a fix: deploy_sync新增mofin_db.py同步(根目录→profile) 2026-07-10 11:59:08 +08:00
知微 7f65f0cbd2 fix: 九维分析全面升级-资金流+消息面入prompt+交叉综合+capital_flow_collector修mo_data引用 2026-07-10 11:45:03 +08:00
知微 c48429b994 feat: 单日暴跌>7%实时告警(不依赖zone边界) 2026-07-10 11:30:46 +08:00
知微 73df767ac0 fix: 买入区用live_prices+统一DB读取+报告前验价 2026-07-10 10:26:14 +08:00
知微 e461c57028 fix: stale_detector零标记漏洞(买入区上沿~+20%未覆盖) 2026-07-10 09:43:27 +08:00
知微 66c3cfecc3 fix: 健康监控全绿(小果cron移除+死表清理+补录写入方) 2026-07-10 01:02:52 +08:00
知微 b63bfc11f5 fix: 仓位输出要求带一句话理由 2026-07-10 00:54:57 +08:00
知微 ebc3a15f73 fix: 仅买入信号输出仓位+仓位计算公式(RR/大盘/品种) 2026-07-10 00:14:52 +08:00