diff --git a/VERSION b/VERSION index 92fc430a..83dcd12c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.82.0 +0.83.0 diff --git a/backend/app/api/v1/ai_workflows.py b/backend/app/api/v1/ai_workflows.py index ab7b3450..98684133 100644 --- a/backend/app/api/v1/ai_workflows.py +++ b/backend/app/api/v1/ai_workflows.py @@ -29,11 +29,13 @@ from app.services.ai.tool_registry import ( safe_web_fetch, ) from app.services.ai.workflow_evolver import ( + FIXTURE_EXPECT_KEY, compute_workflow_health, dismiss_ledger_entry, get_evolution_ledger, get_evolution_policy, incubate_workflow_from_runs, + normalize_fixture_expect, propose_meta_evolution, propose_workflow_evolution, record_run_feedback, @@ -176,6 +178,9 @@ class WorkflowFixtureCreateRequest(BaseModel): earth_context: dict[str, Any] = Field(default_factory=dict) context_json: dict[str, Any] | None = None sample_question: str = "" + # Gradable assertions: numbers / must_include / must_not_include / + # require_uncertainty_without_evidence / min_evidence (stored in context_json["expect"]). + expect: dict[str, Any] | None = None class AdvisorChatMessageInput(BaseModel): @@ -421,6 +426,12 @@ async def create_ai_workflow_fixture( ctx_payload = dict(payload.context_json if payload.context_json is not None else payload.earth_context or {}) if payload.description.strip() and "_description" not in ctx_payload: ctx_payload["_description"] = payload.description.strip() + expect = normalize_fixture_expect( + payload.expect if payload.expect is not None else ctx_payload.get(FIXTURE_EXPECT_KEY) + ) + ctx_payload.pop(FIXTURE_EXPECT_KEY, None) + if expect: + ctx_payload[FIXTURE_EXPECT_KEY] = expect row = AIWorkflowFixture( workflow_id=workflow_id, name=payload.name.strip(), @@ -863,6 +874,7 @@ async def stream_advisor_playground_chat( error_text = "" resolved_model = str(payload.model_override or "").strip() resolved_provider = "" + verification: dict[str, Any] = {} workflow_revision = 1 is_slash_cmd = effective_message.strip().startswith( ("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate") @@ -996,6 +1008,8 @@ async def stream_advisor_playground_chat( resolved_model = str(ev_data["model"]) if ev_data.get("provider"): resolved_provider = str(ev_data["provider"]) + if isinstance(ev_data.get("verification"), dict): + verification = ev_data["verification"] elif ev_name == "error": status_value = "failed" error_text = str(ev_data.get("message") or "Workflow execution failed") @@ -1035,6 +1049,14 @@ async def stream_advisor_playground_chat( "provider": resolved_provider, "latency_ms": latency_ms, "workflow_revision": workflow_revision, + **( + { + "verification_passed": bool(verification.get("passed", True)), + "verification_warnings": list(verification.get("warnings") or [])[:6], + } + if verification + else {} + ), }, error_message=error_text[:500], started_at=started_at, diff --git a/backend/app/api/v1/compute_intelligence.py b/backend/app/api/v1/compute_intelligence.py index 1ecb0f58..b7cb4c7c 100644 --- a/backend/app/api/v1/compute_intelligence.py +++ b/backend/app/api/v1/compute_intelligence.py @@ -1,7 +1,6 @@ """Compute observations, administrator configuration and independent facility samples.""" from datetime import UTC, datetime -from typing import Literal from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression from app.api.v1.visualization import convert_compute_centers_to_geojson diff --git a/backend/app/api/v1/datasource_config.py b/backend/app/api/v1/datasource_config.py index b4846638..e2723706 100644 --- a/backend/app/api/v1/datasource_config.py +++ b/backend/app/api/v1/datasource_config.py @@ -44,7 +44,7 @@ from app.services.custom_datasource_runtime import ( ) from app.services.datasource_connectivity import ( _resolve_aisstream_api_key, - _resolve_spacetrack_credentials_with_override, + resolve_spacetrack_credentials, get_builtin_connection_status, save_connectivity_success, strip_connectivity_validation, @@ -123,7 +123,10 @@ class DataSourceConfigCreate(BaseModel): description: Optional[str] = None source_type: str = Field(..., description="rest, websocket, http, api, database") endpoint: str = Field(..., max_length=500) - auth_type: AuthType = Field(default=AuthType.NONE, description="none, bearer, api_key, basic") + auth_type: AuthType = Field( + default=AuthType.NONE, + description="none, bearer, api_key, basic, oauth_client", + ) auth_config: dict = Field(default={}) headers: dict = Field(default={}) config: dict = Field(default={"timeout": 30, "retry": 3}) @@ -162,28 +165,6 @@ def _is_builtin_config_name(name: str | None) -> bool: return bool(name and name in DEFAULT_DATASOURCES) -async def _ensure_builtin_connection_verified( - db: AsyncSession, - config_data: DataSourceConfigCreate, -) -> None: - if not _is_builtin_config_name(config_data.name): - return - - status_result = await get_builtin_connection_status( - db, - config_data.name, - config_data.endpoint, - config_data.auth_type, - config_data.headers, - config_data.config, - ) - if not status_result.get("connected"): - raise HTTPException( - status_code=400, - detail=status_result.get("message") or "请先完成连接验证,再保存内置采集器配置。", - ) - - class CustomSampleRequest(BaseModel): datasource_config_id: Optional[int] = None config: Optional[DataSourceConfigCreate] = None @@ -543,12 +524,7 @@ async def reveal_builtin_config_secrets( payload.update({"api_key": api_key, "api_key_source": api_key_source}) details.update({"api_key_configured": bool(api_key), "api_key_source": api_key_source}) elif provider == "spacetrack": - if auth_config.get("username") or auth_config.get("password"): - username = str(auth_config.get("username") or "") - password = str(auth_config.get("password") or "") - credential_source = "datasource_config" - else: - username, password, credential_source = _resolve_spacetrack_credentials_with_override() + username, password, credential_source = await resolve_spacetrack_credentials(db) payload.update( { "username": username, @@ -606,6 +582,32 @@ async def get_config( } +_SECRET_AUTH_KEYS = frozenset( + {"api_key", "client_secret", "password", "token", "access_token", "bearer_token"} +) + + +def _is_masked_secret(value: Any) -> bool: + if not isinstance(value, str): + return False + stripped = value.strip() + return bool(stripped) and set(stripped) <= {"•", "*"} + + +def _merge_auth_config(existing: dict[str, Any] | None, incoming: dict[str, Any] | None) -> dict[str, Any]: + """Merge partial `auth_config` updates while preserving omitted or masked secrets.""" + merged = dict(existing or {}) + if not isinstance(incoming, dict): + return merged + for key, raw in incoming.items(): + if key in _SECRET_AUTH_KEYS: + cleaned = str(raw or "").strip() if isinstance(raw, str) else raw + if not cleaned or _is_masked_secret(cleaned): + continue + merged[key] = raw + return merged + + @router.post("/configs") async def create_config( config_data: DataSourceConfigCreate, @@ -619,7 +621,7 @@ async def create_config( source_type=config_data.source_type, endpoint=config_data.endpoint, auth_type=config_data.auth_type, - auth_config=config_data.auth_config, + auth_config=_merge_auth_config({}, config_data.auth_config), headers=config_data.headers, config=strip_connectivity_validation(config_data.config), ) @@ -655,8 +657,8 @@ async def update_config( for field, value in update_data.items(): if field == "config": value = strip_connectivity_validation(value) - if field == "auth_config" and value == {} and (config.auth_config or {}): - continue + if field == "auth_config": + value = _merge_auth_config(config.auth_config or {}, value) setattr(config, field, value) await db.commit() diff --git a/backend/app/api/v1/settings.py b/backend/app/api/v1/settings.py index 09b57820..194cdf06 100644 --- a/backend/app/api/v1/settings.py +++ b/backend/app/api/v1/settings.py @@ -2,7 +2,7 @@ from copy import deepcopy from datetime import UTC, datetime import os from pathlib import Path -from typing import Literal, Optional +from typing import Optional from urllib.parse import urlsplit from fastapi import APIRouter, Depends, HTTPException, Query, Request, status @@ -70,7 +70,6 @@ from app.services.llm_model_catalog import ( LLMProviderCatalogConfigError, can_refresh_catalog_without_api_key, catalog_error_message, - catalog_requires_api_key, fetch_model_catalog, ) from app.services.scheduler import sync_datasource_job @@ -759,24 +758,6 @@ def _runtime_config_from_ai_payload(ai_payload: dict) -> dict: } -def _ai_provider_runtime_fingerprint(ai_payload: dict) -> dict: - runtime_config = _runtime_config_from_ai_payload(ai_payload) - llm_config = runtime_config.get("llm_config") or {} - return { - "service_url": runtime_config.get("service_url") or "", - "service_token": runtime_config.get("service_token") or "", - "timeout_seconds": int(runtime_config.get("timeout_seconds") or 0), - "retry_attempts": int(runtime_config.get("retry_attempts") or 0), - "provider": llm_config.get("provider") or "", - "provider_api": llm_config.get("provider_api") or "", - "base_url": llm_config.get("base_url") or "", - "model": llm_config.get("model") or "", - "api_key": llm_config.get("api_key") or "", - "max_tokens": int(llm_config.get("max_tokens") or 0), - "anthropic_version": llm_config.get("anthropic_version") or "", - } - - async def _validate_ai_provider_full_connection(ai_payload: dict) -> dict: runtime_config = _runtime_config_from_ai_payload(ai_payload) client = AIProviderClient( diff --git a/backend/app/core/data_sources.yaml b/backend/app/core/data_sources.yaml index 513a533c..03880cd3 100644 --- a/backend/app/core/data_sources.yaml +++ b/backend/app/core/data_sources.yaml @@ -14,10 +14,10 @@ fao: landing_point_url: "https://data.apps.fao.org/catalog/dataset/1b75ff21-92f2-4b96-9b7b-98e8aa65ad5d/resource/b6071077-d1d4-4e97-aa00-42e902847c87/download/landing-point-geo.csv" telegeography: - # TeleGeography 海缆/系统主数据源,当前使用 GitHub 镜像 JSON - cable_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/cable.json" - # TeleGeography 登陆点主数据源,当前使用 GitHub 镜像 JSON - landing_point_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/landing_point.json" + # TeleGeography 官方海缆/系统 JSON 接口 + cable_url: "https://www.submarinecablemap.com/api/v3/cable/all.json" + # TeleGeography 官方登陆点 GeoJSON 接口 + landing_point_url: "https://www.submarinecablemap.com/api/v3/landing-point/landing-point-geo.json" # TeleGeography 历史 API 存档,用于 cable collector 的 fallback archived_cable_url: "https://web.archive.org/web/2024/https://www.submarinecablemap.com/api/v3/cable" # TeleGeography 官网页面,用于 cable collector 的最终 HTML 抓取 fallback diff --git a/backend/app/core/datasource_defaults.py b/backend/app/core/datasource_defaults.py index 4d28a55e..54c4ff7d 100644 --- a/backend/app/core/datasource_defaults.py +++ b/backend/app/core/datasource_defaults.py @@ -161,7 +161,7 @@ DEFAULT_DATASOURCES = { "is_free": True, "requires_credentials": True, "credential_provider": "spacetrack", - "credential_status": "planned", + "credential_status": "supported", }, "celestrak_tle": { "id": 20, diff --git a/backend/app/core/enums.py b/backend/app/core/enums.py index a06e7509..608a3671 100644 --- a/backend/app/core/enums.py +++ b/backend/app/core/enums.py @@ -217,6 +217,7 @@ class AuthType(StrEnum): BEARER = "bearer" API_KEY = "api_key" BASIC = "basic" + OAUTH_CLIENT = "oauth_client" class TVSourceType(StrEnum): diff --git a/backend/app/models/ai_workflow.py b/backend/app/models/ai_workflow.py index df9790fd..3e58ac3e 100644 --- a/backend/app/models/ai_workflow.py +++ b/backend/app/models/ai_workflow.py @@ -52,6 +52,9 @@ class AIWorkflow(Base): "published_graph": self.published_graph or {}, "draft_graph": self.draft_graph, "bindings": self.bindings or {}, + "draft_bindings": ( + self.draft_graph.get("bindings") if isinstance(self.draft_graph, dict) else None + ), "updated_by": self.updated_by, "created_at": to_iso8601_utc(self.created_at), "updated_at": to_iso8601_utc(self.updated_at), diff --git a/backend/app/services/ai/dag_executor.py b/backend/app/services/ai/dag_executor.py index 23bd3a01..0cb496c5 100644 --- a/backend/app/services/ai/dag_executor.py +++ b/backend/app/services/ai/dag_executor.py @@ -10,6 +10,12 @@ from typing import Any, AsyncIterator from app.core.logging import get_logger from app.schemas.ai import ChatMessage, ImageAttachment, SituationalAnalysisRequest +from app.services.ai.scene_directives import ( + INFLUENCE_ZONE_GUIDANCE, + consume_text_holding_scene_tag, + extract_planet_scene_from_text, + merge_scene_specs, +) from app.services.ai.thinking_sanitizer import strip_thinking_text from app.services.ai.tool_registry import ( TimeBasis, @@ -23,7 +29,7 @@ from app.services.ai.tool_registry import ( query_vessel_posture_tool, safe_web_fetch, ) -from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES +from app.services.ai.workflow_registry import MAX_WORKFLOW_NODES, _extract_first_json_object from app.services.compute_center_locations import build_compute_center_location_query from app.services.location.agent_resolver import run_l1_structured_facility_resolvers @@ -101,24 +107,44 @@ def render_workflow_template( return _TEMPLATE_VAR_RE.sub(lambda m: _lookup(m.group(1)), raw) -def _extract_target_ids_and_codes( +def _target_entity_type(target: dict[str, Any]) -> str: + return str(target.get("entity_type") or target.get("type") or "").strip().lower() + + +def _target_id_for_types( targets: list[dict[str, Any]], - earth_context: dict[str, Any], -) -> tuple[str | None, list[str], str]: - first = targets[0] if targets else {} - primary_id = str( - first.get("entity_id") - or first.get("id") - or earth_context.get("entity_id") - or "" - ).strip() or None + entity_types: frozenset[str], +) -> str | None: + """Return the ID of the first selected target whose type matches `entity_types`. + + Each data source must query its own object: a multi-select of cable + vessel + BGP + must never leak the cable ID into the vessel or BGP lookup, regardless of click order. + """ + for target in targets: + if _target_entity_type(target) in entity_types: + raw = str(target.get("entity_id") or target.get("id") or "").strip() + if raw: + return raw + return None + + +def _extract_codes_and_mode(earth_context: dict[str, Any]) -> tuple[list[str], str]: codes = earth_context.get("selected_codes") if not isinstance(codes, list) or not codes: codes = ["CN", "US"] else: codes = [str(c).strip().upper() for c in codes if str(c).strip()][:12] or ["CN", "US"] mode = str(earth_context.get("mode") or "global_share") - return primary_id, codes, mode + return codes, mode + + +_BGP_ENTITY_TYPES = frozenset({"bgp"}) +_CABLE_ENTITY_TYPES = frozenset({"cable", "landing_point"}) +_SATELLITE_ENTITY_TYPES = frozenset({"satellite"}) +_VESSEL_ENTITY_TYPES = frozenset({"vessel"}) +_COMPUTE_FACILITY_TYPES = frozenset( + {"supercomputer", "gpu_cluster", "data_center", "cloud_center", "edge_node", "compute_center_unresolved"} +) async def _execute_tool( @@ -131,7 +157,7 @@ async def _execute_tool( allow_external_tools: bool, ) -> dict[str, Any]: """Execute one whitelisted read-only or controlled external tool cleanly.""" - primary_id, codes, mode = _extract_target_ids_and_codes(targets, earth_context) + codes, mode = _extract_codes_and_mode(earth_context) time_basis: TimeBasis = str(earth_context.get("time_basis") or "retrospective") # type: ignore[assignment] if time_basis not in {"live", "as_known_then", "retrospective"}: time_basis = "retrospective" @@ -158,7 +184,7 @@ async def _execute_tool( if tool_id == "query_bgp_incidents": incidents = await query_bgp_incidents_tool( db, - incident_key=primary_id if any(t.get("entity_type") == "bgp" for t in targets) else None, + incident_key=_target_id_for_types(targets, _BGP_ENTITY_TYPES), limit=8, time_basis=time_basis, cutoff_at=cutoff_at, @@ -169,32 +195,32 @@ async def _execute_tool( db, time_basis=time_basis, cutoff_at=cutoff_at, - entity_id=primary_id if any(t.get("entity_type") in {"cable", "landing_point"} for t in targets) else None, + entity_id=_target_id_for_types(targets, _CABLE_ENTITY_TYPES), ) if tool_id == "query_satellite_posture": return await query_satellite_posture_tool( db, time_basis=time_basis, cutoff_at=cutoff_at, - entity_id=primary_id if any(t.get("entity_type") == "satellite" for t in targets) else None, + entity_id=_target_id_for_types(targets, _SATELLITE_ENTITY_TYPES), ) if tool_id == "query_vessel_posture": return await query_vessel_posture_tool( db, time_basis=time_basis, cutoff_at=cutoff_at, - entity_id=primary_id if any(t.get("entity_type") == "vessel" for t in targets) else None, + entity_id=_target_id_for_types(targets, _VESSEL_ENTITY_TYPES), ) if tool_id == "query_recent_earth_news": news_ctx = earth_context.get("news_context") if isinstance(earth_context.get("news_context"), dict) else {} region = str(news_ctx.get("region_key") or "").strip() or None return await query_recent_earth_news_tool(db, region=region, limit=10) if tool_id in _L1_KNOWLEDGE_TOOL_IDS: - target_name = str( - (targets[0].get("label") if targets else "") - or question - or "Unknown Facility" - ).strip() + facility = next( + (t for t in targets if _target_entity_type(t) in _COMPUTE_FACILITY_TYPES), + targets[0] if targets else {}, + ) + target_name = str(facility.get("label") or question or "Unknown Facility").strip() query = build_compute_center_location_query(name=target_name) candidates, resolver_log, _ = await run_l1_structured_facility_resolvers(query, db=db) return { @@ -320,13 +346,21 @@ def _has_downstream_llm( return False +TRIGGER_SOURCES = frozenset({"interactive", "ingest"}) + + def _eval_edge_condition( edge: dict[str, Any], pred_state: dict[str, Any], targets: list[dict[str, Any]], + trigger_source: str = "interactive", ) -> bool: cond = str(edge.get("condition") or "always").strip() - if cond in {"always", "", "interactive", "ingest", "not_terminal", "high_confidence_hit", "fallback_to_agent"}: + if cond in TRIGGER_SOURCES: + # Background RSS ingest and user-clicked analysis share one graph; only the branch + # matching the actual trigger may run (avoids a second model call and leaked JSON). + return cond == trigger_source + if cond in {"always", "", "not_terminal", "high_confidence_hit", "fallback_to_agent"}: return True if cond == "on_empty_or_low_confidence": return bool(pred_state.get("is_empty")) or float(pred_state.get("confidence", 1.0)) < 0.6 @@ -364,6 +398,145 @@ def _build_deterministic_fallback_markdown( return "\n".join(lines).strip() +# Prompt keys whose LLM contract is a strict JSON object (rendered as cards, never streamed raw). +COMPUTE_BRIEF_PROMPT_KEY = "compute.posture.brief" +_STRUCTURED_JSON_PROMPT_KEYS = frozenset({COMPUTE_BRIEF_PROMPT_KEY}) +_COMPUTE_BRIEF_SCHEMA_HINT = ( + "严格输出单个紧凑 JSON 对象(不加围栏外文字),字段结构:\n" + '{"headline": str, "headline_en": str, "executive_assertion": str, "executive_assertion_en": str, ' + '"causes": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], ' + '"breakthrough_levers": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], ' + '"blind_spots": [str], "evidence_ids": [str]};所有 evidence_ids 必须来自 context.evidence。' +) +_EVIDENCE_GAP_SUGGESTIONS = ( + "补充一手信源(运营商公告、BGP 采集器原始记录、官方通报)后复核成因", + "核对事件时间窗与受影响前缀 / 资产是否与所选对象一致", +) + + +def _node_wants_structured_json(node: dict[str, Any]) -> bool: + params = node.get("params") if isinstance(node.get("params"), dict) else {} + return ( + str(node.get("prompt_key") or "") in _STRUCTURED_JSON_PROMPT_KEYS + or str(params.get("output_format") or "").strip().lower() == "json" + ) + + +def _compute_series_from_tools(tool_results: dict[str, Any]) -> dict[str, Any] | None: + series = tool_results.get("query_compute_posture") + if not isinstance(series, dict) or series.get("error"): + return None + if not series.get("compute") and not series.get("years"): + return None + return series + + +def _resolve_compute_brief( + parsed: dict[str, Any] | None, + series: dict[str, Any], +) -> tuple[Any, bool]: + """Validate an LLM compute brief against verified evidence; fall back to the deterministic baseline.""" + from app.services.ai.posture_agent import ( + StrategicPostureBrief, + build_deterministic_posture_brief, + verify_brief_citations, + ) + + if isinstance(parsed, dict): + try: + brief = StrategicPostureBrief.model_validate(parsed) + return verify_brief_citations(brief, series.get("evidence") or {}), True + except Exception as exc: + logger.warning_event( + "Compute brief failed schema or citation verification; using deterministic baseline", + event="ai_dag.compute_brief.fallback", + context={"error": str(exc)[:300]}, + ) + return build_deterministic_posture_brief(series), False + + +def _render_structured_markdown(parsed: dict[str, Any]) -> str: + """Render a structured JSON analysis (e.g. StrategicPostureBrief) as readable Markdown.""" + lines: list[str] = [] + headline = str(parsed.get("headline") or parsed.get("title") or "").strip() + if headline: + lines.append(f"### {headline}") + assertion = str( + parsed.get("executive_assertion") or parsed.get("summary") or parsed.get("answer_markdown") or "" + ).strip() + if assertion: + lines.extend(["", assertion]) + for key, label in ( + ("key_judgments", "核心判断"), + ("causes", "成因归因"), + ("breakthrough_levers", "突破杠杆"), + ): + items = parsed.get(key) + if not isinstance(items, list) or not items: + continue + lines.extend(["", f"**{label}**"]) + for item in items[:6]: + if isinstance(item, dict): + item_label = str(item.get("label") or item.get("title") or "").strip() + detail = str(item.get("detail") or item.get("text") or "").strip() + if item_label and detail: + lines.append(f"- **{item_label}**:{detail}") + elif item_label or detail: + lines.append(f"- {item_label or detail}") + elif str(item).strip(): + lines.append(f"- {str(item).strip()}") + blind_spots = [str(b).strip() for b in (parsed.get("blind_spots") or []) if str(b).strip()] + if blind_spots: + lines.extend(["", "**待核实盲区**", *[f"- {b}" for b in blind_spots[:4]]]) + return "\n".join(lines).strip() + + +def _compile_compute_workbench( + series: dict[str, Any], + brief: Any, + earth_context: dict[str, Any], +) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: + """Compile the existing compute `ViewSpec` workbench (trend + matrix) from verified series.""" + from app.services.ai.workflow_runtime import compile_compute_view_spec + + codes, mode = _extract_codes_and_mode(earth_context) + try: + view, scene = compile_compute_view_spec( + codes=codes, + mode=mode, + series=series, + posture={"payload": brief.model_dump(mode="json")}, + ) + except Exception as exc: + logger.warning_event( + "Compute workbench compilation failed", + event="ai_dag.compute_view_spec.failed", + context={"error": str(exc)[:300]}, + ) + return None, None + return view.model_dump(mode="json"), scene.model_dump(mode="json") + + +def _build_evidence_gap_markdown(tool_results: dict[str, Any], warnings: list[str]) -> str: + """User-facing block delivered when an evidence guardrail fails: cause pending + follow-ups.""" + pending: list[str] = [] + for tid, res in tool_results.items(): + if not isinstance(res, dict): + continue + if res.get("error") or res.get("skipped") or not _has_meaningful_tool_data({tid: res}): + pending.append(f"`{tid}` 未返回可溯源数据,需人工补查") + pending.extend(_EVIDENCE_GAP_SUGGESTIONS) + reason = ";".join(warnings) or "缺少结构化证据" + lines = [ + "", + "", + f"> **证据校验未通过({reason})**:以上成因判断一律视为「原因待核实」,不作为定论。", + "> **待查项**:", + *[f"> - {item}" for item in pending[:6]], + ] + return "\n".join(lines) + + async def run_workflow_dag_stream( *, db: Any, @@ -381,12 +554,19 @@ async def run_workflow_dag_stream( model_override: str | None = None, allow_external_tools: bool = False, extra_meta: dict[str, Any] | None = None, + trigger_source: str = "interactive", + cancel_event: asyncio.Event | None = None, ) -> AsyncIterator[dict[str, Any]]: """Execute a workflow DAG topologically and emit structured SSE-ready events.""" + if trigger_source not in TRIGGER_SOURCES: + trigger_source = "interactive" wf_id = str(workflow.get("workflow_id") or "default.general") wf_name = str(workflow.get("name") or wf_id) active_rev = int(workflow.get("active_revision") or 1) bindings = workflow.get("bindings") if isinstance(workflow.get("bindings"), dict) else {} + draft_graph = workflow.get("draft_graph") + if use_draft and isinstance(draft_graph, dict) and isinstance(draft_graph.get("bindings"), dict): + bindings = draft_graph["bindings"] graph = ( workflow.get("draft_graph") if use_draft and isinstance(workflow.get("draft_graph"), dict) @@ -438,9 +618,17 @@ async def run_workflow_dag_stream( resolved_provider: str | None = None resolved_model: str | None = None scene_spec: dict[str, Any] | None = None + parsed_dag_scene: dict[str, Any] | None = None + view_spec: dict[str, Any] | None = None + compute_brief: Any = None + compute_brief_llm_verified = False + guardrail_ran = False + guardrail_warnings: list[str] = [] last_llm_output: str = "" for node in ordered_nodes: + if cancel_event is not None and cancel_event.is_set(): + return nid = str(node["id"]) ntype = str(node.get("node_type") or "llm_agent") ntitle = str(node.get("title") or nid) @@ -453,7 +641,7 @@ async def run_workflow_dag_stream( pred_state = node_states.get(pred_id) if not pred_state or pred_state.get("skipped"): continue - if _eval_edge_condition(edge, pred_state, clean_targets): + if _eval_edge_condition(edge, pred_state, clean_targets, trigger_source): passed = True break if not passed: @@ -560,7 +748,23 @@ async def run_workflow_dag_stream( f"{node_prompt}\n\n用户请求:{effective_question or question}" if node_prompt else (effective_question or question) - ).strip() + ) + structured = _node_wants_structured_json(node) + is_compute_brief = str(node.get("prompt_key") or "") == COMPUTE_BRIEF_PROMPT_KEY + if is_compute_brief: + objective = f"{objective}\n\n{_COMPUTE_BRIEF_SCHEMA_HINT}" + wants_scene_zones = ( + not has_next_llm + and not structured + and (wf_id.startswith("earth.") or bool(clean_earth_ctx) or bool(clean_targets)) + ) + if wants_scene_zones: + sys_prompt = f"{sys_prompt}\n\n{INFLUENCE_ZONE_GUIDANCE}".strip() + objective = ( + f"{objective}\n\n" + "【空间联动提醒】若本回答涉及任何明确国家、地区、海域走廊或地理影响范围,请务必按系统指令在正文最末尾另起一行附带 ...。" + ) + objective = objective.strip() # Execute any extra read-only tools configured directly on the LLM node before inference. node_tool_results: dict[str, Any] = {} @@ -592,6 +796,8 @@ async def run_workflow_dag_stream( } if clean_earth_ctx: ctx_payload["earth_context"] = clean_earth_ctx + if wants_scene_zones: + ctx_payload["scene_overlay_guidance"] = INFLUENCE_ZONE_GUIDANCE if attachments: ctx_payload["attachments"] = attachments[:8] @@ -626,14 +832,23 @@ async def run_workflow_dag_stream( images=parsed_images, ) + compute_series = _compute_series_from_tools(tool_results) if is_compute_brief else None + if not ai_ready or ai_client is None: - fallback_md = _build_deterministic_fallback_markdown( - workflow_name=wf_name, - question=effective_question or question, - targets=clean_targets, - tool_results=tool_results, - ai_configured=False, - ) + if compute_series is not None and not has_next_llm: + compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, compute_series) + fallback_md = ( + _render_structured_markdown(compute_brief.model_dump(mode="json")) + + "\n\n> 当前未配置可用 AI Provider,以上为基于已核验算力台账的确定性研判。" + ) + else: + fallback_md = _build_deterministic_fallback_markdown( + workflow_name=wf_name, + question=effective_question or question, + targets=clean_targets, + tool_results=tool_results, + ai_configured=False, + ) node_outputs[nid] = fallback_md node_states[nid] = {"skipped": False, "confidence": 0.65, "is_empty": False} executed_trace.append(nid) @@ -647,8 +862,13 @@ async def run_workflow_dag_stream( continue timeout_sec = max(5, min(int(node.get("timeout_seconds") or 60), 300)) - if has_next_llm: + if cancel_event is not None and cancel_event.is_set(): + return + if has_next_llm or structured: + # Intermediate nodes and strict-JSON nodes run non-streaming so raw JSON never reaches the user. resp = await asyncio.wait_for(ai_client.analyze(req), timeout=timeout_sec) + if cancel_event is not None and cancel_event.is_set(): + return clean_text, inline_thoughts = strip_thinking_text(str(getattr(resp, "content", "") or "")) node_outputs[nid] = clean_text or str(getattr(resp, "content", "") or "") if node_outputs[nid]: @@ -660,6 +880,22 @@ async def run_workflow_dag_stream( final_reasoning_md = final_reasoning_md.strip() generation_mode = "llm_verified" zero_token = False + if structured and not has_next_llm: + parsed = _extract_first_json_object(node_outputs[nid]) + narrative = "" + if compute_series is not None: + compute_brief, compute_brief_llm_verified = _resolve_compute_brief(parsed, compute_series) + narrative = _render_structured_markdown(compute_brief.model_dump(mode="json")) + if not compute_brief_llm_verified: + narrative += "\n\n> 模型结论未通过结构或证据 ID 核验,已改用已核验台账的确定性研判。" + elif parsed: + narrative = _render_structured_markdown(parsed) + narrative = narrative.strip() or node_outputs[nid].strip() + node_outputs[nid] = narrative + last_llm_output = narrative + final_answer_md = narrative + if narrative: + yield {"event": "text", "data": {"delta": narrative}} node_states[nid] = { "skipped": False, "confidence": 0.85 if node_outputs[nid] else 0.4, @@ -673,10 +909,13 @@ async def run_workflow_dag_stream( else: text_parts: list[str] = [] reasoning_parts: list[str] = [] + pending_scene_tail = "" resolved_provider = provider_name or None resolved_model = preferred_model or default_model or None async for ev in ai_client.stream_analyze(req, request_id=run_id): - if request is not None and await request.is_disconnected(): + if (cancel_event is not None and cancel_event.is_set()) or ( + request is not None and await request.is_disconnected() + ): return ev_type = str(ev.get("event") or "") if ev_type == "start": @@ -691,7 +930,10 @@ async def run_workflow_dag_stream( elif ev_type == "text" and ev.get("delta"): delta = str(ev["delta"]) text_parts.append(delta) - yield {"event": "text", "data": {"delta": delta}} + combined_buf = pending_scene_tail + delta + emit_chunk, pending_scene_tail = consume_text_holding_scene_tag(combined_buf) + if emit_chunk: + yield {"event": "text", "data": {"delta": emit_chunk}} elif ev_type == "done": if isinstance(ev.get("provider"), str) and ev["provider"]: resolved_provider = ev["provider"] @@ -701,9 +943,29 @@ async def run_workflow_dag_stream( err_msg = str(ev.get("message") or ev.get("detail") or "AI stream error") raise RuntimeError(err_msg) + if pending_scene_tail: + cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail) + if cleaned_tail: + yield {"event": "text", "data": {"delta": cleaned_tail}} + if cancel_event is not None and cancel_event.is_set(): + return + raw_text = "".join(text_parts) clean_text, inline_thoughts = strip_thinking_text(raw_text) - final_answer_md = (clean_text or raw_text).strip() + stripped_answer, node_parsed_scene = extract_planet_scene_from_text(clean_text or raw_text) + if node_parsed_scene: + parsed_dag_scene = node_parsed_scene + logger.info_event( + "DAG LLM node emitted scene directives", + event="ai_dag.scene.extracted", + context={ + "workflow_id": wf_id, + "run_id": run_id, + "node_id": nid, + "zones_count": len(node_parsed_scene.get("influence_zones") or []), + }, + ) + final_answer_md = stripped_answer.strip() if inline_thoughts: reasoning_parts.extend(inline_thoughts) if reasoning_parts: @@ -746,6 +1008,14 @@ async def run_workflow_dag_stream( extra_block = f"\n\n> {disclaimer}" final_answer_md += extra_block yield {"event": "text", "data": {"delta": extra_block}} + guardrail_ran = True + if not passed: + guardrail_warnings.extend(w for w in warnings if w not in guardrail_warnings) + if gr.get("require_evidence") and not evidence: + # Evidence-required analyses must not present unverified causes as conclusions. + gap_block = _build_evidence_gap_markdown(tool_results, warnings) + final_answer_md += gap_block + yield {"event": "text", "data": {"delta": gap_block}} node_states[nid] = { "skipped": False, "confidence": 0.95 if passed else 0.45, @@ -785,6 +1055,14 @@ async def run_workflow_dag_stream( if t.get("entity_id") or t.get("id") ], } + wants_compute_view = compute_brief is not None or str(params.get("view_spec") or "") == "compute" + series_for_view = _compute_series_from_tools(tool_results) if wants_compute_view else None + if series_for_view is not None: + if compute_brief is None: + compute_brief, compute_brief_llm_verified = _resolve_compute_brief(None, series_for_view) + view_spec, compute_scene = _compile_compute_workbench(series_for_view, compute_brief, clean_earth_ctx) + if scene_spec is None and compute_scene is not None: + scene_spec = compute_scene node_states[nid] = {"skipped": False, "confidence": 1.0, "is_empty": False} executed_trace.append(nid) yield { @@ -802,13 +1080,33 @@ async def run_workflow_dag_stream( ) yield {"event": "text", "data": {"delta": final_answer_md}} + if parsed_dag_scene: + dag_domain = str((clean_earth_ctx or {}).get("domain") or "global") + scene_spec = merge_scene_specs(scene_spec, parsed_dag_scene, domain=dag_domain) + + if view_spec is not None: + # Late `meta` patch: the Earth copilot already applies `view_spec` from meta events to render + # trend/matrix workbench cards; the DAG only knows the spec after the series + brief nodes ran. + yield { + "event": "meta", + "data": {"run_id": run_id, "domain": "compute", "view_spec": view_spec, "scene_spec": scene_spec}, + } + + if isinstance(scene_spec, dict) and (scene_spec.get("influence_zones") or parsed_dag_scene): + yield {"event": "scene", "data": {"scene_spec": scene_spec}} + + verification = { + "guardrail_ran": guardrail_ran, + "passed": not guardrail_warnings, + "warnings": guardrail_warnings, + } yield { "event": "done", "data": { "run_id": run_id, "workflow_id": wf_id, "workflow_name": wf_name, - "status": "completed", + "status": "completed" if not guardrail_warnings else "unverified", "generation_mode": generation_mode, "zero_token": zero_token, "provider": resolved_provider, @@ -816,6 +1114,8 @@ async def run_workflow_dag_stream( "nodes": executed_trace, "evidence": evidence, "scene_spec": scene_spec, + "view_spec": view_spec, + "verification": verification, "answer_markdown": final_answer_md, "reasoning_markdown": final_reasoning_md, "text_length": len(final_answer_md), diff --git a/backend/app/services/ai/scene_directives.py b/backend/app/services/ai/scene_directives.py new file mode 100644 index 00000000..5b6e87ed --- /dev/null +++ b/backend/app/services/ai/scene_directives.py @@ -0,0 +1,150 @@ +"""Shared `` prompt guidance and streaming extraction for Earth Influence Zones.""" + +from __future__ import annotations + +import json +import re +from typing import Any + +from app.core.logging import get_logger +from app.services.ai.workflow_runtime import validate_influence_zones + +logger = get_logger(__name__, service="ai_scene") + +PLANET_SCENE_TAG_OPEN = "" +PLANET_SCENE_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL | re.IGNORECASE) +PLANET_SCENE_OPEN_RE = re.compile(r"<\s*planet_scene\b", re.IGNORECASE) +_CODE_FENCE_OPEN_RE = re.compile(r"^\s*```[a-zA-Z0-9_-]*\s*\n?") +_CODE_FENCE_CLOSE_RE = re.compile(r"\n?\s*```\s*$") +_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])") + +INFLUENCE_ZONE_GUIDANCE = ( + "【地球影响范围联动指令】正文仍用自然 Markdown 输出(绝不在正文解释本标签);" + "只要分析涉及明确地理国家、地区、消费/市场辐射域、基础设施影响区、海域/海峡走廊、峰会/组织或用户询问“影响范围/影响地区/覆盖区域”," + "就必须在回答**最末尾另起一行**附带一个纯 JSON(禁用 markdown 代码围栏)的系统隐藏标签:\n" + "{...}\n" + "分层输出规范(严格遵循):\n" + "- 第一层(必需,直接当事国/核心对象):shape.mode=\"countries\",color=\"#ef4444\",opacity=0.54,edge.style=\"sharp\";必须填全所有直接核心国家且严格使用标准 ISO-3 代码(如朝鲜必须写 \"PRK\",禁用 \"DPRK\";中国 \"CHN\"、韩国 \"KOR\"、日本 \"JPN\"、俄罗斯 \"RUS\"、英国 \"GBR\")。\n" + "- 第二层(若事件存在跨国/区域外溢则必填;纯单一国内消费/内部新闻则不填第二、三层):次级邻近/区域辐射,shape.mode=\"countries\" 或已支持的 \"region_preset\",color=\"#f59e0b\",opacity=0.32,edge.style=\"soft\"。\n" + "- 第三层(仅当明确涉及海峡、海域航道或边境辐射带时可选):shape.mode=\"circle\"(center:[lat,lon], radius_km),color=\"#38bdf8\",opacity=0.28,edge.style=\"soft\"。\n" + "完整单国示例:\n" + "{\"influence_zones\":[{\"id\":\"chn-core\",\"label\":\"直接影响:中国\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\"]}}],\"camera_hint\":{\"lat\":35.0,\"lon\":104.0}}\n" + "双国核心+区域外溢+海域辐射示例:\n" + "{\"influence_zones\":[{\"id\":\"core\",\"label\":\"核心国家\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\",\"PRK\"]}},{\"id\":\"spill\",\"label\":\"东北亚周边外溢\",\"color\":\"#f59e0b\",\"opacity\":0.32,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"fade\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"KOR\",\"JPN\",\"RUS\"]}},{\"id\":\"sea\",\"label\":\"黄海—朝鲜海峡航道辐射\",\"color\":\"#38bdf8\",\"opacity\":0.28,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"radial\"},\"shape\":{\"mode\":\"circle\",\"center\":[36.5,124.5],\"radius_km\":850}}],\"camera_hint\":{\"lat\":38.0,\"lon\":122.0}}\n" + "可选 region_preset 枚举(仅限此列表,勿自造名称):" + "APEC, ASIA_PACIFIC, NORTHEAST_ASIA, EAST_ASIA, KOREAN_PENINSULA, SOUTHEAST_ASIA, SOUTH_ASIA, CENTRAL_ASIA, ASEAN, INDO_PACIFIC, " + "EU, EUROPE, EASTERN_EUROPE, NORTHERN_EUROPE, WESTERN_EUROPE, G7, BRICS, NATO, MIDDLE_EAST, MENA, AMERICAS, NORTH_AMERICA, SOUTH_AMERICA, AFRICA;" + "animation.type 选 \"sweep\"、\"radial\" 或 \"fade\"。" +) + + +def sanitize_camera_hint(raw: Any) -> dict[str, float] | None: + if not isinstance(raw, dict): + return None + cleaned: dict[str, float] = {} + for key in ("lat", "lon", "altitude", "zoom"): + val = raw.get(key) + if isinstance(val, (int, float)) and not isinstance(val, bool): + cleaned[key] = float(val) + return cleaned if ("lat" in cleaned and "lon" in cleaned) else None + + +def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None: + """Parse JSON inside `` even if wrapped in code fences or containing trailing commas.""" + text = str(raw_json or "").strip() + if not text: + return None + text = _CODE_FENCE_OPEN_RE.sub("", text) + text = _CODE_FENCE_CLOSE_RE.sub("", text).strip() + candidates = [text] + first_brace = text.find("{") + last_brace = text.rfind("}") + if first_brace != -1 and last_brace > first_brace: + sliced = text[first_brace : last_brace + 1] + if sliced != text: + candidates.append(sliced) + for cand in candidates: + for attempt in (cand, _TRAILING_COMMA_RE.sub(r"\1", cand)): + try: + parsed = json.loads(attempt) + except Exception: + continue + if isinstance(parsed, dict): + return parsed + return None + + +def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]: + """Strip `...` blocks and return validated scene spec fields.""" + if not text: + return "", None + parsed_scene: dict[str, Any] | None = None + matches = PLANET_SCENE_RE.findall(text) + for raw_json in matches: + payload = _parse_scene_json_candidate(raw_json) + if payload is None: + continue + zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))] + camera_hint = sanitize_camera_hint(payload.get("camera_hint")) + if zones or camera_hint: + parsed_scene = {} + if zones: + parsed_scene["influence_zones"] = zones + if camera_hint: + parsed_scene["camera_hint"] = camera_hint + + if matches and parsed_scene is not None: + extracted_zones = parsed_scene.get("influence_zones") or [] + logger.info_event( + "Extracted planet scene directives", + event="ai_scene.directive.extracted", + context={ + "zones_count": len(extracted_zones), + "zone_ids": [z.get("id") for z in extracted_zones if isinstance(z, dict)], + "has_camera_hint": "camera_hint" in parsed_scene, + }, + ) + elif matches: + logger.warning_event( + "Planet scene directive ignored after parse/validation failure", + event="ai_scene.directive.dropped", + context={"snippet": str(matches[-1])[:300]}, + ) + + cleaned = PLANET_SCENE_RE.sub("", text) + open_match = PLANET_SCENE_OPEN_RE.search(cleaned) + if open_match: + cleaned = cleaned[: open_match.start()] + return cleaned.rstrip(), parsed_scene + + +def consume_text_holding_scene_tag(buffer: str, *, flush_all: bool = False) -> tuple[str, str]: + """Yield visible text before ` dict[str, Any] | None: + if not parsed_scene and not isinstance(base_scene, dict): + return None + merged: dict[str, Any] = dict(base_scene) if isinstance(base_scene, dict) else {} + if parsed_scene: + merged.update(parsed_scene) + if domain and not merged.get("domain"): + merged["domain"] = domain + return merged diff --git a/backend/app/services/ai/stream_turn.py b/backend/app/services/ai/stream_turn.py index d262ecce..bbaadab2 100644 --- a/backend/app/services/ai/stream_turn.py +++ b/backend/app/services/ai/stream_turn.py @@ -32,9 +32,20 @@ from app.services.ai.tool_registry import ( query_global_situational_tool, query_recent_earth_news_tool, ) +from app.services.ai.scene_directives import ( + INFLUENCE_ZONE_GUIDANCE as _INFLUENCE_ZONE_GUIDANCE, + consume_text_holding_scene_tag as _consume_text_holding_scene_tag, + extract_planet_scene_from_text, +) from app.services.ai.workflow_evolver import schedule_post_run_evolution from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows -from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn +from app.services.ai.workflow_runtime import ( + ActiveRunHandle, + classify_turn_intent, + execute_session_turn, + register_active_run_handle, + unregister_active_run_handle, +) from app.services.ai_client import AIProviderClient logger = get_logger(__name__, service="ai_stream") @@ -186,6 +197,7 @@ def _build_news_analysis_request( context["user_memory_notes"] = memory_notes if pinned_summaries: context["pinned_comparisons"] = pinned_summaries + context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE return SituationalAnalysisRequest( title="Planet 全球新闻与国际局势研判", objective=( @@ -194,16 +206,17 @@ def _build_news_analysis_request( "1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n" "2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n" "3. **后续重点观察信号与不确定边界**。\n" - "请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。" + "正文直接输出面向用户的 Markdown,不要把正文包在 JSON 里;若存在任何明确的地理国家、地区或海域影响范围,请在正文最末尾附带系统指令要求的 ...。" ), system_prompt=( "你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。" "如有前序对话与用户备忘录,请保持指代与口径延续。" - "请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。" + "请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。\n\n" + f"{_INFLUENCE_ZONE_GUIDANCE}" ), context=context, constraints=[ - "Output clean user-facing Markdown directly (not JSON).", + "Output clean user-facing Markdown directly (except the optional trailing ... tag when geographic impact zones apply).", "Distinguish reported facts from analytical outlook.", ], thinking=thinking_cfg, @@ -239,20 +252,23 @@ def _build_telemetry_stream_request( context["user_memory_notes"] = memory_notes if pinned_summaries: context["pinned_comparisons"] = pinned_summaries + context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE return SituationalAnalysisRequest( title=f"Planet 态势参谋分析({domain})", objective=( f"用户问题:{question}\n\n" "请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条," - "使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。" + "使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要把正文包在 JSON 对象里;" + "若涉及明确国家、地区或海域范围,请在正文最末尾附带系统指令要求的 ...。" ), system_prompt=( "你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;" - "所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。" + "所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。\n\n" + f"{_INFLUENCE_ZONE_GUIDANCE}" ), context=context, constraints=[ - "Output clean Markdown directly (not JSON).", + "Output clean Markdown directly (except the optional trailing ... tag when geographic impact zones apply).", "Do not invent telemetry counts or unverified outages outside context.", ], thinking=thinking_cfg, @@ -365,6 +381,18 @@ async def stream_session_turn( wf_model = str(model_name or "") wf_provider = str(provider_name or "") wf_revision = int(wf_dict.get("active_revision") or 1) + wf_scene_zones_count = 0 + run_handle = register_active_run_handle( + ActiveRunHandle( + run_id=run_id, + session_id=session_id_val if session is not None else None, + actor_key=getattr(access, "actor_key", "anonymous"), + workflow_id=workflow_id, + access_tier=getattr(access, "access_tier", "public_zero_cost"), + question=question[:500], + started_at=wf_started_at, + ) + ) try: wf_earth_ctx: dict[str, Any] = { **merged_ctx, @@ -398,6 +426,7 @@ async def stream_session_turn( request=request, run_id=run_id, allow_external_tools=allow_external, + cancel_event=run_handle.cancel_event, extra_meta={ "session_id": session_id_val, "domain": domain, @@ -411,26 +440,42 @@ async def stream_session_turn( **({"session_token": issued_session_token} if issued_session_token else {}), }, ): + if run_handle.cancel_event.is_set() or ( + request is not None and await request.is_disconnected() + ): + wf_status = "cancelled" + break ev_name = str(item.get("event") or "") ev_data = dict(item.get("data") or {}) if ev_name == "node" and ev_data.get("status") == "completed": nid = str(ev_data.get("node_id") or "") if nid and nid not in wf_trace: wf_trace.append(nid) + elif ev_name == "scene": + s_spec = ev_data.get("scene_spec") + if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list): + wf_scene_zones_count = len(s_spec["influence_zones"]) elif ev_name == "done": + if run_handle.cancel_event.is_set(): + wf_status = "cancelled" + break if isinstance(ev_data.get("nodes"), list): wf_trace = [str(n) for n in ev_data["nodes"] if n] if ev_data.get("model"): wf_model = str(ev_data["model"]) if ev_data.get("provider"): wf_provider = str(ev_data["provider"]) + s_spec = ev_data.get("scene_spec") + if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list): + wf_scene_zones_count = len(s_spec["influence_zones"]) wf_answer = str(ev_data.get("answer_markdown") or "") ev_data.setdefault("usage", {}) ev_data["compacted"] = compacted_flag ev_data["conversation_summary"] = compacted_summary ev_data["memory_used"] = memory_used_flag if session is not None and isinstance(session.context_state, dict): - updated_recent = [*recent_history, {"role": "user", "content": question}] + base_recent = list(session.context_state.get("recent_messages") or recent_history) + updated_recent = [*base_recent, {"role": "user", "content": question}] if wf_answer: updated_recent.append({"role": "assistant", "content": wf_answer[:1800]}) session.context_state = { @@ -442,6 +487,8 @@ async def stream_session_turn( wf_status = "failed" wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error") yield _format_sse(ev_name, ev_data) + if run_handle.cancel_event.is_set(): + wf_status = "cancelled" except asyncio.CancelledError: wf_status = "cancelled" raise @@ -455,6 +502,7 @@ async def stream_session_turn( ) yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)}) finally: + unregister_active_run_handle(run_id) try: wf_completed_at = datetime.now(UTC) wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000)) @@ -479,6 +527,7 @@ async def stream_session_turn( "provider": wf_provider, "latency_ms": wf_latency_ms, "workflow_revision": wf_revision, + "scene_zones_count": wf_scene_zones_count, }, error_message=wf_error[:500], started_at=wf_started_at, @@ -590,7 +639,8 @@ async def stream_session_turn( def _persist_session_memory(answer_text: str) -> None: if session is None or not isinstance(session.context_state, dict): return - updated_recent = [*recent_history, {"role": "user", "content": question}] + base_recent = list(session.context_state.get("recent_messages") or recent_history) + updated_recent = [*base_recent, {"role": "user", "content": question}] if answer_text: updated_recent.append({"role": "assistant", "content": answer_text[:1800]}) session.context_state = { @@ -665,13 +715,27 @@ async def stream_session_turn( text_chunks: list[str] = [] reasoning_chunks: list[str] = [] + pending_scene_tail = "" resolved_provider = provider_name resolved_model = model_name final_usage: dict[str, Any] = {} + direct_run_handle = register_active_run_handle( + ActiveRunHandle( + run_id=run_id, + session_id=session_id_val if session is not None else None, + actor_key=getattr(access, "actor_key", "anonymous"), + workflow_id=f"stream.{domain}", + access_tier=getattr(access, "access_tier", "public_zero_cost"), + question=question[:500], + started_at=datetime.now(UTC), + ) + ) try: async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id): - if request is not None and await request.is_disconnected(): + if direct_run_handle.cancel_event.is_set() or ( + request is not None and await request.is_disconnected() + ): return ev_type = str(ev.get("event") or "") if ev_type == "start": @@ -688,7 +752,10 @@ async def stream_session_turn( delta = ev.get("delta") if isinstance(delta, str) and delta: text_chunks.append(delta) - yield _format_sse("text", {"delta": delta}) + combined_buf = pending_scene_tail + delta + emit_chunk, pending_scene_tail = _consume_text_holding_scene_tag(combined_buf) + if emit_chunk: + yield _format_sse("text", {"delta": emit_chunk}) elif ev_type == "done": if isinstance(ev.get("provider"), str) and ev["provider"]: resolved_provider = ev["provider"] @@ -699,17 +766,30 @@ async def stream_session_turn( elif ev_type == "error": raise RuntimeError(str(ev.get("detail") or "AI stream error")) + if direct_run_handle.cancel_event.is_set(): + return + + if pending_scene_tail: + cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail) + if cleaned_tail: + yield _format_sse("text", {"delta": cleaned_tail}) + combined_text = "".join(text_chunks).strip() if not combined_text: raise RuntimeError("AI provider stream returned empty response") clean_text, inline_thoughts = strip_thinking_text(combined_text) + clean_text, parsed_scene = extract_planet_scene_from_text(clean_text or combined_text) combined_reasoning = "".join(reasoning_chunks).strip() if inline_thoughts: extra_thought = "\n\n".join(inline_thoughts) combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought final_answer_md = clean_text or combined_text + merged_scene_spec: dict[str, Any] | None = dict(scene_spec) if isinstance(scene_spec, dict) else None + if parsed_scene: + merged_scene_spec = {**(merged_scene_spec or {}), "domain": (merged_scene_spec or {}).get("domain") or domain, **parsed_scene} + _persist_session_memory(final_answer_md) if hasattr(db, "commit"): try: @@ -717,22 +797,26 @@ async def stream_session_turn( except Exception: pass - yield _format_sse( - "done", - { - "status": "completed", - "generation_mode": "llm_verified", - "zero_token": False, - "provider": resolved_provider, - "model": resolved_model, - "usage": final_usage, - "compacted": compacted_flag, - "conversation_summary": compacted_summary, - "memory_used": memory_used_flag, - "answer_markdown": final_answer_md, - "reasoning_markdown": combined_reasoning, - }, - ) + if merged_scene_spec is not None and (merged_scene_spec.get("influence_zones") or parsed_scene): + yield _format_sse("scene", {"scene_spec": merged_scene_spec}) + + done_payload: dict[str, Any] = { + "status": "completed", + "generation_mode": "llm_verified", + "zero_token": False, + "provider": resolved_provider, + "model": resolved_model, + "usage": final_usage, + "compacted": compacted_flag, + "conversation_summary": compacted_summary, + "memory_used": memory_used_flag, + "answer_markdown": final_answer_md, + "reasoning_markdown": combined_reasoning, + } + if merged_scene_spec is not None: + done_payload["scene_spec"] = merged_scene_spec + + yield _format_sse("done", done_payload) except asyncio.CancelledError: raise except Exception as exc: @@ -772,3 +856,5 @@ async def stream_session_turn( "fallback_reason": str(exc), }, ) + finally: + unregister_active_run_handle(run_id) diff --git a/backend/app/services/ai/workflow_evolver.py b/backend/app/services/ai/workflow_evolver.py index e0ecf6d2..114d0a39 100644 --- a/backend/app/services/ai/workflow_evolver.py +++ b/backend/app/services/ai/workflow_evolver.py @@ -21,6 +21,7 @@ import copy from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta import os +import re from typing import Any, Protocol from uuid import uuid4 @@ -38,6 +39,7 @@ from app.services.ai.dag_executor import run_workflow_dag_stream from app.services.ai.thinking_sanitizer import strip_thinking_text from app.services.ai.workflow_registry import ( ALLOWED_NODE_PATCH_FIELDS, + DRAFT_BINDINGS_KEY, TOOL_CATALOG, VALID_TOOL_IDS, _apply_validated_node_patches, @@ -216,6 +218,80 @@ class UnusedToolSignalDetector: return [] +FIXTURE_EXPECT_KEY = "expect" +_UNCERTAINTY_MARKERS = ( + "待核实", "待查", "不确定", "证据不足", "无法确认", "尚无法", "有待", "unverified", "uncertain", "insufficient evidence", +) + + +def normalize_fixture_expect(raw: Any) -> dict[str, Any]: + """Normalize gradable fixture assertions stored under `context_json["expect"]`.""" + if not isinstance(raw, dict): + return {} + + def _str_list(key: str) -> list[str]: + vals = raw.get(key) + if not isinstance(vals, list): + return [] + return [str(v).strip()[:120] for v in vals if str(v).strip()][:10] + + numbers: list[str] = [] + for val in raw.get("numbers") or []: + if isinstance(val, bool): + continue + if isinstance(val, (int, float)): + numbers.append(str(int(val)) if float(val).is_integer() else str(val)) + elif isinstance(val, str) and re.fullmatch(r"-?\d+(?:\.\d+)?", val.strip()): + numbers.append(val.strip()) + expect: dict[str, Any] = {} + if numbers: + expect["numbers"] = numbers[:10] + for key in ("must_include", "must_not_include"): + items = _str_list(key) + if items: + expect[key] = items + if raw.get("require_uncertainty_without_evidence"): + expect["require_uncertainty_without_evidence"] = True + min_evidence = raw.get("min_evidence") + if isinstance(min_evidence, int) and not isinstance(min_evidence, bool) and min_evidence > 0: + expect["min_evidence"] = min(min_evidence, 50) + return expect + + +def _answer_contains_number(answer: str, number: str) -> bool: + return re.search(rf"(? list[str]: + """Return the failed checks for one sample run (empty list == pass).""" + failures: list[str] = [] + answer = str(result.get("answer") or "") + if result.get("error"): + failures.append(f"执行出错:{str(result['error'])[:120]}") + if not answer.strip(): + failures.append("没有输出正文") + if result.get("verification_passed") is False: + warns = ";".join(result.get("verification_warnings") or []) or "护栏校验失败" + failures.append(f"护栏校验未通过:{warns}") + for number in expect.get("numbers") or []: + if not _answer_contains_number(answer, number): + failures.append(f"未给出期望数值 {number}") + for phrase in expect.get("must_include") or []: + if phrase not in answer: + failures.append(f"缺少必备表述「{phrase}」") + for phrase in expect.get("must_not_include") or []: + if phrase in answer: + failures.append(f"出现禁用表述「{phrase}」") + evidence_count = int(result.get("evidence_count") or 0) + if expect.get("min_evidence") and evidence_count < int(expect["min_evidence"]): + failures.append(f"证据条目 {evidence_count} 少于要求的 {expect['min_evidence']}") + if expect.get("require_uncertainty_without_evidence") and evidence_count == 0: + lowered = answer.lower() + if not any(marker in lowered for marker in _UNCERTAINTY_MARKERS): + failures.append("证据不足时未保留不确定性(缺少「待核实/证据不足」等表述)") + return failures + + class FixtureABEvaluator: evaluator_id = "fixture_ab" @@ -255,9 +331,14 @@ class FixtureABEvaluator: comparisons: list[dict[str, Any]] = [] base_ok = 0 prop_ok = 0 + graded = 0 + regressions: list[str] = [] for row in rows: question = str(row.sample_question or "").strip() or f"请分析 {row.name}" ctx = dict(row.context_json or {}) + expect = normalize_fixture_expect(ctx.pop(FIXTURE_EXPECT_KEY, None)) + if expect: + graded += 1 base_res = await _run_graph_single_sample( db=db, workflow=workflow, @@ -274,24 +355,32 @@ class FixtureABEvaluator: earth_context=ctx, ai_client=ai_client, ) + for res in (base_res, prop_res): + res["failures"] = grade_fixture_result(res, expect) + res["ok"] = not res["failures"] + res["answer_preview"] = str(res.pop("answer", ""))[:280] if base_res["ok"]: base_ok += 1 if prop_res["ok"]: prop_ok += 1 + if base_res["ok"] and not prop_res["ok"]: + regressions.append(str(row.name)) comparisons.append( { "fixture_id": row.id, "fixture_name": row.name, "question": question[:160], + "graded": bool(expect), + "expect": expect, "base": base_res, "proposed": prop_res, } ) - if prop_ok > base_ok: - verdict = "improved" - elif prop_ok < base_ok: + if regressions or prop_ok < base_ok: verdict = "regressed" + elif prop_ok > base_ok: + verdict = "improved" else: avg_base_ms = sum(c["base"]["latency_ms"] for c in comparisons) / len(comparisons) avg_prop_ms = sum(c["proposed"]["latency_ms"] for c in comparisons) / len(comparisons) @@ -300,13 +389,19 @@ class FixtureABEvaluator: else: verdict = "neutral" + graded_note = "" if graded else "(样本未设置可判对错的断言,仅校验执行成功与护栏)" return { "evaluator_id": self.evaluator_id, "fixture_count": len(comparisons), + "graded_fixture_count": graded, "base_passed": base_ok, "proposed_passed": prop_ok, + "regressions": regressions, "verdict": verdict, - "summary": f"已对照 {len(comparisons)} 组样本:原版通过 {base_ok}/{len(comparisons)},新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict})。", + "summary": ( + f"已对照 {len(comparisons)} 组样本(含断言 {graded} 组):原版通过 {base_ok}/{len(comparisons)}," + f"新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict}){graded_note}。" + ), "comparisons": comparisons, } @@ -947,6 +1042,20 @@ async def _evaluate_meta_canary(db: AsyncSession) -> None: ) if meta_canary is None: return + meta_target = meta_canary.get("target_revision") + meta_live = ( + await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == META_WORKFLOW_ID)) + ).scalar_one_or_none() + if isinstance(meta_target, int) and meta_live is not None and int(meta_live) != meta_target: + await update_ledger_entry( + db, + str(meta_canary["id"]), + { + "status": "superseded", + "superseded_reason": f"元引擎当前生效版本已变为 v{int(meta_live)}(灰度目标 v{meta_target}),终止灰度且不回滚。", + }, + ) + return meta_started = _parse_iso(meta_canary.get("created_at")) downstream = [ e @@ -1002,6 +1111,28 @@ async def evaluate_canary_and_maybe_rollback( if canary is None: return None + # A manual publish / rollback after this canary started supersedes it: rolling back now would + # overwrite the newer live revision (e.g. revert a hand-published v3 to v1). + target_rev = canary.get("target_revision") + live_rev = ( + await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == workflow_id)) + ).scalar_one_or_none() + if isinstance(target_rev, int) and live_rev is not None and int(live_rev) != target_rev: + updated = await update_ledger_entry( + db, + str(canary["id"]), + { + "status": "superseded", + "superseded_reason": f"当前生效版本已变为 v{int(live_rev)}(灰度目标 v{target_rev}),终止本轮灰度且不回滚。", + }, + ) + logger.info_event( + "Workflow canary superseded by a newer live revision", + event="ai_evolver.canary.superseded", + context={"workflow_id": workflow_id, "target_revision": target_rev, "live_revision": int(live_rev)}, + ) + return {"action": "superseded", "entry": updated} + runs = ( await db.execute( select(WorkflowRun) @@ -1204,20 +1335,12 @@ def _deterministic_business_patches( "reason": f"供应商 {profile.get('provider')} 支持原生联网检索,开启后可协同补充最新一手信源。", } ) - if not patches: - base_sys = str(llm_node.get("system_prompt") or "").strip() - model_name = str(profile.get("model") or "当前模型").strip() - tag = f"[模型适配 {model_name}] 请优先依据工具返回的实测数值作答,禁止臆测缺失字段。" - if tag not in base_sys and base_sys: - patches.append( - { - "node_id": llm_node["id"], - "field": "system_prompt", - "after": f"{base_sys}\n{tag}", - "reason": f"针对当前模型({model_name})补强事实边界约束。", - } - ) - summary = f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。" + # No capability mismatch found -> no change (never pad with generic prompt clauses). + summary = ( + f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。" + if patches + else f"当前模型 {profile.get('model') or profile.get('provider')} 与工作流配置匹配,无需调整。" + ) return summary, patches inst_lower = instruction.lower() @@ -1255,20 +1378,21 @@ def _deterministic_business_patches( "reason": f"精简近期零调用的闲置工具({', '.join(unused[:3])}),减少无效上下文干扰。", } ) - if not patches: + if not patches and instruction.strip(): + # Only an explicit admin instruction justifies a prompt edit without a detected signal. base_sys = str(llm_node.get("system_prompt") or "").strip() - target_note = instruction.strip() or ( - "先明确区分已核验事实与待查证缺口,不确定的数值或来源须直接说明。" - ) + target_note = instruction.strip() if target_note not in base_sys and base_sys: patches.append( { "node_id": llm_node["id"], "field": "system_prompt", "after": f"{base_sys}\n[调优约束] {target_note}", - "reason": "基于近期负反馈或调优目标加固提示词护栏。", + "reason": "按管理员调优目标加固提示词护栏。", } ) + if not patches: + return "未检测到需要调整的信号,本轮无需修改。", [] summary = ( f"已针对「{instruction.strip()}」生成节点调优建议。" if instruction.strip() @@ -1277,6 +1401,159 @@ def _deterministic_business_patches( return summary, patches +# Every (node, field) the meta-evolver may change must measurably alter the business proposal +# request built below; anything else would create versions that change nothing downstream. +META_EVOLVABLE_FIELDS: frozenset[tuple[str, str]] = frozenset( + { + ("diag_node", "system_prompt"), + ("diag_node", "prompt"), + ("patch_node", "system_prompt"), + ("patch_node", "prompt"), + ("patch_node", "thinking_enabled"), + } +) +_DEFAULT_EVOLVER_SYSTEM_PROMPT = "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。" +_NO_CHANGE_CLAUSE = "若现有工作流已满足目标、无需调整,请返回空的 node_patches 数组,并在 summary 中说明理由。" + + +def build_business_evolution_request( + *, + workflow_id: str, + mode: str, + instruction: str, + diag_node: dict[str, Any], + patch_node: dict[str, Any], + schema: dict[str, Any], + context: dict[str, Any], +) -> SituationalAnalysisRequest: + """Build the business-evolution LLM request from the live meta-evolver nodes.""" + diag_sys = str(diag_node.get("system_prompt") or "").strip() + diag_prompt = str(diag_node.get("prompt") or "").strip() + patch_sys = str(patch_node.get("system_prompt") or "").strip() + patch_prompt = str(patch_node.get("prompt") or "").strip() + combined_sys = f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() if (patch_sys or diag_sys) else "" + objective_parts = [ + f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)", + f"工作流 ID:{workflow_id}", + f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}", + ] + if diag_prompt: + objective_parts.append(f"[诊断任务]\n{diag_prompt}") + if patch_prompt: + objective_parts.append(f"[补丁任务]\n{patch_prompt}") + objective_parts.append(_NO_CHANGE_CLAUSE) + return SituationalAnalysisRequest( + title=f"Evolve workflow {workflow_id}", + objective="\n".join(objective_parts)[:16000], + system_prompt=(combined_sys or _DEFAULT_EVOLVER_SYSTEM_PROMPT)[:8000], + context=context, + thinking={"mode": "auto"} if bool(patch_node.get("thinking_enabled", True)) else {"mode": "off"}, + response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}}, + ) + + +def _full_graph_diff(base_graph: dict[str, Any], proposed_graph: dict[str, Any]) -> list[dict[str, Any]]: + """All node/edge differences between two graphs (layout positions ignored).""" + try: + base = _validate_graph_payload(base_graph) + proposed = _validate_graph_payload(proposed_graph) + except HTTPException: + return [] + base_nodes = {str(n["id"]): n for n in base.get("nodes") or []} + prop_nodes = {str(n["id"]): n for n in proposed.get("nodes") or []} + changes: list[dict[str, Any]] = [] + for nid in sorted(set(base_nodes) | set(prop_nodes)): + bnode, pnode = base_nodes.get(nid), prop_nodes.get(nid) + if bnode is None or pnode is None: + changes.append( + { + "node_id": nid, + "node_title": (pnode or bnode or {}).get("title") or nid, + "field": "__node__", + "before": None if bnode is None else "present", + "after": None if pnode is None else "present", + } + ) + continue + for key in sorted(set(bnode) | set(pnode)): + if key == "position" or bnode.get(key) == pnode.get(key): + continue + changes.append( + { + "node_id": nid, + "node_title": pnode.get("title") or nid, + "field": key, + "before": copy.deepcopy(bnode.get(key)), + "after": copy.deepcopy(pnode.get(key)), + } + ) + + def _edge_keys(graph: dict[str, Any]) -> set[tuple[str, str, str]]: + return { + (str(e.get("source")), str(e.get("target")), str(e.get("condition") or "always")) + for e in graph.get("edges") or [] + if isinstance(e, dict) + } + + base_edges, prop_edges = _edge_keys(base), _edge_keys(proposed) + if base_edges != prop_edges: + changes.append( + { + "node_id": "__edges__", + "node_title": "edges", + "field": "edges", + "before": sorted(list(e) for e in base_edges - prop_edges), + "after": sorted(list(e) for e in prop_edges - base_edges), + } + ) + return changes + + +def _no_change_result( + *, + workflow_id: str, + mode: str, + base_revision: int, + summary: str, + proposed_graph: dict[str, Any], + health: dict[str, Any] | None = None, + meta_revision: int | None = None, +) -> dict[str, Any]: + return { + "workflow_id": workflow_id, + "mode": mode, + "base_revision": base_revision, + "meta_revision": meta_revision, + "summary": summary, + "changes": [], + "changes_vs_live": [], + "proposed_graph": proposed_graph, + "constitution_ok": True, + "violations": [], + "applied_status": "no_change", + "new_revision": None, + "blocked_reason": "", + "ledger_entry": None, + "ab_eval": None, + "health": health, + } + + +def _ab_gate_allows_auto_publish(ab_eval: dict[str, Any]) -> tuple[bool, str]: + """Auto-publish only when graded fixtures show the candidate is not worse than live.""" + if int(ab_eval.get("fixture_count") or 0) == 0: + return False, "自动发布需先通过 A/B 门禁:当前工作流没有固定样本(Fixtures)。" + if int(ab_eval.get("graded_fixture_count") or 0) == 0: + return False, "自动发布需先通过 A/B 门禁:固定样本均未设置可判对错的断言(expect),无法证明候选版本不退化。" + regressions = list(ab_eval.get("regressions") or []) + if regressions: + return False, f"A/B 门禁未通过:{len(regressions)} 条样本在候选版本上退化({', '.join(regressions[:3])})。" + verdict = str(ab_eval.get("verdict") or "") + if verdict in {"regressed", "slower"}: + return False, f"A/B 门禁未通过(判定:{verdict})。" + return True, "" + + async def propose_workflow_evolution( db: AsyncSession, workflow_id: str, @@ -1309,7 +1586,13 @@ async def propose_workflow_evolution( health = await compute_workflow_health(db, workflow_id, ai_client=ai_client) parent_revision = int(wf.active_revision or 1) - base_graph = copy.deepcopy(wf.draft_graph or wf.published_graph or {}) + live_graph = copy.deepcopy(wf.published_graph or {}) + # Only an admin explicitly tuning into a draft may build on their own unpublished draft. + # Background / auto-publish evolution always starts from the live revision so it can never + # smuggle unpublished human edits into production or clear them. + builds_on_human_draft = trigger == "manual" and apply_mode != "auto" and wf.draft_graph is not None + base_graph = copy.deepcopy(wf.draft_graph if builds_on_human_draft else live_graph) + base_graph.pop(DRAFT_BINDINGS_KEY, None) # Optional DGM archive parent selection if branch_from_best and health.get("recommended_parent_revision"): @@ -1323,6 +1606,7 @@ async def propose_workflow_evolution( ).scalar_one_or_none() if rev_row is not None and isinstance(rev_row.graph_json, dict): base_graph = copy.deepcopy(rev_row.graph_json) + base_graph.pop(DRAFT_BINDINGS_KEY, None) parent_revision = best_rev # Collect bad/selected run context for GEPA diagnosis @@ -1381,6 +1665,7 @@ async def propose_workflow_evolution( summary = "" raw_patches: list[dict[str, Any]] = [] + ai_decided = False if ai_ready and client is not None: schema = { "type": "object", @@ -1402,22 +1687,13 @@ async def propose_workflow_evolution( }, "required": ["summary", "node_patches"], } - diag_sys = str(diag_node.get("system_prompt") or "").strip() - patch_sys = str(patch_node.get("system_prompt") or "").strip() - combined_sys = ( - f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() - or "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。" - ) - objective = ( - f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)\n" - f"工作流 ID:{workflow_id}\n" - f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}\n" - f"{str(patch_node.get('prompt') or '')}" - ).strip() - req = SituationalAnalysisRequest( - title=f"Evolve workflow {workflow_id}", - objective=objective[:16000], - system_prompt=combined_sys[:8000], + req = build_business_evolution_request( + workflow_id=workflow_id, + mode=mode, + instruction=instruction, + diag_node=diag_node, + patch_node=patch_node, + schema=schema, context={ "workflow_id": workflow_id, "parent_revision": parent_revision, @@ -1431,7 +1707,6 @@ async def propose_workflow_evolution( "selected_run": selected_run.to_dict() if selected_run else None, "aflow_lessons": lessons, }, - response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}}, ) try: resp = await client.analyze(req) @@ -1441,6 +1716,8 @@ async def propose_workflow_evolution( summary = str(parsed.get("summary") or "").strip() if isinstance(parsed.get("node_patches"), list): raw_patches = parsed["node_patches"] + # A valid, explicitly empty patch list means "no change needed" — honour it. + ai_decided = True except Exception as exc: logger.warning_event( "AI evolution proposal failed; using deterministic fallback", @@ -1448,7 +1725,7 @@ async def propose_workflow_evolution( context={"workflow_id": workflow_id, "mode": mode, "error": str(exc)}, ) - if not raw_patches: + if not ai_decided: summary, raw_patches = _deterministic_business_patches( base_graph, mode=mode, @@ -1458,11 +1735,23 @@ async def propose_workflow_evolution( ) proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches) + if not diffs: + return _no_change_result( + workflow_id=workflow_id, + mode=mode, + base_revision=parent_revision, + summary=summary or "引擎判断当前工作流无需修改。", + proposed_graph=proposed_graph, + health=health, + ) + is_auto_apply = apply_mode == "auto" + # Everything that would actually ship, measured against the live revision (not just engine patches). + changes_vs_live = _full_graph_diff(live_graph, proposed_graph) constitution_ok, violations = validate_evolution_patch( - base_graph, + live_graph if is_auto_apply else base_graph, proposed_graph, - diffs, + changes_vs_live if is_auto_apply else diffs, is_meta=False, is_auto=is_auto_apply, ) @@ -1471,11 +1760,16 @@ async def propose_workflow_evolution( new_revision = None blocked_reason = "" ledger_entry: dict[str, Any] | None = None + ab_eval: dict[str, Any] | None = None if apply_mode == "draft": - if not constitution_ok or not diffs: + if trigger != "manual" and wf.draft_graph is not None: + # Never overwrite an admin's unpublished draft from a background run. + applied_status = "skipped" + blocked_reason = "存在未发布的人工草稿,自动进化不覆盖草稿,本轮跳过。" + elif not constitution_ok: applied_status = "blocked" - blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动" + blocked_reason = ";".join(violations) else: await save_workflow_draft( db, @@ -1496,6 +1790,8 @@ async def propose_workflow_evolution( "meta_revision": meta_revision, "summary": summary, "changes": diffs, + "changes_vs_live": changes_vs_live, + "built_on_human_draft": builds_on_human_draft, }, ) elif apply_mode == "auto": @@ -1510,10 +1806,17 @@ async def propose_workflow_evolution( if not budget_ok: applied_status = "blocked" blocked_reason = budget_msg - elif not constitution_ok or not diffs: + elif not constitution_ok: applied_status = "blocked" - blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动" + blocked_reason = ";".join(violations) else: + # Auto-publish must prove on graded fixtures that the candidate is not worse than live. + ab_eval = await run_fixture_ab_eval(db, workflow_id, proposed_graph, max_fixtures=5) + gate_ok, gate_msg = _ab_gate_allows_auto_publish(ab_eval) + if not gate_ok: + applied_status = "blocked" + blocked_reason = gate_msg + if applied_status != "blocked": prev_active_rev = int(wf.active_revision or 1) published = await publish_workflow( db, @@ -1521,6 +1824,7 @@ async def propose_workflow_evolution( graph=proposed_graph, change_summary=f"[Auto-Evolve/{mode}] {summary[:120]}", actor="system:auto_evolver", + keep_draft=True, ) applied_status = "auto_published" new_revision = int(published.get("active_revision") or (prev_active_rev + 1)) @@ -1539,6 +1843,8 @@ async def propose_workflow_evolution( "baseline_failure_rate": health["failure_rate"], "summary": summary, "changes": diffs, + "changes_vs_live": changes_vs_live, + "ab_eval_summary": (ab_eval or {}).get("summary"), }, ) if applied_status == "blocked": @@ -1554,6 +1860,7 @@ async def propose_workflow_evolution( "summary": summary or f"{mode} blocked", "rollback_reason": blocked_reason, "changes": diffs, + "changes_vs_live": changes_vs_live, }, ) @@ -1564,6 +1871,7 @@ async def propose_workflow_evolution( "meta_revision": meta_revision, "summary": summary or "暂无需要变更的字段。", "changes": diffs, + "changes_vs_live": changes_vs_live, "proposed_graph": proposed_graph, "constitution_ok": constitution_ok, "violations": violations, @@ -1571,6 +1879,7 @@ async def propose_workflow_evolution( "new_revision": new_revision, "blocked_reason": blocked_reason, "ledger_entry": ledger_entry, + "ab_eval": ab_eval, "health": health, } @@ -1598,6 +1907,8 @@ async def _run_graph_single_sample( answer = "" err = "" nodes_done: list[str] = [] + verification: dict[str, Any] = {} + evidence_count = 0 try: async for ev in run_workflow_dag_stream( db=db, @@ -1613,6 +1924,10 @@ async def _run_graph_single_sample( if ev_name == "done": answer = str(ev_data.get("answer_markdown") or "") nodes_done = [str(x) for x in (ev_data.get("nodes") or [])] + if isinstance(ev_data.get("verification"), dict): + verification = ev_data["verification"] + if isinstance(ev_data.get("evidence"), dict): + evidence_count = len(ev_data["evidence"]) elif ev_name == "error": err = str(ev_data.get("message") or "DAG error") except Exception as exc: @@ -1620,11 +1935,14 @@ async def _run_graph_single_sample( latency_ms = max(0, int((_utc_now() - started).total_seconds() * 1000)) return { - "ok": bool(answer.strip()) and not err, + "answer": answer, "latency_ms": latency_ms, "answer_length": len(answer.strip()), "nodes": nodes_done, "error": err, + "verification_passed": bool(verification.get("passed", True)), + "verification_warnings": list(verification.get("warnings") or []), + "evidence_count": evidence_count, } @@ -1874,7 +2192,11 @@ async def propose_meta_evolution( if meta_wf is None: raise HTTPException(status_code=404, detail=f"Workflow '{META_WORKFLOW_ID}' not found") - base_graph = copy.deepcopy(meta_wf.draft_graph or meta_wf.published_graph or {}) + builds_on_human_draft = trigger == "meta_manual" and apply_mode != "auto" and meta_wf.draft_graph is not None + base_graph = copy.deepcopy( + meta_wf.draft_graph if builds_on_human_draft else (meta_wf.published_graph or {}) + ) + base_graph.pop(DRAFT_BINDINGS_KEY, None) ledger = await _load_ledger_entries(db) outcomes = [ e @@ -1901,6 +2223,7 @@ async def propose_meta_evolution( summary = "" raw_patches: list[dict[str, Any]] = [] + meta_ai_decided = False if ai_ready and client is not None: schema = { "type": "object", @@ -1926,8 +2249,9 @@ async def propose_meta_evolution( title="Meta-evolve workflow evolver", objective=( f"管理员指示:{instruction.strip() or '基于进化台账中已验证与被回滚/忽略的案例,优化元引擎诊断与补丁合成精度。'}\n" - "仅允许修改 `diag_node` 或 `patch_node` 的提示词或 thinking_enabled;" - "严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。" + "仅允许修改 `diag_node` 的 system_prompt/prompt,或 `patch_node` 的 system_prompt/prompt/thinking_enabled;" + "严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。\n" + f"{_NO_CHANGE_CLAUSE}" ), system_prompt="你是智能星球 AI 元进化策略师。仅输出严格 JSON:{summary, node_patches}。", context={ @@ -1949,6 +2273,7 @@ async def propose_meta_evolution( summary = str(parsed.get("summary") or "").strip() if isinstance(parsed.get("node_patches"), list): raw_patches = parsed["node_patches"] + meta_ai_decided = True except Exception as exc: logger.warning_event( "AI meta-evolution request failed; using deterministic prompt refinement", @@ -1956,7 +2281,8 @@ async def propose_meta_evolution( context={"error": str(exc)}, ) - if not raw_patches: + if not meta_ai_decided and (instruction.strip() or outcomes): + # Deterministic refinement needs a real basis: an admin instruction or ledger outcomes. target_node = next( (n for n in (base_graph.get("nodes") or []) if n.get("id") == "patch_node"), None, @@ -1987,7 +2313,25 @@ async def propose_meta_evolution( f"基于 {len(outcomes)} 条进化台账记录(验证有效 {verified_count},回滚 {rollback_count},忽略 {dismissed_count})生成元引擎自举方案。" ) + # Drop patches to fields that have no downstream effect on the business proposal request. + raw_patches = [ + p + for p in raw_patches + if isinstance(p, dict) + and (str(p.get("node_id") or ""), str(p.get("field") or "")) in META_EVOLVABLE_FIELDS + ] proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches) + if not diffs: + return { + **_no_change_result( + workflow_id=META_WORKFLOW_ID, + mode="meta", + base_revision=int(meta_wf.active_revision or 1), + summary=summary or "元引擎判断当前策略无需修改(暂无进化台账结果或明确指示)。", + proposed_graph=proposed_graph, + ), + "outcomes_analyzed": len(outcomes), + } is_auto_apply = apply_mode == "auto" constitution_ok, violations = validate_evolution_patch( base_graph, @@ -2004,9 +2348,12 @@ async def propose_meta_evolution( policy = await get_evolution_policy(db) if apply_mode == "draft": - if not constitution_ok or not diffs: + if trigger != "meta_manual" and meta_wf.draft_graph is not None: + applied_status = "skipped" + blocked_reason = "存在未发布的人工元引擎草稿,自动元进化不覆盖草稿,本轮跳过。" + elif not constitution_ok: applied_status = "blocked" - blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动" + blocked_reason = ";".join(violations) else: await save_workflow_draft( db, @@ -2045,9 +2392,9 @@ async def propose_meta_evolution( if not budget_ok: applied_status = "blocked" blocked_reason = budget_msg - elif not constitution_ok or not diffs: + elif not constitution_ok: applied_status = "blocked" - blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动" + blocked_reason = ";".join(violations) else: prev_rev = int(meta_wf.active_revision or 1) published = await publish_workflow( @@ -2056,6 +2403,7 @@ async def propose_meta_evolution( graph=proposed_graph, change_summary=f"[Meta-Evolve] {summary[:120]}", actor="system:meta_evolver" if trigger != "meta_manual" else actor, + keep_draft=True, ) applied_status = "auto_published" new_revision = int(published.get("active_revision") or (prev_rev + 1)) diff --git a/backend/app/services/ai/workflow_registry.py b/backend/app/services/ai/workflow_registry.py index b781ad99..a791bfc4 100644 --- a/backend/app/services/ai/workflow_registry.py +++ b/backend/app/services/ai/workflow_registry.py @@ -4,14 +4,13 @@ from __future__ import annotations from collections import deque import copy -from datetime import UTC, datetime import inspect import json import re from typing import Any from uuid import uuid4 -from fastapi import HTTPException, status +from fastapi import HTTPException from sqlalchemy import delete, desc, select from sqlalchemy.ext.asyncio import AsyncSession @@ -140,6 +139,8 @@ TOOL_CATALOG: list[dict[str, Any]] = [ VALID_TOOL_IDS: frozenset[str] = frozenset(item["id"] for item in TOOL_CATALOG) MAX_WORKFLOW_NODES = 12 +# Graph-level key carrying Earth bindings inside drafts and revision snapshots (no extra column). +DRAFT_BINDINGS_KEY = "bindings" VALID_NODE_TYPES: frozenset[str] = frozenset( {"trigger", "deterministic", "llm_agent", "guardrail", "output"} ) @@ -1355,7 +1356,7 @@ async def create_workflow( workflow_id=wf_id, revision=1, status="published", - graph_json=validated_graph, + graph_json={**validated_graph, DRAFT_BINDINGS_KEY: dict(normalized_bindings)}, change_summary="Created custom workflow", created_by=actor, ) @@ -1437,7 +1438,11 @@ async def update_workflow_metadata( if description_en is not None: row.description_en = description_en.strip() if bindings is not None: + # Explicit "save bindings now" is a deliberate live change; keep any pending draft in sync + # so a later draft publish does not silently revert it. row.bindings = normalize_bindings(bindings) + if isinstance(row.draft_graph, dict): + row.draft_graph = {**row.draft_graph, DRAFT_BINDINGS_KEY: dict(row.bindings)} row.updated_by = actor await db.commit() await db.refresh(row) @@ -1480,9 +1485,17 @@ async def save_workflow_draft( ).scalar_one_or_none() if row is None: raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") - row.draft_graph = _validate_graph_payload(graph) + previous_draft_bindings = ( + row.draft_graph.get(DRAFT_BINDINGS_KEY) if isinstance(row.draft_graph, dict) else None + ) + staged = _validate_graph_payload(graph) + # Draft bindings stay inside the draft so the public Earth entry only changes on publish + # and is restored by discarding the draft. if bindings is not None: - row.bindings = normalize_bindings(bindings) + staged[DRAFT_BINDINGS_KEY] = normalize_bindings(bindings) + elif isinstance(previous_draft_bindings, dict): + staged[DRAFT_BINDINGS_KEY] = previous_draft_bindings + row.draft_graph = staged if name is not None and name.strip(): row.name = name.strip()[:160] if description is not None: @@ -1523,6 +1536,7 @@ async def publish_workflow( description: str | None = None, change_summary: str = "", actor: str = "admin", + keep_draft: bool = False, ) -> dict[str, Any]: await ensure_builtin_workflows(db) row = ( @@ -1531,13 +1545,17 @@ async def publish_workflow( if row is None: raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found") target_graph = graph if graph is not None else (row.draft_graph or row.published_graph) + staged_bindings = target_graph.get(DRAFT_BINDINGS_KEY) if isinstance(target_graph, dict) else None validated = _validate_graph_payload(target_graph) next_rev = int(row.active_revision or 1) + 1 row.published_graph = validated - row.draft_graph = None + if not keep_draft: + row.draft_graph = None row.active_revision = next_rev if bindings is not None: row.bindings = normalize_bindings(bindings) + elif isinstance(staged_bindings, dict): + row.bindings = normalize_bindings(staged_bindings) if name is not None and name.strip(): row.name = name.strip()[:160] if description is not None: @@ -1548,7 +1566,8 @@ async def publish_workflow( workflow_id=workflow_id, revision=next_rev, status="published", - graph_json=validated, + # Snapshot bindings with the graph so rollback restores the matching Earth entry. + graph_json={**validated, DRAFT_BINDINGS_KEY: dict(row.bindings or {})}, change_summary=change_summary.strip() or f"Published revision v{next_rev}", created_by=actor, ) diff --git a/backend/app/services/ai/workflow_runtime.py b/backend/app/services/ai/workflow_runtime.py index 071f36d2..b84eb9a0 100644 --- a/backend/app/services/ai/workflow_runtime.py +++ b/backend/app/services/ai/workflow_runtime.py @@ -94,6 +94,17 @@ def get_active_run_handle(run_id: str) -> ActiveRunHandle | None: return _ACTIVE_RUNS.get(run_id) +def register_active_run_handle(handle: ActiveRunHandle) -> ActiveRunHandle: + """Register an active streaming/execution run handle for explicit cooperative cancellation.""" + _ACTIVE_RUNS[handle.run_id] = handle + return handle + + +def unregister_active_run_handle(run_id: str) -> None: + """Remove an active run handle once execution finishes or aborts.""" + _ACTIVE_RUNS.pop(run_id, None) + + def cancel_active_run_handle(run_id: str) -> bool: """Signal cancellation event and abort in-flight asyncio task if active.""" handle = _ACTIVE_RUNS.get(run_id) @@ -136,6 +147,481 @@ class WorkbenchBlockSpec(BaseModel): data: dict[str, Any] = Field(default_factory=dict) +class InfluenceZoneEdgeSpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + style: Literal["soft", "sharp"] = "soft" + feather_px: float = Field(default=22.0, ge=0.0, le=48.0) + border_width: float = Field(default=1.5, ge=0.0, le=6.0) + + +class InfluenceZoneAnimationSpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + type: Literal["sweep", "radial", "fade"] = "sweep" + direction: str = Field(default="west_to_east", max_length=32) + duration_ms: int = Field(default=1800, ge=150, le=8000) + delay_ms: int = Field(default=0, ge=0, le=5000) + + +class InfluenceZoneShapeSpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + mode: Literal["countries", "region_preset", "circle", "polygon"] + countries: list[str] = Field(default_factory=list, max_length=64) + region_preset: str | None = Field(default=None, max_length=32) + center: list[float] | None = Field(default=None, min_length=2, max_length=2) + radius_km: float | None = Field(default=None, ge=20.0, le=15000.0) + coordinates: list[list[list[float]]] = Field(default_factory=list, max_length=16) + + +class InfluenceZoneSpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + id: str = Field(..., min_length=1, max_length=64) + label: str = Field(default="", max_length=80) + color: str = Field(default="#38bdf8", pattern=r"^#[0-9a-fA-F]{6}$") + opacity: float = Field(default=0.42, ge=0.05, le=0.9) + z_index: int = Field(default=0, ge=-50, le=50) + edge: InfluenceZoneEdgeSpec = Field(default_factory=InfluenceZoneEdgeSpec) + animation: InfluenceZoneAnimationSpec = Field(default_factory=InfluenceZoneAnimationSpec) + shape: InfluenceZoneShapeSpec + + +_SCENE_COLOR_NAMES: dict[str, str] = { + "red": "#ef4444", + "crimson": "#dc2626", + "orange": "#f97316", + "amber": "#f59e0b", + "yellow": "#eab308", + "green": "#22c55e", + "emerald": "#10b981", + "teal": "#14b8a6", + "cyan": "#06b6d4", + "blue": "#38bdf8", + "indigo": "#6366f1", + "purple": "#a855f7", + "violet": "#8b5cf6", + "pink": "#ec4899", + "white": "#f8fafc", +} + +SUPPORTED_REGION_PRESETS: frozenset[str] = frozenset( + { + "APEC", + "ASIA_PACIFIC", + "NORTHEAST_ASIA", + "EAST_ASIA", + "KOREAN_PENINSULA", + "SOUTHEAST_ASIA", + "SOUTH_ASIA", + "CENTRAL_ASIA", + "INDO_PACIFIC", + "ASEAN", + "EU", + "EUROPE", + "EASTERN_EUROPE", + "NORTHERN_EUROPE", + "WESTERN_EUROPE", + "G7", + "BRICS", + "NATO", + "MIDDLE_EAST", + "MENA", + "AMERICAS", + "NORTH_AMERICA", + "SOUTH_AMERICA", + "AFRICA", + } +) + +_REGION_PRESET_ALIASES: dict[str, str] = { + "东北亚": "NORTHEAST_ASIA", + "NE_ASIA": "NORTHEAST_ASIA", + "东亚": "EAST_ASIA", + "朝鲜半岛": "KOREAN_PENINSULA", + "PENINSULA": "KOREAN_PENINSULA", + "东南": "SOUTHEAST_ASIA", + "东南亚": "SOUTHEAST_ASIA", + "SE_ASIA": "SOUTHEAST_ASIA", + "南亚": "SOUTH_ASIA", + "中亚": "CENTRAL_ASIA", + "亚太": "ASIA_PACIFIC", + "印太": "INDO_PACIFIC", + "欧洲": "EUROPE", + "东欧": "EASTERN_EUROPE", + "北欧": "NORTHERN_EUROPE", + "NORDIC": "NORTHERN_EUROPE", + "BALTIC": "NORTHERN_EUROPE", + "波罗的海": "NORTHERN_EUROPE", + "西欧": "WESTERN_EUROPE", + "欧盟": "EU", + "北约": "NATO", + "东盟": "ASEAN", + "中东": "MIDDLE_EAST", + "中东北非": "MENA", + "MIDDLE_EAST_NORTH_AFRICA": "MENA", + "美洲": "AMERICAS", + "北美": "NORTH_AMERICA", + "南美": "SOUTH_AMERICA", + "拉美": "SOUTH_AMERICA", + "LATIN_AMERICA": "SOUTH_AMERICA", + "非洲": "AFRICA", +} + +_COUNTRY_ALIAS_MAP: dict[str, str] = { + "CN": "CHN", + "CHN": "CHN", + "CHINA": "CHN", + "PRC": "CHN", + "中国": "CHN", + "HK": "CHN", + "HKG": "CHN", + "香港": "CHN", + "MO": "CHN", + "MAC": "CHN", + "澳门": "CHN", + "TW": "CHN", + "TWN": "CHN", + "台湾": "CHN", + "KP": "PRK", + "PRK": "PRK", + "DPRK": "PRK", + "NK": "PRK", + "NKR": "PRK", + "NORTH KOREA": "PRK", + "NORTH_KOREA": "PRK", + "朝鲜": "PRK", + "北朝鲜": "PRK", + "朝鲜民主主义人民共和国": "PRK", + "KR": "KOR", + "KOR": "KOR", + "ROK": "KOR", + "KOREA": "KOR", + "SOUTH KOREA": "KOR", + "SOUTH_KOREA": "KOR", + "韩国": "KOR", + "南韩": "KOR", + "大韩民国": "KOR", + "US": "USA", + "USA": "USA", + "AMERICA": "USA", + "美国": "USA", + "RU": "RUS", + "RUS": "RUS", + "RUSSIA": "RUS", + "俄罗斯": "RUS", + "俄国": "RUS", + "JP": "JPN", + "JPN": "JPN", + "JAPAN": "JPN", + "日本": "JPN", + "UK": "GBR", + "GB": "GBR", + "GBR": "GBR", + "BRITAIN": "GBR", + "英国": "GBR", + "FR": "FRA", + "FRA": "FRA", + "FRANCE": "FRA", + "法国": "FRA", + "DE": "DEU", + "DEU": "DEU", + "GERMANY": "DEU", + "德国": "DEU", + "IN": "IND", + "IND": "IND", + "INDIA": "IND", + "印度": "IND", + "AU": "AUS", + "AUS": "AUS", + "AUSTRALIA": "AUS", + "澳大利亚": "AUS", + "CA": "CAN", + "CAN": "CAN", + "CANADA": "CAN", + "加拿大": "CAN", + "BR": "BRA", + "BRA": "BRA", + "BRAZIL": "BRA", + "巴西": "BRA", + "SG": "SGP", + "SGP": "SGP", + "SINGAPORE": "SGP", + "新加坡": "SGP", + "ID": "IDN", + "IDN": "IDN", + "INDONESIA": "IDN", + "印尼": "IDN", + "VN": "VNM", + "VNM": "VNM", + "VIETNAM": "VNM", + "越南": "VNM", + "TH": "THA", + "THA": "THA", + "THAILAND": "THA", + "泰国": "THA", + "MY": "MYS", + "MYS": "MYS", + "MALAYSIA": "MYS", + "马来西亚": "MYS", + "PH": "PHL", + "PHL": "PHL", + "PHILIPPINES": "PHL", + "菲律宾": "PHL", + "UA": "UKR", + "UKR": "UKR", + "UKRAINE": "UKR", + "乌克兰": "UKR", + "IR": "IRN", + "IRN": "IRN", + "IRAN": "IRN", + "伊朗": "IRN", + "SA": "SAU", + "SAU": "SAU", + "沙特": "SAU", + "TR": "TUR", + "TUR": "TUR", + "TURKEY": "TUR", + "土耳其": "TUR", + "IL": "ISR", + "ISR": "ISR", + "ISRAEL": "ISR", + "以色列": "ISR", + "EG": "EGY", + "EGY": "EGY", + "EGYPT": "EGY", + "埃及": "EGY", + "SO": "SOM", + "SOM": "SOM", + "SOMALIA": "SOM", + "索马里": "SOM", + "YE": "YEM", + "YEM": "YEM", + "YEMEN": "YEM", + "也门": "YEM", + "AE": "ARE", + "ARE": "ARE", + "UAE": "ARE", + "阿联酋": "ARE", + "MN": "MNG", + "MNG": "MNG", + "MONGOLIA": "MNG", + "蒙古": "MNG", + "PL": "POL", + "POL": "POL", + "POLAND": "POL", + "波兰": "POL", +} + + +def _normalize_country_code(raw: Any) -> str: + text = str(raw or "").strip() + if not text: + return "" + upper = text.upper() + return _COUNTRY_ALIAS_MAP.get(text) or _COUNTRY_ALIAS_MAP.get(upper) or upper + + +def _normalize_region_preset(raw: Any) -> str | None: + text = str(raw or "").strip() + if not text: + return None + normalized = re.sub(r"[\s-]+", "_", text.upper()) + canonical = _REGION_PRESET_ALIASES.get(text) or _REGION_PRESET_ALIASES.get(normalized) or normalized + return canonical[:32] if canonical in SUPPORTED_REGION_PRESETS else None + + +def _coerce_bounded_float(value: Any, low: float, high: float, default: float) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + return default + try: + num = float(value) + except Exception: + return default + return max(low, min(high, num)) + + +def _coerce_bounded_int(value: Any, low: int, high: int, default: int) -> int: + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + return default + try: + num = int(float(value)) + except Exception: + return default + return max(low, min(high, num)) + + +def _normalize_zone_color(raw: Any) -> str: + text = str(raw or "").strip().lower() + if re.fullmatch(r"#[0-9a-f]{6}", text): + return text + if re.fullmatch(r"#[0-9a-f]{3}", text): + return "#" + "".join(ch * 2 for ch in text[1:]) + return _SCENE_COLOR_NAMES.get(text, "#38bdf8") + + +def _normalize_influence_zone_candidate(item: dict[str, Any], idx: int) -> dict[str, Any]: + """Sanitize tolerant LLM-authored influence zone fields before strict Pydantic validation.""" + raw_edge = item.get("edge") + edge_dict: dict[str, Any] = {} + hoisted_opacity = None + if isinstance(raw_edge, str): + style = raw_edge.strip().lower() + edge_dict["style"] = style if style in {"soft", "sharp"} else "soft" + elif isinstance(raw_edge, dict): + if "opacity" in raw_edge: + hoisted_opacity = raw_edge.get("opacity") + style = str(raw_edge.get("style") or "soft").strip().lower() + edge_dict["style"] = style if style in {"soft", "sharp"} else "soft" + if "feather_px" in raw_edge: + edge_dict["feather_px"] = _coerce_bounded_float(raw_edge.get("feather_px"), 0.0, 48.0, 22.0) + if "border_width" in raw_edge: + edge_dict["border_width"] = _coerce_bounded_float(raw_edge.get("border_width"), 0.0, 6.0, 1.5) + + raw_anim = item.get("animation") + anim_dict: dict[str, Any] = {} + if isinstance(raw_anim, str): + atype = raw_anim.strip().lower() + anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep" + elif isinstance(raw_anim, dict): + atype = str(raw_anim.get("type") or "sweep").strip().lower() + anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep" + if raw_anim.get("direction"): + anim_dict["direction"] = str(raw_anim["direction"])[:32] + if "duration_ms" in raw_anim: + anim_dict["duration_ms"] = _coerce_bounded_int(raw_anim.get("duration_ms"), 150, 8000, 1800) + if "delay_ms" in raw_anim: + anim_dict["delay_ms"] = _coerce_bounded_int(raw_anim.get("delay_ms"), 0, 5000, 0) + + raw_shape = item.get("shape") + shape_src = dict(raw_shape) if isinstance(raw_shape, dict) else { + k: item[k] + for k in ("mode", "countries", "country", "iso_codes", "region_preset", "region", "center", "radius_km", "coordinates") + if k in item + } + raw_countries = shape_src.get("countries") if "countries" in shape_src else (shape_src.get("country") or shape_src.get("iso_codes")) + if isinstance(raw_countries, str): + raw_country_items = [raw_countries] + elif isinstance(raw_countries, list): + raw_country_items = raw_countries[:64] + else: + raw_country_items = [] + countries_list: list[str] = [] + seen_countries: set[str] = set() + for raw_c in raw_country_items: + norm_c = _normalize_country_code(raw_c) + if norm_c and norm_c not in seen_countries: + seen_countries.add(norm_c) + countries_list.append(norm_c) + + region_preset = shape_src.get("region_preset") or shape_src.get("region") + region_preset_val = _normalize_region_preset(region_preset) + + raw_center = shape_src.get("center") + center_val: list[float] | None = None + if isinstance(raw_center, dict) and "lat" in raw_center and "lon" in raw_center: + center_val = [ + _coerce_bounded_float(raw_center.get("lat"), -90.0, 90.0, 0.0), + _coerce_bounded_float(raw_center.get("lon"), -180.0, 180.0, 0.0), + ] + elif isinstance(raw_center, (list, tuple)) and len(raw_center) >= 2: + center_val = [ + _coerce_bounded_float(raw_center[0], -90.0, 90.0, 0.0), + _coerce_bounded_float(raw_center[1], -180.0, 180.0, 0.0), + ] + + raw_coords = shape_src.get("coordinates") + coords_val: list[list[list[float]]] = [] + if isinstance(raw_coords, list) and raw_coords: + first_coord = raw_coords[0] + # Auto-wrap 2D polygon rings ([[lon, lat], ...]) to MultiPolygon ring list ([[[lon, lat], ...]]). + if ( + isinstance(first_coord, (list, tuple)) + and first_coord + and isinstance(first_coord[0], (int, float)) + ): + coords_val = [raw_coords] # type: ignore[list-item] + else: + coords_val = raw_coords[:16] + + mode = str(shape_src.get("mode") or "").strip().lower() + if mode not in {"countries", "region_preset", "circle", "polygon"}: + if countries_list: + mode = "countries" + elif region_preset_val: + mode = "region_preset" + elif center_val is not None: + mode = "circle" + elif coords_val: + mode = "polygon" + elif mode == "region_preset" and region_preset_val is None and countries_list: + mode = "countries" + + shape_clean: dict[str, Any] = {"mode": mode} + if countries_list: + shape_clean["countries"] = countries_list + if region_preset_val: + shape_clean["region_preset"] = region_preset_val + if center_val is not None: + shape_clean["center"] = center_val + if shape_src.get("radius_km") is not None: + shape_clean["radius_km"] = _coerce_bounded_float(shape_src.get("radius_km"), 20.0, 15000.0, 600.0) + if coords_val: + shape_clean["coordinates"] = coords_val + + opacity_raw = item.get("opacity", hoisted_opacity) + candidate: dict[str, Any] = { + "id": str(item.get("id") or f"zone-{idx + 1}").strip()[:64] or f"zone-{idx + 1}", + "label": str(item.get("label") or item.get("name") or item.get("title") or "")[:80], + "color": _normalize_zone_color(item.get("color")), + "opacity": _coerce_bounded_float(opacity_raw, 0.05, 0.9, 0.42), + "z_index": _coerce_bounded_int(item.get("z_index"), -50, 50, 0), + "shape": shape_clean, + } + if edge_dict: + candidate["edge"] = edge_dict + if anim_dict: + candidate["animation"] = anim_dict + return candidate + + +def validate_influence_zones(raw: Any) -> list[InfluenceZoneSpec]: + """Validate and bound LLM-proposed influence zones without failing the response.""" + if not isinstance(raw, list): + return [] + validated: list[InfluenceZoneSpec] = [] + for idx, item in enumerate(raw[:12]): + if not isinstance(item, dict): + continue + candidate = _normalize_influence_zone_candidate(item, idx) + shape = candidate.get("shape") or {} + mode = shape.get("mode") + has_renderable_shape = ( + (mode == "countries" and bool(shape.get("countries"))) + or (mode == "region_preset" and bool(shape.get("region_preset"))) + or (mode == "circle" and shape.get("center") is not None) + or (mode == "polygon" and bool(shape.get("coordinates"))) + ) + if not has_renderable_shape: + logger.warning_event( + "Influence zone candidate rejected due to empty/unrenderable shape", + event="ai_scene.zone.rejected", + context={"index": idx, "mode": mode, "id": candidate.get("id")}, + ) + continue + try: + validated.append(InfluenceZoneSpec.model_validate(candidate)) + except Exception as exc: + logger.warning_event( + "Influence zone candidate rejected", + event="ai_scene.zone.rejected", + context={"index": idx, "error": str(exc)}, + ) + continue + return validated + + class SceneSpec(BaseModel): model_config = ConfigDict(extra="forbid") @@ -147,6 +633,7 @@ class SceneSpec(BaseModel): camera_hint: dict[str, float] | None = None presentation_key: str | None = None auto_play_presentation: bool = False + influence_zones: list[InfluenceZoneSpec] = Field(default_factory=list, max_length=12) class ViewSpec(BaseModel): diff --git a/backend/app/services/collectors/base.py b/backend/app/services/collectors/base.py index 9ea1e2c8..b709b901 100644 --- a/backend/app/services/collectors/base.py +++ b/backend/app/services/collectors/base.py @@ -7,7 +7,7 @@ from datetime import UTC, datetime from time import perf_counter from urllib.parse import urlparse import httpx -from sqlalchemy import delete, insert, select, text, update +from sqlalchemy import delete, insert, select, update from sqlalchemy.ext.asyncio import AsyncSession from app.core.collected_data_fields import build_dynamic_metadata, get_record_field @@ -66,6 +66,15 @@ class BaseCollector(ABC): self._fetch_is_complete: bool = False self._fetch_is_sample_fallback: bool = False self._sample_fallback_reason: Optional[str] = None + self._db_commit_lock: Optional[asyncio.Lock] = asyncio.Lock() + + def _get_db_commit_lock(self) -> asyncio.Lock: + """Return the per-collector lock used to serialize DB session commits.""" + lock = getattr(self, "_db_commit_lock", None) + if lock is None: + lock = asyncio.Lock() + self._db_commit_lock = lock + return lock def _mark_fetch_complete(self, complete: bool = True) -> None: """Mark the current fetch payload as a verified full-universe snapshot.""" @@ -157,7 +166,9 @@ class BaseCollector(ABC): async def update_progress(self, records_processed: int, *, commit: bool = False, force: bool = False): """Update task progress - call this during data processing""" - if self._current_task and self._db_session: + if not self._current_task or not self._db_session: + return + async with self._get_db_commit_lock(): self._current_task.records_processed = records_processed if self._current_task.total_records and self._current_task.total_records > 0: self._current_task.progress = ( @@ -172,7 +183,9 @@ class BaseCollector(ABC): await self._publish_task_update(force=force) async def set_phase(self, phase: str, *, message: str | None = None, reset_progress: bool = True): - if self._current_task and self._db_session: + if not self._current_task or not self._db_session: + return + async with self._get_db_commit_lock(): self._current_task.phase = phase self._current_task.phase_message = message if reset_progress: @@ -198,24 +211,25 @@ class BaseCollector(ABC): if not self._current_task or not self._db_session: return - if progress is None and current is not None and total and total > 0: - progress = (current / total) * 100 + async with self._get_db_commit_lock(): + if progress is None and current is not None and total and total > 0: + progress = (current / total) * 100 - if progress is not None: - self._current_task.phase_progress = max(0.0, min(float(progress), 100.0)) - if current is not None: - self._current_task.phase_current = max(0, int(current)) - if total is not None: - self._current_task.phase_total = max(0, int(total)) - if unit is not None: - self._current_task.phase_unit = unit - if message is not None: - self._current_task.phase_message = message + if progress is not None: + self._current_task.phase_progress = max(0.0, min(float(progress), 100.0)) + if current is not None: + self._current_task.phase_current = max(0, int(current)) + if total is not None: + self._current_task.phase_total = max(0, int(total)) + if unit is not None: + self._current_task.phase_unit = unit + if message is not None: + self._current_task.phase_message = message - if commit: - await self._db_session.commit() + if commit: + await self._db_session.commit() - await self._publish_task_update(force=force) + await self._publish_task_update(force=force) @abstractmethod async def fetch(self) -> List[Dict[str, Any]]: diff --git a/backend/app/services/collectors/iptoasn.py b/backend/app/services/collectors/iptoasn.py index c0fa8c7b..634aaef8 100644 --- a/backend/app/services/collectors/iptoasn.py +++ b/backend/app/services/collectors/iptoasn.py @@ -116,16 +116,17 @@ class IPtoASNPrefixGeoCollector(BaseCollector): ] total_expected = sum(expected_sizes) if expected_sizes else 0 if total_expected > 0 and self._current_task and self._db_session: - self._current_task.total_records = total_expected - self._current_task.records_processed = 0 - self._current_task.progress = 0.0 - self._current_task.phase_progress = 0.0 - self._current_task.phase_message = "正在下载 IPtoASN 数据" - self._current_task.phase_current = 0 - self._current_task.phase_total = total_expected - self._current_task.phase_unit = "bytes" - await self._db_session.commit() - await self._publish_task_update(force=True) + async with self._get_db_commit_lock(): + self._current_task.total_records = total_expected + self._current_task.records_processed = 0 + self._current_task.progress = 0.0 + self._current_task.phase_progress = 0.0 + self._current_task.phase_message = "正在下载 IPtoASN 数据" + self._current_task.phase_current = 0 + self._current_task.phase_total = total_expected + self._current_task.phase_unit = "bytes" + await self._db_session.commit() + await self._publish_task_update(force=True) url_progress: dict[str, int] = {url: 0 for url in dataset_urls} progress_lock = asyncio.Lock() @@ -136,29 +137,29 @@ class IPtoASNPrefixGeoCollector(BaseCollector): if total_expected <= 0: return async with progress_lock: - current = max(0, downloaded_bytes) - if current < url_progress[url]: + url_downloaded = max(0, downloaded_bytes) + if url_downloaded < url_progress[url]: return - url_progress[url] = current + url_progress[url] = url_downloaded aggregated = sum(url_progress.values()) now = time.monotonic() + current = min(aggregated, total_expected) should_emit = ( - aggregated >= total_expected - or aggregated - last_emit["value"] >= min_emit_bytes - or now - last_emit["t"] >= 2.0 + (current >= total_expected and last_emit["value"] < total_expected) + or current - last_emit["value"] >= min_emit_bytes + or (current > last_emit["value"] and now - last_emit["t"] >= 2.0) ) if not should_emit: return - last_emit["value"] = aggregated + last_emit["value"] = current last_emit["t"] = now - current = min(aggregated, total_expected) - await self.update_phase_progress( - current=current, - total=total_expected, - unit="bytes", - message="正在下载 IPtoASN 数据", - ) - await self.update_progress(current, commit=True) + await self.update_phase_progress( + current=current, + total=total_expected, + unit="bytes", + message="正在下载 IPtoASN 数据", + ) + await self.update_progress(current, commit=True) dataset_paths = await asyncio.gather( *( diff --git a/backend/app/services/collectors/spacetrack.py b/backend/app/services/collectors/spacetrack.py index da5a2513..e507c0b0 100644 --- a/backend/app/services/collectors/spacetrack.py +++ b/backend/app/services/collectors/spacetrack.py @@ -52,9 +52,11 @@ class SpaceTrackTLECollector(BaseCollector): async def fetch(self) -> List[Dict[str, Any]]: from app.core.config import settings + from app.services.datasource_connectivity import resolve_spacetrack_credentials - username = settings.SPACETRACK_USERNAME - password = settings.SPACETRACK_PASSWORD + username, password, _ = await resolve_spacetrack_credentials(self._db_session) + username = username or settings.SPACETRACK_USERNAME + password = password or settings.SPACETRACK_PASSWORD if not username or not password: logger.warning_event( diff --git a/backend/app/services/credential_guides.py b/backend/app/services/credential_guides.py index 2d628cad..eddc208d 100644 --- a/backend/app/services/credential_guides.py +++ b/backend/app/services/credential_guides.py @@ -131,9 +131,36 @@ AISSTREAM_DEFAULT_GUIDE = CredentialGuideDefault( ) +SPACETRACK_DEFAULT_GUIDE = CredentialGuideDefault( + provider="spacetrack", + title="Space-Track TLE 凭证获取教程", + prompt=( + "请生成一份中文教程,指导开发者注册并获取 Space-Track.org 的账号凭证并配置到 Planet。" + "包含注册登录、遵循查询频率限制(如 GP 查询间隔)、在 Planet 采集器配置页填写用户名与密码、" + "测试连通性与常见失败排查。请以 Space-Track 当前官网文档为准。" + ), + markdown="""## Space-Track TLE 凭证获取 + +官方入口:https://www.space-track.org/ + +1. 前往 Space-Track.org 注册或登录账号。 +2. 确认账号已完成邮箱激活且可正常通过网站登录。 +3. 回到 Planet 的「采集管理 -> 采集器配置 -> `spacetrack_tle`」。 +4. 填写 `用户名` 与 `密码`(或通过环境变量 `SPACETRACK_USERNAME` / `SPACETRACK_PASSWORD` 注入)。 +5. 点击「连接测试」验证登录态与 TLE 查询接口后点击「保存」。 + +### 注意事项 + +- Space-Track 对 GP 数据接口有严格的限频策略,请避免高频手动重复抓取。 +- 本源使用表单会话登录(`/ajaxauth/login`),不要将账号密码当作普通 HTTP Basic Header 暴露。 +""", +) + + DEFAULT_CREDENTIAL_GUIDES = { BARENTSWATCH_DEFAULT_GUIDE.provider: BARENTSWATCH_DEFAULT_GUIDE, AISSTREAM_DEFAULT_GUIDE.provider: AISSTREAM_DEFAULT_GUIDE, + SPACETRACK_DEFAULT_GUIDE.provider: SPACETRACK_DEFAULT_GUIDE, } diff --git a/backend/app/services/datasource_connectivity.py b/backend/app/services/datasource_connectivity.py index db18342d..aba0069f 100644 --- a/backend/app/services/datasource_connectivity.py +++ b/backend/app/services/datasource_connectivity.py @@ -3,10 +3,13 @@ from __future__ import annotations from datetime import UTC, datetime +import csv import hashlib +import io import json import os from typing import Any +from urllib.parse import urlparse import httpx from sqlalchemy import func, select @@ -17,6 +20,7 @@ from app.core.enums import JobStatus from app.models.collected_data import CollectedData from app.models.datasource import DataSource from app.models.datasource_config import DataSourceConfig +from app.models.earth_news import EarthNewsItem from app.models.system_setting import SystemSetting from app.services.barentswatch import ( BarentsWatchConfig, @@ -29,6 +33,26 @@ from app.services.barentswatch import ( CONNECTIVITY_VALIDATION_KEY = "connectivity_validation" CONNECTIVITY_STORE_CATEGORY = "datasource_connectivity_validations" SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream"} +_ARCGIS_SOURCES = frozenset( + {"arcgis_cables", "arcgis_landing_points", "arcgis_cable_landing_relation"} +) +_EPOCH_CSV_URL = "https://epoch.ai/data/gpu_clusters.csv" + + +def _is_masked_secret(value: Any) -> bool: + if not isinstance(value, str): + return False + stripped = value.strip() + return bool(stripped) and set(stripped) <= {"•", "*"} + + +def _clean_override_value(override: dict[str, str] | None, key: str, *, secret: bool = False) -> str: + if not isinstance(override, dict): + return "" + raw = str(override.get(key) or "").strip() + if not raw or (secret and _is_masked_secret(raw)): + return "" + return raw def _sha256_json(payload: Any) -> str: @@ -46,26 +70,68 @@ def _resolve_spacetrack_credentials() -> tuple[str, str, str]: return username, password, source or "missing" -def _resolve_spacetrack_credentials_with_override( +async def resolve_spacetrack_credentials( + db=None, credential_override: dict[str, str] | None = None, ) -> tuple[str, str, str]: - if credential_override and ( - credential_override.get("username") or credential_override.get("password") - ): - return ( - str(credential_override.get("username") or ""), - str(credential_override.get("password") or ""), - "draft", - ) - return _resolve_spacetrack_credentials() + """Resolve Space-Track credentials (`draft override -> DataSourceConfig -> env -> ~/.zshrc`).""" + db_user = "" + db_pass = "" + if db is not None and hasattr(db, "execute"): + try: + result = await db.execute( + select(DataSourceConfig) + .where(DataSourceConfig.name == "spacetrack_tle") + .where(DataSourceConfig.is_active.is_(True)) + ) + record = result.scalar_one_or_none() + if record is not None: + auth_cfg = record.auth_config or {} + runtime_cfg = record.config or {} + db_user = str(auth_cfg.get("username") or runtime_cfg.get("username") or "").strip() + db_pass = str(auth_cfg.get("password") or runtime_cfg.get("password") or "").strip() + except Exception: + db_user = "" + db_pass = "" + + env_user, env_pass, env_source = _resolve_spacetrack_credentials() + username = db_user or env_user + password = db_pass or env_pass + source = "datasource_config" if (db_user or db_pass) else env_source + + ov_user = _clean_override_value(credential_override, "username") + ov_pass = _clean_override_value(credential_override, "password", secret=True) + if ov_user or ov_pass: + return ov_user or username, ov_pass or password, "draft" + return username, password, source or "missing" + + +async def _resolve_barentswatch_with_override( + db, + endpoint: str, + credential_override: dict[str, str] | None = None, +) -> BarentsWatchConfig: + """Resolve BarentsWatch credentials merging partial draft overrides with saved config.""" + saved = await resolve_barentswatch_config(db) + ov_id = _clean_override_value(credential_override, "client_id") + ov_secret = _clean_override_value(credential_override, "client_secret", secret=True) + has_override = bool(ov_id or ov_secret) + return BarentsWatchConfig( + endpoint=str(endpoint or "").strip() or saved.endpoint, + client_id=ov_id or saved.client_id, + client_secret=ov_secret or saved.client_secret, + credential_source="draft" if has_override else saved.credential_source, + endpoint_source="draft" if str(endpoint or "").strip() else saved.endpoint_source, + ) async def _resolve_aisstream_api_key( db=None, credential_override: dict[str, str] | None = None, ) -> tuple[str, str]: - if credential_override and credential_override.get("api_key"): - return str(credential_override["api_key"]), "draft" + ov_key = _clean_override_value(credential_override, "api_key", secret=True) + if ov_key: + return ov_key, "draft" env_key = os.getenv("AISSTREAM_API_KEY") zshrc_key = _read_zshrc_env().get("AISSTREAM_API_KEY") @@ -125,15 +191,12 @@ async def build_builtin_connectivity_checksum( has_credentials = not defaults.get("requires_credentials", False) if credential_provider == "barentswatch": - if credential_override: - client_id = credential_override.get("client_id", "") - client_secret = credential_override.get("client_secret", "") - credential_source = "draft" - else: - barentswatch_config = await resolve_barentswatch_config(db) - client_id = barentswatch_config.client_id - client_secret = barentswatch_config.client_secret - credential_source = barentswatch_config.credential_source + barentswatch_config = await _resolve_barentswatch_with_override( + db, endpoint, credential_override + ) + client_id = barentswatch_config.client_id + client_secret = barentswatch_config.client_secret + credential_source = barentswatch_config.credential_source has_credentials = bool(client_id and client_secret) credential_fingerprint = _sha256_json( { @@ -142,8 +205,8 @@ async def build_builtin_connectivity_checksum( } ) elif credential_provider == "spacetrack": - username, password, credential_source = _resolve_spacetrack_credentials_with_override( - credential_override + username, password, credential_source = await resolve_spacetrack_credentials( + db, credential_override ) has_credentials = bool(username and password) credential_fingerprint = _sha256_json( @@ -176,6 +239,113 @@ async def build_builtin_connectivity_checksum( } +def _prepare_builtin_http_probe( + source: str, + endpoint: str, + headers: dict[str, str], +) -> tuple[str, Any, dict[str, str]]: + """Build lightweight protocol-accurate probe URL, params, and headers for a built-in source.""" + probe_url = str(endpoint or "").strip() + probe_params: Any = None + probe_headers = dict(headers) + + if source == "bgpstream_bgp": + base = probe_url.rstrip("/") + probe_url = base if base.endswith("/data") else f"{base}/data" + end = int(datetime.now(UTC).timestamp()) - 3600 + start = end - 3600 + probe_params = [ + ("projects[]", "routeviews"), + ("collectors[]", "route-views2"), + ("types[]", "updates"), + ("intervals[]", f"{start},{end}"), + ] + probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)") + elif source == "celestrak_tle": + if "?" not in probe_url: + probe_params = {"CATNR": "25544", "FORMAT": "json"} + elif source in _ARCGIS_SOURCES: + if probe_url.rstrip("/").endswith("/query") and "f=" not in probe_url: + probe_params = {"where": "1=1", "returnCountOnly": "true", "f": "json"} + elif source == "epoch_ai_gpu": + parsed = urlparse(probe_url) + if parsed.hostname == "epoch.ai" and not parsed.path.endswith(".csv"): + probe_url = _EPOCH_CSV_URL + elif source == "ris_live_bgp": + probe_headers.setdefault( + "X-RIS-Subscribe", + json.dumps({"host": "rrc00", "type": "UPDATE", "require": "announcements"}), + ) + probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)") + return probe_url, probe_params, probe_headers + + +async def _read_bounded_probe_bytes(response: httpx.Response, limit: int = 65536) -> bytes: + chunks: list[bytes] = [] + size = 0 + async for chunk in response.aiter_bytes(): + chunks.append(chunk) + size += len(chunk) + if size >= limit: + break + return b"".join(chunks)[:limit] + + +async def _validate_builtin_probe_response(source: str, response: httpx.Response) -> str | None: + """Validate response content for sources that return HTTP 200 even on invalid queries.""" + if source == "ris_live_bgp": + first_line = "" + async for line in response.aiter_lines(): + stripped = line.strip() + if stripped: + first_line = stripped + break + if not first_line: + return "RIS Live 流未返回任何有效消息。" + try: + payload = json.loads(first_line) + except json.JSONDecodeError: + return "RIS Live 返回非 JSON 响应。" + return None if isinstance(payload, dict) else "RIS Live 响应结构异常。" + + if source not in _ARCGIS_SOURCES | {"bgpstream_bgp", "celestrak_tle", "epoch_ai_gpu"}: + return None + + limit = 4096 if source == "epoch_ai_gpu" else 65536 + raw = await _read_bounded_probe_bytes(response, limit=limit) + text = raw.decode(response.encoding or "utf-8", errors="replace").lstrip("\ufeff").strip() + + if source == "epoch_ai_gpu": + if text.lower().startswith(("{"camera_hint":{"lat":28.0,"lon":128.0},' + '"influence_zones":[{"id":"apec-core","label":"核心与会国","color":"#ef4444",' + '"opacity":0.62,"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"west_to_east"},' + '"shape":{"mode":"countries","countries":["CHN","USA","RUS"]}}]}' + ), + } + yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 64}} + + app = FastAPI() + app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness") + app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb() + app.dependency_overrides[get_ai_provider_client] = lambda: _SceneStreamingClient() + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + res = await client.post( + "/api/v1/situational-awareness/sessions/stateless/turns/stream", + json={ + "question": "请分析这条国际新闻:「APEC 中美俄元首会晤」在地缘上的影响范围", + "domain": "news", + "news_context": { + "id": "apec-1", + "title": "APEC 中美俄元首会晤", + "summary": "中美俄三方会晤与亚太经济体协同", + "source": "Reuters", + "region": "亚太", + }, + }, + ) + assert res.status_code == 200 + events = _parse_sse_text(res.text) + text_deltas = "".join(data["delta"] for name, data in events if name == "text") + assert "" not in text_deltas + assert "APEC 峰会影响聚焦中美俄及亚太经济体" in text_deltas + + scene_events = [data for name, data in events if name == "scene"] + assert len(scene_events) == 1 + zones = scene_events[0]["scene_spec"]["influence_zones"] + assert len(zones) == 1 + assert zones[0]["id"] == "apec-core" + assert zones[0]["shape"]["countries"] == ["CHN", "USA", "RUS"] + + done_ev = events[-1][1] + assert "" not in done_ev["answer_markdown"] + assert done_ev["scene_spec"]["camera_hint"]["lat"] == 28.0 + + validated = SceneSpec.model_validate({ + "domain": "global", + "influence_zones": zones, + }) + assert validated.influence_zones[0].edge.style == "sharp" + + +@pytest.mark.asyncio +async def test_workflow_dag_stream_emits_influence_zones_for_red_sea_news(monkeypatch): + reset_stream_quota_ledger() + + class _EmptyScalarResult: + def scalar_one_or_none(self): + return None + + class _DagStubDb(_StubDb): + async def execute(self, *_args, **_kwargs): + return _EmptyScalarResult() + + async def fake_global_tool(*_args, **_kwargs): + return {"domain": "global", "domain_summaries": [], "evidence": {}} + + async def fake_recent_news(*_args, **_kwargs): + return { + "domain": "news", + "available": True, + "count": 1, + "items": [{"id": "n-redsea", "title": "红海安全成为埃及与索马里军方会谈重点"}], + "evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Red Sea News"}}, + } + + monkeypatch.setattr("app.services.ai.dag_executor.query_global_situational_tool", fake_global_tool) + monkeypatch.setattr("app.services.ai.dag_executor.query_recent_earth_news_tool", fake_recent_news) + monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool) + monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news) + + captured_requests = [] + + class _DagSceneClient(AIProviderClient): + def __init__(self): + super().__init__( + service_url="http://aiprovider.test", + llm_config={ + "provider": "minimax", + "provider_api": "anthropic-messages", + "base_url": "https://api.minimaxi.com/anthropic", + "api_key": "secret-key", + "model": "MiniMax-M3.1-Flash", + }, + ) + + async def stream_analyze(self, payload, request_id=None): + captured_requests.append(payload) + yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"} + yield {"event": "text", "delta": "红海安全会谈核心涉及埃及与索马里及曼德海峡航道。\n{"camera_hint":{"lat":18.0,"lon":39.0},"influence_zones":[' + '{"id":"redsea-corridor","label":"红海—曼德海峡走廊","color":"#38bdf8","opacity":0.28,' + '"edge":{"style":"soft"},"animation":{"type":"radial"},' + '"shape":{"mode":"circle","center":[15.5,42.5],"radius_km":950}},' + '{"id":"egy-som","label":"埃及与索马里","color":"#f59e0b","opacity":0.55,' + '"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"north_to_south"},' + '"shape":{"mode":"countries","countries":["EGY","SOM"]}}]}' + ), + } + yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash"} + + app = FastAPI() + app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness") + app.dependency_overrides[situational_awareness.get_db] = lambda: _DagStubDb() + app.dependency_overrides[get_ai_provider_client] = lambda: _DagSceneClient() + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + res = await client.post( + "/api/v1/situational-awareness/sessions/stateless/turns/stream", + json={ + "question": "该事件影响范围?", + "domain": "news", + "workflow_id": "earth.news.analysis", + }, + ) + assert res.status_code == 200 + events = _parse_sse_text(res.text) + text_deltas = "".join(data["delta"] for name, data in events if name == "text") + assert "" not in text_deltas + assert "红海安全会谈核心涉及埃及与索马里" in text_deltas + + scene_events = [data for name, data in events if name == "scene"] + assert len(scene_events) == 1 + zones = scene_events[0]["scene_spec"]["influence_zones"] + assert [z["id"] for z in zones] == ["redsea-corridor", "egy-som"] + + done_ev = events[-1][1] + assert "" not in done_ev["answer_markdown"] + assert len(done_ev["scene_spec"]["influence_zones"]) == 2 + assert captured_requests and "scene_overlay_guidance" in captured_requests[0].context + assert "" in (captured_requests[0].system_prompt or "") + + +def test_scene_directives_tolerate_code_fences_and_llm_field_quirks(): + from app.services.ai.scene_directives import extract_planet_scene_from_text + from app.services.ai.workflow_runtime import validate_influence_zones + + raw = ( + "直接影响地区为中国市场。\n" + "\n" + "```json\n" + "{\n" + ' "influence_zones": [\n' + " {\n" + ' "name": "直接影响:中国",\n' + ' "color": "red",\n' + ' "edge": {"style": "sharp", "opacity": 0.55, "extra_ignored": true},\n' + ' "animation": "sweep",\n' + ' "countries": "CHN",\n' + ' "extra_note": "ignore me",\n' + " },\n" + " {\n" + ' "id": "corridor",\n' + ' "color": "#38b",\n' + ' "opacity": 1.4,\n' + ' "shape": {"mode": "circle", "center": {"lat": 15.5, "lon": 42.5}, "radius_km": 5}\n' + " },\n" + " ],\n" + ' "camera_hint": {"lat": 35.0, "lon": 104.0}\n' + "}\n" + "```\n" + "" + ) + cleaned, parsed = extract_planet_scene_from_text(raw) + assert cleaned == "直接影响地区为中国市场。" + assert parsed is not None + assert parsed["camera_hint"] == {"lat": 35.0, "lon": 104.0} + zones = parsed["influence_zones"] + assert len(zones) == 2 + assert zones[0]["label"] == "直接影响:中国" + assert zones[0]["color"] == "#ef4444" + assert zones[0]["opacity"] == pytest.approx(0.55) + assert zones[0]["edge"]["style"] == "sharp" + assert zones[0]["animation"]["type"] == "sweep" + assert zones[0]["shape"]["mode"] == "countries" + assert zones[0]["shape"]["countries"] == ["CHN"] + + assert zones[1]["color"] == "#3388bb" + assert zones[1]["opacity"] == pytest.approx(0.9) + assert zones[1]["shape"]["center"] == [15.5, 42.5] + assert zones[1]["shape"]["radius_km"] == pytest.approx(20.0) + + # Also test validate_influence_zones directly with edge string + flat region_preset + direct = validate_influence_zones( + [{"id": "apec", "color": "#f59e0b", "edge": "soft", "region_preset": "APEC"}] + ) + assert len(direct) == 1 + assert direct[0].edge.style == "soft" + assert direct[0].shape.mode == "region_preset" + assert direct[0].shape.region_preset == "APEC" + + +def test_validate_influence_zones_normalizes_dprk_presets_polygons_and_rejects_empty(): + from app.services.ai.workflow_runtime import validate_influence_zones + + zones = validate_influence_zones( + [ + {"id": "core", "color": "red", "countries": ["CHN", "DPRK", "朝鲜", "KP"]}, + {"id": "ne-asia", "color": "amber", "region_preset": "东北亚"}, + {"id": "ne-asia-en", "color": "amber", "shape": {"mode": "region_preset", "region_preset": "northeast-asia"}}, + {"id": "poly2d", "color": "#38bdf8", "coordinates": [[120.0, 35.0], [126.0, 35.0], [126.0, 40.0]]}, + {"id": "unknown-preset", "color": "#38bdf8", "shape": {"mode": "region_preset", "region_preset": "MARS_BELT"}}, + {"id": "empty-countries", "color": "#ef4444", "shape": {"mode": "countries", "countries": []}}, + ] + ) + assert [z.id for z in zones] == ["core", "ne-asia", "ne-asia-en", "poly2d"] + assert zones[0].shape.countries == ["CHN", "PRK"] + assert zones[1].shape.mode == "region_preset" + assert zones[1].shape.region_preset == "NORTHEAST_ASIA" + assert zones[2].shape.region_preset == "NORTHEAST_ASIA" + assert zones[3].shape.mode == "polygon" + assert len(zones[3].shape.coordinates) == 1 + assert len(zones[3].shape.coordinates[0]) == 3 + + +@pytest.mark.asyncio +async def test_stream_turn_cooperative_cancel_stops_stream_and_preserves_session_memory(monkeypatch): + from types import SimpleNamespace + import app.services.ai.stream_turn as st_mod + from app.services.ai.workflow_runtime import cancel_active_run_handle + from app.services.ai.access_policy import AccessContext + + async def _fake_recent_news(*_args, **_kwargs): + return {"items": [], "evidence": {}} + + async def _fake_global_tool(*_args, **_kwargs): + return {"domain_summaries": [], "evidence": {}} + + monkeypatch.setattr(st_mod, "query_recent_earth_news_tool", _fake_recent_news) + monkeypatch.setattr(st_mod, "query_global_situational_tool", _fake_global_tool) + + class FakeSlowClient: + llm_config = {"provider": "minimax", "model": "MiniMax-M3.1-Flash", "max_tokens": 4096} + + async def is_ready(self): + return True, "minimax", "MiniMax-M3.1-Flash" + + async def stream_analyze(self, req, request_id=None): + yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"} + yield {"event": "text", "delta": "first chunk "} + # Simulate cooperative cancel triggered by overlapping turn before finishing + assert cancel_active_run_handle(request_id) is True + yield {"event": "text", "delta": "should not appear"} + yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash", "usage": {}} + + class DummyDb: + async def commit(self): + return None + + session = SimpleNamespace( + id="sess-cancel-test", + context_state={"recent_messages": [{"role": "user", "content": "keep me"}], "domain": "news"}, + pinned_items=[], + ) + access = AccessContext(tier="public_zero_cost", actor_key="test-actor", hourly_paid_quota=100) + events = [] + async for raw_ev in st_mod.stream_session_turn( + DummyDb(), + request=None, + session=session, + question="旧提问", + context_override={"domain": "news"}, + news_context={"id": "n1", "title": "中朝关系", "source": "BBC World"}, + access=access, + ai_client=FakeSlowClient(), + client_run_id="run-cancel-1", + ): + events.append(raw_ev) + + joined = "".join(events) + assert "should not appear" not in joined + assert "event: done" not in joined + assert session.context_state["recent_messages"] == [{"role": "user", "content": "keep me"}] diff --git a/backend/tests/test_datasource_collector_fixes.py b/backend/tests/test_datasource_collector_fixes.py new file mode 100644 index 00000000..ac3fb764 --- /dev/null +++ b/backend/tests/test_datasource_collector_fixes.py @@ -0,0 +1,414 @@ +"""Regression tests for collector auth_type, secret persistence, Space-Track config, and probes.""" + +from __future__ import annotations + +import asyncio +import gzip +from types import SimpleNamespace + +import httpx +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import create_engine, select +from sqlalchemy.orm import sessionmaker + +from app.core.enums import AuthType +from app.core.security import get_current_user +from app.core.websocket.broadcaster import broadcaster +from app.db.session import Base, get_db +from app.main import app +from app.models.collected_data import CollectedData +from app.models.datasource import DataSource +from app.models.datasource_config import DataSourceConfig +from app.models.earth_news import EarthNewsItem +from app.models.system_setting import SystemSetting +from app.services import datasource_connectivity +from app.services.collectors.base import BaseCollector +from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector +from app.services.collectors.spacetrack import SpaceTrackTLECollector + + +class _SyncAsAsyncSession: + def __init__(self, sync_session): + self._s = sync_session + + def add(self, obj): + return self._s.add(obj) + + async def execute(self, stmt, *args, **kwargs): + return self._s.execute(stmt, *args, **kwargs) + + async def scalar(self, stmt, *args, **kwargs): + return self._s.scalar(stmt, *args, **kwargs) + + async def get(self, model, ident): + return self._s.get(model, ident) + + async def delete(self, obj): + return self._s.delete(obj) + + async def commit(self): + return self._s.commit() + + async def rollback(self): + return self._s.rollback() + + async def refresh(self, obj): + return self._s.refresh(obj) + + async def close(self): + return self._s.close() + + +def _make_db(): + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all( + engine, + tables=[ + DataSourceConfig.__table__, + DataSource.__table__, + CollectedData.__table__, + SystemSetting.__table__, + EarthNewsItem.__table__, + ], + ) + sync_factory = sessionmaker(engine, expire_on_commit=False) + + class _Ctx: + def __call__(self): + return self + + async def __aenter__(self): + self._sess = _SyncAsAsyncSession(sync_factory()) + return self._sess + + async def __aexit__(self, *_args): + await self._sess.close() + + return engine, _Ctx() + + +def _mock_httpx_factory(handler): + real_async_client = httpx.AsyncClient + transport = httpx.MockTransport(handler) + + def _factory(*_args, **kwargs): + kwargs.pop("follow_redirects", None) + kwargs["transport"] = transport + return real_async_client(**kwargs) + + return _factory + + +@pytest.mark.asyncio +async def test_barentswatch_oauth_client_accepted_and_partial_update_preserves_secret(monkeypatch): + assert AuthType.OAUTH_CLIENT.value == "oauth_client" + engine, factory = _make_db() + captured: dict = {} + + def handler(request: httpx.Request) -> httpx.Response: + captured["urls"] = [*captured.get("urls", []), str(request.url)] + if "barentswatch.no/connect/token" in str(request.url): + captured["token_body"] = request.content.decode() + return httpx.Response(200, json={"access_token": "tok_test_123"}) + captured["auth_header"] = request.headers.get("Authorization") + return httpx.Response(200, json=[]) + + monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler)) + + async def override_db(): + async with factory() as session: + yield session + + def override_user(): + return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") + + app.dependency_overrides[get_db] = override_db + app.dependency_overrides[get_current_user] = override_user + try: + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + # 1. Create BarentsWatch config with auth_type=oauth_client (previously 422) + create_resp = await client.post( + "/api/v1/datasources/configs", + json={ + "name": "barentswatch_vessels", + "source_type": "api", + "endpoint": "https://live.ais.barentswatch.no/v1/latest/combined", + "auth_type": "oauth_client", + "auth_config": {"client_id": "id-1", "client_secret": "real-secret-1"}, + }, + ) + assert create_resp.status_code == 200, create_resp.text + cfg_id = create_resp.json()["id"] + + # 2. Partial PUT updating client_id (omitting masked client_secret) preserves real-secret-1 + put_resp = await client.put( + f"/api/v1/datasources/configs/{cfg_id}", + json={ + "endpoint": "https://live.ais.barentswatch.no/v1/latest/combined", + "auth_type": "oauth_client", + "auth_config": {"client_id": "id-2", "client_secret": "••••••••"}, + }, + ) + assert put_resp.status_code == 200, put_resp.text + + async with factory() as db: + row = (await db.execute(select(DataSourceConfig).where(DataSourceConfig.id == cfg_id))).scalar_one() + assert row.auth_config["client_id"] == "id-2" + assert row.auth_config["client_secret"] == "real-secret-1" + + # 3. Builtin connect with partial auth_config uses merged saved secret + conn_resp = await client.post( + "/api/v1/datasources/configs/builtin/connect", + json={ + "name": "barentswatch_vessels", + "source_type": "api", + "endpoint": "https://live.ais.barentswatch.no/v1/latest/combined", + "auth_type": "oauth_client", + "auth_config": {"client_id": "id-2"}, + }, + ) + assert conn_resp.status_code == 200, conn_resp.text + assert conn_resp.json()["success"] is True + assert "client_secret=real-secret-1" in captured["token_body"] + assert captured["auth_header"] == "Bearer tok_test_123" + finally: + app.dependency_overrides.clear() + engine.dispose() + + +@pytest.mark.asyncio +async def test_spacetrack_collector_uses_saved_database_credentials(monkeypatch): + engine, factory = _make_db() + monkeypatch.delenv("SPACETRACK_USERNAME", raising=False) + monkeypatch.delenv("SPACETRACK_PASSWORD", raising=False) + monkeypatch.setattr(datasource_connectivity, "_read_zshrc_env", lambda: {}) + posted: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST" and "ajaxauth/login" in str(request.url): + posted.append(request.content.decode()) + return httpx.Response(200, text="{}") + if request.method == "GET" and str(request.url).rstrip("/").endswith("space-track.org"): + return httpx.Response(200, text="ok") + return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}]) + + monkeypatch.setattr("app.services.collectors.spacetrack.httpx.AsyncClient", _mock_httpx_factory(handler)) + + try: + async with factory() as db: + db.add( + DataSourceConfig( + name="spacetrack_tle", + source_type="api", + endpoint="https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json", + auth_type="basic", + auth_config={"username": "db-user", "password": "db-password"}, + is_active=True, + ) + ) + await db.commit() + collector = SpaceTrackTLECollector() + collector._db_session = db + collector._resolved_url = "https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json" + rows = await collector.fetch() + assert rows == [{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}] + assert posted and "identity=db-user" in posted[0] and "password=db-password" in posted[0] + finally: + engine.dispose() + + +@pytest.mark.asyncio +async def test_builtin_connectivity_probes_match_collector_protocols(monkeypatch): + seen_requests: list[tuple[str, dict[str, str]]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + url = str(request.url) + seen_requests.append((url, dict(request.headers))) + if "broker.bgpstream.caida.org" in url: + if url.endswith("/v2"): + return httpx.Response(404) + return httpx.Response(200, json={"error": None, "data": {"resources": []}}) + if "celestrak.org" in url: + if "CATNR=25544" not in url: + return httpx.Response(200, text='Invalid query: ""') + return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544}]) + if "services.arcgis.com" in url: + if "f=json" not in url: + return httpx.Response(200, text="ArcGIS HTML") + return httpx.Response(200, json={"count": 42}) + if "epoch.ai" in url: + if url.endswith("gpu-clusters"): + return httpx.Response(200, text="", headers={"content-type": "text/html"}) + return httpx.Response(200, text="Name,Country,Status\nFrontier,USA,Active\n", headers={"content-type": "text/csv"}) + if "ris-live.ripe.net" in url: + assert "x-ris-subscribe" in request.headers + return httpx.Response(200, text='{"type":"ris_message","data":{}}\n', headers={"content-type": "application/x-ndjson"}) + return httpx.Response(404) + + monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler)) + + engine, factory = _make_db() + try: + async with factory() as db: + for source, endpoint in [ + ("bgpstream_bgp", "https://broker.bgpstream.caida.org/v2"), + ("celestrak_tle", "https://celestrak.org/NORAD/elements/gp.php"), + ("arcgis_cables", "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query"), + ("epoch_ai_gpu", "https://epoch.ai/data/gpu-clusters"), + ("ris_live_bgp", "https://ris-live.ripe.net/v1/stream/?format=json&client=planet-ris-live"), + ("media_news_archive", ""), + ]: + res = await datasource_connectivity.test_builtin_connectivity( + source, endpoint, "none", {}, {"timeout": 10}, db=db + ) + assert res["success"] is True, (source, res) + + assert any("/v2/data?" in url and "intervals%5B%5D=" in url for url, _ in seen_requests) + + # Reject fake HTTP 200 responses when content fails validation (e.g., ArcGIS/CelesTrak bad params) + bad_arcgis = await datasource_connectivity.test_builtin_connectivity( + "arcgis_cables", + "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query?f=html", + "none", + {}, + {"timeout": 10}, + ) + assert bad_arcgis["success"] is False + + bad_celestrak = await datasource_connectivity.test_builtin_connectivity( + "celestrak_tle", + "https://celestrak.org/NORAD/elements/gp.php?BAD=1", + "none", + {}, + {"timeout": 10}, + ) + assert bad_celestrak["success"] is False + finally: + engine.dispose() + + +class _StrictNonConcurrentSession: + """Fake AsyncSession that fails immediately if commit() is entered concurrently.""" + + def __init__(self, task: SimpleNamespace) -> None: + self.task = task + self._in_commit = False + self.active_commits = 0 + self.max_concurrent_commits = 0 + self.commit_count = 0 + self.committed_progress: list[int] = [] + + async def commit(self) -> None: + if self._in_commit: + raise RuntimeError("concurrent operations are not permitted") + self._in_commit = True + self.active_commits += 1 + self.max_concurrent_commits = max(self.max_concurrent_commits, self.active_commits) + try: + self.committed_progress.append(int(self.task.records_processed or 0)) + await asyncio.sleep(0.01) + self.commit_count += 1 + finally: + self.active_commits -= 1 + self._in_commit = False + + +def _make_task_stub(task_id: int = 29) -> SimpleNamespace: + return SimpleNamespace( + id=task_id, + status="running", + phase="downloading", + phase_progress=0.0, + phase_message="", + phase_current=0, + phase_total=0, + phase_unit="bytes", + progress=0.0, + records_processed=0, + total_records=0, + started_at=None, + completed_at=None, + error_message=None, + ) + + +@pytest.mark.asyncio +async def test_iptoasn_parallel_download_progress_serializes_db_commits(tmp_path, monkeypatch): + v4_path = tmp_path / "ip2asn-v4.tsv.gz" + v6_path = tmp_path / "ip2asn-v6.tsv.gz" + with gzip.open(v4_path, "wt", encoding="utf-8") as f: + f.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n") + with gzip.open(v6_path, "wt", encoding="utf-8") as f: + f.write("2606:4700::\t2606:4700::ffff\t13335\tUS\tCLOUDFLARENET\n") + + async def _noop_broadcast(_payload): + return None + + monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast) + + collector = IPtoASNPrefixGeoCollector() + task = _make_task_stub(task_id=29) + strict_session = _StrictNonConcurrentSession(task) + collector._resolved_url = "https://iptoasn.com/data/ip2asn-combined.tsv.gz" + collector._db_session = strict_session + collector._current_task = task + + async def _fake_fetch_remote_info(_client, _url): + return {"content_length": 10_000_000} + + async def _fake_download_dataset_file(_client, url, *, progress_callback=None): + for step in (2_500_000, 5_000_000, 7_500_000, 10_000_000, 10_000_000): + if progress_callback: + await progress_callback(step, 10_000_000) + await asyncio.sleep(0) + return v4_path if "v4" in url else v6_path + + async def _no_short_circuit(_db, *, file_sha256): + return None + + monkeypatch.setattr(collector._downloader, "fetch_remote_info", _fake_fetch_remote_info) + monkeypatch.setattr(collector, "_download_dataset_file", _fake_download_dataset_file) + monkeypatch.setattr(collector, "_can_short_circuit_unchanged_file", _no_short_circuit) + + rows = await collector.fetch() + + assert len(rows) == 2 + assert {row["asn"] for row in rows} == {"13335"} + assert strict_session.max_concurrent_commits == 1 + assert strict_session.commit_count >= 2 + assert strict_session.committed_progress == sorted(strict_session.committed_progress) + assert collector._current_task.records_processed == 20_000_000 + + +@pytest.mark.asyncio +async def test_base_collector_serializes_concurrent_progress_and_phase_commits(monkeypatch): + class _DummyCollector(BaseCollector): + name = "dummy_concurrent_collector" + + async def fetch(self): + return [] + + async def _noop_broadcast(_payload): + return None + + monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast) + + collector = _DummyCollector() + task = _make_task_stub(task_id=30) + task.total_records = 10 + strict_session = _StrictNonConcurrentSession(task) + collector._current_task = task + collector._db_session = strict_session + + await asyncio.gather( + collector.update_progress(1, commit=True, force=True), + collector.update_phase_progress(current=2, total=10, unit="rows", message="step 2", commit=True, force=True), + collector.set_phase("downloading", message="step 3"), + collector.update_progress(4, commit=True, force=True), + collector.update_phase_progress(current=5, total=10, unit="rows", message="step 5", commit=True, force=True), + collector.set_phase("parsing", message="step 6"), + ) + + assert strict_session.max_concurrent_commits == 1 + assert strict_session.commit_count == 6 diff --git a/backend/tests/test_workflow_evolver.py b/backend/tests/test_workflow_evolver.py index 1be3938c..3bd7f6ce 100644 --- a/backend/tests/test_workflow_evolver.py +++ b/backend/tests/test_workflow_evolver.py @@ -102,6 +102,21 @@ async def _make_sqlite_session(): return engine, _Ctx() +async def _add_graded_fixture(client, workflow_id: str) -> None: + """Graded fixture that the deterministic (no-AI) fallback answer satisfies on both A/B sides.""" + resp = await client.post( + f"/api/v1/ai/workflows/{workflow_id}/fixtures", + json={ + "name": "Graded baseline", + "sample_question": "全球态势摘要", + "context_json": {"domain": "global"}, + "expect": {"must_include": ["全球态势摘要"]}, + }, + ) + assert resp.status_code == 200 + assert resp.json()["context_json"]["expect"] == {"must_include": ["全球态势摘要"]} + + @pytest.mark.asyncio async def test_meta_workflow_seeded_excluded_from_public_and_single_level_recursion_locked(): engine, factory = await _make_sqlite_session() @@ -316,15 +331,15 @@ async def test_evolution_policy_feedback_health_model_drift_and_dgm_archive(monk assert health["model_drift_detected"] is True assert "query_global_situational" in health["unused_tools"] - # 4. Propose `model_adapt` (deterministic fallback fills minimal patch) + # 4. Model explicitly returns an empty patch -> the engine must accept "no change" prop_resp = await client.post( "/api/v1/ai/evolution/propose/default.general", json={"mode": "model_adapt", "apply_mode": "preview"}, ) assert prop_resp.status_code == 200 prop = prop_resp.json() - assert prop["constitution_ok"] is True - assert len(prop["changes"]) >= 1 + assert prop["applied_status"] == "no_change" + assert prop["changes"] == [] # 5. Incubate new custom workflow from `default.general` BGP runs inc_resp = await client.post("/api/v1/ai/evolution/incubate") @@ -377,6 +392,8 @@ async def test_canary_auto_rollback_and_meta_canary_rollback(monkeypatch): assert meta_pub.json()["applied_status"] == "auto_published" assert meta_pub.json()["new_revision"] == 2 + # Auto-publish requires a graded fixture A/B gate + await _add_graded_fixture(client, "default.general") # Auto-publish default.general v2 (uses live meta v2) evo_pub = await client.post( "/api/v1/ai/evolution/propose/default.general", @@ -548,6 +565,7 @@ async def test_lock_quota_cooldown_dgm_branching_canary_verify_and_ledger_dismis "/api/v1/ai/evolution/policy", json={"locked_workflows": [], "daily_auto_budget": 2}, ) + await _add_graded_fixture(client, "default.general") pub1 = await client.post( "/api/v1/ai/evolution/propose/default.general", json={"mode": "optimize", "instruction": "Always cite verified telemetry", "apply_mode": "auto"}, diff --git a/backend/tests/test_workflow_review_regressions.py b/backend/tests/test_workflow_review_regressions.py new file mode 100644 index 00000000..b01f2546 --- /dev/null +++ b/backend/tests/test_workflow_review_regressions.py @@ -0,0 +1,609 @@ +"""Regression tests for the v0.82.0 workflow review: Earth DAG data/evidence/card output and evolver safety.""" + +from __future__ import annotations + +import copy +import json +from types import SimpleNamespace + +import pytest +from sqlalchemy import create_engine, event, select +from sqlalchemy.orm import sessionmaker + +from app.db.session import Base +from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision +from app.models.bgp_incident import BGPIncident +from app.models.collected_data import CollectedData +from app.models.earth_news import EarthNewsItem +from app.models.situational_assessment import WorkflowRun +from app.models.system_setting import SystemSetting +from app.services.ai import dag_executor +from app.services.ai.dag_executor import _execute_tool, run_workflow_dag_stream +from app.services.ai.workflow_evolver import ( + META_WORKFLOW_ID, + _load_ledger_entries, + append_ledger_entry, + build_business_evolution_request, + evaluate_canary_and_maybe_rollback, + grade_fixture_result, + propose_meta_evolution, + propose_workflow_evolution, + run_fixture_ab_eval, + update_evolution_policy, +) +from app.services.ai.workflow_registry import ( + _fallback_workflow_dict, + create_workflow, + discard_workflow_draft, + ensure_builtin_workflows, + list_public_workflow_bindings, + publish_workflow, + rollback_workflow, + save_workflow_draft, +) + + +class _SyncAsAsyncSession: + def __init__(self, sync_session): + self._s = sync_session + + def add(self, obj): + return self._s.add(obj) + + async def execute(self, stmt, *args, **kwargs): + return self._s.execute(stmt, *args, **kwargs) + + async def scalar(self, stmt, *args, **kwargs): + return self._s.scalar(stmt, *args, **kwargs) + + async def get(self, model, ident): + return self._s.get(model, ident) + + async def delete(self, obj): + return self._s.delete(obj) + + async def flush(self): + return self._s.flush() + + async def commit(self): + return self._s.commit() + + async def rollback(self): + return self._s.rollback() + + async def refresh(self, obj): + return self._s.refresh(obj) + + async def close(self): + return self._s.close() + + +def _make_db(): + engine = create_engine("sqlite:///:memory:") + event.listen( + engine, + "connect", + lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), + ) + Base.metadata.create_all( + engine, + tables=[ + AIWorkflow.__table__, + AIWorkflowRevision.__table__, + AIWorkflowFixture.__table__, + WorkflowRun.__table__, + SystemSetting.__table__, + BGPIncident.__table__, + CollectedData.__table__, + EarthNewsItem.__table__, + ], + ) + return engine, _SyncAsAsyncSession(sessionmaker(engine, expire_on_commit=False)()) + + +async def _collect(stream) -> list[dict]: + return [ev async for ev in stream] + + +def _done(events: list[dict]) -> dict: + return next(ev["data"] for ev in events if ev["event"] == "done") + + +def _text(events: list[dict]) -> str: + return "".join(ev["data"]["delta"] for ev in events if ev["event"] == "text") + + +# --------------------------------------------------------------------------- +# 1. Cross-layer evidence: each source must query its own object regardless of click order +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_multi_select_targets_route_each_source_to_its_own_object(monkeypatch): + seen: dict[str, list] = {"bgp": [], "cable": [], "vessel": []} + + async def fake_bgp(_db, *, incident_key=None, **_kw): + seen["bgp"].append(incident_key) + return [] + + async def fake_cable(_db, *, entity_id=None, **_kw): + seen["cable"].append(entity_id) + return {} + + async def fake_vessel(_db, *, entity_id=None, **_kw): + seen["vessel"].append(entity_id) + return {} + + monkeypatch.setattr(dag_executor, "query_bgp_incidents_tool", fake_bgp) + monkeypatch.setattr(dag_executor, "query_cable_posture_tool", fake_cable) + monkeypatch.setattr(dag_executor, "query_vessel_posture_tool", fake_vessel) + + cable = {"entity_type": "cable", "entity_id": "cable-peace"} + vessel = {"entity_type": "vessel", "entity_id": "mmsi-413000000"} + bgp = {"entity_type": "bgp", "entity_id": "bgp-incident-77"} + for order in ([cable, vessel, bgp], [bgp, vessel, cable], [vessel, bgp, cable]): + for tool in ("query_bgp_incidents", "query_cable_posture", "query_vessel_posture"): + await _execute_tool( + None, tool, question="q", targets=order, earth_context={}, allow_external_tools=False + ) + assert set(seen["bgp"]) == {"bgp-incident-77"} + assert set(seen["cable"]) == {"cable-peace"} + assert set(seen["vessel"]) == {"mmsi-413000000"} + + # A source with no matching target gets no ID (never another layer's ID). + seen["vessel"].clear() + await _execute_tool(None, "query_vessel_posture", question="q", targets=[cable, bgp], earth_context={}, allow_external_tools=False) + assert seen["vessel"] == [None] + + +# --------------------------------------------------------------------------- +# 2. Compute comparison workflow must hand a ViewSpec workbench to the Earth copilot +# --------------------------------------------------------------------------- + +_SERIES = { + "years": (2023, 2024), + "compute": [ + {"year": 2023, "values": {"CN": 30.0, "US": 52.0}, "evidence_id": "ev-top500-2023"}, + {"year": 2024, "values": {"CN": 37.0, "US": 50.0}, "evidence_id": "ev-top500-2024"}, + ], + "unit": "%", + "evidence": { + "ev-top500-2023": {"id": "ev-top500-2023", "title": "TOP500 2023", "publisher": "TOP500", "url": "https://top500.org/2023"}, + "ev-top500-2024": {"id": "ev-top500-2024", "title": "TOP500 2024", "publisher": "TOP500", "url": "https://top500.org/2024"}, + }, + "time_basis": "retrospective", +} + + +class _ComputeBriefAI: + def __init__(self, content: str): + self.content = content + self.stream_calls = 0 + + async def is_ready(self): + return True, "fake", "fake-model" + + async def analyze(self, req): + return SimpleNamespace(content=self.content, provider="fake", model="fake-model") + + async def stream_analyze(self, req, request_id=None): + self.stream_calls += 1 + yield {"event": "text", "delta": "should not stream"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("valid_brief", [True, False]) +async def test_compute_comparison_workflow_emits_view_spec_and_no_raw_json(monkeypatch, valid_brief): + async def fake_compute(_db, countries, mode="global_share", **_kw): + return copy.deepcopy(_SERIES) + + monkeypatch.setattr(dag_executor, "query_compute_posture_tool", fake_compute) + brief = { + "headline": "中国算力份额升至 37%", + "headline_en": "China share rises to 37%", + "executive_assertion": "2024 年中国全球算力份额为 37%。", + "executive_assertion_en": "China held 37% in 2024.", + "causes": [ + {"label": "装机增长", "detail": "新增超算集中投运", "evidence_ids": ["ev-top500-2024" if valid_brief else "ev-made-up"]} + ], + "breakthrough_levers": [], + "blind_spots": ["未覆盖商业云内部集群"], + "evidence_ids": ["ev-top500-2024"], + } + ai = _ComputeBriefAI(json.dumps(brief, ensure_ascii=False)) + workflow = _fallback_workflow_dict("compute.comparison") + events = await _collect( + run_workflow_dag_stream( + db=None, + workflow=workflow, + question="对比中美算力", + earth_context={"selected_codes": ["CN", "US"], "mode": "global_share"}, + ai_client=ai, + ) + ) + done = _done(events) + text = _text(events) + assert ai.stream_calls == 0 + assert not text.lstrip().startswith("{") and '"headline"' not in text + assert isinstance(done["view_spec"], dict) and done["view_spec"].get("blocks") + late_meta = [ev["data"] for ev in events if ev["event"] == "meta" and ev["data"].get("view_spec")] + assert late_meta and late_meta[-1]["domain"] == "compute" + if valid_brief: + assert "中国算力份额升至 37%" in text + else: + assert "确定性研判" in text + + +# --------------------------------------------------------------------------- +# 3. Evidence guardrail failures must reach the user and the evaluator +# --------------------------------------------------------------------------- + + +def _guarded_graph(system_prompt: str = "研判 BGP 成因") -> dict: + return { + "nodes": [ + {"id": "t", "node_type": "trigger", "title": "入口"}, + {"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": system_prompt}, + {"id": "gr", "node_type": "guardrail", "title": "证据校验", "guardrails": {"require_evidence": True}}, + {"id": "out", "node_type": "output", "title": "输出"}, + ], + "edges": [ + {"id": "e1", "source": "t", "target": "llm"}, + {"id": "e2", "source": "llm", "target": "gr"}, + {"id": "e3", "source": "gr", "target": "out"}, + ], + } + + +class _StreamAI: + """Streams an answer chosen by the node system prompt (lets A/B graphs answer differently).""" + + def __init__(self, answers: dict[str, str], default: str = "研判完成"): + self.answers = answers + self.default = default + + async def is_ready(self): + return True, "fake", "fake-model" + + async def analyze(self, req): + return SimpleNamespace(content=self._pick(req), provider="fake", model="fake-model") + + async def stream_analyze(self, req, request_id=None): + yield {"event": "text", "delta": self._pick(req)} + + def _pick(self, req) -> str: + for key, answer in self.answers.items(): + if key in (req.system_prompt or ""): + return answer + return self.default + + +@pytest.mark.asyncio +async def test_missing_evidence_marks_run_unverified_and_delivers_pending_cause(): + workflow = {"workflow_id": "custom.bgp_cause", "name": "BGP 成因", "published_graph": _guarded_graph()} + events = await _collect( + run_workflow_dag_stream( + db=None, workflow=workflow, question="AS4837 为什么异常", ai_client=_StreamAI({}, "成因是上游劫持。") + ) + ) + done = _done(events) + assert done["status"] == "unverified" + assert done["verification"]["passed"] is False + assert "原因待核实" in done["answer_markdown"] and "待查项" in done["answer_markdown"] + failures = grade_fixture_result( + {"answer": done["answer_markdown"], "error": "", "verification_passed": False, "verification_warnings": done["verification"]["warnings"]}, + {}, + ) + assert any("护栏" in f for f in failures) + + +# --------------------------------------------------------------------------- +# 4. News: one click runs only the interactive branch +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_news_analysis_runs_only_the_branch_matching_the_trigger(monkeypatch): + async def fake_news(_db, region=None, limit=10): + return {"items": [{"title": "headline"}], "evidence": {}} + + async def fake_global(_db, **_kw): + return {"items": [], "evidence": {}} + + monkeypatch.setattr(dag_executor, "query_recent_earth_news_tool", fake_news) + monkeypatch.setattr(dag_executor, "query_global_situational_tool", fake_global) + calls: list[str] = [] + + class _AI: + async def is_ready(self): + return True, "fake", "fake-model" + + async def analyze(self, req): + calls.append("analyze") + return SimpleNamespace(content='{"location": {}, "localizations": {}}', provider="fake", model="m") + + async def stream_analyze(self, req, request_id=None): + calls.append("stream") + yield {"event": "text", "delta": "研判正文"} + + workflow = _fallback_workflow_dict("earth.news.analysis") + events = await _collect(run_workflow_dag_stream(db=None, workflow=workflow, question="分析这条新闻", ai_client=_AI())) + skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"} + assert "news_enrich_node" in skipped + assert calls == ["stream"] + assert _text(events) == "研判正文" + + calls.clear() + events = await _collect( + run_workflow_dag_stream(db=None, workflow=workflow, question="enrich", ai_client=_AI(), trigger_source="ingest") + ) + skipped = {ev["data"]["node_id"] for ev in events if ev["event"] == "node" and ev["data"]["status"] == "skipped"} + assert "news_analyst_node" in skipped + + +# --------------------------------------------------------------------------- +# 5. Draft bindings stay out of the public Earth entry until publish; rollback restores them +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_draft_bindings_do_not_touch_public_entry_and_roll_back_with_graph(): + engine, db = _make_db() + try: + await ensure_builtin_workflows(db) + wf_id = "earth.news.analysis" + + async def public_ids() -> set[str]: + return {item["workflow_id"] for item in await list_public_workflow_bindings(db)} + + assert wf_id in await public_ids() + row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one() + graph = copy.deepcopy(row.published_graph) + live_bindings = copy.deepcopy(row.bindings) + disabled = {**live_bindings, "enabled": False} + + saved = await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin") + assert wf_id in await public_ids() + assert saved["draft_bindings"]["enabled"] is False + await discard_workflow_draft(db, wf_id) + assert wf_id in await public_ids() + + enabled_rev = (await publish_workflow(db, wf_id, graph=graph, bindings=live_bindings))["active_revision"] + await save_workflow_draft(db, wf_id, graph, bindings=disabled, actor="admin") + await publish_workflow(db, wf_id) + assert wf_id not in await public_ids() + await rollback_workflow(db, wf_id, enabled_rev) + assert wf_id in await public_ids() + finally: + engine.dispose() + + +# --------------------------------------------------------------------------- +# 6. Canary rollback must not overwrite a newer manual publish +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_canary_rollback_is_superseded_by_manual_publish(): + from datetime import UTC, datetime, timedelta + + engine, db = _make_db() + try: + await ensure_builtin_workflows(db) + wf_id = "default.general" + row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one() + graph = copy.deepcopy(row.published_graph) + await publish_workflow(db, wf_id, graph=graph, actor="system:auto_evolver") # v2 canary + await append_ledger_entry( + db, + {"workflow_id": wf_id, "status": "canary", "base_revision": 1, "target_revision": 2, "canary_runs_target": 5}, + ) + manual = copy.deepcopy(graph) + manual["nodes"][0]["description"] = "manual v3" + await publish_workflow(db, wf_id, graph=manual, actor="admin") # v3 manual + now = datetime.now(UTC) + timedelta(seconds=2) + for idx in range(2): + db.add( + WorkflowRun( + id=f"v2_fail_{idx}", workflow_id=wf_id, status="failed", access_tier="admin", actor_key="admin", + question="q", input_params={}, tool_trace=[], budget_used={"workflow_revision": 2}, + error_message="boom", started_at=now + timedelta(seconds=idx), completed_at=now + timedelta(seconds=idx + 1), + ) + ) + await db.commit() + res = await evaluate_canary_and_maybe_rollback(db, wf_id) + assert res["action"] == "superseded" + row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one() + assert row.active_revision == 3 + assert row.published_graph["nodes"][0]["description"] == "manual v3" + finally: + engine.dispose() + + +# --------------------------------------------------------------------------- +# 7. Evolver can conclude "no change" (business + meta) +# --------------------------------------------------------------------------- + + +class _EmptyPatchAI: + async def is_ready(self): + return True, "fake", "fake-model" + + async def analyze(self, req): + return SimpleNamespace(content='{"summary": "无需修改", "node_patches": []}') + + +@pytest.mark.asyncio +async def test_explicit_empty_patch_ends_round_without_new_version(): + engine, db = _make_db() + try: + await ensure_builtin_workflows(db) + await update_evolution_policy(db, {"business_mode": "auto", "meta_mode": "auto"}) + for wf_id in ("compute.comparison", "default.general"): + for apply_mode in ("preview", "draft", "auto"): + res = await propose_workflow_evolution( + db, wf_id, apply_mode=apply_mode, ai_client=_EmptyPatchAI(), trigger="manual" + ) + assert res["applied_status"] == "no_change", (wf_id, apply_mode) + meta_res = await propose_meta_evolution(db, apply_mode="auto", ai_client=_EmptyPatchAI()) + assert meta_res["applied_status"] == "no_change" + + class _NoAI: + async def is_ready(self): + return False, "", "" + + # No AI, no ledger outcomes, no instruction -> nothing to base a meta rule on. + meta_fallback = await propose_meta_evolution(db, apply_mode="auto", ai_client=_NoAI()) + assert meta_fallback["applied_status"] == "no_change" + rows = (await db.execute(select(AIWorkflow))).scalars().all() + assert all(r.active_revision == 1 and r.draft_graph is None for r in rows) + assert await _load_ledger_entries(db) == [] + finally: + engine.dispose() + + +# --------------------------------------------------------------------------- +# 8. Graded A/B: 37 vs 73 must be a regression, and auto-publish requires the gate +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_graded_fixture_ab_detects_wrong_number_and_gates_auto_publish(monkeypatch): + engine, db = _make_db() + try: + await ensure_builtin_workflows(db) + base_graph = { + "nodes": [ + {"id": "t", "node_type": "trigger", "title": "入口"}, + {"id": "llm", "node_type": "llm_agent", "title": "研判", "system_prompt": "PROMPT_BASE"}, + {"id": "out", "node_type": "output", "title": "输出"}, + ], + "edges": [{"id": "e1", "source": "t", "target": "llm"}, {"id": "e2", "source": "llm", "target": "out"}], + } + await create_workflow(db, workflow_id="custom.metric", name="指标研判", graph=base_graph) + proposed = copy.deepcopy(base_graph) + proposed["nodes"][1]["system_prompt"] = "PROMPT_NEW" + ai = _StreamAI({"PROMPT_BASE": "观测值为 37。", "PROMPT_NEW": "观测值为 73。"}) + + async def fake_client(_db): + return ai + + monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client) + db.add( + AIWorkflowFixture( + workflow_id="custom.metric", name="观测值 37", sample_question="当前观测值是多少?", + context_json={"expect": {"numbers": [37]}}, + ) + ) + await db.commit() + ab = await run_fixture_ab_eval(db, "custom.metric", proposed) + assert (ab["base_passed"], ab["proposed_passed"]) == (1, 0) + assert ab["verdict"] == "regressed" and ab["regressions"] == ["观测值 37"] + assert ab["graded_fixture_count"] == 1 + + # Auto-publish of that regressing candidate is blocked by the A/B gate. + await update_evolution_policy(db, {"business_mode": "auto"}) + + class _PatchAI(_StreamAI): + async def analyze(self, req): + return SimpleNamespace( + content=json.dumps( + {"summary": "调整提示词", "node_patches": [{"node_id": "llm", "field": "system_prompt", "after": "PROMPT_NEW", "reason": "test"}]} + ) + ) + + res = await propose_workflow_evolution( + db, "custom.metric", apply_mode="auto", ai_client=_PatchAI(ai.answers), trigger="manual" + ) + assert res["applied_status"] == "blocked" + assert "A/B" in res["blocked_reason"] + row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == "custom.metric"))).scalar_one() + assert row.active_revision == 1 + finally: + engine.dispose() + + +# --------------------------------------------------------------------------- +# 9. Auto evolution builds from the live revision and never ships human drafts +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_auto_evolution_ignores_unpublished_human_draft(monkeypatch): + engine, db = _make_db() + try: + await ensure_builtin_workflows(db) + wf_id = "default.general" + stream_ai = _StreamAI({}, "研判完成:态势稳定。") + + async def fake_client(_db): + return stream_ai + + monkeypatch.setattr("app.services.ai.workflow_evolver.get_ai_provider_client", fake_client) + db.add( + AIWorkflowFixture( + workflow_id=wf_id, name="稳定性", sample_question="全球态势", + context_json={"expect": {"must_include": ["研判完成"]}}, + ) + ) + await db.commit() + row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one() + human_draft = copy.deepcopy(row.published_graph) + for node in human_draft["nodes"][:3]: + node["description"] = "HUMAN EDIT" + await save_workflow_draft(db, wf_id, human_draft, actor="admin") + await update_evolution_policy(db, {"business_mode": "auto"}) + + class _PatchAI(_StreamAI): + async def analyze(self, req): + return SimpleNamespace( + content=json.dumps( + {"summary": "增加一步", "node_patches": [{"node_id": "advisor_agent", "field": "max_steps", "after": 4, "reason": "test"}]} + ) + ) + + res = await propose_workflow_evolution( + db, wf_id, apply_mode="auto", trigger="auto_post_run", ai_client=_PatchAI({}, "研判完成:态势稳定。") + ) + assert res["applied_status"] == "auto_published", res["blocked_reason"] + row = (await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == wf_id))).scalar_one() + assert all(n.get("description") != "HUMAN EDIT" for n in row.published_graph["nodes"]) + assert row.draft_graph is not None + assert sum(1 for n in row.draft_graph["nodes"] if n.get("description") == "HUMAN EDIT") == 3 + assert [(c["node_id"], c["field"]) for c in res["changes_vs_live"]] == [("advisor_agent", "max_steps")] + ledger = await _load_ledger_entries(db) + assert ledger[0]["changes_vs_live"] == res["changes_vs_live"] + finally: + engine.dispose() + + +# --------------------------------------------------------------------------- +# 10. Every meta-evolvable field changes the downstream business request +# --------------------------------------------------------------------------- + + +def test_meta_evolvable_fields_change_business_request(): + base_diag = {"system_prompt": "诊断系统", "prompt": "诊断任务 A", "thinking_enabled": True} + base_patch = {"system_prompt": "输出 JSON node_patches", "prompt": "补丁任务", "thinking_enabled": True} + + def build(diag, patch): + req = build_business_evolution_request( + workflow_id="default.general", mode="optimize", instruction="", diag_node=diag, patch_node=patch, + schema={"type": "object"}, context={}, + ) + return req.model_dump() + + baseline = build(base_diag, base_patch) + variants = { + ("diag_node", "system_prompt"): build({**base_diag, "system_prompt": "诊断系统 v2"}, base_patch), + ("diag_node", "prompt"): build({**base_diag, "prompt": "诊断任务 B"}, base_patch), + ("patch_node", "system_prompt"): build(base_diag, {**base_patch, "system_prompt": "输出 JSON node_patches v2"}), + ("patch_node", "prompt"): build(base_diag, {**base_patch, "prompt": "补丁任务 v2"}), + ("patch_node", "thinking_enabled"): build(base_diag, {**base_patch, "thinking_enabled": False}), + } + from app.services.ai.workflow_evolver import META_EVOLVABLE_FIELDS + + assert set(variants) == set(META_EVOLVABLE_FIELDS) + for key, req in variants.items(): + assert req != baseline, key + assert META_WORKFLOW_ID == "meta.workflow_evolver" diff --git a/client/bun.lock b/client/bun.lock index fb077ce0..a751c659 100644 --- a/client/bun.lock +++ b/client/bun.lock @@ -16,7 +16,7 @@ "pmtiles": "4.4.1", "satellite.js": "5.0.0", "simplex-noise": "4.0.1", - "three": "0.128.0", + "three": "0.160.1", "typescript": "5.9.3", }, }, @@ -595,7 +595,7 @@ "temp-file": ["temp-file@3.4.0", "https://registry.npmmirror.com/temp-file/-/temp-file-3.4.0.tgz", { "dependencies": { "async-exit-hook": "^2.0.1", "fs-extra": "^10.0.0" } }, "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg=="], - "three": ["three@0.128.0", "https://registry.npmmirror.com/three/-/three-0.128.0.tgz", {}, "sha512-i0ap/E+OaSfzw7bD1TtYnPo3VEplkl70WX5fZqZnfZsE3k3aSFudqrrC9ldFZfYFkn1zwDmBcdGfiIm/hnbyZA=="], + "three": ["three@0.160.1", "", {}, "sha512-Bgl2wPJypDOZ1stAxwfWAcJ0WQf7QzlptsxkjYiURPz+n5k4RBDLsq+6f9Y75TYxn6aHLcWz+JNmwTOXWrQTBQ=="], "tiny-async-pool": ["tiny-async-pool@1.3.0", "https://registry.npmmirror.com/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", { "dependencies": { "semver": "^5.5.0" } }, "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA=="], diff --git a/client/package.json b/client/package.json index 33da7b2d..ca8c5624 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "planet-client", - "version": "0.82.0", + "version": "0.83.0", "description": "Intelligent Planet Program - Native Electron Earth Viewer", "private": true, "packageManager": "bun@1", @@ -26,7 +26,7 @@ "pmtiles": "4.4.1", "satellite.js": "5.0.0", "simplex-noise": "4.0.1", - "three": "0.128.0", + "three": "0.160.1", "typescript": "5.9.3" }, "scripts": { diff --git a/client/scripts/build-earth-bundle.mjs b/client/scripts/build-earth-bundle.mjs index ceb0b27b..78ea7204 100644 --- a/client/scripts/build-earth-bundle.mjs +++ b/client/scripts/build-earth-bundle.mjs @@ -15,7 +15,7 @@ const bundleEarthDir = join(desktopRoot, '.earth-bundle/earth') const require = createRequire(join(desktopRoot, 'package.json')) const VENDOR_PACKAGES = [ - { id: 'three', outFile: 'three.mjs', resolvePath: 'three/build/three.module.js' }, + { id: 'three', outFile: 'three.mjs' }, { id: 'pmtiles', outFile: 'pmtiles.mjs' }, { id: '@mapbox/vector-tile', outFile: 'mapbox-vector-tile.mjs' }, { id: 'pbf', outFile: 'pbf.mjs' }, diff --git a/client/src/main/recording-indicator.ts b/client/src/main/recording-indicator.ts index 57066234..fa71f5d4 100644 --- a/client/src/main/recording-indicator.ts +++ b/client/src/main/recording-indicator.ts @@ -1,4 +1,4 @@ -import { BrowserWindow, screen, type Display } from 'electron' +import { BrowserWindow, screen } from 'electron' import { getClientLocale } from './i18n' import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core' diff --git a/client/src/preload/splash.ts b/client/src/preload/splash.ts index 183065c1..65e4286a 100644 --- a/client/src/preload/splash.ts +++ b/client/src/preload/splash.ts @@ -7,8 +7,7 @@ interface GlobePoint { lat: number lon: number kind: 0 | 1 | 2 - shardAngle: number - shardSpeed: number + dissolveOrder: number phase: number } @@ -201,8 +200,7 @@ function buildGlobePoints(): GlobePoint[] { lat, lon: (lonDeg * Math.PI) / 180, kind: 2, - shardAngle: rand() * Math.PI * 2, - shardSpeed: 0.65 + rand() * 1.15, + dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35), phase: rand() * Math.PI * 2, }) } else if (kind === 1 && y % 2 === 0 && x % interiorStep === 0) { @@ -211,8 +209,7 @@ function buildGlobePoints(): GlobePoint[] { lat, lon: (lonDeg * Math.PI) / 180, kind: 1, - shardAngle: rand() * Math.PI * 2, - shardSpeed: 0.5 + rand() * 0.9, + dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35), phase: rand() * Math.PI * 2, }) } else if (kind === 0 && y % 5 === 0 && x % oceanStep === 0) { @@ -221,8 +218,7 @@ function buildGlobePoints(): GlobePoint[] { lat, lon: (lonDeg * Math.PI) / 180, kind: 0, - shardAngle: rand() * Math.PI * 2, - shardSpeed: 0.4 + rand() * 0.7, + dissolveOrder: clamp01((Math.abs(lat) / (Math.PI * 0.5)) * 0.65 + rand() * 0.35), phase: rand() * Math.PI * 2, }) } @@ -921,31 +917,19 @@ export function createDesktopSplashController(options: { cx: number, cy: number, ) => { - const warp = exitRatio > 0 ? exitRatio * exitRatio : 0 + const dolly = exitRatio > 0 ? 1 + exitRatio * exitRatio * 0.06 : 1 + const exitFade = exitRatio > 0 ? 1 - smoothstep(0.12, 0.88, exitRatio) : 1 for (const star of stars) { - const sx = star.x * w - const sy = star.y * h + const sx = cx + (star.x * w - cx) * dolly + const sy = cy + (star.y * h - cy) * dolly const twinkle = 0.55 + 0.45 * Math.sin(elapsed * star.twinkleSpeed + star.phase) - const alpha = star.alpha * twinkle * (1 - exitRatio * 0.75) + const alpha = star.alpha * twinkle * exitFade if (alpha <= 0.01) continue ctx.fillStyle = `rgba(210, 232, 255, ${alpha.toFixed(3)})` - if (warp > 0.02) { - const dx = sx - cx - const dy = sy - cy - const len = Math.max(1, Math.hypot(dx, dy)) - const streak = warp * 44 - ctx.strokeStyle = `rgba(176, 224, 255, ${(alpha * 0.85).toFixed(3)})` - ctx.lineWidth = star.size * 0.85 - ctx.beginPath() - ctx.moveTo(sx, sy) - ctx.lineTo(sx + (dx / len) * streak, sy + (dy / len) * streak) - ctx.stroke() - } else { - ctx.beginPath() - ctx.arc(sx, sy, star.size, 0, Math.PI * 2) - ctx.fill() - } + ctx.beginPath() + ctx.arc(sx, sy, star.size, 0, Math.PI * 2) + ctx.fill() } } @@ -967,7 +951,7 @@ export function createDesktopSplashController(options: { const perspK = 3.25 const tiltX = -0.25 const rollZ = -0.11 - const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 2.1) + const yaw = (108 * Math.PI) / 180 + elapsed * (0.26 + coreReveal * 0.42 + burst * 0.32) const eclipseR = radius * 0.955 const coronaOffsetAngle = -Math.PI * 0.68 + progress * Math.PI * 0.45 @@ -976,26 +960,26 @@ export function createDesktopSplashController(options: { const lx = cx + Math.cos(coronaOffsetAngle) * eclipseR * 0.72 const ly = cy + Math.sin(coronaOffsetAngle) * eclipseR * 0.72 const coronaAlpha = dawnIntensity * fade - const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 1.4)) + const corona = ctx.createRadialGradient(lx, ly, eclipseR * 0.15, cx, cy, eclipseR * (1.9 + burst * 0.55)) corona.addColorStop(0, `rgba(238, 249, 255, ${(0.9 * coronaAlpha).toFixed(3)})`) corona.addColorStop(0.28, `rgba(136, 208, 255, ${(0.5 * coronaAlpha).toFixed(3)})`) corona.addColorStop(0.62, `rgba(48, 118, 212, ${(0.15 * coronaAlpha).toFixed(3)})`) corona.addColorStop(1, 'rgba(1, 3, 8, 0)') ctx.fillStyle = corona ctx.beginPath() - ctx.arc(cx, cy, eclipseR * (1.95 + burst * 1.4), 0, Math.PI * 2) + ctx.arc(cx, cy, eclipseR * (1.95 + burst * 0.55), 0, Math.PI * 2) ctx.fill() } if (coreReveal > 0.01) { const haloAlpha = coreReveal * fade - const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 1.4)) + const glow = ctx.createRadialGradient(cx, cy, radius * 0.12, cx, cy, radius * (1.75 + burst * 0.55)) glow.addColorStop(0, `rgba(66, 152, 255, ${(0.28 * haloAlpha).toFixed(3)})`) glow.addColorStop(0.52, `rgba(48, 128, 228, ${(0.11 * haloAlpha).toFixed(3)})`) glow.addColorStop(1, 'rgba(2, 4, 10, 0)') ctx.fillStyle = glow ctx.beginPath() - ctx.arc(cx, cy, radius * (1.85 + burst * 1.4), 0, Math.PI * 2) + ctx.arc(cx, cy, radius * (1.85 + burst * 0.55), 0, Math.PI * 2) ctx.fill() } @@ -1027,24 +1011,26 @@ export function createDesktopSplashController(options: { ctx.stroke() } - // Act 2: Three tilted orbital rings drawing into full orbits, expanding on Act 3 burst + // Act 2: Three tilted orbital rings drawing into full orbits, smoothly expanding & fading on Act 3 iris if (orbitReveal > 0.01) { + const ringEase = exitRatio > 0 ? 1 - Math.pow(1 - exitRatio, 2.6) : 0 + const ringFade = fade * (1 - smoothstep(0.08, 0.82, exitRatio)) const ringConfigs = [ - { rx: radius * (1.36 + burst * 1.6), ry: radius * (0.4 + burst * 0.5), rot: -0.34, color: '116, 206, 255' }, - { rx: radius * (1.56 + burst * 2.0), ry: radius * (0.5 + burst * 0.6), rot: 0.42, color: '146, 184, 255' }, - { rx: radius * (1.18 + burst * 1.3), ry: radius * (0.34 + burst * 0.4), rot: 0.08, color: '214, 240, 255' }, + { rx: radius * (1.36 + ringEase * 0.72), ry: radius * (0.4 + ringEase * 0.22), rot: -0.34, color: '116, 206, 255' }, + { rx: radius * (1.56 + ringEase * 0.72), ry: radius * (0.5 + ringEase * 0.22), rot: 0.42, color: '146, 184, 255' }, + { rx: radius * (1.18 + ringEase * 0.72), ry: radius * (0.34 + ringEase * 0.22), rot: 0.08, color: '214, 240, 255' }, ] for (let i = 0; i < ringConfigs.length; i += 1) { const ringReveal = clamp01((orbitReveal - i * 0.1) / 0.8) - if (ringReveal <= 0.005) continue + if (ringReveal <= 0.005 || ringFade <= 0.005) continue const ring = ringConfigs[i] const a = elapsed * (1.2 + i * 0.45) + i * 2.1 ctx.save() ctx.translate(cx, cy) ctx.rotate(ring.rot + elapsed * 0.08 * (i % 2 === 0 ? 1 : -1)) - ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * fade).toFixed(3)})` - ctx.lineWidth = 1.15 + ctx.strokeStyle = `rgba(${ring.color}, ${(0.28 * ringReveal * ringFade).toFixed(3)})` + ctx.lineWidth = Math.max(0.65, 1.05 * (1 - exitRatio * 0.35)) ctx.beginPath() if (ringReveal >= 0.995) { ctx.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2) @@ -1055,31 +1041,26 @@ export function createDesktopSplashController(options: { const sx = Math.cos(a) * ring.rx const sy = Math.sin(a) * ring.ry - ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * fade).toFixed(3)})` + ctx.fillStyle = `rgba(225, 247, 255, ${(0.92 * ringReveal * ringFade).toFixed(3)})` ctx.beginPath() - ctx.arc(sx, sy, 2.6 + burst * 1.5, 0, Math.PI * 2) + ctx.arc(sx, sy, Math.max(0.8, 2.4 * (1 - exitRatio * 0.55)), 0, Math.PI * 2) ctx.fill() ctx.restore() } } - // Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> radial scatter + // Shared 3D globe point cloud: Dawn coastline lights -> full holographic sphere -> coherent iris dissolve const oceanReveal = clamp01((coreReveal - 0.25) / 0.75) + const sphereScale = 1 + smoothstep(0, 1, exitRatio) * 0.22 + const dotSizeFactor = 1 - exitRatio * 0.35 for (const pt of globePoints) { const p = projectSpherePoint(pt.lat, pt.lon, yaw, tiltX, rollZ) - if (burst === 0 && p.nz < -0.22) continue + if (exitRatio === 0 && p.nz < -0.22) continue - const radialBoost = 1 + burst * (1.6 + pt.shardSpeed * 2.8) - const jitterX = Math.cos(pt.shardAngle) * burst * 0.28 - const jitterY = Math.sin(pt.shardAngle) * burst * 0.28 - const px = p.nx * radialBoost + jitterX - const py = p.ny * radialBoost + jitterY - const pz = p.nz + burst * pt.shardSpeed * 1.1 - - const depth = Math.max(0.25, perspD - pz) - const screenScale = (radius * perspK) / depth - const sx = cx + px * screenScale - const sy = cy + py * screenScale + const depth = Math.max(0.25, perspD - p.nz) + const screenScale = (radius * perspK * sphereScale) / depth + const sx = cx + p.nx * screenScale + const sy = cy + p.ny * screenScale if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) continue const depthFade = p.nz >= 0 ? 1 : Math.max(0.14, 1 + p.nz * 2.2) @@ -1102,31 +1083,20 @@ export function createDesktopSplashController(options: { pointGain = oceanReveal * 0.28 * depthFade } - const alpha = pointGain * polarFade * fade + const exitPointFade = + exitRatio > 0 ? 1 - smoothstep(pt.dissolveOrder * 0.32, pt.dissolveOrder * 0.32 + 0.44, exitRatio) : 1 + const alpha = pointGain * polarFade * fade * exitPointFade if (alpha <= 0.015) continue - if (burst > 0.03) { - const prevBoost = Math.max(1, radialBoost - 0.36 * pt.shardSpeed * burst) - const prevScale = (radius * perspK) / Math.max(0.3, perspD - p.nz) - const ox = cx + p.nx * prevBoost * prevScale - const oy = cy + p.ny * prevBoost * prevScale - ctx.strokeStyle = `rgba(${color}, ${Math.min(1, alpha * 1.15).toFixed(3)})` - ctx.lineWidth = dotR - ctx.beginPath() - ctx.moveTo(ox, oy) - ctx.lineTo(sx, sy) - ctx.stroke() - } else { - ctx.fillStyle = `rgba(${color}, ${alpha.toFixed(3)})` - ctx.beginPath() - ctx.arc(sx, sy, dotR, 0, Math.PI * 2) - ctx.fill() - } + ctx.fillStyle = `rgba(${color}, ${alpha.toFixed(3)})` + ctx.beginPath() + ctx.arc(sx, sy, Math.max(0.55, dotR * dotSizeFactor), 0, Math.PI * 2) + ctx.fill() } // Intercontinental telemetry arcs across front hemisphere - if (arcReveal > 0.01 && burst < 0.55) { - const arcAlpha = arcReveal * fade * Math.max(0, 1 - burst * 1.6) + if (arcReveal > 0.01 && exitRatio < 0.45) { + const arcAlpha = arcReveal * fade * (1 - smoothstep(0.0, 0.45, exitRatio)) for (const arc of ARC_DEFINITIONS) { const p1 = projectSpherePoint((arc.lat1 * Math.PI) / 180, (arc.lon1 * Math.PI) / 180, yaw, tiltX, rollZ) const p2 = projectSpherePoint((arc.lat2 * Math.PI) / 180, (arc.lon2 * Math.PI) / 180, yaw, tiltX, rollZ) @@ -1138,7 +1108,7 @@ export function createDesktopSplashController(options: { const y2 = cy + p2.ny * radius * 1.02 const mx = (p1.nx + p2.nx) * 0.5 const my = (p1.ny + p2.ny) * 0.5 - const lift = 1.24 + burst * 0.9 + const lift = 1.24 + burst * 0.18 const cpx = cx + mx * radius * lift const cpy = cy + my * radius * lift @@ -1160,14 +1130,25 @@ export function createDesktopSplashController(options: { } } - // Act 3: Climax shockwave ring on scatter burst - if (burst > 0.005) { - const shockR = radius * (0.88 + exitRatio * 5.2) - ctx.strokeStyle = `rgba(168, 228, 255, ${(0.72 * (1 - exitRatio)).toFixed(3)})` - ctx.lineWidth = Math.max(1, 3.2 * (1 - exitRatio)) - ctx.beginPath() - ctx.arc(cx, cy, shockR, 0, Math.PI * 2) - ctx.stroke() + // Act 3: Dual-layer refined optical aperture iris reveal + if (exitRatio > 0.005) { + const iris = 1 - Math.pow(1 - exitRatio, 3) + const irisFade = smoothstep(0.0, 0.12, exitRatio) * (1 - smoothstep(0.18, 0.82, exitRatio)) + if (irisFade > 0.005) { + const outerR = radius * (1.02 + iris * 1.55) + ctx.strokeStyle = `rgba(162, 218, 255, ${(0.36 * irisFade).toFixed(3)})` + ctx.lineWidth = 1.0 + ctx.beginPath() + ctx.arc(cx, cy, outerR, 0, Math.PI * 2) + ctx.stroke() + + const companionR = radius * (0.98 + iris * 1.22) + ctx.strokeStyle = `rgba(98, 184, 255, ${(0.14 * irisFade).toFixed(3)})` + ctx.lineWidth = 2.6 + ctx.beginPath() + ctx.arc(cx, cy, companionR, 0, Math.PI * 2) + ctx.stroke() + } } } @@ -1217,13 +1198,13 @@ export function createDesktopSplashController(options: { if (reducedMotion) { rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(exitRatio, 1.35)).toFixed(3)}` } else { - // Portal cutout expands from center while particle bursts continue radiating over edges - const holePct = Math.pow(exitRatio, 1.45) * 135 - const edgePct = holePct + 18 + // Wide feathered optical iris handoff into the live 3D Earth + const holePct = Math.pow(exitRatio, 1.35) * 115 + const edgePct = holePct + 36 const maskValue = `radial-gradient(circle at ${cx.toFixed(1)}px ${cy.toFixed(1)}px, transparent ${holePct.toFixed(1)}%, #000 ${edgePct.toFixed(1)}%)` rootEl.style.webkitMaskImage = maskValue rootEl.style.maskImage = maskValue - rootEl.style.opacity = `${Math.max(0, 1 - Math.pow(Math.max(0, exitRatio - 0.55) / 0.45, 1.5)).toFixed(3)}` + rootEl.style.opacity = `${Math.max(0, 1 - smoothstep(0.28, 1, exitRatio)).toFixed(3)}` } } diff --git a/client/tests/splash-config.test.ts b/client/tests/splash-config.test.ts index 2bf99bb5..e49f3c6e 100644 --- a/client/tests/splash-config.test.ts +++ b/client/tests/splash-config.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' @@ -275,4 +275,20 @@ describe('splash theme configuration and landmask', () => { }) expect(capHit).toEqual({ targetProgress: 1, readyToExit: true }) }) + + test('splash exit choreography uses calm coherent optical dissolve without outward radial streaks', () => { + const splashSrc = readFileSync(new URL('../src/preload/splash.ts', import.meta.url), 'utf8') + expect(splashSrc).not.toContain('shardSpeed') + expect(splashSrc).not.toContain('shardAngle') + expect(splashSrc).not.toContain('radialBoost') + expect(splashSrc).not.toContain('warp * 44') + + let prevFade = 1 + for (const ratio of [0, 0.25, 0.5, 0.75, 1]) { + const phase = computeSplashMorphPhases(1, ratio) + expect(phase.fade).toBeLessThanOrEqual(prevFade + 1e-9) + prevFade = phase.fade + } + expect(computeSplashMorphPhases(1, 1).fade).toBe(0) + }) }) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index dcbaa7b2..055da48a 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,25 @@ This project follows the repository versioning rule: - `improvement` -> `+0.0.1`(bugfix + 小功能混合) - `bugfix` -> `+0.0.1` +## [0.83.0] — 2026-12-02 + +Released: 2026-12-02 + +### Highlights + +- **Earth Phase 1–4 贴地影响范围与三维视觉升级**: 上线贴地影响范围着色器引擎(`influence-zones.js` + `scene_directives.py`,单次离屏模糊合成与层级叠序 `renderOrderBase = 0.965`)、本地云图 `earth_clouds_2048.png` 瑞利晨昏散射与地面云影、`surface-ribbon.js` 屏幕空间抗锯齿发光丝带(国界/雷达/弧线/海缆/航迹/轨道)及 GPU 投影 Iridium 足迹。 +- **Earth 聚合徽标视觉统一与优先一折连线**: 聚合徽标统一为 `28px` 深色玻璃内核 + `2.5px` 纯色 / `conic-gradient` 比例分段环及子类别明细提示;卡片引导线升级为“能一折优先一折、最多一折”策略,短距与紧凑胶囊平滑退化。 +- **AI 参谋自进化约束加固与数据源连通性修复**: 加固 `workflow_evolver.py` / `dag_executor.py` / `stream_turn.py` 的无变更结果、可判对错 A/B 样本、草稿隔离与灰度防覆盖机制;修复 Space-Track/ArcGIS/Epoch 等数据源连通性校验与凭据引导。 +- **Electron 客户端启动动效、打包构建与双语统一**: 更新桌面端 `splash.ts` 启动页配置与 Earth 热更包构建,并完成控制台、登录、文档页品牌图标及中英文纯净度统一;清理近 3 日冗余死代码并同步规划与技术文档。 + +### Added / Changed + +- Earth & Frontend: `influence-zones.js`、`surface-ribbon.js`、`earth-surface-material.js`、`cluster-presentation.js`、`callout-connector.js`、`admin-write-auth.js`、`datasourceConfigHelpers.ts` +- Backend: `scene_directives.py`、`dag_executor.py`、`workflow_evolver.py`、`workflow_runtime.py`、`stream_turn.py`、`datasource_connectivity.py` +- Desktop Client: `client/src/preload/splash.ts`、`client/scripts/build-earth-bundle.mjs`、`client/bun.lock` + +--- + ## [0.82.0] — 2026-12-01 Released: 2026-12-01 diff --git a/docs/plans/README.md b/docs/plans/README.md index d06bd96c..e9124455 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -23,6 +23,8 @@ 当前重点入口: - [开发 Agent 模型分配与 Token 控制计划](development-agent-model-allocation-plan.md) +- [Earth 贴地影响范围与电影级三维视觉升级方案](earth-influence-zones-and-vfx-upgrade-plan.md) +- [AI 参谋工作流可视化编排、客户端上下文与受控位置 Agent 方案](ai-advisor-workflow-and-location-agent-plan.md) - [Earth 地理资源、空间浮动卡片与性能实施计划](earth-spatial-presentation-and-geographic-assets-plan.md) - [算力与资源态势:展示、采集与 AI 迭代实施计划](compute-resource-intelligence-plan.md) - [控制台 i18n 接入计划](/home/ray/dev/linkong/planet/docs/plans/admin-console-i18n-plan.md) diff --git a/docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md b/docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md index 070be430..3be68053 100644 --- a/docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md +++ b/docs/plans/earth-influence-zones-and-vfx-upgrade-plan.md @@ -1,6 +1,6 @@ # Earth 贴地影响范围与电影级三维视觉升级方案 -> 状态:**规划待排期**(全量 Three.js / 着色器 / Agent 场景协议只读评估已完成,当前无需升级 `three@0.128.0` 亦不引入全屏后处理 `UnrealBloomPass`,全部效果可在核显与 Electron 60fps 录屏约束下通过轻量化自定义 Shader 实现)。 +> 状态:**已落地实现(随 `v0.83.0` 发布)**。已完成 Phase 1–4 全部核心引擎与渲染管线交付([influence-zones.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/influence-zones.js)、[scene_directives.py](/home/ray/dev/linkong/planet/backend/app/services/ai/scene_directives.py)、[surface-ribbon.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/surface-ribbon.js)、[earth-surface-material.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth-surface-material.js)、[iridium-footprint-adapter.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/iridium-footprint-adapter.js) 及本地云图 `earth_clouds_2048.png`),仍保持 `three@0.128.0` 无全屏后处理约束。 --- diff --git a/docs/plans/earth-interactable-layer-plan.md b/docs/plans/earth-interactable-layer-plan.md index 20392e06..85f88c63 100644 --- a/docs/plans/earth-interactable-layer-plan.md +++ b/docs/plans/earth-interactable-layer-plan.md @@ -312,3 +312,17 @@ hover / locked 使用少量 overlay: | `frontend/public/earth/js/main.js` | 当前集中处理 hover、click、locked 和 info-card 入口 | 后续需要接入通用 icon picking 结果 | | `docs/technical/zh/earth-layer-style-reference.md` | 当前视觉参数参考 | 实现后同步默认 glow 和通用参数 | | `docs/technical/zh/earth-render-layer-order.md` | 当前层级参考 | 实现后同步 surface icon 层级范围 | + +--- + +## 后续演进:跨图层聚合与屏幕空间防重叠(待排期) + +当前聚合按图层控制器独立计算(`compute-centers`、`bgp-events`、`bgp-collectors`、`earth-interactables` 各自成簇),且仅使用固定球面世界距离(`CLUSTER_DISTANCE = 15`)与 `coLocatedGroups`(`0.00015°`)的展开态偏移。由此带来两个待解决的交互问题: + +1. 当一个图层的折叠数字徽章(如 `compute-centers` 的 `2`)与另一图层的未聚合单点(如莫斯科同城 `bgp-collectors`)在低缩放下投影重合时,DOM 覆盖层 `.map-clusters` 会直接挡住底部 WebGL 图标并吞掉鼠标拾取事件。 +2. 固定世界距离加上单种子贪心聚类的质心偏移,在拉远视角下容易使相邻点未合并却在屏幕像素空间重合。 + +待选演进方向(排期前二选一): + +- **方案 A(优先推荐)**:跨图层统一聚合 + 基于当前相机缩放的屏幕像素距离自适应归并(单徽章多色分段环天然复用现有 `conic-gradient` 视觉契约)。 +- **方案 B**:保持各图层语义独立,将折叠态聚合徽章纳入与异图层单点之间的屏幕空间碰撞避让,并补齐错位引导线以保证底层图标可独立拾取。 diff --git a/docs/technical/en/agents-aiprovider.md b/docs/technical/en/agents-aiprovider.md index 502e47a8..09696a9d 100644 --- a/docs/technical/en/agents-aiprovider.md +++ b/docs/technical/en/agents-aiprovider.md @@ -149,6 +149,14 @@ Implemented in [workflow_evolver.py](/home/ray/dev/linkong/planet/backend/app/se - **Tier 0 (Immutable Python Constitution Kernel)**: enforces acyclic DAG structure and trigger/output preservation, blocks emptying `system_prompt`, restricts tools to allowlisted IDs, caps auto-mode blast radius (`<= 2` nodes and `<= 40%` of nodes), freezes the `verify_output` node on `meta.workflow_evolver`, blocks custom `meta.*` creation (single-level recursion lock), enforces `24h / 7d` cooldowns and daily auto-evolution quotas, and runs a **5-run canary window** with automatic rollback on consecutive failures or elevated bad-rating rates (with a 3-outcome meta-canary rollback guard on `meta.workflow_evolver`). - **Tier 1 (Business Optimization & Model Drift Adaptation)**: `GET /api/v1/ai/evolution/health/{workflow_id}` computes 0-token health metrics, active model capability drift, unused tools, and DGM best-parent revision recommendations; `POST /api/v1/ai/evolution/propose/{workflow_id}` reads live `diag_node` / `patch_node` prompts from `meta.workflow_evolver` alongside historical ledger lessons; `POST /api/v1/ai/evolution/eval/{workflow_id}` runs Fixture A/B checks and `POST /api/v1/ai/evolution/incubate` proposes new workflows from frequent `default.general` queries. Non-blocking post-run hooks run via `schedule_post_run_evolution`. - **Tier 2 (Meta-Evolution & Extensibility Hooks)**: `POST /api/v1/ai/evolution/meta-evolve` evolves `meta.workflow_evolver` prompts under an independent `meta_mode` (`off | draft | auto`) using objective ledger outcomes; `EvolutionSignalDetector` (`SIGNAL_DETECTORS`) and `EvolutionEvaluator` (`EVALUATORS`) provide clean `Protocol` extension points. +- **Evolution safety constraints (hardened after the v0.82.0 review)**: + - **"No change" is a valid outcome**: a valid empty `node_patches` list ends the round with `applied_status: no_change` (no revision, no ledger entry); the deterministic fallback only patches on real signals (failures/downvotes/model capability mismatch/admin instruction/ledger outcomes) and never pads prompts. + - **Gradable A/B fixtures**: fixtures accept `expect` (`numbers`, `must_include`, `must_not_include`, `require_uncertainty_without_evidence`, `min_evidence`, stored in `context_json.expect`) on `POST /api/v1/ai/workflows/{id}/fixtures`; grading covers execution errors, guardrail verification, and assertions, and any fixture that passes on live but fails on the candidate yields `regressed`. **Auto-publish requires the A/B gate**: missing fixtures, fixtures without assertions, or any regression block publication. + - **Live revision baseline**: background/auto-publish evolution always starts from the live revision, never reads or clears unpublished human drafts (auto-draft mode skips when a human draft exists), records the full candidate-vs-live diff in `changes_vs_live`, and applies the auto blast-radius limit to that full diff. + - **Canary cannot overwrite newer revisions**: before settling, the canary checks the live revision is still its target; if a manual publish/rollback superseded it, the entry becomes `superseded` without rollback (same for the meta canary). + - **Meta fields must take effect**: meta-evolution may only change `diag_node.system_prompt / prompt` and `patch_node.system_prompt / prompt / thinking_enabled`, all of which feed the business request (`build_business_evolution_request`); meta-evolution stays off by default. +- **Earth workflow data, evidence, and card output**: `dag_executor.py` selects each data source's own target ID by entity type (cable/vessel/BGP multi-select is order-independent); `interactive / ingest` edges route strictly by trigger source (a news click no longer runs the RSS localization branch); strict-JSON nodes such as `compute.posture.brief` run non-streaming, are verified via `StrategicPostureBrief` + evidence IDs, rendered as narrative, and the output node compiles the compute `view_spec` workbench (delivered via a closing `meta` event and `done.view_spec`); a failed `require_evidence` guardrail appends a "cause pending verification" block with follow-ups and marks `done.status` as `unverified` with `verification`. +- **Draft binding isolation**: Earth entry bindings edited in a draft live in `draft_graph.bindings` (returned as `draft_bindings`), apply only on publish, and are restored by discarding the draft; each published revision snapshots bindings in `graph_json.bindings` so rollback restores them. "Save bindings only" (`PATCH /workflows/{id}`) remains an explicit immediate action. - **Feedback & Policy APIs**: `POST /api/v1/ai/runs/{run_id}/feedback`, `GET /api/v1/ai/runs?feedback=negative|positive`, `GET/PUT /api/v1/ai/evolution/policy`, `GET /api/v1/ai/evolution/ledger`, and `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss`. Save, set-as-default, and connectivity testing remain three separate responsibilities. Runtime prompts resolve from published `AIWorkflow` nodes and versioned `default_prompts.json` resources while preserving `task_key` compatibility. diff --git a/docs/technical/en/earth-frontend-context.md b/docs/technical/en/earth-frontend-context.md index 02566432..0fed4f5c 100644 --- a/docs/technical/en/earth-frontend-context.md +++ b/docs/technical/en/earth-frontend-context.md @@ -376,7 +376,7 @@ If future cable, satellite, or news cruise is added, do not copy a new set of `m `globe-navigation.js` retains the safe zoom-distance mapping. Mouse and single-touch drags uniformly use legacy screen deltas, 0.18 smoothing and release inertia, including movement outside the globe silhouette; ray/sphere intersection no longer gates dragging. Normal zoom retains legacy sensitivity. Once the globe exceeds the viewport, a smooth surface-distance/viewport cap limits excessive rotation at extreme zoom. Horizontal motion uses geographic yaw, vertical input changes tilt, and quaternion math prevents multi-revolution reversal. Pinch transitions and pointer capture remain intact. -Surface markers retain category icons and fixed geographic cluster membership. Numbered solid circles expand through a 320ms tween above 250% zoom; zoom never regroups members, and 500% has no aggregate badges. Vessels retain independent heading arrows without clustering. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md). +Surface markers retain category icons and fixed geographic cluster membership. `28px` dark translucent-core circular badges with colored outer rings expand through a 320ms tween above 250% zoom; zoom never regroups members, and 500% has no aggregate badges. Vessels retain independent heading arrows without clustering. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md). Wheel input has two paths. Traditional mouse wheels keep the 10% step and short animation, using `wheelZoomTarget` as the logical base for continuous wheel input. Trackpads and high-precision wheels use the pixel delta for continuous zoom and call `setZoomLevel()` directly instead of passing through the 10% stepped animation. The trackpad path also filters a short-window, old-direction residual delta after a real direction change so inertia tails do not pull a just-reversed zoom back in the previous direction. @@ -508,7 +508,7 @@ Focus state and per-type limits decide expanded cards versus capsules. Shared st ### Cluster badges and Spiderfy -Ordinary surface markers retain GPU batches. Each aggregate uses the same projected children in `cluster-presentation.js` through collapse, expansion and the final resting state. A 26px solid numbered circle represents the group, with an amber ring for mixed categories. Membership changes only with data or filters, never through intermediate groups while zooming. +Ordinary surface markers retain GPU batches. Each aggregate uses the same projected children in `cluster-presentation.js` through collapse, expansion and the final resting state. Badges share a `28px` dark-glass core with white tabular counts: single-type groups wear a `2.5px` solid `--cluster-color` ring, while mixed groups render a proportional `conic-gradient` ring (`--cluster-ring` with `4deg` dark dividers and a minimum minority arc floor) plus localized subtype breakdowns via `formatClusterTitle`. Membership changes only with data or filters, never through intermediate groups while zooming. `cluster-motion.js` drives a 320ms cubic tween after visible icons are prepared and decoded, with encoded textures cached. Children interpolate from the group center to their real projections; `marker-stack.js` owns final display offsets. Animation and resting endpoints retain the same DOM nodes, with continuous reversal. @@ -614,3 +614,9 @@ When compute image configuration has no model/group rules, resolution uses a bou - `workflow-bindings.js` fetches `/api/v1/earth/workflow-bindings` and dynamically projects published custom/built-in workflow actions onto matching Earth surfaces (info cards, news/topic cards, Copilot quick actions, and multi-target comparison tray). - Electron `screen-recorder.ts` captures `win.webContents.mainFrame` cleanly without framing chrome while preserving native Alt menu access, and Earth `i18n.js` / `index.html` keep `zh-CN` and `en-US` copy separated cleanly while syncing locale preferences with the console. + +### Surface Influence Zones, Cinematic Shading, and Prefer-One-Bend Callouts (v0.83.0) + +- **Surface Influence Zones & Stage Directives** (`influence-zones.js` + `scene_directives.py`): renders geopolitical country/region presets and great-circle radius zones emitted by AI/stage directives via single-pass offscreen `scratchCanvas` soft-blur compositing and explicit `tier` / `z_index` stacking (`renderOrderBase = 0.965`, strictly between HD imagery `0.96` and borders `0.97`). +- **Rayleigh Scattering, Ribbons & GPU Iridium Projection**: `earth-surface-material.js` and `earth.js` pair with `earth_clouds_2048.png` for Rayleigh terminator shading, soft surface cloud shadows, and grazing water highlights; `surface-ribbon.js` unifies screen-space anti-aliased glowing ribbons for borders, BGP radar/stage arcs, cable pulses, vessel tracks, and selected satellite orbits; `iridium-footprint-adapter.js` moves Iridium footprint vertices onto GPU projection. +- **Prefer-One-Bend Callout Routing & Write Auth**: `callout-connector.js` (`applyPreferredOneBendAnchor`) shifts aligned perimeter anchors toward the card body/header when sufficient major-axis distance and edge span exist so connectors prefer one clean bend (never exceeding one bend, gracefully falling back to a 2-point line on compact capsules or short spans); `admin-write-auth.js` gates Earth-side compute location collection and saving behind admin token refresh and `/login` prompts. diff --git a/docs/technical/en/earth-interactable-clustering.md b/docs/technical/en/earth-interactable-clustering.md index 45be126d..7c341e4e 100644 --- a/docs/technical/en/earth-interactable-clustering.md +++ b/docs/technical/en/earth-interactable-clustering.md @@ -1,6 +1,6 @@ # Earth interactable clustering -`interactable.js` owns fixed geographic membership, `cluster-motion.js` owns timed tweening, and `cluster-presentation.js` owns circular badges, projected children, picking and Spiderfy. Independent markers remain GPU Points. Each clustered child uses the same DOM icon throughout its animation and at the final position. +`interactable.js` owns fixed geographic membership, `cluster-motion.js` owns timed tweening, and `cluster-presentation.js` owns `28px` dark-glass circular badges (`2.5px` solid or proportional `conic-gradient` multi-type rings), projected children, picking and Spiderfy. Independent markers remain GPU Points. Each clustered child uses the same DOM icon throughout its animation and at the final position. ## Membership and zoom diff --git a/docs/technical/en/earth-render-layer-order.md b/docs/technical/en/earth-render-layer-order.md index b6228193..eb32184a 100644 --- a/docs/technical/en/earth-render-layer-order.md +++ b/docs/technical/en/earth-render-layer-order.md @@ -20,8 +20,10 @@ Note: the layer control panel order and the registration / startup load order ar | 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. | | 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. | | 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. | -| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere. | -| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering shares the surface pass; no fullscreen post-processing. | +| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere; uses Rayleigh terminator shading and subtle grazing water reflection. | +| 0.962 | Cloud shadow shell | `earth.js` | Shared HD surface radius with slight angular offset | `depthTest: true`, `depthWrite: false`, raycast disabled | Follows the cloud toggle and casts soft surface cloud shadows from `earth_clouds_2048.png`, strictly above `0.96` and below `0.965`. | +| 0.965 | Surface influence zones | `influence-zones.js`, `scene_directives.py` | Reuses the `128×128` spherical shell at `r = 100.48` (`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`); `renderOrderBase = 0.965`, stepping by `0.0003` per tier | `depthTest: true`, `depthWrite: false`, raycast disabled | Supports single-pass offscreen soft blur compositing for country presets and great-circle fragment shading for circular zones; stays above `0.96` HD imagery and strictly below `0.97` borders and all surface icons. | +| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 (`FrontSide` shader + `earth_clouds_2048.png`) | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering and Mie forward glow combine across the surface/atmosphere shells without fullscreen post-processing. | | 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cables and landing-point anchors share the HD surface offset `0.48` and the same triangle-surface coordinates | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. | | 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. | | 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. | @@ -108,4 +110,4 @@ Co-located markers share a compact projection stack across categories; screen co Regional news and compute retain the `#earth-region-callouts` root (z-index 20) and share flank/corridor assignment with object details through `callout-stage-arbitrator.js`, which assigns symmetric left and right flanks to bilateral `CN` and `US` spotlight peers via `bilateralPeerKey`. Expanded cards inside the regional root use 50, drag foreground 55, hover expansion 60–65, ordinary capsules 30, and dimmed/shrunk rear capsules 8, whereas spotlight and hover-expanded cards stay 100% opaque on the rear hemisphere while switching their connector to a dashed `.is-rear` rim guide and exposing a header rotate-to-front button. -Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`), and East-West synergy arcs batch into one elevated `LineSegments` (`renderOrder = 4.55`) to prevent far-zoom z-fighting; stage logical AS route arcs render as high-altitude before/after trajectories (`renderOrder = 4.72` / `4.76`) and dispose geometry and materials immediately on hide or tour exit. +Compute hub drill-down overlays and stage logical AS route arcs follow strict shell separation and batching rules: China's eight National Compute Hubs render through a single GPU-instanced `createInteractableLayer` at `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` (`renderOrder = 4.58`); western green-hub `AdditiveBlending` pulse rings use `renderOrder = 4.42` (`depthWrite: false`); East-West synergy arcs, stage logical AS routes, country hover highlights, selected cable pulses, vessel tracks, and selected satellite orbits share the screen-space anti-aliased `surface-ribbon.js` pipeline (avoiding the Windows ANGLE 1px `THREE.Line` cap); and Iridium footprints run through GPU vertex projection in `iridium-footprint-adapter.js`, disposing geometry and materials immediately on hide or tour exit. diff --git a/docs/technical/zh/agents-aiprovider.md b/docs/technical/zh/agents-aiprovider.md index 314a4741..57317ff5 100644 --- a/docs/technical/zh/agents-aiprovider.md +++ b/docs/technical/zh/agents-aiprovider.md @@ -149,6 +149,14 @@ Admin 的 AI 页面已按模型配置与参谋编排拆分为两部分: - **Tier 0(Python 不可变宪法内核)**:强制校验 DAG 无环与入口/输出保留、禁止清空 `system_prompt`、禁止使用非白名单工具、限制自动变更半径(单次 `<= 2` 个且 `<= 40%` 节点)、永久冻结元引擎 `verify_output` 节点、禁止自定义 `meta.*` 命名空间(单层元递归锁)、按 `24h / 7d` 冷却与每日自动预算加锁,并在自动发布后启动 **5 次运行灰度观察窗**(连续 2 次失败或差评/失败率超阈即自动回滚,元引擎自身受下游 3 次结果窗口自动回退保护)。 - **Tier 1(业务自优化与模型漂移适配)**:`GET /api/v1/ai/evolution/health/{workflow_id}` 执行 0-Token 健康度与活跃模型能力漂移诊断并计算 DGM 历史最佳父版本;`POST /api/v1/ai/evolution/propose/{workflow_id}` 结合 `meta.workflow_evolver` 线上发布的 `diag_node` / `patch_node` 提示词及历史进化台账正负经验产出补丁;`POST /api/v1/ai/evolution/eval/{workflow_id}` 与 `POST /api/v1/ai/evolution/incubate` 分别支持样本 A/B 对照与从 `default.general` 高频提问孵化新工作流。运行完成后通过 `schedule_post_run_evolution` 异步非阻塞检查灰度与冷却条件。 - **Tier 2(元进化 & 可扩展注册表)**:`POST /api/v1/ai/evolution/meta-evolve` 按独立开关(`off | draft | auto`)迭代 `meta.workflow_evolver` 提示词策略;同时通过 `EvolutionSignalDetector`(`SIGNAL_DETECTORS`)与 `EvolutionEvaluator`(`EVALUATORS`)协议方便后续扩展新探针或评测器。 +- **进化安全约束(v0.82.0 复核后补强)**: + - **允许「无需修改」**:模型返回合法的空 `node_patches` 时本轮以 `applied_status: no_change` 正常结束,不生成新版本与台账;确定性兜底仅在检测到真实信号(失败/差评/模型能力不匹配/管理员指令/台账结果)时才出补丁,不再追加泛化提示词。 + - **可判对错的 A/B 样本**:样本可在 `POST /api/v1/ai/workflows/{id}/fixtures` 的 `expect` 中声明 `numbers`、`must_include`、`must_not_include`、`require_uncertainty_without_evidence`、`min_evidence`(存于 `context_json.expect`);评测同时判定执行错误、护栏校验与断言,任一样本在候选版本上由通过变失败即判 `regressed`。**自动发布前强制执行 A/B 门禁**:没有样本、样本无断言或存在退化都会拦截发布。 + - **以线上版本为基线**:后台/自动发布进化始终基于当前生效版本生成候选,不读取也不清空未发布的人工草稿(自动草稿模式遇到人工草稿直接跳过),台账 `changes_vs_live` 记录候选相对线上版本的完整差异,自动发布变更半径也按完整差异计算。 + - **灰度防覆盖**:灰度结算前核对当前生效版本仍是本轮灰度目标,若已被人工发布或回滚取代则标记 `superseded` 且不回滚(元引擎灰度同理)。 + - **元进化字段必须生效**:元进化仅允许修改 `diag_node.system_prompt / prompt` 与 `patch_node.system_prompt / prompt / thinking_enabled`,这些字段都会进入业务进化请求(`build_business_evolution_request`);元进化默认保持关闭。 +- **地球工作流取数、证据与卡片输出**:`dag_executor.py` 按实体类型为每个数据源选取各自对象 ID(多选海缆/船舶/BGP 时与点击顺序无关);`interactive / ingest` 边按实际触发来源路由(前台新闻分析不再执行后台汉化分支);`compute.posture.brief` 等严格 JSON 节点以非流式执行,经 `StrategicPostureBrief` 与证据 ID 核验后渲染为正文,并在输出节点编译算力 `view_spec` 工作台(通过收尾 `meta` 事件与 `done.view_spec` 下发);`require_evidence` 护栏未通过时向用户追加「原因待核实」与待查项,`done.status` 记为 `unverified` 并附 `verification`。 +- **草稿绑定隔离**:草稿中的地球入口绑定保存在 `draft_graph.bindings`(详情返回 `draft_bindings`),仅在发布时生效、丢弃草稿即恢复;每个发布版本的 `graph_json.bindings` 同时快照绑定,回滚时一并恢复。「仅保存绑定」(`PATCH /workflows/{id}`)仍为即时生效的显式操作。 - **反馈与运行记录接口**:`POST /api/v1/ai/runs/{run_id}/feedback`(提交 `-1 | 0 | 1` 评价与原因备注,差评实时复核灰度健康)与 `GET /api/v1/ai/runs?feedback=negative|positive`;战略策略与台账维护由 `GET/PUT /api/v1/ai/evolution/policy`、`GET /api/v1/ai/evolution/ledger` 与 `POST /api/v1/ai/evolution/ledger/{entry_id}/dismiss` 提供。 保存、设为默认和连通性测试是三个独立职责:保存只持久化表单,设为默认只切换默认 provider/tool,连通性测试只验证当前草稿是否可用,不应隐式保存或切换默认项。 diff --git a/docs/technical/zh/earth-frontend-context.md b/docs/technical/zh/earth-frontend-context.md index b6a01790..0c952a75 100644 --- a/docs/technical/zh/earth-frontend-context.md +++ b/docs/technical/zh/earth-frontend-context.md @@ -433,7 +433,7 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文 跨 Interactable 的同坐标关系也在公共层记录,但真实位置必须始终以 `icon_base_position` 为准。缩放、避让、聚合和后续 spiderfy 展开都只能改变屏幕表现,不能写回 `marker.position` 或 `THREE.Points` 里的业务锚点;巡航定位、详情卡、搜索定位和 picking 返回对象都必须落回真实经纬度。多个图标归入同一个经纬度 key 时,公共层只写 `icon_avoidance_*` 元数据,供业务层弱化 halo 或显示聚合提示;真正的低缩放聚合应通过独立 cluster glyph / screen layout 层实现,而不是把对象沿地表切平面挪开。 -地表标记保留分类图标,聚合使用固定地理成员及带数量的实心圆。缩放只驱动 320ms 展开/收拢补间,不重新分档聚类;超过 250% 展开,500% 无聚合圆标。船只关闭聚合,保留独立航向箭头。实现与验收见 [聚合说明](/home/ray/dev/linkong/planet/docs/technical/zh/earth-interactable-clustering.md)。 +地表标记保留分类图标,聚合使用固定地理成员及 `28px` 深色半透明内核搭配分色外环的圆形徽标。缩放只驱动 320ms 展开/收拢补间,不重新分档聚类;超过 250% 展开,500% 无聚合圆标。船只关闭聚合,保留独立航向箭头。实现与验收见 [聚合说明](/home/ray/dev/linkong/planet/docs/technical/zh/earth-interactable-clustering.md)。 接口细节、生命周期和接入示例见: @@ -641,7 +641,7 @@ Earth 由 `earth-runtime-plugin.mjs` 将本地模块合并为带内容哈希的 ### 聚合圆标与 Spiderfy -普通地表标记继续由 `interactable.js` 批量绘制;聚合组使用 `cluster-presentation.js` 的同一组投影节点贯穿合并、展开和展开后停留。圆标为 26px 实心渐变圆,显示真实成员数,混合类别带琥珀外圈。分组只随数据或筛选更新,缩放过程中不反复拆成中间子簇。 +普通地表标记继续由 `interactable.js` 批量绘制;聚合组使用 `cluster-presentation.js` 的同一组投影节点贯穿合并、展开和展开后停留。圆标统一采用 `28px` 深色半透明玻璃内核与白字计数,单类别使用 `2.5px` 纯色圆环,混合类别由 `buildClusterRingGradient` 生成按占比分段(带 `4°` 深色分隔与最小可见扇区下限)的 `conic-gradient` 多色圆环,并通过 `formatClusterTitle` 输出本地化大类/子类别明细。分组只随数据或筛选更新,缩放过程中不反复拆成中间子簇。 `cluster-motion.js` 用固定 320ms 三次缓动控制进度。可见图标准备和解码完成后才开始计时,纹理编码按缓存复用;子点从组中心补间到真实标记投影,最终显示偏移由 `marker-stack.js` 统一计算。动画与终点保持同一个 DOM 节点,反向切换从当前进度续接。 @@ -753,3 +753,9 @@ BGP 观测站以 collector 编号建立标记索引。共享索引不登记空 I - `workflow-bindings.js` 拉取 `/api/v1/earth/workflow-bindings` 发布的白名单工作流绑定,依据当前选中实体类型与交互界面位面(信息卡、新闻卡、算力专题卡、Copilot 快捷动作与多选对比托盘)动态渲染专项分析动作。 - Electron 客户端 `screen-recorder.ts` 以 `win.webContents.mainFrame` 捕获无边框纯净画面并保持 Windows 原生 Alt 菜单兼容;`i18n.js` 与 `index.html` 对齐 `zh-CN` / `en-US` 纯净语种映射并同步管理台语言偏好。 + +### 贴地影响范围、三维视觉升级与优先一折连线(v0.83.0) + +- **贴地影响范围与阶段导演指令**(`influence-zones.js` + `scene_directives.py`):支持 AI / 场景指令下发 `influence_zones`(国家/区域预设多边形及大圆辐射区),通过单次离屏 `scratchCanvas` 模糊合成与层级排序(`tier` / `z_index`)渲染可配置颜色、透明度、`edge_mode`(`sharp` / `soft`)及入场扫光;保持 `renderOrderBase = 0.965`,位于高清地表之上、国界与交互图标之下。 +- **行星本体光影与丝带管线**:`earth-surface-material.js` 与 `earth.js` 结合本地 `earth_clouds_2048.png` 实现三阶瑞利散射晨昏过渡、海面掠射高光与地表云影投影;`surface-ribbon.js` 为国界 hover、BGP 雷达/高空路由、选中海缆流光、船舶尾迹及选中卫星轨道提供统一屏幕空间抗锯齿发光丝带;`iridium-footprint-adapter.js` 将 Iridium 足迹迁入 GPU 顶点投影。 +- **卡片连线优先一折与管理写鉴权**:`callout-connector.js`(`applyPreferredOneBendAnchor`)在主轴跨度与卡片可用边长充足时优先偏出单一折点(严格保持 `<= 1` 折,短距或紧凑胶囊平滑退化为 2 点直线);`admin-write-auth.js` 统一管控 Earth 侧算力中心位置采集与保存的管理员会话鉴权及 `/login` 引导。 diff --git a/docs/technical/zh/earth-interactable-clustering.md b/docs/technical/zh/earth-interactable-clustering.md index 0265dff0..3e1fdd58 100644 --- a/docs/technical/zh/earth-interactable-clustering.md +++ b/docs/technical/zh/earth-interactable-clustering.md @@ -1,6 +1,6 @@ # 智能星球可交互图标聚合 -`interactable.js` 负责固定地理成员,`cluster-motion.js` 负责时间补间,`cluster-presentation.js` 负责圆形聚合、展开图标、拾取与 Spiderfy。普通独立标记继续使用 GPU Points;聚合成员从动画开始到终点由同一 DOM 图标显示,不再切回另一套位置。 +`interactable.js` 负责固定地理成员,`cluster-motion.js` 负责时间补间,`cluster-presentation.js` 负责 `28px` 深色玻璃内核搭配 `2.5px` 纯色或按子类别占比分段的 `conic-gradient` 圆环聚合徽标、展开图标、拾取与 Spiderfy。普通独立标记继续使用 GPU Points;聚合成员从动画开始到终点由同一 DOM 图标显示,不再切回另一套位置。 ## 成员与缩放 diff --git a/docs/technical/zh/earth-render-layer-order.md b/docs/technical/zh/earth-render-layer-order.md index 31f65e0f..400bfbb6 100644 --- a/docs/technical/zh/earth-render-layer-order.md +++ b/docs/technical/zh/earth-render-layer-order.md @@ -21,8 +21,10 @@ | 0 | 智能星球基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 | | 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset = 0.32`,与海陆填色共用网格及半径 | depthTest=true、depthWrite=false,禁用 raycast | 加载占位及高清材质关闭时使用;填色就绪后按 renderOrder 覆盖。 | | 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 | -| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距。 | -| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3 | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照并入高清地表,不新增全屏后处理。 | +| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距;支持三阶瑞利散射晨昏过渡与海面掠射光。 | +| 0.962 | 云影投影球壳 | `earth.js` | 与高清材质共用球半径、微角偏移 | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 随大气云图开关联动,基于 `earth_clouds_2048.png` 投射柔和地表云影,严格位于 `0.96` 之上、`0.965` 之下。 | +| 0.965 | 贴地影响范围层 | `influence-zones.js`, `scene_directives.py` | 复用 `r = 100.48`(`EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET`)`128×128` 球壳;`renderOrderBase = 0.965`,按 `tier` / `z_index` 递增 `0.0003` | `depthTest: true`, `depthWrite: false`, 禁用 raycast | 支持区域预设单次离屏模糊合成与圆形大圆距离片元着色,严格压在 `0.96` 高清地表之上且低于国界线 `0.97` 与全部交互图标。 | +| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3(`FrontSide` Shader + `earth_clouds_2048.png`) | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照与 Mie 前向散射并入高清地表与大气壳,不新增全屏后处理。 | | 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆与登陆点统一使用高清地表 `0.48` 偏移和同源三角表面坐标 | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 | | 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 | | 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 | @@ -110,4 +112,4 @@ Earth 的地表不是单一 mesh,而是多层近似同心球:基座球、海 区域新闻与算力保留 `#earth-region-callouts` 根节点(z-index 20),并与物件详情共享 `callout-stage-arbitrator.js` 的左右侧及纵向走廊;中美双主舞台对比卡通过 `bilateralPeerKey` 对称分配左右走廊。区域根内展开卡片为 50、拖拽前景为 55,悬停展开层为 60–65;普通胶囊为 30,背面胶囊为 8 并渐淡缩小,而主舞台及悬停展开卡在背面时保持正文 100% 不透明,仅将连线切换为 `.is-rear` 虚线边缘引导并激活标题栏“转至正面视角”按钮。 -算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线合批为单次 `LineSegments`(`renderOrder = 4.55`,顶点抬升高于球面壳避免远景 z-fighting);BGP 舞台回放逻辑 AS 路由弧线以高空虚线/实线绘制(`renderOrder = 4.72` / `4.76`),退出或隐藏图层时立即 `dispose()` 几何与材质。 +算力专题下钻图层与逻辑路由演出弧线严格遵守同心壳深度与合批规则:中国“东数西算”八大国家算力枢纽复用 `createInteractableLayer` 单次实例化合批,贴地偏移为 `EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48`、`renderOrder = 4.58`;西部绿电枢纽双环 `AdditiveBlending` 脉冲环 `renderOrder = 4.42`(`depthWrite: false`),东西部协同弧线与高空 BGP 逻辑路由、国界 hover、选中海缆流光、船舶尾迹及选中卫星轨道共用 `surface-ribbon.js` 屏幕空间抗锯齿发光丝带底层(摆脱 Windows ANGLE 下 `THREE.Line` 1px 限制),Iridium 足迹通过 `iridium-footprint-adapter.js` 迁入 GPU 顶点投影;退出或隐藏图层时立即 `dispose()` 几何与材质。 diff --git a/docs/version-history.md b/docs/version-history.md index 0ad38d17..67e38388 100644 --- a/docs/version-history.md +++ b/docs/version-history.md @@ -16,12 +16,13 @@ ## Current Version - `main` 当前主线历史推导到:`0.16.5` -- `dev` 当前开发分支历史推导到:`0.82.0` +- `dev` 当前开发分支历史推导到:`0.83.0` ## Timeline | Version | Type | Branch | Commit | Summary | | --- | --- | --- | --- | --- | +| `0.83.0` | feature | `dev` | `v0.83.0` | Earth Phase 1–4 贴地影响范围与三维视觉升级、聚合分色环与优先一折连线、AI 参谋自进化加固与数据源连通性修复、桌面客户端启动与资源包更新及代码文档清理 | | `0.82.0` | feature | `dev` | `v0.82.0` | AI 参谋 3 层工作流自进化与元进化(Tier-0 安全内核/金丝雀回滚/Fixture A/B 评测/多模态 Playground 与地球绑定)、Electron 无边框录屏与 i18n、AI 模型目录升级及 README Mermaid 架构图 | | `0.81.0` | feature | `dev` | `v0.81.0` | 重构 AI 参谋(纯聊天 Playground/本地上下文抽屉/React Flow 9 工作流编排/AI Diff 调优/运行审计)与告警观测台,升级 L0–L4 Tool-Calling 位置 Agent、防爬鉴权与 X-API-Key、桌面录屏及多模型聚合目录 | | `0.80.3` | improvement | `dev` | `v0.80.3` | 发布含全平台最新客户端安装包与 Earth 热更包的 0.80.3;固化仅含客户端更新才创建 Gitea Release 与 OCI release-manifest 发现规则 | diff --git a/frontend/package.json b/frontend/package.json index c020b750..92217d8c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "planet-frontend", - "version": "0.82.0", + "version": "0.83.0", "private": true, "packageManager": "bun@1", "dependencies": { diff --git a/frontend/public/earth/assets/earth_clouds_2048.png b/frontend/public/earth/assets/earth_clouds_2048.png new file mode 100644 index 00000000..57adc635 Binary files /dev/null and b/frontend/public/earth/assets/earth_clouds_2048.png differ diff --git a/frontend/public/earth/css/compute-topic.css b/frontend/public/earth/css/compute-topic.css index c27ec851..0dff9a60 100644 --- a/frontend/public/earth/css/compute-topic.css +++ b/frontend/public/earth/css/compute-topic.css @@ -1308,15 +1308,28 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging) position: absolute; z-index: 162; left: 50%; - bottom: calc(86px * var(--hud-scale)); + bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1)); transform: translateX(-50%); - width: min(calc(760px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); + width: min(calc(640px * var(--hud-scale)), calc(100vw - 2 * var(--hud-offset))); padding: 0; border-radius: 0; display: flex; flex-direction: column; gap: 0; border-color: rgba(145, 195, 255, 0.38); + transition: bottom 0.24s ease; +} + +body:has(.earth-bottom-dock > :not([hidden])) .stage-narrative-bar { + bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1) + 48px); +} + +body:has(.earth-toolbar-cluster.is-expanded) .stage-narrative-bar { + bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1)); +} + +body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidden])) .stage-narrative-bar { + bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1) + 48px); } .stage-narrative-bar__top { @@ -4163,6 +4176,12 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist { background: rgba(120, 180, 255, 0.2); } +.wb-action-pill.is-active { + border-color: rgba(164, 214, 255, 0.56); + background: rgba(92, 180, 255, 0.24); + color: #e0f2fe; +} + .wb-action-pill .material-symbols-rounded { display: inline-flex; align-items: center; diff --git a/frontend/public/earth/css/hud.css b/frontend/public/earth/css/hud.css index 252cafdc..59b02041 100644 --- a/frontend/public/earth/css/hud.css +++ b/frontend/public/earth/css/hud.css @@ -4031,15 +4031,14 @@ label.is-disabled.earth-mobile-settings-card { max-height: calc(30px * var(--hud-scale)); aspect-ratio: 1 / 1; padding: 0; - border: 1px solid rgba(122, 180, 255, 0.24); + border: 1px solid rgba(212, 227, 244, 0.16); border-radius: 50%; - background: - radial-gradient(circle at 35% 22%, rgba(255, 255, 255, 0.2), transparent 58%), - linear-gradient(180deg, rgba(121, 159, 207, 0.18), rgba(72, 101, 139, 0.24)); + background: rgba(255, 255, 255, 0.045); color: var(--hud-title); cursor: pointer; vertical-align: middle; transition: + background 0.16s ease, border-color 0.18s ease, color 0.18s ease, transform 0.18s ease, @@ -4065,7 +4064,8 @@ label.is-disabled.earth-mobile-settings-card { .earth-settings-reload-action:hover { transform: translateY(-1px); - border-color: rgba(125, 197, 255, 0.46); + background: rgba(255, 255, 255, 0.09); + border-color: rgba(148, 197, 255, 0.36); } .earth-settings-reload-action:disabled { @@ -4577,20 +4577,26 @@ label.is-disabled.earth-mobile-settings-card { .earth-shortcut-key { min-width: calc(68px * var(--hud-scale)); - border: 1px solid rgba(122, 180, 255, 0.24); - border-radius: calc(6px * var(--hud-scale)); - background: - radial-gradient(circle at 35% 22%, rgba(255, 255, 255, 0.16), transparent 58%), - linear-gradient(180deg, rgba(121, 159, 207, 0.16), rgba(72, 101, 139, 0.2)); + border: 1px solid rgba(212, 227, 244, 0.16); + border-radius: 0; + background: rgba(255, 255, 255, 0.04); color: var(--hud-title); padding: calc(6px * var(--hud-scale)) calc(10px * var(--hud-scale)); font: inherit; font-size: calc(0.68rem * var(--hud-scale)); - font-weight: 800; + font-weight: 700; + letter-spacing: 0.04em; cursor: pointer; + transition: background 0.16s ease, border-color 0.16s ease, color 0.16s ease; +} + +.earth-shortcut-key:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(148, 197, 255, 0.34); } .earth-shortcut-key.is-capturing { + background: rgba(52, 211, 153, 0.12); border-color: rgba(110, 226, 188, 0.52); color: #d8fff3; } @@ -5095,13 +5101,18 @@ label.is-disabled.earth-mobile-settings-card { .legend-filter { width: 100%; border: 0; + border-radius: calc(4px * var(--hud-scale)); background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; + transition: opacity 0.16s ease, background 0.16s ease; } +.legend-filter:hover { background: rgba(255, 255, 255, 0.06); } .legend-filter[aria-pressed="false"] { opacity: 0.35; } +.legend-filter[aria-pressed="false"]:hover, +.legend-filter[aria-pressed="false"]:focus-visible { opacity: 0.95; } .legend-filter:focus-visible { outline: 1px solid #7dd3fc; outline-offset: -1px; } .satellite-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 6; contain: layout style paint; } @@ -5119,13 +5130,14 @@ label.is-disabled.earth-mobile-settings-card { .map-clusters { position:absolute; inset:0; pointer-events:none; z-index:5; } .map-clusters__legs { position:absolute; inset:0; width:100%; height:100%; overflow:visible; pointer-events:none; } .map-clusters__legs line { stroke:#94a3b8; stroke-width:1; } -.map-cluster-badge { position:absolute; width:26px; height:26px; padding:0; display:grid; place-items:center; - transform:translate(-50%,-50%); border-radius:50%; border:1.5px solid color-mix(in srgb,var(--cluster-color,#a855f7),#ffffff 68%); - background:linear-gradient(135deg,var(--cluster-color,#a855f7),color-mix(in srgb,var(--cluster-color,#a855f7),#020617 40%)); - box-shadow:0 0 14px color-mix(in srgb,var(--cluster-color,#a855f7),transparent 30%),0 4px 10px #0008; - color:white; font:800 11px system-ui,sans-serif; cursor:pointer; pointer-events:auto; } +.map-cluster-badge { position:absolute; width:28px; height:28px; padding:0; display:grid; place-items:center; + transform:translate(-50%,-50%); border-radius:50%; border:2.5px solid transparent; + background:linear-gradient(155deg,rgba(15,25,42,0.92),rgba(7,13,24,0.95)) padding-box,linear-gradient(var(--cluster-color,#a855f7),var(--cluster-color,#a855f7)) border-box; + box-shadow:inset 0 1px 0 rgba(255,255,255,0.16),0 0 12px color-mix(in srgb,var(--cluster-color,#38bdf8),transparent 64%),0 4px 10px #0008; + color:white; font:800 11px system-ui,sans-serif; font-variant-numeric:tabular-nums; cursor:pointer; pointer-events:auto; } .map-cluster-badge:hover { transform:translate(-50%,-50%) scale(1.18); } -.map-cluster-badge.is-mixed::after { content:""; position:absolute; inset:-4px; border:1.5px solid #f59e0b; border-radius:50%; pointer-events:none; } +.map-cluster-badge.is-mixed { + background:linear-gradient(155deg,rgba(15,25,42,0.92),rgba(7,13,24,0.95)) padding-box,var(--cluster-ring,conic-gradient(#14b8a6,#a855f7)) border-box; } .map-cluster-child { position:absolute; left:0; top:0; width:36px; height:36px; border:0; padding:0; background:transparent; cursor:pointer; pointer-events:auto; } .map-cluster-child img { width:100%; height:100%; pointer-events:none; } .map-cluster-badge[hidden],.map-cluster-child[hidden] { display:none; } @@ -5147,3 +5159,149 @@ label.is-disabled.earth-mobile-settings-card { @media (prefers-reduced-motion:reduce) { .has-bgp > .map-cluster-bgp-pulse { animation:none; display:none; } } .map-cluster-child.is-selected img { filter:drop-shadow(0 0 5px var(--member-color,#38bdf8)) brightness(1.15); } + +.earth-bottom-dock { + position: fixed; + left: 50%; + bottom: calc(var(--hud-offset, 16px) + 74px * var(--hud-scale, 1)); + transform: translateX(-50%); + z-index: 160; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: center; + gap: 8px; + width: max-content; + max-width: min(94vw, 1080px); + pointer-events: none; + transition: bottom 0.24s ease; +} +body:has(.earth-toolbar-cluster.is-expanded) .earth-bottom-dock { + bottom: calc(var(--hud-offset, 16px) + 168px * var(--hud-scale, 1)); +} +.layout-mode-mobile .earth-bottom-dock { + bottom: calc(88px + var(--safe-bottom, 0px)); + flex-direction: column-reverse; + max-width: calc(100vw - 16px); +} + +.earth-influence-pill { + position: relative; + flex: 0 1 auto; + display: flex; + align-items: center; + gap: 12px; + height: 38px; + box-sizing: border-box; + max-width: min(86vw, 680px); + padding: 6px 10px 6px 12px; + border-radius: 999px; + pointer-events: auto; +} +.earth-bottom-dock:has(#earth-target-tray:not([hidden])) .earth-influence-pill { + max-width: min(56vw, 520px); +} +.layout-mode-mobile .earth-bottom-dock:has(#earth-target-tray:not([hidden])) .earth-influence-pill { + max-width: calc(100vw - 16px); +} +.earth-influence-pill[hidden] { + display: none; +} +.earth-influence-pill__viewport { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + display: flex; + align-items: center; +} +.earth-influence-pill__viewport.is-marquee { + -webkit-mask-image: linear-gradient(90deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%); + mask-image: linear-gradient(90deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%); +} +.earth-influence-pill__track { + display: inline-flex; + align-items: center; + gap: 24px; + width: max-content; +} +.earth-influence-pill__viewport.is-marquee .earth-influence-pill__track { + animation: earthInfluenceMarquee var(--marquee-duration, 18s) linear infinite; +} +.earth-influence-pill:hover .earth-influence-pill__track { + animation-play-state: paused; +} +.earth-influence-pill__group { + display: inline-flex; + align-items: center; + gap: 12px; + flex: none; +} +@keyframes earthInfluenceMarquee { + from { + transform: translateX(0); + } + to { + transform: translateX(calc(-50% - 12px)); + } +} +@media (prefers-reduced-motion: reduce) { + .earth-influence-pill__viewport.is-marquee { + overflow-x: auto; + scrollbar-width: none; + -webkit-mask-image: none; + mask-image: none; + } + .earth-influence-pill__viewport.is-marquee .earth-influence-pill__track { + animation: none; + } +} +.earth-influence-pill__item { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + line-height: 1.2; + color: rgba(241, 245, 249, 0.92); + white-space: nowrap; +} +.earth-influence-pill__dot { + width: 8px; + height: 8px; + border-radius: 999px; + flex: none; + background: var(--zone-color, #38bdf8); +} +.earth-influence-pill__slider-wrap { + display: inline-flex; + align-items: center; + gap: 6px; + padding-left: 8px; + border-left: 1px solid rgba(148, 163, 184, 0.22); +} +.earth-influence-pill__slider { + width: 72px; + accent-color: #38bdf8; + cursor: pointer; +} +.earth-influence-pill__clear { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 999px; + background: rgba(148, 163, 184, 0.16); + color: rgba(226, 232, 240, 0.9); + cursor: pointer; +} +.earth-influence-pill__clear:hover { + background: rgba(148, 163, 184, 0.28); +} +.earth-influence-pill__clear .earth-influence-pill-icon.material-symbols-rounded { + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; +} diff --git a/frontend/public/earth/css/info-panel.css b/frontend/public/earth/css/info-panel.css index 4fd08b7b..5c7e2022 100644 --- a/frontend/public/earth/css/info-panel.css +++ b/frontend/public/earth/css/info-panel.css @@ -829,6 +829,19 @@ body[data-callout-line-style="bold"] .callout-connector circle { font-size: calc(0.7rem * var(--hud-scale)); } +.info-card-auth-link { + display: inline-block; + margin-left: calc(6px * var(--hud-scale)); + color: var(--hud-accent); + font-weight: 500; + text-decoration: none; +} + +.info-card-auth-link:hover, +.info-card-auth-link:focus-visible { + text-decoration: underline; +} + .info-card-compute-collect-candidates { margin-top: calc(6px * var(--hud-scale)); display: flex; @@ -995,7 +1008,7 @@ body[data-callout-line-style="bold"] .callout-connector circle { display: flex; flex-direction: column; gap: 3px; - border-radius: 12px; + border-radius: 0; letter-spacing: 0; } @@ -1063,19 +1076,19 @@ body[data-callout-line-style="bold"] .callout-connector circle { } .earth-target-tray { - position: fixed; - left: 50%; - bottom: calc(var(--hud-offset, 16px) + 4px); - transform: translateX(-50%); - z-index: 160; - max-width: min(720px, calc(100vw - 24px)); - padding: 6px 8px; - border-radius: 14px; + position: relative; + flex: 0 1 auto; + max-width: min(90vw, 640px); + min-height: 38px; + box-sizing: border-box; + padding: 5px 8px; + border-radius: 999px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; letter-spacing: 0; + pointer-events: auto; } .earth-target-tray[hidden] { @@ -1137,9 +1150,9 @@ body[data-callout-line-style="bold"] .callout-connector circle { } .earth-target-tray__analyze { - height: 28px; - padding: 0 10px; - border-radius: 8px; + height: 26px; + padding: 0 11px; + border-radius: 999px; border: 1px solid rgba(92, 200, 255, 0.35); background: rgba(92, 200, 255, 0.22); color: #e6f7ff; @@ -1152,6 +1165,10 @@ body[data-callout-line-style="bold"] .callout-connector circle { letter-spacing: 0; } +.earth-target-tray .hud-panel__action { + border-radius: 999px; +} + .earth-target-tray__analyze:hover { background: rgba(92, 200, 255, 0.32); } diff --git a/frontend/public/earth/css/layer-panel.css b/frontend/public/earth/css/layer-panel.css index 466d3ee8..b67dfcce 100644 --- a/frontend/public/earth/css/layer-panel.css +++ b/frontend/public/earth/css/layer-panel.css @@ -205,11 +205,19 @@ transition: color 0.18s ease; } -/* Icon brightens when layer is active */ +/* Icon brightens when layer is active or hovered */ .layer-row:has(.layer-row-toggle.active) .layer-row-icon { color: var(--hud-accent); } +.layer-row:hover:not(:has(.layer-row-toggle.is-disabled)) .layer-row-icon { + color: var(--hud-title); +} + +.layer-row:hover:has(.layer-row-toggle.active) .layer-row-icon { + color: var(--hud-accent); +} + .layer-row-copy { flex: 1 1 auto; min-width: 0; diff --git a/frontend/public/earth/css/toolbar.css b/frontend/public/earth/css/toolbar.css index 9185e23a..6696dd4e 100644 --- a/frontend/public/earth/css/toolbar.css +++ b/frontend/public/earth/css/toolbar.css @@ -368,6 +368,11 @@ line-height: 1; } +.earth-zoom-toolbar .earth-zoom-btn:hover, +.earth-zoom-toolbar .earth-zoom-btn:focus-visible { + color: #38bdf8; +} + .earth-zoom-toolbar .earth-zoom-value { display: inline-flex; align-items: center; diff --git a/frontend/public/earth/index.html b/frontend/public/earth/index.html index be907ecb..c6f374ae 100644 --- a/frontend/public/earth/index.html +++ b/frontend/public/earth/index.html @@ -9,7 +9,7 @@