@stalfh233/omc-cli 0.6.44 → 0.6.49

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 (43) hide show
  1. package/dist/capability-overview.js +113 -0
  2. package/dist/cli-stdout.js +3 -0
  3. package/dist/cli.js +255 -60
  4. package/dist/command-transport.js +5 -1
  5. package/dist/discovery.js +193 -75
  6. package/dist/goal-plan.js +1244 -0
  7. package/dist/goal-routes.js +78 -3
  8. package/dist/graph.js +264 -38
  9. package/dist/lanes/app.js +4 -0
  10. package/dist/lanes/apply-changes.js +1 -0
  11. package/dist/lanes/b2-registration.js +24 -0
  12. package/dist/lanes/businessrule.js +5 -0
  13. package/dist/lanes/custom-page.js +8 -0
  14. package/dist/lanes/datarule.js +4 -0
  15. package/dist/lanes/dictionary.js +13 -0
  16. package/dist/lanes/environment.js +2 -0
  17. package/dist/lanes/field.js +14 -0
  18. package/dist/lanes/folder.js +4 -0
  19. package/dist/lanes/form.js +5 -0
  20. package/dist/lanes/list-view.js +5 -0
  21. package/dist/lanes/meta.js +5 -0
  22. package/dist/lanes/model.js +9 -0
  23. package/dist/lanes/online-js.js +2 -0
  24. package/dist/lanes/organization.js +20 -0
  25. package/dist/lanes/perm.js +5 -5
  26. package/dist/lanes/programming.js +6 -0
  27. package/dist/lanes/report.js +9 -0
  28. package/dist/lanes/rule-lifecycle.js +6 -0
  29. package/dist/lanes/rulelog.js +1 -0
  30. package/dist/lanes/runtime-data.js +6 -0
  31. package/dist/lanes/workflow.js +18 -0
  32. package/dist/mcp-graph.js +180 -41
  33. package/dist/package-tool.js +1 -0
  34. package/dist/search-index.js +137 -0
  35. package/dist/tool-search.js +647 -0
  36. package/dist/tools.js +1 -0
  37. package/dist/write.js +2 -1
  38. package/docs/omc-introduction.md +5 -7
  39. package/package.json +6 -5
  40. package/skills/omc-business-configuration.md +2 -1
  41. package/skills/omc-capabilities.md +3 -2
  42. package/skills/omc-start-here.md +21 -7
  43. package/skills/omc-tool-selection.md +7 -15
@@ -66,6 +66,24 @@ function capabilityWhy(capabilityId, goal) {
66
66
  return capabilityId;
67
67
  }
68
68
  }
69
+ /**
70
+ * Leading read verbs. `READ_CUES` is an "includes anywhere" list, so a bare
71
+ * 「查」 cannot join it without matching 排查/检查/追查… in write asks. But a goal
72
+ * that OPENS with a read verb is unambiguous: 「查采购申请里金额大于一万的单据」
73
+ * is a query even though 「查询一下」/「查一下」 are the only cue phrases.
74
+ *
75
+ * Missing this made a READ ask fall to the default build ladder and match the
76
+ * `workflow.update` recipe (amount thresholds share vocabulary with 金额分级) —
77
+ * a read question handed a write tool. (r59 M6, T2 end-to-end.)
78
+ */
79
+ const LEADING_READ_VERBS = ["查", "看", "读", "列", "搜", "找", "盘", "导出"];
80
+ /** Leading verbs that are ALSO common write verbs when the goal names a target field. */
81
+ const AMBIGUOUS_LEADING_READ = ["统计", "汇总"];
82
+ /**
83
+ * A verb that puts the result SOMEWHERE. 「统计子表异常行数**写入**主表字段」 opens
84
+ * with 统计 but is a compute/写 ask; 「统计这个月提交了多少单据」 is a query.
85
+ */
86
+ const WRITE_DESTINATION = /(写入|写到|写进|回写|落到|存到|更新到|同步到|填到)/;
69
87
  function detectMode(goal) {
70
88
  if (SCOUT_CUES.some((cue) => goal.includes(cue)))
71
89
  return "scout";
@@ -77,6 +95,11 @@ function detectMode(goal) {
77
95
  return "build";
78
96
  if (READ_CUES.some((cue) => goal.includes(cue)))
79
97
  return "read";
98
+ const lead = goal.trimStart();
99
+ if (LEADING_READ_VERBS.some((verb) => lead.startsWith(verb)) && !/^(查重|查错)/.test(lead))
100
+ return "read";
101
+ if (AMBIGUOUS_LEADING_READ.some((verb) => lead.startsWith(verb)) && !WRITE_DESTINATION.test(goal))
102
+ return "read";
80
103
  // No verb: keep the historical build ladder (it is the safe default shape).
81
104
  return "build";
82
105
  }
@@ -465,8 +488,11 @@ const COMPOSER_ROUTES = Object.freeze([
465
488
  summary: "存量模型加字段一条命令:建字段 → 发布 → 重建表单 → 列表追加列;--conditions 固定过滤 + --demo-rows 演示行同链折入——字段+过滤+演示数据的多段需求整句一次问,4-8 次调用合成 1 条命令",
466
489
  // (add verb) × (field noun)——「给既有/存量模型加字段」是变更类需求的最高频动作(r30/r31 探针实证手工链 4 调)
467
490
  groups: [["加", "新增", "添加", "补", "增加"], ["字段"]],
468
- // 只收「加字段本体」;规则/校验/计算/编号/流程语义各有归宿(round10:'给金额字段加自动校验规则' 应归 datarule,不能被本 composer 抢走)
469
- avoid: ["新建模型", "建模型", "从零", "子表", "childFields", "编号规则", "序列号", "规则", "校验", "计算", "默认值", "流程", "权限", "按钮"],
491
+ // 只收「加字段本体」;规则/校验/计算/流程语义各有归宿(round10:'给金额字段加自动校验规则' 应归 datarule,不能被本 composer 抢走)
492
+ // r59: 删掉「编号规则」「序列号」——dry-run 实测 `field-add --fields '[{…seqNoSetting…}]'`
493
+ // 通过(建字段→发布→重建表单→列表加列),这两个词却把「加一个序列号字段」赶去
494
+ // capability/recipe 的 9–12 回合长路。编号/序列号是字段属性,不是另一张能力面。
495
+ avoid: ["新建模型", "建模型", "从零", "子表", "childFields", "规则", "校验", "计算", "默认值", "流程", "权限", "按钮"],
470
496
  topics: ["omc-write-hazards"],
471
497
  },
472
498
  {
@@ -669,7 +695,46 @@ function readOverviewRoute(registry, goal, index) {
669
695
  },
670
696
  };
671
697
  }
672
- export function goalRoute(registry, goal) {
698
+ /**
699
+ * 引用 / 影响面提问的图谱指路(2026-11-12,r57 真机)。
700
+ *
701
+ * 为什么需要:graph 不是配置能力(不在 18 个 capability 里),所以
702
+ * `CAPABILITY_CUES` 没有它的入口,`next "这个字段在哪用了"` 只会路由到
703
+ * `field.list`(读字段定义)——答的不是「谁引用了它」。r57 探针从零搭 6 个工作包,
704
+ * `omc graph` **一次都没用过**,尽管 `omc help omc-start-here` §1b 写得很详细。
705
+ *
706
+ * 保守触发:只在**明确问引用/影响/删除前检查**时给,且不改变原有 route——
707
+ * 只追加一条可核对的指路,原有路由行照旧。给不出唯一目标 code 时只给
708
+ * `status`/`search` 这类**不带 code 也能跑**的入口。
709
+ */
710
+ const GRAPH_INTENT_RE = /(?:谁|哪(?:个|些|里))?(?:引用|使用|用到|依赖|被用|用到了)|影响面|影响范围|爆炸半径|牵连|波及|删(?:除|掉)?(?:前|之前|了会不会|会怎样|有没有风险)|能不能删|可以删(?:吗|么)|\bimpact\b|\breferences?\b|\bwho uses\b/i;
711
+ const GRAPH_OBJECT_RE = /\b([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\b/g;
712
+ function graphHintFor(goal) {
713
+ if (!GRAPH_INTENT_RE.test(goal))
714
+ return undefined;
715
+ const codes = [...new Set(goal.match(GRAPH_OBJECT_RE) ?? [])];
716
+ // ⚠️ 参数面不同(2026-11-12 真机逐条验证):`status`/`references` 收 --env(仅作绑定提示),
717
+ // 而 `impact`/`search` 是纯离线子命令,**传 --env 会 `unknown option` 直接失败**——
718
+ // 给用户一份跑不通的命令比不给更糟,所以这里按子命令分别拼。
719
+ const commands = codes.length === 1
720
+ ? [
721
+ `omc graph references field ${codes[0]} --env <环境名>`,
722
+ `omc graph references model ${codes[0]} --env <环境名>`,
723
+ `omc graph impact model ${codes[0]} # 注意:impact 不收 --env`,
724
+ ]
725
+ : [
726
+ "omc graph status --env <环境名> # 先看索引在不在、覆盖了哪些应用",
727
+ "omc graph search <词> # 用业务名找 code,再 references(search 不收 --env)",
728
+ ];
729
+ return {
730
+ why: codes.length === 1 ? `问到「${codes[0]}」的引用/影响面` : "问到引用/影响面(未给出唯一 code)",
731
+ state: "unknown",
732
+ firstCommand: "omc graph status --env <环境名>; 无索引则 omc graph pull --env <环境名>(只读,约 1 分钟)",
733
+ commands,
734
+ note: "图谱是本地的引用索引(毫秒级):一次调用答「谁引用了它」,替代逐模型 model.inspect / rule.get 枚举。索引不含规则条件叶子与流程绑定,命中后仍以 rule.get 原文为准。宿主接了 MCP 时用 omc_graph_explore(安装器自动注册)。",
735
+ };
736
+ }
737
+ function goalRouteInner(registry, goal) {
673
738
  const index = capabilityRouteIndex(registry);
674
739
  // r49 F1(探针复现):whole-package 主推 intent 前必须确认命中能力的 intent 覆盖——
675
740
  // intent.level=none 的能力(如 perm)主推 intent 是把用户推向走不通的路。
@@ -1165,4 +1230,14 @@ export function goalRoute(registry, goal) {
1165
1230
  : { firstAnswer: { state: "needs-input", question: "要操作哪个对象?给我 schemaCode(或模型业务名,我列清单核对)", action: LIST_MODELS_ACTION, why: "未命中配方:需要目标对象 code 才能给出一步可跑的写命令" } }),
1166
1231
  };
1167
1232
  }
1233
+ /**
1234
+ * `next` 的对外入口:原有路由结果原样返回,只在「引用/影响面」类提问上追加
1235
+ * `graphHint`(不改 route、不改 confident、不改 firstAnswer)。理由见
1236
+ * `graphHintFor` 注释——图谱不在能力注册表里,只能在这里补入口。
1237
+ */
1238
+ export function goalRoute(registry, goal) {
1239
+ const base = goalRouteInner(registry, goal);
1240
+ const hint = graphHintFor(goal);
1241
+ return hint === undefined ? base : { ...base, graphHint: hint };
1242
+ }
1168
1243
  //# sourceMappingURL=goal-routes.js.map
package/dist/graph.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { chmodSync, closeSync, existsSync, mkdirSync, openSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { joinConfigRoot } from "./command-transport.js";
5
5
  import { decodeJsonColumn, JSON_COLUMN_NULL_COALESCE } from "./json-column.js";
@@ -65,20 +65,173 @@ export function indexAgeMinutes(pulledAtIso, now = Date.now()) {
65
65
  return 0;
66
66
  return Math.max(0, Math.floor((now - pulled) / 60_000));
67
67
  }
68
- export class GraphIndexAbsentError extends Error {
68
+ /** Base for "the index cannot answer this call" (absent / ambiguous / unreadable). */
69
+ export class GraphIndexError extends Error {
70
+ constructor(message) {
71
+ super(message);
72
+ this.name = "GraphIndexError";
73
+ }
74
+ }
75
+ export class GraphIndexAbsentError extends GraphIndexError {
69
76
  constructor(message) {
70
77
  super(message);
71
78
  this.name = "GraphIndexAbsentError";
72
79
  }
73
80
  }
81
+ /** The file is there but cannot be answered from (corrupt / schema mismatch). */
82
+ export class GraphIndexUnreadableError extends GraphIndexError {
83
+ constructor(message) {
84
+ super(message);
85
+ this.name = "GraphIndexUnreadableError";
86
+ }
87
+ }
74
88
  export class GraphPullLockHeldError extends Error {
75
89
  constructor(message) {
76
90
  super(message);
77
91
  this.name = "GraphPullLockHeldError";
78
92
  }
79
93
  }
80
- export function graphDbPath(root) {
81
- return join(resolve(root ?? process.env.OMC_GRAPH_PATH ?? joinConfigRoot()), ".omc", "graph", "graph.db");
94
+ /** Project root that owns `<root>/.omc/graph/` (explicit > OMC_GRAPH_PATH > config root). */
95
+ export function graphRoot(root) {
96
+ return resolve(root ?? process.env.OMC_GRAPH_PATH ?? joinConfigRoot());
97
+ }
98
+ /**
99
+ * File-name-safe token for an environment name. The common case (ASCII env
100
+ * names) stays human-readable so `ls .omc/graph/` is self-explanatory; names
101
+ * that need rewriting get a digest suffix so two environments can never
102
+ * collapse onto one file.
103
+ */
104
+ export function graphEnvSlug(env) {
105
+ const trimmed = env.trim();
106
+ const safe = trimmed.replace(/[^A-Za-z0-9._-]/g, "-");
107
+ if (safe === trimmed && safe !== "" && safe !== "." && safe !== "..")
108
+ return safe;
109
+ return `${safe === "." || safe === ".." || safe === "" ? "env" : safe}-${sha256(trimmed).slice(0, 6)}`;
110
+ }
111
+ /**
112
+ * `<root>/.omc/graph/<env>.db` — one index per (project, environment).
113
+ *
114
+ * `graph.db` (no env) is the pre-0.6.x slot and stays readable: an upgraded
115
+ * machine keeps answering from it until the next pull, which writes the
116
+ * env-named file and drops the superseded legacy one.
117
+ */
118
+ export function graphDbPath(root, env) {
119
+ const dir = join(graphRoot(root), ".omc", "graph");
120
+ const wanted = env?.trim();
121
+ return join(dir, wanted ? `${graphEnvSlug(wanted)}.db` : "graph.db");
122
+ }
123
+ function metaOf(dbPath) {
124
+ const DatabaseSyncCtor = nodeSqlite().DatabaseSync;
125
+ const db = new DatabaseSyncCtor(dbPath, { readOnly: true });
126
+ try {
127
+ const meta = {};
128
+ for (const row of db.prepare("SELECT key, value FROM meta").all())
129
+ meta[row.key] = row.value;
130
+ meta.__rules = String(db.prepare("SELECT COUNT(*) AS n FROM rules").get().n);
131
+ meta.__models = String(db.prepare("SELECT COUNT(DISTINCT schema_code) AS n FROM rules").get().n);
132
+ return meta;
133
+ }
134
+ finally {
135
+ db.close();
136
+ }
137
+ }
138
+ function describeIndex(dbPath) {
139
+ const legacySlot = dbPath.split(/[\\/]/).pop() === "graph.db";
140
+ const base = { dbPath, dbId: sha256(dbPath).slice(0, 12), legacySlot, ...(existsSync(dbPath) ? { bytes: statSync(dbPath).size } : { bytes: 0 }) };
141
+ try {
142
+ const meta = metaOf(dbPath);
143
+ const pulledAtIso = meta.pulledAtIso ?? "";
144
+ return {
145
+ ...base,
146
+ environmentName: meta.environmentName ?? "",
147
+ projectPath: meta.projectPath ?? dirname(dirname(dirname(dbPath))),
148
+ applicationCode: meta.applicationCode ?? "",
149
+ pulledAtIso,
150
+ ageDays: indexAgeDays(pulledAtIso),
151
+ ageMinutes: indexAgeMinutes(pulledAtIso),
152
+ rules: Number(meta.__rules ?? 0),
153
+ models: Number(meta.__models ?? 0),
154
+ readable: true,
155
+ };
156
+ }
157
+ catch (error) {
158
+ return { ...base, environmentName: "", projectPath: dirname(dirname(dirname(dbPath))), applicationCode: "", pulledAtIso: "", ageDays: 0, ageMinutes: 0, rules: 0, models: 0, readable: false, error: error instanceof Error ? error.message : String(error) };
159
+ }
160
+ }
161
+ /**
162
+ * Every index under one project root. Sorted by environment so the answer is
163
+ * stable; a corrupt file is reported (`readable:false`) rather than skipped —
164
+ * "it exists but I cannot read it" is a different fact from "no index".
165
+ */
166
+ export function listGraphIndexes(root) {
167
+ const dir = join(graphRoot(root), ".omc", "graph");
168
+ if (!existsSync(dir))
169
+ return [];
170
+ let names;
171
+ try {
172
+ names = readdirSync(dir).filter((name) => name.endsWith(".db"));
173
+ }
174
+ catch {
175
+ return [];
176
+ }
177
+ return names
178
+ .map((name) => describeIndex(join(dir, name)))
179
+ .sort((a, b) => (a.environmentName === b.environmentName ? a.dbPath.localeCompare(b.dbPath) : a.environmentName.localeCompare(b.environmentName)));
180
+ }
181
+ /** Human-readable "what can I query here" line, used by every refusal. */
182
+ function availableIndexesHint(root) {
183
+ const entries = listGraphIndexes(root);
184
+ if (entries.length === 0)
185
+ return `该配置根下没有任何索引(${join(graphRoot(root), ".omc", "graph")})`;
186
+ const listed = entries.map((entry) => ` - env=${entry.environmentName || "(不可读)"}${entry.legacySlot ? "(legacy graph.db)" : ""} · ${entry.rules} 规则/${entry.models} 模型 · ${entry.ageMinutes} 分钟前`).join("\n");
187
+ return `可用索引(--env 选择其一):\n${listed}`;
188
+ }
189
+ /**
190
+ * Resolve which file a read opens.
191
+ *
192
+ * - env given: `<env>.db`; if absent, a legacy `graph.db` still answers when its
193
+ * meta says the same environment (upgrade path, no re-pull required).
194
+ * - env omitted: unambiguous only. One index → it; several → refuse with the
195
+ * list instead of picking one (a silent pick is how cross-env answers get
196
+ * mistaken for truth).
197
+ */
198
+ export function resolveGraphDbPath(root, env) {
199
+ const wanted = env?.trim();
200
+ if (wanted) {
201
+ const direct = graphDbPath(root, wanted);
202
+ if (existsSync(direct)) {
203
+ // The file name is a claim, the meta is the truth. A renamed/copied
204
+ // index must not silently answer for an environment it never pulled —
205
+ // resolveGraphDbPath is exported and used directly (e.g. MCP
206
+ // entityInventory), so the guard cannot live only in openGraphIndex.
207
+ const entry = describeIndex(direct);
208
+ if (entry.readable && entry.environmentName && entry.environmentName !== wanted)
209
+ throw new GraphIndexAbsentError(`索引文件 ${direct} 记录的来源环境是「${entry.environmentName}」,不是「${wanted}」;重跑 omc graph pull --env ${wanted}。${availableIndexesHint(root)}`);
210
+ return direct;
211
+ }
212
+ const legacy = graphDbPath(root);
213
+ if (existsSync(legacy) && describeIndex(legacy).environmentName === wanted)
214
+ return legacy;
215
+ throw new GraphIndexAbsentError(`没有环境「${wanted}」的本地索引(${direct});先 omc graph pull --env ${wanted}。${availableIndexesHint(root)}`);
216
+ }
217
+ const legacy = graphDbPath(root);
218
+ const others = listGraphIndexes(root).filter((entry) => !entry.legacySlot);
219
+ if (others.length === 0) {
220
+ if (existsSync(legacy))
221
+ return legacy;
222
+ throw new GraphIndexAbsentError(`没有本地规则图索引(${join(graphRoot(root), ".omc", "graph")});先运行 omc graph pull --env <env> 全量重建`);
223
+ }
224
+ if (others.length === 1)
225
+ return others[0].dbPath;
226
+ const legacyNote = existsSync(legacy) ? `\n另有 legacy graph.db(env=${describeIndex(legacy).environmentName || "不可读"})` : "";
227
+ throw new GraphIndexAmbiguousError(`这个配置根下有 ${others.length} 份索引,必须用 --env 指定查哪一份。${availableIndexesHint(root)}${legacyNote}\n只读清点:omc graph indexes`);
228
+ }
229
+ /** Several indexes live under this root and the caller did not say which. */
230
+ export class GraphIndexAmbiguousError extends GraphIndexError {
231
+ constructor(message) {
232
+ super(message);
233
+ this.name = "GraphIndexAmbiguousError";
234
+ }
82
235
  }
83
236
  /**
84
237
  * Extract api-fact reference edges from one rule's stored node graph. The
@@ -181,7 +334,7 @@ export function extractListViewEdges(schemaCode, viewCode, model) {
181
334
  * `datarule-list`) and vice versa (`rule-list`). Output is sorted so the
182
335
  * published DB is byte-stable regardless of completion order.
183
336
  */
184
- export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRENCY, requestedApplication) {
337
+ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRENCY, requestedApplication, root) {
185
338
  const identity = session.environmentFingerprint();
186
339
  const pulledAtIso = new Date().toISOString();
187
340
  const totalStart = Date.now();
@@ -417,6 +570,10 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
417
570
  identityFingerprint: identity,
418
571
  environmentName: session.environmentName,
419
572
  applicationCode,
573
+ // Point 3: record WHICH project this index belongs to. Env is a platform
574
+ // identity shared by every project that pulls it; without this row two
575
+ // projects' indexes are indistinguishable on the receipt.
576
+ projectPath: graphRoot(root),
420
577
  coverage: { applicationCodes: [applicationCode] },
421
578
  ...(scope !== undefined ? { applicationResolution: applicationResolutionOf(scope) } : {}),
422
579
  pulledAtIso,
@@ -443,8 +600,8 @@ function parseApplicationResolution(raw) {
443
600
  return undefined;
444
601
  }
445
602
  }
446
- function ensureGraphDir() {
447
- const dir = dirname(graphDbPath());
603
+ function ensureGraphDir(dbPath) {
604
+ const dir = dirname(dbPath);
448
605
  mkdirSync(dir, { recursive: true, mode: 0o700 });
449
606
  return dir;
450
607
  }
@@ -453,9 +610,11 @@ function ensureGraphDir() {
453
610
  * considered abandoned and taken over. This is a LOCAL index lock — pull never
454
611
  * writes the environment, so it must not touch the environment write lock.
455
612
  */
456
- async function withGraphPullLock(run) {
457
- ensureGraphDir();
458
- const lockPath = `${graphDbPath()}.lock`;
613
+ async function withGraphPullLock(dbPath, run) {
614
+ ensureGraphDir(dbPath);
615
+ // The lock is PER INDEX FILE: pulling `test` must not block pulling `prod`
616
+ // into the same project (they write different files).
617
+ const lockPath = `${dbPath}.lock`;
459
618
  const owner = `${process.pid} ${new Date().toISOString()}`;
460
619
  let fd;
461
620
  try {
@@ -503,10 +662,13 @@ async function withGraphPullLock(run) {
503
662
  }
504
663
  /** Wholesalerebuild + atomic publish (staging file + rename), 0600. */
505
664
  export async function publishGraphPull(session, concurrency = DEFAULT_PULL_CONCURRENCY, options = {}) {
665
+ // The environment decides the file: one project can index `test` and `prod`
666
+ // side by side, so the target is not known until the session resolves.
667
+ const dbPath = graphDbPath(options.root, session.environmentName);
506
668
  try {
507
- return await withGraphPullLock(async () => {
669
+ return await withGraphPullLock(dbPath, async () => {
508
670
  const requested = options.applicationCodes?.length ? options.applicationCodes : [undefined];
509
- const parts = await Promise.all(requested.map((application) => pullRuleGraph(session, concurrency, application)));
671
+ const parts = await Promise.all(requested.map((application) => pullRuleGraph(session, concurrency, application, options.root)));
510
672
  const first = parts[0];
511
673
  const data = parts.length === 1 ? first : {
512
674
  ...first,
@@ -520,7 +682,7 @@ export async function publishGraphPull(session, concurrency = DEFAULT_PULL_CONCU
520
682
  scanned: parts.reduce((sum, part) => ({ models: sum.models + part.scanned.models, rules: sum.rules + part.scanned.rules, datarules: sum.datarules + part.scanned.datarules, views: sum.views + part.scanned.views, parseFailures: sum.parseFailures + part.scanned.parseFailures }), { models: 0, rules: 0, datarules: 0, views: 0, parseFailures: 0 }),
521
683
  timings: { listMs: parts.reduce((n, part) => n + part.timings.listMs, 0), readMs: parts.reduce((n, part) => n + part.timings.readMs, 0), totalMs: parts.reduce((n, part) => n + part.timings.totalMs, 0) },
522
684
  };
523
- const staging = `${graphDbPath()}.staging-${process.pid}`;
685
+ const staging = `${dbPath}.staging-${process.pid}`;
524
686
  rmSync(staging, { force: true });
525
687
  const DatabaseSyncCtor = nodeSqlite().DatabaseSync;
526
688
  const db = new DatabaseSyncCtor(staging);
@@ -597,20 +759,31 @@ export async function publishGraphPull(session, concurrency = DEFAULT_PULL_CONCU
597
759
  }
598
760
  chmodSync(staging, 0o600);
599
761
  const dbBytes = statSync(staging).size;
600
- renameSync(staging, graphDbPath());
762
+ renameSync(staging, dbPath);
763
+ // Upgrade path: a legacy `graph.db` holding the SAME environment is now
764
+ // superseded by `<env>.db`. Leaving it behind would make a no-`--env` read
765
+ // ambiguous (two files, one environment). Best effort, never fatal.
766
+ const legacy = graphDbPath();
767
+ if (legacy !== dbPath) {
768
+ try {
769
+ if (existsSync(legacy) && describeIndex(legacy).environmentName === data.meta.environmentName)
770
+ unlinkSync(legacy);
771
+ }
772
+ catch { /* keep both rather than fail a successful pull */ }
773
+ }
601
774
  return { ...data, dbBytes };
602
775
  });
603
776
  }
604
777
  catch (error) {
605
778
  // A failed build must not leave staging garbage next to the index.
606
- rmSync(`${graphDbPath()}.staging-${process.pid}`, { force: true });
779
+ rmSync(`${dbPath}.staging-${process.pid}`, { force: true });
607
780
  throw error;
608
781
  }
609
782
  }
610
- function openGraphIndex() {
611
- const dbPath = graphDbPath();
783
+ function openGraphIndex(selector = {}) {
784
+ const dbPath = resolveGraphDbPath(selector.root, selector.env);
612
785
  if (!existsSync(dbPath))
613
- throw new GraphIndexAbsentError("没有本地规则图索引(<配置根>/.omc/graph/graph.db);先运行 omc graph pull --env <env> 全量重建");
786
+ throw new GraphIndexAbsentError(`没有本地规则图索引(${dbPath});先运行 omc graph pull --env <env> 全量重建`);
614
787
  let db;
615
788
  try {
616
789
  const DatabaseSyncCtor = nodeSqlite().DatabaseSync;
@@ -619,7 +792,12 @@ function openGraphIndex() {
619
792
  for (const row of db.prepare("SELECT key, value FROM meta").all())
620
793
  meta[row.key] = row.value;
621
794
  if (meta.schemaVersion !== GRAPH_SCHEMA_VERSION)
622
- throw new GraphIndexAbsentError(`索引 schema 版本不匹配(${meta.schemaVersion ?? "unknown"} ≠ ${GRAPH_SCHEMA_VERSION});当前版本需要 schema ${GRAPH_SCHEMA_VERSION},旧版索引已作废,请重跑 omc graph pull(schema 升版需重拉)`);
795
+ throw new GraphIndexUnreadableError(`索引 schema 版本不匹配(${meta.schemaVersion ?? "unknown"} ≠ ${GRAPH_SCHEMA_VERSION});当前版本需要 schema ${GRAPH_SCHEMA_VERSION},旧版索引已作废,请重跑 omc graph pull(schema 升版需重拉)`);
796
+ // An env-named file that says a different environment is a stale/renamed
797
+ // fixture, not an answer. Refuse rather than silently cross environments.
798
+ const wanted = selector.env?.trim();
799
+ if (wanted && meta.environmentName && meta.environmentName !== wanted)
800
+ throw new GraphIndexAbsentError(`索引文件 ${dbPath} 记录的来源环境是「${meta.environmentName}」,不是「${wanted}」;重跑 omc graph pull --env ${wanted}。${availableIndexesHint(selector.root)}`);
623
801
  const ruleCount = db.prepare("SELECT COUNT(*) AS n FROM rules").get().n;
624
802
  const modelCount = db.prepare("SELECT COUNT(DISTINCT schema_code) AS n FROM rules").get().n;
625
803
  const entityCounts = {
@@ -664,8 +842,14 @@ function openGraphIndex() {
664
842
  const coverage = { applicationCodes, ...(tenantApplications ? { tenantApplications } : {}), fields: { coveredApplications: fieldApplications, notCovered: applicationCodes.filter((code) => !fieldApplications.includes(code)), countsByApplication } };
665
843
  return {
666
844
  db,
845
+ dbPath,
667
846
  summary: {
668
847
  environmentName: meta.environmentName ?? "",
848
+ // Point 3: the answer carries its own provenance. A pre-0.6.x index
849
+ // has no projectPath row — derive it from the DB location instead of
850
+ // claiming "unknown", and never require a re-pull for this.
851
+ projectPath: meta.projectPath ?? dirname(dirname(dirname(dbPath))),
852
+ dbId: sha256(dbPath).slice(0, 12),
669
853
  applicationCode: meta.applicationCode ?? "",
670
854
  coverage,
671
855
  // Persisted as JSON by the writer; a legacy index (pre-0.5.4) has no
@@ -692,7 +876,7 @@ function openGraphIndex() {
692
876
  }
693
877
  catch (error) {
694
878
  db?.close();
695
- throw error instanceof GraphIndexAbsentError ? error : new GraphIndexAbsentError(`索引不可读(schema 不匹配或文件损坏):${error instanceof Error ? error.message : String(error)};重跑 omc graph pull`);
879
+ throw error instanceof GraphIndexError ? error : new GraphIndexUnreadableError(`索引不可读(schema 不匹配或文件损坏):${error instanceof Error ? error.message : String(error)};重跑 omc graph pull`);
696
880
  }
697
881
  }
698
882
  /**
@@ -729,12 +913,41 @@ function zeroHitKindHint(db, kind, code, command) {
729
913
  return undefined;
730
914
  return `;注意:${code} 在索引中以 ${kinds.join("/")} 身份出现——kind 可能选错,试 omc graph ${command} ${kinds[0]} ${code}`;
731
915
  }
732
- export function queryGraphReferences(kind, code) {
733
- const { db, summary } = openGraphIndex();
916
+ /**
917
+ * `schemaCode.code` 形式的精确定位(2026-11-12 r58 真机)。
918
+ *
919
+ * 探针按我们新写的「改/删前先查影响面」用 `graph references field
920
+ * crm_contract.contract_no` → **静默 matches: []**(不报错、不提示形状不对),
921
+ * 而裸 `contract_no` 会**把别的模型的同名字段合并进来**(crm_expiry_scan_log /
922
+ * mcc_sync_log 各有自己的 contract_no)。一个漏报一个过报,没有可用写法。
923
+ *
924
+ * 为什么能精确:datarule.targets 与 listview.columns 只能引用**本模型**字段,
925
+ * 所以 `edges.schema_code`(引用者所在模型)就是被引用字段的宿主模型。
926
+ */
927
+ function splitScopedCode(code) {
928
+ const dot = code.indexOf(".");
929
+ if (dot <= 0 || dot === code.length - 1)
930
+ return null;
931
+ const schemaCode = code.slice(0, dot);
932
+ const bare = code.slice(dot + 1);
933
+ if (bare.includes("."))
934
+ return null; // 只认一层 a.b
935
+ return { schemaCode, code: bare };
936
+ }
937
+ export function queryGraphReferences(kind, rawCode, selector = {}) {
938
+ const { db, summary } = openGraphIndex(selector);
734
939
  try {
735
- const rows = db
736
- .prepare("SELECT schema_code, rule_code, node_code, node_type, via, application_code FROM edges WHERE kind = ? AND code = ? ORDER BY schema_code, rule_code, node_code, via")
737
- .all(kind, code);
940
+ // 字段可带宿主模型限定(`crm_contract.contract_no`):只认字段面——
941
+ // model/service 的 code 本身含点会歧义,那里保持原样查询。
942
+ const scoped = kind === "field" ? splitScopedCode(rawCode) : null;
943
+ const code = scoped?.code ?? rawCode;
944
+ const rows = (scoped === null
945
+ ? db
946
+ .prepare("SELECT schema_code, rule_code, node_code, node_type, via, application_code FROM edges WHERE kind = ? AND code = ? ORDER BY schema_code, rule_code, node_code, via")
947
+ .all(kind, code)
948
+ : db
949
+ .prepare("SELECT schema_code, rule_code, node_code, node_type, via, application_code FROM edges WHERE kind = ? AND code = ? AND schema_code = ? ORDER BY schema_code, rule_code, node_code, via")
950
+ .all(kind, code, scoped.schemaCode));
738
951
  const matches = rows.map((row) => ({
739
952
  schemaCode: row.schema_code,
740
953
  ruleCode: row.rule_code,
@@ -751,10 +964,18 @@ export function queryGraphReferences(kind, code) {
751
964
  // 明说表单与流程权限表不在扫描范围。散文字段不承担安全契约:这里给结构化
752
965
  // coverage,让「没人引用」与「这一面没扫」在机器可读层面可分。
753
966
  const coverage = GRAPH_COVERAGE;
967
+ // 裸字段 code 会跨模型合并同名(r58 真机:contract_no 在三个模型里各有一个,
968
+ // 裸查把别人的引用也算进来)。零命中或命中含其它模型时,明确说清并给精确写法。
969
+ const otherSchemas = [...new Set(matches.map((match) => match.schemaCode))].filter((schema) => schema !== code);
970
+ const unscopedFieldNote = kind === "field" && scoped === null && otherSchemas.length > 0
971
+ ? `裸字段 code 会跨模型合并同名:本次命中来自 ${otherSchemas.join("、")}(各自的同名字段)。要只查某一个模型的该字段,写 <schemaCode>.<字段code>(如 crm_contract.${code})——datarule/listview 只能引用本模型字段,所以按宿主模型过滤是精确的。`
972
+ : undefined;
754
973
  return {
755
974
  kind,
756
- code,
975
+ code: rawCode,
976
+ ...(scoped !== null ? { resolvedScope: { schemaCode: scoped.schemaCode, code: scoped.code } } : {}),
757
977
  matches,
978
+ ...(unscopedFieldNote !== undefined ? { scopeNote: unscopedFieldNote } : {}),
758
979
  coverage,
759
980
  index: summary,
760
981
  ...(matches.length === 0
@@ -774,8 +995,8 @@ export function queryGraphReferences(kind, code) {
774
995
  db.close();
775
996
  }
776
997
  }
777
- export function queryGraphReferencesBatch(kind, codes) {
778
- const { db, summary } = openGraphIndex();
998
+ export function queryGraphReferencesBatch(kind, codes, selector = {}) {
999
+ const { db, summary } = openGraphIndex(selector);
779
1000
  try {
780
1001
  const wanted = [...new Set(codes.filter(Boolean))];
781
1002
  const rows = wanted.length === 0 ? [] : db.prepare(`SELECT code, schema_code, rule_code, node_code, node_type, via FROM edges WHERE kind = ? AND code IN (${wanted.map(() => "?").join(",")}) ORDER BY code, schema_code, rule_code, node_code, via`).all(kind, ...wanted);
@@ -785,8 +1006,8 @@ export function queryGraphReferencesBatch(kind, codes) {
785
1006
  db.close();
786
1007
  }
787
1008
  }
788
- export function queryGraphEdges(fromSchema, toSchema, kind, offset = 0, limit = 50) {
789
- const { db, summary } = openGraphIndex();
1009
+ export function queryGraphEdges(fromSchema, toSchema, kind, offset = 0, limit = 50, selector = {}) {
1010
+ const { db, summary } = openGraphIndex(selector);
790
1011
  try {
791
1012
  const conditions = [];
792
1013
  const params = [];
@@ -812,20 +1033,25 @@ export function queryGraphEdges(fromSchema, toSchema, kind, offset = 0, limit =
812
1033
  db.close();
813
1034
  }
814
1035
  }
815
- export function readGraphStatus() {
816
- const { db, summary } = openGraphIndex();
1036
+ export function readGraphStatus(selector = {}) {
1037
+ const { db, dbPath, summary } = openGraphIndex(selector);
817
1038
  try {
818
1039
  const gaps = db.prepare("SELECT kind, ref, note FROM gaps ORDER BY kind, ref LIMIT 50").all();
819
- const dbPath = graphDbPath();
1040
+ const projectRoot = summary.projectPath || dirname(dirname(dirname(dbPath)));
1041
+ const otherIndexes = listGraphIndexes(selector.root).filter((entry) => entry.dbPath !== dbPath);
820
1042
  return {
821
1043
  index: summary,
822
1044
  dbBytes: statSync(dbPath).size,
823
1045
  dbPath,
824
1046
  dbId: sha256(dbPath).slice(0, 12),
825
- mcpHint: `MCP 工具按注册时的 --path 读库(当前索引根:${dirname(dirname(dbPath))});要让 MCP 看到本次拉取,请执行 omc graph pull --path ${dirname(dirname(dbPath))} --env <env>。`,
1047
+ mcpHint: `MCP 用 --path 指向项目根、用 env 参数选索引(本项目根:${projectRoot};当前 env=${summary.environmentName || "?"})。要让 MCP 看到本次拉取,执行 omc graph pull --path ${projectRoot} --env ${summary.environmentName || "<env>"}。`,
826
1048
  ageMinutes: summary.ageMinutes,
827
1049
  staleAfterMinutes: summary.staleAfterMinutes,
828
1050
  ...(summary.staleWarning ? { warning: summary.staleWarning } : {}),
1051
+ // One project, several environments: status must say what ELSE is
1052
+ // queryable here, otherwise the caller cannot discover the sibling index
1053
+ // without guessing a file name.
1054
+ ...(otherIndexes.length > 0 ? { otherIndexes: otherIndexes.map((entry) => ({ environmentName: entry.environmentName, dbId: entry.dbId, pulledAtIso: entry.pulledAtIso, ageMinutes: entry.ageMinutes, rules: entry.rules, models: entry.models })) } : {}),
829
1055
  coverage: summary.coverage,
830
1056
  coveredApplications: summary.coverage.applicationCodes,
831
1057
  tenantApplications: summary.coverage.tenantApplications ?? summary.coverage.applicationCodes,
@@ -843,8 +1069,8 @@ export function readGraphStatus() {
843
1069
  * a prefix match (`引用*`), which is also what makes CJK usable: unicode61
844
1070
  * stores a CJK run as one token, so a full-run query hits only by prefix.
845
1071
  */
846
- export function searchGraphRules(term, limit = 20, offset = 0) {
847
- const { db, summary } = openGraphIndex();
1072
+ export function searchGraphRules(term, limit = 20, offset = 0, selector = {}) {
1073
+ const { db, summary } = openGraphIndex(selector);
848
1074
  try {
849
1075
  const tokens = term.trim().split(/\s+/).filter((token) => token !== "");
850
1076
  let matches = [];
@@ -923,8 +1149,8 @@ export function searchGraphRules(term, limit = 20, offset = 0) {
923
1149
  * read/write these codes — verify those too." Bounded: 50 rules, 20 codes per
924
1150
  * kind; the same fail-closed gap semantics as references apply.
925
1151
  */
926
- export function impactGraph(kind, code) {
927
- const { db, summary } = openGraphIndex();
1152
+ export function impactGraph(kind, code, selector = {}) {
1153
+ const { db, summary } = openGraphIndex(selector);
928
1154
  try {
929
1155
  const hop1 = db
930
1156
  .prepare("SELECT DISTINCT schema_code, rule_code FROM edges WHERE kind = ? AND code = ? AND node_type NOT IN ('datarule', 'listview') ORDER BY schema_code, rule_code LIMIT 51")
package/dist/lanes/app.js CHANGED
@@ -53,6 +53,7 @@ function isFallbackGroup(group) {
53
53
  export function registerAppLane(tools) {
54
54
  tools.push(defineTool({
55
55
  name: "app.list",
56
+ search: { intents: ["有哪些应用", "应用清单", "列出应用", "看看有哪些应用包", "应用列表"] },
56
57
  layer: "low",
57
58
  kind: "read",
58
59
  lane: APP_LANE,
@@ -90,6 +91,7 @@ export function registerAppLane(tools) {
90
91
  writeTool({
91
92
  tools,
92
93
  name: "app.create",
94
+ search: { intents: ["新建应用", "创建一个应用", "建应用包", "加一个应用"] },
93
95
  lane: APP_LANE,
94
96
  scope: APP_TOOLS["app.create"].scope,
95
97
  description: APP_TOOLS["app.create"].description,
@@ -201,6 +203,7 @@ export function registerAppLane(tools) {
201
203
  writeTool({
202
204
  tools,
203
205
  name: "app.update",
206
+ search: { intents: ["改应用", "给应用改名", "重命名应用", "更新应用配置"] },
204
207
  lane: APP_LANE,
205
208
  scope: APP_TOOLS["app.update"].scope,
206
209
  description: APP_TOOLS["app.update"].description,
@@ -250,6 +253,7 @@ export function registerAppLane(tools) {
250
253
  writeTool({
251
254
  tools,
252
255
  name: "app.delete",
256
+ search: { intents: ["删除应用", "删掉这个应用", "删应用包"] },
253
257
  lane: APP_LANE,
254
258
  scope: APP_TOOLS["app.delete"].scope,
255
259
  description: APP_TOOLS["app.delete"].description,
@@ -36,6 +36,7 @@ export function registerApplyChangesLane(tools) {
36
36
  const siblings = tools;
37
37
  tools.push(defineTool({
38
38
  name: "apply_changes",
39
+ search: { intents: ["批量执行", "批量应用"] },
39
40
  layer: "high",
40
41
  kind: "write",
41
42
  // r28k F7:选用时机写进 describe 首句——一次审批 N 个有序变更;单条调试用 omc call。