@stalfh233/omc-cli 0.8.7 → 0.8.9

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.
@@ -3843,8 +3843,114 @@ export function registerWorkflowLane(tools) {
3843
3843
  lane: WORKFLOW_LANE,
3844
3844
  scope: WORKFLOW_TOOLS["workflow.delete"].scope,
3845
3845
  description: WORKFLOW_TOOLS["workflow.delete"].description,
3846
- inputSchema: { schemaCode: z.string().min(1), code: z.string().min(1).describe("流程编码——本参数名是 code") },
3846
+ inputSchema: {
3847
+ schemaCode: z.string().min(1),
3848
+ code: z.string().min(1).describe("流程编码——本参数名是 code"),
3849
+ unbindListviews: z
3850
+ .boolean()
3851
+ .optional()
3852
+ .describe("先解绑列表视图再删流程:true 时对本模型每个绑定了本流程的列表视图执行 listview.configure(actions:[] + replaceActions:true,保留原列 fieldCodes),成功后才删流程;任一步解绑失败即停、不删流程。**会改动视图配置(移除该视图 add 动作的平台关联),必须显式确认才做。** 默认 false 只删流程,遇 303024 仍拒绝并给 nextCommand"),
3853
+ },
3854
+ // F7(0.8.8):dry-run 与真写共用同一份只读扫描——预览列出会被解绑的视图,
3855
+ // 真写在任何写 wire 之前也先跑这里。两者都不写。
3856
+ writeLint: async (session, args) => {
3857
+ if (args.unbindListviews !== true) {
3858
+ return {
3859
+ wouldChange: true,
3860
+ summary: `即将删除流程 ${args.code}(未请求解绑列表视图)`,
3861
+ listviewUnbind: {
3862
+ requested: false,
3863
+ note: "未传 unbindListviews;不改任何视图配置。若平台回 303024,重发时带 unbindListviews:true 让本工具先解绑。",
3864
+ },
3865
+ };
3866
+ }
3867
+ const scan = await scanListviewsBoundToWorkflow(session, args.schemaCode, args.code);
3868
+ return {
3869
+ wouldChange: true,
3870
+ summary: scan.bound.length > 0
3871
+ ? `先解绑 ${scan.bound.length} 个列表视图,再删除流程 ${args.code}`
3872
+ : `未发现绑定本流程的列表视图;将直接删除流程 ${args.code}`,
3873
+ listviewUnbind: {
3874
+ requested: true,
3875
+ readable: scan.readable,
3876
+ ...(scan.bound.length > 0
3877
+ ? {
3878
+ views: scan.bound.map(({ code, name, fieldCodes }) => ({
3879
+ code,
3880
+ name,
3881
+ ...(fieldCodes.length > 0 ? { fieldCodes } : {}),
3882
+ action: "listview.configure actions:[] + replaceActions:true",
3883
+ })),
3884
+ }
3885
+ : {}),
3886
+ ...(scan.unreadableViews.length > 0 ? { unreadableViews: scan.unreadableViews } : {}),
3887
+ then: "workflow.delete",
3888
+ ...(scan.readable
3889
+ ? {}
3890
+ : { note: "视图清单读取失败:真写仍会先读;读不到绑定时只删流程,平台 303024 会挡住,不误放行。" }),
3891
+ },
3892
+ };
3893
+ },
3847
3894
  execute: async (session, args) => {
3895
+ const steps = [];
3896
+ // Opt-in unbind (F7): the workflow.publish side effect binds every list
3897
+ // view's `add` action to this workflow, and workflow.delete then answers
3898
+ // 303024 until those associations are gone. Unbind FIRST, and stop
3899
+ // before the delete if any view cannot be cleared (never half-delete).
3900
+ if (args.unbindListviews === true) {
3901
+ const scan = await scanListviewsBoundToWorkflow(session, args.schemaCode, args.code);
3902
+ const configure = siblings.find((tool) => tool.name === "listview.configure");
3903
+ if (scan.bound.length > 0 && configure?.writeExecute === undefined)
3904
+ throw new ToolRefusalError({
3905
+ status: "refused",
3906
+ blocker: "workflow-unbind-step-unavailable",
3907
+ workflowCode: args.code,
3908
+ message: "workflow.delete 需要 listview.configure 来解绑视图,但它未注册写执行;零写入停止",
3909
+ });
3910
+ for (const view of scan.bound) {
3911
+ const fieldCodes = view.fieldCodes.length > 0 ? view.fieldCodes : ["createdTime", "creater", "name", "sequenceNo"];
3912
+ try {
3913
+ const outcome = await configure.writeExecute(session, {
3914
+ schemaCode: args.schemaCode,
3915
+ code: view.code,
3916
+ fieldCodes,
3917
+ actions: [],
3918
+ replaceActions: true,
3919
+ });
3920
+ if ("status" in outcome)
3921
+ throw new ToolRefusalError({
3922
+ status: "refused",
3923
+ blocker: "workflow-unbind-step-stopped",
3924
+ workflowCode: args.code,
3925
+ viewCode: view.code,
3926
+ message: `解绑视图 ${view.code} 中途停止(${String(outcome.envelope?.message ?? outcome.status)})`,
3927
+ });
3928
+ steps.push({
3929
+ step: "listview.configure",
3930
+ status: "ok",
3931
+ viewCode: view.code,
3932
+ viewName: view.name,
3933
+ actions: "cleared",
3934
+ replaceActions: true,
3935
+ readback: outcome.readback,
3936
+ });
3937
+ }
3938
+ catch (error) {
3939
+ const cause = error instanceof Error ? error.message : String(error);
3940
+ throw new ToolRefusalError({
3941
+ status: "refused",
3942
+ blocker: "workflow-unbind-failed",
3943
+ workflowCode: args.code,
3944
+ schemaCode: args.schemaCode,
3945
+ viewCode: view.code,
3946
+ steps,
3947
+ nextCommand: `omc call listview.configure --env <env> --args '${JSON.stringify({ schemaCode: args.schemaCode, code: view.code, fieldCodes, actions: [], replaceActions: true })}'`,
3948
+ message: `解绑列表视图 ${view.code} 失败,已停止:**流程 ${args.code} 未删除**(不半删)。原因:${cause}。` +
3949
+ `按 nextCommand 修好该视图后重发 workflow.delete(仍带 unbindListviews:true);已成功解绑的视图在 steps 里。`,
3950
+ });
3951
+ }
3952
+ }
3953
+ }
3848
3954
  let performed;
3849
3955
  try {
3850
3956
  performed = await wireCall(session, { path: ENDPOINTS.workflowDelete, method: "POST", query: { workflowCode: args.code } });
@@ -3909,13 +4015,35 @@ export function registerWorkflowLane(tools) {
3909
4015
  ? `绑在:${bound.map((view) => `${view.code}(${view.name})action=${view.actionCode ?? "?"}`).join("、")}。`
3910
4016
  : `默认视图多半是 ${args.schemaCode}(workflow.create 会自动绑)。`) +
3911
4017
  `先解绑再删:粘贴 nextCommand(listview.configure:actions:[] + replaceActions:true + 现有 fieldCodes),再重试 workflow.delete。` +
4018
+ (args.unbindListviews === true
4019
+ ? `本次已带 unbindListviews:true,但仍有绑定未被清掉(见 boundListviews / unreadableViews);按 nextCommand 处理后重试。`
4020
+ : `也可以重发 workflow.delete 并带 unbindListviews:true,让本工具先逐个视图解绑再删。`) +
3912
4021
  `整体清理也可用 omc model-purge --code ${args.schemaCode}(级联带走流程模板与视图)。`,
3913
4022
  });
3914
4023
  }
3915
4024
  throw error;
3916
4025
  }
3917
4026
  const header = await wireCall(session, { path: ENDPOINTS.workflowGetHeader, query: { workflowCode: args.code } }).catch(() => ({ data: null }));
3918
- return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, absent: header.data === null || header.data === undefined } };
4027
+ const absent = header.data === null || header.data === undefined;
4028
+ if (args.unbindListviews === true) {
4029
+ steps.push({ step: "workflow.delete", status: "ok", workflowCode: args.code, errcode: performed.errcode, absent });
4030
+ }
4031
+ return {
4032
+ performed: { errcode: performed.errcode },
4033
+ readback: {
4034
+ workflowCode: args.code,
4035
+ absent,
4036
+ ...(args.unbindListviews === true
4037
+ ? {
4038
+ listviewUnbind: {
4039
+ requested: true,
4040
+ unboundViews: steps.filter((step) => step.step === "listview.configure").map((step) => step.viewCode),
4041
+ },
4042
+ }
4043
+ : {}),
4044
+ },
4045
+ ...(steps.length > 0 ? { steps } : {}),
4046
+ };
3919
4047
  },
3920
4048
  rollback: workflowRollbackSpec("workflow.delete"),
3921
4049
  });
@@ -4329,53 +4457,68 @@ export function registerWorkflowLane(tools) {
4329
4457
  }
4330
4458
  return { bound, readable };
4331
4459
  }
4332
- /** Best-effort: which list views still bind this workflow (303024 recovery). */
4333
- async function findListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4460
+ /**
4461
+ * Which list views bind this workflow, plus whether the READ succeeded.
4462
+ * `readable:false` means "could not list views" (NOT "none bound") — callers
4463
+ * must fail open to the platform's 303024 rather than deleting blind
4464
+ * (F7 0.8.8). Bindings are only ever created on the `add` action by
4465
+ * workflow.publish → updateBizQueryAddAction (8.6.26
4466
+ * WorkflowTemplateController.java:791,818-846; 2.1.5 :695-711,741-761).
4467
+ */
4468
+ async function scanListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4334
4469
  const bound = [];
4470
+ const unreadableViews = [];
4471
+ let listed;
4335
4472
  try {
4336
- const listed = wireRows((await wireCall(session, { path: ENDPOINTS.listQueryList, query: { schemaCode, clientType: "PC" } })).data);
4337
- for (const row of listed) {
4338
- const code = String(row.code ?? "");
4339
- if (!code)
4473
+ listed = wireRows((await wireCall(session, { path: ENDPOINTS.listQueryList, query: { schemaCode, clientType: "PC" } })).data);
4474
+ }
4475
+ catch {
4476
+ return { bound, readable: false, unreadableViews };
4477
+ }
4478
+ for (const row of listed) {
4479
+ const code = String(row.code ?? "");
4480
+ if (!code)
4481
+ continue;
4482
+ try {
4483
+ const got = await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode, code, clientType: "PC" } });
4484
+ const model = (got.data ?? null);
4485
+ if (!model)
4340
4486
  continue;
4341
- try {
4342
- const got = await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode, code, clientType: "PC" } });
4343
- const model = (got.data ?? null);
4344
- if (!model)
4487
+ const actions = Array.isArray(model.queryActions) ? model.queryActions : [];
4488
+ const fieldCodes = (Array.isArray(model.queryColumns) ? model.queryColumns : [])
4489
+ .map((column) => String(column.propertyCode ?? ""))
4490
+ .filter(Boolean);
4491
+ for (const action of actions) {
4492
+ const association = action.associationType ?? action.queryActionRelativeType;
4493
+ const associationCode = String(action.associationCode ?? action.relativeCode ?? "");
4494
+ const isWorkflow = association === 1 ||
4495
+ association === "1" ||
4496
+ association === "WORKFLOW" ||
4497
+ String(association).toUpperCase() === "WORKFLOW";
4498
+ if (!isWorkflow)
4345
4499
  continue;
4346
- const actions = Array.isArray(model.queryActions) ? model.queryActions : [];
4347
- const fieldCodes = (Array.isArray(model.queryColumns) ? model.queryColumns : [])
4348
- .map((column) => String(column.propertyCode ?? ""))
4349
- .filter(Boolean);
4350
- for (const action of actions) {
4351
- const association = action.associationType ?? action.queryActionRelativeType;
4352
- const associationCode = String(action.associationCode ?? action.relativeCode ?? "");
4353
- const isWorkflow = association === 1 ||
4354
- association === "1" ||
4355
- association === "WORKFLOW" ||
4356
- String(association).toUpperCase() === "WORKFLOW";
4357
- if (!isWorkflow)
4358
- continue;
4359
- if (associationCode && associationCode !== workflowCode && associationCode !== schemaCode)
4360
- continue;
4361
- bound.push({
4362
- code,
4363
- name: String(row.name ?? model.name ?? code),
4364
- actionCode: action.actionCode === undefined || action.actionCode === null ? null : String(action.actionCode),
4365
- associationCode: associationCode || null,
4366
- fieldCodes,
4367
- });
4368
- }
4369
- }
4370
- catch {
4371
- // one view unreadable — keep scanning
4500
+ if (associationCode && associationCode !== workflowCode && associationCode !== schemaCode)
4501
+ continue;
4502
+ bound.push({
4503
+ code,
4504
+ name: String(row.name ?? model.name ?? code),
4505
+ actionCode: action.actionCode === undefined || action.actionCode === null ? null : String(action.actionCode),
4506
+ associationCode: associationCode || null,
4507
+ fieldCodes,
4508
+ });
4372
4509
  }
4373
4510
  }
4511
+ catch {
4512
+ // one view unreadable — keep scanning, but remember it: it may still
4513
+ // carry the binding, so an opted-in delete must not claim "clean".
4514
+ unreadableViews.push(code);
4515
+ }
4374
4516
  }
4375
- catch {
4376
- // list unreadable — caller still gets a generic detach recipe
4377
- }
4378
- return bound;
4517
+ return { bound, readable: true, unreadableViews };
4518
+ }
4519
+ /** Best-effort: which list views still bind this workflow (303024 recovery). */
4520
+ async function findListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4521
+ return (await scanListviewsBoundToWorkflow(session, schemaCode, workflowCode)).bound;
4379
4522
  }
4380
4523
  // `list_permission` echoes the PERMISSION row id plus the unit's display name
4381
4524
  // and code — never the unitId (WorkflowTemplateController.getPermissionMap).
@@ -28,13 +28,55 @@ 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 { inboundModelReferences, inboundReferenceRefusal } from "./lanes/model-references.js";
32
+ import { resolveModelTreeNode } from "./lanes/model.js";
31
33
  import { SessionManager } from "./session-manager.js";
32
34
  import { ConfigStore, defaultPaths } from "./config-store.js";
35
+ /** The ONLY step kinds the purge may execute on its own. `model.delete` is never one. */
36
+ const UNBIND_STEP_TOOLS = new Set(["field.delete", "field.publish"]);
37
+ /**
38
+ * Restrict a `deletionSteps` list to the unlink-only steps. Safety invariant:
39
+ * the purge never executes arbitrary commands from the refusal — only the two
40
+ * tools that remove a reference column and republish its owner.
41
+ */
42
+ export function unbindDeletionSteps(steps) {
43
+ return steps.filter((step) => UNBIND_STEP_TOOLS.has(step.tool));
44
+ }
45
+ /**
46
+ * The "same command with the new flag" the blocked/partial receipt points at.
47
+ * One purge command does instances → unbind → model cascade.
48
+ */
49
+ export function unbindPurgeCommand(schemaCode, options = {}) {
50
+ return `omc model-purge --code ${schemaCode} --unbind-references${options.purgeInstances === true ? " --purge-instances" : ""} --apply`;
51
+ }
33
52
  async function sessionFor(environment) {
34
53
  const store = new ConfigStore(defaultPaths());
35
54
  const sessions = new SessionManager(store);
36
55
  return sessions.session(environment);
37
56
  }
57
+ /**
58
+ * Map the inner refusal's executable steps to an ordered list of prerequisite
59
+ * targets, e.g. `["field.delete:items.repairRef", "field.publish:m",
60
+ * "model.delete:m"]`. The old purge receipt built this from
61
+ * `referencingModels` codes and produced `["m", "m"]` for a self-reference
62
+ * (the child column resolves back to the parent) — a list with no executable
63
+ * prerequisite and the target twice. Deriving it from the shared
64
+ * `deletionSteps` keeps the order and never repeats an entry.
65
+ */
66
+ export function purgeDeletionOrder(steps) {
67
+ const seen = new Set();
68
+ const order = [];
69
+ for (const step of steps) {
70
+ const schemaCode = String(step.args.schemaCode ?? "");
71
+ const code = typeof step.args.code === "string" ? step.args.code : "";
72
+ const target = step.tool === "field.delete" ? `field.delete:${schemaCode}.${code}` : `${step.tool}:${schemaCode}`;
73
+ if (seen.has(target))
74
+ continue;
75
+ seen.add(target);
76
+ order.push(target);
77
+ }
78
+ return order;
79
+ }
38
80
  /**
39
81
  * Read-only discovery: everything the purge would remove, in dependency order.
40
82
  * `session` is injectable so tests can plan against a fake platform; the CLI
@@ -146,6 +188,42 @@ export async function planPurge(options, injected) {
146
188
  const steps = [];
147
189
  if (instanceCount > 0)
148
190
  steps.push(options.purgeInstances ? `workflow.delete_instance ×${instanceCount}` : `⛔ ${instanceCount} 个流程实例(需 --purge-instances)`);
191
+ // Inbound-reference pre-scan: the SAME shared scan model.delete runs before
192
+ // physically_delete (src/lanes/model-references.ts). Read-only; a failure of
193
+ // the scan must not block the plan — the write path re-scans and refuses.
194
+ let referencePreview = {};
195
+ if (modelExists) {
196
+ try {
197
+ const resolved = await resolveModelTreeNode(session, options.schemaCode);
198
+ const references = resolved.treeRows.length > 0 ? await inboundModelReferences(session, [options.schemaCode], resolved.treeRows) : [];
199
+ if (references.length > 0) {
200
+ const refusal = inboundReferenceRefusal(options.schemaCode, references);
201
+ const unbindEnabled = options.unbindReferences === true;
202
+ const unbindSteps = unbindDeletionSteps(refusal.deletionSteps);
203
+ const nextCommand = unbindPurgeCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances });
204
+ referencePreview = {
205
+ inboundReferences: references,
206
+ deletionSteps: refusal.deletionSteps,
207
+ deletionOrder: purgeDeletionOrder(refusal.deletionSteps),
208
+ nextCommand,
209
+ ...(unbindEnabled ? { unbindReferences: true, unbindSteps: purgeDeletionOrder(unbindSteps) } : {}),
210
+ referenceNotice: `${options.schemaCode} 有入站引用(${refusal.referencingModels.map((model) => model.schemaCode).join("、")};` +
211
+ `子表列经 parentCode 解析回本模型时属于自引用)。` +
212
+ (unbindEnabled
213
+ ? `已开启 --unbind-references:本命令会先按 deletionSteps 执行拆引用(${unbindSteps.map((step) => step.tool).join(" → ")};` +
214
+ `**破坏性:会删除引用列/子表关联列,列数据不可恢复**),全部成功后再让 model.delete 级联;任一步失败即停,不会删模型。`
215
+ : `--apply 的 model.delete 会零写入拒绝;nextCommand 是加上 --unbind-references 的同一条命令(本命令会自动拆引用;` +
216
+ `**破坏性:会删除引用列/子表关联列,列数据不可恢复**),也可以自己按 deletionSteps 逐条执行。`),
217
+ };
218
+ steps.push(unbindEnabled
219
+ ? `🔧 拆引用(--unbind-references):${unbindSteps.map((step) => step.command).join(" → ")} → 再删模型`
220
+ : `⛔ 入站引用:先执行 deletionSteps(${refusal.deletionSteps[0]?.command ?? ""}),再删模型`);
221
+ }
222
+ }
223
+ catch {
224
+ // A scan error is reported by the write path's own gate; the plan stays useful.
225
+ }
226
+ }
149
227
  steps.push(`model.delete ${options.schemaCode}(级联带走:${[
150
228
  workflowCode ? `流程 ${workflowCode}` : undefined,
151
229
  listViews.length > 0 ? `${listViews.length} 个列表视图` : undefined,
@@ -173,6 +251,7 @@ export async function planPurge(options, injected) {
173
251
  instanceIds: [...instanceIds].slice(0, 50),
174
252
  steps,
175
253
  blockers,
254
+ ...referencePreview,
176
255
  };
177
256
  }
178
257
  /**
@@ -242,10 +321,12 @@ export async function cmdModelPurge(args) {
242
321
  const environment = flag("--env") ?? flag("--environment");
243
322
  const apply = args.includes("--apply");
244
323
  const purgeInstances = args.includes("--purge-instances");
324
+ const unbindReferences = args.includes("--unbind-references");
245
325
  const usage = [
246
- "用法:omc model-purge --code <模型code> [--purge-instances] [--env <环境>] [--apply]",
326
+ "用法:omc model-purge --code <模型code> [--purge-instances] [--unbind-references] [--env <环境>] [--apply]",
247
327
  " 一条命令按依赖倒序清掉:列表视图 → 自建业务规则 → 流程实例 → 流程 → 模型(字段/表单/计算规则/预置规则随模型级联)。",
248
328
  " 默认 dry-run(只列计划,不写)。--purge-instances 才删流程实例(workflow.delete 遇到实例会 402508)。",
329
+ " --unbind-references 才会先按 deletionSteps 拆入站引用(field.delete 引用列 + field.publish 所属模型,**破坏性:列数据不可恢复**),再删模型。",
249
330
  " 每步回读确认;某步失败即停并说明已完成到哪一步(幂等,可修好后重跑)。",
250
331
  ].join("\n");
251
332
  const invalid = (message) => {
@@ -254,7 +335,7 @@ export async function cmdModelPurge(args) {
254
335
  };
255
336
  if (!schemaCode)
256
337
  return invalid("--code 必填");
257
- const options = { schemaCode, apply, purgeInstances, ...(environment !== undefined ? { environment } : {}) };
338
+ const options = { schemaCode, apply, purgeInstances, unbindReferences, ...(environment !== undefined ? { environment } : {}) };
258
339
  let plan;
259
340
  try {
260
341
  plan = await planPurge(options);
@@ -265,12 +346,21 @@ export async function cmdModelPurge(args) {
265
346
  return CLI_EXIT_CODES.internal;
266
347
  }
267
348
  if (!apply) {
349
+ const referenced = plan.inboundReferences !== undefined && plan.inboundReferences.length > 0;
350
+ const unbindEnabled = plan.unbindReferences === true;
268
351
  writeEnvelope(envelope("ok", {
269
- status: plan.blockers.length > 0 ? "blocked" : "dry-run",
352
+ status: plan.blockers.length > 0 || (referenced && !unbindEnabled) ? "blocked" : "dry-run",
270
353
  ...plan,
271
354
  ...(plan.blockers.length > 0
272
355
  ? {}
273
- : { note: "dry-run 只列计划、不写。--apply 按上面的顺序执行;每步回读确认。" }),
356
+ : {
357
+ note: `dry-run 只列计划、不写。--apply 按上面的顺序执行;每步回读确认。` +
358
+ (referenced
359
+ ? unbindEnabled
360
+ ? `已开启 --unbind-references:--apply 会先执行 unbindSteps(${(plan.unbindSteps ?? []).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**),再把 model.delete 交给主流程级联。`
361
+ : `入站引用已预扫(与 model.delete 同一份 gate):model.delete 会零写入拒绝;nextCommand 是加上 --unbind-references 的同一条命令(**破坏性:会删除引用列/子表关联列,列数据不可恢复**),也可以自己按 deletionSteps 逐条拆。`
362
+ : ""),
363
+ }),
274
364
  }, request));
275
365
  return CLI_EXIT_CODES.ok;
276
366
  }
@@ -284,12 +374,82 @@ export async function cmdModelPurge(args) {
284
374
  }));
285
375
  return CLI_EXIT_CODES.policyRefused;
286
376
  }
287
- const steps = [];
288
377
  const session = await sessionFor(environment);
289
378
  const call = async (tool, toolArgs) => {
290
379
  const outcome = await runToolCall(tool, { args: toolArgs, requestId: request, ...(environment !== undefined ? { environment } : {}), print: () => undefined });
291
380
  return { ok: outcome.exitCode === 0, result: outcome.result };
292
381
  };
382
+ const execution = await executePurge(plan, session, call);
383
+ const result = execution.result;
384
+ const steps = Array.isArray(result.steps) ? result.steps : [];
385
+ const classified = classifyResult(execution.failed ? { ...result, requested: steps.length, succeeded: steps.filter((step) => step.status !== "failed").length } : result);
386
+ writeEnvelope(envelope(classified.status, result, request, classified.error));
387
+ return execution.failed ? 1 : 0;
388
+ }
389
+ const invalidStepMessage = "步骤参数不完整,拒绝执行(只按 deletionSteps 逐字执行 field.delete/field.publish,不执行任意命令)";
390
+ /**
391
+ * Execute the unlink half of `deletionSteps` in order. Stops at the first
392
+ * failure; the caller must then skip `model.delete` (a half-unlinked model must
393
+ * not disappear). Never runs anything outside `field.delete`/`field.publish`.
394
+ */
395
+ export async function executeUnbindSteps(call, steps) {
396
+ const candidates = unbindDeletionSteps(steps);
397
+ const produced = [];
398
+ const executed = [];
399
+ for (let index = 0; index < candidates.length; index += 1) {
400
+ const step = candidates[index];
401
+ const label = step.tool === "field.delete"
402
+ ? `field.delete:${String(step.args.schemaCode ?? "")}.${String(step.args.code ?? "")}`
403
+ : `field.publish:${String(step.args.schemaCode ?? "")}`;
404
+ const schemaCode = step.args.schemaCode;
405
+ const code = step.args.code;
406
+ const shapeValid = typeof schemaCode === "string" &&
407
+ schemaCode.length > 0 &&
408
+ (step.tool !== "field.delete" || (typeof code === "string" && code.length > 0));
409
+ if (!shapeValid) {
410
+ produced.push({ step: label, status: "failed", detail: { code: "unbind-step-malformed", message: invalidStepMessage } });
411
+ return { failed: true, steps: produced, executed, remaining: candidates.slice(index), failedStep: label, failureMessage: invalidStepMessage };
412
+ }
413
+ let ok = false;
414
+ let failureMessage;
415
+ try {
416
+ const outcome = await call(step.tool, step.args);
417
+ ok = outcome.ok;
418
+ if (!ok)
419
+ failureMessage = typeof outcome.result.message === "string" && outcome.result.message.length > 0 ? outcome.result.message : refusalText(outcome.result);
420
+ }
421
+ catch (error) {
422
+ failureMessage = error instanceof Error ? error.message : String(error);
423
+ }
424
+ produced.push({
425
+ step: label,
426
+ status: ok ? "ok" : "failed",
427
+ ...(ok ? {} : { detail: { message: failureMessage ?? "平台拒绝" } }),
428
+ });
429
+ if (!ok) {
430
+ return {
431
+ failed: true,
432
+ steps: produced,
433
+ executed,
434
+ remaining: candidates.slice(index),
435
+ failedStep: label,
436
+ failureMessage: failureMessage ?? "平台拒绝",
437
+ };
438
+ }
439
+ executed.push(label);
440
+ }
441
+ return { failed: false, steps: produced, executed, remaining: [] };
442
+ }
443
+ /**
444
+ * Write phase: instances → `model.delete`, then build the receipt. Split from
445
+ * `cmdModelPurge` so the failure pass-through can be exercised without a live
446
+ * environment (the old code inline-built the receipt, so the F9 regression —
447
+ * dropping the inner `deletionSteps` and pointing `nextCommand` at the same
448
+ * command — had no test surface).
449
+ */
450
+ export async function executePurge(plan, session, call) {
451
+ const schemaCode = plan.schemaCode;
452
+ const steps = [];
293
453
  const record = (step, ok, detail) => {
294
454
  steps.push({ step, status: ok ? "ok" : "failed", ...(detail ? { detail } : {}) });
295
455
  };
@@ -314,8 +474,24 @@ export async function cmdModelPurge(args) {
314
474
  steps.push(...instanceOutcome.steps);
315
475
  let failed = instanceOutcome.failed;
316
476
  const unremovableInstances = instanceOutcome.unremovableInstances;
477
+ // F7(0.8.9,探针 D):`--unbind-references` 才执行拆引用。只跑
478
+ // deletionSteps 里的 field.delete/field.publish(model.delete 仍由本命令的
479
+ // 主流程负责,绝不重复)。任一步失败即停,模型不删。
480
+ let unbindOutcome;
481
+ if (!failed && plan.unbindReferences === true && (plan.deletionSteps?.length ?? 0) > 0) {
482
+ const candidates = plan.deletionSteps ?? [];
483
+ unbindOutcome = await executeUnbindSteps(call, candidates);
484
+ steps.push(...unbindOutcome.steps);
485
+ if (unbindOutcome.failed)
486
+ failed = true;
487
+ }
317
488
  // 2) the model — everything else cascades with it.
318
489
  let referrers = [];
490
+ // F9(0.8.8,探针 C):内层 model.delete 的零写入拒绝已带 inboundReferences /
491
+ // deletionSteps(可复制 command)。旧 purge 把它们压成 referrers 字符串,再用
492
+ // referrers 拼 deletionOrder/nextCommand:自引用(子表列 parentCode 解析回自身)
493
+ // 时得到 ["m","m"],nextCommand 只是重跑同一条命令——照做必再撞同一拒绝。
494
+ let deleteRefusal;
319
495
  if (!failed) {
320
496
  const outcome = await call("model.delete", { schemaCode });
321
497
  const readback = outcome.result.readback;
@@ -323,35 +499,66 @@ export async function cmdModelPurge(args) {
323
499
  referrers = Array.isArray(outcome.result.referencingModels)
324
500
  ? outcome.result.referencingModels.map((row) => String(row.schemaCode ?? "")).filter((code) => code.length > 0)
325
501
  : [];
502
+ const refusalMessage = typeof outcome.result.message === "string" && outcome.result.message.length > 0 ? outcome.result.message : refusalText(outcome.result);
326
503
  record(`model.delete:${schemaCode}`, outcome.ok || absent, outcome.ok || absent
327
504
  ? (readback ? { cascades: true, absent: readback.absent ?? null } : undefined)
328
- : { message: refusalText(outcome.result), ...(referrers.length > 0 ? { referencedBy: referrers } : {}) });
329
- if (!outcome.ok && !absent)
505
+ : { message: refusalMessage, ...(referrers.length > 0 ? { referencedBy: referrers } : {}) });
506
+ if (!outcome.ok && !absent) {
330
507
  failed = true;
508
+ const inboundReferences = Array.isArray(outcome.result.inboundReferences) ? outcome.result.inboundReferences : [];
509
+ const deletionSteps = Array.isArray(outcome.result.deletionSteps) ? outcome.result.deletionSteps : [];
510
+ if (inboundReferences.length > 0)
511
+ deleteRefusal = { inboundReferences, deletionSteps, message: refusalMessage };
512
+ }
331
513
  }
332
514
  const status = failed ? "partial" : "ok";
515
+ const rerunCommand = unbindPurgeCommand(schemaCode);
516
+ // Pass the inner refusal through verbatim; the purge-level receipt must not
517
+ // promise keys it dropped (F9: message named deletionSteps that were absent).
518
+ const failureFields = unbindOutcome?.failed === true
519
+ ? {
520
+ nextAction: "fix-and-rerun",
521
+ unbindReferences: true,
522
+ failedStep: unbindOutcome.failedStep,
523
+ remainingSteps: unbindOutcome.remaining,
524
+ modelDeletePending: true,
525
+ nextCommand: rerunCommand,
526
+ message: `${schemaCode} 未删除:拆引用在 ${unbindOutcome.failedStep ?? "某一步"} 失败,已停在该步;` +
527
+ `**未调用 model.delete,模型仍存在**。原因:${unbindOutcome.failureMessage ?? "平台拒绝"}。` +
528
+ `已成功的拆引用步骤不回滚(幂等,重跑不会重复破坏);修复后重跑本命令(nextCommand)继续。`,
529
+ }
530
+ : deleteRefusal !== undefined
531
+ ? {
532
+ nextAction: "execute-deletion-steps",
533
+ inboundReferences: deleteRefusal.inboundReferences,
534
+ deletionSteps: deleteRefusal.deletionSteps,
535
+ deletionOrder: purgeDeletionOrder(deleteRefusal.deletionSteps),
536
+ nextCommand: rerunCommand,
537
+ ...(referrers.length > 0 ? { blockedBy: referrers } : {}),
538
+ message: `${schemaCode} 未删除(零写入拒绝,未启动平台删除任务)。${deleteRefusal.message} ` +
539
+ `两条路:① 一条命令自动拆引用:nextCommand(--unbind-references;**破坏性:会删除指向本模型的引用列/子表关联列,列数据不可恢复**),` +
540
+ `拆完引用后由 model.delete 级联;② 自己按 deletionSteps 逐条执行。不要在未拆引用时重试 --apply(不带 --unbind-references 仍会零写入拒绝)。`,
541
+ }
542
+ : {
543
+ nextAction: "fix-and-rerun",
544
+ ...(referrers.length > 0 ? { blockedBy: referrers } : {}),
545
+ message: referrers.length > 0
546
+ ? `${schemaCode} 仍被 ${referrers.join("、")} 的关联字段引用,模型不能删。先跑 omc model-purge --code ${schemaCode}(dry-run)拿 inboundReferences / deletionSteps;` +
547
+ `再加 --unbind-references --apply 让一条命令自动拆引用(破坏性:会删除引用列),或逐条拆后再 --apply。`
548
+ : "在失败的这一步停下(幂等,可修好后重跑同一条命令)。已成功的步骤不会重复破坏。",
549
+ };
333
550
  const result = {
334
551
  status,
335
552
  schemaCode,
336
553
  verdict: plan.modelExists && !failed ? "cascading" : "clean",
337
554
  ...(plan.workflowCode !== undefined ? { workflowCode: plan.workflowCode } : {}),
555
+ ...(plan.unbindReferences === true ? { unbindReferences: true } : {}),
556
+ ...(unbindOutcome !== undefined ? { unboundSteps: unbindOutcome.executed, unbindFailed: unbindOutcome.failed } : {}),
338
557
  deletedInstances: steps.filter((step) => step.step.startsWith("workflow.delete_instance:") && step.status === "ok").length,
339
558
  ...(unremovableInstances.length > 0 ? { unremovableInstances } : {}),
340
559
  steps,
341
560
  ...(failed
342
- ? {
343
- nextAction: "fix-and-rerun",
344
- ...(referrers.length > 0
345
- ? {
346
- blockedBy: referrers,
347
- deletionOrder: [...referrers, schemaCode],
348
- nextCommand: `omc model-purge --code ${referrers[0]} --purge-instances --apply`,
349
- }
350
- : {}),
351
- message: referrers.length > 0
352
- ? `${schemaCode} 仍被 ${referrers.join("、")} 的关联字段引用,模型不能删(平台 deleteFunctions 的异步拒绝已提前到调用时)。按 deletionOrder 先清引用方,再重跑本命令。`
353
- : "在失败的这一步停下(幂等,可修好后重跑同一条命令)。已成功的步骤不会重复破坏。",
354
- }
561
+ ? failureFields
355
562
  : unremovableInstances.length > 0
356
563
  ? {
357
564
  cleanupWarning: `${unremovableInstances.length} 条停滞实例无法通过平台 REST 删除(delete_instance 50000:业务对象已不存在,平台 NPE)。` +
@@ -360,13 +567,13 @@ export async function cmdModelPurge(args) {
360
567
  maintainerAction: `DELETE FROM biz_workflow_instance WHERE id IN (${unremovableInstances.map((item) => `'${item.id}'`).join(", ")});`,
361
568
  }
362
569
  : {
363
- note: "已清理:流程实例逐个删除 → model.delete 级联带走流程模板/列表视图/字段/表单/业务规则。" +
570
+ note: "已清理:流程实例逐个删除 → " +
571
+ (unbindOutcome !== undefined ? "拆入站引用(field.delete 引用列 → field.publish 所属模型)→ " : "") +
572
+ "model.delete 级联带走流程模板/列表视图/字段/表单/业务规则。" +
364
573
  "model.delete 是平台异步任务(建删除历史后立即返回,级联时长不定),稍后仍能读到模型记录属正常残留,重跑本命令即可(幂等)。" +
365
574
  "**这就是 r12–r14 三次脏沙盒的根治**:实例先走,就不会留下指向空模板的待办。",
366
575
  }),
367
576
  };
368
- const classified = classifyResult(status === "partial" ? { ...result, requested: steps.length, succeeded: steps.filter((step) => step.status !== "failed").length } : result);
369
- writeEnvelope(envelope(classified.status, result, request, classified.error));
370
- return failed ? 1 : 0;
577
+ return { failed, result };
371
578
  }
372
579
  //# sourceMappingURL=model-purge.js.map