业务本体与标准实体:跨源键值对齐、对账共变算子、健康证据链与实体助手

- 新增标准业务实体(CanonicalEntity)模型、确定性跨源编码翻译、后台候选实体扫描与文档驱动实体智能助手
- 新增指标本体图谱(factor / reconciles_with / upstream_driver)、DAG 防环校验以及 ontology_neighbors / source_health 内置工具
- 新增跨源对账(analysis_reconcile)与滞后共变(analysis_cochange)分析算子,打通 [[h:H1]] 数据源健康证据链、报告导出与本体消融评测
- 数据目录新增「标准业务实体」视图与候选审阅工作台,口径页集成指标本体拓扑面板与端到端浏览器检查
This commit is contained in:
ThearchyHelios
2026-11-12 12:57:53 +08:00
parent 2f90f0eb3a
commit 8d9a712eae
106 changed files with 16654 additions and 295 deletions
+101 -8
View File
@@ -49,18 +49,25 @@ from app.providers.factory import (
)
from app.engine.sql_problems import event_checks
from app.data import catalog_view
from app.data.source_health import ledger_entry as health_ledger_entry
from app.ledger.querycore import CALIBER_QUERY
from app.tools.analysis import (
REFUSED_CODE as ANALYSIS_REFUSED,
SCOPE_KEY as ANALYSIS_SCOPE_KEY,
AnalysisScope,
call_error_text,
event_view,
health_event_view,
health_payload_of,
health_reply_text,
input_snapshot,
is_analysis_tool,
payload_of,
record_ontology_call,
reply_text,
run_snapshot,
)
from app.tools.ontology import ONTOLOGY_TOOLS, SOURCE_HEALTH
from app.tools.datasource import QUERY_PREFIX, run_masks_results, run_reads_only, run_scope_fixed, run_versions
from app.tools.registry import (
ToolArgsError,
@@ -132,6 +139,10 @@ async def _build_messages(state: GraphState, ctx: NodeContext, tools: list[BaseT
messages: list[BaseMessage] = []
system_parts: list[str] = []
if ctx.cfg("ask_data_optimization") == 1:
from app.chat.optimization import CONCISE_RULE
system_parts.append(CONCISE_RULE)
system = ctx.render_str(ctx.cfg("system", ""), state)
if system:
system_parts.append(system)
@@ -421,7 +432,8 @@ def _guard(ctx: NodeContext, model_id: str) -> Guard | None:
{k: ctx.cfg(k) for k in ("max_steps", "budget_tokens", "budget_usd")},
ctx.run.agent_limits, settings.max_agent_steps,
)
return Guard(limits=limits, window=catalog.find_context(model_id) or FALLBACK_CONTEXT)
return Guard(limits=limits, window=catalog.find_context(model_id) or FALLBACK_CONTEXT,
canonical_calls=ctx.cfg("ask_data_optimization") in (1, 2))
def _policy(ctx: NodeContext, tool: BaseTool, args: dict[str, Any], granted: set[str]) -> str:
@@ -456,9 +468,12 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
except ProviderNotConfigured as e:
raise NodeError(ctx.node.id, not_configured(e)) from e
# 绑了分析工具才建分析容器:本节点查过的结果、做过的分析都放在这里(app/tools/analysis.py),编号和交回模型的一致
# 绑了分析工具、本体工具、口径查询或显式开启调查策略时建分析容器:本节点查过的结果、做过的分析与健康核查都放在这里
bound_names = ctx.cfg("tools", []) or []
scope = (AnalysisScope(node_id=ctx.node.id, snapshot=run_snapshot(ctx.run))
if any(is_analysis_tool(n) for n in ctx.cfg("tools", []) or []) else None)
if (any(is_analysis_tool(n) or n in ONTOLOGY_TOOLS or n == CALIBER_QUERY for n in bound_names)
or bool(ctx.cfg("investigation")))
else None)
tools = await _resolve_tools(ctx, state, scope)
tool_map = {t.name: t for t in tools}
# 默认串行:一轮只调一个工具,拿到结果再想下一步。并行更快,但一批工具
@@ -493,12 +508,54 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
total_usage[key] += usage[key]
total_usage["cost_usd"] = round(total_usage["cost_usd"] + usage["cost_usd"], 6)
inline_evidence = ctx.cfg("ask_data_optimization") == 2 and evidence_on
def _live_catalog() -> dict[str, Any]:
from app.engine.evidence import build_catalog
return build_catalog(
nodes=state.get("nodes") or {},
ledger=[*(state.get("evidence") or []), *entries],
inputs=state.get("input") or {},
)
class _InlineStreamProxy:
def __init__(self, inner_ctx: NodeContext, live_cat: dict[str, Any]) -> None:
from app.engine.evidence import StreamRenderer
self._ctx = inner_ctx
self._cat = live_cat
self._renderer = StreamRenderer(live_cat, cells_allowed=True)
def __getattr__(self, attr: str) -> Any:
return getattr(self._ctx, attr)
def emit(self, event_type: EventType | str, **data: Any) -> None:
if event_type == EventType.LLM_TOKEN:
if txt := self._renderer.feed(str(data.get("delta") or "")):
self._ctx.emit(EventType.LLM_TOKEN, delta=txt)
return
if event_type == EventType.LOG and data.get("code") == "stream_fallback":
from app.engine.evidence import StreamRenderer
self._renderer = StreamRenderer(self._cat, cells_allowed=True)
self._ctx.emit(event_type, **data)
def flush(self) -> None:
if tail := self._renderer.flush():
self._ctx.emit(EventType.LLM_TOKEN, delta=tail)
# @task 的返回值会进 checkpoint:人工审批导致节点重放时,
# 之前已经完成的模型调用和工具执行不会重跑,也就不会重复计费。
@task
async def llm_step(step: int, payload: list[BaseMessage]) -> BaseMessage:
started = time.perf_counter()
response = await _invoke_streaming(model, payload, ctx, model_id)
if inline_evidence and any(e.get("kind") == "query" for e in entries):
proxy = _InlineStreamProxy(ctx, _live_catalog())
response = await _invoke_streaming(model, payload, proxy, model_id) # type: ignore[arg-type]
proxy.flush()
else:
response = await _invoke_streaming(model, payload, ctx, model_id)
_report(response, started)
return response
@@ -507,7 +564,12 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
# 用 base_model 而不是上面那个绑过工具的 model:收尾轮必须在**结构上**
# 发不出工具调用,靠提示词说"别调工具"是约束不住的
started = time.perf_counter()
response = await _invoke_streaming(base_model, payload, ctx, model_id)
if inline_evidence and any(e.get("kind") == "query" for e in entries):
proxy = _InlineStreamProxy(ctx, _live_catalog())
response = await _invoke_streaming(base_model, payload, proxy, model_id) # type: ignore[arg-type]
proxy.flush()
else:
response = await _invoke_streaming(base_model, payload, ctx, model_id)
_report(response, started)
return response
@@ -570,6 +632,8 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
# 交回模型的「【分析 An】」是同一个(_record_call 紧接着按同一个容器编),不记台账的执行没有编号
analysis = payload_of(content) if ok and is_analysis_tool(name) else None
alias = scope.next_alias() if analysis and scope is not None and evidence_on else None
health = health_payload_of(content) if ok and name == SOURCE_HEALTH else None
health_alias = scope.next_health_alias() if health and scope is not None and evidence_on else None
ctx.emit(
EventType.TOOL_END if ok else EventType.TOOL_ERROR,
tool=name,
@@ -582,6 +646,8 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
**({"query_artifacts": [q["artifact"] for q in queries]} if len(queries) > 1 else {}),
**({"analysis_artifact": analysis["artifact"], "analysis": event_view(analysis["result"], alias)}
if analysis else {}),
**({"health_artifact": health["artifact"], "source_health": health_event_view(health["result"], health_alias)}
if health else {}),
# 查询当时数据源的表结构快照:和查询快照一样落在封存范围内,证据接口从这里认它
**({"schema_artifact": first["schema_artifact"]} if first and first.get("schema_artifact") else {}),
# 这次查询的 SQL 检查结果单独带上:preview 截到前 2000 个字符,checks 通常在截掉的那段里
@@ -804,12 +870,17 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
outcome = await tool_step(step, name, args, call_id)
content = outcome["content"]
if outcome["ok"]:
record_ontology_call(scope, name, content)
record = {"tool": name, "args": args, "ok": outcome["ok"],
"duration_ms": outcome["duration_ms"], "result": content[:4000]}
if evidence_on:
# 编号只取决于 tool_step 的返回值(重放时取自 checkpoint),重放出来的还是这一套
content = _record_call(ctx.node.id, exec_no, call_id, name, args, outcome, record,
queries, entries, scope, run_id=ctx.run.run_id)
elif scope is not None and outcome["ok"] and name == SOURCE_HEALTH:
if found_health := health_payload_of(content):
scope.add_health(found_health["result"], found_health["artifact"])
transcript.append(record)
messages.append(ToolMessage(content=content, tool_call_id=call_id))
if guard:
@@ -925,9 +996,22 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
extra = {"max_tokens": extracted.get("max_tokens")} if code == "agent_field_truncated" else {}
await once(ctx, EventType.LOG, level="warn", code=code, message=message, fields=names, **extra)
raw_final_text: str | None = None
shown_text = final_text
if inline_evidence and final_text:
raw_final_text = final_text
if any(e.get("kind") == "query" for e in entries):
from app.chat.direct_evidence import normalize_and_bind_fast_citations
from app.engine.evidence import render_markers
live_cat = _live_catalog()
cleaned_raw = normalize_and_bind_fast_citations(final_text, live_cat)
shown_text = render_markers(cleaned_raw, live_cat, cells_allowed=True)
total_usage["total_tokens"] = total_usage["input_tokens"] + total_usage["output_tokens"]
result = {
"text": final_text,
"text": shown_text,
**({"raw_text": raw_final_text} if raw_final_text is not None else {}),
"steps": len(transcript),
**({"investigation": investigation} if investigation["active"] else {}),
"tool_calls": transcript,
@@ -944,11 +1028,11 @@ async def run_agent(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
if entries:
updates["evidence"] = entries
if ctx.cfg("emit_message", True):
updates["messages"] = [AIMessage(content=final_text or "(空)")]
updates["messages"] = [AIMessage(content=shown_text or "(空)")]
var_name = ctx.cfg("assign_to", "")
if var_name:
# 开了 cite_fields 的,变量里是核对过的 data(值以快照为准),下游口径卡按字段取
updates["vars"] = {var_name: cited[0] if cited is not None else final_text}
updates["vars"] = {var_name: cited[0] if cited is not None else shown_text}
return updates
@@ -987,6 +1071,15 @@ def _record_call(node_id: str, exec_no: int, call_id: str, name: str, args: dict
entries.append(ledger_entry(found["result"], node_id=node_id, exec_no=exec_no, artifact=found["artifact"],
call_id=call_id))
return reply_text(alias, found["result"])
if scope is not None and outcome.get("ok") and name == SOURCE_HEALTH:
found_health = health_payload_of(content)
if found_health is None:
return content
h_alias = scope.add_health(found_health["result"], found_health["artifact"])
record.update(alias=h_alias, health_artifact=found_health["artifact"])
entries.append(health_ledger_entry(found_health["result"], node_id=node_id, exec_no=exec_no,
artifact=found_health["artifact"], call_id=call_id))
return health_reply_text(h_alias, found_health["result"])
items = _called_queries(outcome, content, name)
if not items:
return content
+24
View File
@@ -421,6 +421,30 @@ async def run_metrics(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
metrics=[m["id"] for m in lacking], metric_names=[m["name"] for m in lacking],
reason=lacking[0]["no_data_reason"],
message="指标" + "".join(f"「{m['name']}」" for m in lacking) + lacking[0]["no_data_reason"])
if violated := [m for m in metrics if m.get("contract_findings")]:
raw_findings = [
dict(f) if isinstance(f, Mapping) else str(f)
for m in violated
for f in (m.get("contract_findings") or [])
if f
]
first_finding = raw_findings[0] if raw_findings else ""
detail = (
str(first_finding.get("detail") or first_finding.get("code") or "触发指标数值契约异常")
if isinstance(first_finding, Mapping)
else (str(first_finding) or "触发指标数值契约异常")
)
ctx.emit(
EventType.LOG,
level="warn",
code="metric_contract_violated",
metric=violated[0]["id"],
metrics=[m["id"] for m in violated],
metric_names=[m["name"] for m in violated],
findings=raw_findings,
reason=detail,
message="指标" + "".join(f"「{m['name']}」" for m in violated) + f"触发数值契约告警:{detail}",
)
card = {
"kind": "metric_set",
"validation_version": 1,
+174 -11
View File
@@ -547,6 +547,15 @@ class _MaskedCells:
snap = None
self._memo[artifact] = await _cited_masks(snap, source, self._masks, artifact) if isinstance(snap, dict) else {}
async def all_query_masks(self) -> dict[str, dict[str, list[str]]]:
"""预读当前目录全部查询快照的遮罩列映射,供快速直查在直通组装前过滤遮罩列。"""
for entry in self._catalog.values():
if isinstance(entry, dict) and entry.get("kind") == "query":
artifact = entry.get("artifact")
if isinstance(artifact, str) and artifact and artifact not in self._memo:
await self._read(artifact, entry.get("source"))
return {a: m for a, m in self._memo.items() if m}
def _masked_said(hits: list[dict[str, Any]]) -> str:
"""报告引用了遮罩列的那几处在缺口、日志里怎么说:「引用了 2 处取自遮罩列的格子(「v:Q2.r0.tel」、…)」,引用了值取自
@@ -791,19 +800,155 @@ async def _store(doc: dict[str, Any], ctx: NodeContext) -> str | None:
return None
async def _run_fast_inline_report(state: GraphState, ctx: NodeContext, on_violation: str) -> dict[str, Any]:
"""快速直查专用零模型直通证据封装:0 次 LLM 调用、< 10ms 纯内存组装 report_doc 与封存事件。"""
from app.api.evidence import withheld_metrics
from app.chat.direct_evidence import normalize_and_bind_fast_citations
from app.engine.evidence import iter_segments
started = time.perf_counter()
source = str(ctx.cfg("reuse_answer_from", ""))
previous = (state.get("nodes") or {}).get(source) or {}
raw_answer = str(
previous.get("raw_text") if isinstance(previous.get("raw_text"), str) else (previous.get("text") or "")
).strip()
shown_fallback = str(previous.get("text") or raw_answer).strip()
evidence_on = ledger_enabled(ctx.run)
zero_usage = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "cost_usd": 0, "calls": 0}
upstream_model = str(previous.get("model") or "evidence")
def _plain_pass(text_val: str) -> dict[str, Any]:
res = {
"text": text_val,
"doc_artifact": None,
"stats": {},
"violations": [],
"repairs": 0,
"model": upstream_model,
"duration_ms": int((time.perf_counter() - started) * 1000),
"answer_reused": True,
"writer_calls": 0,
**({"claims": "off", "analysis_claims": "off"} if evidence_on else {}),
}
upd: dict[str, Any] = {"nodes": {ctx.node.id: res}, "usage": zero_usage}
if ctx.cfg("emit_message", True):
upd["messages"] = [AIMessage(content=text_val or "(空)")]
var_name = ctx.cfg("assign_to", "")
if var_name:
upd["vars"] = {var_name: text_val}
return upd
if not evidence_on or not raw_answer:
return _plain_pass(shown_fallback)
spec = ctx.run.spec
upstream = {**state, "nodes": {k: v for k, v in (state.get("nodes") or {}).items() if k != ctx.node.id}}
catalog = report_catalog(upstream, spec, ctx.node) # type: ignore[arg-type]
if not any(entry.get("kind") == "query" for entry in catalog.values()):
return _plain_pass(shown_fallback)
withheld = await withheld_metrics(catalog, nodes=state.get("nodes") or {}, ledger=state.get("evidence") or [])
catalog = withhold_metrics(catalog, withheld, _masked_word())
masked = _MaskedCells(catalog)
query_masks = await masked.all_query_masks()
prepared = normalize_and_bind_fast_citations(_unfenced(raw_answer), catalog, masked_columns=query_masks)
entities = report_entities(spec, ctx.node) == "link"
allow = report_allowance(spec, ctx.node)
doc = await masked(
compose_doc(
prepared,
catalog,
node_id=ctx.run.global_id(ctx.node.id),
run_id=ctx.run.run_id,
allow_numbers=allow,
cells_allowed=True,
entities=entities,
absence=False,
analysis_claims=None,
)
)
text = doc["markdown"]
has_cited = doc["stats"].get("numbers_cited", 0) > 0 or any(
s.get("state") == "deterministic" for s in iter_segments(doc)
)
if not has_cited:
return _plain_pass(text)
doc_artifact = await _store(doc, ctx)
if doc_artifact:
ctx.emit(
EventType.REPORT_CHECKED,
doc_artifact=doc_artifact,
ok=not doc["violations"],
stats=doc["stats"],
violations=doc["violations"][:20],
repairs=0,
on_violation=on_violation,
failed=False,
claims="off",
analysis_claims="off",
)
ctx.emit(
EventType.LOG,
level="info",
code="report_answer_reused",
message="已零延迟核验查询证据并生成可点击溯源文档",
)
result = {
"text": text,
"doc_artifact": doc_artifact,
"stats": doc["stats"],
"violations": doc["violations"][:20],
"repairs": 0,
"model": upstream_model,
"duration_ms": int((time.perf_counter() - started) * 1000),
"answer_reused": True,
"writer_calls": 0,
"claims": "off",
"analysis_claims": "off",
**({"masked_metrics": withheld} if withheld else {}),
}
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}, "usage": zero_usage}
if ctx.cfg("emit_message", True):
updates["messages"] = [AIMessage(content=text or "(空)")]
var_name = ctx.cfg("assign_to", "")
if var_name:
updates["vars"] = {var_name: text}
return updates
async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
numbers, max_repairs = _options(ctx)
on_violation = str(ctx.cfg("on_violation", "") or "") or await _default_on_violation(ctx.run.run_id)
if on_violation not in ON_VIOLATION:
raise NodeError(ctx.node.id, _only("on_violation", ("flag", "fail"), on_violation))
async with SessionLocal() as session:
try:
model, model_id = await get_chat_model(session, _model_spec(ctx))
except ProviderNotConfigured as e:
raise NodeError(ctx.node.id, not_configured(e)) from e
# 写作目录的篇幅按这个模型的上下文窗口定(evidence.catalog_budget)
window = await model_window(session, _model_spec(ctx), model_id)
if ctx.cfg("ask_data_optimization") == 2:
return await _run_fast_inline_report(state, ctx, on_violation)
candidate = ""
if ctx.cfg("ask_data_optimization") == 1 and ledger_enabled(ctx.run) \
and await _run_class(ctx.run.run_id) == "exploratory":
source = str(ctx.cfg("reuse_answer_from", ""))
parents = {e.source for e in ctx.run.spec.edges if e.target == ctx.node.id}
agent_ids = {n.id for n in ctx.run.spec.nodes if n.type == NodeType.AGENT}
previous = (state.get("nodes") or {}).get(source) or {}
raw_answer = previous.get("text")
if source in parents & agent_ids and not previous.get("limited") and isinstance(raw_answer, str) \
and 0 < len(raw_answer.strip()) <= 1200 and re.search(r"\[\[(?:v|m):", raw_answer) \
and not leaked_markup(raw_answer):
candidate = raw_answer
model, model_id, window = None, "evidence", 4096
if not candidate:
async with SessionLocal() as session:
try:
model, model_id = await get_chat_model(session, _model_spec(ctx))
except ProviderNotConfigured as e:
raise NodeError(ctx.node.id, not_configured(e)) from e
window = await model_window(session, _model_spec(ctx), model_id)
spec = ctx.run.spec
# 目录按上游的产出建:这个节点自己上一次的产出(循环里重跑时)不算,它记下的 masked_metrics 这一次重新认
@@ -866,7 +1011,13 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
nudged = False
async def draft(payload: list[BaseMessage]) -> tuple[BaseMessage, str]:
nonlocal nudged
nonlocal nudged, model, model_id
if model is None:
async with SessionLocal() as session:
try:
model, model_id = await get_chat_model(session, _model_spec(ctx))
except ProviderNotConfigured as e:
raise NodeError(ctx.node.id, not_configured(e)) from e
stream = _RenderedStream(ctx, catalog, cells)
began = time.perf_counter()
response = await _invoke_streaming(model, payload, stream, model_id) # type: ignore[arg-type]
@@ -904,8 +1055,18 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
doc["analysis_scope"] = scope
return doc
response, raw = await draft(messages)
doc = await compose(raw)
reused = False
if candidate and claims != CLAIMS_JUDGE and not failed and not writer.trimmed \
and not any(entry.get("truncated") for entry in catalog.values()):
doc = await compose(candidate)
reused = not doc["violations"] and doc["stats"].get("numbers_cited", 0) > 0
if reused:
response = AIMessage(content=candidate)
ctx.emit(EventType.LOG, level="info", code="report_answer_reused",
message="已直接核验问数答案和引用证据,无需再次调用模型撰写")
else:
response, raw = await draft(messages)
doc = await compose(raw)
repairs = 0
while (blocking := _blocking(doc["violations"], numbers)) and repairs < max_repairs \
and not (repairs and not _again(blocking, analysis)):
@@ -986,7 +1147,8 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
f"报告有 {len(blocking)} 处未通过核对(已要求重写 {repairs} 次):{head}{more}。{_fail_advice(blocking)}",
)
usage = {key: sum(one[key] for one in spent) for key in spent[0]}
usage = ({key: sum(one[key] for one in spent) for key in spent[0]} if spent else
{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "cost_usd": 0, "calls": 0})
usage["cost_usd"] = round(usage["cost_usd"], 6)
text = doc["markdown"]
result = {
@@ -997,6 +1159,7 @@ async def run_report(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
"repairs": repairs,
"model": model_id,
"duration_ms": int((time.perf_counter() - started) * 1000),
**({"answer_reused": reused, "writer_calls": len(spent)} if ctx.cfg("ask_data_optimization") == 1 else {}),
**({"claims": claims} if evidence_on else {}),
# 分析说法核对的处置:出口按它和文档里记的那一项判 strict 要不要记缺口(升级前的运行没有这个键)
**({"analysis_claims": analysis} if evidence_on else {}),
+12
View File
@@ -298,11 +298,18 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
schema = first.get("schema_artifact") if first else None
# 这次查询的 SQL 检查结果单独带上:preview 只有前 2000 个字符,checks 排在 rows 后面,通常被截掉
checks = event_checks(result) if is_platform_query(name) else []
health: dict[str, Any] | None = None
if name == "source_health":
from app.tools.analysis import health_event_view, health_payload_of
health = health_payload_of(result)
ctx.emit(EventType.TOOL_END, tool=name, duration_ms=elapsed,
preview=json.dumps(result, ensure_ascii=False, default=str)[:2000],
artifact=snapshot_id, **({"query_artifact": first["artifact"]} if first else {}),
# 一次调用交回多条查询(caliber_query)时把工件 id 全列出来:只给第一条,界面上剩下的就点不开
**({"query_artifacts": [q["artifact"] for q in queries]} if len(queries) > 1 else {}),
**({"health_artifact": health["artifact"], "source_health": health_event_view(health["result"])}
if health else {}),
**({"schema_artifact": schema} if schema else {}), **({"checks": checks} if checks else {}))
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
@@ -313,6 +320,11 @@ async def run_tool(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
if snapshot_id:
entries.append({"kind": "tool", "node_id": ctx.node.id, "exec": exec_no, "artifact": snapshot_id,
"tool": name})
if health:
from app.data.source_health import ledger_entry as health_ledger_entry
entries.append(health_ledger_entry(health["result"], node_id=ctx.node.id, exec_no=exec_no,
artifact=health["artifact"]))
for item in queries:
# 实际执行的执行身份(K10):query_id 是逻辑查询、execution_id 是这一次、attempt 是第几次。
# 口径查询那条自己带着(K09 算好的),别的按这次节点执行的序号算