@stalfh233/omc-cli 0.6.47 → 0.6.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/capability-overview.js +114 -1
  2. package/dist/cli-stdout.js +3 -0
  3. package/dist/cli.js +318 -62
  4. package/dist/closest-match.js +22 -3
  5. package/dist/command-transport.js +5 -1
  6. package/dist/discovery.js +193 -75
  7. package/dist/goal-plan.js +1296 -0
  8. package/dist/goal-routes.js +87 -5
  9. package/dist/graph.js +223 -34
  10. package/dist/intent/capabilities/field.js +24 -0
  11. package/dist/intent/plan-apply.js +10 -3
  12. package/dist/intent/schema.js +24 -1
  13. package/dist/lanes/app.js +4 -0
  14. package/dist/lanes/apply-changes.js +1 -0
  15. package/dist/lanes/b2-registration.js +24 -0
  16. package/dist/lanes/businessrule.js +14 -0
  17. package/dist/lanes/custom-page.js +8 -0
  18. package/dist/lanes/datarule.js +4 -0
  19. package/dist/lanes/dictionary.js +13 -0
  20. package/dist/lanes/environment.js +2 -0
  21. package/dist/lanes/field.js +5 -0
  22. package/dist/lanes/folder.js +4 -0
  23. package/dist/lanes/form.js +5 -0
  24. package/dist/lanes/list-view-contract.js +1 -1
  25. package/dist/lanes/list-view.js +5 -0
  26. package/dist/lanes/meta.js +5 -0
  27. package/dist/lanes/model.js +9 -0
  28. package/dist/lanes/online-js.js +2 -0
  29. package/dist/lanes/organization.js +20 -0
  30. package/dist/lanes/perm.js +5 -5
  31. package/dist/lanes/programming.js +6 -0
  32. package/dist/lanes/report.js +9 -0
  33. package/dist/lanes/rule-lifecycle.js +6 -0
  34. package/dist/lanes/rulelog.js +1 -0
  35. package/dist/lanes/runtime-data.js +39 -1
  36. package/dist/lanes/workflow.js +18 -0
  37. package/dist/mcp-graph.js +180 -41
  38. package/dist/package-tool.js +1 -0
  39. package/dist/recipes/workflow.js +1 -1
  40. package/dist/search-index.js +137 -0
  41. package/dist/tool-search.js +647 -0
  42. package/dist/tool-types.js +6 -0
  43. package/dist/tools.js +1 -0
  44. package/dist/write.js +2 -1
  45. package/docs/omc-introduction.md +5 -7
  46. package/package.json +6 -5
  47. package/skills/omc-business-configuration.md +2 -1
  48. package/skills/omc-capabilities.md +4 -2
  49. package/skills/omc-start-here.md +21 -7
  50. package/skills/omc-tool-selection.md +7 -15
  51. package/skills/omc-write-hazards.md +1 -1
@@ -1060,6 +1060,7 @@ async function diagnoseDbException(session, schemaCode, error) {
1060
1060
  export function registerRuntimeDataLane(tools) {
1061
1061
  tools.push(defineTool({
1062
1062
  name: "data.list",
1063
+ search: { intents: ["查业务数据", "查询数据", "查数据", "查记录", "查单据"] },
1063
1064
  layer: "low",
1064
1065
  kind: "read",
1065
1066
  lane: RUNTIME_LANE,
@@ -1187,8 +1188,40 @@ export function registerRuntimeDataLane(tools) {
1187
1188
  const catalog = await publishedFields();
1188
1189
  const codes = catalog.map((row) => row.code);
1189
1190
  const sample = catalog.slice(0, FILTER_FIELD_SAMPLE_LIMIT);
1191
+ // r60c-F6(真机复现):`contract_amount` 拼错 + `gt` 过滤时建议了
1192
+ // `contract_name`(SHORT_TEXT)——名字最像,类型全错,照抄得到类型错
1193
+ // 或空结果。didYouMean 按「名字相似 × 类型匹配」重排:数值比较族
1194
+ // op(gt/lt/gte/lte/between)优先推 NUMERICAL/DATE 字段。
1195
+ const opByField = new Map();
1196
+ const walkLeaves = (node) => {
1197
+ if (Array.isArray(node)) {
1198
+ node.forEach(walkLeaves);
1199
+ return;
1200
+ }
1201
+ if (node === null || typeof node !== "object")
1202
+ return;
1203
+ const leaf = node;
1204
+ if (typeof leaf.field === "string" && leaf.field && typeof leaf.op === "string")
1205
+ opByField.set(leaf.field, String(leaf.op).toLowerCase());
1206
+ Object.values(leaf).forEach(walkLeaves);
1207
+ };
1208
+ walkLeaves(condition);
1209
+ const NUMERIC_OPS = new Set(["gt", "lt", "gte", "lte", "between", "notbetween"]);
1210
+ const NUMERICISH_TYPES = new Set([2, 3]); // NUMERICAL, DATE
1190
1211
  const didYouMean = Object.fromEntries(injected.missing
1191
- .map((code) => [code, closestMatch(code, codes)])
1212
+ .map((code) => {
1213
+ let suggestion = closestMatch(code, codes);
1214
+ const op = opByField.get(code);
1215
+ if (suggestion !== undefined && op !== undefined && NUMERIC_OPS.has(op)) {
1216
+ const suggestedType = catalog.find((row) => row.code === suggestion)?.type;
1217
+ if (suggestedType !== undefined && !NUMERICISH_TYPES.has(suggestedType)) {
1218
+ const typeMatched = catalog.find((row) => NUMERICISH_TYPES.has(row.type) && closestMatch(code, [row.code]) === row.code);
1219
+ if (typeMatched !== undefined)
1220
+ suggestion = typeMatched.code;
1221
+ }
1222
+ }
1223
+ return [code, suggestion];
1224
+ })
1192
1225
  .filter((entry) => entry[1] !== undefined));
1193
1226
  const didYouMeanHint = Object.entries(didYouMean).map(([from, to]) => `;${from} 是否想写 ${to}`).join("");
1194
1227
  // r26b 读回体积审计(2026-11-05):目录此前在**同一个信封里被写三遍**
@@ -1522,6 +1555,7 @@ export function registerRuntimeDataLane(tools) {
1522
1555
  }));
1523
1556
  tools.push(defineTool({
1524
1557
  name: "data.load",
1558
+ search: { intents: ["读一条记录", "按id查记录", "看单条数据", "读业务数据详情"] },
1525
1559
  layer: "low",
1526
1560
  kind: "read",
1527
1561
  lane: RUNTIME_LANE,
@@ -1593,6 +1627,7 @@ export function registerRuntimeDataLane(tools) {
1593
1627
  writeTool({
1594
1628
  tools,
1595
1629
  name: "data.save",
1630
+ search: { intents: ["存草稿", "保存草稿单据", "新建草稿数据"] },
1596
1631
  lane: RUNTIME_LANE,
1597
1632
  scope: RUNTIME_TOOLS["data.save"].scope,
1598
1633
  description: RUNTIME_TOOLS["data.save"].description,
@@ -1820,6 +1855,7 @@ export function registerRuntimeDataLane(tools) {
1820
1855
  writeTool({
1821
1856
  tools,
1822
1857
  name: "data.update",
1858
+ search: { intents: ["改一条记录", "编辑单据", "更新业务数据"] },
1823
1859
  lane: RUNTIME_LANE,
1824
1860
  scope: RUNTIME_TOOLS["data.update"].scope,
1825
1861
  description: RUNTIME_TOOLS["data.update"].description,
@@ -1916,6 +1952,7 @@ export function registerRuntimeDataLane(tools) {
1916
1952
  writeTool({
1917
1953
  tools,
1918
1954
  name: "data.delete",
1955
+ search: { intents: ["删一条记录", "删单据", "删除业务数据"] },
1919
1956
  lane: RUNTIME_LANE,
1920
1957
  scope: RUNTIME_TOOLS["data.delete"].scope,
1921
1958
  description: RUNTIME_TOOLS["data.delete"].description,
@@ -2030,6 +2067,7 @@ export function registerRuntimeDataLane(tools) {
2030
2067
  writeTool({
2031
2068
  tools,
2032
2069
  name: "data.submit",
2070
+ search: { intents: ["造测试数据", "造数据", "录数据", "造单据", "提交数据"] },
2033
2071
  lane: RUNTIME_LANE,
2034
2072
  scope: RUNTIME_TOOLS["data.submit"].scope,
2035
2073
  description: RUNTIME_TOOLS["data.submit"].description,
@@ -2387,6 +2387,7 @@ export function registerWorkflowLane(tools) {
2387
2387
  const siblings = tools;
2388
2388
  tools.push(defineTool({
2389
2389
  name: "workflow.get_draft",
2390
+ search: { intents: ["看流程草稿", "查流程草稿"] },
2390
2391
  layer: "low",
2391
2392
  kind: "read",
2392
2393
  lane: WORKFLOW_LANE,
@@ -2415,6 +2416,7 @@ export function registerWorkflowLane(tools) {
2415
2416
  }));
2416
2417
  tools.push(defineTool({
2417
2418
  name: "workflow.get_published",
2419
+ search: { intents: ["查看流程模板", "看流程", "查流程"] },
2418
2420
  layer: "low",
2419
2421
  kind: "read",
2420
2422
  lane: WORKFLOW_LANE,
@@ -2499,6 +2501,7 @@ export function registerWorkflowLane(tools) {
2499
2501
  }));
2500
2502
  tools.push(defineTool({
2501
2503
  name: "workflow.validate",
2504
+ search: { intents: ["校验流程", "流程预检", "检查流程配置有没有问题"] },
2502
2505
  layer: "low",
2503
2506
  kind: "read",
2504
2507
  lane: WORKFLOW_LANE,
@@ -2552,6 +2555,7 @@ export function registerWorkflowLane(tools) {
2552
2555
  writeTool({
2553
2556
  tools,
2554
2557
  name: "workflow.create",
2558
+ search: { intents: ["新建流程", "建流程", "建审批流", "新建审批流", "配审批流", "配置审批流", "审批流模板", "流程模板"] },
2555
2559
  lane: WORKFLOW_LANE,
2556
2560
  scope: WORKFLOW_TOOLS["workflow.create"].scope,
2557
2561
  description: WORKFLOW_TOOLS["workflow.create"].description,
@@ -2613,6 +2617,7 @@ export function registerWorkflowLane(tools) {
2613
2617
  writeTool({
2614
2618
  tools,
2615
2619
  name: "workflow.update",
2620
+ search: { intents: ["更新流程", "修改流程", "改流程", "加审批节点"] },
2616
2621
  lane: WORKFLOW_LANE,
2617
2622
  scope: WORKFLOW_TOOLS["workflow.update"].scope,
2618
2623
  description: WORKFLOW_TOOLS["workflow.update"].description,
@@ -2737,6 +2742,7 @@ export function registerWorkflowLane(tools) {
2737
2742
  writeTool({
2738
2743
  tools,
2739
2744
  name: "workflow.publish",
2745
+ search: { intents: ["发布流程"] },
2740
2746
  lane: WORKFLOW_LANE,
2741
2747
  scope: WORKFLOW_TOOLS["workflow.publish"].scope,
2742
2748
  description: WORKFLOW_TOOLS["workflow.publish"].description,
@@ -2804,6 +2810,7 @@ export function registerWorkflowLane(tools) {
2804
2810
  writeTool({
2805
2811
  tools,
2806
2812
  name: "workflow.bindRule",
2813
+ search: { intents: ["绑定规则", "流程绑定规则", "给流程绑规则"] },
2807
2814
  lane: WORKFLOW_LANE,
2808
2815
  scope: WORKFLOW_TOOLS["workflow.bindRule"].scope,
2809
2816
  description: WORKFLOW_TOOLS["workflow.bindRule"].description,
@@ -2984,6 +2991,7 @@ export function registerWorkflowLane(tools) {
2984
2991
  writeTool({
2985
2992
  tools,
2986
2993
  name: "workflow.setButtons",
2994
+ search: { intents: ["勾选按钮", "表单操作按钮", "节点按钮", "按钮权限"] },
2987
2995
  lane: WORKFLOW_LANE,
2988
2996
  scope: WORKFLOW_TOOLS["workflow.setButtons"].scope,
2989
2997
  description: WORKFLOW_TOOLS["workflow.setButtons"].description,
@@ -3107,6 +3115,7 @@ export function registerWorkflowLane(tools) {
3107
3115
  writeTool({
3108
3116
  tools,
3109
3117
  name: "workflow.delete",
3118
+ search: { intents: ["删除流程", "删掉审批流", "删除流程模板"] },
3110
3119
  lane: WORKFLOW_LANE,
3111
3120
  scope: WORKFLOW_TOOLS["workflow.delete"].scope,
3112
3121
  description: WORKFLOW_TOOLS["workflow.delete"].description,
@@ -3193,6 +3202,7 @@ export function registerWorkflowLane(tools) {
3193
3202
  // gates/readbacks are identical, in one governed package.
3194
3203
  registerPackageTool(tools, {
3195
3204
  name: "configure_workflow",
3205
+ search: { intents: ["配置工作流"] },
3196
3206
  lane: WORKFLOW_LANE,
3197
3207
  scope: WORKFLOW_TOOLS["configure_workflow"].scope,
3198
3208
  description: WORKFLOW_TOOLS["configure_workflow"].description,
@@ -3254,6 +3264,7 @@ export function registerWorkflowLane(tools) {
3254
3264
  });
3255
3265
  tools.push(defineTool({
3256
3266
  name: "workitem.list",
3267
+ search: { intents: ["查我的待办", "我的待办", "待办列表", "查待办"] },
3257
3268
  layer: "low",
3258
3269
  kind: "read",
3259
3270
  lane: WORKFLOW_LANE,
@@ -3400,6 +3411,7 @@ export function registerWorkflowLane(tools) {
3400
3411
  }));
3401
3412
  tools.push(defineTool({
3402
3413
  name: "workflow.instanceActivity",
3414
+ search: { intents: ["流程实例状态", "实例节点状态", "节点状态", "流程走到哪", "实例每个节点"] },
3403
3415
  layer: "low",
3404
3416
  kind: "read",
3405
3417
  lane: WORKFLOW_LANE,
@@ -3565,6 +3577,7 @@ export function registerWorkflowLane(tools) {
3565
3577
  };
3566
3578
  tools.push(defineTool({
3567
3579
  name: "workflow.permissions",
3580
+ search: { intents: ["谁能发起这个流程", "发起权限清单", "流程发起权限列表"] },
3568
3581
  layer: "low",
3569
3582
  kind: "read",
3570
3583
  lane: WORKFLOW_LANE,
@@ -3627,6 +3640,7 @@ export function registerWorkflowLane(tools) {
3627
3640
  writeTool({
3628
3641
  tools,
3629
3642
  name: "workflow.addPermission",
3643
+ search: { intents: ["加发起权限", "给流程加发起权限", "授予发起权限", "谁能发起流程"] },
3630
3644
  lane: WORKFLOW_LANE,
3631
3645
  scope: WORKFLOW_TOOLS["workflow.addPermission"].scope,
3632
3646
  description: WORKFLOW_TOOLS["workflow.addPermission"].description,
@@ -3719,6 +3733,7 @@ export function registerWorkflowLane(tools) {
3719
3733
  writeTool({
3720
3734
  tools,
3721
3735
  name: "workflow.removePermission",
3736
+ search: { intents: ["撤销发起权限", "撤销权限", "取消发起权限"] },
3722
3737
  lane: WORKFLOW_LANE,
3723
3738
  scope: WORKFLOW_TOOLS["workflow.removePermission"].scope,
3724
3739
  description: WORKFLOW_TOOLS["workflow.removePermission"].description,
@@ -3856,6 +3871,7 @@ export function registerWorkflowLane(tools) {
3856
3871
  });
3857
3872
  tools.push(defineTool({
3858
3873
  name: "org.role.list",
3874
+ search: { intents: ["有哪些角色", "角色清单", "列出角色", "看角色组和角色"] },
3859
3875
  layer: "low",
3860
3876
  kind: "read",
3861
3877
  lane: WORKFLOW_LANE,
@@ -3900,6 +3916,7 @@ export function registerWorkflowLane(tools) {
3900
3916
  }));
3901
3917
  tools.push(defineTool({
3902
3918
  name: "org.department.list",
3919
+ search: { intents: ["查部门树", "部门列表", "查部门", "组织架构"] },
3903
3920
  layer: "low",
3904
3921
  kind: "read",
3905
3922
  lane: WORKFLOW_LANE,
@@ -3943,6 +3960,7 @@ export function registerWorkflowLane(tools) {
3943
3960
  }));
3944
3961
  tools.push(defineTool({
3945
3962
  name: "org.user.search",
3963
+ search: { intents: ["搜员工", "找人", "按名字查用户", "搜索账号"] },
3946
3964
  layer: "low",
3947
3965
  kind: "read",
3948
3966
  lane: WORKFLOW_LANE,
package/dist/mcp-graph.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { DatabaseSync } from "node:sqlite";
3
- import { existsSync } from "node:fs";
4
- import { resolve } from "node:path";
3
+ import { readdirSync } from "node:fs";
4
+ import { basename, join, resolve, sep } from "node:path";
5
5
  import { createInterface } from "node:readline";
6
- import { GraphIndexAbsentError, graphDbPath, impactGraph, queryGraphReferences, readGraphStatus, searchGraphRules, } from "./graph.js";
6
+ import { GraphIndexError, graphRoot, impactGraph, listGraphIndexes, queryGraphReferences, readGraphStatus, resolveGraphDbPath, searchGraphRules, } from "./graph.js";
7
7
  /**
8
8
  * Stdio MCP server for the local rule-graph index (ADR-0008).
9
9
  *
@@ -33,6 +33,80 @@ const ownVersion = () => {
33
33
  }
34
34
  };
35
35
  const SERVER_INFO = { name: "omc-graph", version: ownVersion() };
36
+ let serverConfig = { roots: [] };
37
+ export function configureGraphServer(config) {
38
+ serverConfig = { roots: [...(config.roots ?? [])] };
39
+ }
40
+ function registeredRoots() {
41
+ // No `--path` behaves exactly like the CLI: OMC_GRAPH_PATH, else the config
42
+ // root (OMC_CONFIG_HOME / cwd). Resolving through graphRoot() keeps the MCP
43
+ // face and the CLI face pointed at the same directory.
44
+ return serverConfig.roots.length > 0 ? [...serverConfig.roots] : [graphRoot()];
45
+ }
46
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "target", ".venv", "venv", "__pycache__"]);
47
+ /** Roots that actually carry at least one index, in stable order. */
48
+ function scanProjects() {
49
+ const seen = new Set();
50
+ const found = [];
51
+ const consider = (root) => {
52
+ const resolved = resolve(root);
53
+ if (seen.has(resolved))
54
+ return;
55
+ seen.add(resolved);
56
+ const indexes = listGraphIndexes(resolved);
57
+ if (indexes.length > 0)
58
+ found.push({ root: resolved, indexes });
59
+ };
60
+ for (const root of registeredRoots()) {
61
+ consider(root);
62
+ // Workspace layout: one level down only — cheap (a single readdir), and it
63
+ // is where `<workspace>/<project>/.omc/graph` actually lives.
64
+ let children = [];
65
+ try {
66
+ children = readdirSync(resolve(root), { withFileTypes: true });
67
+ }
68
+ catch { /* unreadable root — the explicit --path entries still work */ }
69
+ for (const child of children) {
70
+ if (!child.isDirectory())
71
+ continue;
72
+ if (child.name.startsWith(".") || SKIP_DIRS.has(child.name))
73
+ continue;
74
+ consider(join(resolve(root), child.name));
75
+ }
76
+ }
77
+ return found.sort((a, b) => a.root.localeCompare(b.root));
78
+ }
79
+ function projectNames() {
80
+ return scanProjects().map((project) => project.root);
81
+ }
82
+ /**
83
+ * Resolve the `project` argument: a registered root by basename, or a path
84
+ * that equals / sits under one of the registered roots. Anything else is
85
+ * refused with the known list — a read-only index still should not let a caller
86
+ * wander outside what the operator registered.
87
+ */
88
+ function resolveProjectRoot(project) {
89
+ const roots = registeredRoots();
90
+ const wanted = project?.trim();
91
+ if (!wanted)
92
+ return roots[0];
93
+ // Basename collision is a real layout (work/a/app + work/b/app): picking the
94
+ // first silently would answer from the WRONG project's index — the exact
95
+ // failure mode this multi-project change exists to prevent. Refuse instead.
96
+ const byName = [...new Set([...roots, ...projectNames()])].filter((root) => basename(root).toLowerCase() === wanted.toLowerCase());
97
+ if (byName.length === 1)
98
+ return byName[0];
99
+ if (byName.length > 1)
100
+ throw new GraphIndexError(`项目名「${wanted}」有歧义,匹配到多个项目根:${byName.join("、")}。请改传完整绝对路径。`);
101
+ const asPath = resolve(wanted);
102
+ const inside = roots.find((root) => {
103
+ const resolved = resolve(root);
104
+ return asPath === resolved || asPath.startsWith(resolved + sep);
105
+ });
106
+ if (inside)
107
+ return asPath;
108
+ throw new GraphIndexError(`未知项目「${wanted}」。已注册/已建索引的项目:${(projectNames().length > 0 ? projectNames() : roots).join("、") || "(无)"}。用 omc_graph_projects 列全部,或让维护者用 --path 把它注册进 MCP。`);
109
+ }
36
110
  const KINDS = ["field", "model", "service"];
37
111
  const MATCH_CAP = 50;
38
112
  const ERROR_CODES = { parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603 };
@@ -45,15 +119,16 @@ function respondError(id, code, message) {
45
119
  const INSTRUCTIONS_INDEXED = [
46
120
  "规则/配置图检索(本地索引,先于逐平台扫描使用):",
47
121
  "- 改名/删除/重构一个 字段(field)/模型(model)/服务(service) 前,先用 omc_graph_explore 查引用与影响面;查\"谁引用了 X\"也走它。",
122
+ "- 不确定查哪个库时先调 omc_graph_projects(零参数):列出所有项目根 + 各自可查的环境名。",
123
+ "- 每个索引的身份是「项目根 + 环境名」这一对:同一个项目可以同时建了 test/prod 等多份,同一环境也可以被多个项目各自 pull。所以 explore/status 用 project(目录名或绝对路径)+ env 指定;只给 env 时不唯一就会报歧义并列出可用环境。",
48
124
  "- 索引只覆盖:业务规则(methodMapping/targetObjectCode)、数据规则(propertyCodes 与公式 {字段})、视图(列/排序/条件)。**不含**规则条件叶子与流程绑定。",
49
125
  "- search 语义:只匹配规则 code+name 的**词首**(中文子串不命中:搜「预算」匹配不到「增加预算」)。",
50
- "答案带 freshness/pulledAtIso——索引是快照,平台侧改动后需 CLI 重建:omc graph pull --env <env>(只读远端,约 1 分钟)。MCP 按注册时的 --path 读库;CLI pull 必须把 --path 指到本目录才能写入本库。",
51
- "索引绑定单一环境(environmentName);查别的环境先重新 pull。",
126
+ "答案带 environmentName/projectPath/dbId 与 freshness/pulledAtIso——索引是快照(平台侧改动后需 CLI 重建:omc graph pull --path <项目根> --env <env>,只读远端约 1 分钟),且多库并存时靠这三个字段自证归属。",
52
127
  ].join("\n");
53
128
  const INSTRUCTIONS_NO_INDEX = [
54
- "规则/配置图检索(omc-graph):当前项目还没有本地索引(<项目>/.omc/graph/graph.db 不存在),工具暂时无法回答。",
55
- "先请用户执行 CLI:omc graph pull --env <环境名>(只读远端,约 1 分钟;环境名以 omc doctor 的「环境=」或 .omc-env 为准),完成后再来调用。",
56
- "不要在无索引状态下反复重试本工具。",
129
+ "规则/配置图检索(omc-graph):已注册的项目根下还没有任何本地索引(<项目根>/.omc/graph/<env>.db 都不存在),工具暂时无法回答。",
130
+ "先请用户执行 CLI:omc graph pull --path <项目根> --env <环境名>(只读远端,约 1 分钟;环境名以 omc doctor 的「环境=」或 .omc-env 为准),完成后再来调用。",
131
+ "多项目/多环境时用 omc graph indexes(CLI)或 omc_graph_projects(MCP)确认到底有哪些库。不要在无索引状态下反复重试本工具。",
57
132
  ].join("\n");
58
133
  const EXPLORE_TOOL = {
59
134
  name: "omc_graph_explore",
@@ -74,7 +149,8 @@ const EXPLORE_TOOL = {
74
149
  kind: { type: "string", enum: [...KINDS], description: "限定一种引用种类;省略则 field/model/service 全查" },
75
150
  schemaCode: { type: "string", description: "限定字段所属模型;也可用于校验模型。" },
76
151
  applicationCode: { type: "string", description: "限定应用;仅返回该应用的实体与引用" },
77
- env: { type: "string", description: "期望的环境名;与索引所属环境不一致时会拒绝(防跨环境误答)" },
152
+ env: { type: "string", description: "查哪个环境的索引。一个项目可同时建了多个环境(test/prod…),省略时要求该项目根下只有一份索引,否则报歧义并列出可用环境" },
153
+ project: { type: "string", description: "查哪个项目的索引:注册过的项目根(可只给目录名)或根下的绝对路径。省略=第一个注册的 --path。用 omc_graph_projects 列全部" },
78
154
  offset: { type: "integer", minimum: 0, description: "引用/实体结果起始偏移;truncated 时使用 nextOffset" },
79
155
  limit: { type: "integer", minimum: 1, maximum: MATCH_CAP, description: "每类结果最多返回多少条(默认 50)" },
80
156
  },
@@ -83,11 +159,27 @@ const EXPLORE_TOOL = {
83
159
  };
84
160
  const STATUS_TOOL = {
85
161
  name: "omc_graph_status",
86
- description: "索引完整性与新鲜度(所有身份与新鲜度字段同层):environmentName、freshness(complete|partial)、模型/规则计数、pulledAtIso、ageMinutes、staleAfterMinutes、dbId、dbPath、coverage、gaps。超过阈值会给 warning;索引缺失会给出 pull 指引。",
87
- inputSchema: { type: "object", properties: {} },
162
+ description: "索引完整性与新鲜度(所有身份与新鲜度字段同层):environmentName、projectPath、freshness(complete|partial)、模型/规则计数、pulledAtIso、ageMinutes、staleAfterMinutes、dbId、dbPath、otherIndexes(同项目其它环境)、coverage、gaps。超过阈值会给 warning;索引缺失/多份未指定会给出 pull 或选库指引。",
163
+ inputSchema: {
164
+ type: "object",
165
+ properties: {
166
+ env: { type: "string", description: "查哪个环境的索引(同项目可有多环境);省略时要求该项目根下只有一份" },
167
+ project: { type: "string", description: "查哪个项目;省略=第一个注册的 --path。用 omc_graph_projects 列全部" },
168
+ },
169
+ },
170
+ };
171
+ const PROJECTS_TOOL = {
172
+ name: "omc_graph_projects",
173
+ description: "列出这台机器上所有可查的本地图谱索引:项目根、环境名、规则/模型规模、拉取时间与新鲜度、dbId。多项目或多环境时先调它,再按 project+env 查 explore/status。零参数。",
174
+ inputSchema: {
175
+ type: "object",
176
+ properties: {
177
+ project: { type: "string", description: "只看某个项目(目录名或绝对路径);省略=所有已注册根及其一级子目录" },
178
+ },
179
+ },
88
180
  };
89
181
  export function graphToolDefinitions() {
90
- return [EXPLORE_TOOL, STATUS_TOOL];
182
+ return [PROJECTS_TOOL, EXPLORE_TOOL, STATUS_TOOL];
91
183
  }
92
184
  function toolResult(payload, isError = false) {
93
185
  return { content: [{ type: "text", text: JSON.stringify(payload) }], ...(isError ? { isError: true } : {}) };
@@ -124,8 +216,8 @@ function levenshtein(a, b) {
124
216
  }
125
217
  return prev[b.length];
126
218
  }
127
- function entityInventory() {
128
- const db = new DatabaseSync(graphDbPath(), { readOnly: true });
219
+ function entityInventory(selector = {}) {
220
+ const db = new DatabaseSync(resolveGraphDbPath(selector.root, selector.env), { readOnly: true });
129
221
  try {
130
222
  return [
131
223
  ...db.prepare("SELECT schema_code, name, application_code FROM models").all().map((r) => ({ kind: "model", schemaCode: r.schema_code, code: r.schema_code, name: r.name ?? "", applicationCode: r.application_code ?? undefined })),
@@ -137,8 +229,8 @@ function entityInventory() {
137
229
  db.close();
138
230
  }
139
231
  }
140
- function suggestions(query) {
141
- return entityInventory().map((row) => {
232
+ function suggestions(query, selector = {}) {
233
+ return entityInventory(selector).map((row) => {
142
234
  const q = query.toLocaleLowerCase();
143
235
  const values = [row.code, row.name].map((v) => v.toLocaleLowerCase());
144
236
  const prefix = values.some((v) => v.startsWith(q)) ? 0 : values.some((v) => v.includes(q)) ? 1 : 2;
@@ -150,15 +242,53 @@ function cap(rows, offset = 0, limit = MATCH_CAP) {
150
242
  const page = rows.slice(offset, offset + limit);
151
243
  return { rows: page, truncated: offset + page.length < rows.length, offset, limit, ...(offset + page.length < rows.length ? { nextOffset: offset + page.length } : {}), total: rows.length };
152
244
  }
245
+ /** Which (project, environment) an argument set points at. */
246
+ function selectorOf(args) {
247
+ const project = typeof args.project === "string" && args.project.trim() ? args.project.trim() : undefined;
248
+ const env = typeof args.env === "string" && args.env.trim() ? args.env.trim() : undefined;
249
+ return { root: resolveProjectRoot(project), ...(env ? { env } : {}) };
250
+ }
153
251
  /** Shared handler core — exported so tests drive it without a stdio pair. */
154
- export async function executeGraphTool(name, rawArgs) {
252
+ export async function executeGraphTool(name, rawArgs, context) {
155
253
  const args = (rawArgs ?? {});
254
+ const previousConfig = serverConfig;
255
+ if (context?.roots !== undefined)
256
+ serverConfig = { roots: [...context.roots] };
156
257
  try {
258
+ if (name === PROJECTS_TOOL.name) {
259
+ const only = typeof args.project === "string" && args.project.trim() ? args.project.trim() : undefined;
260
+ const projects = scanProjects()
261
+ .filter((project) => only === undefined || basename(project.root).toLowerCase() === only.toLowerCase() || resolve(project.root) === resolve(only))
262
+ .map((project) => ({
263
+ projectPath: project.root,
264
+ indexes: project.indexes.map((entry) => ({
265
+ environmentName: entry.environmentName,
266
+ dbId: entry.dbId,
267
+ readable: entry.readable,
268
+ rules: entry.rules,
269
+ models: entry.models,
270
+ applicationCode: entry.applicationCode,
271
+ pulledAtIso: entry.pulledAtIso,
272
+ ageMinutes: entry.ageMinutes,
273
+ ...(entry.error ? { error: entry.error } : {}),
274
+ })),
275
+ }));
276
+ return toolResult({
277
+ status: "ok",
278
+ roots: registeredRoots(),
279
+ count: projects.reduce((sum, project) => sum + project.indexes.length, 0),
280
+ projects,
281
+ note: "查询时把 project(项目根或目录名)与 env(环境名)一起传给 omc_graph_explore / omc_graph_status;省略 env 要求该项目根下只有一份索引。",
282
+ ...(projects.length === 0 ? { nextCommand: "omc graph pull --path <项目根> --env <环境名>" } : {}),
283
+ });
284
+ }
157
285
  if (name === STATUS_TOOL.name) {
158
- const status = readGraphStatus();
286
+ const selector = selectorOf(args);
287
+ const status = readGraphStatus(selector);
159
288
  // Keep a tiny compatibility locator for older MCP clients; all identity,
160
- // freshness, coverage and gaps fields live at the top level.
161
- return toolResult({ status: "ok", ...status, ...status.index, index: { environmentName: status.index.environmentName } });
289
+ // freshness, coverage and gaps fields live at the top level. The locator
290
+ // now carries projectPath+dbId so an answer proves WHICH index it read.
291
+ return toolResult({ status: "ok", ...status, ...status.index, index: { environmentName: status.index.environmentName, projectPath: status.index.projectPath, dbId: status.index.dbId } });
162
292
  }
163
293
  if (name === EXPLORE_TOOL.name) {
164
294
  const query = typeof args.query === "string" ? args.query.trim() : "";
@@ -174,11 +304,11 @@ export async function executeGraphTool(name, rawArgs) {
174
304
  const applicationCode = typeof args.applicationCode === "string" && args.applicationCode.trim() ? args.applicationCode.trim() : undefined;
175
305
  if (schemaCode && kind !== "field" && kind !== "model")
176
306
  return toolError("schemaCode 仅适用于 kind=field|model");
177
- const status = readGraphStatus();
307
+ // env/project SELECT the index (they used to only cross-check it): one
308
+ // project can hold `test` and `prod` side by side.
309
+ const selector = selectorOf(args);
310
+ const status = readGraphStatus(selector);
178
311
  const index = status.index;
179
- if (typeof args.env === "string" && args.env.trim() && args.env.trim() !== index.environmentName) {
180
- return toolError(`索引属于环境「${index.environmentName}」;要查「${args.env.trim()}」请先 omc graph pull --env ${args.env.trim()} 重建索引`);
181
- }
182
312
  const kinds = kind === undefined ? [...KINDS] : [kind];
183
313
  const offset = typeof args.offset === "number" && Number.isSafeInteger(args.offset) && args.offset >= 0 ? args.offset : 0;
184
314
  const limit = typeof args.limit === "number" && Number.isSafeInteger(args.limit) && args.limit > 0 && args.limit <= MATCH_CAP ? args.limit : MATCH_CAP;
@@ -186,7 +316,7 @@ export async function executeGraphTool(name, rawArgs) {
186
316
  const impact = {};
187
317
  // Resolve from an unpaged search. The result page is presentation only;
188
318
  // otherwise offset=2 can silently change the subject being inspected.
189
- const search = searchGraphRules(primaryQuery, limit, offset);
319
+ const search = searchGraphRules(primaryQuery, limit, offset, selector);
190
320
  const scopedSearch = applicationCode ? {
191
321
  ...search,
192
322
  matches: {
@@ -195,12 +325,12 @@ export async function executeGraphTool(name, rawArgs) {
195
325
  field: { ...search.matches.field, items: search.matches.field.items.filter((row) => row.applicationCode === applicationCode) },
196
326
  },
197
327
  } : search;
198
- const resolvedSearch = searchGraphRules(primaryQuery, MATCH_CAP, 0);
328
+ const resolvedSearch = searchGraphRules(primaryQuery, MATCH_CAP, 0, selector);
199
329
  const loweredQuery = primaryQuery.toLocaleLowerCase();
200
- const allCandidates = entityInventory().filter((r) => (r.code.toLocaleLowerCase().includes(loweredQuery) || r.name.toLocaleLowerCase().includes(loweredQuery)) &&
330
+ const allCandidates = entityInventory(selector).filter((r) => (r.code.toLocaleLowerCase().includes(loweredQuery) || r.name.toLocaleLowerCase().includes(loweredQuery)) &&
201
331
  (!schemaCode || (r.kind !== "service" && r.schemaCode === schemaCode)) &&
202
332
  (!applicationCode || r.applicationCode === applicationCode));
203
- const candidatesForQuery = (term) => entityInventory().filter((r) => (r.code.toLocaleLowerCase().includes(term.toLocaleLowerCase()) || r.name.toLocaleLowerCase().includes(term.toLocaleLowerCase())) &&
333
+ const candidatesForQuery = (term) => entityInventory(selector).filter((r) => (r.code.toLocaleLowerCase().includes(term.toLocaleLowerCase()) || r.name.toLocaleLowerCase().includes(term.toLocaleLowerCase())) &&
204
334
  (!schemaCode || (r.kind !== "service" && r.schemaCode === schemaCode)) &&
205
335
  (!applicationCode || r.applicationCode === applicationCode));
206
336
  const perQueryModels = queries.map((term) => new Set(candidatesForQuery(term).filter((r) => r.kind === "model").map((r) => r.schemaCode)));
@@ -225,7 +355,7 @@ export async function executeGraphTool(name, rawArgs) {
225
355
  : [];
226
356
  for (const one of kinds) {
227
357
  const subject = subjects.find((s) => s.kind === one);
228
- const ref = queryGraphReferences(one, subject?.code ?? query);
358
+ const ref = queryGraphReferences(one, subject?.code ?? query, selector);
229
359
  const scopedMatches = ref.matches.filter((row) => !applicationCode || row.applicationCode === applicationCode).filter((row) => subject && one === "field" && schemaCode ? row.schemaCode === schemaCode : true);
230
360
  const capped = cap(scopedMatches, offset, limit);
231
361
  // r35a-F4c(真机 2026-11-06):**MCP 面是第三个消费者**——CLI 的 references
@@ -240,7 +370,7 @@ export async function executeGraphTool(name, rawArgs) {
240
370
  ...(ref.gapWarning ? { gapWarning: ref.gapWarning } : {}),
241
371
  };
242
372
  if (scopedMatches.length > 0 || kind !== undefined || subject !== undefined) {
243
- const imp = impactGraph(one, subject?.code ?? query);
373
+ const imp = impactGraph(one, subject?.code ?? query, selector);
244
374
  const scopedRules = subject && one === "field" && schemaCode ? imp.rules.filter((row) => row.schemaCode === schemaCode) : imp.rules;
245
375
  impact[one] = {
246
376
  totals: scopedRules.length === imp.rules.length ? imp.totals : { ...imp.totals, rules: scopedRules.length },
@@ -272,19 +402,20 @@ export async function executeGraphTool(name, rawArgs) {
272
402
  query,
273
403
  ...(queries.length > 1 ? { queries, match: args.match === "all" ? "all" : "any" } : {}),
274
404
  hitModels: [...hitModels],
275
- ...(() => { const page = cap([...hitFieldModels].flatMap((schema) => entityInventory().filter((r) => r.kind === "field" && r.schemaCode === schema && (!applicationCode || r.applicationCode === applicationCode)).map((r) => ({ schemaCode: schema, code: r.code, name: r.name }))), offset, limit); return { hitFields: page.rows, hitFieldsCount: page.total, ...(page.truncated ? { hitFieldsTruncated: true, hitFieldsNextOffset: page.nextOffset } : {}) }; })(),
405
+ ...(() => { const page = cap([...hitFieldModels].flatMap((schema) => entityInventory(selector).filter((r) => r.kind === "field" && r.schemaCode === schema && (!applicationCode || r.applicationCode === applicationCode)).map((r) => ({ schemaCode: schema, code: r.code, name: r.name }))), offset, limit); return { hitFields: page.rows, hitFieldsCount: page.total, ...(page.truncated ? { hitFieldsTruncated: true, hitFieldsNextOffset: page.nextOffset } : {}) }; })(),
276
406
  found: resolvedEntity !== undefined,
277
407
  ...(resolvedEntity ? { resolved: { kind: resolvedEntity.kind, schemaCode: "schemaCode" in resolvedEntity ? resolvedEntity.schemaCode : "", code: resolvedEntity.code, matchedOn: { on: resolvedEntity.name.includes(query) ? "name" : "code", fragment: query }, ...(resolvedEntity.applicationCode ? { applicationCode: resolvedEntity.applicationCode } : {}) } } : {}),
278
408
  ...(resolvedEntity ? { otherCandidates: allCandidates.filter((r) => r.code !== resolvedEntity.code).slice(0, 5).map((r) => ({ schemaCode: r.schemaCode ?? r.code, name: r.name, ...(r.applicationCode ? { applicationCode: r.applicationCode } : {}) })) } : {}),
279
409
  ...(ambiguous ? { ambiguous: true, candidates: exactSame.map((r) => ({ schemaCode: r.schemaCode, code: r.code, name: r.name })) } : {}),
280
410
  ...(kind !== undefined ? { kind } : {}),
411
+ // Point 3: every answer names the project AND environment it came from.
281
412
  index,
282
413
  references,
283
414
  impact,
284
415
  search: { count: search.rules.length, rules: search.rules, matches: decoratedMatches, coverage: search.coverage },
285
416
  ...(nextCall ? { nextCall } : {}),
286
417
  ...(noEntityHit && composite ? { unsupportedQuerySyntax: true, hint: "组合检索暂不支持,请拆词单查后求交" } : {}),
287
- ...(noEntityHit ? { suggestions: suggestions(query), hint: "可尝试 suggestions 中的实体 code/name;引用明细请使用匹配 code 查 references/impact" } : {}),
418
+ ...(noEntityHit ? { suggestions: suggestions(query, selector), hint: "可尝试 suggestions 中的实体 code/name;引用明细请使用匹配 code 查 references/impact" } : {}),
288
419
  searchNote: `${searchNote}${paginationNote}${queries.length > 1 ? " 规则面(词首匹配)不参与 queries[] 的实体求交。" : ""}`,
289
420
  ...(search.note ? { searchNote: `${searchNote}\n${search.note}` } : {}),
290
421
  // 旧句「索引不含规则条件叶子与流程绑定」漏了表单与流程权限(r35a-F4 实证
@@ -296,11 +427,13 @@ export async function executeGraphTool(name, rawArgs) {
296
427
  return toolError(`未知工具:${name}`);
297
428
  }
298
429
  catch (error) {
299
- if (error instanceof GraphIndexAbsentError) {
300
- return toolError(`本地索引不存在(${graphDbPath()})。先执行:omc graph pull --env <环境名>(只读远端,约 1 分钟),完成后再调用`);
301
- }
430
+ if (error instanceof GraphIndexError)
431
+ return toolError(error.message);
302
432
  return toolError(error instanceof Error ? error.message : String(error));
303
433
  }
434
+ finally {
435
+ serverConfig = previousConfig;
436
+ }
304
437
  }
305
438
  async function handleMessage(message) {
306
439
  const id = message.id;
@@ -318,7 +451,7 @@ async function handleMessage(message) {
318
451
  protocolVersion: requested,
319
452
  capabilities: { tools: {} },
320
453
  serverInfo: SERVER_INFO,
321
- instructions: existsSync(graphDbPath()) ? INSTRUCTIONS_INDEXED : INSTRUCTIONS_NO_INDEX,
454
+ instructions: scanProjects().length > 0 ? INSTRUCTIONS_INDEXED : INSTRUCTIONS_NO_INDEX,
322
455
  });
323
456
  return;
324
457
  }
@@ -343,12 +476,18 @@ async function handleMessage(message) {
343
476
  }
344
477
  /**
345
478
  * Run the stdio server. Resolves when stdin closes (the host went away).
346
- * `projectRoot` (from --path) pins the index location exactly like the
347
- * codegraph registration does — never trust the host's cwd.
479
+ *
480
+ * `projectRoots` come from repeatable `--path` flags and pin where indexes are
481
+ * looked up — never trust the host's cwd. Registering several roots (or one
482
+ * workspace root whose children are projects) is what makes "one server, all
483
+ * projects" work: the caller picks with the `project` argument.
348
484
  */
349
- export async function runMcpGraphServer(projectRoot) {
350
- if (projectRoot)
351
- process.chdir(resolve(projectRoot));
485
+ export async function runMcpGraphServer(projectRoots) {
486
+ const roots = (typeof projectRoots === "string" ? [projectRoots] : projectRoots ?? []).map((root) => resolve(root));
487
+ if (roots.length > 0) {
488
+ serverConfig = { roots };
489
+ process.chdir(roots[0]);
490
+ }
352
491
  const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
353
492
  lines.on("line", (line) => {
354
493
  const text = line.trim();
@@ -21,6 +21,7 @@ import { defineTool } from "./tool-types.js";
21
21
  export function registerPackageTool(tools, spec) {
22
22
  tools.push(defineTool({
23
23
  name: spec.name,
24
+ ...(spec.search === undefined ? {} : { search: spec.search }),
24
25
  layer: "high",
25
26
  kind: "write",
26
27
  lane: spec.lane,
@@ -108,7 +108,7 @@ const workflowConditionalTwoLevel = Object.freeze({
108
108
  id: "workflow-conditional-two-level-approval",
109
109
  title: "金额>阈值走两级审批,否则一级(分叉再汇合)",
110
110
  status: "requires-prior-readback",
111
- aliases: ["两级审批", "条件两级", "金额大于", "一级或两级", "分叉再汇合"],
111
+ aliases: ["两级审批", "条件两级", "金额大于", "一级或两级", "分叉再汇合", "条件审批", "条件分支", "按条件审批", "条件流程"],
112
112
  tool: "workflow.update",
113
113
  args: {
114
114
  environment,