{"repo": "binbinyu99-crypto/wuxing-flywheel", "files": {"engine/wuxing_balance.py": {"40c43465d8c9ddef6690ba2d5c45804ab1a12cfd": {"t": 1785599308.254503, "n": 9904, "h": "e30441cedb922d92", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nWuxing Balance Monitor - Five Elements Imbalance Detection\nDetects when any single element dominates and triggers auto-rebalancing.\n\nWuxing Basis:\n- Each element should occupy ~20% of system activity\n- imbalance_ratio > 2.0 triggers rebalancing\n- Rebalancing uses xiangke (mutual restraint) to suppress dominant element\n\"\"\"\nimport json, os, time, urllib.request\nfrom datetime import datetime\n\nHUB_URL = \"http://localhost:19104\"\n\n# Five elements and their task phase mappings\nELEMENT_PHASES = {\n \"wood\": {\"keywords\": [\"seed\", \"idea\", \"diverge\", \"create\", \"brainstorm\", \"explore\", \"wood\", \"mu\", \"qinglong\"],\n \"label\": \"Wood/Mu\", \"emoji\": \"wood\", \"role\": \"Seed/Divergence\"},\n \"fire\": {\"keywords\": [\"execute\", \"analyze\", \"build\", \"deploy\", \"run\", \"fire\", \"huo\", \"zhuque\", \"implement\"],\n \"label\": \"Fire/Huo\", \"emoji\": \"fire\", \"role\": \"Execution/Output\"},\n \"earth\": {\"keywords\": [\"deliver\", \"feedback\", \"review\", \"report\", \"earth\", \"tu\", \"hub\", \"integrate\", \"merge\"],\n \"label\": \"Earth/Tu\", \"emoji\": \"earth\", \"role\": \"Delivery/Feedback\"},\n \"metal\": {\"keywords\": [\"validate\", \"adversarial\", \"audit\", \"check\", \"metal\", \"jin\", \"baihu\", \"quality\", \"test\"],\n \"label\": \"Metal/Jin\", \"emoji\": \"metal\", \"role\": \"Validation/Adversarial\"},\n \"water\": {\"keywords\": [\"learn\", \"converge\", \"knowledge\", \"research\", \"water\", \"shui\", \"xuanwu\", \"study\", \"cognition\"],\n \"label\": \"Water/Shui\", \"emoji\": \"water\", \"role\": \"Learning/Convergence\"},\n}\n\n# Xiangke pairs: dominant -> suppressed_by\nXIANGKE_SUPPRESS = {\n \"wood\": \"metal\", # jin ke mu\n \"fire\": \"water\", # shui ke huo\n \"earth\": \"wood\", # mu ke tu\n \"metal\": \"fire\", # huo ke jin\n \"water\": \"earth\", # tu ke shui\n}\n\n# Rebalancing actions\nREBALANCE_ACTIONS = {\n \"wood\": {\"action\": \"throttle_seeds\", \"boost\": \"fire\", \"desc\": \"Too many seeds - throttle creation, boost execution\"},\n \"fire\": {\"action\": \"slow_claiming\", \"boost\": \"earth\", \"desc\": \"Execution overload - slow claiming, force delivery\"},\n \"earth\": {\"action\": \"trigger_review\", \"boost\": \"metal\", \"desc\": \"Delivery backlog - auto-trigger adversarial review\"},\n \"metal\": {\"action\": \"ease_standards\", \"boost\": \"wood\", \"desc\": \"Over-validation - ease standards, boost diversity\"},\n \"water\": {\"action\": \"force_seeding\", \"boost\": \"wood\", \"desc\": \"Cognition idle - force seed generation from knowledge\"},\n}\n\nIMBALANCE_THRESHOLD = 2.0\nCRITICAL_THRESHOLD = 3.0\n\ndef classify_task(task):\n \"\"\"Classify a task into a Wuxing element based on keywords\"\"\"\n title = (task.get(\"title\", \"\") + \" \" + task.get(\"description\", \"\")).lower()\n task_id = task.get(\"task_id\", \"\").lower()\n combined = title + \" \" + task_id\n \n scores = {}\n for element, config in ELEMENT_PHASES.items():\n score = sum(1 for kw in config[\"keywords\"] if kw in combined)\n scores[element] = score\n \n if max(scores.values()) == 0:\n return \"earth\" # default to earth (delivery/general)\n \n return max(scores, key=scores.get)\n\ndef fetch_tasks():\n \"\"\"Fetch all tasks from Hub\"\"\"\n try:\n req = urllib.request.Request(f\"{HUB_URL}/api/v1/tasks?limit=500\")\n with urllib.request.urlopen(req, timeout=10) as resp:\n data = json.loads(resp.read().decode())\n if isinstance(data, list):\n return data\n return data.get(\"tasks\", data.get(\"data\", []))\n except Exception as e:\n print(f\"Hub fetch error: {e}\")\n return []\n\ndef analyze_balance(tasks=None):\n \"\"\"Analyze current Wuxing balance across all tasks\"\"\"\n if tasks is None:\n tasks = fetch_tasks()\n \n # Count by element\n counts = {e: 0 for e in ELEMENT_PHASES}\n pending_counts = {e: 0 for e in ELEMENT_PHASES}\n completed_counts = {e: 0 for e in ELEMENT_PHASES}\n \n for task in tasks:\n element = classify_task(task)\n counts[element] += 1\n status = task.get(\"status\", \"pending\")\n if status in (\"pending\", \"claimed\", \"in_progress\"):\n pending_counts[element] += 1\n elif status in (\"completed\", \"done\"):\n completed_counts[element] += 1\n \n total = sum(counts.values())\n if total == 0:\n return {\"balanced\": True, \"counts\": counts, \"total\": 0, \"alerts\": []}\n \n avg = total / 5.0\n \n # Calculate ratios\n ratios = {}\n for e in ELEMENT_PHASES:\n ratios[e] = counts[e] / avg if avg > 0 else 0\n \n # Detect imbalances\n alerts = []\n dominant = max(ratios, key=ratios.get)\n weakest = min(ratios, key=ratios.get)\n \n if ratios[dominant] > CRITICAL_THRESHOLD:\n suppressor = XIANGKE_SUPPRESS[dominant]\n action = REBALANCE_ACTIONS[dominant]\n alerts.append({\n \"level\": \"CRITICAL\",\n \"dominant\": dominant,\n \"ratio\": round(ratios[dominant], 2),\n \"suppressor\": suppressor,\n \"action\": action[\"action\"],\n \"boost\": action[\"boost\"],\n \"description\": action[\"desc\"],\n })\n elif ratios[dominant] > IMBALANCE_THRESHOLD:\n suppressor = XIANGKE_SUPPRESS[dominant]\n action = REBALANCE_ACTIONS[dominant]\n alerts.append({\n \"level\": \"WARNING\",\n \"dominant\": dominant,\n \"ratio\": round(ratios[dominant], 2),\n \"suppressor\": suppressor,\n \"action\": action[\"action\"],\n \"boost\": action[\"boost\"],\n \"description\": action[\"desc\"],\n })\n \n if ratios[weakest] < 0.3 and total > 20:\n alerts.append({\n \"level\": \"DEFICIT\",\n \"element\": weakest,\n \"ratio\": round(ratios[weakest], 2),\n \"description\": f\"{ELEMENT_PHASES[weakest]['label']} severely underrepresented\",\n })\n \n return {\n \"balanced\": len(alerts) == 0,\n \"timestamp\": datetime.now().isoformat(),\n \"total_tasks\": total,\n \"counts\": counts,\n \"pending\": pending_counts,\n \"completed\": completed_counts,\n \"ratios\": {e: round(r, 2) for e, r in ratios.items()},\n \"dominant\": dominant,\n \"weakest\": weakest,\n \"imbalance_ratio\": round(ratios[dominant], 2),\n \"alerts\": alerts,\n \"xiangke_map\": XIANGKE_SUPPRESS,\n }\n\ndef get_rebalance_recommendations(analysis):\n \"\"\"Generate actionable recommendations from balance analysis\"\"\"\n if analysis[\"balanced\"]:\n return [\"System is balanced. No action needed.\"]\n \n recs = []\n for alert in analysis[\"alerts\"]:\n if alert[\"level\"] in (\"CRITICAL\", \"WARNING\"):\n dom = alert[\"dominant\"]\n sup = alert[\"suppressor\"]\n recs.append(f\"[{alert['level']}] {ELEMENT_PHASES[dom]['label']} dominates (ratio {alert['ratio']}x)\")\n recs.append(f\" -> Apply {ELEMENT_PHASES[sup]['label']} constraint ({XIANGKE_SUPPRESS[dom]})\")\n recs.append(f\" -> Action: {alert['description']}\")\n recs.append(f\" -> Boost: {ELEMENT_PHASES[alert['boost']]['label']}\")\n elif alert[\"level\"] == \"DEFICIT\":\n elem = alert[\"element\"]\n recs.append(f\"[DEFICIT] {ELEMENT_PHASES[elem]['label']} underrepresented (ratio {alert['ratio']}x)\")\n recs.append(f\" -> Generate more {elem} tasks\")\n \n return recs\n\ndef format_balance_report(analysis):\n \"\"\"Format a human-readable balance report\"\"\"\n lines = []\n lines.append(\"=== Wuxing Balance Report ===\")\n lines.append(f\"Time: {analysis.get('timestamp', 'N/A')}\")\n lines.append(f\"Total Tasks: {analysis['total_tasks']}\")\n lines.append(\"\")\n \n for e in [\"wood\", \"fire\", \"earth\", \"metal\", \"water\"]:\n cfg = ELEMENT_PHASES[e]\n count = analysis[\"counts\"][e]\n ratio = analysis[\"ratios\"].get(e, 0)\n bar = \"#\" * int(ratio * 10)\n status = \"OK\" if 0.5 <= ratio <= 2.0 else (\"HIGH\" if ratio > 2.0 else \"LOW\")\n lines.append(f\" {cfg['label']:12s} | {count:4d} | ratio {ratio:.2f} | {bar:20s} | {status}\")\n \n lines.append(\"\")\n lines.append(f\"Dominant: {analysis['dominant']} ({analysis['imbalance_ratio']}x)\")\n lines.append(f\"Weakest: {analysis['weakest']}\")\n lines.append(f\"Balanced: {analysis['balanced']}\")\n \n if analysis[\"alerts\"]:\n lines.append(\"\")\n lines.append(\"ALERTS:\")\n for rec in get_rebalance_recommendations(analysis):\n lines.append(f\" {rec}\")\n \n return \"\\n\".join(lines)\n\n\nif __name__ == \"__main__\":\n print(\"=== Wuxing Balance Self-Test ===\")\n \n # Test with mock tasks\n mock_tasks = []\n for i in range(30):\n mock_tasks.append({\"title\": f\"seed idea {i}\", \"task_id\": f\"T-SEED-{i}\", \"status\": \"pending\"})\n for i in range(10):\n mock_tasks.append({\"title\": f\"execute analysis {i}\", \"task_id\": f\"T-EXEC-{i}\", \"status\": \"completed\"})\n for i in range(5):\n mock_tasks.append({\"title\": f\"validate audit {i}\", \"task_id\": f\"T-AUDIT-{i}\", \"status\": \"pending\"})\n for i in range(3):\n mock_tasks.append({\"title\": f\"research learn {i}\", \"task_id\": f\"T-LEARN-{i}\", \"status\": \"completed\"})\n for i in range(2):\n mock_tasks.append({\"title\": f\"deliver report {i}\", \"task_id\": f\"T-REPORT-{i}\", \"status\": \"completed\"})\n \n analysis = analyze_balance(mock_tasks)\n print(format_balance_report(analysis))\n \n assert not analysis[\"balanced\"], \"Should detect imbalance\"\n assert analysis[\"dominant\"] == \"wood\", f\"Wood should dominate, got {analysis['dominant']}\"\n assert len(analysis[\"alerts\"]) > 0, \"Should have alerts\"\n assert analysis[\"alerts\"][0][\"suppressor\"] == \"metal\", \"Metal should suppress wood\"\n \n print(\"\\nAll tests passed!\")\n \n # Try real Hub data\n print(\"\\n=== Live Hub Analysis ===\")\n live = analyze_balance()\n if live[\"total_tasks\"] > 0:\n print(format_balance_report(live))\n else:\n print(\"No Hub data available (Hub may be down)\")\n"}}, "engine/xiangke_engine.py": {"4fc8d006de060f20a54d6b1d32cf81780ef57711": {"t": 1785599308.607751, "n": 13376, "h": "3e442de984486b6f", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nxiangke_engine.py - 五行相克约束引擎 v1.0\n实现五行相克的动态平衡机制\n\n相克五对(五角星):\n 金克木 — 验证约束发散(验证分数低 → 限制种子数量)\n 木克土 — 创新挑战现实(种子新颖度高 → 提高土的校验标准)\n 土克水 — 现实约束收敛(校验残差高 → 水不能轻易收敛)\n 水克火 — 认知约束执行(未知领域多 → 降低执行置信度)\n 火克金 — 执行压制对抗(执行分数高 → 降低验证权重,防止过度质疑)\n\n核心原则:相克不是消灭,是约束。任何一极过强都会被克制。\n\"\"\"\n\nimport json, time\n\n# ===== 相克规则引擎 =====\n\nclass XiangkeEngine:\n \"\"\"五行相克动态平衡引擎\"\"\"\n \n # 相克关系表:{克者: 被克者}\n RELATIONS = {\n \"metal\": \"wood\", # 金克木\n \"wood\": \"earth\", # 木克土\n \"earth\": \"water\", # 土克水\n \"water\": \"fire\", # 水克火\n \"fire\": \"metal\", # 火克金\n }\n \n # 默认参数\n DEFAULT_PARAMS = {\n \"wood\": {\"seed_count\": 15, \"divergence_temp\": 0.9, \"weight\": 1.0},\n \"fire\": {\"execution_confidence\": 1.0, \"detail_level\": \"full\", \"weight\": 1.0},\n \"earth\": {\"validation_threshold\": 0.5, \"strictness\": \"normal\", \"weight\": 1.0},\n \"metal\": {\"validation_weight\": 0.25, \"challenge_depth\": \"standard\", \"weight\": 1.0},\n \"water\": {\"convergence_threshold\": 0.3, \"min_evidence\": 2, \"weight\": 1.0},\n }\n \n def __init__(self):\n self.params = json.loads(json.dumps(self.DEFAULT_PARAMS))\n self.adjustments = [] # log of all adjustments\n \n def apply_constraints(self, phase_results):\n \"\"\"\n Given results from completed phases, apply 相克 constraints to downstream phases.\n \n Args:\n phase_results: dict of {phase_name: {score: float, output: dict, ...}}\n \n Returns:\n dict of adjusted parameters for remaining phases\n \"\"\"\n adjustments = []\n \n for attacker, defender in self.RELATIONS.items():\n if attacker not in phase_results:\n continue\n \n score = self._extract_score(phase_results[attacker])\n \n if attacker == \"metal\" and defender == \"wood\":\n adjustments.extend(self._metal_ke_wood(score, phase_results.get(\"metal\", {})))\n \n elif attacker == \"wood\" and defender == \"earth\":\n adjustments.extend(self._wood_ke_earth(score, phase_results.get(\"wood\", {})))\n \n elif attacker == \"earth\" and defender == \"water\":\n adjustments.extend(self._earth_ke_water(score, phase_results.get(\"earth\", {})))\n \n elif attacker == \"water\" and defender == \"fire\":\n adjustments.extend(self._water_ke_fire(score, phase_results.get(\"water\", {})))\n \n elif attacker == \"fire\" and defender == \"metal\":\n adjustments.extend(self._fire_ke_metal(score, phase_results.get(\"fire\", {})))\n \n self.adjustments.extend(adjustments)\n return {\n \"adjusted_params\": self.params,\n \"adjustments\": adjustments\n }\n \n def _extract_score(self, result):\n \"\"\"Extract normalized score from phase result\"\"\"\n if isinstance(result, dict):\n output = result.get(\"output\", result)\n if isinstance(output, dict):\n for key in [\"overall_score\", \"divergence_score\", \"execution_score\", \n \"grounding_score\", \"convergence_score\", \"integrity_score\"]:\n if key in output:\n return float(output[key])\n # metal_validator format\n if \"dimension_scores\" in output:\n scores = output[\"dimension_scores\"].values()\n if scores:\n return sum(scores) / len(scores)\n return 0.5 # default\n \n # ===== 五对相克具体实现 =====\n \n def _metal_ke_wood(self, metal_score, metal_result):\n \"\"\"金克木:验证分数低 → 约束种子发散\"\"\"\n adjustments = []\n \n if metal_score < 0.4:\n # 验证严重不通过 → 大幅限制种子\n self.params[\"wood\"][\"seed_count\"] = 5\n self.params[\"wood\"][\"divergence_temp\"] = 0.5\n adjustments.append({\n \"rule\": \"金克木(强约束)\",\n \"trigger\": f\"验证分数={metal_score:.2f} < 0.4\",\n \"action\": \"种子数15→5,发散温度0.9→0.5\",\n \"reason\": \"验证器发现严重问题,需收敛种子方向避免无效发散\"\n })\n elif metal_score < 0.6:\n # 有条件通过 → 适度限制\n self.params[\"wood\"][\"seed_count\"] = 10\n self.params[\"wood\"][\"divergence_temp\"] = 0.7\n adjustments.append({\n \"rule\": \"金克木(适度约束)\",\n \"trigger\": f\"验证分数={metal_score:.2f} < 0.6\",\n \"action\": \"种子数15→10,发散温度0.9→0.7\",\n \"reason\": \"验证发现部分问题,适度约束发散范围\"\n })\n \n # 如果有具体红旗,进一步约束\n output = metal_result.get(\"output\", {})\n if isinstance(output, dict):\n red_flags = output.get(\"red_flags\", [])\n if len(red_flags) > 5:\n self.params[\"wood\"][\"seed_count\"] = max(3, self.params[\"wood\"][\"seed_count\"] - 3)\n adjustments.append({\n \"rule\": \"金克木(红旗加码)\",\n \"trigger\": f\"{len(red_flags)}个红旗\",\n \"action\": f\"种子数再减3→{self.params['wood']['seed_count']}\",\n \"reason\": \"红旗过多,进一步收敛\"\n })\n \n return adjustments\n \n def _wood_ke_earth(self, wood_score, wood_result):\n \"\"\"木克土:种子新颖度高 → 提高土的校验标准\"\"\"\n adjustments = []\n \n if wood_score > 0.8:\n self.params[\"earth\"][\"validation_threshold\"] = 0.7\n self.params[\"earth\"][\"strictness\"] = \"strict\"\n adjustments.append({\n \"rule\": \"木克土(高标准校验)\",\n \"trigger\": f\"发散分数={wood_score:.2f} > 0.8\",\n \"action\": \"校验阈值0.5→0.7,严格模式\",\n \"reason\": \"种子高度发散,需要更严格的现实校验防止空想\"\n })\n elif wood_score > 0.6:\n self.params[\"earth\"][\"validation_threshold\"] = 0.6\n adjustments.append({\n \"rule\": \"木克土(适度校验)\",\n \"trigger\": f\"发散分数={wood_score:.2f} > 0.6\",\n \"action\": \"校验阈值0.5→0.6\",\n \"reason\": \"种子较发散,适度提高校验标准\"\n })\n \n return adjustments\n \n def _earth_ke_water(self, earth_score, earth_result):\n \"\"\"土克水:现实校验残差高 → 水不能轻易收敛\"\"\"\n adjustments = []\n \n output = earth_result.get(\"output\", {})\n residual = output.get(\"residual\", 0.5) if isinstance(output, dict) else 0.5\n \n if residual > 0.7:\n self.params[\"water\"][\"convergence_threshold\"] = 0.15\n self.params[\"water\"][\"min_evidence\"] = 4\n adjustments.append({\n \"rule\": \"土克水(禁止轻率收敛)\",\n \"trigger\": f\"土阶段残差={residual:.2f} > 0.7\",\n \"action\": \"收敛阈值0.3→0.15,最少证据2→4\",\n \"reason\": \"现实校验发现大量未验证信息,禁止水阶段过早下结论\"\n })\n elif residual > 0.5:\n self.params[\"water\"][\"convergence_threshold\"] = 0.2\n self.params[\"water\"][\"min_evidence\"] = 3\n adjustments.append({\n \"rule\": \"土克水(谨慎收敛)\",\n \"trigger\": f\"土阶段残差={residual:.2f} > 0.5\",\n \"action\": \"收敛阈值0.3→0.2,最少证据2→3\",\n \"reason\": \"现实校验有较多不确定性,水阶段需更多证据才能收敛\"\n })\n \n return adjustments\n \n def _water_ke_fire(self, water_score, water_result):\n \"\"\"水克火:未知领域多 → 降低执行置信度\"\"\"\n adjustments = []\n \n output = water_result.get(\"output\", {})\n unknowns = output.get(\"unknown\", []) if isinstance(output, dict) else []\n \n if len(unknowns) > 5 or water_score < 0.4:\n self.params[\"fire\"][\"execution_confidence\"] = 0.5\n self.params[\"fire\"][\"detail_level\"] = \"cautious\"\n adjustments.append({\n \"rule\": \"水克火(降低执行信心)\",\n \"trigger\": f\"未知项={len(unknowns)},收敛分={water_score:.2f}\",\n \"action\": \"执行置信度1.0→0.5,模式→谨慎\",\n \"reason\": \"认知未收敛,执行层必须标注不确定性,避免过度自信\"\n })\n elif len(unknowns) > 3 or water_score < 0.6:\n self.params[\"fire\"][\"execution_confidence\"] = 0.7\n adjustments.append({\n \"rule\": \"水克火(适度降低执行信心)\",\n \"trigger\": f\"未知项={len(unknowns)},收敛分={water_score:.2f}\",\n \"action\": \"执行置信度1.0→0.7\",\n \"reason\": \"部分领域认知不足,执行建议需标注局限\"\n })\n \n return adjustments\n \n def _fire_ke_metal(self, fire_score, fire_result):\n \"\"\"火克金:执行分数高 → 降低验证权重,防止过度质疑\"\"\"\n adjustments = []\n \n if fire_score > 0.8:\n self.params[\"metal\"][\"validation_weight\"] = 0.15\n self.params[\"metal\"][\"challenge_depth\"] = \"light\"\n adjustments.append({\n \"rule\": \"火克金(压制过度质疑)\",\n \"trigger\": f\"执行分数={fire_score:.2f} > 0.8\",\n \"action\": \"验证权重0.25→0.15,质疑深度→轻度\",\n \"reason\": \"执行层数据充分、逻辑严密,验证层不应过度质疑阻碍推进\"\n })\n elif fire_score > 0.7:\n self.params[\"metal\"][\"validation_weight\"] = 0.20\n adjustments.append({\n \"rule\": \"火克金(适度压制)\",\n \"trigger\": f\"执行分数={fire_score:.2f} > 0.7\",\n \"action\": \"验证权重0.25→0.20\",\n \"reason\": \"执行层质量较高,适度降低验证权重\"\n })\n \n return adjustments\n \n # ===== 辅助方法 =====\n \n def get_prompt_modifiers(self, phase):\n \"\"\"Generate prompt modifier string based on current constraints\"\"\"\n p = self.params.get(phase, {})\n mods = []\n \n if phase == \"wood\":\n if p.get(\"seed_count\", 15) < 15:\n mods.append(f\"注意:本轮种子数量限制为{p['seed_count']}个(相克约束)\")\n if p.get(\"divergence_temp\", 0.9) < 0.9:\n mods.append(\"注意:需要更聚焦的发散,避免天马行空\")\n \n elif phase == \"earth\":\n if p.get(\"strictness\") == \"strict\":\n mods.append(\"注意:严格校验模式 — 每个结论必须有2个以上数据支撑\")\n if p.get(\"validation_threshold\", 0.5) > 0.5:\n mods.append(f\"注意:校验阈值提高到{p['validation_threshold']}(相克约束)\")\n \n elif phase == \"metal\":\n if p.get(\"challenge_depth\") == \"light\":\n mods.append(\"注意:轻度质疑模式 — 聚焦关键风险,不做全面质疑\")\n if p.get(\"validation_weight\", 0.25) < 0.25:\n mods.append(f\"注意:验证权重降至{p['validation_weight']}(火克金约束)\")\n \n elif phase == \"fire\":\n if p.get(\"execution_confidence\", 1.0) < 1.0:\n mods.append(f\"注意:执行置信度={p['execution_confidence']},需标注不确定性\")\n if p.get(\"detail_level\") == \"cautious\":\n mods.append(\"注意:谨慎执行模式 — 每个建议需标注局限和风险\")\n \n elif phase == \"water\":\n if p.get(\"convergence_threshold\", 0.3) < 0.3:\n mods.append(f\"注意:收敛阈值={p['convergence_threshold']},需更多证据才能下结论\")\n if p.get(\"min_evidence\", 2) > 2:\n mods.append(f\"注意:每个结论至少需要{p['min_evidence']}个独立证据支撑\")\n \n return \"\\n\".join(mods) if mods else \"\"\n \n def reset(self):\n \"\"\"Reset to default parameters\"\"\"\n self.params = json.loads(json.dumps(self.DEFAULT_PARAMS))\n self.adjustments = []\n \n def get_balance_report(self):\n \"\"\"Generate a balance report showing current state of all five phases\"\"\"\n report = {\n \"timestamp\": time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"phases\": {},\n \"total_adjustments\": len(self.adjustments),\n \"active_constraints\": []\n }\n \n for phase, params in self.params.items():\n defaults = self.DEFAULT_PARAMS[phase]\n deviations = {}\n for k, v in params.items():\n if v != defaults.get(k):\n deviations[k] = {\"current\": v, \"default\": defaults[k]}\n \n report[\"phases\"][phase] = {\n \"params\": params,\n \"constrained\": len(deviations) > 0,\n \"deviations\": deviations\n }\n \n if deviations:\n report[\"active_constraints\"].append(phase)\n \n return report\n \n def to_dict(self):\n return {\n \"params\": self.params,\n \"adjustments\": self.adjustments,\n \"balance\": self.get_balance_report()\n }\n\n\n# ===== Standalone test =====\nif __name__ == \"__main__\":\n engine = XiangkeEngine()\n \n # Simulate: metal found issues → constrain wood\n test_results = {\n \"metal\": {\n \"output\": {\n \"overall_score\": 0.35,\n \"red_flags\": [\"数据来源不明\", \"自相矛盾\", \"缺乏对比\", \"时间线不现实\", \"忽略竞争\", \"成本低估\"]\n }\n },\n \"fire\": {\n \"output\": {\n \"execution_score\": 0.85\n }\n },\n \"earth\": {\n \"output\": {\n \"residual\": 0.65,\n \"grounding_score\": 0.55\n }\n }\n }\n \n result = engine.apply_constraints(test_results)\n \n print(\"=== 相克约束测试 ===\\n\")\n for adj in result[\"adjustments\"]:\n print(f\"[{adj['rule']}]\")\n print(f\" 触发: {adj['trigger']}\")\n print(f\" 动作: {adj['action']}\")\n print(f\" 原因: {adj['reason']}\")\n print()\n \n print(\"=== Prompt修饰语 ===\\n\")\n for phase in [\"wood\", \"fire\", \"earth\", \"metal\", \"water\"]:\n mod = engine.get_prompt_modifiers(phase)\n if mod:\n print(f\"[{phase}] {mod}\")\n \n print(f\"\\n=== 平衡报告 ===\")\n report = engine.get_balance_report()\n print(f\"活跃约束: {report['active_constraints']}\")\n print(f\"总调整数: {report['total_adjustments']}\")\n"}}, "philosophies/01_qinglong_daoism_emergence/seed_graph.py": {"0af97e325a65192e675cd7f9679c3281f9dd51b9": {"t": 1785599309.282082, "n": 4508, "h": "34e93084efa02e7b", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nSeed Graph v1.0\n青龙·种子飞轮 — 种子关系图谱\n\n种子之间的关联、竞争、演化关系可视化数据生成\n\"\"\"\nimport json, os\nfrom datetime import datetime\n\nclass SeedGraph:\n def __init__(self, db_path=None):\n self.db_path = db_path or os.path.join(os.path.dirname(__file__), \"seed_graph.json\")\n self.data = self._load()\n \n def _load(self):\n if os.path.exists(self.db_path):\n with open(self.db_path, 'r', encoding='utf-8') as f:\n return json.load(f)\n return {\"nodes\": [], \"edges\": [], \"clusters\": [], \"meta\": {\"version\": \"1.0\"}}\n \n def _save(self):\n self.data[\"meta\"][\"updated\"] = datetime.now().isoformat()\n with open(self.db_path, 'w', encoding='utf-8') as f:\n json.dump(self.data, f, ensure_ascii=False, indent=2)\n \n def add_seed_node(self, seed_id, name, domain, score, stage=\"active\"):\n node = {\n \"id\": seed_id, \"name\": name, \"domain\": domain,\n \"score\": score, \"stage\": stage,\n \"size\": max(10, score * 5) # Visual size based on score\n }\n self.data[\"nodes\"].append(node)\n self._save()\n return node\n \n def add_relation(self, from_id, to_id, relation_type, strength):\n \"\"\"relation_type: derives_from, competes_with, synergy, conflicts\"\"\"\n edge = {\n \"from\": from_id, \"to\": to_id,\n \"type\": relation_type, \"strength\": strength\n }\n self.data[\"edges\"].append(edge)\n self._save()\n return edge\n \n def detect_clusters(self):\n \"\"\"简单连通分量检测\"\"\"\n if not self.data[\"nodes\"]:\n return []\n \n node_ids = [n[\"id\"] for n in self.data[\"nodes\"]]\n adjacency = {n: set() for n in node_ids}\n for e in self.data[\"edges\"]:\n if e[\"from\"] in adjacency and e[\"to\"] in adjacency:\n adjacency[e[\"from\"]].add(e[\"to\"])\n adjacency[e[\"to\"]].add(e[\"from\"])\n \n visited = set()\n clusters = []\n \n for node in node_ids:\n if node not in visited:\n cluster = []\n stack = [node]\n while stack:\n n = stack.pop()\n if n not in visited:\n visited.add(n)\n cluster.append(n)\n stack.extend(adjacency[n] - visited)\n clusters.append(cluster)\n \n self.data[\"clusters\"] = [{\"id\": f\"C-{i}\", \"members\": c, \"size\": len(c)} for i, c in enumerate(clusters)]\n self._save()\n return self.data[\"clusters\"]\n \n def get_stats(self):\n domains = {}\n for n in self.data[\"nodes\"]:\n d = n[\"domain\"]\n domains[d] = domains.get(d, 0) + 1\n \n return {\n \"total_nodes\": len(self.data[\"nodes\"]),\n \"total_edges\": len(self.data[\"edges\"]),\n \"clusters\": len(self.data[\"clusters\"]),\n \"domains\": domains,\n \"density\": round(len(self.data[\"edges\"]) / max(len(self.data[\"nodes\"]) * (len(self.data[\"nodes\"])-1) / 2, 1), 2)\n }\n\n\ndef main():\n graph = SeedGraph()\n \n seeds = [\n (\"S-001\", \"四流合一清算\", \"finance\", 8.5),\n (\"S-002\", \"SiC外延片路由\", \"semiconductor\", 7.0),\n (\"S-003\", \"DRG医疗清算\", \"medical\", 6.2),\n (\"S-004\", \"碳纤维DB\", \"materials\", 7.5),\n (\"S-005\", \"智能建筑OS\", \"robotics\", 6.8),\n (\"S-006\", \"LUX经济体\", \"ai\", 7.8),\n (\"S-007\", \"信任网络\", \"ai\", 7.2),\n (\"S-008\", \"预测引擎\", \"ai\", 7.0),\n ]\n \n for sid, name, domain, score in seeds:\n graph.add_seed_node(sid, name, domain, score)\n \n relations = [\n (\"S-001\", \"S-003\", \"synergy\", 0.8),\n (\"S-001\", \"S-006\", \"derives_from\", 0.7),\n (\"S-002\", \"S-004\", \"synergy\", 0.6),\n (\"S-003\", \"S-001\", \"competes_with\", 0.4),\n (\"S-005\", \"S-004\", \"synergy\", 0.5),\n (\"S-006\", \"S-007\", \"derives_from\", 0.9),\n (\"S-007\", \"S-008\", \"synergy\", 0.7),\n ]\n \n for f, t, rtype, strength in relations:\n graph.add_relation(f, t, rtype, strength)\n \n clusters = graph.detect_clusters()\n stats = graph.get_stats()\n \n print(\"=== Seed Graph v1.0 ===\")\n print(f\" {stats['total_nodes']} nodes | {stats['total_edges']} edges | \"\n f\"density={stats['density']} | {stats['clusters']} clusters\")\n print(f\" Domains: {stats['domains']}\")\n for cl in clusters:\n print(f\" Cluster {cl['id']}: {cl['members']}\")\n\nif __name__ == \"__main__\":\n main()\n"}}, "core/config.py": {"b8cb0fcb6623f1a0c9e6631cd08d539bf7933037": {"t": 1785599309.3607907, "n": 787, "h": "2c33ce21e0222d9e", "c": "# -*- coding: utf-8 -*-\n\"\"\"ClawMatrix 配置\"\"\"\nimport os\n\nclass MatrixConfig:\n # 节点身份\n NODE_ID = os.environ.get('MATRIX_NODE_ID', 'skycetus-hub')\n SECRET = os.environ.get('MATRIX_SECRET', 'skycetus-shared-secret')\n \n # 网络\n LISTEN_HOST = '0.0.0.0'\n LISTEN_PORT = int(os.environ.get('MATRIX_PORT', '19102'))\n \n # 标签\n TAGS = ['hub', 'task-distributor', 'skycetus']\n \n # 数据�?\n DB_PATH = os.environ.get('MATRIX_DB', 'D:/ClawMatrix/hub_new.db')\n \n # 加密\n KEY_DIR = 'D:/ClawMatrix/keys'\n \n # 心跳\n HEARTBEAT_INTERVAL = 30 # �?\n NODE_TIMEOUT = 120 # 超过此时间无心跳视为离线\n \n # 文件传输\n MAX_FILE_SIZE = 100 * 1024 * 1024 # 100MB\n TRANSFER_DIR = 'D:/ClawMatrix/transfers'\n \n # Gossip\n GOSSIP_INTERVAL = 60 # �?\n MAX_PEERS = 50\n"}}, "philosophies/01_qinglong_daoism_emergence/seed_competition.py": {"075bed265525ce4b15c9ff31ef33e428b0753704": {"t": 1785599309.397667, "n": 5363, "h": "bdf1cc6b09b29197", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nSeed Competition Engine v1.0\n青龙·种子飞轮 — 种子竞争\n\n核心: 多种子竞争同一任务槽位\n- 种子擂台赛(tournament)\n- 适应度评分(fitness scoring)\n- 淘汰与晋级(elimination)\n- 保护弱种子(diversity floor 10%)\n\"\"\"\nimport json, os, random\nfrom datetime import datetime\n\nclass SeedCompetition:\n def __init__(self, db_path=None):\n self.db_path = db_path or os.path.join(os.path.dirname(__file__), \"seed_competition.json\")\n self.data = self._load()\n \n def _load(self):\n if os.path.exists(self.db_path):\n with open(self.db_path, 'r', encoding='utf-8') as f:\n return json.load(f)\n return {\"tournaments\": [], \"hall_of_fame\": [], \"eliminated\": [], \"meta\": {\"version\": \"1.0\", \"diversity_floor\": 0.10}}\n \n def _save(self):\n self.data[\"meta\"][\"updated\"] = datetime.now().isoformat()\n with open(self.db_path, 'w', encoding='utf-8') as f:\n json.dump(self.data, f, ensure_ascii=False, indent=2)\n \n def create_tournament(self, slot_id, slot_name, candidates):\n \"\"\"candidates: list of {seed_id, name, domain, fitness}\"\"\"\n tournament = {\n \"id\": f\"TOURN-{len(self.data['tournaments'])+1:03d}\",\n \"slot\": slot_id, \"slot_name\": slot_name,\n \"candidates\": candidates, \"rounds\": [],\n \"winner\": None, \"status\": \"active\",\n \"created\": datetime.now().isoformat()\n }\n self.data[\"tournaments\"].append(tournament)\n self._save()\n return tournament\n \n def run_round(self, tournament_id):\n tourn = next((t for t in self.data[\"tournaments\"] if t[\"id\"] == tournament_id), None)\n if not tourn or tourn[\"status\"] != \"active\":\n return None\n \n candidates = [c for c in tourn[\"candidates\"] if c.get(\"alive\", True)]\n if len(candidates) <= 1:\n if candidates:\n tourn[\"winner\"] = candidates[0]\n tourn[\"status\"] = \"completed\"\n self.data[\"hall_of_fame\"].append(candidates[0])\n self._save()\n return {\"status\": \"completed\", \"winner\": tourn[\"winner\"]}\n \n # Pairwise competition\n random.shuffle(candidates)\n round_results = []\n survivors = []\n \n for i in range(0, len(candidates) - 1, 2):\n a, b = candidates[i], candidates[i+1]\n # Fitness + random noise (exploration)\n a_score = a[\"fitness\"] + random.uniform(-1, 1)\n b_score = b[\"fitness\"] + random.uniform(-1, 1)\n \n if a_score >= b_score:\n winner, loser = a, b\n else:\n winner, loser = b, a\n \n # Diversity floor: 10% chance loser survives anyway\n loser_survives = random.random() < self.data[\"meta\"][\"diversity_floor\"]\n \n survivors.append(winner)\n if loser_survives:\n survivors.append(loser)\n round_results.append({\"winner\": winner[\"seed_id\"], \"loser\": loser[\"seed_id\"], \"loser_saved\": True})\n else:\n loser[\"alive\"] = False\n self.data[\"eliminated\"].append(loser)\n round_results.append({\"winner\": winner[\"seed_id\"], \"loser\": loser[\"seed_id\"], \"loser_saved\": False})\n \n # Odd one out gets a bye\n if len(candidates) % 2 == 1:\n survivors.append(candidates[-1])\n \n tourn[\"rounds\"].append({\"round\": len(tourn[\"rounds\"]) + 1, \"results\": round_results, \"survivors\": len(survivors)})\n self._save()\n return {\"status\": \"round_complete\", \"survivors\": len(survivors), \"eliminated\": len(candidates) - len(survivors)}\n \n def get_stats(self):\n completed = [t for t in self.data[\"tournaments\"] if t[\"status\"] == \"completed\"]\n return {\n \"total_tournaments\": len(self.data[\"tournaments\"]),\n \"completed\": len(completed),\n \"hall_of_fame\": len(self.data[\"hall_of_fame\"]),\n \"total_eliminated\": len(self.data[\"eliminated\"])\n }\n\n\ndef main():\n engine = SeedCompetition()\n \n candidates = [\n {\"seed_id\": \"S-101\", \"name\": \"四流合一v2\", \"domain\": \"finance\", \"fitness\": 8.5, \"alive\": True},\n {\"seed_id\": \"S-102\", \"name\": \"DRG智能清算\", \"domain\": \"medical\", \"fitness\": 7.2, \"alive\": True},\n {\"seed_id\": \"S-103\", \"name\": \"供应链AI路由\", \"domain\": \"semiconductor\", \"fitness\": 7.8, \"alive\": True},\n {\"seed_id\": \"S-104\", \"name\": \"碳纤维数据库\", \"domain\": \"materials\", \"fitness\": 7.0, \"alive\": True},\n {\"seed_id\": \"S-105\", \"name\": \"量子计算模拟\", \"domain\": \"ai\", \"fitness\": 5.5, \"alive\": True},\n {\"seed_id\": \"S-106\", \"name\": \"智能建筑控制\", \"domain\": \"robotics\", \"fitness\": 6.8, \"alive\": True},\n ]\n \n tourn = engine.create_tournament(\"SLOT-01\", \"Q2核心产品\", candidates)\n print(f\"=== Seed Competition v1.0 ===\")\n print(f\" Tournament {tourn['id']}: {tourn['slot_name']} ({len(candidates)} candidates)\")\n \n for i in range(3):\n result = engine.run_round(tourn[\"id\"])\n if not result:\n break\n print(f\" Round {i+1}: {result}\")\n if result[\"status\"] == \"completed\":\n print(f\" WINNER: {result['winner']['name']} (fitness={result['winner']['fitness']})\")\n break\n \n stats = engine.get_stats()\n print(f\"\\n Stats: {stats}\")\n\nif __name__ == \"__main__\":\n main()\n"}}, "philosophies/01_qinglong_daoism_emergence/seed_evaluator.py": {"f947b72a8f8a3132df8bc788d4d912a4b13c055c": {"t": 1785599309.4655614, "n": 6987, "h": "68a2eceb869f31cd", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nSeed Evaluator v1.0\n青龙·种子飞轮 — 种子质量评估\n\n10维评估模型(对应Robin的10个认知API):\n1. 问题定义清晰度\n2. 问题分解可行性\n3. 价值函数明确度\n4. 解决方案多样性\n5. 风险可识别性\n6. 资源可估算性\n7. 约束可映射性\n8. 竞争可分析性\n9. 执行计划可行性\n10. 叙事输出完整度\n\"\"\"\nimport json, os\nfrom datetime import datetime\nimport random\n\nclass SeedEvaluator:\n def __init__(self, db_path=None):\n self.db_path = db_path or os.path.join(os.path.dirname(__file__), \"seed_evaluations.json\")\n self.data = self._load()\n self.dimensions = [\n \"problem_clarity\", \"decomposition\", \"value_function\",\n \"solution_diversity\", \"risk_identification\", \"resource_estimation\",\n \"constraint_mapping\", \"competition_analysis\", \"execution_plan\",\n \"narrative_output\"\n ]\n \n def _load(self):\n if os.path.exists(self.db_path):\n with open(self.db_path, 'r', encoding='utf-8') as f:\n return json.load(f)\n return {\"evaluations\": [], \"stats\": {}, \"meta\": {\"version\": \"1.0\"}}\n \n def _save(self):\n self.data[\"meta\"][\"updated\"] = datetime.now().isoformat()\n with open(self.db_path, 'w', encoding='utf-8') as f:\n json.dump(self.data, f, ensure_ascii=False, indent=2)\n \n def evaluate_seed(self, seed_id, seed_name, domain, scores):\n \"\"\"\n scores: dict with 10 dimension scores (0-10 each)\n Returns: evaluation with overall score and recommendation\n \"\"\"\n overall = sum(scores.values()) / len(scores)\n \n # Weighted: value_function and execution_plan matter more\n weighted = (\n scores.get(\"problem_clarity\", 5) * 1.0 +\n scores.get(\"decomposition\", 5) * 1.0 +\n scores.get(\"value_function\", 5) * 1.5 +\n scores.get(\"solution_diversity\", 5) * 1.0 +\n scores.get(\"risk_identification\", 5) * 1.2 +\n scores.get(\"resource_estimation\", 5) * 1.0 +\n scores.get(\"constraint_mapping\", 5) * 0.8 +\n scores.get(\"competition_analysis\", 5) * 1.0 +\n scores.get(\"execution_plan\", 5) * 1.5 +\n scores.get(\"narrative_output\", 5) * 1.0\n ) / 11.0\n \n if weighted >= 8:\n recommendation = \"immediate_execute\"\n priority = \"P0\"\n elif weighted >= 6:\n recommendation = \"incubate\"\n priority = \"P1\"\n elif weighted >= 4:\n recommendation = \"needs_work\"\n priority = \"P2\"\n else:\n recommendation = \"archive\"\n priority = \"P3\"\n \n weak_dims = [d for d, s in scores.items() if s < 5]\n strong_dims = [d for d, s in scores.items() if s >= 8]\n \n evaluation = {\n \"seed_id\": seed_id, \"seed_name\": seed_name, \"domain\": domain,\n \"scores\": scores, \"overall\": round(overall, 1),\n \"weighted\": round(weighted, 1),\n \"recommendation\": recommendation, \"priority\": priority,\n \"weak_dimensions\": weak_dims, \"strong_dimensions\": strong_dims,\n \"timestamp\": datetime.now().isoformat()\n }\n \n self.data[\"evaluations\"].append(evaluation)\n self._update_stats(domain, weighted)\n self._save()\n return evaluation\n \n def _update_stats(self, domain, score):\n if domain not in self.data[\"stats\"]:\n self.data[\"stats\"][domain] = {\"count\": 0, \"total_score\": 0, \"avg\": 0}\n self.data[\"stats\"][domain][\"count\"] += 1\n self.data[\"stats\"][domain][\"total_score\"] += score\n self.data[\"stats\"][domain][\"avg\"] = round(\n self.data[\"stats\"][domain][\"total_score\"] / self.data[\"stats\"][domain][\"count\"], 1)\n \n def get_portfolio_analysis(self):\n \"\"\"分析种子组合的健康度\"\"\"\n evals = self.data[\"evaluations\"]\n if not evals:\n return {}\n \n by_priority = {}\n for e in evals:\n p = e[\"priority\"]\n by_priority[p] = by_priority.get(p, 0) + 1\n \n by_domain = {}\n for e in evals:\n d = e[\"domain\"]\n if d not in by_domain:\n by_domain[d] = []\n by_domain[d].append(e[\"weighted\"])\n \n domain_health = {d: {\"count\": len(s), \"avg\": round(sum(s)/len(s), 1)} \n for d, s in by_domain.items()}\n \n return {\n \"total_seeds\": len(evals),\n \"by_priority\": by_priority,\n \"domain_health\": domain_health,\n \"avg_quality\": round(sum(e[\"weighted\"] for e in evals) / len(evals), 1)\n }\n\n\ndef main():\n evaluator = SeedEvaluator()\n \n seeds = [\n (\"S-001\", \"四流合一清算引擎\", \"finance\", {\n \"problem_clarity\": 9, \"decomposition\": 8, \"value_function\": 9,\n \"solution_diversity\": 7, \"risk_identification\": 8, \"resource_estimation\": 7,\n \"constraint_mapping\": 8, \"competition_analysis\": 9, \"execution_plan\": 8,\n \"narrative_output\": 8\n }),\n (\"S-002\", \"SiC外延片供应链路由\", \"semiconductor\", {\n \"problem_clarity\": 8, \"decomposition\": 7, \"value_function\": 8,\n \"solution_diversity\": 6, \"risk_identification\": 7, \"resource_estimation\": 6,\n \"constraint_mapping\": 7, \"competition_analysis\": 8, \"execution_plan\": 6,\n \"narrative_output\": 7\n }),\n (\"S-003\", \"DRG/DIP医疗清算\", \"medical\", {\n \"problem_clarity\": 7, \"decomposition\": 6, \"value_function\": 7,\n \"solution_diversity\": 5, \"risk_identification\": 8, \"resource_estimation\": 5,\n \"constraint_mapping\": 6, \"competition_analysis\": 6, \"execution_plan\": 5,\n \"narrative_output\": 6\n }),\n (\"S-004\", \"碳纤维产业链数据库\", \"materials\", {\n \"problem_clarity\": 8, \"decomposition\": 8, \"value_function\": 7,\n \"solution_diversity\": 7, \"risk_identification\": 6, \"resource_estimation\": 7,\n \"constraint_mapping\": 7, \"competition_analysis\": 7, \"execution_plan\": 7,\n \"narrative_output\": 8\n }),\n (\"S-005\", \"量子材料模拟平台\", \"materials\", {\n \"problem_clarity\": 6, \"decomposition\": 5, \"value_function\": 5,\n \"solution_diversity\": 8, \"risk_identification\": 4, \"resource_estimation\": 3,\n \"constraint_mapping\": 4, \"competition_analysis\": 5, \"execution_plan\": 3,\n \"narrative_output\": 5\n }),\n ]\n \n print(\"=== Seed Evaluator v1.0 (10-dim) ===\")\n for sid, name, domain, scores in seeds:\n ev = evaluator.evaluate_seed(sid, name, domain, scores)\n print(f\" {sid} {name:20s} | weighted={ev['weighted']:.1f} | \"\n f\"{ev['priority']} {ev['recommendation']}\")\n if ev[\"weak_dimensions\"]:\n print(f\" weak: {', '.join(ev['weak_dimensions'][:3])}\")\n \n portfolio = evaluator.get_portfolio_analysis()\n print(f\"\\n Portfolio: {portfolio['total_seeds']} seeds | \"\n f\"avg quality={portfolio['avg_quality']}\")\n print(f\" By priority: {portfolio['by_priority']}\")\n\nif __name__ == \"__main__\":\n main()\n"}}, "philosophies/02_zhuque_confucius_investigation/fire_engine.py": {"6f232321645a11d8104bd5a029387868aff72a18": {"t": 1785599309.4702165, "n": 11674, "h": "af590224aa27a6fc", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nFire Engine (Zhuque/South) - Task Execution & Pipeline\nPart of the Wuxing Flywheel System\n\nRole in xiangsheng: wood->fire (Seeds Ignite Execution)\nRole in xiangke: fire->metal (Execution Challenges Rigid Validation)\n\nCore functions:\n1. Task decomposition - break complex tasks into sub-tasks\n2. Execution planning - create execution DAG\n3. LLM-powered execution - use multi-model routing\n4. Result aggregation - merge sub-task results\n5. Quality self-check before passing to Earth\n\"\"\"\nimport json, os, sqlite3, hashlib, subprocess, time as _time, re\nfrom datetime import datetime\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nDB_DIR = os.path.dirname(os.path.abspath(__file__))\nDB_PATH = os.path.join(DB_DIR, \"fire_execution.db\")\n\ndef _init_db(db_path=None):\n p = db_path or DB_PATH\n conn = sqlite3.connect(p)\n conn.execute(\"\"\"CREATE TABLE IF NOT EXISTS executions (\n id TEXT PRIMARY KEY, task_id TEXT, task_text TEXT, status TEXT,\n sub_tasks TEXT, results TEXT, quality_score REAL,\n started_at TEXT, completed_at TEXT, duration_s REAL, model_used TEXT\n )\"\"\")\n conn.execute(\"\"\"CREATE TABLE IF NOT EXISTS execution_log (\n id INTEGER PRIMARY KEY AUTOINCREMENT, exec_id TEXT, step TEXT, \n detail TEXT, timestamp TEXT\n )\"\"\")\n conn.commit()\n return conn\n\ndef _call_llm(prompt, model=\"minimax\"):\n \"\"\"Call LLM via curl subprocess (Windows SSL workaround)\"\"\"\n import subprocess, json\n \n api_key = \"sk-cp-wBP8BgBJbLsGCUshk0x5oYKbiydygx-RMk0iJDhANE6epg6gMnRBRg5hPN1eioB3PURgoeEiv7o2kLE7vOqibkLG1_3daWsmo-7kkkVxS4t7guHj7exDGwo\"\n \n payload = {\n \"model\": \"MiniMax-M2.7\",\n \"max_tokens\": 4096,\n \"thinking\": {\"type\": \"enabled\", \"budget_tokens\": 300},\n \"messages\": [{\"role\": \"user\", \"content\": prompt}]\n }\n \n try:\n result = subprocess.run(\n [\"curl.exe\", \"-s\", \"-X\", \"POST\",\n \"https://api.minimaxi.com/anthropic/v1/messages\",\n \"-H\", f\"x-api-key: {api_key}\",\n \"-H\", \"anthropic-version: 2023-06-01\",\n \"-H\", \"Content-Type: application/json\",\n \"-d\", json.dumps(payload, ensure_ascii=False)],\n capture_output=True, text=True, timeout=120\n )\n \n resp = json.loads(result.stdout)\n for block in resp.get(\"content\", []):\n if block.get(\"type\") == \"text\":\n return block.get(\"text\", \"\")\n return \"\"\n except Exception as e:\n return f\"[LLM Error: {str(e)}]\"\n\ndef decompose_task(task_text, max_subtasks=5):\n \"\"\"Break a complex task into sub-tasks\"\"\"\n # Simple heuristic decomposition (no LLM needed for basic cases)\n subtasks = []\n \n # Check for explicit enumeration\n numbered = re.findall(r'(?:\\d+[.)]\\s*|[-*]\\s+)(.+?)(?:\\n|$)', task_text)\n if numbered and len(numbered) >= 2:\n for item in numbered[:max_subtasks]:\n subtasks.append({\"text\": item.strip(), \"type\": \"explicit\"})\n return subtasks\n \n # Keyword-based decomposition\n phases = {\n \"research\": [\"analyze\", \"research\", \"investigate\", \"study\", \"examine\", \"review\"],\n \"design\": [\"design\", \"architect\", \"plan\", \"structure\", \"blueprint\", \"layout\"],\n \"build\": [\"build\", \"implement\", \"develop\", \"create\", \"code\", \"construct\"],\n \"test\": [\"test\", \"validate\", \"verify\", \"benchmark\", \"evaluate\", \"assess\"],\n \"deploy\": [\"deploy\", \"launch\", \"release\", \"publish\", \"deliver\", \"ship\"]\n }\n \n detected_phases = []\n for phase, keywords in phases.items():\n if any(kw in task_text.lower() for kw in keywords):\n detected_phases.append(phase)\n \n if not detected_phases:\n detected_phases = [\"research\", \"build\"] # default\n \n for phase in detected_phases[:max_subtasks]:\n subtasks.append({\n \"text\": f\"{phase.title()}: {task_text[:100]}\",\n \"type\": \"auto\",\n \"phase\": phase\n })\n \n return subtasks\n\ndef execute_task(task_text, task_id=None, use_llm=False, domain=\"general\"):\n \"\"\"Execute a task through the fire pipeline\"\"\"\n conn = _init_db()\n \n eid = f\"EXEC-{datetime.now().strftime('%Y%m%d%H%M%S')}-{hashlib.md5(task_text[:50].encode()).hexdigest()[:6]}\"\n start_time = _time.time()\n \n conn.execute(\n \"INSERT INTO executions VALUES (?,?,?,?,?,?,?,?,?,?,?)\",\n (eid, task_id or \"unknown\", task_text, \"running\", \"[]\", \"\", 0,\n datetime.now().isoformat(), None, 0, \"none\")\n )\n conn.commit()\n \n # Step 1: Decompose\n subtasks = decompose_task(task_text)\n conn.execute(\"UPDATE executions SET sub_tasks=? WHERE id=?\",\n (json.dumps(subtasks, ensure_ascii=False), eid))\n conn.execute(\"INSERT INTO execution_log VALUES (NULL,?,?,?,?)\",\n (eid, \"decompose\", f\"{len(subtasks)} sub-tasks\", datetime.now().isoformat()))\n conn.commit()\n \n # Step 2: Execute (with or without LLM)\n results = []\n model_used = \"local\"\n \n if use_llm:\n model_used = \"MiniMax-M2.7\"\n for st in subtasks:\n prompt = f\"You are an industry analysis expert. Execute this task concisely:\\n\\n{st['text']}\\n\\nDomain: {domain}\\n\\nProvide structured analysis with key findings.\"\n result = _call_llm(prompt)\n results.append({\"subtask\": st[\"text\"], \"result\": result, \"status\": \"completed\" if result and not result.startswith(\"[LLM\") else \"failed\"})\n else:\n for st in subtasks:\n results.append({\n \"subtask\": st[\"text\"],\n \"result\": f\"[Local execution] Task decomposed and ready for LLM processing: {st['text']}\",\n \"status\": \"completed\"\n })\n \n # Step 3: Quality self-check\n completed = sum(1 for r in results if r[\"status\"] == \"completed\")\n total_content = sum(len(r.get(\"result\", \"\")) for r in results)\n \n quality = (\n 0.4 * (completed / max(len(results), 1)) + # completion rate\n 0.3 * min(total_content / 2000, 1.0) + # content depth\n 0.2 * min(len(subtasks) / 3, 1.0) + # decomposition quality\n 0.1 * (1.0 if domain != \"general\" else 0.5) # domain specificity\n )\n \n duration = _time.time() - start_time\n \n conn.execute(\n \"UPDATE executions SET status=?, results=?, quality_score=?, completed_at=?, duration_s=?, model_used=? WHERE id=?\",\n (\"completed\", json.dumps(results, ensure_ascii=False), quality,\n datetime.now().isoformat(), duration, model_used, eid)\n )\n conn.execute(\"INSERT INTO execution_log VALUES (NULL,?,?,?,?)\",\n (eid, \"complete\", f\"quality={quality:.3f}, duration={duration:.1f}s\", datetime.now().isoformat()))\n conn.commit()\n conn.close()\n \n return {\n \"execution_id\": eid,\n \"task_id\": task_id,\n \"status\": \"completed\",\n \"subtasks\": len(subtasks),\n \"completed\": completed,\n \"quality_score\": round(quality, 3),\n \"duration_s\": round(duration, 2),\n \"model_used\": model_used,\n \"results\": results\n }\n\ndef xiangke_challenge_metal(validation_result):\n \"\"\"Fire challenges Metal (xiangke): execution pushes back on rigid validation\"\"\"\n challenges = []\n \n if isinstance(validation_result, str):\n try:\n validation_result = json.loads(validation_result)\n except:\n return {\"verdict\": \"ACCEPT\", \"challenges\": [], \"message\": \"Cannot parse validation result\"}\n \n score = validation_result.get(\"overall_score\", 1.0)\n verdict = validation_result.get(\"verdict\", \"PASS\")\n \n # Challenge overly strict validation\n if verdict == \"FAIL\" and score > 0.35:\n challenges.append({\n \"type\": \"borderline_fail\",\n \"message\": f\"Score {score:.2f} is close to threshold. Consider CONDITIONAL instead of FAIL.\",\n \"severity\": \"warning\"\n })\n \n # Check if adversarial tests are too aggressive\n adversarial = validation_result.get(\"adversarial_results\", [])\n false_positives = sum(1 for a in adversarial if a.get(\"passed\") is False and a.get(\"confidence\", 1) < 0.5)\n if false_positives > 0:\n challenges.append({\n \"type\": \"false_positive_risk\",\n \"message\": f\"{false_positives} adversarial flags may be false positives (low confidence)\",\n \"severity\": \"warning\"\n })\n \n challenge_score = max(0, 1.0 - len(challenges) * 0.2)\n \n return {\n \"challenge_score\": round(challenge_score, 3),\n \"challenges\": challenges,\n \"verdict\": \"OVERRIDE\" if challenge_score < 0.5 else \"ACCEPT\",\n \"original_verdict\": verdict\n }\n\ndef get_stats(db_path=None):\n \"\"\"Get fire engine statistics\"\"\"\n conn = _init_db(db_path)\n \n total = conn.execute(\"SELECT COUNT(*) FROM executions\").fetchone()[0]\n completed = conn.execute(\"SELECT COUNT(*) FROM executions WHERE status='completed'\").fetchone()[0]\n avg_quality = conn.execute(\"SELECT AVG(quality_score) FROM executions WHERE status='completed'\").fetchone()[0] or 0\n avg_duration = conn.execute(\"SELECT AVG(duration_s) FROM executions WHERE status='completed'\").fetchone()[0] or 0\n \n by_model = conn.execute(\"SELECT model_used, COUNT(*) FROM executions GROUP BY model_used\").fetchall()\n \n conn.close()\n \n return {\n \"total_executions\": total,\n \"completed\": completed,\n \"avg_quality\": round(avg_quality, 3),\n \"avg_duration_s\": round(avg_duration, 2),\n \"by_model\": {m[0]: m[1] for m in by_model}\n }\n\n\ndef _run_tests():\n import tempfile\n global DB_PATH\n old_path = DB_PATH\n DB_PATH = os.path.join(tempfile.mkdtemp(), \"test_fire.db\")\n \n passed = 0\n total = 5\n \n # Test 1: Decompose task\n st = decompose_task(\"Research SiC market, design comparison framework, build analysis tool, test with real data\")\n assert len(st) >= 3, f\"Too few subtasks: {st}\"\n passed += 1\n print(f\" Test 1 PASS: {len(st)} sub-tasks decomposed\")\n \n # Test 2: Execute task (local mode)\n r = execute_task(\"Analyze competitive landscape of SiC power devices\", task_id=\"T-001\", domain=\"semiconductor\")\n assert r[\"status\"] == \"completed\", f\"Not completed: {r}\"\n assert r[\"quality_score\"] > 0, f\"Zero quality: {r}\"\n passed += 1\n print(f\" Test 2 PASS: executed, quality={r['quality_score']}, {r['subtasks']} subtasks\")\n \n # Test 3: Xiangke challenge metal\n mock_validation = {\"overall_score\": 0.45, \"verdict\": \"FAIL\", \"adversarial_results\": []}\n c = xiangke_challenge_metal(mock_validation)\n assert c[\"verdict\"] in [\"ACCEPT\", \"OVERRIDE\"], f\"Bad verdict: {c}\"\n assert len(c[\"challenges\"]) > 0, f\"No challenges for borderline fail: {c}\"\n passed += 1\n print(f\" Test 3 PASS: challenged metal, verdict={c['verdict']}, {len(c['challenges'])} challenges\")\n \n # Test 4: Stats\n stats = get_stats()\n assert stats[\"total_executions\"] >= 1, f\"No executions: {stats}\"\n passed += 1\n print(f\" Test 4 PASS: {stats['total_executions']} executions, avg_quality={stats['avg_quality']}\")\n \n # Test 5: Numbered task decomposition\n st2 = decompose_task(\"1. Research market size\\n2. Identify key players\\n3. Analyze pricing\\n4. Write report\")\n assert len(st2) == 4, f\"Wrong count: {st2}\"\n assert st2[0][\"type\"] == \"explicit\", f\"Not explicit: {st2}\"\n passed += 1\n print(f\" Test 5 PASS: explicit decomposition, {len(st2)} items\")\n \n DB_PATH = old_path\n return passed, total\n\nif __name__ == \"__main__\":\n print(\"Fire Engine (Zhuque/South) - Self Tests\")\n passed, total = _run_tests()\n print(f\"\\nResults: {passed}/{total} passed\")\n"}}, "philosophies/01_qinglong_daoism_emergence/auto_incubation.py": {"66dc8fe8b6ac3496ef57ffaf424936047020bf5f": {"t": 1785599309.506779, "n": 5712, "h": "1a794e102a2e2998", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nAuto Incubation Pipeline v1.0\n青龙·种子飞轮 — 自动孵化流水线\n\n种子→评估→孵化→任务 全自动\n\"\"\"\nimport json, os\nfrom datetime import datetime\n\nclass AutoIncubation:\n def __init__(self, db_path=None):\n self.db_path = db_path or os.path.join(os.path.dirname(__file__), \"incubation_pipeline.json\")\n self.data = self._load()\n \n def _load(self):\n if os.path.exists(self.db_path):\n with open(self.db_path, 'r', encoding='utf-8') as f:\n return json.load(f)\n return {\"pipeline\": [], \"graduated\": [], \"rejected\": [], \"meta\": {\"version\": \"1.0\"}}\n \n def _save(self):\n self.data[\"meta\"][\"updated\"] = datetime.now().isoformat()\n with open(self.db_path, 'w', encoding='utf-8') as f:\n json.dump(self.data, f, ensure_ascii=False, indent=2)\n \n def intake(self, seed_id, name, domain, raw_score):\n \"\"\"Stage 1: 种子进入流水线\"\"\"\n entry = {\n \"seed_id\": seed_id, \"name\": name, \"domain\": domain,\n \"stage\": \"intake\", \"raw_score\": raw_score,\n \"stages_completed\": [], \"entered\": datetime.now().isoformat()\n }\n self.data[\"pipeline\"].append(entry)\n self._save()\n return entry\n \n def evaluate(self, seed_id):\n \"\"\"Stage 2: 评估\"\"\"\n entry = next((e for e in self.data[\"pipeline\"] if e[\"seed_id\"] == seed_id), None)\n if not entry:\n return None\n \n if entry[\"raw_score\"] >= 6.0:\n entry[\"stage\"] = \"incubating\"\n entry[\"eval_result\"] = \"pass\"\n elif entry[\"raw_score\"] >= 4.0:\n entry[\"stage\"] = \"needs_work\"\n entry[\"eval_result\"] = \"conditional\"\n else:\n entry[\"stage\"] = \"rejected\"\n entry[\"eval_result\"] = \"fail\"\n self.data[\"rejected\"].append(entry)\n self.data[\"pipeline\"].remove(entry)\n \n entry[\"stages_completed\"].append(\"evaluate\")\n self._save()\n return entry\n \n def incubate(self, seed_id, iterations=3):\n \"\"\"Stage 3: 孵化(模拟迭代改进)\"\"\"\n entry = next((e for e in self.data[\"pipeline\"] if e[\"seed_id\"] == seed_id), None)\n if not entry or entry[\"stage\"] not in (\"incubating\", \"needs_work\"):\n return None\n \n score = entry[\"raw_score\"]\n for i in range(iterations):\n improvement = 0.3 * (10 - score) / 10 # 递减改进\n score += improvement\n \n entry[\"incubated_score\"] = round(score, 2)\n entry[\"iterations\"] = iterations\n entry[\"stages_completed\"].append(\"incubate\")\n \n if score >= 7.0:\n entry[\"stage\"] = \"ready\"\n else:\n entry[\"stage\"] = \"incubating\"\n \n self._save()\n return entry\n \n def graduate(self, seed_id):\n \"\"\"Stage 4: 毕业成为任务\"\"\"\n entry = next((e for e in self.data[\"pipeline\"] if e[\"seed_id\"] == seed_id), None)\n if not entry or entry[\"stage\"] != \"ready\":\n return None\n \n task = {\n \"task_id\": f\"T-{seed_id}\",\n \"name\": entry[\"name\"],\n \"domain\": entry[\"domain\"],\n \"source_seed\": seed_id,\n \"quality_score\": entry.get(\"incubated_score\", entry[\"raw_score\"]),\n \"graduated\": datetime.now().isoformat()\n }\n \n entry[\"stage\"] = \"graduated\"\n entry[\"stages_completed\"].append(\"graduate\")\n self.data[\"graduated\"].append(task)\n self._save()\n return task\n \n def run_full_pipeline(self, seeds):\n \"\"\"一键全流程\"\"\"\n results = []\n for s in seeds:\n self.intake(s[\"id\"], s[\"name\"], s[\"domain\"], s[\"score\"])\n self.evaluate(s[\"id\"])\n entry = next((e for e in self.data[\"pipeline\"] if e[\"seed_id\"] == s[\"id\"]), None)\n if entry and entry[\"stage\"] in (\"incubating\", \"needs_work\"):\n self.incubate(s[\"id\"])\n entry = next((e for e in self.data[\"pipeline\"] if e[\"seed_id\"] == s[\"id\"]), None)\n if entry and entry[\"stage\"] == \"ready\":\n task = self.graduate(s[\"id\"])\n results.append({\"seed\": s[\"id\"], \"result\": \"graduated\", \"task\": task[\"task_id\"]})\n else:\n results.append({\"seed\": s[\"id\"], \"result\": entry[\"stage\"] if entry else \"lost\"})\n elif entry:\n results.append({\"seed\": s[\"id\"], \"result\": entry[\"stage\"]})\n else:\n results.append({\"seed\": s[\"id\"], \"result\": \"rejected\"})\n return results\n\n\ndef main():\n pipeline = AutoIncubation()\n \n seeds = [\n {\"id\": \"S-201\", \"name\": \"券商四流清算SaaS\", \"domain\": \"finance\", \"score\": 8.5},\n {\"id\": \"S-202\", \"name\": \"SiC外延片路由器\", \"domain\": \"semiconductor\", \"score\": 7.0},\n {\"id\": \"S-203\", \"name\": \"DRG/DIP医疗清算\", \"domain\": \"medical\", \"score\": 6.2},\n {\"id\": \"S-204\", \"name\": \"碳纤维供应链DB\", \"domain\": \"materials\", \"score\": 7.5},\n {\"id\": \"S-205\", \"name\": \"量子模拟平台\", \"domain\": \"ai\", \"score\": 3.5},\n {\"id\": \"S-206\", \"name\": \"智能建筑OS\", \"domain\": \"robotics\", \"score\": 5.8},\n ]\n \n print(\"=== Auto Incubation Pipeline v1.0 ===\")\n results = pipeline.run_full_pipeline(seeds)\n for r in results:\n icon = {\"graduated\": \"+\", \"incubating\": \"~\", \"needs_work\": \"?\", \"rejected\": \"x\"}.get(r[\"result\"], \"?\")\n task_info = f\" -> {r['task']}\" if \"task\" in r else \"\"\n print(f\" [{icon}] {r['seed']:6s} {r['result']:12s}{task_info}\")\n \n print(f\"\\n Pipeline: {len(pipeline.data['pipeline'])} in pipeline, \"\n f\"{len(pipeline.data['graduated'])} graduated, \"\n f\"{len(pipeline.data['rejected'])} rejected\")\n\nif __name__ == \"__main__\":\n main()\n"}}, "philosophies/01_qinglong_daoism_emergence/seed_scorer.py": {"372a8387337e1b39f1fafdd8e7a7788effad14cc": {"t": 1785599309.5084505, "n": 5586, "h": "fda99a79e601f0b8", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nseed_scorer.py v1.0.0 — Wood Engine Seed Scoring Model\n========================================================\nScores and ranks seeds before they enter the pipeline,\nfiltering low-quality seeds early.\n\nScoring dimensions:\n - Specificity (0-1): How specific vs vague\n - Novelty (0-1): How different from existing seeds\n - Actionability (0-1): Can it be analyzed?\n - Domain relevance (0-1): Fits the target domain?\n\nDecision: Robin 2026-05-02\n\"\"\"\n\nimport json, hashlib, re\nfrom typing import List, Dict\n\nVERSION = \"1.0.0\"\n\n# Minimum score to pass into pipeline\nMIN_SCORE = 0.3\n\n\ndef score_seed(seed: str, domain: str = \"general\",\n existing_seeds: List[str] = None) -> Dict:\n \"\"\"Score a single seed on 4 dimensions.\"\"\"\n specificity = _score_specificity(seed)\n novelty = _score_novelty(seed, existing_seeds or [])\n actionability = _score_actionability(seed)\n relevance = _score_relevance(seed, domain)\n \n composite = (specificity * 0.25 + novelty * 0.25 +\n actionability * 0.30 + relevance * 0.20)\n \n return {\n \"seed\": seed[:100],\n \"scores\": {\n \"specificity\": round(specificity, 3),\n \"novelty\": round(novelty, 3),\n \"actionability\": round(actionability, 3),\n \"relevance\": round(relevance, 3),\n },\n \"composite\": round(composite, 3),\n \"passes\": composite >= MIN_SCORE,\n }\n\n\ndef score_batch(seeds: List[str], domain: str = \"general\") -> Dict:\n \"\"\"Score and rank a batch of seeds.\"\"\"\n results = []\n for i, seed in enumerate(seeds):\n existing = seeds[:i] # Compare against earlier seeds\n result = score_seed(seed, domain, existing)\n results.append(result)\n \n results.sort(key=lambda x: -x[\"composite\"])\n passed = [r for r in results if r[\"passes\"]]\n \n return {\n \"total\": len(seeds),\n \"passed\": len(passed),\n \"filtered\": len(seeds) - len(passed),\n \"ranked\": results,\n \"avg_score\": round(sum(r[\"composite\"] for r in results) / max(len(results), 1), 3),\n }\n\n\ndef _score_specificity(seed: str) -> float:\n \"\"\"More specific = higher score.\"\"\"\n words = seed.split()\n if len(words) < 3:\n return 0.2\n if len(words) > 20:\n return 0.6\n \n # Check for specific indicators\n score = 0.5\n if any(c.isdigit() for c in seed):\n score += 0.15\n if any(w in seed.lower() for w in [\"specifically\", \"exactly\", \"particularly\", \"namely\"]):\n score += 0.1\n if len(words) >= 8:\n score += 0.1\n if any(c in seed for c in [\"%\", \"$\", \"=\", \">\"]):\n score += 0.1\n \n return min(score, 1.0)\n\n\ndef _score_novelty(seed: str, existing: List[str]) -> float:\n \"\"\"More different from existing seeds = higher score.\"\"\"\n if not existing:\n return 0.8\n \n seed_hash = set(seed.lower().split())\n max_overlap = 0\n for ex in existing:\n ex_hash = set(ex.lower().split())\n if not seed_hash or not ex_hash:\n continue\n overlap = len(seed_hash & ex_hash) / max(len(seed_hash | ex_hash), 1)\n max_overlap = max(max_overlap, overlap)\n \n return max(1.0 - max_overlap, 0.1)\n\n\ndef _score_actionability(seed: str) -> float:\n \"\"\"Can this seed lead to concrete analysis?\"\"\"\n score = 0.5\n \n action_words = [\"analyze\", \"compare\", \"evaluate\", \"assess\", \"measure\",\n \"test\", \"verify\", \"explore\", \"investigate\", \"examine\",\n \"how\", \"why\", \"what\", \"impact\", \"effect\", \"trend\"]\n \n lower = seed.lower()\n matches = sum(1 for w in action_words if w in lower)\n score += min(matches * 0.1, 0.4)\n \n if len(seed) < 10:\n score -= 0.2\n \n return max(min(score, 1.0), 0.1)\n\n\ndef _score_relevance(seed: str, domain: str) -> float:\n \"\"\"Does the seed match the target domain?\"\"\"\n domain_keywords = {\n \"finance\": [\"market\", \"stock\", \"option\", \"fund\", \"price\", \"risk\",\n \"return\", \"portfolio\", \"hedge\", \"trade\", \"bond\"],\n \"technology\": [\"algorithm\", \"data\", \"system\", \"network\", \"compute\",\n \"software\", \"hardware\", \"chip\", \"AI\", \"model\"],\n \"materials\": [\"carbon\", \"silicon\", \"alloy\", \"fiber\", \"polymer\",\n \"ceramic\", \"metal\", \"composite\", \"crystal\", \"nano\"],\n }\n \n if domain == \"general\":\n return 0.7\n \n keywords = domain_keywords.get(domain, [])\n if not keywords:\n return 0.5\n \n lower = seed.lower()\n matches = sum(1 for kw in keywords if kw in lower)\n return min(0.3 + matches * 0.15, 1.0)\n\n\ndef self_test():\n print(f\"seed_scorer.py v{VERSION}\")\n \n # Single seed\n r = score_seed(\"Analyze the impact of SiC wafer pricing on EV battery costs\", \"materials\")\n assert r[\"passes\"] == True\n assert r[\"composite\"] > 0.5\n print(\" single: PASS\")\n \n # Batch\n seeds = [\n \"Analyze SiC market trends and pricing dynamics\",\n \"What is the competitive landscape for SiC suppliers?\",\n \"stuff\",\n \"How does SiC compare to GaN in power electronics?\",\n ]\n batch = score_batch(seeds, \"materials\")\n assert batch[\"passed\"] >= 2\n assert batch[\"filtered\"] >= 1 # \"stuff\" should be filtered\n assert batch[\"ranked\"][0][\"composite\"] >= batch[\"ranked\"][-1][\"composite\"]\n print(\" batch: PASS\")\n \n # Novelty\n n = _score_novelty(\"completely unique topic\", [\"same old thing\"])\n assert n > 0.5\n print(\" novelty: PASS\")\n \n print(\" ALL PASS\")\n return True\n\n\nif __name__ == \"__main__\":\n self_test()\n"}}, "core/models.py": {"c1d49e40369573a137e02eef265fe10501d50f62": {"t": 1785599309.649572, "n": 1857, "h": "9d4bc860db64a337", "c": "# -*- coding: utf-8 -*-\n\"\"\"Hub 数据库层 - SQLite\"\"\"\nimport sqlite3\nimport os\nfrom datetime import datetime\n\nDB_PATH = os.environ.get('MATRIX_DB', 'D:/ClawMatrix/hub_new.db')\n\ndef get_db():\n \"\"\"获取数据库连接\"\"\"\n conn = sqlite3.connect(DB_PATH, timeout=10)\n conn.row_factory = sqlite3.Row\n return conn\n\ndef init_db():\n \"\"\"初始化数据库表\"\"\"\n conn = get_db()\n cursor = conn.cursor()\n \n # 任务表\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS tasks (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n task_id TEXT UNIQUE NOT NULL,\n goal TEXT,\n scope TEXT,\n constraints TEXT,\n done_definition TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 0,\n created_at TEXT,\n updated_at TEXT,\n node_id TEXT,\n result TEXT,\n error TEXT\n )\n ''')\n \n # 节点表\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS nodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n node_id TEXT UNIQUE NOT NULL,\n name TEXT,\n status TEXT DEFAULT 'offline',\n last_heartbeat TEXT,\n capabilities TEXT,\n credits INTEGER DEFAULT 0\n )\n ''')\n \n # 事件日志表\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS event_log (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n event_id TEXT,\n event_type TEXT,\n node_id TEXT,\n data TEXT,\n created_at TEXT\n )\n ''')\n \n # Lux 表\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS lux (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n node_id TEXT UNIQUE,\n credits INTEGER DEFAULT 0,\n updated_at TEXT\n )\n ''')\n \n conn.commit()\n conn.close()\n\n# 初始化\ninit_db()\n"}}, "philosophies/01_qinglong_daoism_emergence/seed_to_task.py": {"0f46c48f8cdef9694796dfca0100eaffab8619d7": {"t": 1785599309.7008402, "n": 7910, "h": "228df21813b1a4ca", "c": "\n\"\"\"\nseed_to_task.py - 种子→任务自动转换引擎\n种子经过评分后自动生成DAG任务树,分配优先级和资源,写入Hub\n\"\"\"\nimport json, hashlib, time, sys\nfrom datetime import datetime\n\nclass SeedToTaskEngine:\n \"\"\"将评分通过的种子自动转换为DAG任务树\"\"\"\n \n # Task templates by seed type\n TASK_TEMPLATES = {\n 'research': {\n 'phases': [\n {'name': 'Literature Review', 'type': 'qinglong', 'weight': 0.2},\n {'name': 'Data Collection', 'type': 'qinglong', 'weight': 0.2},\n {'name': 'Analysis', 'type': 'xuanwu', 'weight': 0.3},\n {'name': 'Report Generation', 'type': 'zhuque', 'weight': 0.3},\n ],\n 'base_lux': 100\n },\n 'development': {\n 'phases': [\n {'name': 'Requirements Analysis', 'type': 'qinglong', 'weight': 0.15},\n {'name': 'Architecture Design', 'type': 'xuanwu', 'weight': 0.2},\n {'name': 'Implementation', 'type': 'zhuque', 'weight': 0.35},\n {'name': 'Testing', 'type': 'baihu', 'weight': 0.15},\n {'name': 'Deployment', 'type': 'zhuque', 'weight': 0.15},\n ],\n 'base_lux': 150\n },\n 'analysis': {\n 'phases': [\n {'name': 'Problem Definition', 'type': 'qinglong', 'weight': 0.15},\n {'name': 'Multi-source Research', 'type': 'qinglong', 'weight': 0.25},\n {'name': 'Evaluation & Scoring', 'type': 'baihu', 'weight': 0.25},\n {'name': 'Synthesis', 'type': 'xuanwu', 'weight': 0.2},\n {'name': 'Output Report', 'type': 'zhuque', 'weight': 0.15},\n ],\n 'base_lux': 120\n },\n 'default': {\n 'phases': [\n {'name': 'Discovery', 'type': 'qinglong', 'weight': 0.25},\n {'name': 'Evaluation', 'type': 'baihu', 'weight': 0.25},\n {'name': 'Convergence', 'type': 'xuanwu', 'weight': 0.25},\n {'name': 'Output', 'type': 'zhuque', 'weight': 0.25},\n ],\n 'base_lux': 80\n }\n }\n \n PRIORITY_MAP = {\n 'approve': 'P1',\n 'review': 'P2',\n 'reject': 'P3'\n }\n \n def __init__(self, hub_url='http://localhost:19104'):\n self.hub_url = hub_url\n self.generated_tasks = []\n \n def convert_seed(self, seed_id, seed_content, evaluation, seed_type='default'):\n \"\"\"将种子转换为DAG任务树\"\"\"\n if evaluation['decision'] == 'reject':\n return {'status': 'rejected', 'reason': 'Seed evaluation rejected'}\n \n template = self.TASK_TEMPLATES.get(seed_type, self.TASK_TEMPLATES['default'])\n priority = self.PRIORITY_MAP.get(evaluation['decision'], 'P2')\n \n # Calculate LUX based on evaluation score\n score_multiplier = evaluation['weighted_total'] / 7.0\n total_lux = int(template['base_lux'] * score_multiplier)\n \n # Generate DAG\n dag = self._generate_dag(seed_id, seed_content, template, priority, total_lux)\n \n # Add metadata\n dag['seed_id'] = seed_id\n dag['evaluation_id'] = evaluation['eval_id']\n dag['evaluation_score'] = evaluation['weighted_total']\n dag['created_at'] = datetime.now().isoformat()\n dag['total_lux'] = total_lux\n dag['priority'] = priority\n dag['seed_type'] = seed_type\n \n self.generated_tasks.append(dag)\n return dag\n \n def _generate_dag(self, seed_id, content, template, priority, total_lux):\n \"\"\"生成DAG任务树\"\"\"\n tasks = []\n dependencies = {}\n prev_task_id = None\n \n for i, phase in enumerate(template['phases']):\n phase_name = phase['name']\n task_id = f\"task-{hashlib.md5(f'{seed_id}-{phase_name}-{time.time()}'.encode()).hexdigest()[:16]}\"\n \n phase_lux = int(total_lux * phase['weight'])\n \n task = {\n 'task_id': task_id,\n 'title': f\"{phase['name']} - {content[:50]}\",\n 'description': f\"Phase {i+1}/{len(template['phases'])}: {phase['name']}. Seed: {content[:200]}\",\n 'priority': priority,\n 'lux_reward': max(10, phase_lux),\n 'flywheel_phase': phase['type'],\n 'phase_index': i,\n 'tags': [phase['type'], seed_id[:12]]\n }\n tasks.append(task)\n \n # Build dependency chain (sequential DAG)\n if prev_task_id:\n dependencies[task_id] = [prev_task_id]\n else:\n dependencies[task_id] = []\n \n prev_task_id = task_id\n \n return {\n 'tasks': tasks,\n 'dependencies': dependencies,\n 'dag_type': 'sequential',\n 'task_count': len(tasks)\n }\n \n def submit_to_hub(self, dag, dry_run=True):\n \"\"\"将DAG任务树提交到Hub\"\"\"\n if dry_run:\n return {\n 'status': 'dry_run',\n 'task_count': dag['task_count'],\n 'total_lux': dag['total_lux'],\n 'tasks': [{'id': t['task_id'], 'title': t['title'], 'lux': t['lux_reward']} for t in dag['tasks']]\n }\n \n # Real submission via Hub API\n import urllib.request\n results = []\n admin_key = ''\n try:\n admin_key = open(r'D:\\ClawMatrix\\.hub_admin_key').read().strip()\n except:\n pass\n \n for task in dag['tasks']:\n payload = json.dumps({\n 'title': task['title'],\n 'description': task['description'],\n 'priority': task['priority'],\n 'lux_reward': task['lux_reward'],\n 'tags': task.get('tags', [])\n }).encode()\n \n try:\n req = urllib.request.Request(\n f\"{self.hub_url}/api/v1/task/create\",\n data=payload,\n headers={\n 'Content-Type': 'application/json',\n 'X-Matrix-Secret': admin_key\n }\n )\n resp = urllib.request.urlopen(req, timeout=10)\n result = json.loads(resp.read())\n results.append({'task_id': task['task_id'], 'status': 'created', 'hub_response': result})\n except Exception as e:\n results.append({'task_id': task['task_id'], 'status': 'failed', 'error': str(e)})\n \n return {'status': 'submitted', 'results': results}\n \n def get_generated_tasks(self):\n return self.generated_tasks\n\n\n# === Self-test ===\nif __name__ == '__main__':\n sys.stdout.reconfigure(encoding='utf-8')\n \n engine = SeedToTaskEngine()\n \n # Mock evaluation result\n mock_eval = {\n 'eval_id': 'eval-test123',\n 'weighted_total': 7.5,\n 'decision': 'approve'\n }\n \n # Convert seed\n dag = engine.convert_seed(\n 'seed-test-001',\n 'Build a distributed clearing system for securities firms with event sourcing and double-entry ledger',\n mock_eval,\n seed_type='development'\n )\n \n print(\"=== Seed-to-Task Engine Test ===\")\n print(f\"Seed Type: {dag['seed_type']}\")\n print(f\"Priority: {dag['priority']}\")\n print(f\"Total LUX: {dag['total_lux']}\")\n print(f\"Task Count: {dag['task_count']}\")\n print(f\"\\nGenerated DAG:\")\n for t in dag['tasks']:\n deps = dag['dependencies'].get(t['task_id'], [])\n dep_str = f\" (depends on: {deps[0][:12]}...)\" if deps else \" (root)\"\n print(f\" [{t['flywheel_phase']}] {t['title']} - {t['lux_reward']}L{dep_str}\")\n \n # Dry run submission\n result = engine.submit_to_hub(dag, dry_run=True)\n print(f\"\\nDry Run: {result['status']}, {result['task_count']} tasks, {result['total_lux']}L\")\n \n print(\"\\nSeed-to-Task Engine: OK\")\n"}}, "philosophies/01_qinglong_daoism_emergence/creative_seed_engine.py": {"e120c24cd78d1a37fc7ac70fb72b9cf67d56c936": {"t": 1785599309.7214348, "n": 11269, "h": "6f2256083e0fc9b9", "c": "# -*- coding: utf-8 -*-\n\"\"\"\ncreative_seed_engine.py - 青龙创意发散引擎 v2.0 (Seed-03)\nv1.0.0 | 2026-05-03\n\nGenerates diverse, high-quality seed angles for the Wood phase.\nUses multiple creativity techniques:\n1. SCAMPER (Substitute, Combine, Adapt, Modify, Put-to-use, Eliminate, Reverse)\n2. Six Thinking Hats (White/Red/Black/Yellow/Green/Blue)\n3. First Principles decomposition\n4. Analogy bridging (cross-domain pattern matching)\n5. Contrarian inversion\n\"\"\"\nimport json, random, hashlib\nfrom typing import Dict, List, Optional, Tuple\nfrom datetime import datetime\n\n# Creativity technique templates\nSCAMPER_PROMPTS = {\n \"substitute\": \"What if we replaced a key component with something entirely different?\",\n \"combine\": \"What if we merged this with an unrelated domain?\",\n \"adapt\": \"What existing solution from another field could be adapted here?\",\n \"modify\": \"What if we magnified or minimized a key aspect by 10x?\",\n \"put_to_use\": \"What if this capability was applied to a completely different problem?\",\n \"eliminate\": \"What if we removed the most obvious constraint?\",\n \"reverse\": \"What if we approached this from the exact opposite direction?\"\n}\n\nSIX_HATS = {\n \"white\": {\"role\": \"Data Analyst\", \"focus\": \"What facts and data do we have? What's missing?\"},\n \"red\": {\"role\": \"Intuition\", \"focus\": \"What's your gut feeling? What emotions does this trigger?\"},\n \"black\": {\"role\": \"Devil's Advocate\", \"focus\": \"What could go wrong? What are the risks?\"},\n \"yellow\": {\"role\": \"Optimist\", \"focus\": \"What's the best possible outcome? What value is hidden?\"},\n \"green\": {\"role\": \"Creative\", \"focus\": \"What's a wild, unconventional approach?\"},\n \"blue\": {\"role\": \"Strategist\", \"focus\": \"What's the meta-pattern? How do we organize our thinking?\"}\n}\n\n\nclass CreativeSeedEngine:\n \"\"\"Generate diverse seed angles for Wuxing Wood phase.\"\"\"\n \n def __init__(self, llm_fn=None):\n self.llm_fn = llm_fn\n self.seed_history: List[Dict] = []\n self.diversity_threshold = 0.3 # Min cosine distance between seeds\n \n def generate_seeds(self, topic: str, count: int = 8, \n techniques: List[str] = None,\n context: dict = None) -> List[Dict]:\n \"\"\"\n Generate diverse seed angles for a topic.\n \n Args:\n topic: The analysis topic\n count: Number of seeds to generate\n techniques: Which techniques to use (default: all)\n context: Additional context (prior results, constraints)\n \n Returns:\n List of seed dicts with angle, technique, rationale\n \"\"\"\n techniques = techniques or [\"scamper\", \"six_hats\", \"first_principles\", \n \"analogy\", \"contrarian\"]\n \n all_seeds = []\n \n for technique in techniques:\n if technique == \"scamper\":\n all_seeds.extend(self._scamper_seeds(topic, context))\n elif technique == \"six_hats\":\n all_seeds.extend(self._six_hats_seeds(topic, context))\n elif technique == \"first_principles\":\n all_seeds.extend(self._first_principles_seeds(topic, context))\n elif technique == \"analogy\":\n all_seeds.extend(self._analogy_seeds(topic, context))\n elif technique == \"contrarian\":\n all_seeds.extend(self._contrarian_seeds(topic, context))\n \n # Deduplicate and score\n scored = self._score_and_rank(all_seeds, topic)\n \n # Select top-N with diversity\n selected = self._diverse_select(scored, count)\n \n # Record\n self.seed_history.append({\n \"timestamp\": datetime.now().isoformat(),\n \"topic\": topic[:100],\n \"generated\": len(all_seeds),\n \"selected\": len(selected),\n \"techniques\": techniques\n })\n \n return selected\n \n def _scamper_seeds(self, topic: str, context: dict = None) -> List[Dict]:\n seeds = []\n for key, prompt in SCAMPER_PROMPTS.items():\n seeds.append({\n \"angle\": \"{}: {}\".format(key.upper(), prompt),\n \"technique\": \"scamper\",\n \"sub_technique\": key,\n \"topic_application\": \"Apply {} to: {}\".format(key, topic[:80]),\n \"novelty_score\": 0.6 + random.random() * 0.3\n })\n return seeds\n \n def _six_hats_seeds(self, topic: str, context: dict = None) -> List[Dict]:\n seeds = []\n for color, hat in SIX_HATS.items():\n seeds.append({\n \"angle\": \"{} Hat ({}): {}\".format(color.capitalize(), hat[\"role\"], hat[\"focus\"]),\n \"technique\": \"six_hats\",\n \"sub_technique\": color,\n \"topic_application\": \"Analyze '{}' as {}\".format(topic[:60], hat[\"role\"]),\n \"novelty_score\": 0.5 + random.random() * 0.3\n })\n return seeds\n \n def _first_principles_seeds(self, topic: str, context: dict = None) -> List[Dict]:\n principles = [\n \"What are the fundamental truths/axioms here?\",\n \"Strip away all assumptions — what remains?\",\n \"What would a solution look like if built from scratch?\",\n \"What constraints are real vs self-imposed?\",\n \"What's the atomic unit of value in this domain?\"\n ]\n seeds = []\n for p in principles:\n seeds.append({\n \"angle\": \"First Principles: {}\".format(p),\n \"technique\": \"first_principles\",\n \"topic_application\": \"Decompose '{}': {}\".format(topic[:50], p),\n \"novelty_score\": 0.7 + random.random() * 0.2\n })\n return seeds\n \n def _analogy_seeds(self, topic: str, context: dict = None) -> List[Dict]:\n domains = [\n (\"Biology\", \"How does nature solve a similar problem?\"),\n (\"Military\", \"What strategic parallel exists in warfare?\"),\n (\"Sports\", \"What coaching/training insight applies?\"),\n (\"Architecture\", \"How would you design this as a building?\"),\n (\"Music\", \"What's the rhythm, harmony, or dissonance here?\"),\n (\"Cooking\", \"What ingredients, recipe, or timing insights apply?\"),\n ]\n seeds = []\n for domain, question in domains:\n seeds.append({\n \"angle\": \"Analogy from {}: {}\".format(domain, question),\n \"technique\": \"analogy\",\n \"sub_technique\": domain.lower(),\n \"topic_application\": \"Map '{}' to {} domain\".format(topic[:50], domain),\n \"novelty_score\": 0.65 + random.random() * 0.3\n })\n return seeds\n \n def _contrarian_seeds(self, topic: str, context: dict = None) -> List[Dict]:\n inversions = [\n \"What if the opposite of the consensus is true?\",\n \"What if the biggest risk is actually the biggest opportunity?\",\n \"What if we optimized for the minority case instead of majority?\",\n \"What would a competitor do that we'd never consider?\",\n \"What if we deliberately failed at this — what would we learn?\",\n ]\n seeds = []\n for inv in inversions:\n seeds.append({\n \"angle\": \"Contrarian: {}\".format(inv),\n \"technique\": \"contrarian\",\n \"topic_application\": \"Invert assumptions about '{}'\".format(topic[:60]),\n \"novelty_score\": 0.75 + random.random() * 0.2\n })\n return seeds\n \n def _score_and_rank(self, seeds: List[Dict], topic: str) -> List[Dict]:\n \"\"\"Score seeds by relevance and novelty.\"\"\"\n for seed in seeds:\n # Simple heuristic scoring\n novelty = seed.get(\"novelty_score\", 0.5)\n \n # Relevance: check keyword overlap with topic\n topic_words = set(topic.lower().split())\n angle_words = set(seed.get(\"angle\", \"\").lower().split())\n overlap = len(topic_words & angle_words) / max(len(topic_words), 1)\n relevance = min(1.0, overlap * 3 + 0.3) # Boost base relevance\n \n # Combined score\n seed[\"relevance_score\"] = round(relevance, 3)\n seed[\"combined_score\"] = round(novelty * 0.6 + relevance * 0.4, 3)\n \n return sorted(seeds, key=lambda x: x[\"combined_score\"], reverse=True)\n \n def _diverse_select(self, ranked_seeds: List[Dict], count: int) -> List[Dict]:\n \"\"\"Select top seeds ensuring technique diversity.\"\"\"\n selected = []\n techniques_used = set()\n \n # First pass: one from each technique\n for seed in ranked_seeds:\n if len(selected) >= count:\n break\n tech = seed.get(\"technique\", \"unknown\")\n if tech not in techniques_used:\n selected.append(seed)\n techniques_used.add(tech)\n \n # Second pass: fill remaining with best scores\n for seed in ranked_seeds:\n if len(selected) >= count:\n break\n if seed not in selected:\n selected.append(seed)\n \n return selected\n \n def get_stats(self) -> Dict:\n \"\"\"Get engine usage statistics.\"\"\"\n return {\n \"total_runs\": len(self.seed_history),\n \"total_generated\": sum(h[\"generated\"] for h in self.seed_history),\n \"total_selected\": sum(h[\"selected\"] for h in self.seed_history),\n \"avg_generation_per_run\": (\n sum(h[\"generated\"] for h in self.seed_history) / max(len(self.seed_history), 1)\n ),\n \"techniques_used\": list(set(\n t for h in self.seed_history for t in h.get(\"techniques\", [])\n ))\n }\n\n\n# Self-test\nif __name__ == \"__main__\":\n print(\"=== creative_seed_engine.py self-test ===\")\n engine = CreativeSeedEngine()\n \n # Test basic generation\n seeds = engine.generate_seeds(\"AI-powered urban infrastructure optimization\", count=8)\n assert len(seeds) == 8\n print(\" generation: PASS ({} seeds)\".format(len(seeds)))\n \n # Test technique diversity\n techniques = set(s[\"technique\"] for s in seeds)\n assert len(techniques) >= 3\n print(\" diversity: PASS ({} techniques: {})\".format(len(techniques), techniques))\n \n # Test scoring\n assert all(\"combined_score\" in s for s in seeds)\n assert all(0 <= s[\"combined_score\"] <= 1 for s in seeds)\n print(\" scoring: PASS\")\n \n # Test with Chinese topic\n seeds_cn = engine.generate_seeds(\"武汉车谷智能网联汽车产业链分析\", count=6)\n assert len(seeds_cn) == 6\n print(\" chinese_topic: PASS\")\n \n # Test stats\n stats = engine.get_stats()\n assert stats[\"total_runs\"] == 2\n assert stats[\"total_generated\"] > 0\n print(\" stats: PASS ({} total generated)\".format(stats[\"total_generated\"]))\n \n # Test custom techniques\n seeds_fp = engine.generate_seeds(\"test\", count=3, techniques=[\"first_principles\", \"contrarian\"])\n techs = set(s[\"technique\"] for s in seeds_fp)\n assert techs <= {\"first_principles\", \"contrarian\"}\n print(\" custom_techniques: PASS\")\n \n print(\"ALL PASS\")\n"}}, "philosophies/01_qinglong_daoism_emergence/seed_incubator.py": {"01ad62abac0764d09925fd25f6a5831e3e92f99e": {"t": 1785599309.784902, "n": 3663, "h": "134e9d9ce1421aae", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nSeed Incubator v1.0\n青龙·种子飞轮 → 朱雀·任务飞轮 转化引擎\n\n功能:\n- 从种子库读取种子\n- 评估种子成熟度 (potential_value * (1-risk_score/10))\n- 成熟种子 → 生成任务结构\n- 输出: 可执行任务列表\n\"\"\"\nimport json, os, hashlib\nfrom datetime import datetime\n\nclass SeedIncubator:\n def __init__(self, seed_dir=None, output_dir=None):\n self.seed_dir = seed_dir or os.path.join(os.path.dirname(__file__), \"flywheel\", \"seed_store\")\n self.output_dir = output_dir or os.path.join(os.path.dirname(__file__), \"flywheel\", \"incubated\")\n os.makedirs(self.output_dir, exist_ok=True)\n \n def load_seeds(self, batch=None):\n \"\"\"Load all seeds or a specific batch\"\"\"\n all_seeds = []\n if not os.path.exists(self.seed_dir):\n return all_seeds\n for f in os.listdir(self.seed_dir):\n if f.endswith('.json') and (batch is None or batch in f):\n path = os.path.join(self.seed_dir, f)\n with open(path, 'r', encoding='utf-8') as fh:\n data = json.load(fh)\n if \"seeds\" in data:\n all_seeds.extend(data[\"seeds\"])\n return all_seeds\n \n def evaluate_maturity(self, seed):\n \"\"\"Score seed maturity: 0-10\"\"\"\n pv = seed.get(\"potential_value\", 5)\n rs = seed.get(\"risk_score\", 5)\n maturity = pv * (1 - rs / 10)\n return round(maturity, 2)\n \n def incubate(self, min_maturity=3.0, max_tasks=20):\n \"\"\"Convert mature seeds to tasks\"\"\"\n seeds = self.load_seeds()\n if not seeds:\n return {\"tasks\": [], \"stats\": {\"total_seeds\": 0}}\n \n scored = [(s, self.evaluate_maturity(s)) for s in seeds]\n scored.sort(key=lambda x: x[1], reverse=True)\n \n mature = [(s, m) for s, m in scored if m >= min_maturity]\n \n tasks = []\n for seed, maturity in mature[:max_tasks]:\n task = {\n \"id\": f\"T-INC-{hashlib.md5(seed['id'].encode()).hexdigest()[:8]}\",\n \"name\": f\"\\u5b75\\u5316: {seed['name']}\",\n \"domain\": seed.get(\"domain\", \"general\"),\n \"priority\": \"P0\" if maturity > 6 else \"P1\" if maturity > 4 else \"P2\",\n \"source_seed\": seed[\"id\"],\n \"maturity_score\": maturity,\n \"description\": seed.get(\"hypothesis\", \"\"),\n \"status\": \"ready\",\n \"created\": datetime.now().isoformat(),\n }\n tasks.append(task)\n \n result = {\n \"tasks\": tasks,\n \"stats\": {\n \"total_seeds\": len(seeds),\n \"evaluated\": len(scored),\n \"mature\": len(mature),\n \"tasks_generated\": len(tasks),\n \"min_maturity_threshold\": min_maturity,\n }\n }\n \n # Save\n out_path = os.path.join(self.output_dir, f\"incubated_{datetime.now().strftime('%Y%m%d_%H%M')}.json\")\n with open(out_path, 'w', encoding='utf-8') as f:\n json.dump(result, ensure_ascii=False, indent=2, fp=f)\n \n return result\n\n\ndef main():\n incubator = SeedIncubator()\n result = incubator.incubate(min_maturity=3.0, max_tasks=15)\n \n print(\"=== Seed Incubator v1.0 ===\")\n print(f\"Seeds: {result['stats']['total_seeds']}\")\n print(f\"Mature: {result['stats']['mature']}\")\n print(f\"Tasks generated: {result['stats']['tasks_generated']}\")\n \n if result[\"tasks\"]:\n print(f\"\\nTop tasks:\")\n for t in result[\"tasks\"][:5]:\n print(f\" [{t['priority']}] {t['name']} (maturity={t['maturity_score']}, domain={t['domain']})\")\n\n\nif __name__ == \"__main__\":\n main()\n"}}, "src/config.py": {"7b27beeae33523ba529bdcb1df96e8bab2da1f65": {"t": 1785599309.7962055, "n": 787, "h": "bbeed31920392bab", "c": "# -*- coding: utf-8 -*-\n\"\"\"ClawMatrix 配置\"\"\"\nimport os\n\nclass MatrixConfig:\n # 节点身份\n NODE_ID = os.environ.get('MATRIX_NODE_ID', 'skycetus-hub')\n SECRET = os.environ.get('MATRIX_SECRET', 'skycetus-shared-secret')\n \n # 网络\n LISTEN_HOST = '0.0.0.0'\n LISTEN_PORT = int(os.environ.get('MATRIX_PORT', '19102'))\n \n # 标签\n TAGS = ['hub', 'task-distributor', 'skycetus']\n \n # 数据�?\n DB_PATH = os.environ.get('MATRIX_DB', 'D:/ClawMatrix/hub_new.db')\n \n # 加密\n KEY_DIR = 'D:/ClawMatrix/keys'\n \n # 心跳\n HEARTBEAT_INTERVAL = 30 # �?\n NODE_TIMEOUT = 600 # 超过此时间无心跳视为离线\n \n # 文件传输\n MAX_FILE_SIZE = 100 * 1024 * 1024 # 100MB\n TRANSFER_DIR = 'D:/ClawMatrix/transfers'\n \n # Gossip\n GOSSIP_INTERVAL = 60 # �?\n MAX_PEERS = 50\n"}}, "philosophies/02_zhuque_confucius_investigation/multiformat_output.py": {"302bda8415f9ce74c12cd46172068a8c15b10c8a": {"t": 1785599309.8372607, "n": 3020, "h": "9e3d65851ef86a72", "c": "# -*- coding: utf-8 -*-\n\"\"\"\nMulti-Format Output v1.0\n朱雀·任务飞轮 — 多格式输出引擎\n\n同一内容自动转换为HTML/Markdown/JSON/Plain格式\n\"\"\"\nimport json, os\nfrom datetime import datetime\n\nclass MultiFormatOutput:\n def __init__(self):\n self.formats = [\"html\", \"markdown\", \"json\", \"plain\"]\n \n def convert(self, content, title, metadata=None):\n \"\"\"将结构化内容转换为多种格式\"\"\"\n results = {}\n \n # HTML\n sections_html = \"\"\n for section in content.get(\"sections\", []):\n items = \"\".join(f\"
Wuxing Flywheel Analysis - Pipeline v4.1 - %s
\n{description}
\n \n{sec}
五行飞轮认知即服务 · Cognition as a Service
\n\n产业认知驱动的执行优化层
\n\n理想模型决定下限,人类残差决定上限
Full 5-phase flywheel analysis
\n\n{\"keyword\": \"碳化硅\", \"domain\": \"半导体\", \"depth\": \"standard\"}\n\nService health, Hub connection, knowledge base stats
Browse L0 materials database (42 materials × 8 chains)
\n\n?domain=半导体&tier=SView accumulated cognitive residuals
\n\n?keyword=碳化硅&limit=10Free tier: 3 analyses/day per IP
\n\nAPI key: contact@skycetus.cn for paid access
\n\nGitHub ·\n\nSkyCetus
SkyCetus Knowledge Tree — 五行飞轮认知分析索引
\n''']\n \n total_runs = len(runs)\n a_count = sum(1 for r in runs if r[4] == 'A')\n avg_score = sum(float(r[3]) for r in runs) / max(total_runs, 1)\n domains_count = len(tree)\n \n html_parts.append(f'''\n{description}
\n \n{sec}