@stalfh233/omc-cli 0.8.6 → 0.8.7

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.
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { ENDPOINTS } from "../endpoints.js";
3
- import { assertFieldFamilyAllowed, assertSelectionChoicesAllowed, choicesArg, fieldOptionsArg, nameI18nJson, propertyTypeArg, relationTargetOf, relativeCodeArg, SYSTEM_FIELD_CODES, subFieldArg, } from "../field-families.js";
3
+ import { assertFieldFamilyAllowed, assertSelectionChoicesAllowed, choicesArg, fieldOptionsArg, nameI18nJson, propertyTypeArg, relativeCodeArg, SYSTEM_FIELD_CODES, subFieldArg, } from "../field-families.js";
4
4
  import { modelSchemaCodes, lintFieldCreateWrite } from "./field.js";
5
5
  import { fieldChangeWireBody, prepareFieldChange, sameFieldChange } from "../field-change.js";
6
6
  import { executeFormDraftWrite, executeFormPublishWrite } from "../form-support.js";
@@ -18,6 +18,7 @@ import { defineTool, ToolInputError, ToolRefusalError } from "../tool-types.js";
18
18
  import { wireCall, wireRows, WireError } from "../wire.js";
19
19
  import { assertTreeSelectionOptions } from "../field-tree-options.js";
20
20
  import { readModelRecord } from "../model-record.js";
21
+ import { inboundModelReferences, inboundReferenceRefusal } from "./model-references.js";
21
22
  import { MODEL_CREATE_BODY_DEFAULTS, MODEL_LANE_CONTRACT } from "./model-contract.js";
22
23
  import { flattenFolders } from "./folder.js";
23
24
  const MODEL_LANE = MODEL_LANE_CONTRACT.lane;
@@ -788,6 +789,94 @@ export function registerModelLane(tools) {
788
789
  summary: `即将创建模型 ${args.name ?? args.code}(${args.code})${args.modelType === "TREE" ? ",树型" : ",列表型"}${applicationCode ? `(应用 ${applicationCode})` : ""}`,
789
790
  };
790
791
  }
792
+ /** Default total wait for the platform's async delete task (== 8.6.26 physically_delete). */
793
+ const DELETE_TASK_DEFAULT_BUDGET_MS = 60_000;
794
+ /** Test/ops override for how long model.delete waits on the delete-history task. */
795
+ function deleteTaskBudgetMs() {
796
+ const raw = Number(process.env["OMC_MODEL_DELETE_TASK_BUDGET_MS"] ?? DELETE_TASK_DEFAULT_BUDGET_MS);
797
+ return Number.isFinite(raw) && raw >= 0 ? raw : DELETE_TASK_DEFAULT_BUDGET_MS;
798
+ }
799
+ /**
800
+ * Read the platform task behind physically_delete.
801
+ *
802
+ * `getDeleteHistory` (8.6.26 AppPackageController.java:1460-1476 /
803
+ * 2.1.5 :1369-1378) returns AppDeleteHistoryModel; the async worker writes
804
+ * TaskStatus.END on success and TaskStatus.FAIL + message on the caught
805
+ * exception (AppIntegrationFacadeImpl.java:1343-1355). That message is the only
806
+ * place the real refusal reason exists — the sync face always answers errcode 0.
807
+ */
808
+ async function readDeleteTaskSnapshot(session, taskId) {
809
+ const data = (await wireCall(session, { path: ENDPOINTS.appPackageDeleteHistory, query: { taskId } })).data;
810
+ const record = data !== null && typeof data === "object" ? data : {};
811
+ const raw = typeof record.taskStatus === "string" ? record.taskStatus : "";
812
+ const taskStatus = raw === "END" || raw === "FAIL" ? raw : "RUN";
813
+ const message = typeof record.message === "string" && record.message.length > 0 ? record.message : undefined;
814
+ return { taskStatus, ...(message !== undefined ? { message } : {}) };
815
+ }
816
+ /**
817
+ * Bounded wait: poll the delete task (when the platform returned a taskId) AND
818
+ * the authoritative model record. Never unbounded — an endlessly RUN task (the
819
+ * child-table self-reference bug) now ends as `deleteTask.taskStatus:"RUN"` after
820
+ * the budget instead of an endless "级联中".
821
+ */
822
+ async function waitForModelDelete(session, options) {
823
+ const budgetMs = options.budgetMs ?? deleteTaskBudgetMs();
824
+ const startedAt = Date.now();
825
+ let absent = false;
826
+ let task;
827
+ let delay = 1000;
828
+ let polls = 0;
829
+ let historyBroken = false;
830
+ for (;;) {
831
+ polls += 1;
832
+ if (!absent)
833
+ absent = await options.readAbsent();
834
+ let terminal = false;
835
+ let historyUnavailable = false;
836
+ if (options.taskId !== undefined && !historyBroken) {
837
+ try {
838
+ const snapshot = await readDeleteTaskSnapshot(session, options.taskId);
839
+ terminal = snapshot.taskStatus === "END" || snapshot.taskStatus === "FAIL";
840
+ task = {
841
+ taskId: options.taskId,
842
+ taskStatus: snapshot.taskStatus,
843
+ ...(snapshot.message !== undefined ? { message: snapshot.message } : {}),
844
+ waitedMs: Date.now() - startedAt,
845
+ polls,
846
+ budgetMs,
847
+ };
848
+ }
849
+ catch (error) {
850
+ // The history face is an addition; a build without it must not turn a
851
+ // delete into an error — fall back to the record face (still bounded).
852
+ historyUnavailable = true;
853
+ historyBroken = true;
854
+ task = {
855
+ taskId: options.taskId,
856
+ taskStatus: "RUN",
857
+ waitedMs: Date.now() - startedAt,
858
+ polls,
859
+ budgetMs,
860
+ historyUnavailable: true,
861
+ historyError: error instanceof Error ? error.message : String(error),
862
+ };
863
+ }
864
+ }
865
+ if (terminal)
866
+ break;
867
+ if (absent && (options.taskId === undefined || historyUnavailable || historyBroken))
868
+ break;
869
+ const elapsed = Date.now() - startedAt;
870
+ if (elapsed >= budgetMs) {
871
+ if (task !== undefined && task.historyUnavailable !== true)
872
+ task.budgetExhausted = true;
873
+ break;
874
+ }
875
+ await new Promise((resolve) => setTimeout(resolve, Math.max(1, Math.min(delay, budgetMs - elapsed))));
876
+ delay = Math.min(delay * 2, 4000);
877
+ }
878
+ return { absent, ...(task !== undefined ? { task } : {}) };
879
+ }
791
880
  /** model.delete writeTool extra arg: a session-aware dry-run that scans inbound references (no write). */
792
881
  async function modelDeleteDryRun(session, args) {
793
882
  const record = await (async () => {
@@ -803,42 +892,34 @@ export function registerModelLane(tools) {
803
892
  if (record === null)
804
893
  return { wouldChange: false, absent: true, mayBeReferenced: false, reason: "model-already-absent" };
805
894
  const resolved = await resolveModelTreeNode(session, args.schemaCode, args.applicationCode);
806
- const siblings = resolved.treeRows
807
- .filter((row) => row.type === "BizModel" && typeof row.code === "string" && row.code !== args.schemaCode)
808
- .map((row) => ({ schemaCode: String(row.code) }));
895
+ const references = await inboundModelReferences(session, [args.schemaCode], resolved.treeRows);
896
+ // Legacy dry-run shape: one row per referencing model with flat field codes
897
+ // (pinned by r3); the richer per-reference rows ride along as inboundReferences.
809
898
  const referencing = [];
810
- for (const sibling of siblings) {
811
- const fields = [];
812
- for (const isPublish of ["false", "true"]) {
813
- for (const row of wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: sibling.schemaCode, isPublish } })).data)) {
814
- if (relationTargetOf(row) !== args.schemaCode)
815
- continue;
816
- const code = row.code ?? row.propertyCode;
817
- if (typeof code === "string" && !fields.includes(code))
818
- fields.push(code);
819
- }
820
- }
821
- if (fields.length > 0)
822
- referencing.push({ schemaCode: sibling.schemaCode, fields });
899
+ for (const reference of references) {
900
+ const row = referencing.find((entry) => entry.schemaCode === reference.schemaCode) ?? { schemaCode: reference.schemaCode, fields: [] };
901
+ for (const field of reference.fields)
902
+ if (!row.fields.includes(field.code))
903
+ row.fields.push(field.code);
904
+ if (!referencing.includes(row))
905
+ referencing.push(row);
823
906
  }
824
907
  const nodeResolved = resolved.node !== undefined;
825
908
  return {
826
909
  // The dry-run now performs the same inbound-reference scan the executor
827
910
  // does, so "wouldChange:true" is never contradicted by a later refusal
828
911
  // (dogfood R3). `mayBeReferenced` is the honest preview.
829
- wouldChange: !nodeResolved || referencing.length === 0,
830
- mayBeReferenced: referencing.length > 0,
912
+ wouldChange: !nodeResolved || references.length === 0,
913
+ mayBeReferenced: references.length > 0,
914
+ ...(references.length > 0 ? inboundReferenceRefusal(args.schemaCode, references) : {}),
831
915
  referencingModels: referencing,
916
+ inboundReferences: references,
832
917
  treeNodeResolved: nodeResolved,
833
918
  applicationCode: resolved.applicationCode,
834
919
  // r28g F30:plan 以前只报对外引用,不说本模型内部从属资源会被级联清掉。
835
920
  // 计数走轻量读面;失败不挡 dry-run(仍给定性 cascadeNote)。
836
921
  cascadeNote: "删除模型会级联清掉其字段/表单/列表视图/字段级数据规则/业务规则(含平台预置触发行)及运行数据;其它模型对本模型的关联字段不会自动拆——见 mayBeReferenced/referencingModels。预置规则在幻影 schema 上 list 会重灌,故删前勿对已删 schemaCode 再 rule.list。",
837
- ...(referencing.length > 0
838
- ? { blocker: "model-referenced-by", nextAction: "先删引用方模型或先删其关联字段,再删本模型(依赖倒序)" }
839
- : !nodeResolved
840
- ? { blocker: "model-application-unresolved", nextAction: "显式传 applicationCode 或先 discover_environment 确认归属应用" }
841
- : {}),
922
+ ...(references.length > 0 ? {} : nodeResolved ? {} : { blocker: "model-application-unresolved", nextAction: "显式传 applicationCode 或先 discover_environment 确认归属应用" }),
842
923
  };
843
924
  }
844
925
  writeTool({
@@ -922,39 +1003,19 @@ export function registerModelLane(tools) {
922
1003
  }
923
1004
  const targetId = node.id;
924
1005
  const treeRowList = resolved.treeRows.length > 0 ? resolved.treeRows : await treeRows();
925
- // Ticket 23 inbound-reference precheck: the platform's sync face answers
926
- // errcode 0 while the async deleteFunctions dispatcher refuses with
927
- // "xxx被模型 yyy 引用,不能删除" — surface that refusal at call time with
928
- // the referencing models, before any write reaches the environment.
929
- const siblings = treeRowList
930
- .filter((row) => row.type === "BizModel" && typeof row.code === "string" && row.code !== args.schemaCode)
931
- .map((row) => ({ schemaCode: String(row.code), name: typeof row.name === "string" && row.name ? row.name : String(row.code) }));
932
- const referencingModels = [];
933
- for (const sibling of siblings) {
934
- const referencedFields = [];
935
- for (const isPublish of ["false", "true"]) {
936
- const listed = await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: sibling.schemaCode, isPublish } });
937
- for (const row of wireRows(listed.data)) {
938
- if (relationTargetOf(row) !== args.schemaCode)
939
- continue;
940
- const code = row.code ?? row.propertyCode;
941
- if (typeof code === "string" && !referencedFields.some((field) => field.code === code)) {
942
- referencedFields.push({ code, type: row.type ?? row.propertyType });
943
- }
944
- }
945
- }
946
- if (referencedFields.length > 0)
947
- referencingModels.push({ schemaCode: sibling.schemaCode, name: sibling.name, fields: referencedFields });
948
- }
949
- if (referencingModels.length > 0) {
1006
+ // Ticket 23 + 0.8.7 P0: the platform's inbound-reference gate is
1007
+ // getAllAppFunctionsByRelativedCodeNeedFilterDeleted (WORK_SHEET only,
1008
+ // direct self-relation excluded, child-table columns resolved back to
1009
+ // their PARENT model). That resolution is why a parent whose own
1010
+ // child-table column points at itself (a) is not filtered out and
1011
+ // (b) makes the async delete thread recurse forever (task stays RUN).
1012
+ // Refuse before any write with the exact unlink commands.
1013
+ const inboundReferences = await inboundModelReferences(session, [args.schemaCode], treeRowList);
1014
+ if (inboundReferences.length > 0) {
950
1015
  throw new ToolRefusalError({
951
1016
  status: "refused",
952
- blocker: "model-referenced-by",
953
1017
  schemaCode: args.schemaCode,
954
- referencingModels,
955
- deletionOrder: [...referencingModels.map((model) => model.schemaCode), args.schemaCode],
956
- nextCommand: `omc call model.delete --args '${JSON.stringify({ schemaCode: referencingModels[0].schemaCode })}'`,
957
- message: `${args.schemaCode} 被模型 ${referencingModels.map((model) => model.schemaCode).join("、")} 的关联字段引用,不能删除(服务端 deleteFunctions 的异步拒绝已提前到调用时)。依赖倒序清理:先删引用方模型(或先删其关联字段),再删被引用模型;引用方物理删除是平台异步任务、时长不定,完成后再删本模型。`,
1018
+ ...inboundReferenceRefusal(args.schemaCode, inboundReferences),
958
1019
  });
959
1020
  }
960
1021
  // Model deletion CASCADES the workflow template away but leaves
@@ -977,29 +1038,34 @@ export function registerModelLane(tools) {
977
1038
  // Both the model record and the app-tree node are eventually consistent.
978
1039
  // The platform answers as soon as the async task is queued; the cascade
979
1040
  // duration is NOT bounded (measured >4min on a live probe). Poll the
980
- // authoritative record face briefly, then report the tree-node state as a
981
- // pending hint with explicit wait-and-recheck guidance instead of a
982
- // failure — and never as a completed deletion.
983
- let absent = false;
984
- for (let attempt = 0; attempt < 16 && !absent; attempt += 1) {
985
- if (attempt > 0)
986
- await new Promise((resolve) => setTimeout(resolve, Math.min(1000 * attempt, 4000)));
987
- absent = (await readRecord()) === null;
988
- }
1041
+ // authoritative record face AND the platform delete-history task (which
1042
+ // carries the real FAIL reason) within one bounded budget.
1043
+ const wait = await waitForModelDelete(session, {
1044
+ ...(taskId !== undefined ? { taskId } : {}),
1045
+ readAbsent: async () => (await readRecord()) === null,
1046
+ });
1047
+ const absent = wait.absent;
1048
+ const deleteTask = wait.task;
1049
+ const taskFailed = deleteTask?.taskStatus === "FAIL";
989
1050
  const treeNodePending = (await treeRows()).some((row) => row.type === "BizModel" && row.code === args.schemaCode);
990
1051
  // r63(a-F9):absent:true 与 treeNodePending:true 曾并排出现——「记录没了但
991
1052
  // 树上还在」是不是没删干净?给一句显式清零判据,别让探针自己猜组合语义。
992
- const cleanVerdict = absent && !treeNodePending
993
- ? "已删干净(判据:bizmodels 记录 absent=true 且应用树无该 BizModel 节点)"
994
- : absent && treeNodePending
995
- ? "记录已删、树节点残留——级联仍在拆或残留需 model-purge;稍后复核 model.delete(幂等)"
996
- : "尚未删净:记录还在(级联进行中),稍后重跑 model.delete 复核";
1053
+ const cleanVerdict = taskFailed
1054
+ ? "未删除:平台删除任务失败(真因见 deleteTask.message;记录面 absent 只说明还没删,不代表成功)"
1055
+ : absent && !treeNodePending
1056
+ ? "已删干净(判据:bizmodels 记录 absent=true 且应用树无该 BizModel 节点)"
1057
+ : absent && treeNodePending
1058
+ ? "记录已删、树节点残留——级联仍在拆或残留需 model-purge;稍后复核 model.delete(幂等)"
1059
+ : deleteTask?.taskStatus === "RUN"
1060
+ ? `尚未删净:平台删除任务仍在运行(taskStatus=RUN,已等 ${Math.round(deleteTask.waitedMs / 1000)}s/预算 ${Math.round(deleteTask.budgetMs / 1000)}s,taskId=${deleteTask.taskId}),稍后重跑 model.delete 复核`
1061
+ : "尚未删净:记录还在(级联进行中),稍后重跑 model.delete 复核";
997
1062
  return {
998
1063
  performed: { errcode: performed.errcode, deletedId: targetId, applicationCode, ...(taskId !== undefined ? { taskId } : {}) },
999
1064
  readback: {
1000
1065
  absent,
1001
1066
  treeNodePending,
1002
1067
  cleanVerdict,
1068
+ ...(deleteTask !== undefined ? { deleteTask } : {}),
1003
1069
  ...(liveWorkflows.length > 0
1004
1070
  ? {
1005
1071
  workflowWarning: {
@@ -1012,14 +1078,23 @@ export function registerModelLane(tools) {
1012
1078
  },
1013
1079
  }
1014
1080
  : {}),
1015
- ...(absent
1016
- ? {}
1017
- : {
1018
- nextAction: "wait-and-recheck",
1019
- nextCommand: `omc call model.list --args '${JSON.stringify({ filter: args.schemaCode })}'`,
1020
- recheckCommand: `omc residue ${args.schemaCode}`,
1021
- note: "平台 physically_delete 是异步任务:建删除历史后立即返回,级联时长不定(8.6.26 实测可超过 4 分钟),absent:false 表示删除尚未完成,不是失败。平台无 taskId 查询端点,以记录面 absent=true 且应用树无该节点为准;用 nextCommand/recheckCommand 复核,稍后重跑 model.delete(幂等,already-absent 短路)。若刚删除引用方模型,其级联可能仍在拆除关联列,必须等它完成后再删本模型。",
1022
- }),
1081
+ ...(taskFailed
1082
+ ? {
1083
+ blocker: "model-delete-task-failed",
1084
+ nextAction: `平台删除任务失败,模型未删除。真因(平台原文):${deleteTask?.message ?? "平台未返回 message"}。按原文拆掉引用(field.delete → field.publish)或清理残留后重试 model.delete。`,
1085
+ nextCommand: `omc call model.delete --args '${JSON.stringify({ schemaCode: args.schemaCode })}'`,
1086
+ recheckCommand: `omc call model.delete --args '{"schemaCode":"${args.schemaCode}","dryRun":true}'`,
1087
+ }
1088
+ : absent
1089
+ ? {}
1090
+ : {
1091
+ nextAction: "wait-and-recheck",
1092
+ nextCommand: `omc call model.list --args '${JSON.stringify({ filter: args.schemaCode })}'`,
1093
+ recheckCommand: `omc residue ${args.schemaCode}`,
1094
+ note: deleteTask?.taskStatus === "RUN"
1095
+ ? `平台删除任务仍在运行(taskStatus=RUN,taskId=${deleteTask.taskId}),已等 ${Math.round(deleteTask.waitedMs / 1000)}s(预算 ${Math.round(deleteTask.budgetMs / 1000)}s)——不是失败,也不是已删除。用 GET ${ENDPOINTS.appPackageDeleteHistory}?taskId=${deleteTask.taskId} 复核任务结果,或稍后重跑 model.delete(幂等,already-absent 短路)。`
1096
+ : "平台 physically_delete 是异步任务:建删除历史后立即返回,级联时长不定(8.6.26 实测可超过 4 分钟),absent:false 表示删除尚未完成,不是失败。以记录面 absent=true 且应用树无该节点为准;用 nextCommand/recheckCommand 复核,稍后重跑 model.delete(幂等,already-absent 短路)。若刚删除引用方模型,其级联可能仍在拆除关联列,必须等它完成后再删本模型。",
1097
+ }),
1023
1098
  },
1024
1099
  };
1025
1100
  },
@@ -1073,44 +1148,33 @@ export function registerModelLane(tools) {
1073
1148
  });
1074
1149
  }
1075
1150
  const treeRowList = resolvedTrees;
1076
- // Per-target inbound-reference precheck (ticket 23 semantics, scanned
1077
- // once per sibling across all batch targets). Siblings INSIDE the batch
1078
- // are being deleted together and therefore do not block.
1151
+ // Per-target inbound-reference precheck (platform criterion, shared with
1152
+ // model.delete/dry-run). Siblings INSIDE the batch are being deleted
1153
+ // together and therefore do not block; a model's own child-table column
1154
+ // pointing at itself does (platform recursion → task never ends), so self
1155
+ // references are never ignored.
1079
1156
  const batchSet = new Set(targets);
1080
- const siblings = treeRowList
1081
- .filter((row) => row.type === "BizModel" && typeof row.code === "string" && !batchSet.has(String(row.code)))
1082
- .map((row) => ({ schemaCode: String(row.code), name: typeof row.name === "string" && row.name ? row.name : String(row.code) }));
1083
- const blockedTargets = [];
1084
- for (const sibling of siblings) {
1085
- const hitsByTarget = new Map();
1086
- for (const isPublish of ["false", "true"]) {
1087
- const listed = await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: sibling.schemaCode, isPublish } });
1088
- for (const row of wireRows(listed.data)) {
1089
- const target = relationTargetOf(row);
1090
- if (target === undefined || !batchSet.has(target))
1091
- continue;
1092
- const code = row.code ?? row.propertyCode;
1093
- if (typeof code !== "string")
1094
- continue;
1095
- const hits = hitsByTarget.get(target) ?? [];
1096
- if (!hits.some((field) => field.code === code))
1097
- hits.push({ code, type: row.type ?? row.propertyType });
1098
- hitsByTarget.set(target, hits);
1099
- }
1100
- }
1101
- for (const [target, fields] of hitsByTarget) {
1102
- const blocked = blockedTargets.find((entry) => entry.schemaCode === target) ?? { schemaCode: target, referencingModels: [] };
1103
- blocked.referencingModels.push({ schemaCode: sibling.schemaCode, name: sibling.name, fields });
1104
- if (!blockedTargets.includes(blocked))
1105
- blockedTargets.push(blocked);
1106
- }
1107
- }
1108
- if (blockedTargets.length > 0) {
1157
+ const references = await inboundModelReferences(session, targets, treeRowList, {
1158
+ ignoreReferencing: batchSet,
1159
+ skipReading: new Set(alreadyAbsent),
1160
+ });
1161
+ if (references.length > 0) {
1162
+ const blockedTargets = [...new Set(references.map((reference) => reference.referenced))].map((schemaCode) => {
1163
+ const refusal = inboundReferenceRefusal(schemaCode, references.filter((reference) => reference.referenced === schemaCode));
1164
+ return {
1165
+ schemaCode,
1166
+ referencingModels: refusal.referencingModels,
1167
+ inboundReferences: refusal.inboundReferences,
1168
+ deletionSteps: refusal.deletionSteps,
1169
+ nextCommand: refusal.nextCommand,
1170
+ };
1171
+ });
1109
1172
  throw new ToolRefusalError({
1110
1173
  status: "refused",
1111
1174
  blocker: "model-referenced-by",
1112
1175
  blockedTargets,
1113
- message: `批量删除被拒(零副作用):${blockedTargets.map((blocked) => `${blocked.schemaCode} 被模型 ${blocked.referencingModels.map((model) => model.schemaCode).join("、")} 的关联字段引用`).join(";")}。依赖倒序清理:把引用方模型一并纳入 schemaCodes(或先删其关联字段);引用方物理删除是平台异步任务、时长不定,完成后再删被引用模型。`,
1176
+ inboundReferences: references,
1177
+ message: `批量删除被拒(零副作用):${blockedTargets.map((blocked) => `${blocked.schemaCode} 被模型 ${blocked.referencingModels.map((model) => model.schemaCode).join("、")} 的关联字段引用(含子表列自引用,详见 blockedTargets[].inboundReferences)`).join(";")}。依赖倒序清理:把引用方模型一并纳入 schemaCodes(或先删其关联字段);引用方物理删除是平台异步任务、时长不定,完成后再删被引用模型。子表列指向自身体时平台删除线程会无限递归,必须先删该列再删模型。`,
1114
1178
  });
1115
1179
  }
1116
1180
  return { targets, alreadyAbsent, entries, treeRowList, appsToScan, applicationCode };
@@ -1146,20 +1210,23 @@ export function registerModelLane(tools) {
1146
1210
  // 把它留在回执里,判定仍以 perCode.absent 为准。
1147
1211
  const deleteHistory = (performed.data ?? {});
1148
1212
  const taskId = typeof deleteHistory.taskId === "string" && deleteHistory.taskId.length > 0 ? deleteHistory.taskId : undefined;
1149
- // Per-model absence polling on the authoritative record face. The async
1150
- // task duration is unbounded (do not promise a window); pending codes
1151
- // carry the same wait-and-recheck guidance as model.delete.
1213
+ // Per-model absence polling + the platform delete-history task (same
1214
+ // task id for the whole batch). Bounded: a FAIL surfaces the platform
1215
+ // message; a still-RUN task is reported as RUN after the budget.
1152
1216
  const absentSet = new Set();
1153
- for (let attempt = 0; attempt < 16 && absentSet.size < entries.length; attempt += 1) {
1154
- if (attempt > 0)
1155
- await new Promise((resolve) => setTimeout(resolve, Math.min(1000 * attempt, 4000)));
1156
- for (const entry of entries) {
1157
- if (absentSet.has(entry.code))
1158
- continue;
1159
- if ((await readRecord(entry.code)) === null)
1160
- absentSet.add(entry.code);
1161
- }
1162
- }
1217
+ const wait = await waitForModelDelete(session, {
1218
+ ...(taskId !== undefined ? { taskId } : {}),
1219
+ readAbsent: async () => {
1220
+ for (const entry of entries) {
1221
+ if (absentSet.has(entry.code))
1222
+ continue;
1223
+ if ((await readRecord(entry.code)) === null)
1224
+ absentSet.add(entry.code);
1225
+ }
1226
+ return absentSet.size >= entries.length;
1227
+ },
1228
+ });
1229
+ const deleteTask = wait.task;
1163
1230
  const afterTree = (await Promise.all([...appsToScan]
1164
1231
  .filter((appCode) => appCode)
1165
1232
  .map(async (appCode) => flattenTreeRows(wireRows((await wireCall(session, { path: ENDPOINTS.applicationTree, query: { appCode } })).data))))).flat();
@@ -1175,12 +1242,28 @@ export function registerModelLane(tools) {
1175
1242
  }
1176
1243
  const allAbsent = targets.every((code) => perCode[code]?.absent === true);
1177
1244
  const pendingCodes = targets.filter((code) => perCode[code]?.absent === false);
1245
+ const taskFailed = deleteTask?.taskStatus === "FAIL";
1178
1246
  return {
1179
1247
  performed: { errcode: performed.errcode, deletedIds: entries.map((entry) => entry.id), alreadyAbsent, requested: targets, applicationCode, ...(taskId !== undefined ? { taskId } : {}) },
1180
1248
  readback: {
1181
1249
  perCode,
1182
1250
  allAbsent,
1183
- ...(allAbsent ? {} : { nextAction: "wait-and-recheck", nextCommand: `omc residue ${pendingCodes[0] ?? targets[0]}`, note: "部分模型仍在异步级联中;按 perCode 逐项查看,稍后重跑(幂等)。" }),
1251
+ ...(deleteTask !== undefined ? { deleteTask } : {}),
1252
+ ...(taskFailed
1253
+ ? {
1254
+ blocker: "model-delete-task-failed",
1255
+ nextAction: `平台删除任务失败,本批未删除。真因(平台原文):${deleteTask?.message ?? "平台未返回 message"}。按原文拆掉引用(field.delete → field.publish)后重试 model.deleteMany。`,
1256
+ nextCommand: `omc call model.deleteMany --args '${JSON.stringify({ schemaCodes: pendingCodes.length > 0 ? pendingCodes : targets })}'`,
1257
+ }
1258
+ : allAbsent
1259
+ ? {}
1260
+ : {
1261
+ nextAction: "wait-and-recheck",
1262
+ nextCommand: `omc residue ${pendingCodes[0] ?? targets[0]}`,
1263
+ note: deleteTask?.taskStatus === "RUN"
1264
+ ? `平台删除任务仍在运行(taskStatus=RUN,taskId=${deleteTask.taskId}),已等 ${Math.round(deleteTask.waitedMs / 1000)}s(预算 ${Math.round(deleteTask.budgetMs / 1000)}s);用 GET ${ENDPOINTS.appPackageDeleteHistory}?taskId=${deleteTask.taskId} 复核,或稍后重跑(幂等)。`
1265
+ : "部分模型仍在异步级联中;按 perCode 逐项查看,稍后重跑(幂等)。",
1266
+ }),
1184
1267
  },
1185
1268
  };
1186
1269
  },
@@ -5,7 +5,7 @@ export { RUNTIME_DATA_WIRE, RUNTIME_QUERY_OPERATORS, ENGINE_OWNED_KEYS, SUBMIT_S
5
5
  import { RUNTIME_DATA_WIRE } from "omc-core/wire-facts";
6
6
  export function dataListDescription() {
7
7
  const wire = RUNTIME_DATA_WIRE;
8
- return `按简化过滤 DSL 查询业务对象(runtime/query/list);DSL 在 CLI 内翻译为平台 queryCondition(${wire.dslShape}),并按发布字段元数据为每个条件注入 propertyType(未知过滤字段将被拒绝,可用 rawCondition 逃生);响应行在 items[],业务字段在 items[].fields.<code>(不是 rows[],也不是 item 顶层——--jq 常用 items[].fields.sku);空模型返回空列表;未配列的自定义字段投影为 null——这是显示面缺列配置、不是数据缺失(data.load 有值),显式选列在结果中全为 null 而发布字段元数据显示其存在时,readback 追加 projectionHint(先用 listview.configure 配置该模型的默认视图列,或用 data.load 读单条权威值)。键缺席=字段不存在;键在值 null=未投影或真空值(见 projectionHint.unprojected)。`;
8
+ return `按简化过滤 DSL 查询业务对象(runtime/query/list);DSL 在 CLI 内翻译为平台 queryCondition(${wire.dslShape}),并按发布字段元数据为每个条件注入 propertyType(未知过滤字段将被拒绝,可用 rawCondition 逃生);响应行在 items[],业务字段在 items[].fields.<code>(不是 rows[],也不是 item 顶层——--jq 常用 items[].fields.sku);空模型返回空列表;未配列的自定义字段投影为 null——这是显示面缺列配置、不是数据缺失(data.load 有值),显式选列在结果中全为 null 而发布字段元数据显示其存在时,readback 追加 projectionHint(先用 listview.configure 配置该模型的默认视图列,或用 data.load 读单条权威值)。键缺席=字段不存在;键在值 null=未投影或真空值(见 projectionHint.unprojected);逐行未投影看 items[].unprojected(nullSemantics 说明两者都不是「字段不存在」)。`;
9
9
  }
10
10
  export function dataAggregateDescription() {
11
11
  return `临时计数与数值聚合(纯读)。count:runtime/query/list size:1 读 totalElements(服务端精确、不受 cap 影响;带 filter +1 field.list)。sum/avg/min/max:field 必填且已发布 propertyType=2(NUMERICAL);无 GET_LIST 改源时优先 /sum ALL_DATA(coverage.mode=server-aggregate,全量精确),否则/失败/键不符回退本地折叠(strategyFallback;size:200 翻页至 cap 1000,null 不进聚合、avg=sum/非 null 行数,nonNullCount=0→value:null)。complete 看 rowsScanned>=total,否则 missingCount+capNotice,绝不外推。groupBy 单列:count 值域可枚举(options/字典)→值域×count(V+3 wire),分桶并发窗口 4(限流退化 2,见 wire.concurrency),桶序稳定;按 count 降序取 topN(默认 10/上限 20),截断给 truncatedBuckets/bucketsTruncatedCount,null 单列 nullBucket;不可枚举或数值指标→本地扫描(coverage.mode=paged-local-scan/local-scan),数值桶 {key,count,nonNullCount,value} 按 value 降序、并列按 key,null 行进 nullBucket。filter.draftPolicy:count+groupBy 默认 includeDrafts:false 注入 sequenceStatus≠DRAFT;数值指标不默认排除;count 省略=平台默认(无条件含草稿、带条件排草稿);显式 false 强制排除。边界:临时问句用本工具;持久图表/看板用 report.chartdata,视图汇总列用 sumType,写时计算用 datarule type2。子表计数/求和用 child(主表 schemaCode + childSchemaCode/bizObjectId)。`;
@@ -154,7 +154,7 @@ function desc(lead) {
154
154
  }
155
155
  export function assertRuntimeDataContract() {
156
156
  assertLaneContract(RUNTIME_DATA_LANE_CONTRACT);
157
- assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.list", ["queryCondition", "propertyType", "rawCondition", "projectionHint", "listview.configure", "data.load", "items[].fields", "键缺席", "未投影或真空值"]);
157
+ assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.list", ["queryCondition", "propertyType", "rawCondition", "projectionHint", "listview.configure", "data.load", "items[].fields", "items[].unprojected", "nullSemantics", "键缺席", "未投影或真空值"]);
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"]);
@@ -397,6 +397,44 @@ export function projectionHintFace(items, evidence) {
397
397
  ...(unprojected.length > 0 ? { unprojected } : {}),
398
398
  };
399
399
  }
400
+ /**
401
+ * F8(w44,2026-11-26 真机):`data.list` 的行内 `fields` 对**未投影**列也回
402
+ * `null`(与真空值同形),顶层 `projectionHint.unprojected` 只在整列全 null 时
403
+ * 出现,脚本按行对账仍会把 null 当数据丢失。行级 `unprojected` 用**同一份**
404
+ * 视图列证据(queryColumns)逐行标注:值 null 且不在视图列 → 本行未投影。
405
+ * `*_key` 孪生列与系统列不算(投影证据只覆盖业务列);拿不到视图清单时只用
406
+ * `projectionMiss`(请求列在 wire 行里整列缺席)判定,绝不拿 null 猜。
407
+ */
408
+ const isNonBusinessProjectionKey = (key) => RUNTIME_SYSTEM_FIELD_CODES.has(key) || key.endsWith("_") || key.endsWith("_key");
409
+ export function itemUnprojectedFields(fields, projectionMiss, viewColumnCodes) {
410
+ const missed = projectionMiss.length > 0 ? new Set(projectionMiss) : undefined;
411
+ if (viewColumnCodes === undefined && missed === undefined)
412
+ return [];
413
+ const inView = viewColumnCodes === undefined ? undefined : new Set(viewColumnCodes);
414
+ return Object.entries(fields)
415
+ .filter(([code, value]) => {
416
+ if (isNonBusinessProjectionKey(code))
417
+ return false;
418
+ if (value !== null && value !== undefined)
419
+ return false;
420
+ if (inView !== undefined)
421
+ return !inView.has(code);
422
+ return missed.has(code);
423
+ })
424
+ .map(([code]) => code);
425
+ }
426
+ /** 行级 `unprojected` 是加法:既有 `fields` 的键与 null 值逐字保留。 */
427
+ export function attachItemUnprojected(items, projectionMiss, viewColumnCodes) {
428
+ // 键只在**该行真的**有已判定未投影列时出现:无标注的行不加 `unprojected: []`
429
+ // ——每行多 ~20B 会把 25 行的小结果顶过 compact 外置阈值(0.8.7 全量实测
430
+ // composers `data.list --all` 因 `items` 被外置而失败),且空数组没有信息量。
431
+ return items.map((item) => {
432
+ const unprojected = itemUnprojectedFields(item.fields, projectionMiss, viewColumnCodes);
433
+ return unprojected.length > 0 ? { ...item, unprojected } : { ...item };
434
+ });
435
+ }
436
+ /** 人类/脚本读 null 的唯一权威口径;与行级 `unprojected` 同时出现才完整。 */
437
+ export const DATA_LIST_NULL_SEMANTICS = "items[].fields.<code> 键在且值为 null 可能是未投影进视图列(也可能本就是空值),不是「字段不存在」;items[].unprojected 只在该行有已判定的未投影列时出现(列出的 code 值必为 null),键缺席表示本行没有已判定的未投影列;判真值用 data.load。";
400
438
  /**
401
439
  * B2(issue 2026-11-25,真机 `milestone_ledger`):`data.list` 对关联字段静默回
402
440
  * null,而同一条记录 `data.load` 有真实值(`{id, displayCode, <显示字段>}`)。
@@ -1937,6 +1975,8 @@ export function registerRuntimeDataLane(tools) {
1937
1975
  const viewEvidence = nullProjection ? await listViewProjectionEvidence(session, args.schemaCode, args.queryCode ?? args.schemaCode) : undefined;
1938
1976
  const projectionHintAll = projectionHintWithMiss(projectionHintFace(items, viewEvidence), projectionMissAll);
1939
1977
  const columnsNotProjected = await relationNotProjectedOf(items, projectionMissAll, viewEvidence?.viewColumnCodes);
1978
+ const itemsWithProjection = attachItemUnprojected(items, projectionMissAll, viewEvidence?.viewColumnCodes);
1979
+ const anyNullField = items.some((item) => Object.values(item.fields).some((value) => value === null));
1940
1980
  return {
1941
1981
  schemaCode: args.schemaCode,
1942
1982
  ...application,
@@ -1984,9 +2024,10 @@ export function registerRuntimeDataLane(tools) {
1984
2024
  }
1985
2025
  : {}),
1986
2026
  ...(projectionHintAll !== undefined ? { projectionHint: projectionHintAll } : {}),
2027
+ ...(anyNullField ? { nullSemantics: DATA_LIST_NULL_SEMANTICS } : {}),
1987
2028
  ...(projectionMissAll.length > 0 ? { projectionMiss: projectionMissAll } : {}),
1988
2029
  ...(columnsNotProjected.length > 0 ? { columnsNotProjected } : {}),
1989
- items,
2030
+ items: itemsWithProjection,
1990
2031
  };
1991
2032
  }
1992
2033
  let result;
@@ -2126,6 +2167,8 @@ export function registerRuntimeDataLane(tools) {
2126
2167
  const viewEvidence = hasNullValue ? await listViewProjectionEvidence(session, args.schemaCode, args.queryCode ?? args.schemaCode) : undefined;
2127
2168
  const projectionHintPaged = projectionHintWithMiss(projectionHintFace(items, viewEvidence), projectionMissPaged);
2128
2169
  const columnsNotProjected = await relationNotProjectedOf(items, projectionMissPaged, viewEvidence?.viewColumnCodes);
2170
+ const itemsWithProjection = attachItemUnprojected(items, projectionMissPaged, viewEvidence?.viewColumnCodes);
2171
+ const anyNullField = items.some((item) => Object.values(item.fields).some((value) => value === null));
2129
2172
  // F6 工单 05b:只有本页行真的内联了子表数组才给一句(否则零字节);
2130
2173
  // 取第一条命中行,命令里的 schemaCode/childSchemaCode/bizObjectId 都是真值。
2131
2174
  const inlineChild = items
@@ -2165,6 +2208,7 @@ export function registerRuntimeDataLane(tools) {
2165
2208
  })(),
2166
2209
  ...(choiceFilterFields.length > 0 && Number(total ?? 0) === 0 ? { filterValueHint: choiceFilterValueHint(choiceFilterFields) } : {}),
2167
2210
  ...(projectionHintPaged !== undefined ? { projectionHint: projectionHintPaged } : {}),
2211
+ ...(anyNullField ? { nullSemantics: DATA_LIST_NULL_SEMANTICS } : {}),
2168
2212
  ...(projectionMissPaged.length > 0 ? { projectionMiss: projectionMissPaged } : {}),
2169
2213
  ...(columnsNotProjected.length > 0 ? { columnsNotProjected } : {}),
2170
2214
  totalPages,
@@ -2176,7 +2220,7 @@ export function registerRuntimeDataLane(tools) {
2176
2220
  size: page.size ?? args.size ?? 20,
2177
2221
  ...(pageOutOfRange ? { pageOutOfRange: true, emptyPage: true, hint: `page 从 0 开始,当前传了 ${requestedPage};合法范围 0..${Math.max(0, totalPages - 1)}。` } : {}),
2178
2222
  // r29b F8 的 ids/itemsPreview 由 compact(外置时)现算,见 dataListCompactProjection。
2179
- items,
2223
+ items: itemsWithProjection,
2180
2224
  };
2181
2225
  // r29b F8: ids/itemsPreview 已在同信封;artifact 提示由 compact 外置后的
2182
2226
  // fetch/detailArtifactId 承担。这里不改既有 projectionHint 主句(契约测试
@@ -3338,8 +3338,21 @@ export function registerWorkflowLane(tools) {
3338
3338
  // 1 次 get(本模型通常 1-3 个视图)。
3339
3339
  const addBindings = await listviewAddBindings(session, args.schemaCode, args.code);
3340
3340
  const firstPublish = Number(data.workflowVersion) === 1;
3341
+ const firstBoundView = addBindings.bound[0];
3342
+ // Same query/get response as the binding scan — no extra wire round-trip.
3343
+ // The unbind recipe mirrors workflow.delete's 303024 recovery (live-proven:
3344
+ // empty actions + replaceActions:true).
3345
+ const unbindCommand = firstBoundView === undefined
3346
+ ? undefined
3347
+ : `omc call listview.configure --env <env> --args '${JSON.stringify({
3348
+ schemaCode: args.schemaCode,
3349
+ code: firstBoundView.code,
3350
+ fieldCodes: firstBoundView.fieldCodes.length > 0 ? firstBoundView.fieldCodes : ["createdTime", "creater", "name", "sequenceNo"],
3351
+ actions: [],
3352
+ replaceActions: true,
3353
+ })}'`;
3341
3354
  const listviewBinding = {
3342
- bound: addBindings.bound,
3355
+ bound: addBindings.bound.map(({ code, actionCode }) => ({ code, actionCode })),
3343
3356
  ...(firstPublish ? {} : { firstPublish: false }),
3344
3357
  note: addBindings.bound.length > 0
3345
3358
  ? firstPublish
@@ -3348,6 +3361,12 @@ export function registerWorkflowLane(tools) {
3348
3361
  : addBindings.readable
3349
3362
  ? "无隐式绑定"
3350
3363
  : "列表视图读取失败,未能确认 add 绑定;删流程前先 listview.get 复核",
3364
+ ...(addBindings.bound.length > 0
3365
+ ? {
3366
+ beforeWorkflowDelete: "删流程前先解绑:用 listview.configure 清掉该视图 add 动作(actions:[] + replaceActions:true),否则 workflow.delete 会撞 workflow-bound-to-listview(303024,列表还绑着流程);多个视图绑定时逐视图处理。",
3367
+ ...(unbindCommand !== undefined ? { unbindCommand } : {}),
3368
+ }
3369
+ : {}),
3351
3370
  };
3352
3371
  return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, published: isPublished, workflowVersion: data.workflowVersion ?? null, listviewBinding, ...(strippedEmptyConditionGroups > 0 ? { strippedEmptyConditionGroups, strippedEmptyConditionGroupsNote: "调用方连线里有 N 条带平台存量写法 ruleConditionGroup:[](=无条件);工具写前已剥离该键,未上送" } : {}), ...(warnings.length ? { warnings } : {}), ...(participantWarnings.length ? { participantWarnings } : {}), ...(rejectWarnings.length || originatorWarnings.length ? { workflowWarnings: [...rejectWarnings, ...originatorWarnings] } : {}), workflowRenderCompat: workflowRenderCompat(data) } };
3353
3372
  },
@@ -4291,8 +4310,14 @@ export function registerWorkflowLane(tools) {
4291
4310
  String(association ?? "").toUpperCase() === "WORKFLOW";
4292
4311
  return isWorkflow && (associationCode === workflowCode || associationCode === "");
4293
4312
  });
4294
- if (hit)
4295
- bound.push({ code, actionCode: "add" });
4313
+ if (hit) {
4314
+ // Reuse the SAME query/get response for the unbind command's
4315
+ // fieldCodes — no extra wire round-trip at publish time.
4316
+ const fieldCodes = (model !== null && Array.isArray(model.queryColumns) ? model.queryColumns : [])
4317
+ .map((column) => String(column.propertyCode ?? ""))
4318
+ .filter((column) => column.length > 0);
4319
+ bound.push({ code, actionCode: "add", fieldCodes });
4320
+ }
4296
4321
  }
4297
4322
  catch {
4298
4323
  readable = false;