@stalfh233/omc-cli 0.8.14 → 0.8.15

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/artifacts.js CHANGED
@@ -77,8 +77,9 @@ export function isWithinRoot(root, candidate) {
77
77
  /**
78
78
  * Resolve a WRITE target inside the configuration root (mirrors
79
79
  * assertSafeInputPath's containment rule, but the file need not exist yet).
80
- * `omc intent plan --plan-out` uses it so the written plan is readable by
81
- * `omc intent apply`, which enforces the same root.
80
+ * `omc intent plan --plan-out` uses it so the written plan is a normal file in
81
+ * the config root (the plan itself is a CLI product; `intent apply` also accepts
82
+ * plan files from outside the root, e.g. a `--out` envelope in /tmp).
82
83
  *
83
84
  * Issue 06(retro 2026-11-19):Windows 用户拿系统 temp 被拒后不知道往哪写——
84
85
  * ① 越界拒绝时错误直接给出根内**可用的绝对示例路径**(`<root>/artifacts-out/<原名>`),
@@ -6,6 +6,21 @@ import { isWithinRoot } from "./artifacts.js";
6
6
  import { asciiStdout, serializeEnvelope } from "./cli-contract.js";
7
7
  import { currentUsageCommand, priorRepeatedFailures, recordUsageOutput } from "./usage-log.js";
8
8
  let options = { quiet: false, verbose: false };
9
+ /**
10
+ * Probe I F1/F2(0.8.15):`--out` 是全局的「完整信封落盘」开关,stdout 只回
11
+ * `{out,bytes}` 小回执——调用方看不出落盘文件能不能直接用。由知道产物语义的
12
+ * 命令(如 `intent plan`)挂一句下一步,回执即可自解释。一次性消费(同
13
+ * noteOutProjection),避免同进程多次写回串味。
14
+ */
15
+ let outReceiptHint;
16
+ export function setOutReceiptHint(hint) {
17
+ outReceiptHint = hint;
18
+ }
19
+ function takeOutReceiptHint() {
20
+ const hint = outReceiptHint;
21
+ outReceiptHint = undefined;
22
+ return hint;
23
+ }
9
24
  let outProjectionNote;
10
25
  /** 记录一次「`--out` + 投影」的组合;下一个 writeEnvelope 消费它。 */
11
26
  export function noteOutProjection(note) {
@@ -262,6 +277,7 @@ export function writeEnvelope(value) {
262
277
  // 一次性消费:投影说明只属于**本次**调用,任何后续 writeEnvelope(批量/复合
263
278
  // 命令同进程多次写回)都必须回到既有的 `--out` 语义。
264
279
  const projection = takeOutProjection();
280
+ const receiptHint = takeOutReceiptHint();
265
281
  // `--out-file`(issue 2026-11-18 §08.2):完整信封以 raw UTF-8 原子落盘,
266
282
  // stdout 只回小回执。它在 compactForOutput 之前分叉——文件里必须是**完整**
267
283
  // 信封(status/requestId/error 都在),stdout 的小回执固定保留 status。
@@ -330,6 +346,7 @@ export function writeEnvelope(value) {
330
346
  ? {}
331
347
  : { jqNote: `投影值 ${inlineBytes}B 超过 stdout 预算 ${projection.budget}B:完整投影已写入 --out 文件(stdout 只回指针),要看值请读该文件或缩小 --jq 路径;要放大回执用 --max-output-bytes` }),
332
348
  },
349
+ ...(receiptHint !== undefined ? { hint: receiptHint } : {}),
333
350
  };
334
351
  const receiptText = serializeEnvelope(receipt);
335
352
  recordUsageOutput(value, Buffer.byteLength(receiptText, "utf8"), projectedBytes);
@@ -345,10 +362,12 @@ export function writeEnvelope(value) {
345
362
  result: { out: options.outFile, bytes: Buffer.byteLength(pretty, "utf8") },
346
363
  requestId: envelopeValue.requestId ?? null,
347
364
  error: envelopeValue.error ?? null,
365
+ ...(receiptHint !== undefined ? { hint: receiptHint } : {}),
348
366
  }
349
367
  : {
350
368
  ok: envelopeValue.ok ?? true,
351
369
  result: { out: options.outFile, bytes: Buffer.byteLength(pretty, "utf8") },
370
+ ...(receiptHint !== undefined ? { hint: receiptHint } : {}),
352
371
  };
353
372
  const confirmationText = serializeEnvelope(confirmation);
354
373
  recordUsageOutput(value, Buffer.byteLength(confirmationText, "utf8"), Buffer.byteLength(pretty, "utf8"));
package/dist/cli.js CHANGED
@@ -24,8 +24,9 @@ import { cmdProgrammingAdopt, cmdProgrammingApply, cmdProgrammingPull, cmdProgra
24
24
  import { environmentWritable, requiresProductionConfirmation } from "./environment-policy.js";
25
25
  import { CLI_EXIT_CODES, asciiStdout, classifyResult, envelope, errorEnvelope, humanUtf8, installCodePageSafeStderr, refusalText, requestId } from "./cli-contract.js";
26
26
  import { ownsStdout } from "./cli-stdout.js";
27
+ import { installStdoutPipeGuard } from "./stdout-pipe.js";
27
28
  import { formatDoctorHumanSummary, unsupportedCapabilities } from "./version-family-gaps.js";
28
- import { beginWriteFace, configureOutput, endWriteFace, humanSummary, maybeWarnMergedStreams, noteOutProjection, stripOutputFlags, writeEnvelope } from "./cli-output.js";
29
+ import { beginWriteFace, configureOutput, endWriteFace, humanSummary, maybeWarnMergedStreams, noteOutProjection, outputOptions, setOutReceiptHint, stripOutputFlags, writeEnvelope } from "./cli-output.js";
29
30
  import { beginUsage, completeUsage, currentUsageArgsDigest, ensureProjectIgnore, priorIdenticalSuccess, recordUsageOutput, usageReport } from "./usage-log.js";
30
31
  import { artifactFetchHint, artifactRoot, boundResult, emitInvalid, emitResult, emitThrown, emitTransportResult, outputBudget, readArtifact, withTransport, } from "./command-transport.js";
31
32
  import { CLI_DEFAULT_OUTPUT_BYTES, assertSafeOutputPath, pruneArtifacts } from "./artifacts.js";
@@ -34,7 +35,7 @@ import { closeWritableWindow, openWritableWindow, parseWritableTtl, sweepWritabl
34
35
  import { artifactPathMissHint, nullProjectionHint, PATH_MISS_HELP_REF, UNSUPPORTED_JQ_OBJECT_HINT, partialPathMissHint, pathMissCopyableHint, pathMissCopyablePaths, pathMissCrossFaceCorrection, pathMissDidYouMean, projectJsonPath, projectJsonPathFanout, projectResultExtract, shapeOf, SHAPE_MAX_DEPTH, unwrapSinglePathProjection } from "./path-projection.js";
35
36
  import { isUncertainWireError } from "./support.js";
36
37
  import { containerKeyOf } from "./read.js";
37
- import { basename, dirname, join, resolve } from "node:path";
38
+ import { dirname, join, resolve } from "node:path";
38
39
  import { existsSync, readFileSync, writeFileSync, chmodSync, mkdirSync } from "node:fs";
39
40
  import { buildToolRegistry } from "./tools.js";
40
41
  import { parseDurationMs } from "./duration.js";
@@ -719,10 +720,12 @@ async function cmdCall(store, args) {
719
720
  console.error(message);
720
721
  // The MACHINE envelope must carry the same actionable text: agents read
721
722
  // stdout, and the old envelope only repeated the English detail.
722
- // Keep the REJECTED path on stderr only: the machine envelope must not leak
723
- // host layout (ticket 103), so it carries the root plus the bare file name.
724
- const rejectedName = typeof argsFile === "string" ? basename(resolve(configRoot, argsFile)) : "";
725
- writeEnvelope({ ...envelope("error", {}, request, { code: "invalid-input", message: outOfRoot ? `--args-file 必须位于配置根内(配置根 ${configRoot}${rejectedName ? `;本次文件 ${rejectedName}` : ""})。免落盘替代:--args - 从 stdin 读 JSON(echo '<json>' | omc call <tool> --args -),或把文件放进配置根后再引用;限制是为了防参数文件携带凭据被收进会话产物` : argsFile !== undefined && /must be a JSON object/.test(detail) ? `${detail};批量数组请改用 --args-list(最多 200 条,可分批执行)` : detail, retryable: false, ...(outOfRoot ? { configurationRoot: configRoot } : {}) }), resultMeta: accountMeta() });
723
+ // Keep the FULL path the caller passed (resolved) in the envelope: the bare
724
+ // file name read like a relative path and sent the caller looking in cwd
725
+ // (F3, 0.8.15 probe I). The resolved path is the caller's own input, not a
726
+ // leaked host layout (ticket 103); it is what they must move into the root.
727
+ const rejectedPath = typeof argsFile === "string" ? resolve(configRoot, argsFile) : "";
728
+ writeEnvelope({ ...envelope("error", {}, request, { code: "invalid-input", message: outOfRoot ? `--args-file 必须位于配置根内(配置根 ${configRoot}${rejectedPath ? `;本次文件 ${rejectedPath}` : ""})。免落盘替代:--args - 从 stdin 读 JSON(echo '<json>' | omc call <tool> --args -),或把文件放进配置根后再引用;限制是为了防参数文件携带凭据被收进会话产物` : argsFile !== undefined && /must be a JSON object/.test(detail) ? `${detail};批量数组请改用 --args-list(最多 200 条,可分批执行)` : detail, retryable: false, ...(outOfRoot ? { configurationRoot: configRoot } : {}) }), resultMeta: accountMeta() });
726
729
  return CLI_EXIT_CODES.invalidInput;
727
730
  }
728
731
  const registry = buildToolRegistry();
@@ -2599,17 +2602,18 @@ async function cmdIntentPlan(file, environment, planOut, transport, summary = fa
2599
2602
  return emitInvalid(transport, { message: error instanceof Error ? error.message : String(error) });
2600
2603
  }
2601
2604
  }
2602
- const result = await planIntent(read.intent, environment, planOut);
2605
+ let result = await planIntent(read.intent, environment, planOut);
2603
2606
  // a-F12(r60a-F12,r61):--summary 档只回决策字段 + 逐项变更(tool+reason+资源
2604
2607
  // 键,去 args/baselineFingerprint)。内联完整 plan 一个真实需求 ~20KB、含基线
2605
2608
  // 50–60KB——探针只要「会改什么」时被整块计费。要 apply 仍用完整 plan(不带
2606
2609
  // --summary,或 --plan-out 写复核文件)。
2610
+ let summaryProjected = false;
2607
2611
  if (summary) {
2608
2612
  const plan = result.plan;
2609
2613
  if (plan !== undefined && Array.isArray(plan.changes)) {
2610
2614
  // r62c-F3(P0-4):resource 用编译器的资源标识(`field:model.code`),不从
2611
2615
  // args 猜——猜会降级成模型 code,3 个 field.create 无法区分(探针真机撞上)。
2612
- return emitResult({
2616
+ result = {
2613
2617
  ...result,
2614
2618
  plan: undefined,
2615
2619
  changesBrief: plan.changes.map((change) => ({
@@ -2618,10 +2622,29 @@ async function cmdIntentPlan(file, environment, planOut, transport, summary = fa
2618
2622
  ...(change.resource !== undefined ? { resource: change.resource } : {}),
2619
2623
  })),
2620
2624
  summaryNote: "--summary 只回变更清单(去 args/基线);apply 用完整 plan(不带 --summary 或 --plan-out <file>)",
2621
- }, transport);
2625
+ };
2626
+ summaryProjected = true;
2622
2627
  }
2623
2628
  // 已外置/已写文件的分支本就是决策字段面——原样返回。
2624
2629
  }
2630
+ // Probe I F1/F2(0.8.15):`--out` 落的是完整 CLI 信封,stdout 只有小回执。
2631
+ // 回执必须自解释——但必须在 summary 投影**之后**看 result:summary 会剥掉
2632
+ // plan(只留 changesBrief),此前分档会把摘要信封误称「自动取 result.plan」。
2633
+ // 大 plan 则只有 planFile/planArtifactId(result.plan 不存在),各成一档。
2634
+ const outFile = outputOptions().outFile;
2635
+ if (outFile !== undefined && result.status === "ok") {
2636
+ const receipt = result;
2637
+ const outPath = resolve(outFile);
2638
+ const planFile = typeof receipt.planFile === "string" ? receipt.planFile : undefined;
2639
+ const planArtifactId = typeof receipt.planArtifactId === "string" ? receipt.planArtifactId : undefined;
2640
+ setOutReceiptHint(summaryProjected
2641
+ ? `该信封是 --summary 摘要产物(不含 plan):apply 请去掉 --summary 重跑 intent plan,或用 result.planArtifactId(omc intent apply ${planArtifactId ?? planFile ?? "<planArtifactId>"})`
2642
+ : receipt.plan !== undefined
2643
+ ? `该文件是完整 CLI 信封,可直接 omc intent apply ${outPath}(apply 自动取 result.plan);要裸 plan 用 --plan-out`
2644
+ : planFile !== undefined || planArtifactId !== undefined
2645
+ ? `该信封里 plan 已外置(result.plan 不存在):直接 omc intent apply ${planFile ?? planArtifactId}${planFile !== undefined ? "(planFile 在 result.planFile)" : "(planArtifactId 在 result.planArtifactId)"}`
2646
+ : "该信封不含 plan:apply 请重跑 intent plan(不要 --summary);要落盘复核用 --plan-out");
2647
+ }
2625
2648
  return emitResult(result, transport);
2626
2649
  }
2627
2650
  /** Ticket 120 — `omc intent readback <file> --env <env>`: decode the live baseline back into intent shape and verify equivalence. */
@@ -2900,17 +2923,21 @@ async function cmdIntentApply(planPath, options, transport) {
2900
2923
  emit: (result) => emitResult(result, transport),
2901
2924
  invalid: (blocker, message, code = "invalid-input") => emitInvalid(transport, { message, blocker, code }),
2902
2925
  readIntent: (file) => {
2903
- let outcome;
2926
+ let text;
2904
2927
  try {
2905
- outcome = validateIntentText(readIntentFile(intentConfigRoot(), file));
2928
+ text = readIntentFile(intentConfigRoot(), file);
2906
2929
  }
2907
- catch {
2908
- return { kind: "exit", code: CLI_EXIT_CODES.invalidInput };
2930
+ catch (error) {
2931
+ // Probe I 复核:意图源(YAML)在配置根外时,先给根限制/可执行修法,
2932
+ // 不把 JSON.parse 的 `Unexpected token` 当主因(plan 文件可在根外)。
2933
+ return { kind: "invalid", message: `意图源 YAML 必须在配置根内(plan JSON 文件不受此限):${error instanceof Error ? error.message : String(error)}` };
2909
2934
  }
2935
+ const outcome = validateIntentText(text);
2910
2936
  if (!outcome.valid || outcome.intent === undefined) {
2911
2937
  for (const error of outcome.errors)
2912
2938
  console.error(`intent ${file}:${error.line}:${error.column} [${error.code}] ${error.message}`);
2913
- return { kind: "exit", code: CLI_EXIT_CODES.invalidInput };
2939
+ const detail = outcome.errors.map((error) => `${file}:${error.line}:${error.column} [${error.code}] ${error.message}`).join(";");
2940
+ return { kind: "invalid", message: `意图 YAML 校验失败:${detail}` };
2914
2941
  }
2915
2942
  return { kind: "ok", intent: outcome.intent };
2916
2943
  },
@@ -4089,7 +4116,7 @@ async function main() {
4089
4116
  command.command("capability <id>").option("--executable").option("--max-output-bytes <bytes>").addOption(jqOption()).addOption(explainOption()).action(async (id, options) => {
4090
4117
  commandExitCode = await withTransport(options, request, (transport) => cmdCapability(id, transport, options.executable === true, options.jq, options.explain === true));
4091
4118
  });
4092
- const intentCommand = command.command("intent").description("声明式意图面(Spec 107):intent.yaml → validate → plan → apply → readback。**intent/plan 文件必须位于配置根内**(与 --args-file 同规则:配置根外的文件一律拒绝,防携带凭据被收进会话产物;根外内容请先拷入或经 stdin)").addHelpText("after", "\n意图文件(validate/plan/readback 的 <file>)与 plan 产物(--plan-out)都解析到配置根内——配置根外一律 invalid-input(与 call --args-file 同规则)。\n");
4119
+ const intentCommand = command.command("intent").description("声明式意图面(Spec 107):intent.yaml → validate → plan → apply → readback。**意图源文件(validate/plan/readback)必须位于配置根内**(与 --args-file 同规则:根外一律拒绝);**plan 文件(apply 的输入)是 CLI 产物、不含凭据,可在任意路径**(含 /tmp 与 `--out` 落下的完整信封)").addHelpText("after", "\n意图源文件(validate/plan/readback 的 <file>)解析到配置根内——配置根外一律 invalid-input(与 call --args-file 同规则)。plan 文件不走该限制:apply 接受根外路径、裸 plan、以及 `intent plan ... --out <file>` 的完整信封(自动取 result.plan);`intent plan --plan-out` 仍写配置根内。\n");
4093
4120
  intentCommand.command("schema").option("--example [id]").action((options) => { commandExitCode = cmdIntentSchema({ request, maxOutputBytes: CLI_DEFAULT_OUTPUT_BYTES }, typeof options.example === "string" ? options.example : undefined, options.example !== undefined); });
4094
4121
  intentCommand.command("validate <file>").option("--show-intent").action((file, options) => { commandExitCode = cmdIntentValidate(file, { request, maxOutputBytes: CLI_DEFAULT_OUTPUT_BYTES }, options.showIntent === true); });
4095
4122
  intentCommand.command("plan <file>").option("--env <environment>").option("--plan-out <file>").option("--summary", "只回变更清单(tool+reason+资源键,去 args/基线)——复核用;apply 仍需完整 plan").option("--max-output-bytes <bytes>").action(async (file, options) => {
@@ -4207,6 +4234,9 @@ function finish(code) {
4207
4234
  process.exitCode = code;
4208
4235
  setTimeout(() => process.exit(code), 1000).unref();
4209
4236
  }
4237
+ // F10(0.8.15):下游 `head`/`grep -q` 提前关闭管道时,EPIPE 是消费方叫停,
4238
+ // 不是故障——安静 exit 0,别让未处理的流错误在 `2>&1` 合流里变成假挂起。
4239
+ installStdoutPipeGuard();
4210
4240
  const request = requestId();
4211
4241
  main().then((code) => {
4212
4242
  // Commands that own their stdout never grow a trailing envelope. The list is
@@ -894,7 +894,9 @@ export function assertLayoutRequestConflicts(args) {
894
894
  schemaCode: String(args.schemaCode ?? ""),
895
895
  sheetCode: String(args.sheetCode ?? args.schemaCode ?? ""),
896
896
  conflictKeys,
897
- message: `layout 与 ${conflictKeys.join("、")} 互斥:layout 是增量面(以已发布表单为基线,只改这些控件的行分组与 span),不要同时回传整包 attrs/view、不要重建;二选一。`,
897
+ message: `layout 与 ${conflictKeys.join("、")} 互斥:layout 是增量面(以已发布表单为基线,只改这些控件的行分组与 span),不要同时回传整包 attrs/view、不要重建;二选一。${conflictKeys.includes("childColumns")
898
+ ? "子表列要先物化进已发布表单,正确顺序:① 先 `form.publish {rebuild:true}` 把子表列物化进已发布表单;② 再 `form.draft {layout}`(baseline=published);③ 再 `form.publish`。"
899
+ : ""}`,
898
900
  });
899
901
  }
900
902
  /**
@@ -130,6 +130,16 @@ export function writeSummary(tool, args, outcome, phase = "done") {
130
130
  const pending = Object.entries(perCode).filter(([, value]) => value?.absent === false).map(([code]) => code);
131
131
  return `未删净(级联中)${pending.length > 0 ? pending.join("、") : "部分模型"}:平台异步删除任务未完成,记录面仍查得到——不要当作已删除;按 perCode 逐项复核,稍后重跑 model.deleteMany(幂等)`;
132
132
  }
133
+ // P1(探针 I,0.8.15):删前读不到 ≠ 已清理。schemaCode 写错时 id 实际在另一个
134
+ // 模型里,回执曾是 status:ok + already-absent。人类摘要必须同样以否定开头。
135
+ if (phase === "done" && tool === "data.delete" && outcome?.readback?.blocker === "delete-target-not-in-schema") {
136
+ const listed = Array.isArray(outcome.readback.notInSchema) ? outcome.readback.notInSchema.map(String) : [];
137
+ const ids = listed.length > 0
138
+ ? listed
139
+ : [(Array.isArray(args.bizObjectIds) ? String(args.bizObjectIds[0]) : undefined) ?? stringArg(args, "bizObjectId") ?? "?"];
140
+ const schema = stringArg(args, "schemaCode") ?? "?";
141
+ return `未确认删除(delete-target-not-in-schema)${ids.length} 条不属于 ${schema}:${ids.join("、")};本工具无法判定归属——先 model.list 取候选模型再逐个 data.list 核对(或问用户),别据此宣称已清理`;
142
+ }
133
143
  // r28b F11: data.delete already-absent must NOT read as「已删除…」— humans/CI
134
144
  // that skim stderr treat the leading verb as the outcome. Say「未删除」first.
135
145
  if (phase === "done" && tool === "data.delete" && outcome?.performed?.skipped === "already-absent") {
@@ -1,5 +1,5 @@
1
- import { readFileSync } from "node:fs";
2
- import { resolve } from "node:path";
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
3
  import { assertSafeInputPath } from "../artifacts.js";
4
4
  import { CLI_ARGS_MAX_BYTES } from "../call.js";
5
5
  import { INTENT_VERSION, parseIntent, YamlSyntaxError, IntentInvalidError } from "./dsl.js";
@@ -15,6 +15,39 @@ export function readIntentFile(root, path) {
15
15
  throw new Error(`intent file exceeds ${CLI_ARGS_MAX_BYTES} bytes`);
16
16
  return content;
17
17
  }
18
+ /**
19
+ * Probe I F1(0.8.15):`intent apply` 的输入是**plan 文件**,不是意图源文件。
20
+ * plan 是 CLI 自己写出的产物(`--out`/`--plan-out`/artifact),不含凭据,因此
21
+ * 允许配置根外的路径(至少 /tmp)——否则 CLI 刚写出的文件会被自己拒绝。
22
+ * 仍守住形状:拒绝符号链接(只查叶节点,不逐段)、非普通文件、超大文件;
23
+ * 相对路径先按配置根解析(与旧行为兼容:`intent apply plan.json` 仍指向根内),
24
+ * 再按当前目录解析。意图源 YAML(validate/plan/readback)维持 `readIntentFile`
25
+ * 的根内限制。
26
+ */
27
+ export function readPlanFile(root, path) {
28
+ const candidates = isAbsolute(path) ? [path] : [resolve(root, path), resolve(path)];
29
+ let lastError;
30
+ for (const candidate of [...new Set(candidates)]) {
31
+ try {
32
+ const stat = lstatSync(candidate);
33
+ if (stat.isSymbolicLink())
34
+ throw new Error(`plan 文件不能是符号链接:${candidate}`);
35
+ if (!stat.isFile())
36
+ throw new Error(`plan 文件必须是常规文件:${candidate}`);
37
+ if (stat.size > CLI_ARGS_MAX_BYTES)
38
+ throw new Error(`plan 文件超过 ${CLI_ARGS_MAX_BYTES} 字节:${candidate}`);
39
+ const content = readFileSync(candidate, "utf8");
40
+ if (Buffer.byteLength(content) > CLI_ARGS_MAX_BYTES)
41
+ throw new Error(`plan 文件超过 ${CLI_ARGS_MAX_BYTES} 字节:${candidate}`);
42
+ return content;
43
+ }
44
+ catch (error) {
45
+ lastError = error;
46
+ }
47
+ }
48
+ const detail = lastError instanceof Error ? `(${lastError.message})` : "";
49
+ throw new Error(`plan 文件不存在或不可读:${path}${detail}`);
50
+ }
18
51
  /** Validate an intent file's text offline (zero environment contact). */
19
52
  export function validateIntentText(text) {
20
53
  try {
@@ -18,13 +18,13 @@ import { ENDPOINTS } from "../endpoints.js";
18
18
  import { extractBizObjectPage } from "../lanes/runtime-data.js";
19
19
  import { ToolRefusalError, ToolInputError, parseToolInput } from "../tool-types.js";
20
20
  import { jsonBytes, sha256, writeArtifact } from "../support.js";
21
- import { INTENT_COMPILER_VERSION, intentConfigRoot, readIntentFile } from "./cli.js";
21
+ import { INTENT_COMPILER_VERSION, intentConfigRoot, readPlanFile } from "./cli.js";
22
22
  import { validateRuleNodeGraph, PLATFORM_TRIGGER_RULE_CODES, walkConditionLeaves } from "../lanes/rule-graph.js";
23
23
  import { expectedRuleGraph } from "./capabilities/businessrule.js";
24
24
  import { lintIntentFieldCreateChanges, relationTargetsFromPlan } from "./capabilities/field.js";
25
25
  import { readBaseline, baselineFingerprintOf } from "./baseline.js";
26
26
  import { compileIntent } from "./compiler.js";
27
- import { buildPlan, verifyPlan } from "./plan-file.js";
27
+ import { buildPlan, unwrapPlanDocument, verifyPlan } from "./plan-file.js";
28
28
  import { decodeBaseline, compareWithLive } from "./readback.js";
29
29
  const INTENT_PLAN_INLINE_CEILING_BYTES = 16384;
30
30
  /**
@@ -398,7 +398,9 @@ export async function applyIntent(planPath, options, ports) {
398
398
  const invalid = (blocker, message, code = "invalid-input") => ports.invalid(blocker, message, code);
399
399
  let planText;
400
400
  try {
401
- planText = readIntentFile(intentConfigRoot(), planPath);
401
+ // Probe I F1(0.8.15):plan 是 CLI 产物(`--out`/`--plan-out` 都可能落在任何
402
+ // 路径),不能按意图源文件的「配置根内」规则拒绝自己刚写出的文件。
403
+ planText = readPlanFile(intentConfigRoot(), planPath);
402
404
  }
403
405
  catch (fileError) {
404
406
  // The plan for a large intent is externalized: `intent plan` returns
@@ -411,8 +413,8 @@ export async function applyIntent(planPath, options, ports) {
411
413
  }
412
414
  catch {
413
415
  const hint = planPath.endsWith(".json") || planPath.includes("/") || planPath.includes("\\")
414
- ? "plan 文件不存在或不在配置根内;plan 产物里有 planFile/artifactId 两种引用,直接给 planFile 或 artifactId 均可"
415
- : `plan 找不到 "${planPath}"。大 plan 会外置——用 intent plan 结果里的 planFile 路径或 artifactId(可直接 \`omc intent apply <artifactId>\`);小 plan 内联在 result.plan,先落成 .json 再传入`;
416
+ ? "plan 文件不存在或不可读(plan 可在配置根外,如 /tmp;意图源 YAML 仍须在配置根内);plan 产物里有 planFile/artifactId 两种引用,直接给 planFile 或 artifactId 均可"
417
+ : `plan 找不到 "${planPath}"。大 plan 会外置——用 intent plan 结果里的 planFile 路径或 artifactId(可直接 \`omc intent apply <artifactId>\`);小 plan 内联在 result.plan,用 --out 写的信封也可直接 apply(自动取 result.plan)`;
416
418
  return invalid(undefined, `${hint}(原错误:${fileError instanceof Error ? fileError.message : String(fileError)})`);
417
419
  }
418
420
  }
@@ -428,6 +430,10 @@ export async function applyIntent(planPath, options, ports) {
428
430
  // SOURCE intent YAML directly: compile it in-process (same pipeline as
429
431
  // `intent plan`) and apply the resulting plan.
430
432
  const read = ports.readIntent ? ports.readIntent(planPath) : undefined;
433
+ // 意图源定位/校验错误(最典型:YAML 在配置根外)优先于 JSON.parse 的
434
+ // `Unexpected token`——根限制是可执行的修法,解析噪声只会盖住它。
435
+ if (read && read.kind === "invalid")
436
+ return invalid(undefined, read.message);
431
437
  if (read && read.kind === "ok") {
432
438
  try {
433
439
  const context = makeToolContext({ sessions: new SessionManager(new ConfigStore(defaultPaths())) });
@@ -452,6 +458,14 @@ export async function applyIntent(planPath, options, ports) {
452
458
  return invalid(undefined, `plan 文件不是合法 JSON:${error instanceof Error ? error.message : String(error)};意图 YAML 请先 intent plan <yaml> --plan-out <plan.json>,或直接 intent apply <yaml> --env <env>(自动编译)`);
453
459
  }
454
460
  }
461
+ // Probe I F2(0.8.15):`--out` 落的是完整 CLI 信封;apply 自动取 result.plan
462
+ // (或 result 本身是 plan)。裸 plan(schema 在顶层)原样通过。
463
+ const unwrapped = unwrapPlanDocument(parsed);
464
+ if (!unwrapped.ok)
465
+ return invalid(unwrapped.envelope ? "intent-plan-envelope-without-plan" : undefined, unwrapped.reason);
466
+ if (unwrapped.document.fromEnvelope)
467
+ console.error("intent apply:输入是 CLI 信封,已自动取 result.plan");
468
+ parsed = unwrapped.document.plan;
455
469
  const verified = verifyPlan(parsed);
456
470
  if (!verified.ok)
457
471
  return invalid(verified.code, verified.reason);
@@ -61,4 +61,42 @@ export function verifyPlan(value) {
61
61
  return { ok: false, code: "intent-plan-tampered", reason: "plan 哈希不匹配:文件内容与生成时不一致(what you approve must be byte-identical to what executes)" };
62
62
  return { ok: true, plan: plan };
63
63
  }
64
+ /**
65
+ * Probe I F2(0.8.15):`omc intent plan ... --out <file>` 写的是**完整 CLI 信封**
66
+ * (`--out` 是全局信封落盘开关,不是 plan 专用选项),而 `intent apply` 只认裸
67
+ * plan,于是把外层当 plan 读、报 `plan.schema 必须是 omc-intent-plan-v1`。
68
+ * 这里只做文档定位,不校验哈希(verifyPlan 仍是唯一权威):
69
+ * - 裸 plan(`schema` 在顶层)→ 原样;
70
+ * - envelope 的 `result.plan` 或 `result` 本身是 plan → 取出来;
71
+ * - 是信封但取不到 plan → 明确说「你给的是信封,取 result.plan」。
72
+ */
73
+ export function unwrapPlanDocument(value) {
74
+ if (value === null || typeof value !== "object" || Array.isArray(value))
75
+ return { ok: false, envelope: false, reason: "plan 文件必须是 JSON 对象" };
76
+ const record = value;
77
+ if (record.schema === INTENT_PLAN_SCHEMA)
78
+ return { ok: true, document: { plan: value, fromEnvelope: false } };
79
+ const result = record.result;
80
+ if (result !== null && typeof result === "object" && !Array.isArray(result)) {
81
+ const resultRecord = result;
82
+ if (resultRecord.schema === INTENT_PLAN_SCHEMA)
83
+ return { ok: true, document: { plan: result, fromEnvelope: true } };
84
+ const nested = resultRecord.plan;
85
+ if (nested !== null && typeof nested === "object" && !Array.isArray(nested) && nested.schema === INTENT_PLAN_SCHEMA)
86
+ return { ok: true, document: { plan: nested, fromEnvelope: true } };
87
+ }
88
+ const envelopeShaped = "ok" in record || "status" in record || "requestId" in record || "result" in record || "error" in record;
89
+ if (!envelopeShaped)
90
+ return { ok: true, document: { plan: value, fromEnvelope: false } };
91
+ // A large plan is externalized: the envelope carries only planFile/planArtifactId.
92
+ const external = result !== null && typeof result === "object" && !Array.isArray(result) ? result : undefined;
93
+ const reference = typeof external?.planArtifactId === "string"
94
+ ? `planArtifactId=${external.planArtifactId}`
95
+ : typeof external?.planFile === "string"
96
+ ? `planFile=${external.planFile}`
97
+ : undefined;
98
+ const reason = `检测到你给的是 CLI 信封(含 ok/result),但取不到其中的 plan(没有 result.plan,result 本身也不是 plan)——信封文件请取 result.plan 再 apply,或直接用 intent plan --plan-out <plan.json> 写裸 plan`
99
+ + (reference !== undefined ? `;本次信封里 plan 已外置(${reference}),可直接 apply 该引用` : "");
100
+ return { ok: false, envelope: true, reason };
101
+ }
64
102
  //# sourceMappingURL=plan-file.js.map
@@ -5,12 +5,27 @@ import { governedRead } from "../read.js";
5
5
  import { environmentWritable, requiresProductionConfirmation, versionEvidenceOf } from "../environment-policy.js";
6
6
  import { versionFamilyNotice } from "../coverage.js";
7
7
  import { flattenTreeRows } from "../support.js";
8
+ import { repairMojibakeText } from "../mojibake.js";
8
9
  import { defineTool } from "../tool-types.js";
9
10
  import { wireCall, wireRows } from "../wire.js";
10
11
  import { ENVIRONMENT_LANE_CONTRACT } from "./environment-contract.js";
11
12
  import { readProjectCard, writeProjectCard } from "../project-card.js";
12
13
  const ENVIRONMENT_LANE = ENVIRONMENT_LANE_CONTRACT.lane;
13
14
  const ENVIRONMENT_TOOLS = ENVIRONMENT_LANE_CONTRACT.tools;
15
+ /**
16
+ * F11(0.8.15):分组名展示面的保守还原。平台预置分组 `all` 在 DB 里是
17
+ * windows-1252 双编码(wire 原文即 `全部`,字节证据见 src/mojibake.ts),
18
+ * 修好时保留原文并标记,正常中文/ASCII 原样返回。缓存命中路径也走这里,
19
+ * 老卡里存的 mojibake 不会因升级后继续服务。
20
+ */
21
+ function displayGroupName(rawName) {
22
+ if (typeof rawName !== "string")
23
+ return { name: rawName };
24
+ const repaired = repairMojibakeText(rawName);
25
+ return repaired.repaired
26
+ ? { name: repaired.value, nameRaw: rawName, nameMojibake: true }
27
+ : { name: rawName };
28
+ }
14
29
  /** r30f F2 — doctor / discover / fingerprint share one version-evidence face. */
15
30
  function versionEvidenceFor(ctx, session) {
16
31
  const detected = session.detectedVersion();
@@ -109,8 +124,20 @@ export function registerEnvironmentLane(tools) {
109
124
  // r28b F16 / r29f F10:缓存是加速,不是第二套契约。键集必须与冷路径
110
125
  // compact 同形;generatedAt / fromCacheHint 只做额外键。
111
126
  const cachedExtra = cached;
112
- const apps = Array.isArray(cached.applications) ? cached.applications : [];
113
- const groups = Array.isArray(cached.groups) ? cached.groups : [];
127
+ const apps = Array.isArray(cached.applications)
128
+ ? cached.applications.map((row) => {
129
+ const repaired = displayGroupName(row.groupName);
130
+ return repaired.nameMojibake === true
131
+ ? { ...row, groupName: repaired.name, groupNameRaw: repaired.nameRaw, groupNameMojibake: true }
132
+ : row;
133
+ })
134
+ : [];
135
+ const groups = Array.isArray(cached.groups)
136
+ ? cached.groups.map((row) => {
137
+ const repaired = displayGroupName(row.name);
138
+ return repaired.nameMojibake === true ? { ...row, ...repaired } : row;
139
+ })
140
+ : [];
114
141
  const models = Array.isArray(cached.models)
115
142
  ? cached.models.map((row) => ({ schemaCode: row.code, name: row.name }))
116
143
  : [];
@@ -188,7 +215,17 @@ export function registerEnvironmentLane(tools) {
188
215
  // an informed decision.
189
216
  const groups = wireRows((await wireCall(session, { path: ENDPOINTS.applicationGroupList, query: {} })).data).map((row) => {
190
217
  const code = String(row.code ?? "");
191
- return { id: String(row.id ?? ""), code, name: row.name ?? row.groupName ?? code, isFallback: code.toLowerCase() === "all" };
218
+ // F11(0.8.15):平台预置分组 `all` 的名字在 DB 里是 windows-1252
219
+ // 双编码(wire 原文即 `全部`,见 src/mojibake.ts 的字节证据),
220
+ // 只在这一处展示面做保守还原;修好的行同时留 nameRaw + nameMojibake
221
+ // 让调用方知道 name 不是平台原文。正常中文/ASCII 原样不动。
222
+ const rawName = row.name ?? row.groupName ?? code;
223
+ return {
224
+ id: String(row.id ?? ""),
225
+ code,
226
+ ...displayGroupName(rawName),
227
+ isFallback: code.toLowerCase() === "all",
228
+ };
192
229
  });
193
230
  const groupById = new Map(groups.map((group) => [group.id, group]));
194
231
  const apps = appRows.map((row) => {
@@ -200,6 +237,9 @@ export function registerEnvironmentLane(tools) {
200
237
  groupId: groupId ?? null,
201
238
  groupCode: group?.code ?? null,
202
239
  groupName: group?.name ?? null,
240
+ // 键集与缓存命中路径同形(该文件 :132-133 的既有约定):分组名被
241
+ // 保守还原时,应用行也带 nameRaw 语义的原文与标记。
242
+ ...(group?.nameMojibake === true ? { groupNameRaw: group.nameRaw, groupNameMojibake: true } : {}),
203
243
  portalHidden: group === undefined || group.isFallback === true,
204
244
  };
205
245
  });
@@ -311,7 +311,7 @@ export const FIELD_LANE_CONTRACT = Object.freeze({
311
311
  }),
312
312
  "field.get": Object.freeze({
313
313
  scope: "create publish readback",
314
- description: "单字段读(= field.list + code 选择器,含 options/subSchema;子表原始 subSchema 传 full:true,与 field.list.full 同义)。字段行 options 含 mappings 时回执带 mappingRuntimeNote(REST 写不跑映射,配置正确性看 options.mappings)。",
314
+ description: "单字段/多字段读(= field.list + code 或 fields[] 选择器,二者互斥;含 options/subSchema,子表原始 subSchema 传 full:true,与 field.list.full 同义)。字段行 options 含 mappings 时回执带 mappingRuntimeNote(REST 写不跑映射,配置正确性看 options.mappings)。",
315
315
  }),
316
316
  "field.create": Object.freeze({
317
317
  scope: "create publish readback",
@@ -8,7 +8,7 @@ import { writeTool } from "../write.js";
8
8
  import { decodeJsonColumn, decodeJsonObjectColumn, JSON_COLUMN_NULL_COALESCE, JSON_COLUMN_PASSTHROUGH } from "../json-column.js";
9
9
  import { syncFormConditionDataRules } from "./datarule.js";
10
10
  import { FORM_CONDITION_OPTION_KEYS } from "./datarule-protocol.js";
11
- import { defineTool, ToolRefusalError } from "../tool-types.js";
11
+ import { defineTool, isRequiredAlternativePlaceholder, ToolRefusalError } from "../tool-types.js";
12
12
  import { wireCall, wireRows, WireError, optionPublishMessages } from "../wire.js";
13
13
  import { assertTreeSelectionOptions } from "../field-tree-options.js";
14
14
  import { executeFormDraftWrite, executeFormPublishWrite, readFormOrNull } from "../form-support.js";
@@ -833,15 +833,30 @@ export function registerFieldLane(tools) {
833
833
  ...fieldListTool,
834
834
  name: "field.get",
835
835
  search: { intents: ["读一个字段", "单个字段", "字段详情", "这个字段配置", "字段 options", "查字段详情"] },
836
- description: "单字段读(= field.list + code)。options/subSchema 传 full:true。",
836
+ description: "单/多字段读(= field.list + code 或 fields[])。options/subSchema 传 full:true。",
837
837
  inputSchema: {
838
838
  environment: environmentArg,
839
839
  schemaCode: z.string(),
840
840
  code: z.string(),
841
+ fields: z.array(z.string()).optional().describe("(与 code 互斥)"),
841
842
  published: z.boolean().default(false),
842
843
  full: z.boolean().optional().describe("同 field.list.full:完整 options/subSchema(含子表原始 subSchema)"),
843
844
  capability: capabilityArg,
844
845
  },
846
+ inputRefine: (value) => {
847
+ const fields = value.fields;
848
+ if (Array.isArray(fields) && fields.length > 0 && value.code !== undefined && !isRequiredAlternativePlaceholder(value.code))
849
+ return { path: "fields", message: "code 与 fields 互斥:单字段用 code,多字段用 fields:[...];两者只留一个" };
850
+ return undefined;
851
+ },
852
+ handler: async (ctx, args, self) => {
853
+ // 只传 fields[] 时 tool-types 的 required-alternatives 会给 code 补占位值
854
+ // (保持目录必填面稳定);这里剥掉,避免占位符混进 selected 回执。
855
+ const next = { ...args };
856
+ if (isRequiredAlternativePlaceholder(next.code))
857
+ delete next.code;
858
+ return fieldListTool.handler(ctx, next, self);
859
+ },
845
860
  });
846
861
  writeTool({
847
862
  tools,
@@ -580,7 +580,7 @@ export function registerFormLane(tools) {
580
580
  includeSystem: z.boolean().optional(),
581
581
  })
582
582
  .optional()
583
- .describe("增量布局(推荐):{rows:[[\"a\",\"b\"],[\"c\"]],spans?:{a:12},includeSystem?}。以已发布(无则草稿)表单为基线,只改 rows 行分组与这些控件 span,**不必回传整包 attrs**;未列入 rows 的控件保留原行,系统控件须 includeSystem:true 才动。与 draftViewJson/draftAttributesJson/rebuild 互斥"),
583
+ .describe("增量布局(推荐):{rows:[[\"a\",\"b\"],[\"c\"]],spans?:{a:12},includeSystem?}。以已发布(无则草稿)表单为基线,只改 rows 行分组与这些控件 span,**不必回传整包 attrs**;未列入 rows 的控件保留原行,系统控件须 includeSystem:true 才动。与 draftViewJson/draftAttributesJson/rebuild/fieldCodes/childColumns/refreshFromFields/fromReadback 互斥"),
584
584
  allowTypeMismatch: z.boolean().optional().describe("放行控件 type 与字段 propertyType 不匹配(默认拒 form-control-type-mismatch;仅平台模板明确要求特殊控件时用)"),
585
585
  draftHtmlJson: z.string().optional(),
586
586
  fieldCodes: z.array(z.string().min(1)).optional().describe("脚手架绑定的已发布字段(按此顺序);由 configure_form/intent 显式传入。子表列写「父字段.子列」等价于 childColumns"),
@@ -113,6 +113,34 @@ export async function inboundModelReferences(session, targets, treeRows, options
113
113
  left.via.localeCompare(right.via) ||
114
114
  (left.childTable?.code ?? "").localeCompare(right.childTable?.code ?? ""));
115
115
  }
116
+ /**
117
+ * The executable dependency order derived from `deletionSteps` — one entry per
118
+ * distinct target, in the order the caller must execute them. A model that
119
+ * references itself through a child-table column therefore appears as
120
+ * `field.delete:<child>.<col>` / `field.publish:<model>` / `model.delete:<model>`
121
+ * and `model.delete:<model>` shows up ONCE.
122
+ *
123
+ * Before F5 the model.delete refusal listed `[...referencing schemaCodes, target]`
124
+ * — for a self reference that collapsed to a single model code (`["pb_repair"]`),
125
+ * which named no executable unlink step (and the target itself). The historical
126
+ * duplicate `["pb_repair","pb_repair"]` came from model-purge's referrers
127
+ * concatenation before its F9 0.8.8 fix; both receipts now share this helper so
128
+ * they cannot drift.
129
+ */
130
+ export function deletionOrderFromSteps(steps) {
131
+ const seen = new Set();
132
+ const order = [];
133
+ for (const step of steps) {
134
+ const schemaCode = String(step.args.schemaCode ?? "");
135
+ const code = typeof step.args.code === "string" ? step.args.code : "";
136
+ const target = step.tool === "field.delete" ? `field.delete:${schemaCode}.${code}` : `${step.tool}:${schemaCode}`;
137
+ if (seen.has(target))
138
+ continue;
139
+ seen.add(target);
140
+ order.push(target);
141
+ }
142
+ return order;
143
+ }
116
144
  /**
117
145
  * `omc model-purge --unbind-references --apply` — the ONE command that executes
118
146
  * the same `field.delete → field.publish` unlink steps and then lets
@@ -170,7 +198,7 @@ export function inboundReferenceRefusal(target, references, options = {}) {
170
198
  blocker: "model-referenced-by",
171
199
  referencingModels,
172
200
  inboundReferences: [...references],
173
- deletionOrder: [...new Set([...references.map((reference) => reference.schemaCode), target])],
201
+ deletionOrder: deletionOrderFromSteps(steps),
174
202
  deletionSteps: steps,
175
203
  nextCommand: selfPurgeCommand ?? steps[0]?.command ?? `omc call model.delete --args '${JSON.stringify({ schemaCode: target })}'`,
176
204
  nextAction: selfPurgeCommand !== undefined
@@ -144,7 +144,7 @@ export const RUNTIME_DATA_LANE_CONTRACT = Object.freeze({
144
144
  }),
145
145
  "data.delete": Object.freeze({
146
146
  scope: "write authoritative readback form save",
147
- description: desc("M2 runtime data delete (runtime/form/delete) with absence readback. 批量回执按 absent / deleted[].absent / deletionVerified / undeletedIds 判成功;**没有 `present` 键**(旧版与 absent 并列会出现 present:true+absent:true,无法判断读哪条);remainingRows/modelRowsRemaining/modelClean 只描述整表状态,不用于判批量删除成败。"),
147
+ description: desc("M2 runtime data delete (runtime/form/delete) with absence readback. 成功判据=`undeletedIds` 与 `notInSchema` 均为空(deletionVerified:true);删前读不到该 id = 不属于此 schemaCode,默认 uncertain + delete-target-not-in-schema,幂等清理需显式 allowAlreadyAbsent:true。**没有 `present` 键**(旧版与 absent 并列会出现 present:true+absent:true,无法判断读哪条);remainingRows/modelRowsRemaining/modelClean 只描述整表状态,不用于判批量删除成败。"),
148
148
  }),
149
149
  "data.submit": Object.freeze({ scope: "write authoritative readback form save", description: dataSubmitDescription() }),
150
150
  }),
@@ -158,7 +158,7 @@ export function assertRuntimeDataContract() {
158
158
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.aggregate", ["totalElements", "groupBy", "local-scan", "cap 1000", "draftPolicy", "report.chartdata", "sum", "avg", "NUMERICAL", "nonNullCount"]);
159
159
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.save", ["bizObjectId", "sheetCode", "bizsheet/get", "workflowCode", "sequenceStatus", "workItem", "propertyType 9", "50000", "mappings", "rowStatus", "DRAFT", "submit:true", "CHILD_TABLE"]);
160
160
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.update", ["runtime/form/save", "bizObjectId", "COMPLETED", "304001", "form/load", "rowStatus", "child-rows-upsert"]);
161
- assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.delete", ["absence", "sheetCode"]);
161
+ assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.delete", ["absence", "sheetCode", "notInSchema", "allowAlreadyAbsent"]);
162
162
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.submit", ["getReplayToken", "replayToken", "bizObjectId", "objectId", "DRAFT", "COMPLETED", "10009", "100005", "NPE", "两段式", "finishStart=FALSE"]);
163
163
  if (!RUNTIME_DATA_WIRE.workflowDraftSave.includes("finishStart=FALSE"))
164
164
  throw new Error("runtime-data contract must pin the portal draft-save chain (finishStart=FALSE)");