onto.ts 64.9 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 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
/**
 * 本体平台的类型与接口:本体空间、内核、数据管道、业务建模、能力(动作 / 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" | "value_type";
export type FnCategory = "aggregate" | "rule" | "decision" | "object_set" | "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 {
  /** 只有关系带:两端对象与基数 */
  from_type?: string; to_type?: string; cardinality?: string;
  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;
  /** 对象是接口 */
  abstract?: boolean;
}
export interface Concept extends ConceptBrief {
  spec: any; bindings: Binding[]; evidence: Evidence[]; published_copy: any;
  /** 接口:哪些对象实现了它 */
  implementations?: { id: string; name: string; mapping: Record<string, string> }[];
  abstract?: boolean;
}
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[];
  source_kinds?: { kind: string; label: string }[]; formats?: string[]; tones?: string[]; grains?: string[];
  set_ops?: string[]; value_types?: ValueTypeDef[]; system_objects?: { id: string; name: string }[];
  write_ops?: Record<string, 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 DiffItem { id: string; name: string; kind: string }
export interface HealthIssue { id: string; name: string; kind: string; type_key: string; level: "error" | "warn"; code: string; message: string }
export interface HealthReport { errors: HealthIssue[]; warnings: HealthIssue[]; usage?: HealthIssue[]; checked: number }
export interface ReleasePreview {
  ids: string[]; auto: (DiffItem & { because: string })[]; blocked: { id: string; name: string; used_by: string[] }[];
  diff: Diff; health: HealthReport;
}
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 ObjRef { type_id: string; type_name: string; key: string; label: string }
export interface ObjectRec { type_id: string; type_name: string; key: string; label: string; properties: Record<string, any>; overridden?: string[];
  /** 指向别的对象的属性:属性名 → 对方是谁 */
  refs?: Record<string, ObjRef> }

/** 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; now_id?: string;
  target_label?: string; param_labels?: Record<string, string>; param_values?: Record<string, string>;
  /** 提交前的每条校验过没过;blocked = 有没过的 */
  checks?: { label: string; ok: boolean; message: string }[]; blocked?: boolean;
  /** 分段审批:每一段的名称、谁批、这一单是不是免批 */
  stages?: { name: string; approver_roles: string[]; skip: boolean; why: string }[]; stage_index?: number | null;
  approval_decision?: { function: string; why: string; priority: 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[];
    stage?: number; stage_name?: string; decided_name?: string }[];
  can_approve?: boolean; cannot_reason?: string; can_cancel?: boolean;
  submitted_name?: 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 AutobindResult {
  items: { id: string; concept_id: string; name: string; kind: string; text: string; why: string }[];
  skipped: { concept_id: string; name: string; kind: string; why: 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;
  /** AI 建模里还没决定的草案 */
  modeling_drafts: 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; submitted_name?: string }
export interface Workbench {
  user: { id: string; name: string; roles: string[]; biz_roles: string[]; can_run: boolean };
  kpis: { name: string; value: any; unit: string; format?: string; direction: string; formula: string; dimensions: string[]; run_id?: number }[];
  alerts?: { id: string; watch: string; watch_id: string; label: string; first_seen_at: string | null }[];
  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 ModelLog { t: string; msg: string }
export interface ModelStage {
  key: string; label: string; desc: string; status: string; log: ModelLog[]; counts: Record<string, any>;
  started_at?: string; ended_at?: string;
}
export interface ModelRunRec {
  id: string; title: string; status: string; error: string; options: any;
  /** 有人按了暂停 / 终止、正在停下来 */
  control: "" | "stop" | "cancel";
  stages: ModelStage[]; counts: Record<string, number>; created_by: string; created_at: string; updated_at: string;
  started_at: string | null; elapsed_ms: number;
  inputs: { doc_ids: number[]; files: string[]; chunks: number };
}
export interface ModelCallStat { calls: number; ms: number; prompt_tokens: number; output_tokens: number; reasoning_tokens: number }
/** 草案体检:每条一个检查项,must 的都过了 = 能直接用(代替以前 AI 自报的可信度) */
export interface Readiness { ready: boolean; checks: { ok: boolean; text: string; must: boolean }[] }
/** 在真实业务数据上试算的结果 */
export interface Trial {
  ok?: boolean; error?: string; summary?: string; value?: any; total?: number; skipped?: boolean;
  dist?: [any, number][]; samples?: { label: string; value: any }[] | string[];
}
/** 建模草案:审核项 + 采纳后落成的元素(是否已上线、没上线的原因) */
export interface ModelDraftItem extends ReviewItem {
  concept?: { id: string; name: string; status: string; dirty: boolean; issue: string } | null;
  issue?: string;
  readiness?: Readiness;
}
export interface ModelSopDraft {
  id: string; title: string; description: string; status: string; step_count: number; owner_role: string;
  current_version: number; params: SopParam[]; validation: SopValidation; updated_at: string;
  outline: { id: string; title: string; kind: string; kind_label: string; depth: number }[]; issue: string;
  /** 文档里写的执行时间(「每天 9:00」),定时任务按它配 */
  schedule?: string;
  /** 文档里这个流程的步骤条目,对上了几条(covers:条目编号 → 步骤 id) */
  coverage?: { covers?: Record<string, string>; total?: number; covered?: number; missing?: string[] };
  /** 在草案世界里试运行的结果 */
  dry_run?: { ok?: boolean; skipped?: boolean; summary?: string; error?: string; status?: string;
              steps?: { title: string; status: string; note: string }[] };
  fix_log?: { instruction: string; summary: string; before_errors: number; after_errors: number }[];
}
/** 建模起草的定时任务 / 监控(采纳时建成监控并启用) */
export interface ModelWatchDraft {
  id: string; title: string; status: "pending" | "accepted" | "discarded"; issue: string; weak: boolean; basis: string;
  watch_id?: string; req_ids?: string[]; trial?: Trial; edited?: string;
  body: {
    title?: string; description?: string; owner_role?: string; condition?: string;
    schedule?: { kind: string; at?: string; weekday?: number; day?: number; every_minutes?: number; cron?: string };
    source?: { kind: "sop" | "object" | "metric"; sop?: string; object_type?: string; metric?: string; dimensions?: string[] };
    strategies?: { kind: string; sop?: string; role?: string; subject?: string; title?: string; action?: string; params?: Record<string, any> }[];
  };
}
/** 文档条目(「列条目」拆出来的) */
export interface ModelReq {
  id: string; section: string; kind: string; kind_label: string; text: string; quote: string; process: string; role: string;
}
export type CheckStatus = "covered" | "partial" | "missing" | "builtin" | "na";
export interface ModelCheckItem extends Partial<ModelReq> {
  id: string; text: string; status: CheckStatus; by: string[];
  doc_says?: string; draft_has?: string; gap?: string; reason?: string; question?: string; ignored?: boolean;
  fix?: { type?: string; target?: string; kind?: string; name?: string; instruction?: string };
  /** AI 按对账改过:改了什么、改之前是什么情况 */
  fixed?: ModelFixLog | null; before?: { status?: string; gap?: string; draft_has?: string };
  /** 老记录 */
  note?: string;
}
/** 对账:文档条目逐条对上草案 */
export interface ModelCheck {
  items?: ModelCheckItem[];
  questions?: string[];
  summary?: Partial<Record<CheckStatus, number>>;
}
export interface ModelFixLog { req_id: string; type: string; target: string; ok: boolean; summary: string; instruction: string; at: string }
export interface ModelRunFull extends ModelRunRec {
  items: Record<"object_type" | "link_type" | "function" | "action" | "other", ModelDraftItem[]>;
  sops: ModelSopDraft[];
  watches: ModelWatchDraft[];
  check: ModelCheck;
  reqs?: ModelReq[];
  fixes?: ModelFixLog[];
  /** 这次建模用的模型 */
  model?: string;
  call_stats: Record<string, ModelCallStat>;
}
export interface ModelCallRec {
  id: number; stage: string; feature: string; label: string; model: string; status: string; started_at: string;
  duration_ms: number; prompt_tokens: number; output_tokens: number; reasoning_tokens: number; cached: boolean;
  error: string; reasoning_chars: number; output_preview: string;
}
export interface ModelCallDetail extends Omit<ModelCallRec, "reasoning_chars" | "output_preview" | "feature"> {
  prompt: string; reasoning: string; output: string;
}
export interface AdoptResult {
  accepted: string[]; failed: Record<string, string>; published: number; revision?: number;
  held: Record<string, string>; warnings: any[]; sops: Record<string, string>; watches: Record<string, string>;
}
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;
}

/** 流程卡里的一步(画布上的一个节点)。不同 type 用到的字段不同,见后端 sop/spec.py 的说明。 */
export type StepType = "query" | "function" | "compute" | "skill" | "decision" | "foreach" | "human_task" | "notify"
  | "action" | "write" | "subprocess" | "end";
export interface StepError { mode: "stop" | "default" | "branch"; retry?: number; default?: any; next?: string; timeout?: number }
export interface SopStep {
  id: string; type: StepType; title: string; description?: string; next?: string; output?: string;
  ui?: { x: number; y: number }; error?: StepError | null; [k: string]: any;
}
export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string;
  options?: string[]; required: boolean; default?: any; description?: string;
  columns?: { name: string; label: string; type: string; required?: boolean; object_type?: string }[] }
/** 结构化校验结果:带 step_id,前端据此把问题标到对应步骤上 */
export interface SopIssue { level: "error" | "warning"; step_id: string; message: string }
export interface SopSpec { params: SopParam[]; start: string; steps: SopStep[]; evidence: any[]; priority?: string; domain?: string;
  ui?: { start?: { x: number; y: number } } }

/** 条件组:若干「数据 比较 值」用 并且 / 或者 连起来,可以嵌一层子条件组;或一段高级表达式。 */
export interface CondItem { left: string; op: string; right?: any }
export interface CondGroup { mode: "all" | "any"; items: (CondItem | CondGroup)[] }
export type FlowCond = CondGroup | { expr: string } | null;
/** 数据结构(每一步产出什么):对象有 fields,列表有 items。 */
export interface DataSchema { name?: string; label?: string; type: string; fields?: DataSchema[]; items?: DataSchema;
  options?: string[]; object_type?: string }
/** 一份能被后面步骤引用的数据:某一步的结果、一个参数,或循环体里的「当前这一条」。 */
export interface FlowOutput { id: string; var: string; title: string; kind: string; scope: string; schema: DataSchema }
export interface FlowPaletteItem { type: StepType; preset?: string; label: string; desc: string }
export interface FlowMeta {
  types: Record<string, string>; groups: { label: string; items: FlowPaletteItem[] }[];
  ops: Record<string, string>; query_ops: Record<string, string>; write_ops: Record<string, string>;
  agg_fns: Record<string, string>; field_types: string[]; param_types: string[]; value_types: string[];
  error_modes: Record<string, string>; foreach_limit: number; functions: string[];
  list_functions: { name: string; sig: string; desc: string }[];
}
export interface FlowLink { link: string; label: string; direction: string; single: boolean; object_type: string; fields: DataSchema[] }
export interface SopValidation { errors: string[]; warnings: string[]; issues?: SopIssue[]; draft_refs?: DraftRef[] }

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; runs_30d?: number; success_rate_30d?: number | null;
  last_run?: { id: string; status: string; at: string; trigger: string; started_by: string } | null;
  updated_at: string; owner_role: string; process_concept_id: string;
}
export interface SopDef extends SopBrief {
  spec: SopSpec; validation: SopValidation; 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;
  /** 逐条处理:每一行各自的运行 */
  rows?: SopRun[];
  /** 在等人的步骤:它的待办 / 审批单,以及当前这个人能不能直接办 */
  task?: TaskRec & { can_handle: boolean };
  action?: { id: string; status: string; priority?: string; summary: string; error: string; approver_roles: string[];
    can_decide: boolean; can_retry: boolean };
  /** 已经办完的动作步骤:它做了什么 */
  action_brief?: { id: string; status: string; summary: string; error: string };
}
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; kind?: string; row_index?: number;
  steps: SopStepRun[] | null; spec?: SopSpec;
  /** 运行时填的参数,按人看的样子 */
  params_view?: { name: string; label: string; value: string; raw: any; object_type: string }[];
  started_by_name?: string;
  /** 列表里用:走到哪一步、在等谁 */
  current?: { title: string; status: string; waiting_for: string } | null; step_total?: number;
}
/** 预警事件:一个命中键从发现到恢复 / 忽略的一整轮(也是本体里的系统对象「预警事件」)。 */
export interface AlertEvent {
  id: string; watch_id: string; rule: string; key: string; title: string;
  object: { type_id: string; type_name: string; key: string; label: string } | null;
  severity: "高" | "中" | "低"; status: "新发现" | "处置中" | "待验证" | "已恢复" | "已忽略";
  value: number | null; baseline: number | null; deviation: number | null;
  detail: { row?: Record<string, any>; detectors?: Record<string, any> };
  fired: { kind: string; ok: boolean; ref?: string; ref_kind?: string; text: string; at?: string }[];
  handling: string; auto_handled: boolean; owner_role: string;
  first_seen_at: string | null; last_seen_at: string | null; last_fired_at: string | null; handled_at: string | null;
  recovered_at: string | null; recover_hours: number | null; fire_count: number; seen_count: number;
  recurrence_of: string; is_recurrence: boolean; silence_until: string | null; note: string; closed_by: string;
}
export interface AlertStats {
  days: number; total: number; open: number; recovered: number; ignored: number;
  auto_rate: number | null; avg_recover_hours: number | null; recurrence_rate: number | null;
  false_alarm_rate: number | null; by_severity: Record<string, number>;
}
export type WatchField = { path: string; label: string; type: string; enum?: string[]; format?: string; unit?: string;
                           track?: boolean; detector?: boolean };
export interface WatchDetector { name: string; fn: string; field: string; window: number; from?: string[]; to?: string[] }

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?: any[]; target_type?: string;
  /** "sop" = 建议发起的流程卡(本人确认即发起),其余为要提交审批的动作 */
  kind?: string; sop?: string; sop_id?: string; description?: string; version?: number;
  steps?: { id: string; title: string; kind_label: string; depth: number }[];
  /** 流程卡:还缺哪些必填参数 */
  missing?: string[];
  /** 已经提交 / 确认过:ref 是审批单或流程运行的编号 */
  submitted?: { ref: string; by: string; at: 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 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" | "sql_hint"; 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" | "task";
  sop?: string; action?: string; params?: Record<string, any>; object_key?: string;
  reason?: string; role?: string; title?: string; instructions?: string; subject?: string; body?: string;
  /** 严重度至少到这一级才做这一项 */
  min_severity?: "高" | "中" | "低";
}
export interface WatchDef {
  id: string; title: string; description: string; enabled: boolean;
  schedule: WatchSchedule; schedule_text: string;
  trigger: { kind: "schedule" | "change"; properties?: string[]; on?: string[] };
  source: { kind: "metric" | "object" | "object_set" | "sop"; metric?: string; dimensions?: string[];
            time?: string; object_type?: string; set?: string; inputs?: Record<string, any>; limit?: number; sop?: string };
  detectors: WatchDetector[];
  condition: string;
  severity: { mode: "fixed" | "rules" | "decision"; level: string; rules?: { when: string; level: string }[];
              function?: string; inputs?: Record<string, any> };
  strategies: WatchStrategy[];
  dedup: { key: string; cooldown_hours: number };
  recovery: { mode: "auto" | "manual"; reopen_days: 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; opened?: number; recovered?: 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; unscanned?: number; fired: WatchRunRec["fired"]; suppressed: number; run_id: string; ms: number;
  opened?: number; recovered?: number; misses?: Record<string, any>[];
}
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 }[];
  trigger_kinds: { key: string; label: string; desc: string }[];
  detectors: { key: string; label: string; desc: string }[];
  severities: string[];
  severity_modes: { key: string; label: 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"),
  /** 发布前预览:这次会带上哪些元素(含自动带上的依赖)、会变什么、体检结果。ids 不给 = 全部改动 */
  releasePreview: (ids?: string[]) => req<ReleasePreview>("/api/kernel/release/preview", post({ concept_ids: ids ?? null })),
  /** 整个工作副本的体检 */
  health: () => req<HealthReport>("/api/kernel/health"),
  proposeRelease: (note = "", approve_now = false, ids?: string[]) =>
    req<ReviewItem & { published?: any; cannot_reason?: string }>("/api/kernel/publish", post({ note, approve_now, concept_ids: ids ?? null })),
  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"),
  /** 回滚也是一份变更提案 */
  rollbackPreview: (rev: number) => req<{ revision: number; overwritten: DiffItem[]; lost: DiffItem[] }>(`/api/kernel/revisions/${rev}/rollback-preview`),
  rollback: (rev: number, note = "", confirm = false) =>
    req<ReviewItem>(`/api/kernel/revisions/${rev}/rollback`, post({ note, confirm })),
  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 })),
  runFnTests: (id: string, spec: any, tests: any[]) =>
    req<{ name: string; ok: boolean; got: Record<string, any>; error: string }[]>(`/api/kernel/concepts/${enc(id)}/tests`, post({ spec, tests })),
  checkDecision: (spec: any) => req<{ ok: boolean; issues: string[]; gaps: any[]; overlaps: { inputs: any; rows: number[] }[]; shadowed: number[]; never: number[] }>(
    "/api/kernel/decision/check", post({ spec })),
  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)),
  resolvePeriod: (body: { period?: any; metric?: string; ref: string }) =>
    req<{ period: string; start: string; end: string; label: string }>("/api/kernel/period/resolve", post(body)),
  valueTypes: () => req<ValueTypeDef[]>("/api/kernel/value-types"),
  evalObjectSet: (body: { set?: string; spec?: any; inputs?: Record<string, any>; limit?: number; q?: string }) =>
    req<{ items: ObjectRec[]; total: number; type_name: string; set?: string; fields?: import("./format").FieldMeta[] }>(
      "/api/kernel/object-sets/eval", post(body)),
  metricHistory: (ref: string, grain = "day", n = 30, dimensions: string[] = []) =>
    req<MetricHistory>(`/api/kernel/metrics/${enc(ref)}/history${qs({ grain, n, dimensions: dimensions.join(",") })}`),
  objectHistory: (typeRef: string, key: string, opts: { as_of?: string; property?: string } = {}) =>
    req<ObjectHistory>(`/api/kernel/objects/${enc(typeRef)}/${enc(key)}/history${qs(opts)}`),
  interfaceImpls: (ref: string) =>
    req<{ id: string; name: string; mapping: Record<string, string> }[]>(`/api/kernel/interfaces/${enc(ref)}/implementations`),
  syncStorage: () => req<{ tables: any[] }>("/api/kernel/storage/sync", post()),
  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)),

  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 })),
  queryObjects: (type: string, body: { filters?: any[]; sort?: any[]; q?: string; limit?: number; offset?: number }) =>
    req<{ items: ObjectRec[]; total: number; limit: number; offset: number; fields?: import("./format").FieldMeta[] }>(`/api/kernel/objects/${enc(type)}/query`, post(body)),
  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"])),

  objectFromTable: (ds_id: number, table: string, name = "") => req<Concept>("/api/kernel/from-table", post({ ds_id, table, name })),
  autobind: () => req<AutobindResult>("/api/kernel/autobind"),
  applyAutobind: (ids?: string[]) => req<{ count: number; applied: { concept_id: string; name: string; text: string }[] }>("/api/kernel/autobind", post({ ids })),
  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"),

  // AI 建模
  modelingStages: () => req<{ stages: { key: string; label: string; desc: string }[] }>("/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 }),
  /** 开始 / 继续;fromStage 给了就从这一步重跑 */
  startModelingRun: (id: string, fromStage = "") =>
    req<ModelRunRec>(`/api/kernel/modeling/runs/${enc(id)}/start${qs({ from_stage: fromStage })}`, post()),
  stopModelingRun: (id: string) => req<ModelRunRec>(`/api/kernel/modeling/runs/${enc(id)}/stop`, post()),
  cancelModelingRun: (id: string) => req<ModelRunRec>(`/api/kernel/modeling/runs/${enc(id)}/cancel`, post()),
  modelingCalls: (id: string, stage = "") =>
    req<ModelCallRec[]>(`/api/kernel/modeling/runs/${enc(id)}/calls${qs({ stage })}`).then((r) => _arr<ModelCallRec>(r)),
  modelingCall: (id: string, callId: number) => req<ModelCallDetail>(`/api/kernel/modeling/runs/${enc(id)}/calls/${callId}`),
  adoptModeling: (id: string, itemIds: string[], sopIds: string[] = [], watchIds: string[] = []) =>
    req<AdoptResult>(`/api/kernel/modeling/runs/${enc(id)}/adopt`, post({ item_ids: itemIds, sop_ids: sopIds, watch_ids: watchIds })),
  discardModeling: (id: string, itemIds: string[], sopIds: string[] = [], watchIds: string[] = []) =>
    req<{ discarded: number; sops: number; watches: number }>(`/api/kernel/modeling/runs/${enc(id)}/discard`,
      post({ item_ids: itemIds, sop_ids: sopIds, watch_ids: watchIds })),
  deleteModelingRun: (id: string) => req<{ ok: boolean }>(`/api/kernel/modeling/runs/${enc(id)}`, del),
  modelingDeps: (id: string, itemIds: string[], sopIds: string[] = [], watchIds: string[] = []) =>
    req<{ item_ids: string[]; items: { id: string; name: string; why: string }[] }>(
      `/api/kernel/modeling/runs/${enc(id)}/deps${qs({ item_ids: itemIds.join(","), sop_ids: sopIds.join(","), watch_ids: watchIds.join(",") })}`),
  saveModelingItem: (id: string, itemId: string, patch: Record<string, any>) =>
    req<{ id: string; payload: any; readiness: Readiness; problems: string[] }>(
      `/api/kernel/modeling/runs/${enc(id)}/items/${enc(itemId)}`, put(patch)),
  aiEditModelingItem: (id: string, itemId: string, instruction: string) =>
    req<{ before: any; after: any; problems: string[]; readiness: Readiness; summary: string; new_properties: any[] }>(
      `/api/kernel/modeling/runs/${enc(id)}/items/${enc(itemId)}/ai-edit`, post({ instruction })),
  saveModelingWatch: (id: string, wid: string, body: Record<string, any>) =>
    req<ModelWatchDraft>(`/api/kernel/modeling/runs/${enc(id)}/watches/${enc(wid)}`, put(body)),
  aiEditModelingWatch: (id: string, wid: string, instruction: string) =>
    req<{ before: any; after: any; problems: string[]; trial: Trial; summary: string }>(
      `/api/kernel/modeling/runs/${enc(id)}/watches/${enc(wid)}/ai-edit`, post({ instruction })),
  aiEditModelingSop: (id: string, sid: string, instruction = "") =>
    req<{ changed: boolean; summary: string; validation: SopValidation; dry_run?: any }>(
      `/api/kernel/modeling/runs/${enc(id)}/sops/${enc(sid)}/ai-edit`, post({ instruction })),
  trialModelingSop: (id: string, sid: string) => req<any>(`/api/kernel/modeling/runs/${enc(id)}/sops/${enc(sid)}/trial`, post()),
  fixModelingCheck: (id: string, ids?: string[]) =>
    req<ModelRunRec>(`/api/kernel/modeling/runs/${enc(id)}/check/fix`, post(ids ? { ids } : {})),
  ignoreModelingCheck: (id: string, reqId: string, ignored: boolean) =>
    req<ModelCheck>(`/api/kernel/modeling/runs/${enc(id)}/check/ignore`, post({ id: reqId, ignored })),
  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"])),
  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[]; now_id?: string }) =>
    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 })),
  watchAlerts: (state = "open", watch_id = "", object_type = "", object_key = "") =>
    req<AlertEvent[]>(`/api/watch/alerts${qs({ state, watch_id, object_type, object_key })}`),
  alertStats: (watch_id = "", days = 30) => req<AlertStats>(`/api/watch/alerts/stats${qs({ watch_id, days })}`),
  alert: (id: string) => req<AlertEvent>(`/api/watch/alerts/${enc(id)}`),
  ignoreAlert: (id: string, reason: string, silence_days = 0) =>
    req<AlertEvent>(`/api/watch/alerts/${enc(id)}/ignore`, post({ reason, silence_days })),
  closeAlert: (id: string, note = "") => req<AlertEvent>(`/api/watch/alerts/${enc(id)}/close`, post({ note })),
  watchFields: (source: any, detectors: any[] = []) => req<WatchField[]>("/api/watch/fields", post({ source, detectors })),
  trace: (kind: string, id: string) => req<{ up: any[]; down: any[] }>(`/api/gov/trace${qs({ kind, id })}`),
  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
  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`),
  sopMeta: () => req<FlowMeta>("/api/sop/meta"),
  /** 校验一棵还没保存的步骤树:问题清单 + 每一步产出什么(数据选择器用) */
  validateFlow: (spec: SopSpec, defId = "") =>
    req<SopValidation & { spec: SopSpec; outputs: FlowOutput[] }>("/api/sop/validate", post({ spec, def_id: defId })),
  sopLinks: (objectType: string) => req<FlowLink[]>(`/api/sop/links${qs({ object_type: objectType })}`).then((r) => _arr<FlowLink>(r)),
  saveWriteAsAction: (id: string, stepId: string, step: SopStep, name = "") =>
    req<{ id: string; name: string }>(`/api/sop/defs/${enc(id)}/steps/${enc(stepId)}/save-as-action`, post({ step, name })),
  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> = {}, step?: SopStep) => 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, step })),
  dryRunSop: (id: string, params: any, mock: Record<string, any> = {}) =>
    req<SopRun>(`/api/sop/defs/${enc(id)}/dry-run`, post({ params, mock })),
  /** 发布:有资格的人直接发布(published 有值),其他人自动转成提交审核(review 有值) */
  publishSop: (id: string, note = "") =>
    req<{ published: { def_id: string; version: number } | null; review: ReviewItem | null }>(`/api/sop/defs/${enc(id)}/publish`, post({ note })),
  sopChanges: (id: string) => req<{ changes: { id: string; title: string; change: "added" | "removed" | "changed" }[];
    can_publish_directly: boolean }>(`/api/sop/defs/${enc(id)}/changes`),
  /** source="ask":提问里 AI 建议、本人确认后发起 */
  runSop: (id: string, params: any, source = "") => req<SopRun>(`/api/sop/defs/${enc(id)}/run`, post({ params, source })),
  markAskCard: (turnId: string, kind: "action" | "sop", index: number, ref: string) =>
    req<AskCard>(`/api/ask/turns/${enc(turnId)}/cards`, post({ kind, index, ref })),
  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)}`),
  sopRunsPage: (p: Record<string, unknown> = {}) =>
    req<{ items: SopRun[]; total: number; limit: number; offset: number }>(`/api/sop/runs-page${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),
  saveConversation: (id: string, body: { title?: string; pinned?: boolean }) =>
    req<{ id: string; title: string; pinned: boolean }>(`/api/ask/conversations/${enc(id)}`, put(body)),
  stopAsk: (turnId: string) => req<{ stopped: boolean }>(`/api/ask/turns/${enc(turnId)}/stop`, post({})),
  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; scope_ref?: 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"])) })),
};

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", object_set: "#10b981", decision: "#d946ef", ai: "#14b8a6", interface: "#8b5cf6",
  value_type: "#64748b",
  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: "规则", object_set: "对象集", decision: "决策表", ai: "AI 分析(参考)", interface: "接口",
  value_type: "值类型",
};

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);
}

// ---------------- v10 内核:值类型 / 时间层 ----------------
export interface ValueTypeDef {
  name: string; id: string; builtin: boolean; base_type: string; unit: string; format: string;
  min: number | null; max: number | null; precision: number | null; pattern: string; enum_values: string[];
  message: string; description: string;
}
export interface MetricHistory {
  metric: { id: string; name: string; unit: string }; grain: string; source: "time_column" | "snapshot";
  dimensions: string[]; series: Record<string, { period: string; value: number | null }[]>;
}
export interface ObjectHistory {
  changes: { property: string; old: any; new: any; source: string; ref: string; at: string }[];
  as_of?: { at: string; existed: boolean; properties: Record<string, any> };
  points?: { at: string; value: number | null; text: string }[];
}