onto.ts 46 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
/**
 * 本体平台的类型与接口:本体空间、内核、数据管道、业务建模、能力(动作 / MCP)、SOP、统一提问、治理、评测。
 * 老的文档 / 图谱 / 数据连接接口仍在 api.ts。
 */
import { ApiError } from "./api";

async function req<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(path, init);
  if (!res.ok) {
    let detail = `HTTP ${res.status}`;
    try {
      const body = await res.json();
      detail = typeof body.detail === "string" ? body.detail : JSON.stringify(body.detail ?? body);
    } catch { /* 非 JSON */ }
    throw new ApiError(detail, res.status);
  }
  const ct = res.headers.get("content-type") ?? "";
  return (ct.includes("json") ? res.json() : res.text()) as Promise<T>;
}
const post = (body?: unknown): RequestInit => ({
  method: "POST", headers: { "Content-Type": "application/json" },
  body: body === undefined ? undefined : JSON.stringify(body),
});
const put = (body: unknown): RequestInit => ({ ...post(body), method: "PUT" });
const del: RequestInit = { method: "DELETE" };
const enc = encodeURIComponent;
const qs = (p: Record<string, unknown>) => {
  const q = new URLSearchParams();
  Object.entries(p).forEach(([k, v]) => { if (v !== undefined && v !== null && v !== "") q.set(k, String(v)); });
  const s = q.toString();
  return s ? `?${s}` : "";
};

// ============================== 类型 ==============================
/** 本体只有四种积木;函数再按类别细分。 */
export type ConceptKind = "object_type" | "link_type" | "function" | "action";
export type FnCategory = "aggregate" | "rule" | "calendar" | "decision" | "ml" | "ai";
/** 细分类型:函数取类别,其余就是积木种类。颜色、图标、分组都按它。 */
export type TypeKey = "object_type" | "link_type" | FnCategory | "action";

export interface Me {
  id: string; name: string; kind: string; roles: string[]; biz_roles: string[];
  scope: Record<string, Record<string, string[]>>; workspace: string; permissions: string[];
}
export interface UserRec {
  id: string; name: string; roles: string[]; biz_roles: string[];
  scope: Record<string, Record<string, string[]>>; enabled: boolean;
}

export interface Binding { id: string; concept_id: string; ds_id: number; target_kind: string; ref: any; updated_at?: string }
export interface Evidence { id?: number; doc_id: number; chunk_id: string; heading: string; snippet: string }
export interface ConceptBrief {
  id: string; kind: ConceptKind; kind_label: string; name: string; display_name: string;
  category: FnCategory | ""; object_type: string;
  description: string; synonyms: string[]; status: "draft" | "published" | "deprecated";
  dirty: boolean; version: number; origin: string; published: boolean; updated_at: string | null;
  created_by?: string; domain?: string;
  /** 是否已落到数据:对象有表、关系有 join、聚合有取数表达式;不需要绑定的积木为 null */
  mapped?: boolean | null;
}
export interface Concept extends ConceptBrief {
  spec: any; bindings: Binding[]; evidence: Evidence[]; published_copy: any;
  graph_entities?: { id: string; label: string; type: string; degree: number }[];
}
export interface KernelMeta {
  kinds: { kind: ConceptKind; label: string; desc: string }[];
  categories: { category: FnCategory; label: string; desc: string; engine: string }[];
  data_types: string[]; rule_kinds: string[]; directions: string[]; cardinality: string[];
  binding_kinds: Record<string, string>; functions: string[];
  tools: ToolBrief[]; readonly_functions: FunctionBrief[]; roles: string[];
}
export interface KernelStats {
  by_kind: Record<string, { total: number; draft?: number; published?: number; deprecated?: number }>;
  by_category: Record<string, number>;
  dirty: number; revision: number;
}
export interface Diff {
  added: { id: string; name: string; kind: string; type_key?: string }[];
  removed: { id: string; name: string; kind: string; type_key?: string }[];
  changed: { id: string; name: string; kind: string; type_key?: string; fields: string[];
             changes?: { field: string; before: any; after: any }[] }[];
}
export interface GraphNode {
  id: string; kind: ConceptKind; type_key: TypeKey; name: string; label: string; status: string; dirty: boolean;
  description: string; pos: { x: number; y: number } | null; bound: boolean; owner?: string;
  properties?: { name: string; is_key?: boolean; is_writable?: boolean; data_type?: string }[];
}
export interface GraphEdge { id: string; source: string; target: string; kind: "link" | "owns"; label: string; cardinality?: string; status?: string }
export interface DraftEvent {
  type: "stage" | "classify" | "entities" | "spec" | "validate" | "done" | "error";
  stage?: string; message?: string; kind?: ConceptKind; category?: FnCategory | ""; label?: string; name?: string;
  reason?: string; object_type?: string; properties?: string[]; inputs?: string[]; spec?: any; attempt?: number;
  ok?: boolean; error?: string; draft?: { kind: ConceptKind; name: string; description: string; synonyms: string[]; spec: any };
  samples?: { input: any; expect?: any }[];
}
export interface McpTool { name: string; description: string; inputSchema: any; annotations?: { group?: string } }
export interface RoleRec { id: number; name: string; description: string; members: string[] }
export interface RevisionRec { revision: number; note: string; diff: Diff; published_by: string; created_at: string; concepts: number }
export interface LinkResult {
  concepts: { id: string; kind: string; name: string; matched: string[] }[];
  instances: { concept_id: string; type_name: string; key: string; label: string; matched: string }[];
  time: any;
}
export interface ObjectRec { type_id: string; type_name: string; key: string; label: string; properties: Record<string, any>; overridden?: string[] }

/** binds:函数的「身份参数」(如指标取数的 metric),SOP 编辑器据此把「我的指标 / 规则」映射成对内置函数的调用 */
export interface FunctionBrief { kind: "function"; name: string; title: string; description: string; input_schema: any; category: string; output: string;
  binds?: { param: string; ref: string } | null }
/** 参数下拉的一个选项(x-ref)。status=draft 表示引用的是还没发布的积木 */
export interface RefOption { value: string | number; label: string; id?: string; status?: "published" | "draft"; group?: string; hint?: string; type?: string; enum?: string[] }
export interface Recipe { id: string; title: string; desc: string;
  fields: { name: string; label: string; ref?: string; required?: boolean; multi?: boolean; type?: string; default?: any }[] }
export interface DraftRef { step_id: string; kind: string; name: string }
export interface ToolBrief { kind: "tool"; name: string; title: string; description: string; input_schema: any; risk_level: string; reversible: boolean; external: boolean }
export interface CapDef {
  id: string; kind: "skill" | "action" | "endpoint"; kind_label: string; name: string;
  display_name: string; description: string; spec: any; status: "draft" | "published" | "disabled";
  version: number; risk_level: string; updated_at: string;
}
export interface ActionPreview {
  action: { id: string; name: string; display_name: string; version: number; reversible: boolean; risk_level: string; approver_roles: string[]; priority?: string };
  /** 审批策略算出来的结果:这一单会不会自动执行、为什么 */
  auto?: { mode: string; eligible: boolean; why: string };
  params: Record<string, any>; target_ref: string; summary: string;
  effects: { tool: string; label: string; args: any; preview: { summary: string; changes?: any[]; external?: boolean }; risk_level: string; external: boolean }[];
}
export interface ActionRun {
  id: string; action_id: string; action_name: string; kind: "normal" | "revert"; revert_of: string;
  params: Record<string, any>; target_ref: string; initiator_kind: "user" | "ai" | "sop" | "watch";
  initiator_id: string; submitted_by: string; source_ref: string; reason: string;
  status: string; preview: ActionPreview; result: any; error: string;
  created_at: string; decided_at: string | null; finished_at: string | null;
  approvals: { id: string; status: string; decided_by: string; comment: string; decided_at: string | null; approver_roles: string[] }[];
  can_approve?: boolean; cannot_reason?: string;
  priority: "P0" | "P1" | "P2" | "P3";
  evidence: { kind: string; text: string; ref: string }[];
  impact: { by_type?: Record<string, number>; total?: number; sample?: { type_name: string; label: string; depth: number }[]; synced_at?: string };
}
export interface TaskRec {
  id: string; title: string; description: string; role: string; assignee: string;
  form: { name: string; label: string; type: string; required: boolean; options?: string[] }[];
  checklist: string[]; context: any; object_ref: string; status: "open" | "done" | "cancelled";
  result: any; source_type: string; source_id: string; due_at: string | null; overdue: boolean;
  created_at: string; completed_by: string; completed_at: string | null;
}
export interface ReviewItem {
  id: string; kind: string; kind_label: string; title: string; payload: any; target_ref: string;
  source: string; confidence: number; status: string; assignee_role: string; created_by: string;
  decided_by: string; comment: string; created_at: string; decided_at: string | null;
}
export interface NotificationRec { id: number; title: string; body: string; link: string; read: boolean; created_at: string }
export interface InboxCounts { approvals: number; tasks: number; reviews: number; releases: number; review_counts: Record<string, number>; notifications: number }
export interface ReleaseItem extends ReviewItem { can_decide: boolean; cannot_reason: string }

export interface WorkspaceRec {
  id: string; display_name: string; description: string; industry: string; status: string;
  created_by: string; created_at: string; current?: boolean;
  counts: { object_type: number; link_type: number; function: number; action: number; sop: number };
}
export interface HomeOverview {
  workspace: WorkspaceRec; counts: WorkspaceRec["counts"];
  mapped: { object_total: number; object_unmapped: number }; revision: number; dirty: number;
  datasources: number; pipelines: { total: number; ok: number; failed: number; last_run_at: string | null };
  pending_approvals: number; pending_reviews: number;
  next_steps: { key: string; title: string; hint: string }[];
}
export interface PipelineRec {
  id: string; object_type_id: string; object_type: string; schedule: "manual" | "hourly" | "daily";
  row_limit: number; enabled: boolean; status: string; last_rows: number; last_edges: number;
  last_error: string; last_run_at: string | null; last_duration_ms: number;
}
export interface TraverseNode {
  id: string; type_id: string; type_name: string; key: string; label: string; depth: number;
  via: { link: string; direction: "in" | "out"; from: string } | null; properties: Record<string, any>;
}
export interface TraverseResult {
  root: { id: string; type_name: string; key: string; label: string }; depth: number;
  nodes: TraverseNode[]; edges: { link_id: string; link: string; from: string; to: string }[];
  by_type: Record<string, number>; hidden: number; truncated: boolean; synced_at: string | null;
}
export interface ImpactResult extends TraverseResult {
  layers: { depth: number; groups: { type_name: string; count: number; items: TraverseNode[] }[] }[];
  live: { id: string; type_name: string; key: string; label: string; properties: Record<string, any> }[];
  actions: { name: string; display_name: string; object_type: string }[]; summary: string;
  context?: Record<string, number>;
}
export interface WorkbenchRun { id: string; action_name: string; priority: string; status: string; summary: string; created_at: string; initiator_id: string }
export interface Workbench {
  user: { id: string; name: string; roles: string[]; biz_roles: string[]; can_run: boolean };
  kpis: { name: string; value: any; unit: string; direction: string; formula: string; dimensions: string[]; run_id?: number }[];
  todo: { approvals: WorkbenchRun[]; approvals_total: number; releases: { id: string; title: string; created_by?: string }[];
          tasks: { id: string; title: string; due_at?: string | null; role?: string }[] };
  mine: WorkbenchRun[]; sops: { id: string; title: string; description: string; run_count: number }[];
  questions: string[]; feed: { ts: string; actor: string; summary: string }[];
  /** 自己存的常用问题;经验中枢建议固化的习惯 */
  pinned?: string[]; habits?: MemPattern[];
}
export interface ModelStage { key: string; label: string; desc: string; status: string; log: string[]; counts: Record<string, any> }
export interface ModelRunRec {
  id: string; title: string; status: string; job_id: number; error: string; options: any;
  stages: ModelStage[]; counts: Record<string, number>; created_by: string; created_at: string; updated_at: string;
  inputs: { doc_ids: number[]; files: string[]; chunks: number };
}
export interface ModelRunFull extends ModelRunRec {
  items: Record<"object_type" | "link_type" | "function" | "action" | "other", ReviewItem[]>;
  sops: { id: string; title: string; description: string; status: string; step_count: number }[];
}
export interface RuntimeOverview {
  mcp: { calls_24h: number; success_rate: number | null; by_via: Record<string, number>;
         top_tools: { tool: string; calls: number; failed: number; avg_ms: number }[] };
  approvals: { pending: number; by_priority: Record<string, number>;
               top: { id: string; action_name: string; priority: string; reason: string; created_at: string }[] };
  actions: Record<string, number>; runcards: Record<string, number>;
  pipelines: { objects: number; edges: number; synced_at: string | null; items: PipelineRec[] };
}
export interface AuditRec {
  id: number; ts: string; actor_kind: string; actor_id: string; actor_name: string; event: string;
  target_type: string; target_id: string; summary: string; before?: any; after?: any;
}

export interface SopStep {
  id: string; type: "function" | "skill" | "decision" | "human_task" | "action" | "foreach" | "subprocess" | "end";
  title: string; description: string; lane: string; next: string; output: string;
  function?: string; args?: Record<string, any>;
  skill?: string; inputs?: Record<string, any>;
  branches?: { when: string; next: string; label: string }[]; default?: string;
  role?: string; instructions?: string; form?: { name: string; label: string; type?: string; required?: boolean }[];
  checklist?: string[]; sla_hours?: number;
  action?: string; params?: Record<string, any>; object_key?: string; on_reject?: string;
  sop?: string; outcome?: string;
  /** 逐行处理:按哪份数据逐行($变量),每行最多处理几条 */
  items?: string; limit?: number;
  /** 逐行处理:只处理满足条件的行,如 value > 0 */
  when?: string;
}
export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any }
/** 结构化校验结果:带 step_id,前端据此把错误标到对应节点上 */
export interface SopIssue { level: "error" | "warning"; step_id: string; message: string }

export interface SopSpec {
  params: SopParam[]; roles: string[]; trigger: any; start: string; steps: SopStep[]; evidence: any[];
  priority?: string; domain?: string;
  /** 画布上各步骤的位置;没有的由自动布局补上 */
  layout?: Record<string, { x: number; y: number }>;
}
export interface SopBrief {
  id: string; title: string; description: string; status: string; current_version: number;
  priority?: string; domain?: string; step_types?: string[];
  step_count: number; dry_run_ok: boolean; ai_generated: boolean;
  run_count?: number; updated_at: string; owner_role: string; process_concept_id: string;
}
export interface SopDef extends SopBrief {
  spec: SopSpec; validation: { errors: string[]; warnings: string[]; issues?: SopIssue[]; draft_refs?: DraftRef[] }; draft_hash: string;
  last_dry_run: any; versions: { id: string; version: number; note: string; published_by: string; created_at: string }[];
}
export interface SopStepRun {
  id: string; seq: number; step_id: string; step_type: string; title: string; status: string;
  inputs: any; output: any; note: string; error: string; task_id: string; action_run_id: string;
  child_run_id: string; started_at: string; finished_at: string | null;
}
export interface SopRun {
  id: string; def_id: string; version: number; title: string; mode: string; params: any; vars: any;
  status: string; current_step: string; trigger: string; outcome: string; error: string;
  started_by: string; created_at: string; finished_at: string | null;
  steps: SopStepRun[] | null; spec?: SopSpec;
}

export interface AskCard {
  action: string; action_id?: string; display_name: string; params: Record<string, any>;
  object_key: string; reason: string; preview?: ActionPreview; error?: string;
  param_defs?: { name: string; label: string; type: string; required: boolean; enum: string[] }[]; target_type?: string;
  /** "sop" = 建议发起的流程卡(动作引用写作 sop:<流程卡 id>),其余为普通动作 */
  kind?: string; sop?: string; sop_id?: string; description?: string;
  steps?: { id: string; title: string; type: string; type_label: string; lane?: string }[];
}
export interface DataRef {
  run_id: number; sql: string; columns: string[]; rows: any[][]; metric?: any; period?: any;
  calibre?: any; cited?: boolean; step_id: string;
}
export interface Citation { chunk_id: string; heading: string; doc_id: number; text: string }
export interface Turn {
  id: string; conversation_id: string; seq: number; question: string;
  /** running / done / aborted(用户停止、切换对话、断线)/ error */
  status: string;
  links: LinkResult; plan: any; steps: any[]; answer: string; citations: Citation[];
  data_refs: DataRef[]; actions: AskCard[]; sops: AskCard[]; rating: number; feedback: string;
  duration_ms: number; created_at: string; stats?: Record<string, number>; has_trace?: boolean;
}
export interface AskMeta {
  agents: Record<string, { label: string; desc: string }>;
  tools: Record<string, string>;
  agent_tools: Record<string, string[]>;
}
export interface AskTrace { turn_id: string; events: any[]; stats: Record<string, number>; memory: any }

const _arr = <T,>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);
/** 把对象里指定的字段补成数组(缺失、null、不是数组都算缺)。接口返回的 blob 字段不保证齐全。 */
export function withArrays<T>(obj: T, keys: string[]): T {
  if (!obj || typeof obj !== "object") return obj;
  const o: any = { ...(obj as any) };
  for (const k of keys) if (!Array.isArray(o[k])) o[k] = [];
  return o as T;
}
/** 接口数据不可信:历史轮次可能是中断的、老版本存的,数组字段一律补默认值再渲染。 */
export function normalizeTurn(t: any): Turn {
  const links = t?.links && typeof t.links === "object" ? t.links : {};
  return {
    id: String(t?.id ?? ""), conversation_id: String(t?.conversation_id ?? ""), seq: Number(t?.seq ?? 0),
    question: String(t?.question ?? ""), status: String(t?.status || "done"),
    links: { concepts: _arr(links.concepts).map((c: any) => ({ ...c, matched: _arr(c?.matched) })),
             instances: _arr(links.instances), time: links.time ?? null },
    plan: t?.plan && typeof t.plan === "object" ? t.plan : {}, steps: _arr(t?.steps),
    answer: String(t?.answer ?? ""), citations: _arr(t?.citations), data_refs: _arr(t?.data_refs),
    actions: _arr(t?.actions), sops: _arr(t?.sops), rating: Number(t?.rating ?? 0), feedback: String(t?.feedback ?? ""),
    duration_ms: Number(t?.duration_ms ?? 0), created_at: String(t?.created_at ?? ""),
    stats: t?.stats && typeof t.stats === "object" ? t.stats : {}, has_trace: !!t?.has_trace,
  };
}

// ---------------- 经验中枢 ----------------
export interface MemCase {
  id: string; question: string; intent: string; status: "draft" | "verified" | "deprecated"; score: number | null;
  quality: number; hits: number; fast_hits: number; up_votes: number; down_votes: number; answer_summary: string;
  concepts: { id: string; name: string }[]; plan?: any; sql?: { run_id: number; sql: string; metric?: string; route?: string }[];
  source_turn: string; created_by: string; last_hit_at: string | null; created_at: string; updated_at: string;
}
export interface MemFact {
  id: string; text: string; kind: "definition" | "preference" | "fact"; scope: "workspace" | "user" | "role";
  scope_ref: string; status: "active" | "pending" | "deprecated"; source: string; source_turn: string; hits: number;
  created_by: string; created_at: string; updated_at: string;
}
export interface MemPattern {
  id: string; owner: string; kind: "question" | "action" | "sop"; ref: string; title: string; samples: string[];
  count: number; status: "watching" | "suggested" | "adopted" | "dismissed"; adopted_ref: string; last_at: string;
  text?: string;
}
export interface MemStats {
  cases: Record<string, number>; case_hits: number; fast_hits: number; cases_used_this_week: number;
  facts: Record<string, number>; patterns: Record<string, number>; pending_feedback: number;
}

export interface EvalCase {
  id: string; suite: string; kind: string; question: string; expected: string;
  must_include: string[]; expected_calls: string[]; expected_action: string; source: string; enabled: boolean;
}
export interface EvalRun {
  id: string; suite: string; target: string; status: string; total: number; passed: number;
  pass_rate: number; summary: any; job_id: number; created_at: string; finished_at: string | null;
  results?: any[];
}

// ============================== 接口 ==============================

// ---------------- 监控与定时 ----------------
export interface WatchSchedule {
  kind: "interval" | "daily" | "weekly" | "monthly" | "cron";
  at?: string; weekday?: number; day?: number; every_minutes?: number; cron?: string;
  tz?: string; misfire?: "skip" | "run_once";
}
export interface WatchStrategy {
  kind: "run_sop" | "propose_action" | "notify";
  sop?: string; action?: string; params?: Record<string, any>; object_key?: string;
  reason?: string; role?: string; title?: string; instructions?: string;
}
export interface WatchDef {
  id: string; title: string; description: string; enabled: boolean;
  schedule: WatchSchedule; schedule_text: string;
  source: { kind: "metric" | "object" | "sop"; metric?: string; dimensions?: string[];
            time?: string; object_type?: string; limit?: number; sop?: string };
  condition: string; strategies: WatchStrategy[];
  dedup: { key: string; cooldown_hours: number };
  owner_role: string; next_fire_at: string | null; last_fired_at: string | null;
  last_status: string; last_error: string; fail_count: number;
  created_by: string; created_at: string; updated_at: string;
  run_counts?: Record<string, number>;
}
export interface WatchRunRec {
  id: string; watch_id: string; trigger: string; status: string;
  scanned: number; hit_count: number; fired_count: number; suppressed: number;
  hits: Record<string, any>[]; fired: { kind: string; ok: boolean; text: string; ref?: string; key?: string }[];
  error: string; started_at: string; finished_at: string | null;
}
export interface WatchScanResult {
  watch: string; scanned: number; hits: Record<string, any>[]; hit_count: number;
  over_limit: number; fired: WatchRunRec["fired"]; suppressed: number; run_id: string; ms: number;
}
export interface WatchMeta {
  schedule_kinds: { key: string; label: string; desc: string }[];
  source_kinds: { key: string; label: string; desc: string }[];
  strategy_kinds: { key: string; label: string; desc: string }[];
  max_hits: number;
}

export const onto = {
  // 治理
  me: () => req<Me>("/api/gov/me"),
  users: () => req<{ users: UserRec[]; system_roles: string[] }>("/api/gov/users")
    .then((r) => ({ ...withArrays(r, ["users", "system_roles"]), users: _arr<UserRec>(r?.users).map((u) => withArrays(u, ["roles", "biz_roles"])) })),
  saveUser: (id: string, body: Partial<UserRec>) => req<UserRec>(`/api/gov/users/${enc(id)}`, put(body)),
  audit: (p: Record<string, unknown>) => req<{ total: number; items: AuditRec[] }>(`/api/gov/audit${qs(p)}`),
  auditOne: (id: number) => req<AuditRec>(`/api/gov/audit/${id}`),
  auditExportUrl: (p: Record<string, unknown>) => `/api/gov/audit/export${qs(p)}`,
  reviews: (p: Record<string, unknown>) => req<{ total: number; items: ReviewItem[] }>(`/api/gov/review${qs(p)}`),
  reviewCounts: () => req<Record<string, number>>("/api/gov/review/counts"),
  decideReview: (id: string, body: { accept: boolean; comment?: string; payload?: any }) =>
    req<ReviewItem & { result: any }>(`/api/gov/review/${enc(id)}/decide`, post(body)),
  batchReview: (ids: string[], accept: boolean, comment = "") =>
    req<{ ok: string[]; failed: { id: string; error: string }[] }>("/api/gov/review/batch", post({ ids, accept, comment }))
      .then((r) => withArrays(r, ["ok", "failed"])),
  notifications: (unread = false) => req<{ items: NotificationRec[]; unread: number }>(`/api/gov/notifications${qs({ unread })}`),
  readNotifications: (ids?: number[]) => req<{ ok: boolean }>("/api/gov/notifications/read", post({ ids })),
  llmStats: (days = 7) => req<any>(`/api/gov/llm-stats?days=${days}`).then((d: any) => withArrays(d, ["features", "daily"])),
  roles: () => req<RoleRec[]>("/api/gov/roles").then((rs) => _arr<RoleRec>(rs).map((r) => withArrays(r, ["members"]))),
  saveRole: (name: string, description = "") => req<RoleRec>("/api/gov/roles", post({ name, description })),
  deleteRole: (id: number) => req<{ ok: boolean }>(`/api/gov/roles/${id}`, del),

  // 内核
  kernelMeta: () => req<KernelMeta>("/api/kernel/meta").then((m) => withArrays(m, [
    "kinds", "categories", "data_types", "rule_kinds", "directions", "cardinality", "functions", "tools", "readonly_functions", "roles"])),
  kernelStats: () => req<KernelStats>("/api/kernel/stats"),
  concepts: (p: { kind?: string; status?: string; q?: string } = {}) => req<ConceptBrief[]>(`/api/kernel/concepts${qs(p)}`)
    .then((cs) => _arr<ConceptBrief>(cs).map((c) => withArrays(c, ["synonyms"]))),
  concept: (id: string) => req<Concept>(`/api/kernel/concepts/${enc(id)}`)
    .then((c) => withArrays(c, ["synonyms", "bindings", "evidence"])),
  createConcept: (body: any) => req<Concept>("/api/kernel/concepts", post(body)),
  updateConcept: (id: string, body: any) => req<Concept>(`/api/kernel/concepts/${enc(id)}`, put(body)),
  deleteConcept: (id: string) => req<{ ok: boolean }>(`/api/kernel/concepts/${enc(id)}`, del),
  deprecateConcept: (id: string, reason = "", force = false) => req<Concept>(`/api/kernel/concepts/${enc(id)}/deprecate`, post({ reason, force })),
  restoreConcept: (id: string) => req<Concept>(`/api/kernel/concepts/${enc(id)}`, put({ restore: true })),
  conceptUsage: (id: string) => req<{ type: string; id: string; name: string; kind: string }[]>(`/api/kernel/concepts/${enc(id)}/usage`),
  usage: (id: string) => req<{ type: string; id: string; name: string; kind: string }[]>(`/api/kernel/concepts/${enc(id)}/usage`),
  impact: (id: string) => req<any>(`/api/kernel/concepts/${enc(id)}/impact`),
  lineage: (id: string) => req<{ nodes: { id: string; label: string; kind: string }[]; edges: { from: string; to: string; label: string }[] }>(
    `/api/kernel/concepts/${enc(id)}/lineage`),
  setBinding: (id: string, body: { ds_id: number; target_kind: string; ref: any }) =>
    req<Binding>(`/api/kernel/concepts/${enc(id)}/bindings`, put(body)),
  deleteBinding: (bid: string) => req<{ ok: boolean }>(`/api/kernel/bindings/${enc(bid)}`, del),
  pendingDiff: () => req<Diff>("/api/kernel/diff"),
  /** 提交变更提案(别人审批通过后才发布) */
  proposeRelease: (note: string, approve_now = false) =>
    req<ReviewItem & { published?: any; cannot_reason?: string }>("/api/kernel/publish", post({ note, approve_now })),
  releases: (status = "") => req<ReleaseItem[]>(`/api/kernel/releases${qs({ status })}`),
  decideRelease: (id: string, approve: boolean, comment = "") =>
    req<ReviewItem & { result: any }>(`/api/kernel/releases/${enc(id)}/decide`, post({ approve, comment })),
  revisions: () => req<RevisionRec[]>("/api/kernel/revisions"),
  /** 回滚也是一份变更提案 */
  rollback: (rev: number, note = "") => req<ReviewItem>(`/api/kernel/revisions/${rev}/rollback`, post({ note })),
  compareRevisions: (from: number, to: number) => req<Diff & { from: number; to: number }>(
    `/api/kernel/revisions/compare?from=${from}&to=${to}`),
  graph: () => req<{ nodes: GraphNode[]; edges: GraphEdge[] }>("/api/kernel/graph"),
  saveLayout: (positions: Record<string, { x: number; y: number }>) => req<{ saved: number }>("/api/kernel/layout", put({ positions })),
  tryConcept: (id: string, args: any, object_key = "") => req<any>(`/api/kernel/concepts/${enc(id)}/try`, post({ args, object_key })),
  trySpec: (kind: string, spec: any, args: any, object_key = "", name = "试跑") =>
    req<any>("/api/kernel/try", post({ kind, spec, args, object_key, name })),
  link: (q: string) => req<LinkResult>(`/api/kernel/link?q=${enc(q)}`),
  evalRule: (body: { rule?: string; expression?: string; vars: any }) =>
    req<{ result: any; params: string[]; expression: string }>("/api/kernel/rules/eval", post(body)),
  resolveCalendar: (body: { calendar?: string; spec?: any; ref: string }) =>
    req<{ period: string; start: string; end: string }>("/api/kernel/calendar/resolve", post(body)),
  metricQuery: (body: any) => req<any>("/api/kernel/metrics/query", post(body)),
  metricCompile: (body: any) => req<{ sql: string; ds_id: number; period: any }>("/api/kernel/metrics/compile", post(body)),
  proposeFromDocs: (doc_ids?: number[]) => req<{ job_id: number; chunks: number }>("/api/kernel/propose/documents", post({ doc_ids })),
  proposeFromDatasource: (dsId: number) => req<{ proposed: number; conflicts: number; enriched: number }>(
    `/api/kernel/propose/datasource/${dsId}`, post()),
  graphLink: () => req<{ linked: number; concepts_with_evidence: number }>("/api/kernel/graph-link", post()),
  exportYamlUrl: "/api/kernel/export",
  importYaml: (yaml: string, overwrite = false) => req<any>("/api/kernel/import", post({ yaml, overwrite })),
  templates: () => req<{ id: string; name: string; description: string; concepts: number; roles: number; sops: number;
    counts: Record<string, number> }[]>("/api/kernel/templates"),
  applyTemplate: (id: string, overwrite = false) => req<any>(`/api/kernel/templates/${enc(id)}/apply`, post({ overwrite })),
  objects: (type: string, q = "", limit = 20) =>
    req<{ object_type: { id: string; name: string; spec: any }; items: ObjectRec[] }>(
      `/api/kernel/objects/${enc(type)}${qs({ q, limit })}`),
  object360: (type: string, key: string) => req<any>(`/api/kernel/objects/${enc(type)}/${enc(key)}`)
    .then((d) => withArrays(d, ["metrics", "links", "documents", "edits", "audit", "actions"])),
  syncObjects: (type: string) => req<{ rows: number; edges: number }>(`/api/kernel/objects/${enc(type)}/sync`, post()),
  traverse: (type: string, key: string, depth = 2) =>
    req<TraverseResult>(`/api/kernel/objects/${enc(type)}/${enc(key)}/traverse?depth=${depth}`),
  impactObject: (type: string, key: string, depth = 3) =>
    req<ImpactResult>(`/api/kernel/objects/${enc(type)}/${enc(key)}/impact?depth=${depth}`)
      .then((r) => withArrays(r, ["layers", "live", "actions", "nodes", "edges"])),

  mappings: (dsId: number) => req<Record<string, { concept_id: string; name: string; status: string }[]>>(`/api/kernel/mappings?ds_id=${dsId}`),

  // 本体空间 / 首页
  workspaces: () => req<WorkspaceRec[]>("/api/kernel/workspaces"),
  createWorkspace: (body: { id: string; display_name: string; description?: string; industry?: string; template?: string }) =>
    req<WorkspaceRec>("/api/kernel/workspaces", post(body)),
  updateWorkspace: (id: string, body: Partial<WorkspaceRec>) => req<WorkspaceRec>(`/api/kernel/workspaces/${enc(id)}`, put(body)),
  archiveWorkspace: (id: string) => req<{ ok: boolean }>(`/api/kernel/workspaces/${enc(id)}`, del),
  home: () => req<HomeOverview>("/api/kernel/home"),
  workbench: () => req<Workbench>("/api/kernel/workbench"),

  // 数据管道 / 本体数据集
  pipelines: () => req<{ items: PipelineRec[]; status: { objects: number; edges: number; synced_at: string | null } }>("/api/kernel/pipelines"),
  createPipeline: (object_type: string, schedule = "manual") => req<PipelineRec>("/api/kernel/pipelines", post({ object_type, schedule })),
  ensurePipelines: () => req<{ created: string[] }>("/api/kernel/pipelines/ensure", post()),
  runAllPipelines: () => req<{ job_id: number }>("/api/kernel/pipelines/run-all", post()),
  updatePipeline: (id: string, body: Partial<PipelineRec>) => req<PipelineRec>(`/api/kernel/pipelines/${enc(id)}`, put(body)),
  deletePipeline: (id: string) => req<{ ok: boolean }>(`/api/kernel/pipelines/${enc(id)}`, del),
  runPipeline: (id: string) => req<PipelineRec & { result: any }>(`/api/kernel/pipelines/${enc(id)}/run`, post()),
  dataset: (type: string, q = "", limit = 50, offset = 0) =>
    req<{ object_type: { id: string; name: string }; total: number; items: { key: string; label: string; properties: any; synced_at: string }[] }>(
      `/api/kernel/datasets/${enc(type)}${qs({ q, limit, offset })}`),

  // 业务建模
  modelingStages: () => req<{ stages: { key: string; label: string; desc: string }[];
    templates: { id: string; name: string; description: string; concepts: number }[] }>("/api/kernel/modeling/stages"),
  modelingRuns: () => req<ModelRunRec[]>("/api/kernel/modeling/runs"),
  modelingRun: (id: string) => req<ModelRunFull>(`/api/kernel/modeling/runs/${enc(id)}`),
  createModelingRun: (fd: FormData) => req<ModelRunRec>("/api/kernel/modeling/runs", { method: "POST", body: fd }),
  startModelingRun: (id: string) => req<ModelRunRec>(`/api/kernel/modeling/runs/${enc(id)}/start`, post()),
  deleteModelingRun: (id: string) => req<{ ok: boolean }>(`/api/kernel/modeling/runs/${enc(id)}`, del),
  modelingExportUrl: (id: string) => `/api/kernel/modeling/runs/${enc(id)}/export`,

  // 能力
  catalog: () => req<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] }>("/api/cap/catalog")
    .then((c) => withArrays(c, ["functions", "tools", "defs"])),
  callFunction: (name: string, args: any) => req<any>(`/api/cap/functions/${enc(name)}/call`, post({ args })),
  refOptions: (ref: string, of = "") => req<RefOption[]>(`/api/cap/ref-options${qs({ ref, of })}`).then((r) => _arr<RefOption>(r)),
  capDefs: (kind = "", working = false) => req<CapDef[]>(`/api/cap/defs${qs({ kind, working: working || undefined })}`),
  saveCapDef: (body: any, id?: string) => id
    ? req<CapDef>(`/api/cap/defs/${enc(id)}`, put(body)) : req<CapDef>("/api/cap/defs", post(body)),
  setCapStatus: (id: string, status: string) => req<CapDef>(`/api/cap/defs/${enc(id)}/status`, post({ status })),
  deleteCapDef: (id: string) => req<{ ok: boolean }>(`/api/cap/defs/${enc(id)}`, del),
  runSkill: (ref: string, args: any) => req<any>(`/api/cap/skills/${enc(ref)}/run`, post({ args })),
  prepareAction: (ref: string, params: any, object_key = "") =>
    req<ActionPreview>(`/api/cap/actions/${enc(ref)}/prepare`, post({ params, object_key })),
  proposeAction: (ref: string, body: { params: any; object_key?: string; reason?: string; initiator_kind?: string;
    source_ref?: string; priority?: string; evidence?: any[] }) =>
    req<ActionRun>(`/api/cap/actions/${enc(ref)}/propose`, post(body)),
  actionRuns: (p: Record<string, unknown> = {}) => req<ActionRun[]>(`/api/cap/runs${qs(p)}`)
    .then((rs) => _arr<ActionRun>(rs).map((r) => withArrays(r, ["approvals", "evidence"]))),
  actionRun: (id: string) => req<ActionRun>(`/api/cap/runs/${enc(id)}`).then((r) => withArrays(r, ["approvals", "evidence"])),
  decideAction: (id: string, approve: boolean, comment = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/decide`, post({ approve, comment })),
  cancelAction: (id: string, reason = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/cancel`, post({ reason })),
  revertAction: (id: string, reason = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/revert`, post({ reason })),
  retryAction: (id: string) => req<ActionRun>(`/api/cap/runs/${enc(id)}/retry`, post()),
  approvals: () => req<ActionRun[]>("/api/cap/approvals"),
  tasks: (p: Record<string, unknown> = {}) => req<TaskRec[]>(`/api/cap/tasks${qs(p)}`)
    .then((ts) => _arr<TaskRec>(ts).map((t) => withArrays(t, ["checklist", "form"]))),
  task: (id: string) => req<TaskRec>(`/api/cap/tasks/${enc(id)}`).then((t) => withArrays(t, ["checklist", "form"])),
  completeTask: (id: string, result: any, comment = "") => req<TaskRec>(`/api/cap/tasks/${enc(id)}/complete`, post({ result, comment })),
  claimTask: (id: string) => req<TaskRec>(`/api/cap/tasks/${enc(id)}/claim`, post()),
  inbox: () => req<InboxCounts>("/api/cap/inbox"),
  mcpTools: () => req<{ enabled: boolean; endpoint: string; protocol: string; tools: McpTool[] }>("/api/cap/mcp/tools"),
  mcpCall: (name: string, args: any) => req<{ ok: boolean; result: any; error: string | null }>(
    `/api/cap/mcp/call/${enc(name)}`, post({ args })),
  mcpLogs: (limit = 50) => req<AuditRec[]>(`/api/cap/mcp/logs?limit=${limit}`),
  runtimeOverview: () => req<RuntimeOverview>("/api/cap/runtime/overview"),

  // 监控与定时
  watchMeta: () => req<WatchMeta>("/api/watch/meta"),
  watches: (q = "") => req<WatchDef[]>(`/api/watch${qs({ q })}`),
  watch: (id: string) => req<WatchDef>(`/api/watch/${enc(id)}`),
  createWatch: (body: any) => req<WatchDef>("/api/watch", post(body)),
  saveWatch: (id: string, body: any) => req<WatchDef>(`/api/watch/${enc(id)}`, put(body)),
  deleteWatch: (id: string) => req<{ ok: boolean }>(`/api/watch/${enc(id)}`, del),
  setWatchEnabled: (id: string, enabled: boolean) => req<WatchDef>(`/api/watch/${enc(id)}/enabled`, post({ enabled })),
  scanWatch: (id: string, dry = true, force = false) => req<WatchScanResult>(`/api/watch/${enc(id)}/scan`, post({ dry, force })),
  watchRuns: (watch_id = "", limit = 50) => req<WatchRunRec[]>(`/api/watch/runs${qs({ watch_id, limit })}`),
  previewSchedule: (schedule: any) => req<{ ok: boolean; error?: string; text: string; next: string[] }>(
    "/api/watch/preview-schedule", post({ schedule })),

  // SOP
  sopMeta: () => req<{ step_types: { type: string; label: string }[]; param_types: string[] }>("/api/sop/meta"),
  sops: (p: Record<string, unknown> = {}) => req<SopBrief[]>(`/api/sop/defs${qs(p)}`),
  sop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}`),
  createSop: (body: any) => req<SopDef>("/api/sop/defs", post(body)),
  draftSop: (topic: string, process_concept_id = "") => req<SopDef>("/api/sop/defs/draft", post({ topic, process_concept_id })),
  saveSop: (id: string, body: any) => req<SopDef>(`/api/sop/defs/${enc(id)}`, put(body)),
  archiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/archive`, post()),
  unarchiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/unarchive`, post()),
  sopReferencedBy: (id: string) => req<{ id: string; title: string; step: string }[]>(`/api/sop/defs/${enc(id)}/referenced-by`),
  validateSop: (spec: any) => req<{ spec: SopSpec; errors: string[]; warnings: string[]; issues?: SopIssue[]; draft_refs?: DraftRef[] }>("/api/sop/validate", post({ spec })),
  sopRecipes: () => req<Recipe[]>("/api/sop/recipes"),
  createSopFromRecipe: (id: string, fields: Record<string, any>, title = "") =>
    req<SopDef>(`/api/sop/recipes/${enc(id)}`, post({ fields, title })),
  trySopStep: (id: string, stepId: string, env: Record<string, unknown> = {}) => req<{
    step_id: string; type: string; title: string; ok: boolean; output?: any; note?: string;
    var?: string; error?: string; ms: number }>(`/api/sop/defs/${enc(id)}/steps/${enc(stepId)}/try`, post({ env })),
  dryRunSop: (id: string, params: any) => req<SopRun>(`/api/sop/defs/${enc(id)}/dry-run`, post({ params })),
  submitSop: (id: string, note: string) => req<ReviewItem>(`/api/sop/defs/${enc(id)}/submit`, post({ note })),
  runSop: (id: string, params: any, mode = "live") => req<SopRun>(`/api/sop/defs/${enc(id)}/run`, post({ params, mode })),
  sopVersion: (id: string, v: number) => req<{ spec: SopSpec; version: number }>(`/api/sop/defs/${enc(id)}/versions/${v}`),
  sopRuns: (p: Record<string, unknown> = {}) => req<SopRun[]>(`/api/sop/runs${qs(p)}`),
  sopRun: (id: string) => req<SopRun>(`/api/sop/runs/${enc(id)}`),
  cancelSopRun: (id: string, reason = "") => req<SopRun>(`/api/sop/runs/${enc(id)}/cancel`, post({ reason })),

  // 统一提问
  conversations: () => req<{ id: string; title: string; turns: number; updated_at: string }[]>("/api/ask/conversations"),
  conversation: async (id: string) => {
    const c = await req<{ id: string; title: string; turns: unknown[] }>(`/api/ask/conversations/${enc(id)}`);
    return { id: c.id, title: c.title, turns: _arr(c.turns).map(normalizeTurn) };
  },
  deleteConversation: (id: string) => req<{ ok: boolean }>(`/api/ask/conversations/${enc(id)}`, del),
  askMeta: () => req<AskMeta>("/api/ask/meta"),
  askTrace: async (turnId: string) => {
    const t = await req<AskTrace>(`/api/ask/turns/${enc(turnId)}/trace`);
    return { ...t, events: _arr(t?.events), stats: t?.stats || {}, memory: t?.memory || {} };
  },
  feedback: (turnId: string, rating: number, comment = "", correction = "") =>
    req<{ ok: boolean; review_item: ReviewItem | null; learned?: any }>(`/api/ask/turns/${enc(turnId)}/feedback`, post({ rating, comment, correction })),

  // 经验中枢
  memStats: () => req<MemStats>("/api/memory/stats"),
  memCases: (p: Record<string, unknown> = {}) => req<MemCase[]>(`/api/memory/cases${qs(p)}`),
  saveMemCase: (id: string, body: Partial<MemCase>) => req<MemCase>(`/api/memory/cases/${enc(id)}`, put(body)),
  deleteMemCase: (id: string) => req<{ ok: boolean }>(`/api/memory/cases/${enc(id)}`, del),
  memFacts: (p: Record<string, unknown> = {}) => req<MemFact[]>(`/api/memory/facts${qs(p)}`),
  addMemFact: (body: { text: string; kind: string; scope?: string }) => req<MemFact>("/api/memory/facts", post(body)),
  saveMemFact: (id: string, body: Partial<MemFact>) => req<MemFact>(`/api/memory/facts/${enc(id)}`, put(body)),
  deleteMemFact: (id: string) => req<{ ok: boolean }>(`/api/memory/facts/${enc(id)}`, del),
  memPatterns: (p: Record<string, unknown> = {}) => req<MemPattern[]>(`/api/memory/patterns${qs(p)}`),
  memSuggestions: () => req<MemPattern[]>("/api/memory/suggestions"),
  pinQuestion: (question: string) => req<MemPattern>("/api/memory/pin", post({ question })),
  decidePattern: (id: string, adopt: boolean, adopted_ref = "") =>
    req<MemPattern>(`/api/memory/patterns/${enc(id)}/decide`, post({ adopt, adopted_ref })),

  // 评测
  evalSuites: () => req<{ suites: { suite: string; cases: number; by_kind: Record<string, number> }[]; gold_sets: string[] }>("/api/eval/suites"),
  evalCases: (suite = "") => req<EvalCase[]>(`/api/eval/cases${qs({ suite })}`)
    .then((cs) => _arr<EvalCase>(cs).map((c) => withArrays(c, ["must_include", "expected_calls"]))),
  saveEvalCase: (body: any, id?: string) => id
    ? req<EvalCase>(`/api/eval/cases/${enc(id)}`, put(body)) : req<EvalCase>("/api/eval/cases", post(body)),
  deleteEvalCase: (id: string) => req<{ ok: boolean }>(`/api/eval/cases/${enc(id)}`, del),
  importGold: (gold_set: string) => req<{ imported: number }>("/api/eval/cases/import", post({ gold_set })),
  startEval: (suite: string, target: string, judge = true) => req<EvalRun>("/api/eval/runs", post({ suite, target, judge })),
  evalRuns: () => req<EvalRun[]>("/api/eval/runs"),
  evalRun: (id: string) => req<EvalRun>(`/api/eval/runs/${enc(id)}`)
    .then((r) => ({ ...withArrays(r, ["results"]), results: _arr<any>(r?.results).map((x) => withArrays(x, ["missing", "details"])) })),
  ontologyEval: (gold_set: string) => req<any>("/api/eval/ontology", post({ gold_set })),
};

export const STATUS_LABEL: Record<string, string> = {
  draft: "草稿", published: "已发布", deprecated: "已废弃", disabled: "已停用",
  pending_approval: "待审批", executing: "执行中", done: "已完成", failed: "失败",
  rejected: "已驳回", cancelled: "已撤回", reverted: "已撤销", pending: "待处理",
  accepted: "已采纳", open: "待办", running: "运行中", waiting: "等待中", paused: "已暂停",
  waiting_human: "等人工", waiting_approval: "等审批", waiting_child: "等子流程",
  suggested: "建议", skipped: "跳过", archived: "已归档", auto: "自动执行",
};

export const STATUS_TONE: Record<string, string> = {
  draft: "bg-ink/5 text-muted", published: "bg-ok/10 text-ok", deprecated: "bg-bad/10 text-bad",
  pending_approval: "bg-warn/10 text-warn", executing: "bg-brand2/10 text-brand2",
  done: "bg-ok/10 text-ok", failed: "bg-bad/10 text-bad", rejected: "bg-bad/10 text-bad",
  cancelled: "bg-ink/5 text-muted", reverted: "bg-ink/5 text-muted", pending: "bg-warn/10 text-warn",
  accepted: "bg-ok/10 text-ok", open: "bg-warn/10 text-warn", running: "bg-brand2/10 text-brand2",
  waiting: "bg-warn/10 text-warn", paused: "bg-brand/10 text-brand", waiting_human: "bg-warn/10 text-warn",
  waiting_approval: "bg-warn/10 text-warn", suggested: "bg-brand/10 text-brand", disabled: "bg-ink/5 text-muted",
  archived: "bg-ink/5 text-muted",
};

/** 颜色按细分类型(对象 / 关系 / 函数五类 / 动作)。旧键保留给历史数据与图谱实体。 */
export const KIND_COLOR: Record<string, string> = {
  object_type: "#6366f1", link_type: "#8b5cf6", action: "#ef4444",
  aggregate: "#0ea5e9", rule: "#f59e0b", calendar: "#10b981", decision: "#d946ef", ml: "#ec4899", ai: "#14b8a6",
  function: "#0ea5e9", metric: "#0ea5e9", table: "#64748b", column: "#94a3b8", datasource: "#475569",
  document: "#a16207",
};

export const TYPE_LABEL: Record<string, string> = {
  object_type: "对象", link_type: "关系", action: "动作", function: "函数",
  aggregate: "聚合", rule: "规则", calendar: "周期", decision: "决策表", ml: "模型推理", ai: "AI 分析(参考)",
};

export const PRIORITY_TONE: Record<string, string> = {
  P0: "bg-bad/15 text-bad", P1: "bg-warn/15 text-warn", P2: "bg-brand/10 text-brand", P3: "bg-ink/5 text-muted",
};

export function typeKey(c: { kind: string; category?: string }): TypeKey {
  return (c.kind === "function" ? (c.category || "rule") : c.kind) as TypeKey;
}

export function fmtTime(s?: string | null): string {
  if (!s) return "-";
  return s.replace("T", " ").slice(0, 16);
}

export function errText(e: unknown): string {
  return e instanceof Error ? e.message : String(e);
}