@stalfh233/omc-cli 0.6.47 → 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 +251 -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 +28 -2
  8. package/dist/graph.js +223 -34
  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 +5 -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
  {
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
  /**
@@ -750,8 +934,8 @@ function splitScopedCode(code) {
750
934
  return null; // 只认一层 a.b
751
935
  return { schemaCode, code: bare };
752
936
  }
753
- export function queryGraphReferences(kind, rawCode) {
754
- const { db, summary } = openGraphIndex();
937
+ export function queryGraphReferences(kind, rawCode, selector = {}) {
938
+ const { db, summary } = openGraphIndex(selector);
755
939
  try {
756
940
  // 字段可带宿主模型限定(`crm_contract.contract_no`):只认字段面——
757
941
  // model/service 的 code 本身含点会歧义,那里保持原样查询。
@@ -811,8 +995,8 @@ export function queryGraphReferences(kind, rawCode) {
811
995
  db.close();
812
996
  }
813
997
  }
814
- export function queryGraphReferencesBatch(kind, codes) {
815
- const { db, summary } = openGraphIndex();
998
+ export function queryGraphReferencesBatch(kind, codes, selector = {}) {
999
+ const { db, summary } = openGraphIndex(selector);
816
1000
  try {
817
1001
  const wanted = [...new Set(codes.filter(Boolean))];
818
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);
@@ -822,8 +1006,8 @@ export function queryGraphReferencesBatch(kind, codes) {
822
1006
  db.close();
823
1007
  }
824
1008
  }
825
- export function queryGraphEdges(fromSchema, toSchema, kind, offset = 0, limit = 50) {
826
- const { db, summary } = openGraphIndex();
1009
+ export function queryGraphEdges(fromSchema, toSchema, kind, offset = 0, limit = 50, selector = {}) {
1010
+ const { db, summary } = openGraphIndex(selector);
827
1011
  try {
828
1012
  const conditions = [];
829
1013
  const params = [];
@@ -849,20 +1033,25 @@ export function queryGraphEdges(fromSchema, toSchema, kind, offset = 0, limit =
849
1033
  db.close();
850
1034
  }
851
1035
  }
852
- export function readGraphStatus() {
853
- const { db, summary } = openGraphIndex();
1036
+ export function readGraphStatus(selector = {}) {
1037
+ const { db, dbPath, summary } = openGraphIndex(selector);
854
1038
  try {
855
1039
  const gaps = db.prepare("SELECT kind, ref, note FROM gaps ORDER BY kind, ref LIMIT 50").all();
856
- const dbPath = graphDbPath();
1040
+ const projectRoot = summary.projectPath || dirname(dirname(dirname(dbPath)));
1041
+ const otherIndexes = listGraphIndexes(selector.root).filter((entry) => entry.dbPath !== dbPath);
857
1042
  return {
858
1043
  index: summary,
859
1044
  dbBytes: statSync(dbPath).size,
860
1045
  dbPath,
861
1046
  dbId: sha256(dbPath).slice(0, 12),
862
- 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>"}。`,
863
1048
  ageMinutes: summary.ageMinutes,
864
1049
  staleAfterMinutes: summary.staleAfterMinutes,
865
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 })) } : {}),
866
1055
  coverage: summary.coverage,
867
1056
  coveredApplications: summary.coverage.applicationCodes,
868
1057
  tenantApplications: summary.coverage.tenantApplications ?? summary.coverage.applicationCodes,
@@ -880,8 +1069,8 @@ export function readGraphStatus() {
880
1069
  * a prefix match (`引用*`), which is also what makes CJK usable: unicode61
881
1070
  * stores a CJK run as one token, so a full-run query hits only by prefix.
882
1071
  */
883
- export function searchGraphRules(term, limit = 20, offset = 0) {
884
- const { db, summary } = openGraphIndex();
1072
+ export function searchGraphRules(term, limit = 20, offset = 0, selector = {}) {
1073
+ const { db, summary } = openGraphIndex(selector);
885
1074
  try {
886
1075
  const tokens = term.trim().split(/\s+/).filter((token) => token !== "");
887
1076
  let matches = [];
@@ -960,8 +1149,8 @@ export function searchGraphRules(term, limit = 20, offset = 0) {
960
1149
  * read/write these codes — verify those too." Bounded: 50 rules, 20 codes per
961
1150
  * kind; the same fail-closed gap semantics as references apply.
962
1151
  */
963
- export function impactGraph(kind, code) {
964
- const { db, summary } = openGraphIndex();
1152
+ export function impactGraph(kind, code, selector = {}) {
1153
+ const { db, summary } = openGraphIndex(selector);
965
1154
  try {
966
1155
  const hop1 = db
967
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。