@stalfh233/omc-cli 0.8.14 → 0.8.16

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.
@@ -7,12 +7,13 @@ import { ToolRefusalError } from "../tool-types.js";
7
7
  import { writeTool } from "../write.js";
8
8
  import { registerPackageTool } from "../package-tool.js";
9
9
  import { writeSummary } from "../human-summary.js";
10
- import { defineTool, ToolInputError } from "../tool-types.js";
10
+ import { defineTool, isRequiredAlternativePlaceholder, ToolInputError } from "../tool-types.js";
11
11
  import { DEFAULT_SCAN_CONCURRENCY, mapWithConcurrency } from "../concurrency.js";
12
12
  import { wireCall, wireRows, WireError } from "../wire.js";
13
13
  import { diagnoseInstanceActivity, getInstanceBaseInfo, isCanceledInstanceStatus, isFinishedInstanceStatus, listInstanceActivities, listWorkItemsByParticipant, resolveBizObjectIdByInstance, searchWorkItems, wireString } from "../workflow-support.js";
14
14
  import { readSchemaFormButtons } from "../form-support.js";
15
15
  import { WORKFLOW_EVENT_HANDLER_FIELDS, WORKFLOW_NODE_EVENT_HANDLER_FIELDS, WORKFLOW_LANE_CONTRACT, workflowTemplateArg } from "./workflow-contract.js";
16
+ import { decodeActionRow } from "./list-view-shapes.js";
16
17
  import { PLATFORM_TRIGGER_RULE_CODES } from "./rule-graph.js";
17
18
  import { executeRuleEnableWrite } from "./rule-lifecycle.js";
18
19
  import { PLATFORM_ADMIN_START_BYPASS, resolvePermissionActor } from "../identity.js";
@@ -3351,20 +3352,35 @@ export function registerWorkflowLane(tools) {
3351
3352
  actions: [],
3352
3353
  replaceActions: true,
3353
3354
  })}'`;
3355
+ // F8(0.8.16 探针 J):`workflow.delete` 已支持 `unbindListviews:true`——它
3356
+ // 只解本流程的视图绑定,不动视图其它动作。旧的 beforeWorkflowDelete 只
3357
+ // 指向 listview.configure `actions:[] + replaceActions:true`,那会把
3358
+ // add/delete/import/export/editowner 等其它动作一起清掉。首选 unbindListviews。
3359
+ const workflowDeleteCommand = `omc call workflow.delete --env <env> --args '${JSON.stringify({
3360
+ schemaCode: args.schemaCode,
3361
+ code: args.code,
3362
+ unbindListviews: true,
3363
+ })}'`;
3354
3364
  const listviewBinding = {
3355
3365
  bound: addBindings.bound.map(({ code, actionCode }) => ({ code, actionCode })),
3356
3366
  ...(firstPublish ? {} : { firstPublish: false }),
3357
3367
  note: addBindings.bound.length > 0
3358
3368
  ? firstPublish
3359
- ? "首次发布已把本模型各列表视图的 add 动作绑到本流程;删流程前先 listview.configure 清 actions 或用 workflow.delete 的 nextCommand"
3360
- : "列表视图的 add 动作已绑定本流程(本次不是首次发布,绑定沿用既有配置);删流程前先 listview.configure 清 actions 或用 workflow.delete 的 nextCommand"
3369
+ ? "首次发布已把本模型各列表视图的 add 动作绑到本流程;删流程前用 workflow.delete 的 nextCommand(unbindListviews:true)解绑"
3370
+ : "列表视图的 add 动作已绑定本流程(本次不是首次发布,绑定沿用既有配置);删流程前用 workflow.delete 的 nextCommand(unbindListviews:true)解绑"
3361
3371
  : addBindings.readable
3362
3372
  ? "无隐式绑定"
3363
3373
  : "列表视图读取失败,未能确认 add 绑定;删流程前先 listview.get 复核",
3364
3374
  ...(addBindings.bound.length > 0
3365
3375
  ? {
3366
- beforeWorkflowDelete: "删流程前先解绑:用 listview.configure 清掉该视图 add 动作(actions:[] + replaceActions:true),否则 workflow.delete 会撞 workflow-bound-to-listview(303024,列表还绑着流程);多个视图绑定时逐视图处理。",
3367
- ...(unbindCommand !== undefined ? { unbindCommand } : {}),
3376
+ beforeWorkflowDelete: "删流程前先解绑:首选 nextCommand —— workflow.delete 带 unbindListviews:true,本工具会先逐个视图解绑(只清本流程的绑定,不动视图其它动作),再删流程;否则会撞 workflow-bound-to-listview(303024,列表还绑着流程)。多个视图绑定时由 unbindListviews 逐视图处理。",
3377
+ ...(unbindCommand !== undefined
3378
+ ? {
3379
+ unbindCommand,
3380
+ unbindCommandNote: "次选(只在你想手工改视图时用):listview.configure 清 actions:[] + replaceActions:true 会**顺带清掉该视图的其它动作**(add/delete/import/export/editowner 等),不是只解本流程绑定;只想解本流程绑定请用 nextCommand。",
3381
+ }
3382
+ : {}),
3383
+ nextCommand: workflowDeleteCommand,
3368
3384
  }
3369
3385
  : {}),
3370
3386
  };
@@ -3836,6 +3852,81 @@ export function registerWorkflowLane(tools) {
3836
3852
  },
3837
3853
  rollback: workflowRollbackSpec("workflow.update"),
3838
3854
  });
3855
+ /**
3856
+ * F7(0.8.15,探针 I):候选 workflowCode 列表——解析失败时给可复制的核对面。
3857
+ * 平台没有「流程全集」端点(WorkflowTemplateController 只有按 schemaCode 的
3858
+ * list/getAllWorkflow),所以沿用 workflow.list 的模型索引骨架,并共用同一模型
3859
+ * 上限(WORKFLOW_LIST_MODEL_CAP=50,超出标 candidatesTruncated)。差异:本枚举
3860
+ * 只做 schemaCode→workflowCode 的点查询(每模型 1 wire getWorkflow,不经
3861
+ * isworkflow、不读 get_published 摘要),只服务失败路径,不替代 workflow.list
3862
+ * 的完整清单(那里有存在性/发布态/规则绑定计数)。
3863
+ */
3864
+ const WORKFLOW_DELETE_CANDIDATE_MODEL_CAP = WORKFLOW_LIST_MODEL_CAP;
3865
+ async function availableWorkflowCodes(session) {
3866
+ try {
3867
+ const scope = await resolveApplicationScope(session, undefined);
3868
+ const tree = wireRows((await wireCall(session, { path: ENDPOINTS.applicationTree, query: { appCode: scope.code } })).data);
3869
+ const models = flattenTreeRows(tree).filter((row) => row.type === "BizModel" && typeof row.code === "string" && row.code.length > 0);
3870
+ const scan = models.slice(0, WORKFLOW_DELETE_CANDIDATE_MODEL_CAP);
3871
+ const codes = [];
3872
+ for (const model of scan) {
3873
+ try {
3874
+ const linked = (await wireCall(session, { path: ENDPOINTS.workflowGetBySchema, query: { schemaCode: String(model.code) } })).data;
3875
+ const code = linked !== null && typeof linked.workflowCode === "string" && linked.workflowCode.length > 0 ? linked.workflowCode : undefined;
3876
+ if (code !== undefined)
3877
+ codes.push(code);
3878
+ }
3879
+ catch {
3880
+ // 单模型读失败不中断候选枚举(同 workflow.list 的容错口径)
3881
+ }
3882
+ }
3883
+ return { codes: [...new Set(codes)], scannedModels: scan.length, truncated: models.length > scan.length };
3884
+ }
3885
+ catch {
3886
+ return { codes: [], scannedModels: 0, truncated: false };
3887
+ }
3888
+ }
3889
+ /**
3890
+ * F7(0.8.15,探针 I):只给流程码(code / workflowCode 别名)时反查所属模型。
3891
+ * 依据:平台 get_published 把 header 的 schemaCode 写回模板
3892
+ * (WorkflowTemplateController.getPublished,8.6.26 :618-655 ——
3893
+ * `templateModel.setSchemaCode(headerModel.getSchemaCode())`),一次读即可;
3894
+ * 模型侧 getWorkflow 只反方向(schemaCode → workflowCode),不能当本用途。
3895
+ * 解析不出就零写入拒绝,并列出当前应用可用的 workflowCode + workflow.list 指引。
3896
+ */
3897
+ async function resolveWorkflowDeleteSchema(session, args) {
3898
+ if (!isRequiredAlternativePlaceholder(args.schemaCode))
3899
+ return;
3900
+ let published;
3901
+ try {
3902
+ published = await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode: args.code } });
3903
+ }
3904
+ catch (error) {
3905
+ if (!isWorkflowAbsent(error))
3906
+ throw error;
3907
+ }
3908
+ const data = (published?.data ?? null);
3909
+ const schemaCode = data !== null && typeof data.schemaCode === "string" && data.schemaCode.length > 0 ? data.schemaCode : undefined;
3910
+ if (schemaCode !== undefined) {
3911
+ args.schemaCode = schemaCode;
3912
+ return;
3913
+ }
3914
+ const candidates = await availableWorkflowCodes(session);
3915
+ throw new ToolRefusalError({
3916
+ status: "refused",
3917
+ blocker: "workflow-not-found",
3918
+ workflowCode: args.code,
3919
+ candidates: candidates.codes,
3920
+ scannedModels: candidates.scannedModels,
3921
+ ...(candidates.truncated ? { candidatesTruncated: true } : {}),
3922
+ nextCommand: `omc call workflow.list --args '{}'`,
3923
+ message: `workflow.delete 只给了流程码 ${args.code},但流程读面解析不出它所属的模型(workflow/get_published ${args.code} 缺席或未带回 schemaCode)——无法定位要删的流程,本次零写入。` +
3924
+ (candidates.codes.length > 0
3925
+ ? `当前应用可用的 workflowCode:${candidates.codes.join("、")}。`
3926
+ : `当前应用未扫到可用 workflowCode(scannedModels=${candidates.scannedModels})。`) +
3927
+ `核对流程码后重发(也可同时显式给 schemaCode);流程清单用 nextCommand:omc call workflow.list(按模型索引,可传 applicationCode)。`,
3928
+ });
3929
+ }
3839
3930
  writeTool({
3840
3931
  tools,
3841
3932
  name: "workflow.delete",
@@ -3844,16 +3935,17 @@ export function registerWorkflowLane(tools) {
3844
3935
  scope: WORKFLOW_TOOLS["workflow.delete"].scope,
3845
3936
  description: WORKFLOW_TOOLS["workflow.delete"].description,
3846
3937
  inputSchema: {
3847
- schemaCode: z.string().min(1),
3938
+ schemaCode: z.string().min(1).describe("模型 code;只给 code/workflowCode 时可省略——工具用 workflow/get_published 一次读反查所属模型"),
3848
3939
  code: z.string().min(1).describe("流程编码——本参数名是 code"),
3849
3940
  unbindListviews: z
3850
3941
  .boolean()
3851
3942
  .optional()
3852
- .describe("先解绑列表视图再删流程:true 时对本模型每个绑定了本流程的列表视图执行 listview.configure(actions:[] + replaceActions:true,保留原列 fieldCodes),成功后才删流程;任一步解绑失败即停、不删流程。**会改动视图配置(移除该视图 add 动作的平台关联),必须显式确认才做。** 默认 false 只删流程,遇 303024 仍拒绝并给 nextCommand"),
3943
+ .describe("先解绑列表视图再删流程:true 时对每个绑定了本流程的列表视图,只移除其 add 动作里指向本流程的那一条(保留 delete/import/export/editowner 等其它动作),再删流程;任一步解绑失败即停、不删流程。**会改动视图配置(移除该视图 add 动作的平台关联),必须显式确认才做。** 默认 false 只删流程,遇 303024 仍拒绝并给 nextCommand"),
3853
3944
  },
3854
3945
  // F7(0.8.8):dry-run 与真写共用同一份只读扫描——预览列出会被解绑的视图,
3855
3946
  // 真写在任何写 wire 之前也先跑这里。两者都不写。
3856
3947
  writeLint: async (session, args) => {
3948
+ await resolveWorkflowDeleteSchema(session, args);
3857
3949
  if (args.unbindListviews !== true) {
3858
3950
  return {
3859
3951
  wouldChange: true,
@@ -3879,7 +3971,7 @@ export function registerWorkflowLane(tools) {
3879
3971
  code,
3880
3972
  name,
3881
3973
  ...(fieldCodes.length > 0 ? { fieldCodes } : {}),
3882
- action: "listview.configure actions:[] + replaceActions:true",
3974
+ action: "移除指向本流程的 add 绑定(其余动作原样保留)",
3883
3975
  })),
3884
3976
  }
3885
3977
  : {}),
@@ -3892,6 +3984,7 @@ export function registerWorkflowLane(tools) {
3892
3984
  };
3893
3985
  },
3894
3986
  execute: async (session, args) => {
3987
+ await resolveWorkflowDeleteSchema(session, args);
3895
3988
  const steps = [];
3896
3989
  // Opt-in unbind (F7): the workflow.publish side effect binds every list
3897
3990
  // view's `add` action to this workflow, and workflow.delete then answers
@@ -3907,14 +4000,20 @@ export function registerWorkflowLane(tools) {
3907
4000
  workflowCode: args.code,
3908
4001
  message: "workflow.delete 需要 listview.configure 来解绑视图,但它未注册写执行;零写入停止",
3909
4002
  });
3910
- for (const view of scan.bound) {
4003
+ const boundViews = new Map();
4004
+ for (const view of scan.bound)
4005
+ if (!boundViews.has(view.code))
4006
+ boundViews.set(view.code, view);
4007
+ for (const view of boundViews.values()) {
3911
4008
  const fieldCodes = view.fieldCodes.length > 0 ? view.fieldCodes : ["createdTime", "creater", "name", "sequenceNo"];
4009
+ // F8(0.8.16):只移除指向本流程的 add 行,其余动作原样回写。
4010
+ const remainingActions = actionsWithoutWorkflowBinding(view.actions, args.code, args.schemaCode);
3912
4011
  try {
3913
4012
  const outcome = await configure.writeExecute(session, {
3914
4013
  schemaCode: args.schemaCode,
3915
4014
  code: view.code,
3916
4015
  fieldCodes,
3917
- actions: [],
4016
+ actions: remainingActions,
3918
4017
  replaceActions: true,
3919
4018
  });
3920
4019
  if ("status" in outcome)
@@ -3930,8 +4029,16 @@ export function registerWorkflowLane(tools) {
3930
4029
  status: "ok",
3931
4030
  viewCode: view.code,
3932
4031
  viewName: view.name,
3933
- actions: "cleared",
4032
+ actions: "selective-unbind",
4033
+ removedActions: view.actions
4034
+ .filter((action) => isWorkflowAddBinding(action, args.code, args.schemaCode))
4035
+ .map((action) => ({
4036
+ actionCode: action.actionCode ?? null,
4037
+ associationCode: action.associationCode ?? null,
4038
+ })),
4039
+ keptActions: remainingActions.map((action) => action.actionCode),
3934
4040
  replaceActions: true,
4041
+ note: "add 动作已移除,平台读面不会自动补回(也不会重新绑定本流程);需要恢复新增按钮时用 listview.configure defaultActions:true 重建内置动作。",
3935
4042
  readback: outcome.readback,
3936
4043
  });
3937
4044
  }
@@ -3944,7 +4051,7 @@ export function registerWorkflowLane(tools) {
3944
4051
  schemaCode: args.schemaCode,
3945
4052
  viewCode: view.code,
3946
4053
  steps,
3947
- nextCommand: `omc call listview.configure --env <env> --args '${JSON.stringify({ schemaCode: args.schemaCode, code: view.code, fieldCodes, actions: [], replaceActions: true })}'`,
4054
+ nextCommand: `omc call listview.configure --env <env> --args '${JSON.stringify({ schemaCode: args.schemaCode, code: view.code, fieldCodes, actions: remainingActions, replaceActions: true })}'`,
3948
4055
  message: `解绑列表视图 ${view.code} 失败,已停止:**流程 ${args.code} 未删除**(不半删)。原因:${cause}。` +
3949
4056
  `按 nextCommand 修好该视图后重发 workflow.delete(仍带 unbindListviews:true);已成功解绑的视图在 steps 里。`,
3950
4057
  });
@@ -3996,6 +4103,14 @@ export function registerWorkflowLane(tools) {
3996
4103
  replaceActions: true,
3997
4104
  };
3998
4105
  const detachExample = `omc call listview.configure --env <env> --args '${JSON.stringify(detachArgs)}'`;
4106
+ // F8(0.8.16 复核):安全路径优先——workflow.delete 带 unbindListviews
4107
+ // 只移除本流程的 add 绑定,保留 delete/import/export/editowner 等其它
4108
+ // 动作;listview.configure actions:[] 是全清次选,必须标明代价。
4109
+ const safeUnbindDeleteCommand = `omc call workflow.delete --env <env> --args '${JSON.stringify({
4110
+ schemaCode: args.schemaCode,
4111
+ code: args.code,
4112
+ unbindListviews: true,
4113
+ })}'`;
3999
4114
  throw new ToolRefusalError({
4000
4115
  status: "refused",
4001
4116
  blocker: "workflow-bound-to-listview",
@@ -4009,15 +4124,18 @@ export function registerWorkflowLane(tools) {
4009
4124
  associationCode,
4010
4125
  ...(cols.length > 0 ? { fieldCodes: cols } : {}),
4011
4126
  })),
4012
- nextCommand: detachExample,
4127
+ nextCommand: safeUnbindDeleteCommand,
4128
+ unbindCommand: detachExample,
4129
+ unbindCommandNote: "次选(只在你想手工改视图时用):listview.configure 清 actions:[] + replaceActions:true 会**顺带清掉该视图的其它动作**(add/delete/import/export/editowner 等),不是只解本流程绑定;只想解本流程绑定请用 nextCommand(workflow.delete 带 unbindListviews:true)。",
4013
4130
  message: `流程 ${args.code} 仍被列表视图绑定(303024「列表绑定了流程」)。` +
4014
4131
  (bound.length > 0
4015
4132
  ? `绑在:${bound.map((view) => `${view.code}(${view.name})action=${view.actionCode ?? "?"}`).join("、")}。`
4016
4133
  : `默认视图多半是 ${args.schemaCode}(workflow.create 会自动绑)。`) +
4017
- `先解绑再删:粘贴 nextCommand(listview.configure:actions:[] + replaceActions:true + 现有 fieldCodes),再重试 workflow.delete。` +
4134
+ `先解绑再删:nextCommand 是 workflow.delete 带 unbindListviews:true(只移除本流程的 add 绑定,保留 delete/import/export/editowner 等其它动作)。` +
4135
+ `次选 unbindCommand(listview.configure actions:[] + replaceActions:true + 现有 fieldCodes)会**清掉该视图其它动作**,只在你想手工改视图时用。` +
4018
4136
  (args.unbindListviews === true
4019
- ? `本次已带 unbindListviews:true,但仍有绑定未被清掉(见 boundListviews / unreadableViews);按 nextCommand 处理后重试。`
4020
- : `也可以重发 workflow.delete 并带 unbindListviews:true,让本工具先逐个视图解绑再删。`) +
4137
+ ? `本次已带 unbindListviews:true,但仍有绑定未被清掉(见 boundListviews / unreadableViews);可重发 nextCommand,若仍 303024 用 unbindCommand 逐视图手工处理。`
4138
+ : "") +
4021
4139
  `整体清理也可用 omc model-purge --code ${args.schemaCode}(级联带走流程模板与视图)。`,
4022
4140
  });
4023
4141
  }
@@ -4038,6 +4156,7 @@ export function registerWorkflowLane(tools) {
4038
4156
  listviewUnbind: {
4039
4157
  requested: true,
4040
4158
  unboundViews: steps.filter((step) => step.step === "listview.configure").map((step) => step.viewCode),
4159
+ note: "只移除了指向本流程的 add 绑定;平台读面不会自动补回。需要恢复新增按钮时用 listview.configure defaultActions:true 重建内置动作。",
4041
4160
  },
4042
4161
  }
4043
4162
  : {}),
@@ -4464,6 +4583,11 @@ export function registerWorkflowLane(tools) {
4464
4583
  * (F7 0.8.8). Bindings are only ever created on the `add` action by
4465
4584
  * workflow.publish → updateBizQueryAddAction (8.6.26
4466
4585
  * WorkflowTemplateController.java:791,818-846; 2.1.5 :695-711,741-761).
4586
+ *
4587
+ * 0.8.16 F8: `actions` carries the view's decoded action rows (the same
4588
+ * `query/get` response), so workflow.delete can remove ONLY the workflow-bound
4589
+ * `add` row and write the remaining set back — delete/import/export/editowner
4590
+ * and caller-authored actions survive the unbind.
4467
4591
  */
4468
4592
  async function scanListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4469
4593
  const bound = [];
@@ -4488,6 +4612,7 @@ export function registerWorkflowLane(tools) {
4488
4612
  const fieldCodes = (Array.isArray(model.queryColumns) ? model.queryColumns : [])
4489
4613
  .map((column) => String(column.propertyCode ?? ""))
4490
4614
  .filter(Boolean);
4615
+ const decodedActions = actions.map(decodeActionRow);
4491
4616
  for (const action of actions) {
4492
4617
  const association = action.associationType ?? action.queryActionRelativeType;
4493
4618
  const associationCode = String(action.associationCode ?? action.relativeCode ?? "");
@@ -4505,6 +4630,7 @@ export function registerWorkflowLane(tools) {
4505
4630
  actionCode: action.actionCode === undefined || action.actionCode === null ? null : String(action.actionCode),
4506
4631
  associationCode: associationCode || null,
4507
4632
  fieldCodes,
4633
+ actions: decodedActions,
4508
4634
  });
4509
4635
  }
4510
4636
  }
@@ -4520,6 +4646,40 @@ export function registerWorkflowLane(tools) {
4520
4646
  async function findListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4521
4647
  return (await scanListviewsBoundToWorkflow(session, schemaCode, workflowCode)).bound;
4522
4648
  }
4649
+ /**
4650
+ * F8(0.8.16): is this the workflow-bound `add` row? The platform only ever
4651
+ * binds the `add` action to a workflow (publish → updateBizQueryAddAction),
4652
+ * so that single row is what must go; every other action stays untouched.
4653
+ */
4654
+ const isWorkflowAddBinding = (action, workflowCode, schemaCode) => {
4655
+ if (String(action.actionCode ?? "") !== "add")
4656
+ return false;
4657
+ if (String(action.associationType ?? "").toUpperCase() !== "WORKFLOW")
4658
+ return false;
4659
+ const associationCode = String(action.associationCode ?? "");
4660
+ return associationCode === workflowCode || associationCode === schemaCode || associationCode === "";
4661
+ };
4662
+ /**
4663
+ * Build the configure `actions` payload that keeps every action except the
4664
+ * workflow-bound `add` row. Decoded read rows are converted back to the
4665
+ * configure arg shape (nulls dropped — optional zod fields reject null) and
4666
+ * renumbered, because query/update assigns `sortKey` by array position.
4667
+ */
4668
+ const actionsWithoutWorkflowBinding = (actions, workflowCode, schemaCode) => actions
4669
+ .filter((action) => !isWorkflowAddBinding(action, workflowCode, schemaCode))
4670
+ .map((action, index) => {
4671
+ const row = {
4672
+ actionCode: String(action.actionCode ?? ""),
4673
+ queryActionType: String(action.queryActionType ?? ""),
4674
+ sortKey: index + 1,
4675
+ };
4676
+ for (const key of ["name", "icon", "systemAction", "serviceCode", "serviceMethod", "customService", "associationCode", "associationType"]) {
4677
+ const value = action[key];
4678
+ if (value !== null && value !== undefined)
4679
+ row[key] = value;
4680
+ }
4681
+ return row;
4682
+ });
4523
4683
  // `list_permission` echoes the PERMISSION row id plus the unit's display name
4524
4684
  // and code — never the unitId (WorkflowTemplateController.getPermissionMap).
4525
4685
  // So identity for readback/removal is resolved from the unit's own face.
@@ -28,7 +28,7 @@ import { writeEnvelope } from "./cli-output.js";
28
28
  import { ENDPOINTS } from "./endpoints.js";
29
29
  import { wireCall, wireRows } from "./wire.js";
30
30
  import { readModelRecord } from "./model-record.js";
31
- import { inboundModelReferences, inboundReferenceRefusal, modelPurgeUnbindCommand } from "./lanes/model-references.js";
31
+ import { deletionOrderFromSteps, deletionStepLabel, inboundModelReferences, inboundReferenceRefusal, modelPurgeCommand, modelPurgeUnbindCommand } from "./lanes/model-references.js";
32
32
  import { resolveModelTreeNode } from "./lanes/model.js";
33
33
  import { SessionManager } from "./session-manager.js";
34
34
  import { ConfigStore, defaultPaths } from "./config-store.js";
@@ -49,6 +49,13 @@ export function unbindDeletionSteps(steps) {
49
49
  export function unbindPurgeCommand(schemaCode, options = {}) {
50
50
  return modelPurgeUnbindCommand(schemaCode, options);
51
51
  }
52
+ /**
53
+ * 0.8.16 F7: plain `--apply` — it still tears down self references
54
+ * automatically and only refuses on cross-model references.
55
+ */
56
+ export function purgeApplyCommand(schemaCode, options = {}) {
57
+ return modelPurgeCommand(schemaCode, options);
58
+ }
52
59
  async function sessionFor(environment) {
53
60
  const store = new ConfigStore(defaultPaths());
54
61
  const sessions = new SessionManager(store);
@@ -64,18 +71,7 @@ async function sessionFor(environment) {
64
71
  * `deletionSteps` keeps the order and never repeats an entry.
65
72
  */
66
73
  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;
74
+ return deletionOrderFromSteps(steps);
79
75
  }
80
76
  /**
81
77
  * Read-only discovery: everything the purge would remove, in dependency order.
@@ -199,35 +195,59 @@ export async function planPurge(options, injected) {
199
195
  if (references.length > 0) {
200
196
  const refusal = inboundReferenceRefusal(options.schemaCode, references);
201
197
  const unbindEnabled = options.unbindReferences === true;
202
- const unbindSteps = unbindDeletionSteps(refusal.deletionSteps);
203
- const nextCommand = unbindPurgeCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances });
198
+ const allUnbindSteps = unbindDeletionSteps(refusal.deletionSteps);
199
+ const allLabels = allUnbindSteps.map(deletionStepLabel);
200
+ // 0.8.16 F7: split the unlink plan by reference kind. A self reference
201
+ // (the target's own child-table column resolves back to it) is internal
202
+ // to the model being deleted — purge tears it down automatically. A
203
+ // cross-model reference belongs to another model and still needs the
204
+ // explicit destructive flag. Self owners are always the target itself,
205
+ // so the two label sets are disjoint; filtering the full ordered list
206
+ // keeps the execution order the refusal already established.
207
+ const selfLabelSet = new Set(unbindDeletionSteps(inboundReferenceRefusal(options.schemaCode, references.filter((reference) => reference.selfReference)).deletionSteps).map(deletionStepLabel));
208
+ const crossLabelSet = new Set(unbindDeletionSteps(inboundReferenceRefusal(options.schemaCode, references.filter((reference) => !reference.selfReference)).deletionSteps).map(deletionStepLabel));
209
+ const selfLabels = allLabels.filter((label) => selfLabelSet.has(label));
210
+ const crossLabels = allLabels.filter((label) => crossLabelSet.has(label));
211
+ const nextCommand = crossLabels.length > 0
212
+ ? unbindPurgeCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances })
213
+ : purgeApplyCommand(options.schemaCode, { purgeInstances: instanceCount > 0 && !options.purgeInstances });
204
214
  referencePreview = {
205
215
  inboundReferences: references,
206
216
  deletionSteps: refusal.deletionSteps,
207
217
  deletionOrder: purgeDeletionOrder(refusal.deletionSteps),
208
218
  nextCommand,
219
+ // Self-reference steps are always part of the executable plan; the
220
+ // cross-model subset is the only thing the flag gates.
221
+ ...(selfLabels.length > 0 ? { selfUnbindSteps: selfLabels } : {}),
222
+ ...(crossLabels.length > 0 ? { crossModelUnbindSteps: crossLabels } : {}),
209
223
  // F4(0.8.12,探针 G):dry-run 是「看完整计划」的面,不是执行面。
210
224
  // 入站引用(含自建子表关联列)是删模型必然要拆的内部列,dry-run 直接
211
- // 预置 unbindSteps 并说明 apply 要加的 flag,而不是逼调用方先加破坏性
212
- // 开关才能看到计划。--apply 未带 flag 的行为不变(model.delete 零写入
213
- // 拒绝,引导见 dry-run 的 note)。
225
+ // 预置 unbindSteps;0.8.16 F7 起 wouldRequireFlags 只在真有跨模型引用
226
+ // 时出现(自引用 apply 自动拆,不需要 flag)。
214
227
  ...(unbindEnabled
215
- ? { unbindReferences: true, unbindSteps: purgeDeletionOrder(unbindSteps) }
228
+ ? { unbindReferences: true, unbindSteps: allLabels }
216
229
  : options.apply
217
230
  ? {}
218
- : { unbindSteps: purgeDeletionOrder(unbindSteps), wouldRequireFlags: ["--unbind-references"] }),
231
+ : { unbindSteps: allLabels, ...(crossLabels.length > 0 ? { wouldRequireFlags: ["--unbind-references"] } : {}) }),
219
232
  referenceNotice: `${options.schemaCode} 有入站引用(${refusal.referencingModels.map((model) => model.schemaCode).join("、")};` +
220
233
  `子表列经 parentCode 解析回本模型时属于自引用)。` +
221
234
  (unbindEnabled
222
- ? `已开启 --unbind-references:本命令会先按 deletionSteps 执行拆引用(${unbindSteps.map((step) => step.tool).join(" → ")};` +
235
+ ? `已开启 --unbind-references:本命令会先按 deletionSteps 执行拆引用(${allLabels.join(" → ")};` +
223
236
  `**破坏性:会删除引用列/子表关联列,列数据不可恢复**),全部成功后再让 model.delete 级联;任一步失败即停,不会删模型。`
224
- : `--apply 未带 --unbind-references 时 model.delete 会零写入拒绝;unbindSteps 是本命令会执行的拆引用步骤(` +
225
- `${unbindSteps.map((step) => step.tool).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**),` +
226
- `nextCommand 就是带上 --unbind-references 的同一条命令;也可以自己按 deletionSteps 逐条执行。`),
237
+ : `${selfLabels.length > 0 && crossLabels.length > 0
238
+ ? `检测到自引用 + 跨模型引用:--apply 不带 flag 时**不会自动拆任何引用**(避免半拆,列数据不可恢复),model.delete 会零写入拒绝;nextCommand 带 --unbind-references 一次处理。`
239
+ : selfLabels.length > 0
240
+ ? `--apply 会自动拆自引用列(${selfLabels.join(" → ")};**破坏性:删除列数据不可恢复**),无需 --unbind-references;跨模型引用:无。`
241
+ : `--apply 不会自动拆(只有跨模型引用:${crossLabels.join(" → ")});model.delete 会零写入拒绝,nextCommand 带 --unbind-references。`}` +
242
+ `也可以自己按 deletionSteps 逐条执行。`),
227
243
  };
228
244
  steps.push(unbindEnabled
229
- ? `🔧 拆引用(--unbind-references):${unbindSteps.map((step) => step.command).join(" → ")} → 再删模型`
230
- : `🔗 入站引用(apply 前先拆;--unbind-references 一条命令,或按 deletionSteps 首步 ${refusal.deletionSteps[0]?.command ?? ""})→ 再删模型`);
245
+ ? `🔧 拆引用(--unbind-references):${allUnbindSteps.map((step) => step.command).join(" → ")} → 再删模型`
246
+ : selfLabels.length > 0 && crossLabels.length > 0
247
+ ? `🔗 入站引用(自引用 + 跨模型引用:不带 flag 不自动拆,避免半拆;需 --unbind-references)→ 再删模型`
248
+ : selfLabels.length > 0
249
+ ? `🔗 入站引用(自引用自动拆:${selfLabels.join(" → ")})→ 再删模型`
250
+ : `🔗 入站引用(跨模型引用需 --unbind-references:${crossLabels.join(" → ")})→ 再删模型`);
231
251
  }
232
252
  }
233
253
  catch {
@@ -336,7 +356,7 @@ export async function cmdModelPurge(args, injected) {
336
356
  "用法:omc model-purge --code <模型code> [--purge-instances] [--unbind-references] [--env <环境>] [--apply]",
337
357
  " 一条命令按依赖倒序清掉:列表视图 → 自建业务规则 → 流程实例 → 流程 → 模型(字段/表单/计算规则/预置规则随模型级联)。",
338
358
  " 默认 dry-run(只列计划,不写;入站引用的 unbindSteps 已在 dry-run 预置)。--purge-instances 才删流程实例(workflow.delete 遇到实例会 402508)。",
339
- " --unbind-references 才会先按 deletionSteps 拆入站引用(field.delete 引用列 + field.publish 所属模型,**破坏性:列数据不可恢复**),再删模型;不带它 --apply 不会自动拆引用。",
359
+ " --unbind-references 才会拆**跨模型**入站引用(引用方模型的关联列;field.delete + field.publish,**破坏性:列数据不可恢复**);自引用列属于被删模型自身,--apply 会自动拆(仅当没有跨模型引用时;混合引用需该 flag 一次处理,避免半拆)。",
340
360
  " 每步回读确认;某步失败即停并说明已完成到哪一步(幂等,可修好后重跑)。",
341
361
  ].join("\n");
342
362
  const invalid = (message) => {
@@ -375,9 +395,11 @@ export async function cmdModelPurge(args, injected) {
375
395
  (referenced
376
396
  ? unbindEnabled
377
397
  ? `已开启 --unbind-references:--apply 会先执行 unbindSteps(${(plan.unbindSteps ?? []).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**),再把 model.delete 交给主流程级联。`
378
- : `入站引用已预扫(与 model.delete 同一份 gate):--apply 未带 --unbind-references 时 model.delete 会零写入拒绝。` +
379
- `unbindSteps 是本命令会执行的拆引用步骤(${(plan.unbindSteps ?? []).join(" → ")};**破坏性:会删除引用列/子表关联列,列数据不可恢复**);` +
380
- `nextCommand 是同一条命令加上 ${(plan.wouldRequireFlags ?? ["--unbind-references"]).join(" ")} --apply,也可以自己按 deletionSteps 逐条拆。`
398
+ : (plan.selfUnbindSteps?.length ?? 0) > 0 && (plan.crossModelUnbindSteps?.length ?? 0) > 0
399
+ ? `检测到自引用 + 跨模型引用:--apply 不带 flag 时**不会自动拆任何引用**(避免半拆,列数据不可恢复),model.delete 会零写入拒绝;nextCommand 带 --unbind-references 一次处理。`
400
+ : (plan.selfUnbindSteps?.length ?? 0) > 0
401
+ ? `0.8.16 F7:--apply 会**自动**拆自引用列(${(plan.selfUnbindSteps ?? []).join(" → ")};**破坏性:删除列数据不可恢复**),无需 --unbind-references;跨模型引用:无。`
402
+ : `--apply 不会自动拆(只有跨模型引用:${(plan.crossModelUnbindSteps ?? []).join(" → ")});model.delete 会零写入拒绝,nextCommand 带 --unbind-references。`
381
403
  : ""),
382
404
  }),
383
405
  }, request));
@@ -417,9 +439,7 @@ export async function executeUnbindSteps(call, steps) {
417
439
  const executed = [];
418
440
  for (let index = 0; index < candidates.length; index += 1) {
419
441
  const step = candidates[index];
420
- const label = step.tool === "field.delete"
421
- ? `field.delete:${String(step.args.schemaCode ?? "")}.${String(step.args.code ?? "")}`
422
- : `field.publish:${String(step.args.schemaCode ?? "")}`;
442
+ const label = deletionStepLabel(step);
423
443
  const schemaCode = step.args.schemaCode;
424
444
  const code = step.args.code;
425
445
  const shapeValid = typeof schemaCode === "string" &&
@@ -493,16 +513,27 @@ export async function executePurge(plan, session, call) {
493
513
  steps.push(...instanceOutcome.steps);
494
514
  let failed = instanceOutcome.failed;
495
515
  const unremovableInstances = instanceOutcome.unremovableInstances;
496
- // F7(0.8.9,探针 D):`--unbind-references` 才执行拆引用。只跑
516
+ // F7(0.8.9,探针 D)+ 0.8.16 F7:`--unbind-references` 执行全部拆引用;
517
+ // 不带 flag 时只自动执行 `selfReference` 那部分(模型自身的子表列指回自身,
518
+ // 删模型必然带走它)。**自引用与跨模型引用同时存在时 fail-closed**:不自动
519
+ // 拆任何引用——先删自引用列再被 model.delete 拒绝就是「半拆」,而列数据不可
520
+ // 恢复。混合引用必须由用户带 --unbind-references 一次处理。只跑
497
521
  // deletionSteps 里的 field.delete/field.publish(model.delete 仍由本命令的
498
522
  // 主流程负责,绝不重复)。任一步失败即停,模型不删。
499
523
  let unbindOutcome;
500
- if (!failed && plan.unbindReferences === true && (plan.deletionSteps?.length ?? 0) > 0) {
524
+ let autoUnbindSelfReferences = false;
525
+ const selfLabels = new Set(plan.selfUnbindSteps ?? []);
526
+ const mixedReferencesWithoutFlag = plan.unbindReferences !== true && selfLabels.size > 0 && (plan.crossModelUnbindSteps?.length ?? 0) > 0;
527
+ if (!failed && !mixedReferencesWithoutFlag && (plan.deletionSteps?.length ?? 0) > 0) {
501
528
  const candidates = plan.deletionSteps ?? [];
502
- unbindOutcome = await executeUnbindSteps(call, candidates);
503
- steps.push(...unbindOutcome.steps);
504
- if (unbindOutcome.failed)
505
- failed = true;
529
+ const thatNeedRunning = plan.unbindReferences === true ? candidates : candidates.filter((step) => selfLabels.has(deletionStepLabel(step)));
530
+ if (thatNeedRunning.length > 0) {
531
+ autoUnbindSelfReferences = plan.unbindReferences !== true;
532
+ unbindOutcome = await executeUnbindSteps(call, thatNeedRunning);
533
+ steps.push(...unbindOutcome.steps);
534
+ if (unbindOutcome.failed)
535
+ failed = true;
536
+ }
506
537
  }
507
538
  // 2) the model — everything else cascades with it.
508
539
  let referrers = [];
@@ -531,18 +562,23 @@ export async function executePurge(plan, session, call) {
531
562
  }
532
563
  }
533
564
  const status = failed ? "partial" : "ok";
534
- const rerunCommand = unbindPurgeCommand(schemaCode);
565
+ const mixedReferencesAtRefusal = plan.unbindReferences !== true && selfLabels.size > 0 && (plan.crossModelUnbindSteps?.length ?? 0) > 0;
566
+ const refusalHasCrossModel = (plan.crossModelUnbindSteps?.length ?? 0) > 0 ||
567
+ (deleteRefusal?.inboundReferences ?? []).some((reference) => reference.selfReference !== true);
568
+ // Self-only refs are auto-unbound by a plain `--apply`, so pointing the retry
569
+ // at the destructive flag would be a lie.
570
+ const rerunCommand = refusalHasCrossModel ? unbindPurgeCommand(schemaCode) : purgeApplyCommand(schemaCode);
535
571
  // Pass the inner refusal through verbatim; the purge-level receipt must not
536
572
  // promise keys it dropped (F9: message named deletionSteps that were absent).
537
573
  const failureFields = unbindOutcome?.failed === true
538
574
  ? {
539
575
  nextAction: "fix-and-rerun",
540
- unbindReferences: true,
576
+ ...(plan.unbindReferences === true ? { unbindReferences: true } : { autoUnbindSelfReferences: true }),
541
577
  failedStep: unbindOutcome.failedStep,
542
578
  remainingSteps: unbindOutcome.remaining,
543
579
  modelDeletePending: true,
544
580
  nextCommand: rerunCommand,
545
- message: `${schemaCode} 未删除:拆引用在 ${unbindOutcome.failedStep ?? "某一步"} 失败,已停在该步;` +
581
+ message: `${schemaCode} 未删除:${autoUnbindSelfReferences ? "自动拆自引用" : "拆引用"}在 ${unbindOutcome.failedStep ?? "某一步"} 失败,已停在该步;` +
546
582
  `**未调用 model.delete,模型仍存在**。原因:${unbindOutcome.failureMessage ?? "平台拒绝"}。` +
547
583
  `已成功的拆引用步骤不回滚(幂等,重跑不会重复破坏);修复后重跑本命令(nextCommand)继续。`,
548
584
  }
@@ -554,9 +590,13 @@ export async function executePurge(plan, session, call) {
554
590
  deletionOrder: purgeDeletionOrder(deleteRefusal.deletionSteps),
555
591
  nextCommand: rerunCommand,
556
592
  ...(referrers.length > 0 ? { blockedBy: referrers } : {}),
557
- message: `${schemaCode} 未删除(零写入拒绝,未启动平台删除任务)。${deleteRefusal.message} ` +
558
- `两条路:① 一条命令自动拆引用:nextCommand(--unbind-references;**破坏性:会删除指向本模型的引用列/子表关联列,列数据不可恢复**),` +
559
- `拆完引用后由 model.delete 级联;② 自己按 deletionSteps 逐条执行。不要在未拆引用时重试 --apply(不带 --unbind-references 仍会零写入拒绝)。`,
593
+ message: (mixedReferencesAtRefusal
594
+ ? `${schemaCode} 未删除:检测到自引用 + 跨模型引用。为避免半拆,本次零写入(未删除任何列、未发布模型、未启动平台删除任务)。按 deletionSteps 逐条执行,或 nextCommand(带 --unbind-references)一次处理。 `
595
+ : `${schemaCode} 未删除(零写入拒绝,未启动平台删除任务)。`) +
596
+ `${deleteRefusal.message} ` +
597
+ `两条路:① 一条命令自动拆引用:nextCommand(${refusalHasCrossModel ? "--unbind-references;" : ""}**破坏性:会删除指向本模型的引用列/子表关联列,列数据不可恢复**),` +
598
+ `拆完引用后由 model.delete 级联;② 自己按 deletionSteps 逐条执行。` +
599
+ (refusalHasCrossModel ? "不要在未拆引用时重试 --apply(不带 --unbind-references 仍会零写入拒绝)。" : ""),
560
600
  }
561
601
  : {
562
602
  nextAction: "fix-and-rerun",
@@ -571,7 +611,11 @@ export async function executePurge(plan, session, call) {
571
611
  schemaCode,
572
612
  verdict: plan.modelExists && !failed ? "cascading" : "clean",
573
613
  ...(plan.workflowCode !== undefined ? { workflowCode: plan.workflowCode } : {}),
574
- ...(plan.unbindReferences === true ? { unbindReferences: true } : {}),
614
+ ...(plan.unbindReferences === true
615
+ ? { unbindReferences: true }
616
+ : autoUnbindSelfReferences
617
+ ? { autoUnbindSelfReferences: true }
618
+ : {}),
575
619
  ...(unbindOutcome !== undefined ? { unboundSteps: unbindOutcome.executed, unbindFailed: unbindOutcome.failed } : {}),
576
620
  deletedInstances: steps.filter((step) => step.step.startsWith("workflow.delete_instance:") && step.status === "ok").length,
577
621
  ...(unremovableInstances.length > 0 ? { unremovableInstances } : {}),