@stalfh233/omc-cli 0.8.15 → 0.8.17

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.
@@ -28,7 +28,7 @@ import { writeEnvelope } from "./cli-output.js";
28
28
  import { ENDPOINTS } from "./endpoints.js";
29
29
  import { wireCall, wireRows } from "./wire.js";
30
30
  import { readModelRecord } from "./model-record.js";
31
- import { deletionOrderFromSteps, inboundModelReferences, inboundReferenceRefusal, modelPurgeUnbindCommand } from "./lanes/model-references.js";
31
+ import { deletionOrderFromSteps, deletionStepLabel, inboundModelReferences, inboundReferenceRefusal, modelPurgeCommand, modelPurgeUnbindCommand } from "./lanes/model-references.js";
32
32
  import { resolveModelTreeNode } from "./lanes/model.js";
33
33
  import { SessionManager } from "./session-manager.js";
34
34
  import { ConfigStore, defaultPaths } from "./config-store.js";
@@ -49,6 +49,13 @@ export function unbindDeletionSteps(steps) {
49
49
  export function unbindPurgeCommand(schemaCode, options = {}) {
50
50
  return modelPurgeUnbindCommand(schemaCode, options);
51
51
  }
52
+ /**
53
+ * 0.8.16 F7: plain `--apply` — it still tears down self references
54
+ * automatically and only refuses on cross-model references.
55
+ */
56
+ export function purgeApplyCommand(schemaCode, options = {}) {
57
+ return modelPurgeCommand(schemaCode, options);
58
+ }
52
59
  async function sessionFor(environment) {
53
60
  const store = new ConfigStore(defaultPaths());
54
61
  const sessions = new SessionManager(store);
@@ -188,35 +195,59 @@ export async function planPurge(options, injected) {
188
195
  if (references.length > 0) {
189
196
  const refusal = inboundReferenceRefusal(options.schemaCode, references);
190
197
  const unbindEnabled = options.unbindReferences === true;
191
- const unbindSteps = unbindDeletionSteps(refusal.deletionSteps);
192
- const nextCommand = unbindPurgeCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances });
198
+ const allUnbindSteps = unbindDeletionSteps(refusal.deletionSteps);
199
+ const allLabels = allUnbindSteps.map(deletionStepLabel);
200
+ // 0.8.16 F7: split the unlink plan by reference kind. A self reference
201
+ // (the target's own child-table column resolves back to it) is internal
202
+ // to the model being deleted — purge tears it down automatically. A
203
+ // cross-model reference belongs to another model and still needs the
204
+ // explicit destructive flag. Self owners are always the target itself,
205
+ // so the two label sets are disjoint; filtering the full ordered list
206
+ // keeps the execution order the refusal already established.
207
+ const selfLabelSet = new Set(unbindDeletionSteps(inboundReferenceRefusal(options.schemaCode, references.filter((reference) => reference.selfReference)).deletionSteps).map(deletionStepLabel));
208
+ const crossLabelSet = new Set(unbindDeletionSteps(inboundReferenceRefusal(options.schemaCode, references.filter((reference) => !reference.selfReference)).deletionSteps).map(deletionStepLabel));
209
+ const selfLabels = allLabels.filter((label) => selfLabelSet.has(label));
210
+ const crossLabels = allLabels.filter((label) => crossLabelSet.has(label));
211
+ const nextCommand = crossLabels.length > 0
212
+ ? unbindPurgeCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances })
213
+ : purgeApplyCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances });
193
214
  referencePreview = {
194
215
  inboundReferences: references,
195
216
  deletionSteps: refusal.deletionSteps,
196
217
  deletionOrder: purgeDeletionOrder(refusal.deletionSteps),
197
218
  nextCommand,
219
+ // Self-reference steps are always part of the executable plan; the
220
+ // cross-model subset is the only thing the flag gates.
221
+ ...(selfLabels.length > 0 ? { selfUnbindSteps: selfLabels } : {}),
222
+ ...(crossLabels.length > 0 ? { crossModelUnbindSteps: crossLabels } : {}),
198
223
  // F4(0.8.12,探针 G):dry-run 是「看完整计划」的面,不是执行面。
199
224
  // 入站引用(含自建子表关联列)是删模型必然要拆的内部列,dry-run 直接
200
- // 预置 unbindSteps 并说明 apply 要加的 flag,而不是逼调用方先加破坏性
201
- // 开关才能看到计划。--apply 未带 flag 的行为不变(model.delete 零写入
202
- // 拒绝,引导见 dry-run 的 note)。
225
+ // 预置 unbindSteps;0.8.16 F7 起 wouldRequireFlags 只在真有跨模型引用
226
+ // 时出现(自引用 apply 自动拆,不需要 flag)。
203
227
  ...(unbindEnabled
204
- ? { unbindReferences: true, unbindSteps: purgeDeletionOrder(unbindSteps) }
228
+ ? { unbindReferences: true, unbindSteps: allLabels }
205
229
  : options.apply
206
230
  ? {}
207
- : { unbindSteps: purgeDeletionOrder(unbindSteps), wouldRequireFlags: ["--unbind-references"] }),
231
+ : { unbindSteps: allLabels, ...(crossLabels.length > 0 ? { wouldRequireFlags: ["--unbind-references"] } : {}) }),
208
232
  referenceNotice: `${options.schemaCode} 有入站引用(${refusal.referencingModels.map((model) => model.schemaCode).join("、")};` +
209
233
  `子表列经 parentCode 解析回本模型时属于自引用)。` +
210
234
  (unbindEnabled
211
- ? `已开启 --unbind-references:本命令会先按 deletionSteps 执行拆引用(${unbindSteps.map((step) => step.tool).join(" → ")};` +
235
+ ? `已开启 --unbind-references:本命令会先按 deletionSteps 执行拆引用(${allLabels.join(" → ")};` +
212
236
  `**破坏性:会删除引用列/子表关联列,列数据不可恢复**),全部成功后再让 model.delete 级联;任一步失败即停,不会删模型。`
213
- : `--apply 未带 --unbind-references 时 model.delete 会零写入拒绝;unbindSteps 是本命令会执行的拆引用步骤(` +
214
- `${unbindSteps.map((step) => step.tool).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**),` +
215
- `nextCommand 就是带上 --unbind-references 的同一条命令;也可以自己按 deletionSteps 逐条执行。`),
237
+ : `${selfLabels.length > 0 && crossLabels.length > 0
238
+ ? `检测到自引用 + 跨模型引用:--apply 不带 flag 时**不会自动拆任何引用**(避免半拆,列数据不可恢复),model.delete 会零写入拒绝;nextCommand 带 --unbind-references 一次处理。`
239
+ : selfLabels.length > 0
240
+ ? `--apply 会自动拆自引用列(${selfLabels.join(" → ")};**破坏性:删除列数据不可恢复**),无需 --unbind-references;跨模型引用:无。`
241
+ : `--apply 不会自动拆(只有跨模型引用:${crossLabels.join(" → ")});model.delete 会零写入拒绝,nextCommand 带 --unbind-references。`}` +
242
+ `也可以自己按 deletionSteps 逐条执行。`),
216
243
  };
217
244
  steps.push(unbindEnabled
218
- ? `🔧 拆引用(--unbind-references):${unbindSteps.map((step) => step.command).join(" → ")} → 再删模型`
219
- : `🔗 入站引用(apply 前先拆;--unbind-references 一条命令,或按 deletionSteps 首步 ${refusal.deletionSteps[0]?.command ?? ""})→ 再删模型`);
245
+ ? `🔧 拆引用(--unbind-references):${allUnbindSteps.map((step) => step.command).join(" → ")} → 再删模型`
246
+ : selfLabels.length > 0 && crossLabels.length > 0
247
+ ? `🔗 入站引用(自引用 + 跨模型引用:不带 flag 不自动拆,避免半拆;需 --unbind-references)→ 再删模型`
248
+ : selfLabels.length > 0
249
+ ? `🔗 入站引用(自引用自动拆:${selfLabels.join(" → ")})→ 再删模型`
250
+ : `🔗 入站引用(跨模型引用需 --unbind-references:${crossLabels.join(" → ")})→ 再删模型`);
220
251
  }
221
252
  }
222
253
  catch {
@@ -325,7 +356,7 @@ export async function cmdModelPurge(args, injected) {
325
356
  "用法:omc model-purge --code <模型code> [--purge-instances] [--unbind-references] [--env <环境>] [--apply]",
326
357
  " 一条命令按依赖倒序清掉:列表视图 → 自建业务规则 → 流程实例 → 流程 → 模型(字段/表单/计算规则/预置规则随模型级联)。",
327
358
  " 默认 dry-run(只列计划,不写;入站引用的 unbindSteps 已在 dry-run 预置)。--purge-instances 才删流程实例(workflow.delete 遇到实例会 402508)。",
328
- " --unbind-references 才会先按 deletionSteps 拆入站引用(field.delete 引用列 + field.publish 所属模型,**破坏性:列数据不可恢复**),再删模型;不带它 --apply 不会自动拆引用。",
359
+ " --unbind-references 才会拆**跨模型**入站引用(引用方模型的关联列;field.delete + field.publish,**破坏性:列数据不可恢复**);自引用列属于被删模型自身,--apply 会自动拆(仅当没有跨模型引用时;混合引用需该 flag 一次处理,避免半拆)。",
329
360
  " 每步回读确认;某步失败即停并说明已完成到哪一步(幂等,可修好后重跑)。",
330
361
  ].join("\n");
331
362
  const invalid = (message) => {
@@ -348,15 +379,35 @@ export async function cmdModelPurge(args, injected) {
348
379
  const referenced = plan.inboundReferences !== undefined && plan.inboundReferences.length > 0;
349
380
  const unbindEnabled = plan.unbindReferences === true;
350
381
  const blocked = plan.blockers.length > 0;
382
+ // F6(0.8.17,探针 K):只有跨模型引用才是 blocker。自引用(本模型自己的
383
+ // 子表关联列指回自身)从 0.8.16 起由 --apply 自动拆,dry-run 却仍回
384
+ // blocker:"model-referenced-by"——调用方会把它读成「必须先 --unbind-references,
385
+ // 否则跑不动」,与 apply 的实际行为相反。自引用改为 warning(带 step 清单),
386
+ // 顶层 blocker 只在真有跨模型引用(需要用户决策删别人模型的列)时出现。
387
+ const crossModelReferenced = (plan.crossModelUnbindSteps?.length ?? 0) > 0;
388
+ const selfReferenced = !crossModelReferenced && (plan.selfUnbindSteps?.length ?? 0) > 0;
351
389
  writeEnvelope(envelope("ok", {
352
390
  // F4(0.8.12,探针 G):入站引用是「删模型必然要拆的内部列」,是计划里的
353
391
  // 一步,不是执行失败——dry-run 只有真 blocker(活流程实例)才 blocked。
354
- // 未带 --unbind-references 时保留 blocker:"model-referenced-by"(与
355
- // model.delete dry-run 同名同义),并给出预置的 unbindSteps /
392
+ // 未带 --unbind-references 时,跨模型引用保留 blocker:"model-referenced-by"
393
+ // (与 model.delete dry-run 同名同义),并给出预置的 unbindSteps /
356
394
  // wouldRequireFlags,让调用方无需先加破坏性开关就能看完整计划。
357
395
  status: blocked ? "blocked" : "dry-run",
358
396
  ...plan,
359
- ...(referenced && !unbindEnabled ? { blocker: "model-referenced-by" } : {}),
397
+ ...(referenced && !unbindEnabled && crossModelReferenced ? { blocker: "model-referenced-by" } : {}),
398
+ ...(referenced && !unbindEnabled && selfReferenced
399
+ ? {
400
+ warnings: [
401
+ {
402
+ code: "self-reference-auto-unbind",
403
+ autoUnbindSteps: plan.selfUnbindSteps,
404
+ message: `${plan.schemaCode} 只有自引用(本模型子表关联列指回自身):` +
405
+ `--apply 会自动拆(${(plan.selfUnbindSteps ?? []).join(" → ")}),无需 --unbind-references;跨模型引用:无。` +
406
+ `破坏性:被删列数据不可恢复。`,
407
+ },
408
+ ],
409
+ }
410
+ : {}),
360
411
  ...(blocked
361
412
  ? {}
362
413
  : {
@@ -364,9 +415,11 @@ export async function cmdModelPurge(args, injected) {
364
415
  (referenced
365
416
  ? unbindEnabled
366
417
  ? `已开启 --unbind-references:--apply 会先执行 unbindSteps(${(plan.unbindSteps ?? []).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**),再把 model.delete 交给主流程级联。`
367
- : `入站引用已预扫(与 model.delete 同一份 gate):--apply 未带 --unbind-references 时 model.delete 会零写入拒绝。` +
368
- `unbindSteps 是本命令会执行的拆引用步骤(${(plan.unbindSteps ?? []).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**);` +
369
- `nextCommand 是同一条命令加上 ${(plan.wouldRequireFlags ?? ["--unbind-references"]).join(" ")} --apply,也可以自己按 deletionSteps 逐条拆。`
418
+ : (plan.selfUnbindSteps?.length ?? 0) > 0 && (plan.crossModelUnbindSteps?.length ?? 0) > 0
419
+ ? `检测到自引用 + 跨模型引用:--apply 不带 flag 时**不会自动拆任何引用**(避免半拆,列数据不可恢复),model.delete 会零写入拒绝;nextCommand 带 --unbind-references 一次处理。`
420
+ : (plan.selfUnbindSteps?.length ?? 0) > 0
421
+ ? `0.8.16 F7:--apply 会**自动**拆自引用列(${(plan.selfUnbindSteps ?? []).join(" → ")};**破坏性:删除列数据不可恢复**),无需 --unbind-references;跨模型引用:无。`
422
+ : `--apply 不会自动拆(只有跨模型引用:${(plan.crossModelUnbindSteps ?? []).join(" → ")});model.delete 会零写入拒绝,nextCommand 带 --unbind-references。`
370
423
  : ""),
371
424
  }),
372
425
  }, request));
@@ -406,9 +459,7 @@ export async function executeUnbindSteps(call, steps) {
406
459
  const executed = [];
407
460
  for (let index = 0; index < candidates.length; index += 1) {
408
461
  const step = candidates[index];
409
- const label = step.tool === "field.delete"
410
- ? `field.delete:${String(step.args.schemaCode ?? "")}.${String(step.args.code ?? "")}`
411
- : `field.publish:${String(step.args.schemaCode ?? "")}`;
462
+ const label = deletionStepLabel(step);
412
463
  const schemaCode = step.args.schemaCode;
413
464
  const code = step.args.code;
414
465
  const shapeValid = typeof schemaCode === "string" &&
@@ -482,16 +533,27 @@ export async function executePurge(plan, session, call) {
482
533
  steps.push(...instanceOutcome.steps);
483
534
  let failed = instanceOutcome.failed;
484
535
  const unremovableInstances = instanceOutcome.unremovableInstances;
485
- // F7(0.8.9,探针 D):`--unbind-references` 才执行拆引用。只跑
536
+ // F7(0.8.9,探针 D)+ 0.8.16 F7:`--unbind-references` 执行全部拆引用;
537
+ // 不带 flag 时只自动执行 `selfReference` 那部分(模型自身的子表列指回自身,
538
+ // 删模型必然带走它)。**自引用与跨模型引用同时存在时 fail-closed**:不自动
539
+ // 拆任何引用——先删自引用列再被 model.delete 拒绝就是「半拆」,而列数据不可
540
+ // 恢复。混合引用必须由用户带 --unbind-references 一次处理。只跑
486
541
  // deletionSteps 里的 field.delete/field.publish(model.delete 仍由本命令的
487
542
  // 主流程负责,绝不重复)。任一步失败即停,模型不删。
488
543
  let unbindOutcome;
489
- if (!failed && plan.unbindReferences === true && (plan.deletionSteps?.length ?? 0) > 0) {
544
+ let autoUnbindSelfReferences = false;
545
+ const selfLabels = new Set(plan.selfUnbindSteps ?? []);
546
+ const mixedReferencesWithoutFlag = plan.unbindReferences !== true && selfLabels.size > 0 && (plan.crossModelUnbindSteps?.length ?? 0) > 0;
547
+ if (!failed && !mixedReferencesWithoutFlag && (plan.deletionSteps?.length ?? 0) > 0) {
490
548
  const candidates = plan.deletionSteps ?? [];
491
- unbindOutcome = await executeUnbindSteps(call, candidates);
492
- steps.push(...unbindOutcome.steps);
493
- if (unbindOutcome.failed)
494
- failed = true;
549
+ const thatNeedRunning = plan.unbindReferences === true ? candidates : candidates.filter((step) => selfLabels.has(deletionStepLabel(step)));
550
+ if (thatNeedRunning.length > 0) {
551
+ autoUnbindSelfReferences = plan.unbindReferences !== true;
552
+ unbindOutcome = await executeUnbindSteps(call, thatNeedRunning);
553
+ steps.push(...unbindOutcome.steps);
554
+ if (unbindOutcome.failed)
555
+ failed = true;
556
+ }
495
557
  }
496
558
  // 2) the model — everything else cascades with it.
497
559
  let referrers = [];
@@ -520,18 +582,23 @@ export async function executePurge(plan, session, call) {
520
582
  }
521
583
  }
522
584
  const status = failed ? "partial" : "ok";
523
- const rerunCommand = unbindPurgeCommand(schemaCode);
585
+ const mixedReferencesAtRefusal = plan.unbindReferences !== true && selfLabels.size > 0 && (plan.crossModelUnbindSteps?.length ?? 0) > 0;
586
+ const refusalHasCrossModel = (plan.crossModelUnbindSteps?.length ?? 0) > 0 ||
587
+ (deleteRefusal?.inboundReferences ?? []).some((reference) => reference.selfReference !== true);
588
+ // Self-only refs are auto-unbound by a plain `--apply`, so pointing the retry
589
+ // at the destructive flag would be a lie.
590
+ const rerunCommand = refusalHasCrossModel ? unbindPurgeCommand(schemaCode) : purgeApplyCommand(schemaCode);
524
591
  // Pass the inner refusal through verbatim; the purge-level receipt must not
525
592
  // promise keys it dropped (F9: message named deletionSteps that were absent).
526
593
  const failureFields = unbindOutcome?.failed === true
527
594
  ? {
528
595
  nextAction: "fix-and-rerun",
529
- unbindReferences: true,
596
+ ...(plan.unbindReferences === true ? { unbindReferences: true } : { autoUnbindSelfReferences: true }),
530
597
  failedStep: unbindOutcome.failedStep,
531
598
  remainingSteps: unbindOutcome.remaining,
532
599
  modelDeletePending: true,
533
600
  nextCommand: rerunCommand,
534
- message: `${schemaCode} 未删除:拆引用在 ${unbindOutcome.failedStep ?? "某一步"} 失败,已停在该步;` +
601
+ message: `${schemaCode} 未删除:${autoUnbindSelfReferences ? "自动拆自引用" : "拆引用"}在 ${unbindOutcome.failedStep ?? "某一步"} 失败,已停在该步;` +
535
602
  `**未调用 model.delete,模型仍存在**。原因:${unbindOutcome.failureMessage ?? "平台拒绝"}。` +
536
603
  `已成功的拆引用步骤不回滚(幂等,重跑不会重复破坏);修复后重跑本命令(nextCommand)继续。`,
537
604
  }
@@ -543,9 +610,13 @@ export async function executePurge(plan, session, call) {
543
610
  deletionOrder: purgeDeletionOrder(deleteRefusal.deletionSteps),
544
611
  nextCommand: rerunCommand,
545
612
  ...(referrers.length > 0 ? { blockedBy: referrers } : {}),
546
- message: `${schemaCode} 未删除(零写入拒绝,未启动平台删除任务)。${deleteRefusal.message} ` +
547
- `两条路:① 一条命令自动拆引用:nextCommand(--unbind-references;**破坏性:会删除指向本模型的引用列/子表关联列,列数据不可恢复**),` +
548
- `拆完引用后由 model.delete 级联;② 自己按 deletionSteps 逐条执行。不要在未拆引用时重试 --apply(不带 --unbind-references 仍会零写入拒绝)。`,
613
+ message: (mixedReferencesAtRefusal
614
+ ? `${schemaCode} 未删除:检测到自引用 + 跨模型引用。为避免半拆,本次零写入(未删除任何列、未发布模型、未启动平台删除任务)。按 deletionSteps 逐条执行,或 nextCommand(带 --unbind-references)一次处理。 `
615
+ : `${schemaCode} 未删除(零写入拒绝,未启动平台删除任务)。`) +
616
+ `${deleteRefusal.message} ` +
617
+ `两条路:① 一条命令自动拆引用:nextCommand(${refusalHasCrossModel ? "--unbind-references;" : ""}**破坏性:会删除指向本模型的引用列/子表关联列,列数据不可恢复**),` +
618
+ `拆完引用后由 model.delete 级联;② 自己按 deletionSteps 逐条执行。` +
619
+ (refusalHasCrossModel ? "不要在未拆引用时重试 --apply(不带 --unbind-references 仍会零写入拒绝)。" : ""),
549
620
  }
550
621
  : {
551
622
  nextAction: "fix-and-rerun",
@@ -560,7 +631,11 @@ export async function executePurge(plan, session, call) {
560
631
  schemaCode,
561
632
  verdict: plan.modelExists && !failed ? "cascading" : "clean",
562
633
  ...(plan.workflowCode !== undefined ? { workflowCode: plan.workflowCode } : {}),
563
- ...(plan.unbindReferences === true ? { unbindReferences: true } : {}),
634
+ ...(plan.unbindReferences === true
635
+ ? { unbindReferences: true }
636
+ : autoUnbindSelfReferences
637
+ ? { autoUnbindSelfReferences: true }
638
+ : {}),
564
639
  ...(unbindOutcome !== undefined ? { unboundSteps: unbindOutcome.executed, unbindFailed: unbindOutcome.failed } : {}),
565
640
  deletedInstances: steps.filter((step) => step.step.startsWith("workflow.delete_instance:") && step.status === "ok").length,
566
641
  ...(unremovableInstances.length > 0 ? { unremovableInstances } : {}),
@@ -84,7 +84,7 @@ export async function cmdModelScaffold(args) {
84
84
  " 默认 dry-run(列出将要做什么);--apply 依次执行 建模型→建字段→建子列→发布字段→发布表单。",
85
85
  " 幂等:模型/字段已存在记为 skipped 继续;有真失败时默认不发布(--force-publish 可强发)。",
86
86
  " 每个子调用使用独立 requestId(避免同 id 不同参数被幂等门拒绝);重入已存在字段记 skipped。",
87
- " --fields-file 从配置根内文件读 JSON 数组;--fields - 从 stdin 读 JSON 数组。",
87
+ " --fields-file 从配置根内文件读 JSON 数组(根 = $OMC_CONFIG_HOME 或当前工作目录,根外拒绝;免落盘用 --fields - 读 stdin);--fields - 从 stdin 读 JSON 数组。",
88
88
  ].join("\n");
89
89
  const invalid = (message) => {
90
90
  writeEnvelope(envelope("error", {}, request, { code: "invalid-input", message: `${message}\n${usage}`, retryable: false }));
@@ -402,15 +402,23 @@ export async function cmdModelScaffold(args) {
402
402
  }
403
403
  function describeScaffoldPlan(options) {
404
404
  const childTables = options.fields.filter((field) => scaffoldChildrenOf(field).length > 0);
405
+ const declaredFieldCount = options.fields.length;
406
+ const childColumnCount = options.fields.reduce((sum, field) => sum + scaffoldChildrenOf(field).length, 0);
407
+ // F11(0.8.17,探针 K):dry-run 与 --apply 必须同键同值。旧 dry-run 只给
408
+ // `fields`(顶层数)和一个错的 `childFieldCount`(子表数 + 子列数 = 6,而真实
409
+ // 子列是 5),apply 却给 declaredFieldCount/childColumnCount/fieldCount——同一
410
+ // 份计划两套计数,探针对不上。现在统用 apply 的键名与算法。
405
411
  return {
406
412
  model: options.code,
407
413
  name: options.name,
408
- fields: options.fields.length,
414
+ declaredFieldCount,
415
+ childColumnCount,
416
+ fieldCount: declaredFieldCount + childColumnCount,
409
417
  childTables: childTables.map((field) => ({
410
418
  code: field.code,
411
419
  childFields: scaffoldChildrenOf(field).map((entry) => entry.code),
412
420
  })),
413
- childFieldCount: childTables.reduce((sum, field) => sum + 1 + scaffoldChildrenOf(field).length, 0),
421
+ countsNote: "dry-run 与 --apply 同键同义:declaredFieldCount = --fields 声明的顶层字段数;childColumnCount = 子列总数(子表自身不计数);fieldCount = 最终业务字段总数(declaredFieldCount + childColumnCount)。",
414
422
  publishForm: options.publishForm,
415
423
  steps: [
416
424
  `model.create ${options.code}`,
@@ -820,6 +820,107 @@ function projectPathOnSource(source, path) {
820
820
  }
821
821
  return { ...first };
822
822
  }
823
+ /**
824
+ * F8(0.8.17 真机 P1):拒绝态投影会把「没有值」伪装成成功值。`data.list` 对不存在的
825
+ * 模型回 `{status:"refused", blocker:"schema-not-found", total:0}`,`--jq total` 于是
826
+ * 回 `0`——与「模型存在但没有行」同形,调用方会把「模型没了」读成「0 条数据」。
827
+ *
828
+ * 拒绝不是答案:非诊断路径不投影,回拒绝摘要(blocker/message/nextCommand 原样保留)。
829
+ * **不**笼统禁止 refused 的所有投影——`--jq blocker` / `--jq message` 正是排查入口,
830
+ * 挡掉它们等于让防护挡住自己的逃生门。只挡「会伪装成功值」的载荷字段。
831
+ */
832
+ const REFUSAL_DIAGNOSTIC_KEYS = new Set([
833
+ // 结论与排查入口
834
+ "status",
835
+ "blocker",
836
+ "message",
837
+ "nextCommand",
838
+ "nextAction",
839
+ "errcode",
840
+ "platformErrcode",
841
+ "reason",
842
+ "citation",
843
+ "detail",
844
+ "diagnostic",
845
+ "environmentFingerprint",
846
+ // 证据面:引用点、校验失败、可用候选、恢复选项、存在性与读回
847
+ "references",
848
+ "validation",
849
+ "issues",
850
+ "available",
851
+ "options",
852
+ "coverage",
853
+ "exists",
854
+ "schemaCode",
855
+ "schemaCodes",
856
+ "readback",
857
+ // 身份键(拒绝回执用它们点名对象;不是结果集)
858
+ "ruleCode",
859
+ "serviceCode",
860
+ "methodCode",
861
+ "serviceMethodCode",
862
+ "fieldCode",
863
+ "propertyCode",
864
+ "schema",
865
+ "code",
866
+ "path",
867
+ // 证据计数与扫描自述(不是「结果有 N 行」的载荷 total/count)
868
+ "referenceCount",
869
+ "referenceCountNote",
870
+ "scanNote",
871
+ "methods",
872
+ "disappearingRefs",
873
+ // 恢复指引
874
+ "doNot",
875
+ "note",
876
+ "retryable",
877
+ "environment",
878
+ "owner",
879
+ "lockOwner",
880
+ "recovery",
881
+ "steps",
882
+ "causes",
883
+ ]);
884
+ /**
885
+ * 拒绝态投影闸门的**唯一真相源**(测试直接引用它钉住键集:新增 evidence 键
886
+ * 必须显式登记,否则会被当成载荷挡掉)。
887
+ */
888
+ export function refusalDiagnosticKeys() {
889
+ return REFUSAL_DIAGNOSTIC_KEYS;
890
+ }
891
+ /**
892
+ * 该路径读的是「拒绝回执怎么说的」而不是「平台数据」。首段是信封键
893
+ * (result./ok.)时看下一段;`--jq result`(整包拒绝回执)本身允许——
894
+ * status/blocker 都在里面,不会被读成成功值。
895
+ */
896
+ export function isRefusalDiagnosticPath(path) {
897
+ const segments = path.replace(/^\$\.?/, "").replace(/^[.\/]+/, "").split(/[.\/[]/).filter(Boolean);
898
+ const head = segments[0] === "result" || segments[0] === "ok" ? segments[1] : segments[0];
899
+ if (head === undefined)
900
+ return true;
901
+ return REFUSAL_DIAGNOSTIC_KEYS.has(head);
902
+ }
903
+ /**
904
+ * F7(0.8.17 真机 P1)配套:单路径命中 null 时,若源回执用 `<key>Omitted:true`
905
+ * 显式声明「这段正文已外置」,把这句话带进回执——否则 `--jq models` 回
906
+ * `result:null`,与「真的没有模型」同形(discover_environment 缓存命中就是
907
+ * models:null + modelsOmitted:true)。只给提示,不改值:投影仍是纯投影。
908
+ *
909
+ * 复核修正(0.8.17):这里**不能**引用本回执里的 tablesHint/fetch/artifactId——
910
+ * `detailFile → detailArtifactId` 的替换发生在投影之后,`--jq` 面拿不到它们。
911
+ * 只给一定能执行的下一步:去掉 --jq 重取同一条命令。
912
+ */
913
+ function omittedNullHint(path, source) {
914
+ if (source === null || typeof source !== "object" || Array.isArray(source))
915
+ return undefined;
916
+ const head = path.replace(/^\$\.?/, "").replace(/^[.\/]+/, "").split(/[.\/[]/).filter(Boolean)[0];
917
+ if (head === undefined)
918
+ return undefined;
919
+ const record = source;
920
+ if (record[head] !== null || record[`${head}Omitted`] !== true)
921
+ return undefined;
922
+ return `「${head}」本次为 null 且 ${head}Omitted:true——是「正文已外置」的声明,不是空表(空表是 [])。去掉 --jq 重取同一条命令:未投影回执里有 tablesHint / fetch(含取回该段正文的命令);别把 null 读成「没有数据」。`;
923
+ }
823
924
  export function projectResultExtract(result, paths, keysOnly, retry, explain = false) {
824
925
  const artifactId = typeof result.detailArtifactId === "string" ? result.detailArtifactId : typeof result.artifactId === "string" ? result.artifactId : undefined;
825
926
  // Tools hand an in-process artifact as `detailFile` (a local path);
@@ -857,6 +958,11 @@ export function projectResultExtract(result, paths, keysOnly, retry, explain = f
857
958
  // exist on the result but would silently resolve to a wrong-shaped value on
858
959
  // the artifact (or miss entirely). Never fall back to "parent object".
859
960
  const projectionSource = source;
961
+ // F8:拒绝态非诊断路径一律不投影(见 REFUSAL_DIAGNOSTIC_KEYS)。放在 artifact
962
+ // 合流之后:无论值来自回执还是外置正文,拒绝态的载荷字段都不是答案。
963
+ const refusalSuppressedPaths = result.status === "refused"
964
+ ? new Set(paths.filter((path) => !isRefusalDiagnosticPath(path)))
965
+ : undefined;
860
966
  const out = {
861
967
  status: result.status ?? "ok",
862
968
  ...(artifactId !== undefined ? { artifactId, sha256: artifact?.sha256 } : {}),
@@ -865,10 +971,15 @@ export function projectResultExtract(result, paths, keysOnly, retry, explain = f
865
971
  // 投影只改变取值路径,不改变源结果的完整性事实。尤其是外置 artifact
866
972
  // 场景,调用方仍必须能判断 items 是否被折叠,以及源侧 total/itemsCount。
867
973
  // 只透传源中实际存在的键;未截断结果不要凭空写 truncated:false。
974
+ // 拒绝态例外:total/itemsCount 是拒绝回执的默认 0——透传出去 `--jq total`
975
+ // 又变回「0 行」,与「存在但 0 行」同形(F8)。诊断路径也不透传:它们读的是
976
+ // 拒绝事实,不是结果集规模。
868
977
  const sourceRecord = source && typeof source === "object" && !Array.isArray(source)
869
978
  ? source
870
979
  : undefined;
871
980
  for (const key of ["truncated", "truncatedKeys", "itemsCount", "total"]) {
981
+ if (result.status === "refused" && (key === "total" || key === "itemsCount"))
982
+ continue;
872
983
  if (sourceRecord !== undefined && Object.prototype.hasOwnProperty.call(sourceRecord, key))
873
984
  out[key] = sourceRecord[key];
874
985
  }
@@ -952,6 +1063,21 @@ export function projectResultExtract(result, paths, keysOnly, retry, explain = f
952
1063
  return Buffer.byteLength(JSON.stringify(candidate), "utf8") <= 300 ? { nextCommand: fullFace.nextCommand } : {};
953
1064
  };
954
1065
  out.extract = paths.map((path) => {
1066
+ // F8:拒绝态下载荷字段不是值——回拒绝摘要而不是默认 0/[]/null。
1067
+ // 键本身不存在(`--jq blokcer`)时不吞成拒绝摘要:落回正常 pathMiss,
1068
+ // 保留 didYouMean / correctPath 的自愈提示。
1069
+ if (refusalSuppressedPaths?.has(path) === true && !projectPathOnSource(projectionSource, path).projected.missed) {
1070
+ const blocker = typeof result.blocker === "string" ? result.blocker : "refused";
1071
+ return {
1072
+ path,
1073
+ content: null,
1074
+ refused: true,
1075
+ blocker,
1076
+ ...(typeof result.message === "string" ? { message: result.message } : {}),
1077
+ ...(typeof result.nextCommand === "string" ? { nextCommand: result.nextCommand } : {}),
1078
+ hint: `本次调用被拒绝(${blocker}):「${path}」是拒绝回执的默认字段,不代表「有 0 条 / 空列表」。诊断值用 --jq blocker / message / nextCommand。`,
1079
+ };
1080
+ }
955
1081
  // r28f F2:对象构造 / 函数调用不是 pathMiss——先识别,别伪装成键缺失。
956
1082
  const unsupported = detectUnsupportedJqSyntax(path);
957
1083
  if (unsupported !== undefined) {
@@ -1058,11 +1184,14 @@ export function projectResultExtract(result, paths, keysOnly, retry, explain = f
1058
1184
  : compactMissExtra(path, single.at, baseMiss, fullFace)),
1059
1185
  };
1060
1186
  }
1187
+ const singleValue = single.value ?? null;
1188
+ const nullHint = singleValue === null ? omittedNullHint(path, projectionSource) : undefined;
1061
1189
  return {
1062
1190
  path,
1063
- content: single.value ?? null,
1191
+ content: singleValue,
1064
1192
  ...(autoStripped !== undefined ? { autoStripped } : {}),
1065
1193
  ...(preferResult ? { from: "result" } : {}),
1194
+ ...(nullHint !== undefined ? { hint: nullHint } : {}),
1066
1195
  };
1067
1196
  });
1068
1197
  // r30a F21 / r31c F7: single path keeps top-level `content`. Multi-path used
@@ -1072,12 +1201,14 @@ export function projectResultExtract(result, paths, keysOnly, retry, explain = f
1072
1201
  // projections so two columns align without a second round trip.
1073
1202
  const extracts = out.extract;
1074
1203
  if (paths.length === 1) {
1075
- out.content = extracts[0]?.content ?? null;
1204
+ // 拒绝态条目不是值——不写顶层 content(否则 `content:null` 又成了「值就是 null」)。
1205
+ if (extracts[0]?.refused !== true)
1206
+ out.content = extracts[0]?.content ?? null;
1076
1207
  }
1077
1208
  else {
1078
1209
  const columns = extracts.map((entry) => ({
1079
1210
  path: entry.path,
1080
- values: entry.pathMiss === true || entry.unsupportedSyntax === true
1211
+ values: entry.pathMiss === true || entry.unsupportedSyntax === true || entry.refused === true
1081
1212
  ? []
1082
1213
  : Array.isArray(entry.content)
1083
1214
  ? entry.content
@@ -1114,6 +1245,21 @@ export function projectResultExtract(result, paths, keysOnly, retry, explain = f
1114
1245
  out.hint = `${RESULT_RELATIVE_PATH_NOTE}逐条定位见 extract[](或 rows[] 列对齐);语法教程:${PATH_MISS_HELP_REF}。`;
1115
1246
  }
1116
1247
  }
1248
+ // F8:拒绝态的结论与排查载荷原样保留(不论本路径是否被挡下)——`--jq blocker`
1249
+ // 的信封 error 也要是**这条**拒绝,不是笼统的 "operation refused"。
1250
+ if (result.status === "refused" && paths.length > 0) {
1251
+ if (typeof result.blocker === "string")
1252
+ out.blocker = result.blocker;
1253
+ if (typeof result.message === "string")
1254
+ out.message = result.message;
1255
+ if (typeof result.nextCommand === "string")
1256
+ out.nextCommand = result.nextCommand;
1257
+ // 只有被挡下的载荷路径才是「没回答」;诊断路径(blocker 等)是回答了。
1258
+ if (extracts.some((entry) => entry.refused === true)) {
1259
+ out.unanswered = true;
1260
+ out.hint = `拒绝态不投影载荷字段:本次调用被拒绝(${String(out.blocker)}),被挡下的路径读到的是拒绝回执的默认值(0 / [] / null),与「有 0 条」同形。排查用 --jq blocker / message / nextCommand;要数据先解除拒绝。`;
1261
+ }
1262
+ }
1117
1263
  }
1118
1264
  return out;
1119
1265
  }
@@ -1124,7 +1270,8 @@ export function unwrapSinglePathProjection(projected) {
1124
1270
  if (!Array.isArray(extracts) || extracts.length !== 1)
1125
1271
  return undefined;
1126
1272
  const entry = extracts[0];
1127
- if (entry.pathMiss === true || entry.unsupportedSyntax === true)
1273
+ // refused:拒绝摘要不是值,不能解包成 `result:<默认值>`。
1274
+ if (entry.pathMiss === true || entry.unsupportedSyntax === true || entry.refused === true)
1128
1275
  return undefined;
1129
1276
  const resultMeta = { path: entry.path };
1130
1277
  for (const key of SINGLE_PATH_META_KEYS) {
@@ -37,6 +37,44 @@ const submitCrossFieldCheck = Object.freeze({
37
37
  ],
38
38
  requiresEnvironmentDerivedIds: false,
39
39
  });
40
+ const submitFieldVsConstant = Object.freeze({
41
+ id: "submit-field-vs-constant",
42
+ aliases: ["金额必须大于0", "提交校验 常量比较"],
43
+ title: "提交校验最小例:字段 vs 常量(dataRuleType:1 + checkType:2)——checkType:2=提交校验、dataRuleType:1=校验类;右值 valueType:\"custom\" 是 JSON 值对象(平台也接受裸字面量)",
44
+ status: "offline-valid",
45
+ tool: "datarule.create",
46
+ args: {
47
+ environment,
48
+ schemaCode: model,
49
+ propertyCode: "amount",
50
+ dataRuleType: 1,
51
+ checkType: 2,
52
+ name: "金额必须大于 0",
53
+ options: {
54
+ conditions: '{amount} 大于 {"valueType":"custom","value":0}',
55
+ prompt: "金额必须大于 0",
56
+ },
57
+ },
58
+ preconditions: [
59
+ "目标字段(示例 `amount`)已发布。",
60
+ "**判型一句话**:`dataRuleType:1` 是校验类规则,`checkType:2` 是其中的提交校验;两者一起才是「提交时按条件校验」。",
61
+ ],
62
+ conditionalRequirements: [
63
+ '**右值 `{"valueType":"custom","value":0}` 是 JSON 值对象**;平台也接受裸字面量(如 `{qty} 大于 100`)。只有跨字段比较才用 `{"valueType":"currentModel","value":"<字段code>"}`。',
64
+ "条件串是 `{字段code} 操作符 右值` 三段单空格(中文操作符优先,如 大于/大于等于/等于);多条件用 ` && `、多组用 ` || `。",
65
+ "`prompt` 存纯文本(门户原样显示,URL 编码会弹 %E5.. 乱码)。",
66
+ "执行面:该规则默认只在门户表单提交时由前端执行,CLI `data.submit` 对非空值不跑条件校验——配置面用 `datarule.list` 核对,行为在门户点验。",
67
+ ],
68
+ priorToolReferences: [{ tool: "field.list", args: { environment, schemaCode: model, published: true }, purpose: "确认目标字段已发布" }],
69
+ dryRun: { supported: true, command: `omc call datarule.create --env ${environment} --dry-run --args '<recipe.args>'`, notes: "dry-run 过条件协议校验(裸右值/prompt 编码当场拒),零 wire" },
70
+ expectedReadback: { performed: { errcode: 0 }, readback: { dataRuleType: 1, checkType: 2, rulePresent: true } },
71
+ refusalRecovery: [
72
+ { code: "datarule-submit-prompt-encoded", action: "prompt 存纯文本,别 URL 编码" },
73
+ { code: "datarule-options-invalid", action: `复制 recipe 的三段条件串;常量右值用 {"valueType":"custom","value":<值>},跨字段才用 currentModel` },
74
+ ...commonRecovery,
75
+ ],
76
+ requiresEnvironmentDerivedIds: false,
77
+ });
40
78
  const dataruleCalcRule = Object.freeze({
41
79
  id: "field-compute-rule",
42
80
  title: "字段计算规则:普通字段 + 计算规则(type2,勿用「计算公式」字段类型)",
@@ -218,6 +256,6 @@ const dataruleDisplay = Object.freeze({
218
256
  requiresEnvironmentDerivedIds: false,
219
257
  });
220
258
  export const DATARULE_METADATA = Object.freeze({
221
- "datarule.create": Object.freeze({ recipes: [submitCrossFieldCheck, dataruleCalcRule, dataruleSubtableSum, dataruleChildColumn, dataruleRequired, dataruleReadonly, dataruleDisplay], relatedTools: ["field.list", "datarule.list"] }),
259
+ "datarule.create": Object.freeze({ recipes: [submitFieldVsConstant, submitCrossFieldCheck, dataruleCalcRule, dataruleSubtableSum, dataruleChildColumn, dataruleRequired, dataruleReadonly, dataruleDisplay], relatedTools: ["field.list", "datarule.list"] }),
222
260
  });
223
261
  //# sourceMappingURL=datarule.js.map
@@ -53,7 +53,7 @@ const formDraftTwoColumn = Object.freeze({
53
53
  "**改既有表单**:优先用 `layout:{rows,...}`(见下,增量改行分组/span、不必回传整包 attrs);若要手写整包,先 `form.get full:true` 取 `publishedAttributesJson` 作基线(含 Title/Group/creater/createdTime/sequenceNo 系统控件),只改行分组与 span,不要把本配方的三字段最小布局直接盖上去。判据:`form.get full:true` 返回非空 publishedAttributesJson(或 published:true)→ 既有表单,受 form-publish-degrade 约束;无表单行 / publishedAttributesJson 为空或 \"{}\" → 新建表单,本配方可直接用。",
54
54
  ],
55
55
  conditionalRequirements: [
56
- "**改既有表单可用增量布局(不必回传整包 attrs)**:`form.draft {layout:{rows:[[\"visitNo\",\"customer\"],[\"remark\"]], spans:{visitNo:12,customer:12,remark:24}}}` 以已发布(无则草稿)表单为基线,只改这些控件的行分组与 span——其它控件/属性/HTML 逐键保留;未列入 rows 的控件(含 Title/Group/creater/createdTime/sequenceNo 等系统控件)保留原行,系统控件要移动须显式 `includeSystem:true`。layout 与 draftViewJson/draftAttributesJson/rebuild/fieldCodes/childColumns/refreshFromFields/fromReadback 互斥。列数仍由行分组决定,spans 省略时按行均分 24",
56
+ "**改既有表单可用增量布局(不必回传整包 attrs)**:`form.draft {layout:{rows:[[\"visitNo\",\"customer\"],[\"remark\"]], spans:{visitNo:12,customer:12,remark:24}}}` 以当前草稿为基线(草稿为空时退回已发布),只改这些控件的行分组与 span——其它控件/属性/HTML 逐键保留;未列入 rows 的控件(含 Title/Group/creater/createdTime/sequenceNo 等系统控件)保留原行,系统控件要移动须显式 `includeSystem:true`。layout 与 draftViewJson/draftAttributesJson/rebuild/fieldCodes/childColumns/refreshFromFields/fromReadback 互斥。列数仍由行分组决定,spans 省略时按行均分 24",
57
57
  "**列数由行分组决定,不由 span 决定**:一行放几个 code 就是几列;span 只控制控件在行内的 24 栅格宽度,且必须与行分组自洽(两列 span:12+12,整宽 span:24)",
58
58
  "draftAttributesJson 的每个控件的 `options` 必须是**对象**,不能是 JSON 字符串(否则运行时写 options.name_i18n 抛错、整页空白)",
59
59
  "**控件 type 是表单控件枚举,不是字段 propertyType**:1=单行文本, 2=多行文本, 3=日期, 4=数值, 5=单选, 6=复选, 7=下拉, 8=逻辑, 80=关联单选, 81=关联多选, 201=子表 …;对应 propertyType 0/1/3/2/12/13/14/4/9/11/8。错枚举默认拒 `form-control-type-mismatch`(逃生 allowTypeMismatch:true)",
@@ -85,7 +85,7 @@ const formDraftTwoColumn = Object.freeze({
85
85
  },
86
86
  {
87
87
  code: "form-layout-param-conflict",
88
- action: "layout 与 draftViewJson/draftAttributesJson/rebuild/fieldCodes/childColumns/refreshFromFields/fromReadback 互斥:只改行分组与 span 用 layout;整表重搭或整包回写才用 draft*Json/rebuild。要加子表列的正确顺序:① 先 `form.publish {rebuild:true}` 把子表列物化进已发布表单;② 再 `form.draft {layout}`(baseline=published);③ 再 `form.publish`",
88
+ action: "layout 与 draftViewJson/draftAttributesJson/rebuild/fieldCodes/childColumns/refreshFromFields/fromReadback 互斥:只改行分组与 span 用 layout;整表重搭或整包回写才用 draft*Json/rebuild。要加子表列的正确顺序:① 先 `form.draft {childColumns}` 把子表列绑进草稿;② 再 `form.draft {layout}`(以草稿为基线,不动刚绑的列);③ 再 `form.publish`。整表重建(rebuild:true)也会带上子表列,但会丢手工布局",
89
89
  },
90
90
  {
91
91
  code: "form-publish-degrade",