@stalfh233/omc-cli 0.6.97 → 0.6.98

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.
package/dist/cli.js CHANGED
@@ -27,7 +27,7 @@ import { CLI_DEFAULT_OUTPUT_BYTES, assertSafeOutputPath, pruneArtifacts } from "
27
27
  import { sessionAccountForEnvironment } from "./session-account.js";
28
28
  import { closeWritableWindow, openWritableWindow, parseWritableTtl, sweepWritableWindowsAtStartup, validateWritableReason, writableWindowStatus, WRITABLE_WINDOW_DEFAULT_TTL_MINUTES, WRITABLE_WINDOW_LOG, WRITABLE_WINDOW_MAX_TTL_MINUTES, WritableWindowInputError } from "./writable-window.js";
29
29
  import { artifactPathMissHint, nullProjectionHint, PATH_MISS_HELP_REF, partialPathMissHint, pathMissCopyableHint, pathMissCopyablePaths, pathMissCrossFaceCorrection, pathMissDidYouMean, projectJsonPath, projectJsonPathFanout, projectResultExtract, shapeOf, SHAPE_MAX_DEPTH, unwrapSinglePathProjection } from "./path-projection.js";
30
- import { basename, join, resolve } from "node:path";
30
+ import { basename, dirname, join, resolve } from "node:path";
31
31
  import { existsSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
32
32
  import { buildToolRegistry } from "./tools.js";
33
33
  import { parseDurationMs } from "./duration.js";
@@ -1015,6 +1015,30 @@ function resolvedDefaultEnvironment(store) {
1015
1015
  * template re-read three times is 81 KB of the session.
1016
1016
  */
1017
1017
  const ARTIFACT_INLINE_CEILING_BYTES = 8192;
1018
+ /** commands --json 的上下文预算;当前目录约 31.5KiB,留出兼容窗口。 */
1019
+ const COMMANDS_JSON_INLINE_CEILING_BYTES = 32 * 1024;
1020
+ /** 超过这个体积就提醒走更窄的面(不改变返回值)。 */
1021
+ const COMMANDS_JSON_HINT_BYTES = 16 * 1024;
1022
+ /**
1023
+ * issue 2026-11 F3:默认骨架不是限流——同一句话必须同时出现在 `hint` 与顶层
1024
+ * `message`(并列通道同源),否则只看 message 的程序化消费方会误判。
1025
+ */
1026
+ function artifactOutlineHint(id, bytes, depth) {
1027
+ return `正文 ${Math.round(bytes / 1024)}KB 超过内联上限 ${ARTIFACT_INLINE_CEILING_BYTES}B,默认只回深度 ${depth} 骨架(键/类型/数组长度/示例值),不是输出限流。加深:--depth ≤${SHAPE_MAX_DEPTH};子树骨架:--shape <path>;取键:--keys <a,b>;取路径:--jq '<path>';整包:--full 或 --out <配置根内路径>;只元数据:--meta。`;
1028
+ }
1029
+ function artifactDefaultMetadata(id, bytes, content, depth) {
1030
+ return {
1031
+ status: "ok",
1032
+ artifactId: id,
1033
+ bytes,
1034
+ outline: true,
1035
+ depth,
1036
+ shape: shapeOf(content, depth),
1037
+ hint: artifactOutlineHint(id, bytes, depth),
1038
+ message: artifactOutlineHint(id, bytes, depth),
1039
+ fullCommand: `omc artifact get ${id} --full`,
1040
+ };
1041
+ }
1018
1042
  /**
1019
1043
  * `artifact get --jq`: one path walk, with `[]` fan-out (same syntax as
1020
1044
  * `omc call --jq`). Returns the envelope fields so both the `--summary` and the
@@ -1162,6 +1186,17 @@ async function cmdArtifactGet(id, transport, options = {}) {
1162
1186
  // command instead, which is the portable way to reach the body.
1163
1187
  if (options.pathOnly)
1164
1188
  return emitTransportResult({ status: "ok", artifactId: id, sha256: artifact.sha256, fetch: artifactFetchHint(id) }, transport);
1189
+ // --meta is the stable metadata-only choice. It deliberately never returns
1190
+ // the body, including for small artifacts whose default face is inline.
1191
+ if (options.meta === true) {
1192
+ const depth = options.depth ?? 2;
1193
+ return emitTransportResult({
1194
+ ...artifactDefaultMetadata(id, artifact.content.length, content, depth),
1195
+ sha256: artifact.sha256,
1196
+ projectionRule: "投影要写到叶子(数组元素里的字段);取值用 --jq <path> 或 --keys <a,b>",
1197
+ projectionExample: `omc artifact get ${id} --jq '<path>'`,
1198
+ }, transport);
1199
+ }
1165
1200
  // r75 调查C:`--shape [path]` 回执形状先验——深度受限骨架(默认 2,--depth 可
1166
1201
  // 到 4)。--summary 是预算事实(多大/会不会截断),--shape 是导航图(嵌套骨架
1167
1202
  // 到哪层有哪些键);>8KB 默认 outline 与本分支共用同一份 shapeOf(单一真相源,
@@ -1300,7 +1335,8 @@ async function cmdArtifactGet(id, transport, options = {}) {
1300
1335
  outline: true,
1301
1336
  depth,
1302
1337
  shape: shapeOf(content, depth),
1303
- hint: `正文 ${Math.round(artifact.content.length / 1024)}KB 超过内联上限 ${ARTIFACT_INLINE_CEILING_BYTES}B,默认只回深度 ${depth} 骨架(键/类型/数组长度/示例值)。加深:--depth ≤${SHAPE_MAX_DEPTH};子树骨架:--shape <path>;要某几个键:--keys <a,b>;要某个路径:--jq '<path>'(支持 .rules[code=Create].name 这类数组选择器);确实需要整包:--full,或 --out <配置根内路径> 整包落盘(父目录自动创建,不走 stdout 限额)。`,
1338
+ hint: artifactOutlineHint(id, artifact.content.length, depth),
1339
+ message: artifactOutlineHint(id, artifact.content.length, depth),
1304
1340
  projectionRule: "投影要写到叶子(数组元素里的字段);写整棵父节点(如 data.activities)会因总量超限再次被外置",
1305
1341
  ...(() => {
1306
1342
  const rec = content && typeof content === "object" && !Array.isArray(content) ? content : undefined;
@@ -1311,7 +1347,7 @@ async function cmdArtifactGet(id, transport, options = {}) {
1311
1347
  fullCommand: `omc artifact get ${id} --full`,
1312
1348
  }, transport);
1313
1349
  }
1314
- const result = { status: "ok", artifactId: id, sha256: artifact.sha256, content };
1350
+ const result = { status: "ok", artifactId: id, sha256: artifact.sha256, content, fullCommand: `omc artifact get ${id}`, projectionExample: `omc artifact get ${id} --jq '<path>'` };
1315
1351
  if (Buffer.byteLength(JSON.stringify(result), "utf8") > transport.maxOutputBytes) {
1316
1352
  // 2026-11-04 r70: `--full` used to fall back to the same bare `fetch`
1317
1353
  // pointer it had just been asked to bypass — re-running `--full` re-hits
@@ -1770,6 +1806,17 @@ function cmdDiscovery(kind, transport, value, options = {}) {
1770
1806
  }
1771
1807
  }
1772
1808
  result = inventory;
1809
+ if (options.json === true && options.compact !== true) {
1810
+ const inventoryBytes = Buffer.byteLength(JSON.stringify({ status: "ok", ...inventory }), "utf8");
1811
+ // issue 2026-11 F10:全量目录一行就是 30KB+。超预算外置成 artifact 指针
1812
+ // (--inline 强制内联);尚未超预算但已偏大时给一句指路,别再无声灌上下文。
1813
+ if (options.inline !== true && inventoryBytes > COMMANDS_JSON_INLINE_CEILING_BYTES)
1814
+ return emitTransportResult(boundResult({ status: "ok", ...inventory }, COMMANDS_JSON_INLINE_CEILING_BYTES), transport);
1815
+ // 不往 stdout 加字段:`commands --json` 的字节是 golden 钉死面(新能力必须
1816
+ // opt-in)。指路走 stderr(人类通道),程序化消费者字节不变。
1817
+ if (inventoryBytes > COMMANDS_JSON_HINT_BYTES)
1818
+ console.error(`全量目录 ${Math.round(inventoryBytes / 1024)}KB(单行);找工具用 --compact / --filter / --lane / --kind,确实要全量再加 --inline(当前未超 ${Math.round(COMMANDS_JSON_INLINE_CEILING_BYTES / 1024)}KiB 外置门)`);
1819
+ }
1773
1820
  }
1774
1821
  else if (kind === "contract") {
1775
1822
  if (options.tool !== undefined) {
@@ -2974,13 +3021,20 @@ async function main() {
2974
3021
  return;
2975
3022
  }
2976
3023
  const rows = store.listEnvironments().map((item) => ({ name: item.name, baseUrl: item.profile.baseUrl, applicationCode: item.profile.applicationCode, isDefault: item.profile.isDefault === true, writable: item.profile.writable !== false, credential: store.hasCredential(item.name) ? "ok" : "missing" }));
3024
+ // issue 2026-11 F5:清单来源(配置根 + 项目根)不回显时,同一条命令在不同
3025
+ // cwd 语义不同、且会静默落到机器全局 default——真机会话因此白打错环境。
3026
+ const paths = store.configPaths;
3027
+ const configRoot = dirname(paths.configPath);
3028
+ const projectRoot = dirname(paths.projectEnvPath);
3029
+ const binding = { configRoot, projectRoot, bindingFiles: { ".omc-env": paths.projectEnvPath, ".omc-envs": paths.projectEnvsPath }, note: "环境集合由「项目根」的 .omc-env/.omc-envs + 配置根的 omc.config.json 共同决定;换目录会换集合" };
2977
3030
  if (options.json)
2978
- process.stdout.write(JSON.stringify({ ok: true, environments: rows }, null, 2) + "\n");
3031
+ process.stdout.write(JSON.stringify({ ok: true, configRoot, projectRoot, environments: rows, binding }, null, 2) + "\n");
2979
3032
  else if (rows.length === 0)
2980
- console.error("(none configured; run omc setup)");
3033
+ console.error(`(none configured; run omc setup)\n配置根:${configRoot}\n项目根:${projectRoot}`);
2981
3034
  // A5(GitLab #15):credential: missing 的环境列得出、调不通(auth-config)——
2982
3035
  // 标注出来,防把"没凭据"误判成"参数写错"。
2983
3036
  else {
3037
+ console.error(`配置根:${configRoot} 项目根:${projectRoot}(环境集合由这两处决定,换目录会换集合)`);
2984
3038
  for (const row of rows)
2985
3039
  console.error(`${row.name}${row.isDefault ? " (default)" : ""} ${row.baseUrl} app=${row.applicationCode}${row.writable ? "" : " [read-only]"}${row.credential === "ok" ? "" : " [credential: missing → omc setup]"}`);
2986
3040
  // r55(2026-11-11 Windows 真机联调摩擦):agent 为拿 token 花 7 轮、用户手粘
@@ -3284,7 +3338,7 @@ async function main() {
3284
3338
  console.error(`已清理 ${result.removed} 个读回产物,释放 ${formatBytes(result.freedBytes)};保留 ${result.kept} 个(${formatBytes(result.keptBytes)})`);
3285
3339
  commandExitCode = CLI_EXIT_CODES.ok;
3286
3340
  });
3287
- artifactCommand.command("get <id>").addOption(new Option("--jq [path]", "路径选择器(非 jq);支持 [] 映射与逗号多路径;裸 --jq 列顶层键").argParser((value, previous = []) => [...previous, value]).default([])).option("--extract <path>", "同 --jq(与 omc call 的 --extract 同名,省一次命名切换)").option("--path-only").option("--shape [path]", "回执形状先验:深度受限骨架(键/类型/数组长度/≤40 字符示例值),一次看全嵌套路径图再 --jq;裸 --shape = 整棵根,--shape <path> = 命中子树(同 --jq 的路径 DSL);与 >8KB 默认 outline 同一实现").option("--depth <n>", "骨架深度 1-4(默认 2;--shape 与 >8KB 默认 outline 消费)").option("--summary").option("--keys [a,b]").option("--full", "整包返回正文(默认:正文超过 8KB 时只回深度 2 骨架 outline,按需 --shape/--jq/--keys 定向取值)").option("--out <path>", "把 artifact 原始正文全量写到配置根内文件(0600;写文件不走 stdout 限额,大对象一次落盘备份;回执只给 {out,bytes,sha256} 不回正文。根内父目录自动创建;配置根外(含系统临时目录)拒绝,拒绝错误里带可用的根内示例路径。stdout 管道提取用两步:--out <根内路径> 后 cat 该文件——`--out -` 会破坏单信封契约,不支持)").option("--max-output-bytes <bytes>").action(async (id, options) => {
3341
+ artifactCommand.command("get <id>").addOption(new Option("--jq [path]", "路径选择器(非 jq);支持 [] 映射与逗号多路径;裸 --jq 列顶层键").argParser((value, previous = []) => [...previous, value]).default([])).option("--extract <path>", "同 --jq(与 omc call 的 --extract 同名,省一次命名切换)").option("--path-only").option("--shape [path]", "回执形状先验:深度受限骨架(键/类型/数组长度/≤40 字符示例值),一次看全嵌套路径图再 --jq;裸 --shape = 整棵根,--shape <path> = 命中子树(同 --jq 的路径 DSL);与 >8KB 默认 outline 同一实现").option("--depth <n>", "骨架深度 1-4(默认 2;--shape 与 >8KB 默认 outline 消费)").option("--summary").option("--keys [a,b]").option("--meta", "只回元数据,不回正文").option("--full", "整包返回正文(默认:正文超过 8KB 时只回深度 2 骨架 outline,按需 --shape/--jq/--keys 定向取值)").option("--out <path>", "把 artifact 原始正文全量写到配置根内文件(0600;写文件不走 stdout 限额,大对象一次落盘备份;回执只给 {out,bytes,sha256} 不回正文。根内父目录自动创建;配置根外(含系统临时目录)拒绝,拒绝错误里带可用的根内示例路径。stdout 管道提取用两步:--out <根内路径> 后 cat 该文件——`--out -` 会破坏单信封契约,不支持)").option("--max-output-bytes <bytes>").action(async (id, options) => {
3288
3342
  // A bare `--jq`/`--keys` is a key-inventory request, not a missing argument:
3289
3343
  // commander's "argument missing" (invalid-input + retry) is a dead end the
3290
3344
  // caller cannot fix without already knowing the flag takes a value (r11
@@ -3307,6 +3361,7 @@ async function main() {
3307
3361
  ...(shapeValue !== undefined ? { shape: shapeValue } : {}),
3308
3362
  ...(depthValue !== undefined ? { depth: depthValue } : {}),
3309
3363
  summary: options.summary === true || options.keys === true || bareJq,
3364
+ meta: options.meta === true,
3310
3365
  pureKeys: (options.keys === true || bareJq) && options.summary !== true, ...(typeof options.keys === "string" ? { keys: options.keys } : {}), full: options.full === true, ...(artifactGetOutPath !== undefined ? { out: artifactGetOutPath } : {})
3311
3366
  }));
3312
3367
  });
@@ -3314,7 +3369,7 @@ async function main() {
3314
3369
  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)); });
3315
3370
  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)); });
3316
3371
  const jqOption = () => new Option("--jq [path]", "--jq 不是 jq,仅路径选择器(与 call --jq 同 DSL;可逗号多路径;裸 --jq 列顶层键)").argParser((value, previous = []) => [...previous, value]).default([]);
3317
- command.command("commands").description("路由索引(不是目录):工具计数+展开梯子;--kind read 一屏列全部只读工具与必填参数;--json 才是全量目录").option("--json").option("--compact").option("--filter <keyword>").option("--capability <id>").option("--lane <id>").option("--kind <kind>", "按读写维度过滤:read|write|meta(read = 只读工具索引)").option("--read-only", "等价 --kind read(与 --kind 互斥)").option("--limit <n>", "分页:最多 n 行(1..200;给定即关闭宽词分组)").option("--offset <n>", "分页起点(默认 0;未给 --limit 时按 50)").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.kind !== undefined ? { kind: options.kind } : {}), ...(options.readOnly === true ? { readOnly: true } : {}), ...(options.limit !== undefined ? { limit: options.limit } : {}), ...(options.offset !== undefined ? { offset: options.offset } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) })); });
3372
+ command.command("commands").description("路由索引(不是目录):工具计数+展开梯子;--kind read 一屏列全部只读工具与必填参数;--json 才是全量目录").option("--json").option("--compact").option("--inline", "commands --json 超过 32KiB 时仍内联").option("--filter <keyword>").option("--capability <id>").option("--lane <id>").option("--kind <kind>", "按读写维度过滤:read|write|meta(read = 只读工具索引)").option("--read-only", "等价 --kind read(与 --kind 互斥)").option("--limit <n>", "分页:最多 n 行(1..200;给定即关闭宽词分组)").option("--offset <n>", "分页起点(默认 0;未给 --limit 时按 50)").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, inline: options.inline === true, ...(options.filter ? { filter: options.filter } : {}), ...(options.capability ? { capability: options.capability } : {}), ...(options.lane ? { lane: options.lane } : {}), ...(options.kind !== undefined ? { kind: options.kind } : {}), ...(options.readOnly === true ? { readOnly: true } : {}), ...(options.limit !== undefined ? { limit: options.limit } : {}), ...(options.offset !== undefined ? { offset: options.offset } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) })); });
3318
3373
  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) => {
3319
3374
  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 } : {}) }));
3320
3375
  });
@@ -37,7 +37,7 @@ export function versionEvidenceOf(input) {
37
37
  return {
38
38
  detectedVersion: detected,
39
39
  inAnchorFamily: detected.startsWith(`${input.versionFamily}.`),
40
- versionSource: "system-config",
40
+ versionSource: input.versionSource ?? "system-config",
41
41
  anchorVersion: input.anchorVersion,
42
42
  versionFamily: input.versionFamily,
43
43
  ...(input.versionNotice ? { versionNotice: input.versionNotice } : {}),
@@ -90,7 +90,7 @@ export const DATARULE_LANE_CONTRACT = Object.freeze({
90
90
  "**类型3/4/5 条件串协议(平台 create 不校验,坏形状落库即雷,工具按此协议拒绝)**:`{字段code} 操作符 [值]`。操作符取 **bizdatarule 词表**(与字段 options 的表单交互引擎不同——那是符号式):**中文** 等于/不等于/大于/小于/大于等于/小于等于/包含/不包含/包含全部/不包含全部/包含任意一个/不包含任意一个/等于任意一个/属于/不属于/介于/为空/不为空,也接受符号 `==` `!=` `>` `<` `>=` `<=` `Contains` `IsEmpty` 等。为空/不为空**不带值**(`{field} 不为空`);其余带值(JSON 对象或标量)。多条件 ` && `、多组 ` || `。示例 type4:`options:{requiredFormula:\"{amount} 等于 {\\\"valueType\\\":\\\"specifyOption\\\",\\\"value\\\":\\\"A\\\"}\"}`。**字段绑定用 `propertyCodes`(数组)**,工具自动把 `options.propertyCodes` 也补上。",
91
91
  "`options` is a JSON object sent to the wire as a JSON string(逐类型必读键见 `options` 参数面)。",
92
92
  "类型2(计算/拼接):`options.shortTextStitch`(或 `value`)的值**必须是含 `formula` 的 JSON 对象字符串**,裸串会被工具拒绝(否则引擎返回 null → 误报 305003 死循环);顶层没有 `expression` 键——它只是该嵌套 JSON 内部的字段名(可照抄 `--example field-compute-rule`)。",
93
- "Missing type or schemaCode is refused before any write.",
93
+ "Missing type or schemaCode is refused before any write. 同字段同类型已存在时零写入拒绝(blocker `datarule-duplicate-property-type`,回执带现有 `id` 与改走 `datarule.update` 的命令)——批量造规则不必先 list 自查。",
94
94
  "根因提示:类型2 CALCULATE 在未发布应用上会报假死循环 305003——工具反推后拒 app-not-published;类型 3/4/5 不受影响(误判机制见 `--example field-compute-rule`)。",
95
95
  ]),
96
96
  }),
@@ -17,6 +17,7 @@ function versionEvidenceFor(ctx, session) {
17
17
  const notice = detected ? versionFamilyNotice(ctx.manifest, detected) : undefined;
18
18
  return versionEvidenceOf({
19
19
  detectedVersion: detected,
20
+ versionSource: session.versionEvidenceSource(),
20
21
  versionFamily: ctx.manifest.version_family,
21
22
  anchorVersion: ctx.manifest.anchor_version,
22
23
  ...(notice ? { versionNotice: notice } : {}),
@@ -39,28 +40,25 @@ function versionEvidenceFor(ctx, session) {
39
40
  */
40
41
  const EXTENSION_SHA_UNAVAILABLE = "平台没有暴露扩展/前端构件 build sha 的端点(8.6.26 与 1.1.25 反编译 + 真机均无);版本判断只能用 productVersion";
41
42
  async function platformVersionBlock(session) {
42
- try {
43
- const license = (await wireCall(session, { path: ENDPOINTS.licenseInfo })).data;
44
- const productVersion = license && typeof license.systemVersion === "string" && license.systemVersion.trim() ? license.systemVersion.trim() : undefined;
45
- if (productVersion !== undefined)
46
- return {
47
- productVersion,
48
- ...(typeof license.buildTime === "string" && license.buildTime ? { buildTime: license.buildTime } : {}),
49
- ...(license.licenseType !== undefined && license.licenseType !== null ? { licenseType: license.licenseType } : {}),
50
- ...(typeof license.expiration === "string" && license.expiration ? { licenseExpiration: license.expiration } : {}),
51
- source: "license/info",
52
- extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE,
53
- };
54
- }
55
- catch {
56
- // fall through to the system/config face — the license face is 8.6-only
57
- }
43
+ // F7:license 载荷在登录期已经探测过(session.licenseInfo),这里复用它,不再
44
+ // 为展示面重复打一次 wire;字段口径与 r86 一致(buildTime 只有平台回传才带)。
45
+ const license = session.licenseInfo();
46
+ const licenseVersion = license && typeof license.systemVersion === "string" && license.systemVersion.trim() ? license.systemVersion.trim() : undefined;
47
+ if (licenseVersion !== undefined && license !== undefined)
48
+ return {
49
+ productVersion: licenseVersion,
50
+ ...(typeof license.buildTime === "string" && license.buildTime ? { buildTime: license.buildTime } : {}),
51
+ ...(license.licenseType !== undefined && license.licenseType !== null ? { licenseType: license.licenseType } : {}),
52
+ ...(typeof license.expiration === "string" && license.expiration ? { licenseExpiration: license.expiration } : {}),
53
+ source: "license/info",
54
+ extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE,
55
+ };
58
56
  const raw = session.rawSystemVersion();
59
57
  if (raw !== undefined)
60
58
  return {
61
59
  productVersion: raw,
62
60
  source: "public/system-config systemVersion",
63
- licenseFaceUnavailable: "license/info 不可达(真机 1.1.25:未认证 401、管理员会话 404——该产品线不挂载);buildTime 只在平台回传时才有",
61
+ licenseFaceUnavailable: "license/info 不可达(真机 1.1.25:未认证 401、管理员 404——该产品线不挂载);buildTime 只在平台回传时才有",
64
62
  extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE,
65
63
  };
66
64
  // 登录缓存沿用(老缓存只存了点号版本、没有原串):用 detectedVersion 兜底——
@@ -79,10 +77,10 @@ async function platformVersionBlock(session) {
79
77
  function platformVersionBlockFromSession(session) {
80
78
  const cached = session.rawSystemVersion();
81
79
  if (cached !== undefined)
82
- return { productVersion: cached, source: "public/system-config systemVersion", extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE };
80
+ return { productVersion: cached, source: session.versionEvidenceSource() ?? "public/system-config", extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE };
83
81
  const detected = session.detectedVersion();
84
82
  if (detected !== undefined)
85
- return { productVersion: detected, source: "token-cache detectedVersion(缓存命中面零 wire)", extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE };
83
+ return { productVersion: detected, source: session.versionEvidenceSource() ?? "token-cache", extensionBuildShaUnavailable: EXTENSION_SHA_UNAVAILABLE };
86
84
  return { versionUnavailable: "缓存命中面零 wire:license/info 未查,登录缓存也没有版本证据(refresh:true 重查)" };
87
85
  }
88
86
  export function registerEnvironmentLane(tools) {
@@ -46,8 +46,53 @@ function permissionGroupRows(data) {
46
46
  }
47
47
  const permissionType = (v) => ({ 1: "全部可见", 2: "本部门", 3: "仅自己", 4: "自定义", 5: "角色管理范围", 6: "均不可见" }[String(v)] ?? (v == null ? null : v));
48
48
  const PERMISSION_UPDATE_FUNCTION = "/api/api/system/permission/update_function";
49
- const VIEW_ACTIONS = new Set(["ADD", "DELETE", "IMPORT", "EXPORT", "IMPORT_ATTACHMENT", "EXPORT_ATTACHMENT", "BATCH_SUBMIT", "BATCH_UPDATE", "BATCH_PRINT", "QR_CODE", "EDITOWNER"]);
50
- const FORM_ACTIONS = new Set(["EDIT", "TEMPORARY", "SUBMIT", "COPY", "PRINT", "EDITOWNER"]);
49
+ /**
50
+ * r96(2026-11-24,真机会话 40 次 `perm.auth` 摩擦):动作码此前只活在源码里,
51
+ * `describe perm.auth` 只显示 `grants: array<object>`,非法码只回「未知视图动作码:xxx」
52
+ * ——agent 只能先猜 `add`、再 dry-run 逐个探测。这里把**码 + 中文名 + 平台来源**做成
53
+ * 唯一事实源:错误消息列全(零 tools/list 字节,错误面不进该预算),`labels` 供文档面引用。
54
+ *
55
+ * 平台来源(cp-sources 8.6.26):视图动作 = 列表工具栏按钮
56
+ * (`customButtonViewPerm[].customBtns[].code`),表单动作 = 表单操作按钮
57
+ * (`customButtonFormPerm[].customBtns[].code`)。两族都**大小写敏感、全大写**,
58
+ * 平台未声明的码不会出现(mergeActions 只翻既有按钮的 enable)。
59
+ */
60
+ const VIEW_ACTION_LABELS = Object.freeze({
61
+ ADD: "新增",
62
+ DELETE: "删除",
63
+ IMPORT: "导入",
64
+ EXPORT: "导出",
65
+ IMPORT_ATTACHMENT: "导入附件",
66
+ EXPORT_ATTACHMENT: "导出附件",
67
+ BATCH_SUBMIT: "批量提交",
68
+ BATCH_UPDATE: "批量修改",
69
+ BATCH_PRINT: "批量打印",
70
+ QR_CODE: "打印二维码",
71
+ EDITOWNER: "修改拥有者",
72
+ // 同步类模型才有(BizQueryController:765 把 MANUAL_SYNC 当查询动作过滤;不在
73
+ // getInitViewButtons 的默认 11 个里)。不列进来就等于「能开不能关」——与完整
74
+ // 期望集语义不一致。子表专用码(CLEAR_ROW/ADD_BEFORE/ADD_AFTER)只在
75
+ // `customButtonFormPerm[].childTableBtns` 里,不属于 actions.view/form,别加。
76
+ MANUAL_SYNC: "同步数据",
77
+ });
78
+ const FORM_ACTION_LABELS = Object.freeze({
79
+ EDIT: "编辑",
80
+ TEMPORARY: "暂存",
81
+ SUBMIT: "提交",
82
+ COPY: "复制",
83
+ PRINT: "打印",
84
+ EDITOWNER: "修改拥有者",
85
+ });
86
+ const VIEW_ACTIONS = new Set(Object.keys(VIEW_ACTION_LABELS));
87
+ const FORM_ACTIONS = new Set(Object.keys(FORM_ACTION_LABELS));
88
+ /**
89
+ * r96:`--param grants` / `--full` 里的动作码教学(嵌套 describe 不进 tools/list)。
90
+ * 与 `actionCodeRefusal` 的错误消息同源,避免两处漂移。
91
+ */
92
+ function actionCodeDoc(kind) {
93
+ const labels = kind === "view" ? VIEW_ACTION_LABELS : FORM_ACTION_LABELS;
94
+ return `${kind === "view" ? "视图" : "表单"}动作码,全大写:${Object.entries(labels).map(([code, name]) => `${code}=${name}`).join("、")}`;
95
+ }
51
96
  function permissionRecords(data) {
52
97
  const root = (data && typeof data === "object" ? data : {});
53
98
  const records = first(root, "dataPermissionGroups", "functionPermissions", "functions");
@@ -84,11 +129,37 @@ function mergePropertyPermissions(existing, requested, schemaCode) {
84
129
  }
85
130
  return current;
86
131
  }
132
+ /**
133
+ * 动作面合并(语义:**每个容器内标准动作码的完整期望集**)。
134
+ *
135
+ * 平台 `customBtns[]` 里不止 11 个枚举码:`CustomButtonPermissionModel.addCustomButtons`
136
+ * 还会把**业务规则绑定的自定义按钮**(code = ruleCode)塞进同一张表。所以这里分两类:
137
+ *
138
+ * - 枚举码(VIEW_ACTIONS/FORM_ACTIONS):完整期望集语义——每个容器全表翻转,
139
+ * 未列出的合法码置 false,并进 `turnedOff` 让它**可见**。
140
+ * - 非枚举码(自定义按钮):只做**显式打开**,绝不隐式关闭。
141
+ *
142
+ * 同一模型可以有多个容器(多列表视图 / 多表单 sheet),所以按容器算:
143
+ * `unapplied` = 所有容器都没有;`partial` = 只在部分容器里有(另一半不会凭空造)。
144
+ */
87
145
  function mergeActions(existing, requested, allowed) {
88
146
  if (requested === undefined)
89
- return existing;
147
+ return { merged: existing, unapplied: [], partial: [], turnedOff: [], turnedOffByContainer: [] };
90
148
  const codes = new Set(requested);
91
- return rows(existing).map((container) => {
149
+ const containers = rows(existing).map((container) => {
150
+ const record = container;
151
+ return {
152
+ containerCode: first(record, "containerCode") ?? null,
153
+ present: rows(first(record, "customBtns", "actionPermissions")).map((button) => String(button.code ?? "")),
154
+ };
155
+ });
156
+ const allPresent = new Set(containers.flatMap((container) => container.present));
157
+ const unapplied = requested.filter((code) => !allPresent.has(code));
158
+ const partial = requested.filter((code) => allPresent.has(code) && !containers.every((container) => container.present.includes(code)));
159
+ const turnedOffByContainer = containers
160
+ .map((container) => ({ containerCode: container.containerCode, codes: container.present.filter((code) => allowed.has(code) && !codes.has(code)) }))
161
+ .filter((entry) => entry.codes.length > 0);
162
+ const merged = rows(existing).map((container) => {
92
163
  const c = { ...container };
93
164
  const buttons = rows(first(c, "customBtns", "actionPermissions"));
94
165
  c.customBtns = buttons.map((button) => {
@@ -96,10 +167,14 @@ function mergeActions(existing, requested, allowed) {
96
167
  const code = String(b.code ?? "");
97
168
  if (allowed.has(code))
98
169
  b.enabled = codes.has(code);
170
+ // 自定义按钮:只显式打开,不隐式关闭。
171
+ else if (codes.has(code))
172
+ b.enabled = true;
99
173
  return b;
100
174
  });
101
175
  return c;
102
176
  });
177
+ return { merged, unapplied, partial, turnedOff: [...new Set(turnedOffByContainer.flatMap((entry) => entry.codes))], turnedOffByContainer };
103
178
  }
104
179
  function authProjection(record) {
105
180
  return {
@@ -152,6 +227,52 @@ function changedProjection(before, after, grant) {
152
227
  }
153
228
  return changes;
154
229
  }
230
+ /** 归一化:只做大小写/分隔符折叠,不做模糊匹配(模糊匹配会误杀自定义按钮码)。 */
231
+ const normalizeActionCode = (code) => code.toUpperCase().replace(/[\s_-]/g, "");
232
+ /**
233
+ * 动作码拒绝门(r96)。
234
+ *
235
+ * 只拒**高置信度**的两种错,其余放行交给真机 `unapplied` 回报:
236
+ * 1. 跨族错位(`ADD` 写进 `actions.form`);
237
+ * 2. 仅大小写/分隔符不同(`add` / `IMPORT-ATTACHMENT`)——归一化后与枚举码相等。
238
+ *
239
+ * 不能对任何非枚举码一律拒绝:平台 `customBtns[]` 里还有业务规则绑定的自定义按钮
240
+ * (code = ruleCode,见 `CustomButtonPermissionModel.addCustomButtons`),
241
+ * 一刀切会把合法输入判死。
242
+ */
243
+ function actionCodeRefusal(kind, code) {
244
+ const labels = kind === "view" ? VIEW_ACTION_LABELS : FORM_ACTION_LABELS;
245
+ const legal = Object.keys(labels);
246
+ const normalized = normalizeActionCode(code);
247
+ const sameFamily = legal.find((candidate) => normalizeActionCode(candidate) === normalized);
248
+ const otherLabels = kind === "view" ? FORM_ACTION_LABELS : VIEW_ACTION_LABELS;
249
+ const otherKind = kind === "view" ? "form" : "view";
250
+ const crossFamily = Object.prototype.hasOwnProperty.call(otherLabels, code.toUpperCase()) ? code.toUpperCase() : undefined;
251
+ const legalText = legal.map((c) => `${c}(${labels[c]})`).join("、");
252
+ const base = {
253
+ status: "refused",
254
+ blocker: "permission-action-unknown",
255
+ kind,
256
+ unknownAction: code,
257
+ acceptedValues: { [`actions.${kind}`]: legal },
258
+ // issue 04 acceptance 点名 supportedActions;与 acceptedValues 同源同值,
259
+ // 两个键都给(前者是本仓惯例,后者是报告里的叫法),避免调用方各猜一个。
260
+ supportedActions: legal,
261
+ nextCommand: `omc describe perm.auth --param grants`,
262
+ };
263
+ if (sameFamily !== undefined)
264
+ return new ToolRefusalError({
265
+ ...base,
266
+ didYouMean: { [`actions.${kind}`]: sameFamily },
267
+ message: `未知${kind === "view" ? "视图" : "表单"}动作码:${code}——平台码全大写。是否想写 ${sameFamily}(${labels[sameFamily]})?actions.${kind} 合法值:${legalText}。`,
268
+ });
269
+ if (crossFamily !== undefined)
270
+ return new ToolRefusalError({
271
+ ...base,
272
+ message: `未知${kind === "view" ? "视图" : "表单"}动作码:${code}——${crossFamily} 是${otherKind === "view" ? "视图" : "表单"}动作码(actions.${otherKind}),不能放进 actions.${kind}。actions.${kind} 合法值:${legalText}。`,
273
+ });
274
+ return undefined;
275
+ }
155
276
  function validateGrants(grants) {
156
277
  if (!Array.isArray(grants))
157
278
  throw new ToolRefusalError({ status: "refused", blocker: "permission-grants-invalid", message: "grants 必须是数组" });
@@ -171,13 +292,83 @@ function validateGrants(grants) {
171
292
  }
172
293
  if (grant.rowLevel?.type === 4 && (!Array.isArray(grant.rowLevel.conditions) || grant.rowLevel.conditions.length === 0))
173
294
  throw new ToolRefusalError({ status: "refused", blocker: "permission-custom-condition-required", message: "rowLevel.type=4 必须提供非空 conditions" });
174
- for (const code of grant.actions?.view ?? [])
175
- if (!VIEW_ACTIONS.has(code))
176
- throw new ToolRefusalError({ status: "refused", blocker: "permission-action-unknown", message: `未知视图动作码:${code}` });
177
- for (const code of grant.actions?.form ?? [])
178
- if (!FORM_ACTIONS.has(code))
179
- throw new ToolRefusalError({ status: "refused", blocker: "permission-action-unknown", message: `未知表单动作码:${code}` });
295
+ for (const code of grant.actions?.view ?? []) {
296
+ if (VIEW_ACTIONS.has(code))
297
+ continue;
298
+ const refusal = actionCodeRefusal("view", code);
299
+ if (refusal)
300
+ throw refusal;
301
+ }
302
+ for (const code of grant.actions?.form ?? []) {
303
+ if (FORM_ACTIONS.has(code))
304
+ continue;
305
+ const refusal = actionCodeRefusal("form", code);
306
+ if (refusal)
307
+ throw refusal;
308
+ }
309
+ }
310
+ }
311
+ const TURNED_OFF_HINT = "actions 是完整期望集:这些码在本次请求里没列出,因此被置 false;只想加开不想关,请把它们一并写进请求";
312
+ /**
313
+ * r96:把「读到的权限组 + grants」编成要上送的记录(纯函数,零 wire)。
314
+ * dry-run(dryRunPayload)与真写(execute)共用它,保证「预览」和「真写」永远是同一个答案。
315
+ */
316
+ function planAuthRecords(existing, grants, groupId) {
317
+ const mergedRecords = [];
318
+ const beforeRecords = [];
319
+ const preview = [];
320
+ const unapplied = [];
321
+ const partial = [];
322
+ const turnedOff = [];
323
+ for (const grant of grants) {
324
+ const prior = existing.find((record) => String(first(record, "schemaCode", "functionCode") ?? "") === grant.schemaCode);
325
+ if (!prior)
326
+ throw new ToolRefusalError({ status: "refused", blocker: "permission-target-model-unknown", message: `权限组中不存在模型 ${grant.schemaCode};候选:${existing.map((record) => String(first(record, "schemaCode", "functionCode") ?? "")).filter(Boolean).join(", ")}` });
327
+ beforeRecords.push(prior);
328
+ const merged = { ...prior, permissionGroupId: groupId, schemaCode: grant.schemaCode };
329
+ if (grant.visible !== undefined)
330
+ merged.visibleConfig = { pcAble: grant.visible.pc, mobileAble: grant.visible.mobile };
331
+ if (grant.rowLevel !== undefined) {
332
+ merged.dataPermissionType = grant.rowLevel.type;
333
+ if (grant.rowLevel.conditions !== undefined)
334
+ merged.conditions = grant.rowLevel.conditions;
335
+ }
336
+ if (grant.properties !== undefined)
337
+ merged.propertityPermissionGroups = mergePropertyPermissions(prior.propertityPermissionGroups, grant.properties, grant.schemaCode);
338
+ for (const [kind, requested, allowed, field] of [
339
+ ["view", grant.actions?.view, VIEW_ACTIONS, "customButtonViewPerm"],
340
+ ["form", grant.actions?.form, FORM_ACTIONS, "customButtonFormPerm"],
341
+ ]) {
342
+ if (requested === undefined)
343
+ continue;
344
+ const applied = mergeActions(prior[field], requested, allowed);
345
+ merged[field] = applied.merged;
346
+ preview.push({ schemaCode: grant.schemaCode, kind, requested, unapplied: applied.unapplied, partial: applied.partial, turnedOff: applied.turnedOff, turnedOffByContainer: applied.turnedOffByContainer });
347
+ if (applied.unapplied.length > 0)
348
+ unapplied.push({
349
+ schemaCode: grant.schemaCode,
350
+ kind,
351
+ codes: applied.unapplied,
352
+ hint: `权限组该模型${kind === "view" ? "列表" : "表单"}的全部按钮容器里都没有这些码——平台不会新建按钮;先在该模型的表单/列表设计器里建按钮,或对照 perm.groups 的读回码表`,
353
+ });
354
+ if (applied.partial.length > 0)
355
+ partial.push({
356
+ schemaCode: grant.schemaCode,
357
+ kind,
358
+ codes: applied.partial,
359
+ hint: `这些码只存在于该模型的**部分**${kind === "view" ? "列表视图" : "表单 sheet"}容器里:命中的容器已按请求翻转,缺按钮的容器不会凭空创建(平台只翻既有按钮)`,
360
+ });
361
+ if (applied.turnedOff.length > 0)
362
+ turnedOff.push({
363
+ schemaCode: grant.schemaCode,
364
+ kind,
365
+ codes: applied.turnedOff,
366
+ ...(applied.turnedOffByContainer.length > 1 ? { containers: applied.turnedOffByContainer } : {}),
367
+ });
368
+ }
369
+ mergedRecords.push(merged);
180
370
  }
371
+ return { mergedRecords, beforeRecords, preview, unapplied, partial, turnedOff };
181
372
  }
182
373
  export function authSummary(data) {
183
374
  const r = (data && typeof data === "object" ? data : {});
@@ -192,7 +383,7 @@ export function authSummary(data) {
192
383
  }
193
384
  function scopesFor(data) { return rows(data); }
194
385
  export function registerPermLane(tools) {
195
- tools.push(defineTool({ name: "perm.groups", layer: "low", kind: "read", lane: PERM_LANE, scope: PERM_TOOLS["perm.groups"].scope, description: PERM_TOOLS["perm.groups"].description, search: { intents: ["有哪些权限组", "看应用权限包", "权限组清单"] }, inputSchema: { environment: environmentArg, capability: capabilityArg, appCode: z.string().min(1), groupId: z.string().optional(), schemaCode: z.string().optional(), unitId: z.string().optional(), unitType: z.number().int().min(1).max(3).optional() }, handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
386
+ tools.push(defineTool({ name: "perm.groups", layer: "low", kind: "read", lane: PERM_LANE, scope: PERM_TOOLS["perm.groups"].scope, description: PERM_TOOLS["perm.groups"].description, search: { intents: ["有哪些权限组", "看应用权限包", "权限组清单"] }, inputSchema: { environment: environmentArg, capability: capabilityArg, appCode: z.string().min(1), groupId: z.string().optional(), schemaCode: z.string().optional(), unitId: z.string().optional(), unitType: z.number().int().min(1).max(3).describe("成员类型:1=部门(DEPT)、2=角色(ROLE)、3=用户(USER);只在按成员反查权限组时使用").optional() }, handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
196
387
  if (args.groupId || !args.unitId) {
197
388
  const path = args.groupId ? ENDPOINTS.permissionGroup : ENDPOINTS.permissionAppPackage;
198
389
  const query = args.groupId ? { id: args.groupId, appCode: args.appCode } : { appCode: args.appCode };
@@ -296,26 +487,95 @@ export function registerPermLane(tools) {
296
487
  return { userId: args.userId, appCode: args.appCode, adminBypass, ...(adminBypass ? { adminNotice: "管理员会话恒通过,不代表普通用户;本回执是管理员旁路标记。" } : {}), app: { visible: bool(first(data, "visible", "appVisible")), administrator: bool(first(data, "administrator", "isAdministrator")), allVisible: bool(first(data, "allVisible")) }, models: authSummary(data).models, fields: args.schemaCode ? authSummary(data).fields : [], rowLevel: authSummary(data).rowLevel, layers: { configResolvable: true, runtimeSessionRequired: "真实 load/write 判定受对象权限/业务调用/临时流程授权影响——本工具拒绝单值 allow/deny;验证走目标用户会话或 data.load 双读" } };
297
488
  }) }));
298
489
  writeTool({ tools, name: "perm.assign", lane: PERM_LANE, scope: PERM_TOOLS["perm.assign"].scope, description: PERM_TOOLS["perm.assign"].description, search: { intents: ["把部门加到权限组", "授权权限组", "给权限组加成员"] }, inputSchema: { appCode: z.string().min(1), groupId: z.string().min(1), units: z.array(z.object({ type: z.enum(["DEPT", "ROLE", "USER"]), id: z.string().min(1), name: z.string().optional() })).min(1), mode: z.enum(["assign", "revoke"]) }, execute: async (session, args) => { const unitType = { DEPT: 1, ROLE: 2, USER: 3 }[args.units[0].type]; const units = args.units.map((u) => ({ unitId: u.id, unitType: { DEPT: 1, ROLE: 2, USER: 3 }[u.type], name: u.name ?? "", corpId: session.enterpriseId(), appCode: args.appCode, groupId: args.groupId })); const body = args.mode === "assign" ? { permissionGroupUnits: units, permGroupInfos: [{ appCode: args.appCode, permGroupId: args.groupId }] } : { permGroupIds: [args.groupId], unitIds: args.units.map((u) => u.id), permissionGroupUnits: units, permGroupInfos: [{ appCode: args.appCode, permGroupId: args.groupId }] }; const before = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data; const performed = await wireCall(session, { path: args.mode === "assign" ? ENDPOINTS.permissionAssign : ENDPOINTS.permissionRevoke, method: "POST", body }); const after = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data; const listAfter = (await wireCall(session, { path: ENDPOINTS.permissionGroupUnits, method: "POST", body: { ...units[0], unitType, appCode: args.appCode, corpId: session.enterpriseId() } })).data; return { performed: { errcode: performed.errcode, mode: args.mode }, readback: { groups: permissionGroupRows(listAfter).map(groupView), source: "post-write listPermissionGroups readback (not write echo)", diff: { before: projectMembers(before), after: projectMembers(after) } } }; } });
299
- writeTool({ tools, name: "perm.auth", lane: PERM_LANE, scope: PERM_TOOLS["perm.auth"].scope, description: PERM_TOOLS["perm.auth"].description, search: { intents: ["配模型权限", "设行级权限", "配数据权限", "只能看自己的", "别让他看到", "只能看到自己提的", "只能查看自己", "不能看别人的"] }, inputSchema: { appCode: z.string().min(1), groupId: z.string().min(1), grants: z.array(z.object({ schemaCode: z.string().min(1), visible: z.object({ pc: z.boolean(), mobile: z.boolean() }).optional(), rowLevel: z.object({ type: z.number().int().min(1).max(6).describe("1=全部可见,2=本部门,3=仅自己,4=自定义(须 conditions),5=角色管理范围,6=均不可见"), conditions: z.array(z.array(z.unknown())).optional() }).optional(), properties: z.array(z.object({ propertyCode: z.string().optional(), schemaCode: z.string().optional().describe("可省略,继承 grants.schemaCode"), visible: z.boolean().optional(), writeAble: z.boolean().optional(), decryptAble: z.boolean().optional() })).optional(), actions: z.object({ view: z.array(z.string()).optional(), form: z.array(z.string()).optional() }).optional() })).min(1), mode: z.enum(["merge"]).default("merge") }, preflight: (args) => validateGrants(args.grants), execute: async (session, args) => { const group = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data; const existing = permissionRecords(group); const mergedRecords = []; const beforeRecords = []; for (const grant of args.grants) {
300
- const prior = existing.find((record) => String(first(record, "schemaCode", "functionCode") ?? "") === grant.schemaCode);
301
- if (!prior)
302
- throw new ToolRefusalError({ status: "refused", blocker: "permission-target-model-unknown", message: `权限组中不存在模型 ${grant.schemaCode};候选:${existing.map((record) => String(first(record, "schemaCode", "functionCode") ?? "")).filter(Boolean).join(", ")}` });
303
- beforeRecords.push(prior);
304
- const merged = { ...prior, permissionGroupId: args.groupId, schemaCode: grant.schemaCode };
305
- if (grant.visible !== undefined)
306
- merged.visibleConfig = { pcAble: grant.visible.pc, mobileAble: grant.visible.mobile };
307
- if (grant.rowLevel !== undefined) {
308
- merged.dataPermissionType = grant.rowLevel.type;
309
- if (grant.rowLevel.conditions !== undefined)
310
- merged.conditions = grant.rowLevel.conditions;
311
- }
312
- if (grant.properties !== undefined)
313
- merged.propertityPermissionGroups = mergePropertyPermissions(prior.propertityPermissionGroups, grant.properties, grant.schemaCode);
314
- if (grant.actions?.view !== undefined)
315
- merged.customButtonViewPerm = mergeActions(prior.customButtonViewPerm, grant.actions.view, VIEW_ACTIONS);
316
- if (grant.actions?.form !== undefined)
317
- merged.customButtonFormPerm = mergeActions(prior.customButtonFormPerm, grant.actions.form, FORM_ACTIONS);
318
- mergedRecords.push(merged);
319
- } const performed = await wireCall(session, { path: PERMISSION_UPDATE_FUNCTION, method: "POST", body: mergedRecords }); const refreshed = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data; const afterRecords = permissionRecords(refreshed); const afterBySchema = new Map(afterRecords.map((record) => [String(first(record, "schemaCode", "functionCode") ?? ""), record])); const afterRecordsForDiff = args.grants.map((grant) => afterBySchema.get(grant.schemaCode) ?? mergedRecords.find((record) => record.schemaCode === grant.schemaCode)); return { performed: { errcode: performed.errcode, endpoint: PERMISSION_UPDATE_FUNCTION }, readback: { data: refreshed, diff: { changed: beforeRecords.flatMap((before, index) => changedProjection(before, afterRecordsForDiff[index], args.grants[index])) } } }; } });
490
+ writeTool({
491
+ tools,
492
+ name: "perm.auth",
493
+ lane: PERM_LANE,
494
+ scope: PERM_TOOLS["perm.auth"].scope,
495
+ description: PERM_TOOLS["perm.auth"].description,
496
+ search: { intents: ["配模型权限", "设行级权限", "配数据权限", "只能看自己的", "别让他看到", "只能看到自己提的", "只能查看自己", "不能看别人的"] },
497
+ inputSchema: {
498
+ appCode: z.string().min(1),
499
+ groupId: z.string().min(1),
500
+ grants: z.array(z.object({
501
+ schemaCode: z.string().min(1),
502
+ visible: z.object({ pc: z.boolean(), mobile: z.boolean() }).optional(),
503
+ rowLevel: z.object({
504
+ type: z.number().int().min(1).max(6).describe("1=全部可见,2=本部门,3=仅自己,4=自定义(须 conditions),5=角色管理范围,6=均不可见"),
505
+ conditions: z.array(z.array(z.unknown())).optional(),
506
+ }).optional(),
507
+ properties: z.array(z.object({
508
+ propertyCode: z.string().optional(),
509
+ schemaCode: z.string().optional().describe("可省略,继承 grants.schemaCode"),
510
+ visible: z.boolean().optional(),
511
+ writeAble: z.boolean().optional(),
512
+ decryptAble: z.boolean().optional(),
513
+ })).optional(),
514
+ // r96:动作码此前是 `array<string>`——`--param grants` 只回「字符串数组」,
515
+ // 合法值只在源码里。嵌套 describe 不进 tools/list 投影(只取顶层属性
516
+ // description),所以这两句教学零字节成本地进了 `--param/--full` 面。
517
+ actions: z.object({
518
+ view: z.array(z.string().describe(actionCodeDoc("view"))).optional(),
519
+ form: z.array(z.string().describe(actionCodeDoc("form"))).optional(),
520
+ }).describe("列表/表单动作按钮开关。系统动作码是完整期望集(未列出的会被置 false);自定义按钮码(业务规则绑定的 ruleCode)也可传,但只在既有按钮上显式打开、不会被隐式关闭。平台没有的码不会凭空创建(回执 unapplied)").optional(),
521
+ })).min(1),
522
+ mode: z.enum(["merge"]).default("merge"),
523
+ },
524
+ preflight: (args) => validateGrants(args.grants),
525
+ // r96:dry-run 用 dryRunPayload(只在预览路径跑)而不是 writeLint——后者在真写路径
526
+ // 也会跑一遍,会让每次真写多读一次 297KB 的权限组体。真写与预览仍共用
527
+ // `planAuthRecords`(同一个纯函数),所以两边答案一致。
528
+ // 为什么必须在 dry-run 里说:`actions` 是完整期望集,只传 view:["ADD"] 会把该
529
+ // 模型其余已开按钮一起关掉(本轮真机踩到),而事前的 plan 只有摘要、看不见。
530
+ dryRunPayload: async (session, args) => {
531
+ const group = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data;
532
+ const planned = planAuthRecords(permissionRecords(group), args.grants, args.groupId);
533
+ return {
534
+ wouldApply: planned.preview.map((entry) => ({
535
+ schemaCode: entry.schemaCode,
536
+ kind: entry.kind,
537
+ enable: entry.requested,
538
+ ...(entry.unapplied.length > 0 ? { unapplied: entry.unapplied } : {}),
539
+ ...(entry.partial.length > 0 ? { partial: entry.partial } : {}),
540
+ ...(entry.turnedOff.length > 0 ? { turnedOff: entry.turnedOff, ...(entry.turnedOffByContainer.length > 1 ? { turnedOffByContainer: entry.turnedOffByContainer } : {}) } : {}),
541
+ })),
542
+ ...(planned.unapplied.length > 0 ? { unapplied: planned.unapplied } : {}),
543
+ ...(planned.partial.length > 0 ? { partial: planned.partial } : {}),
544
+ ...(planned.turnedOff.length > 0 ? { turnedOff: planned.turnedOff, turnedOffHint: TURNED_OFF_HINT } : {}),
545
+ note: "只读预览:本面读权限组当前按钮表,未做任何写入",
546
+ };
547
+ },
548
+ execute: async (session, args) => {
549
+ const group = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data;
550
+ const planned = planAuthRecords(permissionRecords(group), args.grants, args.groupId);
551
+ const performed = await wireCall(session, { path: PERMISSION_UPDATE_FUNCTION, method: "POST", body: planned.mergedRecords });
552
+ const refreshed = (await wireCall(session, { path: ENDPOINTS.permissionGroup, method: "GET", query: { id: args.groupId, appCode: args.appCode } })).data;
553
+ const afterRecords = permissionRecords(refreshed);
554
+ const afterBySchema = new Map(afterRecords.map((record) => [String(first(record, "schemaCode", "functionCode") ?? ""), record]));
555
+ // r96:读回缺席 ≠ 写入成功。过去这里静默回落到 mergedRecords(上送体),
556
+ // 于是「平台没保存」在 diff/models 里看起来像「改成功了」——读回不可信。
557
+ // 现在:缺席的模型不进 models、diff 以 before 对 before(零变化),并点名。
558
+ const readbackMissing = args.grants.map((grant) => grant.schemaCode).filter((schemaCode) => !afterBySchema.has(schemaCode));
559
+ const afterRecordsForDiff = args.grants.map((grant, index) => afterBySchema.get(grant.schemaCode) ?? planned.beforeRecords[index]);
560
+ return {
561
+ performed: { errcode: performed.errcode, endpoint: PERMISSION_UPDATE_FUNCTION },
562
+ readback: {
563
+ // r96:这里原来回**整个权限组原始体(本轮真机实测 297 KB)**,导致
564
+ // `diff/unapplied/turnedOff` 被挤出 stdout 预算、只剩 artifact 指针。
565
+ // 只回本次 grants 涉及的模型投影(与 perm.groups 的 auth 投影同形),
566
+ // 完整组仍可用 perm.groups --groupId 读。
567
+ models: args.grants.filter((grant) => afterBySchema.has(grant.schemaCode)).map((grant) => authProjection(afterBySchema.get(grant.schemaCode))),
568
+ diff: { changed: planned.beforeRecords.flatMap((before, index) => changedProjection(before, afterRecordsForDiff[index], args.grants[index])) },
569
+ ...(planned.unapplied.length > 0 ? { unapplied: planned.unapplied } : {}),
570
+ ...(planned.partial.length > 0 ? { partial: planned.partial } : {}),
571
+ ...(planned.turnedOff.length > 0 ? { turnedOff: planned.turnedOff, turnedOffHint: TURNED_OFF_HINT } : {}),
572
+ ...(readbackMissing.length > 0
573
+ ? { readbackMissing: { schemaCodes: readbackMissing, hint: "写后读回里没有这些模型——models/diff 对它们不可信(已按「未确认」处理,不回上送体);先用 perm.groups --groupId 复核,别当成功" } }
574
+ : {}),
575
+ readbackHint: "models 只含本次 grants 涉及的模型;完整权限组用 perm.groups --groupId 读",
576
+ },
577
+ };
578
+ },
579
+ });
320
580
  }
321
581
  //# sourceMappingURL=perm.js.map
@@ -43,13 +43,13 @@ export function dataSubmitDescription() {
43
43
  "Distinct from data.save: data.save persists as DRAFT; data.submit advances the record to COMPLETED (no workflow) or drives the workflow instance.",
44
44
  "**审批提交(带 workItemId)可省略 `formData`**:平台使用已存业务数据,且不要携带子表数组;新建记录(无 bizObjectId/workItemId)才必须传 formData。",
45
45
  `就地语义:${wire.submitInPlace};无流程 readback 必须确认 objectId 与传入 bizObjectId 相同;无 bizObjectId 的 workflowCode 新建单 → PROCESSING + workflowInstanceId,无流程 → 该行 COMPLETED。`,
46
- `既有草稿发起流程的唯一支持形状是两段式:先 data.save 带 workflowCode 暂存(${wire.workflowDraftSave}),再以返回的 workItemId 提交(带流程模型提交**必须**带 bizObjectId+workflowInstanceId+workItemId 三元——只带 bizObjectId 会答「流程实例无待办」、只缺 workItemId 会 50000;完整形状见 omc describe data.submit --example workflow-backed-data-submit,待办查询用 workitem.list)。`,
46
+ `既有草稿发起流程的唯一支持形状是两段式:先 data.save 带 workflowCode 暂存(saveWorkflow→startWorkflow(finishStart=FALSE);getReplayToken 门、sequenceStatus 与返回形状见 data.save 的 workflowCode 段),再以返回的 workItemId 提交(带流程模型提交**必须**带 bizObjectId+workflowInstanceId+workItemId 三元——只带 bizObjectId 会答「流程实例无待办」、只缺 workItemId 会 50000;完整形状见 omc describe data.submit --example workflow-backed-data-submit,待办查询用 workitem.list)。`,
47
47
  `仅无 workflowCode/workItemId/workflowInstanceId 且无 bizObjectId 时保留 save→submit 便捷链(新建记录);只要存在 workItemId 或 workflowInstanceId 就 fail-closed 拒绝(blocker submit-biz-object-id-required),零 runtime/form/submit wire。`,
48
48
  `formType 自动判定:无任何 workflowCode/workItemId/workflowInstanceId 时**先按模型自动判定**——GET workflow/isworkflow?schemaCode=true 则用 workflow/getWorkflow 解析已发布流程码并**发起流程**(formType="${wire.formTypeWorkflow}",自动先 GET getReplayToken 注入 replayToken,否则 ${wire.replayTokenErrcode} 频繁重复提交);模型无流程 → "${wire.formTypeNoWorkflow}"(无流程提交,走 live 已证链 ${wire.submitChain};单发新建对象会 ${wire.typeCastErrcode},bizObject 勿带字符串 status)或 workItemId+workflowInstanceId(审批待办,agree **顶层**通过/驳回(approval 对象里放 agree 会被静默忽略并按通过处理),**必须带 bizObjectId 指向在途单据**,否则引擎 NPE ${wire.approvalNpeErrcode})→ "${wire.formTypeWorkflow}"。即「无流程直接提交、有流程发起流程」,不再把有流程模型的新建数据落成游离 sheet 行。`,
49
- "根因提示:50000 且模型所在应用未发布 → 工具会反推并拒 app-not-published(环境相关、非普遍规律;详见 data.save 同条提示)。",
49
+ "50000 根因与 app-not-published 见 data.save 同条提示(环境相关、非普遍规律)。",
50
50
  "readback.requiredFace:published=已发布表单(权威)/draft=仅草稿/unavailable=读不到(requiredFields:[]≠无必填;真值 form.get --controls)。",
51
51
  "Pass `sheetCode` explicitly when the model has multiple sheets; otherwise the default-form sheetCode is resolved from bizsheet/get.",
52
- "计算字段:API save/update/submit 不重算计算字段(门户前端算好再提交)——写数据请在 formData 自带预算值、勿用 API 回读断言公式;带子表计算字段的模型 API 可能 NPE 50000(详见 data.save 计算字段段)。",
52
+ "计算字段语义(API 不重算、子表计算字段可能 NPE 50000)见 data.save 的「计算字段」段。",
53
53
  ]);
54
54
  }
55
55
  /** Runtime business-object data keyed by field code. */
@@ -313,6 +313,28 @@ function emptyBusinessProjection(items) {
313
313
  return items.length > 0 && businessColumns > 0;
314
314
  }
315
315
  const VIEW_PROJECTION_HINT = "该面仅回视图投影列;业务字段全 null 不代表未写入,真值用 data.load,或用 listview.configure 配列。";
316
+ const PROJECTION_MISS_HINT = "这些字段没有出现在平台返回行里 ≠ 值为空;先查 listview.get 或用 data.load 复核";
317
+ /**
318
+ * Distinguish an omitted wire key from a present empty value. A field is a
319
+ * miss only when it is absent from every returned row; a partial omission is
320
+ * deliberately left alone because it may be row-specific data.
321
+ */
322
+ function dataListProjectionMiss(rows, requestedFields) {
323
+ if (requestedFields === undefined || rows.length === 0)
324
+ return [];
325
+ return requestedFields.filter((field) => rows.every((row) => {
326
+ const data = row.data && typeof row.data === "object" ? row.data : {};
327
+ return !Object.prototype.hasOwnProperty.call(data, field);
328
+ }));
329
+ }
330
+ function projectionHintWithMiss(hint, projectionMiss) {
331
+ if (projectionMiss.length === 0)
332
+ return hint;
333
+ return {
334
+ ...(hint ?? { projectionKnown: false }),
335
+ hint: `${hint?.hint ?? ""}${hint?.hint ? ";" : ""}${PROJECTION_MISS_HINT}`,
336
+ };
337
+ }
316
338
  /**
317
339
  * 从 items 里找「null 业务列」(跨行全 null;任何一行有值就算已投影有数据),
318
340
  * 按视图列证据分类。无 null 业务列时返回 undefined(正常读取零噪音,与旧行为一致)。
@@ -1713,12 +1735,13 @@ export function registerRuntimeDataLane(tools) {
1713
1735
  const selected = fields ?? Object.keys(data).filter((field) => !["id", "bizObjectId", "schemaCode", "sequenceStatus", "createdTime", "updatedTime", "creator", "updater"].includes(field));
1714
1736
  return { id: row.bizObjectId ?? row.id ?? data.id, fields: Object.fromEntries(selected.map((field) => [field, data[field] ?? null])) };
1715
1737
  });
1738
+ const projectionMissAll = dataListProjectionMiss(collected, fields);
1716
1739
  const preview = dataListItemPreview(items);
1717
1740
  const nullProjection = items.some((item) => Object.values(item.fields).some((value) => value === null));
1718
1741
  // F2(retro 24):出现 null 业务列才读视图证据(正常读取零额外 wire);
1719
1742
  // 证据链见 projectionHintFace 的源码注释。
1720
1743
  const viewEvidence = nullProjection ? await listViewProjectionEvidence(session, args.schemaCode, args.queryCode ?? args.schemaCode) : undefined;
1721
- const projectionHintAll = projectionHintFace(items, viewEvidence);
1744
+ const projectionHintAll = projectionHintWithMiss(projectionHintFace(items, viewEvidence), projectionMissAll);
1722
1745
  return {
1723
1746
  schemaCode: args.schemaCode,
1724
1747
  ...application,
@@ -1766,6 +1789,7 @@ export function registerRuntimeDataLane(tools) {
1766
1789
  }
1767
1790
  : {}),
1768
1791
  ...(projectionHintAll !== undefined ? { projectionHint: projectionHintAll } : {}),
1792
+ ...(projectionMissAll.length > 0 ? { projectionMiss: projectionMissAll } : {}),
1769
1793
  items,
1770
1794
  };
1771
1795
  }
@@ -1859,6 +1883,7 @@ export function registerRuntimeDataLane(tools) {
1859
1883
  const selected = fields ?? Object.keys(data).filter((field) => !["id", "bizObjectId", "schemaCode", "sequenceStatus", "createdTime", "updatedTime", "creator", "updater"].includes(field));
1860
1884
  return { id: row.bizObjectId ?? row.id ?? data.id, fields: Object.fromEntries(selected.map((field) => [field, data[field] ?? null])) };
1861
1885
  });
1886
+ const projectionMissPaged = dataListProjectionMiss(page.content, fields);
1862
1887
  // Live 2026-10-19: when a model has NO configured list view, the
1863
1888
  // platform projects only system columns — every business field comes
1864
1889
  // back null while `data.load` shows the real values. That reads as
@@ -1899,7 +1924,7 @@ export function registerRuntimeDataLane(tools) {
1899
1924
  // projectionHintFace / listViewProjectionEvidence 的源码注释。
1900
1925
  const hasNullValue = items.some((item) => Object.values(item.fields).some((value) => value === null));
1901
1926
  const viewEvidence = hasNullValue ? await listViewProjectionEvidence(session, args.schemaCode, args.queryCode ?? args.schemaCode) : undefined;
1902
- const projectionHintPaged = projectionHintFace(items, viewEvidence);
1927
+ const projectionHintPaged = projectionHintWithMiss(projectionHintFace(items, viewEvidence), projectionMissPaged);
1903
1928
  // F6 工单 05b:只有本页行真的内联了子表数组才给一句(否则零字节);
1904
1929
  // 取第一条命中行,命令里的 schemaCode/childSchemaCode/bizObjectId 都是真值。
1905
1930
  const inlineChild = items
@@ -1939,6 +1964,7 @@ export function registerRuntimeDataLane(tools) {
1939
1964
  })(),
1940
1965
  ...(choiceFilterFields.length > 0 && Number(total ?? 0) === 0 ? { filterValueHint: choiceFilterValueHint(choiceFilterFields) } : {}),
1941
1966
  ...(projectionHintPaged !== undefined ? { projectionHint: projectionHintPaged } : {}),
1967
+ ...(projectionMissPaged.length > 0 ? { projectionMiss: projectionMissPaged } : {}),
1942
1968
  totalPages,
1943
1969
  itemsCount: items.length,
1944
1970
  itemsReturned: items.length,
@@ -185,7 +185,7 @@ export const WORKFLOW_LANE_CONTRACT = Object.freeze({
185
185
  }),
186
186
  "workflow.publish": Object.freeze({
187
187
  scope: WORKFLOW_SCOPE,
188
- description: "发布工作流模板(`/api/api/workflow/publish`,raw template JSON body)。`template` **必填**(省略被拒 tool-input-invalid: template Required)。",
188
+ description: "发布工作流模板(`/api/api/workflow/publish`,raw template JSON body)。`template` **可省略**:省略即把已存草稿原样发布(先 workflow.update 写草稿);要带模板时形状见 `omc describe workflow.update --param template`。",
189
189
  }),
190
190
  "workflow.bindRule": Object.freeze({
191
191
  scope: WORKFLOW_SCOPE,
@@ -2195,6 +2195,40 @@ export async function resolveWorkflowArg(session, args) {
2195
2195
  const workflowCode = code && typeof code.workflowCode === "string" && code.workflowCode ? code.workflowCode : null;
2196
2196
  return workflowCode;
2197
2197
  }
2198
+ /**
2199
+ * BUG-05-F8: `isworkflow` can lag behind the real workflow binding. Keep the
2200
+ * ordinary probe hot path unchanged, and only use the bounded model index when
2201
+ * that probe says nothing. The index is intentionally not the high-level
2202
+ * workflow.list tool (which would add summaries/details to this point lookup).
2203
+ */
2204
+ async function resolveWorkflowArgWithFallback(session, args) {
2205
+ if (args.workflowCode)
2206
+ return { workflowCode: args.workflowCode };
2207
+ if (!args.schemaCode)
2208
+ throw new ToolInputError({ status: "error", blocker: "tool-input-invalid", tool: "workflow.*", message: "需要 workflowCode,或 schemaCode(工具内部解析该模型的流程)" });
2209
+ const direct = await resolveWorkflowArg(session, args);
2210
+ if (direct)
2211
+ return { workflowCode: direct, resolution: "schemaCode-bind" };
2212
+ // 直接探针的唯一门槛是 `workflow/isworkflow`——真机里它会滞后于真实绑定。
2213
+ // 因此缺席时**绕过该门**直接问 getWorkflow(不问应用树:单点解析不需要
2214
+ // 模型清单,省一次 wire),拿到平台真实 workflowCode 才继续。
2215
+ const base = {
2216
+ workflowCode: null,
2217
+ resolution: "schemaCode-probe-plus-fallback",
2218
+ scannedModels: 1,
2219
+ nextCommand: `omc call workflow.list --args '{"applicationCode":"<应用code>"}'(按模型索引复核;不要据此断言流程不存在)`,
2220
+ };
2221
+ try {
2222
+ const linked = (await wireCall(session, { path: ENDPOINTS.workflowGetBySchema, query: { schemaCode: args.schemaCode } })).data;
2223
+ const workflowCode = linked && typeof linked.workflowCode === "string" && linked.workflowCode ? linked.workflowCode : null;
2224
+ if (workflowCode)
2225
+ return { ...base, workflowCode, resolution: "workflow-list-fallback" };
2226
+ }
2227
+ catch {
2228
+ return { ...base, readFailed: true, nextCommand: `omc call workflow.list --args '{"applicationCode":"<应用code>"}'(getWorkflow 读取失败;不要断言流程不存在)` };
2229
+ }
2230
+ return base;
2231
+ }
2198
2232
  export async function scanModelWorkflowBindings(session, schemaCode) {
2199
2233
  const workflowCode = await resolveWorkflowArg(session, { schemaCode });
2200
2234
  if (!workflowCode)
@@ -2815,9 +2849,16 @@ export function registerWorkflowLane(tools) {
2815
2849
  }
2816
2850
  return { keyword: participantSearch, scannedModels, withWorkflow, hits, hitsCount: hits.length };
2817
2851
  }
2818
- const workflowCode = await resolveWorkflowArg(session, args);
2852
+ const resolved = await resolveWorkflowArgWithFallback(session, args);
2853
+ const workflowCode = resolved.workflowCode;
2819
2854
  if (!workflowCode)
2820
- return { schemaCode: args.schemaCode, exists: false, published: false, note: "该模型没有已发布流程(workflow/isworkflow=false);先 workflow.create 再 publish" };
2855
+ return {
2856
+ schemaCode: args.schemaCode,
2857
+ exists: false,
2858
+ published: false,
2859
+ ...resolved,
2860
+ note: "流程解析未命中;可能是平台索引不同步或扫描不完整,不据此断言流程不存在。先 workflow.list 确认;确认无绑定后再 workflow.create",
2861
+ };
2821
2862
  let pub;
2822
2863
  try {
2823
2864
  pub = await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode } });
@@ -2840,6 +2881,9 @@ export function registerWorkflowLane(tools) {
2840
2881
  workflowCode,
2841
2882
  exists: true,
2842
2883
  published,
2884
+ ...(resolved.resolution ? { resolution: resolved.resolution } : {}),
2885
+ ...(resolved.scannedModels !== undefined ? { scannedModels: resolved.scannedModels } : {}),
2886
+ ...(resolved.partial ? { partial: true } : {}),
2843
2887
  ...(data && !published ? { note: "平台对未发布流程仍返回草稿形态——此读回不能当作已发布证据;以 published:true / templateType:PUBLISH 为准(先 workflow.publish)" } : {}),
2844
2888
  data: pub.data,
2845
2889
  };
@@ -3114,7 +3158,7 @@ export function registerWorkflowLane(tools) {
3114
3158
  lane: WORKFLOW_LANE,
3115
3159
  scope: WORKFLOW_TOOLS["workflow.publish"].scope,
3116
3160
  description: WORKFLOW_TOOLS["workflow.publish"].description,
3117
- inputSchema: { schemaCode: z.string().min(1), code: z.string().min(1).describe("流程编码——本参数名是 code,传 workflowCode 会被 schema 拒绝"), template: workflowTemplateArg.optional() },
3161
+ inputSchema: { schemaCode: z.string().min(1), code: z.string().min(1).describe("流程编码——本参数名是 code,传 workflowCode 会被 schema 拒绝"), template: workflowTemplateArg.describe("可省略——省略即把已存草稿原样发布(平台原生路径,先 workflow.update 写草稿)。要带模板时形状/连线/参与人/体积铁律与 workflow.update 的 template 完全同源,见 `omc describe workflow.update --param template`(此处不复制第二份,防漂移)").optional() },
3118
3162
  execute: async (session, args) => {
3119
3163
  // An absent template publishes the stored draft as-is — the platform's own
3120
3164
  // path. The schema is optional so the contract no longer contradicts it.
@@ -3570,38 +3614,60 @@ export function registerWorkflowLane(tools) {
3570
3614
  const performed = await wireCall(session, { path: ENDPOINTS.workflowUpdate, method: "POST", body });
3571
3615
  const shouldPublish = args.publish !== false;
3572
3616
  let publishMarked = false;
3617
+ // issue 2026-11 F1:发布后必须读**发布面**。此前只读草稿,草稿里空
3618
+ // customBtns 容器还在、发布面却被平台归一化成 buttonPermission:null——
3619
+ // 回执说「容器内按钮 enabled:false」而真实效果是「容器没了」,调用方据此
3620
+ // 判断「仍命中节点权限分支」,把方案引向错误结论。
3621
+ let authoritative = null;
3573
3622
  if (shouldPublish) {
3574
3623
  const publishPerformed = await wireCall(session, { path: ENDPOINTS.workflowPublish, method: "POST", body });
3575
3624
  assertWorkflowWriteAccepted(publishPerformed, "workflow.setButtons", args.workflowCode);
3576
3625
  const pub = await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode: args.workflowCode } });
3577
- const published = (pub.data ?? null);
3578
- publishMarked = published !== null && (published.templateType === "PUBLISH" || published.published === true);
3626
+ authoritative = (pub.data ?? null);
3627
+ publishMarked = authoritative !== null && (authoritative.templateType === "PUBLISH" || authoritative.published === true);
3579
3628
  }
3580
- const readback = (await wireCall(session, { path: ENDPOINTS.workflowGetDraft, query: { workflowCode: args.workflowCode } })).data;
3629
+ const readback = shouldPublish
3630
+ ? authoritative
3631
+ : (await wireCall(session, { path: ENDPOINTS.workflowGetDraft, query: { workflowCode: args.workflowCode } })).data;
3581
3632
  const nodeButtons = (readback ? readback.activities : draft.activities);
3582
3633
  const rows = Array.isArray(nodeButtons)
3583
3634
  ? nodeButtons
3584
3635
  : nodeButtons && typeof nodeButtons === "object"
3585
3636
  ? Object.values(nodeButtons)
3586
3637
  : [];
3638
+ // 以权威面为准区分三种真实状态:容器不存在 / 容器在但按钮全禁用 / 有启用按钮。
3587
3639
  const state = args.nodes.map((node) => {
3588
3640
  const row = rows.find((entry) => String(entry.activityCode ?? "") === node.activityCode) ?? {};
3589
- const bp = (row.buttonPermission ?? {});
3641
+ const rawPerm = row.buttonPermission;
3642
+ const buttonPermissionIsNull = rawPerm === null || rawPerm === undefined;
3643
+ const bp = (rawPerm ?? {});
3590
3644
  const btns = Array.isArray(bp.customBtns) ? bp.customBtns : [];
3645
+ const enabled = btns.filter((button) => button.enabled === true).map((button) => String(button.code ?? ""));
3646
+ const disabled = btns.filter((button) => button.enabled !== true).map((button) => String(button.code ?? ""));
3647
+ const containers = Array.isArray(bp.childTableBtns) ? bp.childTableBtns.length : 0;
3591
3648
  return {
3592
3649
  activityCode: node.activityCode,
3593
- enabled: btns.filter((button) => button.enabled === true).map((button) => String(button.code ?? "")),
3594
- disabled: btns.filter((button) => button.enabled !== true).map((button) => String(button.code ?? "")),
3650
+ enabled,
3651
+ disabled,
3652
+ buttonPermissionIsNull,
3653
+ mode: buttonPermissionIsNull ? "absent" : enabled.length > 0 ? "enabled-in-container" : "disabled-in-container",
3654
+ childTableButtonContainerCount: containers,
3595
3655
  };
3596
3656
  });
3657
+ const cleared = state.filter((entry) => entry.buttonPermissionIsNull);
3597
3658
  return {
3598
3659
  performed: { errcode: performed.errcode, publishRequested: shouldPublish, nodes: args.nodes.map((node) => node.activityCode) },
3599
3660
  readback: {
3600
3661
  workflowCode: args.workflowCode,
3601
3662
  nodes: state,
3602
3663
  published: publishMarked,
3664
+ readbackFace: shouldPublish ? "published" : "draft",
3603
3665
  buttonNames: names,
3604
- note: "节点未列出的按钮被置为 enabled:false(不删除子表按钮配置);表单页只在 enabled:true 的节点显示该按钮",
3666
+ buttonPermissionIsNull: cleared.length > 0,
3667
+ ...(cleared.length > 0 ? { clearedNodes: cleared.map((entry) => entry.activityCode) } : {}),
3668
+ note: cleared.length > 0
3669
+ ? "权威读回显示这些节点的 buttonPermission 为 null(容器被平台清空/归一化,不是容器仍在但按钮均被禁用):节点不再命中节点权限分支,表单按钮会回落到权限组。子表按钮配置也未保留——需要保留时请只传有内容的 buttonCodes,不要传空数组。"
3670
+ : "权威读回显示 buttonPermission 容器仍在;未列出的表单按钮为 enabled:false,子表按钮配置保留。表单页只在 enabled:true 的节点显示该按钮。",
3605
3671
  },
3606
3672
  };
3607
3673
  },
@@ -967,7 +967,7 @@ export function projectResultExtract(result, paths, keysOnly, retry) {
967
967
  }
968
968
  return out;
969
969
  }
970
- const SINGLE_PATH_META_KEYS = ["from", "artifactId", "sha256", "truncated", "truncatedKeys", "itemsCount", "total", "projectionHint"];
970
+ const SINGLE_PATH_META_KEYS = ["from", "artifactId", "sha256", "truncated", "truncatedKeys", "itemsCount", "total", "projectionHint", "projectionMiss"];
971
971
  const SINGLE_PATH_ENTRY_META_KEYS = ["mapped", "nullEntries", "nonNullEntries", "missedEntries", "from", "autoStripped", "hint"];
972
972
  export function unwrapSinglePathProjection(projected) {
973
973
  const extracts = projected.extract;
@@ -160,11 +160,11 @@ const READ_SHAPES = {
160
160
  // A2 locator:模板摘要 activities[].code ↔ 实例/待办 activityCode(Activity.java:26-30
161
161
  // 存储面原生键就是 activityCode/activityType/activityName;code/name/type 是摘要投影)。
162
162
  locator: { templateActivityKey: "code", instanceKey: "activityCode", workitemKey: "activityCode" },
163
- keys: ["status", "workflowCode", "exists", "published", "workflowSummary:{workflowCode,templateType,activities:array<{index,code,type,name,bizActions?:{<nodeEvent>:[ruleCode]},systemBizActions?:{bizActionType,ruleCodes:[code]}}>,edges:array<{from,to}>,ruleBindings:array<{...}>,nodeRuleBindings?,systemRuleBindings?,ruleBindingCount,originateActivity:{code,type,name,participant}}", "activities:array<{code,name,type,bizActions?,systemBizActions?}>(投影)", "propertyPermissionsCount", "version", "summaryHint", "truncatedKeys?", "omittedKeys?", "truncated?", "data?(外置时 null,完整模板在 detailArtifactId)", "omittedShape?", "omittedNote?", "environmentFingerprint", "detailArtifactId?", "detailSha256?", "fetch?"],
164
- notes: ["规则绑定三个面:流程级 ruleBindings、节点事件 activities[].bizActions、SYSTEM_ACTIVITY 顶层 activities[].systemBizActions(规则绑在系统活动节点本身、激活时执行)——三个面看完再下「没绑」结论;完整模板在 data(外置 detailArtifactId),要深层字段时投影写到叶子(如 --jq 'data.activities[].bizActions')——写整棵父节点会因总量超限再次被外置;activities[] 键=code/name/type,实例/待办面(workflow.instanceActivity、workitem.list)同一概念叫 activityCode/activityName(workitem 行没有 activityType)——跨面对照别拿错键"],
163
+ keys: ["status", "workflowCode", "exists", "published", "workflowSummary:{workflowCode,templateType,activities:array<{index,code,type,name,bizActions?:{<nodeEvent>:[ruleCode]},systemBizActions?:{bizActionType,ruleCodes:[code]}}>,edges:array<{from,to,ruleConditionGroup?:[[{currentDataItem,bizPropertyType,conditionType,value}]],utilizeElse?,popupType?,childMatchType?}>,ruleBindings:array<{...}>,nodeRuleBindings?,systemRuleBindings?,ruleBindingCount,originateActivity:{code,type,name,participant}}", "activities:array<{code,name,type,bizActions?,systemBizActions?}>(投影)", "propertyPermissionsCount", "version", "summaryHint", "truncatedKeys?", "omittedKeys?", "truncated?", "data?(外置时 null,完整模板在 detailArtifactId)", "omittedShape?", "omittedNote?", "environmentFingerprint", "detailArtifactId?", "detailSha256?", "fetch?"],
164
+ notes: ["规则绑定三个面:流程级 ruleBindings、节点事件 activities[].bizActions、SYSTEM_ACTIVITY 顶层 activities[].systemBizActions(规则绑在系统活动节点本身、激活时执行)——三个面看完再下「没绑」结论;完整模板在 data(外置 detailArtifactId),要深层字段时投影写到叶子(如 --jq 'data.activities[].bizActions')——写整棵父节点会因总量超限再次被外置;activities[] 键=code/name/type,实例/待办面(workflow.instanceActivity、workitem.list)同一概念叫 activityCode/activityName(workitem 行没有 activityType)——跨面对照别拿错键", "条件分支在 edges[]:带 ruleConditionGroup 的边就是条件边(条件行含 currentDataItem/bizPropertyType/conditionType/value),utilizeElse:true 是该节点的 else 出口;摘要已含这些字段——确认「金额>1000→主管」这类分支不必再取 data 全量模板"],
165
165
  },
166
166
  "workflow.get_draft": {
167
- keys: ["status", "workflowCode", "exists", "workflowSummary:{workflowCode,templateType,activities:array<{index,code,type,name,bizActions?:{<nodeEvent>:[ruleCode]},systemBizActions?:{bizActionType,ruleCodes:[code]}}>,edges:array<{from,to}>,ruleBindings:array<{...}>,nodeRuleBindings?,systemRuleBindings?,ruleBindingCount,originateActivity:{code,type,name,participant}}", "activities:array<{code,name,type,bizActions?,systemBizActions?}>(投影)", "propertyPermissionsCount", "version", "summaryHint", "truncatedKeys?", "omittedKeys?", "truncated?", "data?(外置时 null,完整模板在 detailArtifactId)", "omittedShape?", "omittedNote?", "environmentFingerprint", "detailArtifactId?", "detailSha256?", "fetch?"],
167
+ keys: ["status", "workflowCode", "exists", "workflowSummary:{workflowCode,templateType,activities:array<{index,code,type,name,bizActions?:{<nodeEvent>:[ruleCode]},systemBizActions?:{bizActionType,ruleCodes:[code]}}>,edges:array<{from,to,ruleConditionGroup?:[[{currentDataItem,bizPropertyType,conditionType,value}]],utilizeElse?,popupType?,childMatchType?}>,ruleBindings:array<{...}>,nodeRuleBindings?,systemRuleBindings?,ruleBindingCount,originateActivity:{code,type,name,participant}}", "activities:array<{code,name,type,bizActions?,systemBizActions?}>(投影)", "propertyPermissionsCount", "version", "summaryHint", "truncatedKeys?", "omittedKeys?", "truncated?", "data?(外置时 null,完整模板在 detailArtifactId)", "omittedShape?", "omittedNote?", "environmentFingerprint", "detailArtifactId?", "detailSha256?", "fetch?"],
168
168
  notes: ["与 workflow.get_published 同形(少了 published 键);节点绑定看 activities[].bizActions、系统活动顶层看 systemBizActions;templateType=DRAFT;深层字段投影写到叶子,完整模板在 data/detailArtifactId"],
169
169
  },
170
170
  // R88 #1:双面排查面。returnsFace 只显 notes 首条——教学并进首条。
package/dist/read.js CHANGED
@@ -44,8 +44,11 @@ export async function governedRead(ctx, tool, args, execute, options = {}) {
44
44
  return refusalFromCoverage(error);
45
45
  }
46
46
  }
47
+ // issue 2026-11 F5:catch 里也要说清「打的是哪台」,所以把 session 提到 try 外。
48
+ let sessionRef;
47
49
  try {
48
50
  const session = await ctx.sessions.session(args.environment);
51
+ sessionRef = session;
49
52
  const environmentFingerprint = safeFingerprint(session);
50
53
  const result = await execute(session);
51
54
  if (result.status === "refused" || result.status === "uncertain")
@@ -111,7 +114,17 @@ export async function governedRead(ctx, tool, args, execute, options = {}) {
111
114
  }
112
115
  catch (error) {
113
116
  if (isUncertainWireError(error))
114
- return { status: "uncertain", frozen: true, reason: `wire-transport:${wireErrorKind(error)}`, detail: error.message };
117
+ return {
118
+ status: "uncertain",
119
+ frozen: true,
120
+ reason: `wire-transport:${wireErrorKind(error)}`,
121
+ detail: error.message,
122
+ // issue 2026-11 F5:传输失败时把「到底打的是哪台」一起回出来——真机会话里
123
+ // env list 是 cwd 作用域,agent 静默落到全局 default 的另一台主机,只看
124
+ // detail 无从判断。configRoot/项目根用 `omc env list` 复核。
125
+ ...(sessionRef !== undefined ? { environment: sessionRef.environmentName, baseUrl: sessionRef.profile.baseUrl } : {}),
126
+ environmentHint: "env 清单随 cwd 变(项目根 .omc-env/.omc-envs + 配置根);`omc env list` 首行回显 configRoot/projectRoot",
127
+ };
115
128
  if (error instanceof WireError)
116
129
  return { status: "refused", blocker: `wire-${error.kind}`, errcode: error.errcode, message: error.message, ...(error.diagnostic ? { diagnostic: error.diagnostic } : {}), ...(error.hint ? { hint: error.hint } : {}) };
117
130
  throw error;
package/dist/rollback.js CHANGED
@@ -353,8 +353,30 @@ export async function applyRollback(ref, options, context) {
353
353
  // explicitification tolerance can never hide a real mismatch past limit.
354
354
  verify = residual.nonAdditionCount === 0 ? "restored" : "mismatch";
355
355
  }
356
+ const mismatch = verify === "mismatch";
357
+ // issue 2026-11 F2:mismatch 的下一步必须能真的把目标改回去。优先给**可粘贴的
358
+ // 单条补偿命令**(取 inverse 的第一条;参数过大时退回 rollback plan/apply,
359
+ // 避免把 1MB 模板塞进回执)。
360
+ const inverseCall = plan.inverse.kind === "calls" ? plan.inverse.calls[0] : undefined;
361
+ const inverseArgs = inverseCall === undefined ? undefined : { ...inverseCall.args, environment: entry.environment };
362
+ const inverseJson = inverseArgs === undefined ? undefined : JSON.stringify(inverseArgs);
363
+ const pasteable = inverseCall !== undefined && inverseJson !== undefined && inverseJson.length <= 1_200;
364
+ const nextCommand = !mismatch
365
+ ? undefined
366
+ : pasteable
367
+ ? `omc call ${inverseCall.tool} --env ${entry.environment} --args '${inverseJson}'`
368
+ : `omc rollback plan ${entry.seq} --env ${entry.environment}`;
369
+ const compensation = !mismatch
370
+ ? undefined
371
+ : pasteable
372
+ ? { tool: inverseCall.tool, args: inverseArgs, why: "权威读回与 before 不一致;这条是本次恢复原本要执行的写,可直接重放" }
373
+ : {
374
+ tool: "rollback.plan",
375
+ args: { seq: entry.seq, environment: entry.environment },
376
+ why: `权威读回与 before 不一致;恢复参数较大(${inverseJson?.length ?? 0}B)不回内联——先看 plan 的 diff,再 omc rollback apply ${entry.seq} 重试`,
377
+ };
356
378
  return {
357
- status: "ok",
379
+ status: mismatch ? "refused" : "ok",
358
380
  rollbackOf: { seq: entry.seq, tool: entry.tool, target: entry.target },
359
381
  calls: results,
360
382
  // B1: the shared step-identity projection (same shape as apply_changes /
@@ -370,7 +392,16 @@ export async function applyRollback(ref, options, context) {
370
392
  matchesBefore: verify === "restored",
371
393
  recoveredTo: { seq: entry.seq, ts: entry.ts },
372
394
  ...(progressFile !== undefined ? { progressFile } : {}),
373
- ...(verify === "mismatch" ? { beforeSha, restoredSha, message: "恢复调用已完成但读回与 before 存在值冲突(非默认显式化):立即人工核对目标现态(omc rollback plan <seq> 的 diff 可复看差异)" } : {}),
395
+ ...(mismatch
396
+ ? {
397
+ beforeSha,
398
+ restoredSha,
399
+ blocker: "rollback-readback-mismatch",
400
+ message: "恢复调用已完成但权威读回与 before 不一致,不得标记成功;按 nextCommand 补偿后重跑 rollback plan 复核",
401
+ nextCommand,
402
+ compensation,
403
+ }
404
+ : {}),
374
405
  hint: "本次恢复的每次调用都走了完整写闸门并已记 journal;恢复本身可再回滚(rollback plan <新 seq>)",
375
406
  };
376
407
  }
package/dist/session.js CHANGED
@@ -23,6 +23,9 @@ export class CloudPivotSession {
23
23
  version;
24
24
  /** r86(retro issue 17):原始版本串("AI-Platform-v1.1.25" 这类含产品线前缀的完整值)。 */
25
25
  rawVersion;
26
+ versionSource;
27
+ /** F7:license 载荷留作读面复用(buildTime/licenseType 只在 license/info 有)。 */
28
+ licenseInfoValue;
26
29
  /**
27
30
  * Non-fatal login caveats (e.g. the `client` blob in system/config was
28
31
  * absent or unreadable, so the token request carried no client_secret).
@@ -67,32 +70,13 @@ export class CloudPivotSession {
67
70
  administrator: cached.administrator,
68
71
  ...(cached.accountIdentity !== undefined ? { accountIdentity: cached.accountIdentity } : {}),
69
72
  };
70
- if (cached.version !== undefined) {
71
- this.version = cached.version;
72
- if (cached.rawVersion !== undefined)
73
- this.rawVersion = cached.rawVersion;
74
- }
75
- else {
76
- // Legacy cache written while version evidence was unavailable: probe the
77
- // public system config once and backfill the cache, otherwise every
78
- // later write stays fail-closed even after the probe itself is fixed
79
- // (live 2026-10-17: AI-Platform deployment, pcServerUrl null).
80
- const systemConfig = await core
81
- .fetchCloudPivotSystemConfig(this.profile.baseUrl, undefined, fetch, core.cloudPivotTenantHeaders(this.profile.engineCode))
82
- .catch(() => undefined);
83
- this.version = detectVersion(systemConfig);
84
- this.rawVersion = detectRawVersion(systemConfig);
85
- if (this.version !== undefined) {
86
- this.tokenCache?.save({
87
- token: cached.token,
88
- enterpriseId: cached.enterpriseId,
89
- administrator: cached.administrator,
90
- ...(cached.accountIdentity !== undefined ? { accountIdentity: cached.accountIdentity } : {}),
91
- version: this.version,
92
- ...(this.rawVersion !== undefined ? { rawVersion: this.rawVersion } : {}),
93
- });
94
- }
95
- }
73
+ const evidence = await this.probeVersionEvidence(cached.version, cached.rawVersion);
74
+ this.version = evidence.version;
75
+ this.rawVersion = evidence.rawVersion;
76
+ this.versionSource = evidence.source;
77
+ // 缓存命中路径只在**拿到证据**时回写(探测失败不得凭空改写缓存)。
78
+ if (evidence.version !== undefined)
79
+ this.saveCachedLogin(this.loginResult, evidence);
96
80
  return this.loginResult;
97
81
  }
98
82
  const core = await omcCore();
@@ -115,16 +99,11 @@ export class CloudPivotSession {
115
99
  ...(systemConfig ? { systemConfig } : {}),
116
100
  });
117
101
  this.loginNotesValue = authenticator.loginNotes();
118
- this.version = detectVersion(systemConfig);
119
- this.rawVersion = detectRawVersion(systemConfig);
120
- this.tokenCache?.save({
121
- token: this.loginResult.token,
122
- enterpriseId: this.loginResult.enterpriseId,
123
- administrator: this.loginResult.administrator,
124
- ...(this.loginResult.accountIdentity !== undefined ? { accountIdentity: this.loginResult.accountIdentity } : {}),
125
- ...(this.version !== undefined ? { version: this.version } : {}),
126
- ...(this.rawVersion !== undefined ? { rawVersion: this.rawVersion } : {}),
127
- });
102
+ const evidence = await this.probeVersionEvidence(undefined, undefined, systemConfig);
103
+ this.version = evidence.version;
104
+ this.rawVersion = evidence.rawVersion;
105
+ this.versionSource = evidence.source;
106
+ this.saveCachedLogin(this.loginResult, evidence);
128
107
  return this.loginResult;
129
108
  }
130
109
  /** Version-family evidence; absent evidence returns undefined (fail closed upstream). */
@@ -135,6 +114,66 @@ export class CloudPivotSession {
135
114
  rawSystemVersion() {
136
115
  return this.rawVersion;
137
116
  }
117
+ versionEvidenceSource() {
118
+ return this.versionSource;
119
+ }
120
+ /** F7:登录期已探测过的 license/info 载荷;读面据此免去第二次 wire。 */
121
+ licenseInfo() {
122
+ return this.licenseInfoValue;
123
+ }
124
+ async probeVersionEvidence(cachedVersion, cachedRawVersion, knownSystemConfig) {
125
+ // F7(issue 05):缓存命中**不意味着**要重新探测。已有版本且属于锚定族
126
+ // (或本来就是 license 证据)就零 wire 直接用;只有「没有版本」或「缓存说
127
+ // 自己不是 8.6 族」时才重探——后者正是真机 1.1.25 误报的场景。
128
+ if (cachedVersion !== undefined && (this.versionSource === "license/info" || cachedVersion.startsWith("8.6.")))
129
+ return { version: cachedVersion, rawVersion: cachedRawVersion, source: this.versionSource ?? "system-config" };
130
+ let license;
131
+ try {
132
+ // license/info 是管理员端点:401/403/404 都属「该产品线没这面」,直接回退。
133
+ // 用裸 http(不走 this.request):后者对 401 会清 token cache 重登,而非管理员
134
+ // 会话读 license 恰好是 401,会把缓存打掉。
135
+ const response = await (await this.http()).request({ path: "/api/license/info", method: "GET", headers: this.headers() });
136
+ if (response.status >= 200 && response.status < 300) {
137
+ const body = response.body;
138
+ const data = body && typeof body === "object" && body.data && typeof body.data === "object"
139
+ ? body.data
140
+ : response.body;
141
+ if (data && typeof data === "object")
142
+ license = data;
143
+ }
144
+ }
145
+ catch {
146
+ // license 面不可达:回退 system/config。
147
+ }
148
+ this.licenseInfoValue = license;
149
+ const licenseVersion = detectVersion(license);
150
+ if (licenseVersion !== undefined)
151
+ return { version: licenseVersion, rawVersion: detectRawVersion(license), source: "license/info" };
152
+ let systemConfig = knownSystemConfig;
153
+ if (!systemConfig) {
154
+ const core = await omcCore();
155
+ systemConfig = await core
156
+ .fetchCloudPivotSystemConfig(this.profile.baseUrl, undefined, fetch, core.cloudPivotTenantHeaders(this.profile.engineCode))
157
+ .catch(() => undefined);
158
+ }
159
+ const publicVersion = detectVersion(systemConfig);
160
+ if (publicVersion !== undefined)
161
+ return { version: publicVersion, rawVersion: detectRawVersion(systemConfig), source: "system-config" };
162
+ if (cachedVersion !== undefined)
163
+ return { version: cachedVersion, rawVersion: cachedRawVersion, source: "token-cache" };
164
+ return {};
165
+ }
166
+ saveCachedLogin(login, evidence) {
167
+ this.tokenCache?.save({
168
+ token: login.token,
169
+ enterpriseId: login.enterpriseId,
170
+ administrator: login.administrator,
171
+ ...(login.accountIdentity !== undefined ? { accountIdentity: login.accountIdentity } : {}),
172
+ ...(evidence.version !== undefined ? { version: evidence.version } : {}),
173
+ ...(evidence.rawVersion !== undefined ? { rawVersion: evidence.rawVersion } : {}),
174
+ ...(evidence.source !== undefined ? { versionSource: evidence.source } : {}),
175
+ });
176
+ }
138
177
  /** Non-fatal login caveats; empty when the login was fully nominal. */
139
178
  loginNotes() {
140
179
  return this.loginNotesValue;
@@ -227,7 +266,9 @@ export class CloudPivotSession {
227
266
  function detectVersion(systemConfig) {
228
267
  if (!systemConfig)
229
268
  return undefined;
230
- for (const key of ["version", "sysVersion", "systemVersion", "productVersion", "serverVersion"]) {
269
+ // 真机 8.6 用 systemVersion;1.1.x 的公共配置与旧缓存用 version——都来自
270
+ // system/config 响应,不是 bundle 版本(bundle 猜版本是 F7 的原始误报来源)。
271
+ for (const key of ["systemVersion", "version", "sysVersion", "productVersion", "serverVersion"]) {
231
272
  const value = systemConfig[key];
232
273
  if (typeof value !== "string")
233
274
  continue;
@@ -246,7 +287,7 @@ function detectVersion(systemConfig) {
246
287
  function detectRawVersion(systemConfig) {
247
288
  if (!systemConfig)
248
289
  return undefined;
249
- for (const key of ["version", "sysVersion", "systemVersion", "productVersion", "serverVersion"]) {
290
+ for (const key of ["systemVersion", "version", "sysVersion", "productVersion", "serverVersion"]) {
250
291
  const value = systemConfig[key];
251
292
  if (typeof value === "string" && value.trim().length > 0)
252
293
  return value.trim();
package/dist/write.js CHANGED
@@ -116,6 +116,11 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
116
116
  frozen: true,
117
117
  reason: `wire-transport:${wireErrorKind(error)}`,
118
118
  detail: error.message,
119
+ // issue 2026-11 F5:同读面——把环境名与 baseUrl 一起回出来,避免
120
+ // 「cwd 落到全局 default 的另一台主机」被误判成参数问题。
121
+ environment: session.environmentName,
122
+ baseUrl: session.profile.baseUrl,
123
+ environmentHint: "env 清单随 cwd 变(项目根 .omc-env/.omc-envs + 配置根);`omc env list` 首行回显 configRoot/projectRoot",
119
124
  message: "write outcome cannot be established; frozen — re-discover before retrying; never assume success",
120
125
  // r46 实证:data.submit 传输中断但平台已落行,按回执盲重试产生重复数据
121
126
  // 再连锁清理。uncertain ≠ 失败——先按业务键查重再决定。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.6.97",
3
+ "version": "0.6.98",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "commander": "14.0.3",
59
- "omc-core": "0.6.97",
59
+ "omc-core": "0.6.98",
60
60
  "proper-lockfile": "4.1.2",
61
61
  "write-file-atomic": "6.0.0",
62
62
  "zod": "^3.23.8",
@@ -74,6 +74,6 @@
74
74
  "directory": "packages/omc-cli"
75
75
  },
76
76
  "optionalDependencies": {
77
- "@stalfh233/omc-fake-platform": "0.6.97"
77
+ "@stalfh233/omc-fake-platform": "0.6.98"
78
78
  }
79
79
  }