@stalfh233/omc-cli 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/coverage/m1-coverage-manifest-v1.json +1 -0
  2. package/dist/approval-flow.js +49 -4
  3. package/dist/batch-call.js +21 -4
  4. package/dist/cli-stdout.js +1 -0
  5. package/dist/cli.js +84 -3
  6. package/dist/code-rules.js +35 -11
  7. package/dist/config-store.js +15 -1
  8. package/dist/endpoints.js +10 -0
  9. package/dist/form-layout.js +79 -0
  10. package/dist/form-support.js +111 -7
  11. package/dist/graph.js +38 -3
  12. package/dist/human-summary.js +19 -1
  13. package/dist/lanes/field-contract.js +5 -1
  14. package/dist/lanes/field-coverage.js +1 -0
  15. package/dist/lanes/field.js +20 -2
  16. package/dist/lanes/form-contract.js +1 -1
  17. package/dist/lanes/form.js +24 -2
  18. package/dist/lanes/list-view.js +104 -2
  19. package/dist/lanes/model-references.js +172 -0
  20. package/dist/lanes/model.js +206 -123
  21. package/dist/lanes/runtime-data-contract.js +4 -4
  22. package/dist/lanes/runtime-data.js +170 -7
  23. package/dist/lanes/workflow.js +213 -45
  24. package/dist/model-purge.js +106 -21
  25. package/dist/model-scaffold.js +52 -10
  26. package/dist/recipes/field.js +44 -1
  27. package/dist/recipes/form.js +33 -6
  28. package/dist/recipes/list-view.js +1 -1
  29. package/dist/reserved.js +28 -0
  30. package/dist/search-index.js +2 -0
  31. package/dist/tool-types.js +1 -0
  32. package/dist/write.js +12 -0
  33. package/package.json +3 -3
  34. package/skills/omc-business-configuration.md +6 -0
  35. package/skills/omc-capabilities.md +1 -1
  36. package/skills/omc-playbook.md +5 -0
  37. package/skills/omc-requirement-vocabulary.md +13 -0
  38. package/skills/omc-start-here.md +1 -1
  39. package/skills/omc-tool-selection.md +2 -0
  40. package/skills/omc-write-hazards.md +3 -0
@@ -0,0 +1,172 @@
1
+ import { ENDPOINTS } from "../endpoints.js";
2
+ import { relationTargetOf } from "../field-families.js";
3
+ import { wireCall, wireRows } from "../wire.js";
4
+ const WORK_SHEET = 9;
5
+ const CHILD_TABLE = 8;
6
+ function propertyTypeOf(row) {
7
+ return Number(row.type ?? row.propertyType);
8
+ }
9
+ function fieldCodeOf(row) {
10
+ const code = row.code ?? row.propertyCode;
11
+ return typeof code === "string" && code.length > 0 ? code : undefined;
12
+ }
13
+ function fieldNameOf(row) {
14
+ return typeof row.name === "string" && row.name.length > 0 ? row.name : String(fieldCodeOf(row) ?? "");
15
+ }
16
+ export async function inboundModelReferences(session, targets, treeRows, options = {}) {
17
+ const targetSet = new Set(targets);
18
+ if (targetSet.size === 0)
19
+ return [];
20
+ const models = new Map();
21
+ for (const row of treeRows) {
22
+ if (row.type !== "BizModel" || typeof row.code !== "string" || row.code.length === 0)
23
+ continue;
24
+ models.set(row.code, { code: row.code, name: typeof row.name === "string" && row.name.length > 0 ? row.name : row.code });
25
+ }
26
+ const skip = options.skipReading ?? new Set();
27
+ const scannable = [...models.values()].filter((model) => !skip.has(model.code));
28
+ const fieldCache = new Map();
29
+ const fieldsOf = async (schemaCode) => {
30
+ const cached = fieldCache.get(schemaCode);
31
+ if (cached !== undefined)
32
+ return cached;
33
+ const rows = [];
34
+ for (const isPublish of ["false", "true"]) {
35
+ const listed = await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish } });
36
+ rows.push(...wireRows(listed.data));
37
+ }
38
+ fieldCache.set(schemaCode, rows);
39
+ return rows;
40
+ };
41
+ // one read pass: every tree model's fields, plus the CHILD_TABLE fields that
42
+ // give us child schema → parent model (isSubSchema()->parentCode on the wire).
43
+ const modelFields = new Map();
44
+ const childOwners = new Map();
45
+ for (const model of scannable) {
46
+ const rows = await fieldsOf(model.code);
47
+ modelFields.set(model.code, rows);
48
+ for (const row of rows) {
49
+ if (propertyTypeOf(row) !== CHILD_TABLE)
50
+ continue;
51
+ const code = fieldCodeOf(row);
52
+ if (code === undefined || childOwners.has(code))
53
+ continue;
54
+ childOwners.set(code, { model, childField: { code, name: fieldNameOf(row) } });
55
+ }
56
+ }
57
+ const ignore = options.ignoreReferencing ?? new Set();
58
+ const found = new Map();
59
+ const add = (referenced, owner, via, field, childTable) => {
60
+ const selfReference = owner.code === referenced;
61
+ // Intra-batch references are allowed by the platform; self references are not.
62
+ if (!selfReference && ignore.has(owner.code))
63
+ return;
64
+ const key = `${referenced}::${owner.code}::${via}::${childTable?.code ?? ""}`;
65
+ const entry = found.get(key) ?? {
66
+ referenced,
67
+ schemaCode: owner.code,
68
+ name: owner.name,
69
+ via,
70
+ fields: [],
71
+ ...(childTable !== undefined ? { childTable } : {}),
72
+ selfReference,
73
+ };
74
+ if (!entry.fields.some((existing) => existing.code === field.code))
75
+ entry.fields.push(field);
76
+ found.set(key, entry);
77
+ };
78
+ for (const model of scannable) {
79
+ for (const row of modelFields.get(model.code)) {
80
+ if (propertyTypeOf(row) !== WORK_SHEET)
81
+ continue;
82
+ const target = relationTargetOf(row);
83
+ if (target === undefined || !targetSet.has(target))
84
+ continue;
85
+ // platform filter step 2: the property is defined ON the target itself.
86
+ if (model.code === target)
87
+ continue;
88
+ const code = fieldCodeOf(row);
89
+ if (code === undefined)
90
+ continue;
91
+ add(target, model, "model-field", { code, name: fieldNameOf(row), type: row.type ?? row.propertyType });
92
+ }
93
+ }
94
+ for (const [childCode, owner] of childOwners) {
95
+ const rows = await fieldsOf(childCode);
96
+ for (const row of rows) {
97
+ if (propertyTypeOf(row) !== WORK_SHEET)
98
+ continue;
99
+ const target = relationTargetOf(row);
100
+ if (target === undefined || !targetSet.has(target))
101
+ continue;
102
+ // platform filter step 2 uses the PROPERTY's schemaCode (the child schema).
103
+ if (childCode === target)
104
+ continue;
105
+ const code = fieldCodeOf(row);
106
+ if (code === undefined)
107
+ continue;
108
+ add(target, owner.model, "child-table", { code, name: fieldNameOf(row), type: row.type ?? row.propertyType }, owner.childField);
109
+ }
110
+ }
111
+ return [...found.values()].sort((left, right) => left.referenced.localeCompare(right.referenced) ||
112
+ left.schemaCode.localeCompare(right.schemaCode) ||
113
+ left.via.localeCompare(right.via) ||
114
+ (left.childTable?.code ?? "").localeCompare(right.childTable?.code ?? ""));
115
+ }
116
+ /**
117
+ * Build the refusal payload shared by the three delete entry points
118
+ * (model.delete dry-run, model.delete, model.deleteMany). The message names the
119
+ * real platform cause and the exact commands that remove the reference.
120
+ */
121
+ export function inboundReferenceRefusal(target, references) {
122
+ const referencingModels = [];
123
+ for (const reference of references) {
124
+ const existing = referencingModels.find((model) => model.schemaCode === reference.schemaCode);
125
+ const fields = reference.fields.map((field) => ({ code: field.code, type: field.type }));
126
+ if (existing)
127
+ existing.fields.push(...fields.filter((field) => !existing.fields.some((known) => known.code === field.code)));
128
+ else
129
+ referencingModels.push({ schemaCode: reference.schemaCode, name: reference.name, fields });
130
+ }
131
+ const steps = [];
132
+ const publishOwners = new Set();
133
+ const step = (tool, args) => {
134
+ steps.push({ tool, args, command: `omc call ${tool} --args '${JSON.stringify(args)}'` });
135
+ };
136
+ for (const reference of references) {
137
+ for (const field of reference.fields) {
138
+ const schemaCode = reference.via === "child-table" ? reference.childTable.code : reference.schemaCode;
139
+ step("field.delete", { schemaCode, code: field.code });
140
+ }
141
+ publishOwners.add(reference.schemaCode);
142
+ }
143
+ for (const owner of publishOwners)
144
+ step("field.publish", { schemaCode: owner });
145
+ step("model.delete", { schemaCode: target });
146
+ const selfReferences = references.filter((reference) => reference.selfReference);
147
+ const externalReferences = references.filter((reference) => !reference.selfReference);
148
+ const selfText = selfReferences.map((reference) => `${reference.childTable.code}.${reference.fields.map((field) => field.code).join("/")}`);
149
+ const externalText = [...new Set(externalReferences.map((reference) => reference.schemaCode))];
150
+ const parts = [];
151
+ if (selfText.length > 0) {
152
+ parts.push(`本模型的子表关联列 ${selfText.join("、")} 指向自身:子表属性的 schemaCode 经 isSubSchema()->parentCode 解析回 ${target},平台删除线程(appendRelatedFunction)会对自身无限递归,physically_delete 先回 taskId 后任务永远停在 RUN——删除**永不完成**,真因只写在平台日志,CLI 只会看到「级联中」。`);
153
+ }
154
+ if (externalText.length > 0) {
155
+ parts.push(`${target} 被模型 ${externalText.join("、")} 的关联字段引用:平台异步任务会以 BIZ_SCHEMA_RELEATIVE_SCHEMA_NOT_EMPTY 失败("${target}被模型 ${externalText[0]} 引用,不能删除")。`);
156
+ }
157
+ return {
158
+ blocker: "model-referenced-by",
159
+ referencingModels,
160
+ inboundReferences: [...references],
161
+ deletionOrder: [...new Set([...references.map((reference) => reference.schemaCode), target])],
162
+ deletionSteps: steps,
163
+ nextCommand: steps[0]?.command ?? `omc call model.delete --args '${JSON.stringify({ schemaCode: target })}'`,
164
+ nextAction: selfText.length > 0
165
+ ? "按 deletionSteps 依赖倒序逐条执行:先 field.delete 删掉指向自身的子表关联列(及其它引用列),再 field.publish 发布所属模型,最后 model.delete(本工具已零写入拒绝,不会启动平台删除任务)"
166
+ : "按 deletionSteps 依赖倒序执行:先删引用方模型的关联字段(或整体删掉引用方模型),再删本模型",
167
+ message: `${target} 不能删除(零写入拒绝,未调用 physically_delete)。${parts.join(" ")}` +
168
+ `依赖倒序(逐条可执行命令见 deletionSteps / nextCommand):先删关联列 → 发布所属模型 → 再删本模型。` +
169
+ `不要在未拆引用时重试 model.delete——平台只会再次回 taskId 并把真因留在删除历史里(模型引用失败时 taskStatus=FAIL,子表自引用时任务永远 RUN)。`,
170
+ };
171
+ }
172
+ //# sourceMappingURL=model-references.js.map
@@ -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
  },