@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
package/dist/cli.js CHANGED
@@ -26,6 +26,7 @@ import { artifactFetchHint, artifactRoot, boundResult, emitInvalid, emitResult,
26
26
  import { CLI_DEFAULT_OUTPUT_BYTES, assertSafeOutputPath, pruneArtifacts } from "./artifacts.js";
27
27
  import { artifactPathMissHint, nullProjectionHint, partialPathMissHint, projectJsonPath, projectJsonPathFanout, projectResultExtract } from "./path-projection.js";
28
28
  import { basename, join, resolve } from "node:path";
29
+ import { writeFileSync } from "node:fs";
29
30
  import { buildToolRegistry } from "./tools.js";
30
31
  import { acquireWriteLock, writeLockHeldFace } from "./write-lock.js";
31
32
  import { cmdCompute } from "./compute.js";
@@ -43,20 +44,22 @@ if (process.argv.includes("--utf8"))
43
44
  else if (process.env.OMC_ASCII_STDOUT !== "0" && process.argv.some((arg) => arg === "--help" || arg === "help")) {
44
45
  process.env.OMC_UTF8_HINT = "1";
45
46
  }
46
- import { commandIndex, commandInventory, describeContract, describeContractFull, describeContractTool, describeExample, describeParam, describeSchemaOnly, describeTool, describeToolFull, filterTools } from "./discovery.js";
47
+ import { SEARCH_MARGIN_THRESHOLD } from "./tool-search.js";
48
+ import { commandCapabilitySlice, commandIndex, commandInventory, describeContract, describeContractFull, describeContractTool, describeExample, describeParam, describeSchemaOnly, describeTool, describeToolFull, filterTools } from "./discovery.js";
47
49
  import { closestMatches } from "./closest-match.js";
48
50
  import { KEY_ALIAS_HINTS, inputAliasSynonymKeys } from "./tool-types.js";
49
51
  import { repeatFullDescribe } from "./describe-cache.js";
50
- import { buildCapabilityOverview, capabilityDetail, capabilityRouteIndex, compactCapabilities, executableCapabilityBundle, resolveCapabilityId, DISCOVERY_AUTHORITY } from "./capability-overview.js";
52
+ import { buildCapabilityOverview, capabilityCandidatesFor, capabilityDetail, capabilityRouteIndex, compactCapabilities, executableCapabilityBundle, resolveCapabilityId, DISCOVERY_AUTHORITY } from "./capability-overview.js";
51
53
  import { goalRoute } from "./goal-routes.js";
52
54
  import { absencePointer } from "./capability-absences.js";
53
55
  import { intentConfigRoot, readIntentFile, validateIntentText } from "./intent/cli.js";
56
+ import { planGoal, planToNdjson, planToNdjsonSkipped } from "./goal-plan.js";
54
57
  import { intentSchemaBlock, intentExample, intentExampleIds } from "./intent/schema.js";
55
58
  import { planIntent, readbackIntent, applyIntent, intentWarnings } from "./intent/plan-apply.js";
56
59
  import { listSkills, readSkill, readSkillOutline, readSkillSection, searchSkills, suggestHelpTopics } from "./skills.js";
57
60
  import { parseToolInput, ToolInputError } from "./tool-types.js";
58
61
  import { WireError, wireCall } from "./wire.js";
59
- import { DEFAULT_PULL_CONCURRENCY, GraphIndexAbsentError, GraphPullLockHeldError, MAX_PULL_CONCURRENCY, impactGraph, publishGraphPull, queryGraphReferences, queryGraphReferencesBatch, queryGraphEdges, readGraphStatus, searchGraphRules, } from "./graph.js";
62
+ import { DEFAULT_PULL_CONCURRENCY, GraphIndexAmbiguousError, GraphIndexError, GraphIndexUnreadableError, GraphPullLockHeldError, MAX_PULL_CONCURRENCY, graphDbPath, graphRoot, impactGraph, listGraphIndexes, publishGraphPull, queryGraphReferences, queryGraphReferencesBatch, queryGraphEdges, readGraphStatus, searchGraphRules, } from "./graph.js";
60
63
  import { cmdResidue } from "./residue.js";
61
64
  import { cmdTrack } from "./track.js";
62
65
  import { ENDPOINTS } from "./endpoints.js";
@@ -1275,12 +1278,26 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1275
1278
  return emitTransportResult({ status: "ok", ...intentSchemaBlock() }, transport);
1276
1279
  }
1277
1280
  if (kind === "commands") {
1281
+ // r59 M2-1: one capability family as a bounded tool index. Resolved before
1282
+ // the scoped check so `--capability` never falls through to the full
1283
+ // catalogue; `--capability` and `--lane/--filter` are mutually exclusive.
1284
+ if (options.capability !== undefined) {
1285
+ if (options.filter !== undefined || options.lane !== undefined) {
1286
+ return emitInvalid(transport, { message: "--capability 与 --filter/--lane 互斥:先按能力取工具名,再用 --filter 在结果里找,或直接 --capability <id>" });
1287
+ }
1288
+ const slice = commandCapabilitySlice(registry, options.capability);
1289
+ if (!slice) {
1290
+ const available = capabilityRouteIndex(registry).routes.map((route) => route.id).join("、");
1291
+ return emitInvalid(transport, { message: `未知 capability "${options.capability}";合法取值:${available}(清单见 omc capabilities)` });
1292
+ }
1293
+ return emitProjectedResult({ status: "ok", ...slice }, transport, options.jq);
1294
+ }
1278
1295
  const scoped = options.filter !== undefined || options.lane !== undefined;
1279
1296
  // Bare `commands` is the bounded index (see commandIndex): the full 54 KB
1280
1297
  // catalogue must be requested with `commands --json` (round-9 heavy-task: an
1281
1298
  // agent paid 4×54 KB on the default face before any hint could land).
1282
1299
  if (options.json !== true && options.compact !== true && !scoped) {
1283
- result = commandIndex(registry);
1300
+ result = commandIndex(registry, { legacy: legacyDiscovery() });
1284
1301
  return emitProjectedResult({ status: "ok", ...result }, transport, options.jq);
1285
1302
  }
1286
1303
  const inventory = commandInventory(registry, { compact: options.compact === true });
@@ -1303,7 +1320,11 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1303
1320
  // r19 ticket 05: semantic filter — capability language(聚合/字典/业务集成)
1304
1321
  // must locate tools, not dead-end on a name-substring miss.
1305
1322
  const semantic = options.filter !== undefined ? filterTools(registry, options.filter) : undefined;
1306
- const semanticByName = semantic ? new Map(semantic.map((hit) => [hit.name, hit.via])) : undefined;
1323
+ // r59 v3: keep the multi-signal score. It used to be dropped here
1324
+ // (`hit.via` only), so grouping fell back to tool COUNT and 「报表」
1325
+ // listed app.delete first.
1326
+ const semanticByName = semantic ? new Map(semantic.map((hit) => [hit.name, hit])) : undefined;
1327
+ const scoreOf = (name) => semanticByName?.get(name)?.score ?? Number.NEGATIVE_INFINITY;
1307
1328
  const matched = tools.filter((tool) => {
1308
1329
  if (options.lane !== undefined && tool.lane !== options.lane)
1309
1330
  return false;
@@ -1311,11 +1332,26 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1311
1332
  return true;
1312
1333
  return semanticByName.has(String(tool.name));
1313
1334
  });
1335
+ // Rows follow match quality (score desc, then name), so the first row is
1336
+ // the best answer, not registry order. Only when a FILTER supplied scores
1337
+ // — `--lane` alone keeps registry order (the golden master pins that shape).
1338
+ if (semanticByName !== undefined) {
1339
+ matched.sort((left, right) => scoreOf(String(right.name)) - scoreOf(String(left.name)) || String(left.name).localeCompare(String(right.name)));
1340
+ }
1314
1341
  inventory.filtered = { filter: options.filter ?? null, lane: options.lane ?? null, matched: matched.length, total: tools.length };
1342
+ // r59 v3 (margin): when the head of the ranking is a near-tie, say so —
1343
+ // the caller should weigh top options (or ask) instead of trusting top1.
1344
+ // 评审 P1-1:margin/top 必须基于 **lane 过滤后** 的排名——`--filter 加字段 --lane b2`
1345
+ // 时全局 top1/2 都在别的 lane,拿全局算会把单结果误标 ambiguous、把别的 lane
1346
+ // 的工具列进 top。
1347
+ const scoped = semantic === undefined ? [] : semantic.filter((hit) => matched.some((tool) => String(tool.name) === hit.name));
1348
+ if (scoped.length >= 2 && scoped[0].score - scoped[1].score < SEARCH_MARGIN_THRESHOLD) {
1349
+ inventory.filtered.ambiguous = true;
1350
+ }
1315
1351
  inventory.tools = matched;
1316
1352
  if (semanticByName !== undefined)
1317
1353
  for (const tool of inventory.tools)
1318
- tool.matchedVia = semanticByName.get(String(tool.name));
1354
+ tool.matchedVia = semanticByName.get(String(tool.name))?.via;
1319
1355
  // A filtered query wants tool rows, not the whole catalogue's discovery,
1320
1356
  // skills, and intent prose. Keep only the authoritative route pointer.
1321
1357
  delete inventory.skills;
@@ -1328,8 +1364,11 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1328
1364
  // match plus governance prose pushed the agent back to the 20 KB face).
1329
1365
  if (matched.length === 0 && semantic !== undefined) {
1330
1366
  delete inventory.governance;
1331
- inventory.filtered.candidates = closestMatches(options.filter ?? "", registry.map((tool) => tool.name), 3).map((candidate) => ({ ...candidate, next: `omc describe ${candidate.name}` }));
1332
- inventory.note = "零命中:换能力词再试(如 聚合/子表/字典/报表/业务集成/定时任务),或用 omc next \"<目标>\" 按任务路由;全量目录仍走 commands --json";
1367
+ // r59 Step 1: candidates are CAPABILITIES, not tool names. The old
1368
+ // closest match over tool names answered an unmet business ask with
1369
+ // app.create/app.delete/app.list — names that share no intent with it.
1370
+ inventory.filtered.candidates = capabilityCandidatesFor(registry, options.filter ?? "", 3);
1371
+ inventory.note = "零命中:没有能力短语匹配这个问法;候选是能力(不是工具名),先按 id 展开该能力的工具,或换能力词(如 聚合/子表/字典/报表/业务集成/定时任务),或 omc next \"<目标>\" 按任务路由;全量目录仍走 commands --json";
1333
1372
  }
1334
1373
  else if (matched.length > BROAD_FILTER_TOOL_THRESHOLD && !isCapabilityIdQuery(registry, options.filter ?? "")) {
1335
1374
  // A broad word("数据" 39 hits / 8 KB)is half a catalogue: keep every
@@ -1341,15 +1380,25 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1341
1380
  const groups = new Map();
1342
1381
  for (const tool of matched) {
1343
1382
  const key = String(tool.capability ?? tool.lane ?? "other");
1344
- const entry = groups.get(key) ?? { capability: key, lane: tool.lane ?? null, tools: [] };
1383
+ // `matched` is already score-ordered, so a group's tool list inherits it.
1384
+ const entry = groups.get(key) ?? { capability: key, lane: tool.lane ?? null, tools: [], score: Number.NEGATIVE_INFINITY };
1385
+ entry.score = Math.max(entry.score, scoreOf(String(tool.name)));
1345
1386
  entry.tools.push(String(tool.name));
1346
1387
  groups.set(key, entry);
1347
1388
  }
1348
1389
  inventory.filtered.matchedAll = matched.length;
1349
1390
  inventory.filtered.grouped = true;
1391
+ // r59 v3: grouped mode hides rows, so name the head of the ranking —
1392
+ // an intent query like 「配审批流」 still gets its best tools up front.
1393
+ inventory.filtered.top = scoped.slice(0, 3).map((hit) => hit.name);
1350
1394
  inventory.tools = [];
1351
- inventory.groups = [...groups.values()].sort((left, right) => right.tools.length - left.tools.length);
1352
- inventory.note = `命中 ${matched.length} 个工具(宽词):已按能力分组只列名字;加更具体的词或 --lane <lane> 取完整行(含 requiredArgs/recipes)`;
1395
+ // r59: order groups by their BEST match, not by tool count — a 6-tool
1396
+ // `workflow` group used to outrank the 5-tool `field` group that
1397
+ // actually matched the word. Count is only a tie-break.
1398
+ inventory.groups = [...groups.values()]
1399
+ .sort((left, right) => right.score - left.score || right.tools.length - left.tools.length || left.capability.localeCompare(right.capability))
1400
+ .map(({ score: _score, ...group }) => group);
1401
+ inventory.note = `命中 ${matched.length} 个工具(宽词):已按能力分组只列名字(top3 已单列);加更具体的词或 --lane <lane> 取完整行(含 requiredArgs/recipes)`;
1353
1402
  }
1354
1403
  }
1355
1404
  result = inventory;
@@ -1396,7 +1445,7 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1396
1445
  }
1397
1446
  }
1398
1447
  else {
1399
- result = describeTool(registry, value ?? "");
1448
+ result = describeTool(registry, value ?? "", { legacy: legacyDiscovery() });
1400
1449
  // r28b 账本(2026-10-28):describe rule.save×11 / form.publish×9——firstCall 教学后
1401
1450
  // 仍反复全量 describe。同参数近期已 ok 时附降载提示,引导 --param/--example 精准取。
1402
1451
  // 无项目 ledger(golden/repo 测试/一次性运行)时 priorIdenticalSuccess 返回
@@ -1463,15 +1512,108 @@ function cmdNext(goal, transport) {
1463
1512
  const result = goalRoute(buildToolRegistry(), goal);
1464
1513
  return emitTransportResult(result, transport);
1465
1514
  }
1515
+ /**
1516
+ * r59 M3 — `omc plan "<目标>" --env <env>`.
1517
+ *
1518
+ * Read-only by construction: this handler only runs the probes `planGoal` asks
1519
+ * for (`model.list` today), and `planGoal` never emits a write step when a probe
1520
+ * is uncertain. `--ndjson` deliberately breaks the single-envelope contract the
1521
+ * same way `omc script` does (it produces the input that command consumes);
1522
+ * every other shape stays one envelope.
1523
+ */
1524
+ async function cmdPlan(goal, options, transport) {
1525
+ if (options.env === undefined || options.env.trim() === "") {
1526
+ return emitInvalid(transport, {
1527
+ message: "`omc plan` 必须指定 --env <环境>:规划要读平台解析 schemaCode/字段 code,没有环境只能给路线(那正是 omc next)。离线形状用 --env <env> --offline(零 wire)",
1528
+ });
1529
+ }
1530
+ if (options.planOut !== undefined) {
1531
+ try {
1532
+ assertSafeOutputPath(intentConfigRoot(), options.planOut, "plan output file");
1533
+ }
1534
+ catch (error) {
1535
+ return emitInvalid(transport, { message: error instanceof Error ? error.message : String(error) });
1536
+ }
1537
+ }
1538
+ const environment = options.env;
1539
+ let target;
1540
+ if (options.recipe !== undefined) {
1541
+ const [toolName, recipeId, ...rest] = options.recipe.split("/");
1542
+ if (toolName === undefined || recipeId === undefined || rest.length > 0) {
1543
+ return emitInvalid(transport, { message: "--recipe 的形状是 <tool>/<recipe>(如 field.create/field-serial-number);配方 id 见 omc describe <tool>" });
1544
+ }
1545
+ target = { tool: toolName, recipe: recipeId };
1546
+ }
1547
+ const plan = await planGoal(buildToolRegistry(), goal, {
1548
+ environment,
1549
+ ...(target !== undefined ? { target } : {}),
1550
+ ...(options.offline === true ? { offline: true } : {}),
1551
+ ...(options.offline === true
1552
+ ? {}
1553
+ : {
1554
+ probe: async (tool, args) => {
1555
+ // Lazy import: the registry→session stack is heavy and only the probe
1556
+ // path needs it (offline planning must stay instant).
1557
+ const { runToolCall } = await import("./call.js");
1558
+ const outcome = await runToolCall(tool, { args, environment, print: () => { } });
1559
+ const status = String(outcome.result.status ?? "");
1560
+ const ok = outcome.exitCode === 0 && status !== "uncertain" && status !== "error" && status !== "refused";
1561
+ return {
1562
+ ok,
1563
+ result: outcome.result,
1564
+ ...(ok ? {} : { error: String(outcome.result.blocker ?? outcome.result.message ?? status) }),
1565
+ };
1566
+ },
1567
+ }),
1568
+ });
1569
+ if (options.planOut !== undefined) {
1570
+ const path = assertSafeOutputPath(intentConfigRoot(), options.planOut, "plan output file");
1571
+ writeFileSync(path, `${JSON.stringify(plan, null, 2)}\n`, { mode: 0o600 });
1572
+ }
1573
+ if (options.ndjson === true) {
1574
+ const lines = planToNdjson(plan);
1575
+ // M4-5: steps that need an earlier step's readback cannot be expressed in
1576
+ // NDJSON (the script runner does no variable interpolation). Name them on
1577
+ // stderr — silently dropping steps is how a chain looks complete but isn't.
1578
+ const skipped = planToNdjsonSkipped(plan);
1579
+ if (skipped.length > 0) {
1580
+ process.stderr.write(`plan: ${skipped.length} 步未进 NDJSON(NDJSON 不做变量插值):\n`);
1581
+ for (const entry of skipped)
1582
+ process.stderr.write(` ${entry.id} ${entry.tool} — ${entry.reason}\n`);
1583
+ process.stderr.write("先把这些步骤按 plan 的 dependsOn 手工串起来,或用 --plan-out 交给编排器\n");
1584
+ }
1585
+ if (lines.length === 0) {
1586
+ // Nothing executable: say why on stderr and keep stdout empty for the
1587
+ // consumer (a `jq`-less pipe must not receive a prose paragraph).
1588
+ process.stderr.write(`plan: 0 个可执行步骤(level=${plan.level} ready=${String(plan.ready)});见 --plan-out 或去掉 --ndjson 看结构化阻塞\n`);
1589
+ return plan.ready ? 0 : CLI_EXIT_CODES.invalidInput;
1590
+ }
1591
+ for (const line of lines)
1592
+ console.log(line);
1593
+ return 0;
1594
+ }
1595
+ return emitResult(plan, transport);
1596
+ }
1466
1597
  /**
1467
1598
  * Ticket 125 — `omc capabilities` / `omc capability <id>`: the Configuration
1468
1599
  * capability overview. Read-only, zero environment contact; a projection of
1469
1600
  * the tool registry, the coverage manifest, and the intent capability registry.
1470
1601
  */
1471
- function cmdCapabilities(transport, compact = false, jq) {
1472
- const result = compactCapabilities(buildToolRegistry(), { compact });
1602
+ function cmdCapabilities(transport, options = {}, jq) {
1603
+ const result = compactCapabilities(buildToolRegistry(), { ...options, legacy: legacyDiscovery() });
1473
1604
  return emitProjectedResult({ status: "ok", ...result }, transport, jq);
1474
1605
  }
1606
+ /**
1607
+ * `OMC_LEGACY_DISCOVERY=1` — the 0.6.48 rollback switch (EXECUTION-PLAN §十).
1608
+ *
1609
+ * It restores the pre-M2 default faces byte-for-byte: bare `commands` with all
1610
+ * rows, `capabilities` with the full projection, and the wide `describe`. The
1611
+ * explicit flags (`--json`, `--full`, `--capability`) are unaffected — only the
1612
+ * defaults move, so a caller that names what it wants never sees a difference.
1613
+ */
1614
+ function legacyDiscovery() {
1615
+ return process.env.OMC_LEGACY_DISCOVERY === "1";
1616
+ }
1475
1617
  function cmdCapability(id, transport, executable = false, jq) {
1476
1618
  const registry = buildToolRegistry();
1477
1619
  const resolved = resolveCapabilityId(id);
@@ -1675,9 +1817,12 @@ async function cmdGraphPull(environment, concurrency, transport, path, applicati
1675
1817
  ...(data.gaps.length > 0 ? { gaps: { count: data.gaps.length, byKind: gapsByKind } } : {}),
1676
1818
  dbBytes: data.dbBytes,
1677
1819
  timings: data.timings,
1678
- dbPath: path ? `${path}/.omc/graph/graph.db` : undefined,
1679
- mcpHint: `MCP 工具按注册时的 --path 读库;要让 MCP 看到本次拉取:omc graph pull --path <MCP 的配置根> --env <env>`,
1680
- nextCommand: "omc graph references <kind> <code>",
1820
+ // One project can hold several environment indexes: the file name IS the
1821
+ // environment, so echo both the target file and the owning project root.
1822
+ dbPath: graphDbPath(path, data.meta.environmentName),
1823
+ projectPath: graphRoot(path),
1824
+ mcpHint: `MCP 面:注册一次 --path ${graphRoot(path)},再用 env 参数(或 omc_graph_projects 列可用索引)选环境;多项目时把各自的 --path 都注册上。`,
1825
+ nextCommand: `omc graph references <kind> <code> --env ${data.meta.environmentName}`,
1681
1826
  }, transport);
1682
1827
  }
1683
1828
  catch (error) {
@@ -1688,15 +1833,26 @@ async function cmdGraphPull(environment, concurrency, transport, path, applicati
1688
1833
  return emitThrown(error, transport);
1689
1834
  }
1690
1835
  }
1691
- function cmdGraphReferences(kind, code, transport, requestedEnvironment) {
1836
+ /** Shared refusal for "the index cannot answer": absent and ambiguous are different facts. */
1837
+ function graphIndexRefusal(error, selector, transport) {
1838
+ const ambiguous = error instanceof GraphIndexAmbiguousError;
1839
+ const unreadable = error instanceof GraphIndexUnreadableError;
1840
+ const pathHint = selector.root ? `--path ${selector.root}` : "";
1841
+ return emitResult({
1842
+ status: "refused",
1843
+ blocker: ambiguous ? "graph-index-ambiguous" : unreadable ? "graph-index-unreadable" : "graph-index-absent",
1844
+ message: `${error.message}${ambiguous ? "" : " 只读清点(不写索引):omc graph indexes;MCP 面读的可能是另一个项目根,比对 dbId/projectPath。"}`,
1845
+ ...(selector.env ? { environment: selector.env } : {}),
1846
+ nextCommand: ambiguous ? `omc graph indexes ${pathHint}`.trim() : `omc graph pull --env ${selector.env ?? "<env>"} ${pathHint}`.trim(),
1847
+ }, transport);
1848
+ }
1849
+ function cmdGraphReferences(kind, code, transport, selector = {}) {
1692
1850
  if (kind !== undefined && !["service", "model", "field"].includes(kind))
1693
1851
  return emitInvalid(transport, { message: "kind 必须是 service / model / field" });
1694
1852
  try {
1695
1853
  const kinds = kind === undefined ? ["service", "model", "field"] : [kind];
1696
- const results = kinds.map((one) => queryGraphReferences(one, code));
1854
+ const results = kinds.map((one) => queryGraphReferences(one, code, selector));
1697
1855
  const result = results[0];
1698
- if (requestedEnvironment !== undefined && requestedEnvironment !== result.index.environmentName)
1699
- return emitResult({ status: "refused", blocker: "graph-environment-mismatch", message: `索引已绑定环境 ${result.index.environmentName},不是 ${requestedEnvironment};请先 omc graph pull --env ${requestedEnvironment}`, index: result.index }, transport);
1700
1856
  if (kind === undefined)
1701
1857
  return emitResult({ status: "ok", code, index: result.index, references: Object.fromEntries(results.map((item) => [item.kind, { matches: item.matches, ...(item.coverage !== undefined ? { coverage: item.coverage } : {}), ...(item.note !== undefined ? { note: item.note } : {}) }])) }, transport);
1702
1858
  return emitResult({
@@ -1707,29 +1863,35 @@ function cmdGraphReferences(kind, code, transport, requestedEnvironment) {
1707
1863
  index: result.index,
1708
1864
  // r35a-F4:覆盖声明必须透传——CLI 这里是白名单式重建,漏加就等于没修
1709
1865
  // (matches:[] 曾被当成可安全删除的依据)。
1866
+ // r58(2026-11-12):同一坑再犯一次——scoped 精确查询的 resolvedScope 与
1867
+ // scopeNote 加在 queryGraphReferences 里,CLI 重建时没带,等于白修。
1868
+ ...(result.resolvedScope !== undefined ? { resolvedScope: result.resolvedScope } : {}),
1869
+ ...(result.scopeNote !== undefined ? { scopeNote: result.scopeNote } : {}),
1710
1870
  ...(result.coverage !== undefined ? { coverage: result.coverage } : {}),
1711
1871
  ...(result.note !== undefined ? { note: result.note } : {}),
1712
1872
  ...(result.gapWarning !== undefined ? { gapWarning: result.gapWarning } : {}),
1713
1873
  }, transport);
1714
1874
  }
1715
1875
  catch (error) {
1716
- if (error instanceof GraphIndexAbsentError)
1717
- return emitResult({ status: "refused", blocker: "graph-index-absent", message: `${error.message} 只读核查(不写索引):omc graph status --env <env>(当前配置根);MCP 面工具读的可能是另一配置根,比对 dbId/dbPath。`, nextCommand: "omc graph pull --env <env>" }, transport);
1876
+ if (error instanceof GraphIndexError)
1877
+ return graphIndexRefusal(error, selector, transport);
1718
1878
  return emitThrown(error, transport);
1719
1879
  }
1720
1880
  }
1721
- function cmdGraphReferencesBatch(kind, codeList, transport) {
1881
+ function cmdGraphReferencesBatch(kind, codeList, transport, selector = {}) {
1722
1882
  if (!["service", "model", "field"].includes(kind))
1723
1883
  return emitInvalid(transport, { message: "kind 必须是 service / model / field" });
1724
1884
  try {
1725
- const result = queryGraphReferencesBatch(kind, codeList.split(",").map((code) => code.trim()));
1885
+ const result = queryGraphReferencesBatch(kind, codeList.split(",").map((code) => code.trim()), selector);
1726
1886
  return emitResult({ status: "ok", ...result }, transport);
1727
1887
  }
1728
1888
  catch (error) {
1889
+ if (error instanceof GraphIndexError)
1890
+ return graphIndexRefusal(error, selector, transport);
1729
1891
  return emitThrown(error, transport);
1730
1892
  }
1731
1893
  }
1732
- function cmdGraphEdges(fromSchema, toSchema, kind, offset, limit, requestedEnvironment, transport) {
1894
+ function cmdGraphEdges(fromSchema, toSchema, kind, offset, limit, transport, selector = {}) {
1733
1895
  try {
1734
1896
  if (kind !== undefined && !["service", "model", "field"].includes(kind))
1735
1897
  return emitInvalid(transport, { message: "kind 必须是 service / model / field" });
@@ -1737,52 +1899,67 @@ function cmdGraphEdges(fromSchema, toSchema, kind, offset, limit, requestedEnvir
1737
1899
  const pageLimit = limit ?? 50;
1738
1900
  if (!Number.isSafeInteger(pageOffset) || pageOffset < 0 || !Number.isSafeInteger(pageLimit) || pageLimit < 1)
1739
1901
  return emitInvalid(transport, { message: "offset 必须是非负整数,limit 必须是正整数" });
1740
- const result = queryGraphEdges(fromSchema, toSchema, kind, pageOffset, pageLimit);
1741
- if (requestedEnvironment !== undefined && requestedEnvironment !== result.index.environmentName)
1742
- return emitResult({ status: "refused", blocker: "graph-environment-mismatch", message: `索引已绑定环境 ${result.index.environmentName},不是 ${requestedEnvironment};请先 omc graph pull --env ${requestedEnvironment}`, index: result.index }, transport);
1902
+ const result = queryGraphEdges(fromSchema, toSchema, kind, pageOffset, pageLimit, selector);
1743
1903
  return emitResult({ status: "ok", ...result }, transport);
1744
1904
  }
1745
1905
  catch (error) {
1906
+ if (error instanceof GraphIndexError)
1907
+ return graphIndexRefusal(error, selector, transport);
1746
1908
  return emitThrown(error, transport);
1747
1909
  }
1748
1910
  }
1749
- function cmdGraphStatus(requestedEnvironment, transport) {
1911
+ function cmdGraphStatus(transport, selector = {}) {
1750
1912
  try {
1751
- const status = readGraphStatus();
1752
- if (requestedEnvironment !== undefined && requestedEnvironment !== status.index.environmentName)
1753
- return emitResult({ status: "refused", blocker: "graph-environment-mismatch", message: `索引已绑定环境 ${status.index.environmentName},不是 ${requestedEnvironment}`, index: status.index }, transport);
1913
+ const status = readGraphStatus(selector);
1754
1914
  // r31a-F16:这里是**第四个**白名单式重建(前三次:compact() 投影、references
1755
1915
  // 覆盖声明、mcp-graph 的 explore)。白名单每漏一个键就等于没修,且不会被任何
1756
1916
  // 单测发现——所以改成展开,新增字段自动透传。
1757
1917
  return emitResult({ status: "ok", ...status }, transport);
1758
1918
  }
1759
1919
  catch (error) {
1760
- if (error instanceof GraphIndexAbsentError)
1761
- return emitResult({ status: "refused", blocker: "graph-index-absent", message: `${error.message} 只读核查(不写索引):omc graph status --env <env>(当前配置根);MCP 面工具读的可能是另一配置根,比对 dbId/dbPath。`, nextCommand: "omc graph pull --env <env>" }, transport);
1920
+ if (error instanceof GraphIndexError)
1921
+ return graphIndexRefusal(error, selector, transport);
1762
1922
  return emitThrown(error, transport);
1763
1923
  }
1764
1924
  }
1765
- function cmdGraphImpact(kind, code, transport) {
1925
+ function cmdGraphImpact(kind, code, transport, selector = {}) {
1766
1926
  if (!["service", "model", "field"].includes(kind))
1767
1927
  return emitInvalid(transport, { message: "kind 必须是 service / model / field(同 rule.references 第一版边界)" });
1768
1928
  try {
1769
- const result = impactGraph(kind, code);
1929
+ const result = impactGraph(kind, code, selector);
1770
1930
  return emitResult({ status: "ok", ...result }, transport);
1771
1931
  }
1772
1932
  catch (error) {
1773
- if (error instanceof GraphIndexAbsentError)
1774
- return emitResult({ status: "refused", blocker: "graph-index-absent", message: `${error.message} 只读核查(不写索引):omc graph status --env <env>(当前配置根);MCP 面工具读的可能是另一配置根,比对 dbId/dbPath。`, nextCommand: "omc graph pull --env <env>" }, transport);
1933
+ if (error instanceof GraphIndexError)
1934
+ return graphIndexRefusal(error, selector, transport);
1775
1935
  return emitThrown(error, transport);
1776
1936
  }
1777
1937
  }
1778
- function cmdGraphSearch(term, transport) {
1938
+ function cmdGraphSearch(term, transport, selector = {}) {
1779
1939
  try {
1780
- const result = searchGraphRules(term);
1940
+ const result = searchGraphRules(term, 20, 0, selector);
1781
1941
  return emitResult({ status: "ok", ...result }, transport);
1782
1942
  }
1783
1943
  catch (error) {
1784
- if (error instanceof GraphIndexAbsentError)
1785
- return emitResult({ status: "refused", blocker: "graph-index-absent", message: `${error.message} 只读核查(不写索引):omc graph status --env <env>(当前配置根);MCP 面工具读的可能是另一配置根,比对 dbId/dbPath。`, nextCommand: "omc graph pull --env <env>" }, transport);
1944
+ if (error instanceof GraphIndexError)
1945
+ return graphIndexRefusal(error, selector, transport);
1946
+ return emitThrown(error, transport);
1947
+ }
1948
+ }
1949
+ /** `omc graph indexes` — every local index under one project root (read-only). */
1950
+ function cmdGraphIndexes(path, transport) {
1951
+ try {
1952
+ const indexes = listGraphIndexes(path);
1953
+ return emitResult({
1954
+ status: "ok",
1955
+ projectPath: graphRoot(path),
1956
+ count: indexes.length,
1957
+ indexes,
1958
+ ...(indexes.length === 0 ? { nextCommand: `omc graph pull --path ${graphRoot(path)} --env <env>` } : {}),
1959
+ ...(indexes.length > 1 ? { note: "该项目根下有多份索引(多环境):读命令必须用 --env 指定;MCP 面用 env 参数。" } : {}),
1960
+ }, transport);
1961
+ }
1962
+ catch (error) {
1786
1963
  return emitThrown(error, transport);
1787
1964
  }
1788
1965
  }
@@ -2088,7 +2265,7 @@ function onboardingHelp() {
2088
2265
  // 结果三次都是全量,还去 describe 找 dedupe 参数(多花 3 轮)。读面确实不做跨调用
2089
2266
  // 结果去重——**明说**比留白强,省掉一次探索。
2090
2267
  "读面不做跨调用结果去重:同一读面同参数连跑 N 次就是 N 次真实读(不会回 unchanged,也没有 dedupe 开关)。要省就 --jq 定向取值或把结果落到自己的变量里复用;`unchanged:true` 只出现在写面回读缓存那一条路径。",
2091
- "工具发现:omc commands --json(含 capability id/lane/recipes;加 --compact 只回工具行、无目录散文)· omc capabilities(能力 id/lane/aliases/tools/依赖顺序)· omc capability <id> --executable(单能力完整执行包)。应用参数矩阵:omc help app-scope。",
2268
+ "工具发现:omc commands(路由索引)→ omc commands --capability <id>(工具名+brief+recipe)→ omc describe <tool>(参数/必填/firstCall)→ --example/--full;omc commands --json 是全量目录(回退面)。能力面:omc capabilities(id+工具数)· omc capabilities --full(id/lane/aliases/tools/依赖顺序)· omc capability <id> --executable(单能力完整执行包)。应用参数矩阵:omc help app-scope。",
2092
2269
  "单工具/契约:omc describe <tool>(schema+recipe+能力路由)· omc contract <lane>(wire 契约+能力路由);环境就绪:omc call discover_environment --env <env> --args '{}'。",
2093
2270
  "写入两道门:对话层草稿确认(omc help omc-config-draft-review)+ 环境 writable 开关;生产环境每笔写需在 args 里带 confirmProduction:true。",
2094
2271
  ].join("\n");
@@ -2610,20 +2787,26 @@ async function main() {
2610
2787
  command.command("residue <prefix>").description("跨面前缀残留扫描(model 全租户/folder/custompage;默认 deep 再查命中模型的 rule/datarule/onlinejs)——收尾「删净」一次证明,clean:true 即零残留。清理入口:omc model-purge --code <schemaCode>(按依赖倒序,默认 dry-run)。只读零写入;report 面暂停维护未扫描").option("--env <environment>", "环境名(默认按 cwd 的 .omc-env 解析)").option("--apps <codes>", "all(默认,全租户)或逗号分隔应用码").option("--no-deep", "只扫 model/folder/custompage,不深查命中模型").option("--all-faces", "列出全部应用×面(含 count:0;默认只回非零面+byFace/userResidues 紧凑形)").option("--max-output-bytes <bytes>").addOption(new Option("--jq [path]", "--jq 不是 jq,仅路径选择器(与 call --jq 同 DSL;可逗号多路径;裸 --jq 列顶层键)").argParser((value, previous = []) => [...previous, value]).default([])).action(async (prefix, options) => { commandExitCode = await withTransport(options, request, (transport) => cmdResidue(prefix, { env: options.env, apps: options.apps, ...(options.deep === false ? { noDeep: true } : {}), ...(options.allFaces ? { allFaces: true } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) }, transport)); });
2611
2788
  command.command("track <schemaCode> <bizObjectId>").description("读取单条业务数据的行级变更留痕(只读;平台来源枚举含 BUSINESS_RULE 时原样回传)").option("--env <environment>").option("--property-code <code>").option("--max-output-bytes <bytes>").action(async (schemaCode, bizObjectId, options) => { commandExitCode = await withTransport(options, request, (transport) => cmdTrack(schemaCode, bizObjectId, { env: options.env, propertyCode: options.propertyCode }, transport)); });
2612
2789
  const jqOption = () => new Option("--jq [path]", "--jq 不是 jq,仅路径选择器(与 call --jq 同 DSL;可逗号多路径;裸 --jq 列顶层键)").argParser((value, previous = []) => [...previous, value]).default([]);
2613
- command.command("commands").option("--json").option("--compact").option("--filter <keyword>").option("--lane <id>").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (options) => { commandExitCode = await withTransport(options, request, (transport) => cmdDiscovery("commands", transport, undefined, { json: options.json === true, compact: options.compact === true, ...(options.filter ? { filter: options.filter } : {}), ...(options.lane ? { lane: options.lane } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) })); });
2790
+ command.command("commands").option("--json").option("--compact").option("--filter <keyword>").option("--capability <id>").option("--lane <id>").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (options) => { commandExitCode = await withTransport(options, request, (transport) => cmdDiscovery("commands", transport, undefined, { json: options.json === true, compact: options.compact === true, ...(options.filter ? { filter: options.filter } : {}), ...(options.capability ? { capability: options.capability } : {}), ...(options.lane ? { lane: options.lane } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) })); });
2614
2791
  command.command("describe <tool>").option("--full").option("--cache-ok", "允许 --full 在同会话重复读时短路为 artifact 指针(默认每次回全文)").option("--schema-only").option("--param <name>").option("--example [id]").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (tool, options) => {
2615
2792
  commandExitCode = await withTransport(options, request, (transport) => cmdDiscovery("describe", transport, tool, { full: options.full === true, cacheOk: options.cacheOk === true, schemaOnly: options.schemaOnly === true, ...(options.param ? { param: options.param } : {}), ...(options.example ? { example: options.example } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) }));
2616
2793
  });
2617
2794
  command.command("contract <lane>").option("--full").option("--tool <name>").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (lane, options) => { commandExitCode = await withTransport(options, request, (transport) => cmdDiscovery("contract", transport, lane, { full: options.full === true, ...(options.tool ? { tool: options.tool } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) })); });
2618
2795
  // 2026-11-05 用户实测:`commands --json` 存在,于是大家自然写 `capabilities --json`
2619
2796
  // ——旧实现报 `unknown option`(退出码 10)。输出本来就是 JSON 信封,接受它做兼容别名。
2620
- command.command("capabilities").option("--compact").option("--json", "兼容别名:输出本就是 JSON 信封(与 commands --json 对齐)").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (options) => { commandExitCode = await withTransport(options, request, (transport) => cmdCapabilities(transport, options.compact === true, options.jq)); });
2797
+ command.command("capabilities").option("--compact").option("--full", "完整投影(id/标题/别名/工具/依赖)——默认只是能力索引").option("--json", "兼容别名:输出本就是 JSON 信封(与 commands --json 对齐)").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (options) => { commandExitCode = await withTransport(options, request, (transport) => cmdCapabilities(transport, { compact: options.compact === true, full: options.full === true }, options.jq)); });
2621
2798
  // `--env` is accepted but ignored: `next` is a zero-environment-contact route
2622
2799
  // solver, and a caller who reflexively passes `--env` should not be refused
2623
2800
  // (round 15 dogfood: `next "<goal>" --env local` → unknown option, one round).
2624
2801
  command.command("next <goal>").option("--env <environment>").option("--max-output-bytes <bytes>").action(async (goal, options) => {
2625
2802
  commandExitCode = await withTransport(options, request, (transport) => cmdNext(goal, transport));
2626
2803
  });
2804
+ // r59 M3 — `omc plan "<目标>" --env <env>`: READ-ONLY probing + a compiled plan.
2805
+ // Distinct from `next` (a route) and from `omc intent plan` (a declarative file):
2806
+ // this answers "what exactly would I run, and what is still missing?".
2807
+ command.command("plan <goal>").option("--env <environment>").option("--environment <environment>").option("--offline", "不接触环境:只报告需要哪些探测(Level 3 形状),零 wire").option("--ndjson", "把可执行步骤按 omc script 的 NDJSON 逐行输出(stdout 因此不是单信封,与 omc script 同类)").option("--recipe <tool/recipe>", "直接规划指定配方(跳过路由),如 field.create/field-serial-number").option("--plan-out <file>", "把完整 plan JSON 写到配置根内文件(供复核/重放)").option("--max-output-bytes <bytes>").addHelpText("after", "\n只读规划:搜索→配方→解析平台 id→本地 schema 校验→ready/missing/ambiguities/blockers。\n`ready=true` 要求:无未解析参数、无歧义、无待设计载荷、每步过 schema、探测无 uncertain。\n探测失败(uncertain)时**不生成任何写步骤**。\n整包需求走 Level 5(指 intent plan),不是原子 call 链。\n").action(async (goal, options) => {
2808
+ commandExitCode = await withTransport(options, request, (transport) => cmdPlan(goal, { env: options.environment ?? options.env, offline: options.offline === true, ndjson: options.ndjson === true, planOut: options.planOut, recipe: options.recipe }, transport));
2809
+ });
2627
2810
  command.command("usage").option("--records").option("--top <n>").option("--max-output-bytes <bytes>").addHelpText("after", "\n用量账本(.omc/usage.jsonl):默认只回汇总(调用数/字节/重复浪费/按工具 Top N);--records 才回原始记录。\n").action(async (options) => {
2628
2811
  const parsedTop = options.top === undefined ? undefined : Number.parseInt(String(options.top), 10);
2629
2812
  commandExitCode = await withTransport(options, request, (transport) => cmdUsage(transport, {
@@ -2681,7 +2864,12 @@ async function main() {
2681
2864
  const codes = options.applicationCodes ? String(options.applicationCodes).split(",").map((code) => code.trim()).filter(Boolean) : undefined;
2682
2865
  commandExitCode = await withTransport(options, request, (transport) => cmdGraphPull(options.environment ?? options.env, parsed, transport, options.path, codes, options.allApplications === true));
2683
2866
  });
2684
- graphCommand.command("references [kind] [code]").option("--batch <codes>").option("--env <environment>", "本子命令不接触环境;该参数仅用于提示索引绑定环境").option("--max-output-bytes <bytes>").addHelpText("after", "\n离线查询(零 wire):省略 kind 时=service|model|field 三类全查;支持 --batch code1,code2(例如 --batch svc_a,svc_b)。\n").action(async (kind, code, options) => {
2867
+ // Read-side selection is symmetric with `pull` (2026-11-13): every offline
2868
+ // subcommand takes --path (which project root) and --env (which environment's
2869
+ // index). One project can hold several environment indexes, and one
2870
+ // environment can be indexed by several projects — the pair is the identity.
2871
+ const withIndexSelector = (options) => ({ root: options.path, env: (options.environment ?? options.env) });
2872
+ graphCommand.command("references [kind] [code]").option("--batch <codes>").option("--env <environment>", "选哪一份索引(同项目可有多环境);省略则要求该项目根下只有一份").option("--path <dir>", "项目根目录(定位 <dir>/.omc/graph/<env>.db)").option("--max-output-bytes <bytes>").addHelpText("after", "\n离线查询(零 wire):省略 kind 时=service|model|field 三类全查;支持 --batch code1,code2(例如 --batch svc_a,svc_b)。\n").action(async (kind, code, options) => {
2685
2873
  // r42b 接线(2026-11-08,r42a-F8):commander 把首个位置参数绑给 [kind],
2686
2874
  // 「references <code>」这种最自然写法会把 code 当 kind 拒掉,而
2687
2875
  // cmdGraphReferences 的三类全查分支只认 kind===undefined——help 承诺的
@@ -2693,22 +2881,28 @@ async function main() {
2693
2881
  boundKind = undefined;
2694
2882
  boundCode = kind;
2695
2883
  }
2696
- commandExitCode = await withTransport(options, request, (transport) => options.batch ? cmdGraphReferencesBatch(boundKind ?? "model", options.batch, transport) : cmdGraphReferences(boundKind, boundCode ?? "", transport, options.environment ?? options.env));
2884
+ const selector = withIndexSelector(options);
2885
+ commandExitCode = await withTransport(options, request, (transport) => options.batch ? cmdGraphReferencesBatch(boundKind ?? "model", options.batch, transport, selector) : cmdGraphReferences(boundKind, boundCode ?? "", transport, selector));
2886
+ });
2887
+ graphCommand.command("references-batch <kind> <code>").option("--env <environment>").option("--path <dir>").option("--max-output-bytes <bytes>").action(async (kind, code, options) => {
2888
+ commandExitCode = await withTransport(options, request, (transport) => cmdGraphReferencesBatch(kind, code, transport, withIndexSelector(options)));
2697
2889
  });
2698
- graphCommand.command("references-batch <kind> <code>").option("--max-output-bytes <bytes>").action(async (kind, code, options) => {
2699
- commandExitCode = await withTransport(options, request, (transport) => cmdGraphReferencesBatch(kind, code, transport));
2890
+ graphCommand.command("edges").option("--env <environment>", "选哪一份索引;省略则要求该项目根下只有一份").option("--path <dir>", "项目根目录").option("--from-schema <code>").option("--to-schema <code>").option("--kind <kind>").option("--offset <n>").option("--limit <n>").option("--max-output-bytes <bytes>").addHelpText("after", "\n离线全图边清单(零 wire);支持 --kind model|field|service 与 --offset/--limit 分页。\n").action(async (options) => {
2891
+ commandExitCode = await withTransport(options, request, (transport) => cmdGraphEdges(options.fromSchema, options.toSchema, options.kind, options.offset === undefined ? undefined : Number(options.offset), options.limit === undefined ? undefined : Number(options.limit), transport, withIndexSelector(options)));
2700
2892
  });
2701
- graphCommand.command("edges").option("--env <environment>", "本子命令不接触环境;该参数仅用于提示索引绑定环境").option("--from-schema <code>").option("--to-schema <code>").option("--kind <kind>").option("--offset <n>").option("--limit <n>").option("--max-output-bytes <bytes>").addHelpText("after", "\n离线全图边清单(零 wire);支持 --kind model|field|service 与 --offset/--limit 分页。\n").action(async (options) => {
2702
- commandExitCode = await withTransport(options, request, (transport) => cmdGraphEdges(options.fromSchema, options.toSchema, options.kind, options.offset === undefined ? undefined : Number(options.offset), options.limit === undefined ? undefined : Number(options.limit), options.environment ?? options.env, transport));
2893
+ graphCommand.command("impact <kind> <code>").option("--env <environment>").option("--path <dir>").option("--max-output-bytes <bytes>").addHelpText("after", "\n影响面(离线):跳1=引用该编码的规则(同 references),跳2=这些规则还读写哪些 service/model/field——改前看爆炸半径。截断上限 50 规则×每类 20 码。\n").action(async (kind, code, options) => {
2894
+ commandExitCode = await withTransport(options, request, (transport) => cmdGraphImpact(kind, code, transport, withIndexSelector(options)));
2703
2895
  });
2704
- graphCommand.command("impact <kind> <code>").option("--max-output-bytes <bytes>").addHelpText("after", "\n影响面(离线):跳1=引用该编码的规则(同 references),跳2=这些规则还读写哪些 service/model/field——改前看爆炸半径。截断上限 50 规则×每类 20 码。\n").action(async (kind, code, options) => {
2705
- commandExitCode = await withTransport(options, request, (transport) => cmdGraphImpact(kind, code, transport));
2896
+ graphCommand.command("search <term...>").option("--env <environment>").option("--path <dir>").option("--max-output-bytes <bytes>").addHelpText("after", "\n检索规则的 code+name(FTS5,末词前缀匹配;**不含规则体/配置内容**)。找到\"关于 X 的规则\"拿 code,再走 references/impact。中文必须是全词或词首通配(如 报名* / 增加预算*)——子串不命中:FTS5 把「增加预算」当一个 token,搜「预算」为 0。\n").action(async (term, options) => {
2897
+ commandExitCode = await withTransport(options, request, (transport) => cmdGraphSearch(term.join(" "), transport, withIndexSelector(options)));
2706
2898
  });
2707
- graphCommand.command("search <term...>").option("--max-output-bytes <bytes>").addHelpText("after", "\n检索规则的 code+name(FTS5,末词前缀匹配;**不含规则体/配置内容**)。找到\"关于 X 的规则\"拿 code,再走 references/impact。中文必须是全词或词首通配(如 报名* / 增加预算*)——子串不命中:FTS5 把「增加预算」当一个 token,搜「预算」为 0。\n").action(async (term, options) => {
2708
- commandExitCode = await withTransport(options, request, (transport) => cmdGraphSearch(term.join(" "), transport));
2899
+ graphCommand.command("status").option("--env <environment>", "选哪一份索引;省略则要求该项目根下只有一份").option("--environment <environment>").option("--path <dir>", "项目根目录").option("--max-output-bytes <bytes>").action(async (options) => {
2900
+ commandExitCode = await withTransport(options, request, (transport) => cmdGraphStatus(transport, withIndexSelector(options)));
2709
2901
  });
2710
- graphCommand.command("status").option("--env <environment>").option("--environment <environment>").option("--max-output-bytes <bytes>").action(async (options) => {
2711
- commandExitCode = await withTransport(options, request, (transport) => cmdGraphStatus(options.environment ?? options.env, transport));
2902
+ // Which indexes exist here? The discovery face for multi-project /
2903
+ // multi-environment setups (CLI twin of the MCP `omc_graph_projects`).
2904
+ graphCommand.command("indexes").option("--path <dir>", "项目根目录(省略=当前配置根)").option("--max-output-bytes <bytes>").addHelpText("after", "\n只读清点:列出该根下所有 <env>.db(环境名/项目路径/新鲜度/规模)。多环境或多项目时先用它决定 --env。\n").action(async (options) => {
2905
+ commandExitCode = await withTransport(options, request, (transport) => cmdGraphIndexes(options.path, transport));
2712
2906
  });
2713
2907
  // MCP stdio server (host registration: cpdocs installer's omc-graph entry;
2714
2908
  // top-level verb like `codegraph serve --mcp`, not a graph subcommand).
@@ -2716,8 +2910,9 @@ async function main() {
2716
2910
  // may reach stdout from here; envelopes/banners never do.
2717
2911
  command
2718
2912
  .command("mcp-graph", { hidden: true })
2719
- .description("以 MCP stdio 服务器运行规则图检索(工具:omc_graph_explore / omc_graph_status)")
2720
- .option("--path <dir>", "项目根目录(定位 .omc/graph/graph.db;MCP 注册时传绝对路径,不信任宿主 cwd)")
2913
+ .description("以 MCP stdio 服务器运行规则图检索(工具:omc_graph_projects / omc_graph_explore / omc_graph_status)")
2914
+ // Repeatable: one server can serve every project on the machine.
2915
+ .option("--path <dir>", "项目根目录,可重复(定位 <dir>/.omc/graph/<env>.db;MCP 注册时传绝对路径,不信任宿主 cwd)。注册一处工作区根即可覆盖其一级子项目", (value, previous = []) => [...previous, value], [])
2721
2916
  .action(async (options) => {
2722
2917
  const { runMcpGraphServer } = await import("./mcp-graph.js");
2723
2918
  commandExitCode = await runMcpGraphServer(options.path);
@@ -125,7 +125,11 @@ function sanitizePaths(value) {
125
125
  // 脱成 [local-path-redacted] 后两面无法比对(探针正是靠比对 dbPath 才发现
126
126
  // 「MCP 读的是 ext-mcc 目录的旧库」);graph-index-absent 的拒绝消息也在叫用户
127
127
  // 「比对 dbId/dbPath」。仅豁免这一个键,其余路径照脱敏不放松。
128
- if (key === "dbPath" && typeof entry === "string") {
128
+ // 2026-11-13:projectPath 同理——多项目/多环境并存时,回执要靠它自证
129
+ // 「这是哪个项目的库」,脱敏后这条信息直接消失(MCP 面本就明文)。
130
+ // 按名豁免的含义:该字段名被约定为「graph 索引归属自证」专用;新命令
131
+ // 若要回显本地路径,走 dbPath/projectPath 之外的键(会被正常脱敏)。
132
+ if ((key === "dbPath" || key === "projectPath") && typeof entry === "string") {
129
133
  output[key] = entry;
130
134
  continue;
131
135
  }