@stalfh233/omc-cli 0.6.86 → 0.6.88

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.
@@ -11,6 +11,7 @@ import { makeToolContext } from "../context.js";
11
11
  import { SessionManager } from "../session-manager.js";
12
12
  import { ConfigStore, defaultPaths } from "../config-store.js";
13
13
  import { buildToolRegistry } from "../tools.js";
14
+ import { executeChangesBatch } from "../lanes/apply-changes.js";
14
15
  import { acquireWriteLock } from "../write-lock.js";
15
16
  import { wireCall, WireError } from "../wire.js";
16
17
  import { ENDPOINTS } from "../endpoints.js";
@@ -213,7 +214,12 @@ export async function planIntent(intent, environment, planOut) {
213
214
  });
214
215
  const planJson = JSON.stringify(plan, null, 2) + "\n";
215
216
  const artifact = createArtifact(artifactRoot(), planJson);
216
- const warnings = intentWarnings(intent);
217
+ // Plan-time warnings authored by the capabilities (e.g. a referenced method
218
+ // delete) join the assembler's own lint warnings on the decision face.
219
+ const warnings = [
220
+ ...(compiled.warnings ?? []).map((warning) => ({ resource: warning.resource, code: warning.code ?? "plan-warning", message: warning.message })),
221
+ ...intentWarnings(intent),
222
+ ];
217
223
  // r39: a destructive plan that deletes a model carrying runtime data got
218
224
  // ZERO warning — the approval object must surface the blast radius. One
219
225
  // cheap total-only query per declared-absent model (never blocks the plan:
@@ -455,6 +461,7 @@ export async function applyIntent(planPath, options, ports) {
455
461
  changes: plan.changes,
456
462
  skippedCount: plan.skipped.length,
457
463
  riskClass: plan.riskClass,
464
+ ...(plan.warnings !== undefined ? { warnings: plan.warnings } : {}),
458
465
  preview: [...toolCounts.entries()].map(([tool, count]) => (count > 1 ? `${tool}×${count}` : tool)).join("、") || "无变更",
459
466
  });
460
467
  }
@@ -516,7 +523,13 @@ export async function applyIntent(planPath, options, ports) {
516
523
  // stages — fields/views drop first, the model shell lags a moment. An
517
524
  // immediate readback then reports a phantom mismatch. Retry the live
518
525
  // verification briefly (bounded) before declaring failure.
519
- const declaresAbsence = plan.intent.models.some((model) => model.absent === true);
526
+ const declaresAbsence = plan.intent.models.some((model) => model.absent === true)
527
+ // T3: service/method deletion propagates the same way (service delete
528
+ // cascades methods, BizServiceServiceImpl.java:259-273).
529
+ || (plan.intent.services ?? []).some((service) => service.absent === true || service.method?.absent === true || (service.methods ?? []).some((method) => method.absent === true));
530
+ const absenceNote = plan.intent.models.some((model) => model.absent === true)
531
+ ? "本变更含 absent:true 删除:平台删除分阶段传播(字段/视图先撤、模型壳后撤),已做 3 次间隔读回仍不等价——先用 model.inspect 的 modelPresent 独立复核再判定;若 modelPresent:false 则删除实际已生效"
532
+ : "本变更含服务/方法 absent:true 删除:删除按平台自身的传播节奏生效(服务删除会级联方法),已做 3 次间隔读回仍不等价——先 service.get(服务面 + 方法列表)独立复核对账;服务已 500001 即删除实际已生效";
520
533
  const attempt = await verifyWithRetry(async () => {
521
534
  try {
522
535
  const report = await verifyIntentLive(session, plan.intent);
@@ -539,7 +552,7 @@ export async function applyIntent(planPath, options, ports) {
539
552
  verification,
540
553
  ...(declaresAbsence
541
554
  ? {
542
- note: "本变更含 absent:true 删除:平台删除分阶段传播(字段/视图先撤、模型壳后撤),已做 3 次间隔读回仍不等价——先用 model.inspect 的 modelPresent 独立复核再判定;若 modelPresent:false 则删除实际已生效",
555
+ note: absenceNote,
543
556
  }
544
557
  : {}),
545
558
  message: "变更已执行,但最终权威读回与意图不等价:交付可能不完整或环境已漂移。按 differences 定位后重新 intent plan(不要盲重试)",
@@ -565,12 +578,16 @@ export async function applyIntent(planPath, options, ports) {
565
578
  // 审计行时读取),不是工具入参、不进 schema。逐步写本身不产生 journal 行
566
579
  // (无 before 快照),所以审计只到「谁用哪份意图、为什么」这一层。
567
580
  const auditContext = options.reason === undefined ? context : { ...context, writeAudit: { reason: options.reason } };
568
- result = (await applyChanges.handler(auditContext, parseToolInput(applyChanges, {
581
+ // B1:执行段直接进入共享批管线(executeChangesBatch → 共享 governed batch
582
+ // executor);intent 自己的门(写锁 / plan 完整性 / baseline drift / 最终
583
+ // 读回 / --no-verify)全部留在本层。回执字段与经 apply_changes.handler
584
+ // 调用时逐字一致(同一个 plan/审批/逐步读回投影)。
585
+ result = (await executeChangesBatch(auditContext, parseToolInput(applyChanges, {
569
586
  changes,
570
587
  environment: plan.environment,
571
588
  summary,
572
589
  ...(options.confirmProduction === true ? { confirmProduction: true } : {}),
573
- }), applyChanges));
590
+ }), registry));
574
591
  }
575
592
  catch (error) {
576
593
  if (error instanceof ToolInputError)
@@ -30,6 +30,7 @@ export function buildPlan(input) {
30
30
  intentHash: intentHashOf(input.intent),
31
31
  changes: input.compiled.changes,
32
32
  skipped: input.compiled.skipped,
33
+ ...(input.compiled.warnings !== undefined && input.compiled.warnings.length > 0 ? { warnings: input.compiled.warnings } : {}),
33
34
  riskClass: input.compiled.riskClass,
34
35
  expectedReadback: input.compiled.expectedReadback,
35
36
  cleanup: input.compiled.cleanup,
@@ -6,6 +6,83 @@ const newFrontend = () => ({ formBoundFieldCodes: [], listviewPresent: false, li
6
6
  function absentLiveModel(code) {
7
7
  return { code, name: null, present: false, fields: [], form: absentForm, frontend: newFrontend() };
8
8
  }
9
+ /**
10
+ * A7 — every difference carries an actionable next step. These defaults are
11
+ * derived from the difference kind alone (which capability/tool owns the
12
+ * repair, and whether re-planning is enough). A capability may override any of
13
+ * them with exact detail (bizservice fills sourcePath + the concrete repair).
14
+ */
15
+ const REPLAN_COMMAND = "omc intent plan <intent.yaml> --env <env>";
16
+ const replan = (tool) => ({ tool, next: { kind: "replan", command: REPLAN_COMMAND }, safeToReplan: true });
17
+ const declareAbsent = (tool) => ({ tool, next: { kind: "edit-intent" }, safeToReplan: true });
18
+ const escape = (tool, command) => ({ tool, next: { kind: "call", ...(command !== undefined ? { command } : {}) }, escapeHatch: true, safeToReplan: false });
19
+ const DIFFERENCE_DEFAULTS = {
20
+ "model-missing": replan("model.create"),
21
+ "model-name-mismatch": replan("model.update"),
22
+ "field-missing": replan("field.create"),
23
+ "field-name-mismatch": replan("field.update"),
24
+ // A field's wire family is immutable: delete+recreate is the only repair.
25
+ "field-type-mismatch": escape("field.delete"),
26
+ "field-options-mismatch": replan("field.update"),
27
+ "field-option-unwritable": escape("field.update"),
28
+ "field-not-published": replan("field.publish"),
29
+ "form-missing": replan("form.draft"),
30
+ "form-not-published": replan("form.publish"),
31
+ "form-not-bound": replan("form.draft"),
32
+ "listview-missing": replan("listview.create"),
33
+ "listview-columns-missing": replan("listview.configure"),
34
+ "listview-system-columns-unexpected": escape("listview.configure"),
35
+ "child-field-missing": replan("field.update"),
36
+ "child-field-type-mismatch": escape("field.update"),
37
+ "child-field-name-mismatch": replan("field.update"),
38
+ "rule-missing": replan("rule.save"),
39
+ "rule-not-enabled": replan("rule.enable"),
40
+ "rule-enabled-unexpected": escape("rule.save"),
41
+ "rule-graph-mismatch": replan("rule.save"),
42
+ "workflow-missing": replan("workflow.create"),
43
+ "workflow-template-mismatch": replan("workflow.update"),
44
+ "workflow-not-published": replan("workflow.publish"),
45
+ "workflow-rule-not-bound": replan("workflow.bindRule"),
46
+ "onlinejs-missing": replan("onlinejs.compose"),
47
+ "onlinejs-source-mismatch": replan("onlinejs.compose"),
48
+ "onlinejs-not-published": replan("onlinejs.compose"),
49
+ "service-missing": replan("service.register"),
50
+ "service-mismatch": replan("service.update"),
51
+ "method-missing": replan("method.create"),
52
+ "method-mismatch": replan("method.update"),
53
+ "report-missing": replan("report.create"),
54
+ "report-mismatch": replan("report.configure"),
55
+ "report-dashboard-missing": replan("report.configure"),
56
+ "report-charts-mismatch": replan("report.configure"),
57
+ "report-charts-unexpected": replan("report.configure"),
58
+ "datarule-missing": replan("datarule.create"),
59
+ "datarule-mismatch": replan("datarule.create"),
60
+ "model-present-unexpected": declareAbsent("model.delete"),
61
+ "field-present-unexpected": declareAbsent("field.delete"),
62
+ "listview-present-unexpected": declareAbsent("listview.delete"),
63
+ "datarule-present-unexpected": escape("datarule.delete"),
64
+ "service-present-unexpected": declareAbsent("service.delete"),
65
+ "method-present-unexpected": declareAbsent("method.delete"),
66
+ };
67
+ /** Merge a capability's explicit detail over the kind defaults (A7). */
68
+ function differenceOf(kind, resource, message, detail) {
69
+ const fallback = DIFFERENCE_DEFAULTS[kind];
70
+ const sourceTool = detail?.sourceTool ?? fallback.tool;
71
+ const sourcePath = detail?.sourcePath;
72
+ const next = detail?.next ?? fallback.next;
73
+ const escapeHatch = detail?.escapeHatch ?? fallback.escapeHatch;
74
+ const safeToReplan = detail?.safeToReplan ?? fallback.safeToReplan;
75
+ return {
76
+ kind,
77
+ resource,
78
+ message,
79
+ ...(sourceTool !== undefined ? { sourceTool } : {}),
80
+ ...(sourcePath !== undefined ? { sourcePath } : {}),
81
+ ...(next !== undefined ? { next } : {}),
82
+ ...(escapeHatch !== undefined ? { escapeHatch } : {}),
83
+ ...(safeToReplan !== undefined ? { safeToReplan } : {}),
84
+ };
85
+ }
9
86
  /**
10
87
  * Decode a baseline into the intent shape (wire ints -> family names). The
11
88
  * optional `intent` lets a declared-absent model run ONLY the model capability,
@@ -41,7 +118,7 @@ export function compareWithLive(intent, live) {
41
118
  const differences = [];
42
119
  const ignored = [];
43
120
  const emit = {
44
- difference: (kind, resource, message) => differences.push({ kind, resource, message }),
121
+ difference: (kind, resource, message, detail) => differences.push(differenceOf(kind, resource, message, detail)),
45
122
  ignored: (resource) => ignored.push(resource),
46
123
  };
47
124
  const capabilities = orderedCapabilities();
@@ -164,7 +164,7 @@ export function intentSchemaBlock() {
164
164
  conditionOperators: INTENT_CONDITION_OPERATORS,
165
165
  workflow: { required: ["code", "name", "publish"], optional: ["template", "bindRules"], note: "bindRules [{handler: start|cancel|activate|end, ruleCodes:[...]}];流程事件只绑自定义规则" },
166
166
  onlinejs: { required: ["source", "publish"], optional: ["sheetCode", "replace"], note: "replace:true 覆盖;merge 时 source 只给生命周期片段,不能是完整 (function(form){...})" },
167
- services: { required: ["code", "name", "adapterCode", "serviceCategoryId", "serviceConfig"], optional: ["method", "methods"], note: "method 与 methods 互斥:method 是单方法(name==code,随 service.register);methods[] 是多方法/给既有服务加方法(name 可不同于 code,缺失 plan method.create、漂移 plan method.update)。自定义/INTERNAL 适配器走二开扩展包导入,不在声明式写面" },
167
+ services: { required: ["code(present 服务还需要 name/adapterCode/serviceCategoryId/serviceConfig;absent:true 的服务只认 code)"], optional: ["name", "adapterCode", "serviceCategoryId", "serviceConfig", "absent", "method", "methods"], absent: "services[].absent:true 删除整个服务(平台级联删方法,riskClass=destructive);服务仍被规则映射引用时 plan 硬拒(intent-service-referenced,平台自己不拦)——先解绑引用规则并 apply,再删服务。服务保留时 methods[].absent:true 删单方法(平台被引用时回 500108)", note: "method 与 methods 互斥:method 是单方法(name==code,随 service.register);methods[] 是多方法/给既有服务加方法(name 可不同于 code,缺失 plan method.create、漂移 plan method.update)。absent:true 只认 code,带 name/config/method(s) 等 shape 键即拒。自定义/INTERNAL 适配器走二开扩展包导入,不在声明式写面" },
168
168
  examples: RUNNABLE_EXAMPLES.map((example) => ({ id: example.id, title: example.title })),
169
169
  exampleHint: "取可运行 YAML:omc describe intent --example <id>",
170
170
  versionNotice: "intent 只覆盖声明式子集(capabilities 的 intent: partial);未覆盖面用 omc call 补齐。",
@@ -1,35 +1,12 @@
1
1
  import { z } from "zod";
2
- import { randomUUID } from "node:crypto";
3
- import { basename } from "node:path";
4
2
  import { confirmProductionArg, environmentArg, WRITE_PROTOCOL } from "../args.js";
5
3
  import { executePackage } from "../package.js";
6
4
  import { plannableArgs } from "../plan.js";
7
- import { isUncertainWireError, wireErrorKind, writeArtifact } from "../support.js";
8
5
  import { defineTool, parseToolInput, ToolInputError, ToolRefusalError } from "../tool-types.js";
9
- import { appendJournalEntry } from "../journal.js";
10
- import { journalAudit } from "../write-audit.js";
11
- import { WireError } from "../wire.js";
12
- /**
13
- * Ticket 58: the batch time budget. `startedAt` is the execution start (ms
14
- * epoch); `budgetMs` undefined means no budget. Exported so the arithmetic is
15
- * pinned by a unit test instead of a timing-sensitive S1 test.
16
- */
17
- export function batchBudgetExceeded(startedAt, budgetMs, now) {
18
- if (budgetMs === undefined)
19
- return false;
20
- return now - startedAt >= budgetMs;
21
- }
22
- /**
23
- * The default whole-batch time budget (8 minutes), applied when the caller
24
- * omits `totalTimeoutMs`. It MUST stay safely below the CLI's own call timeout:
25
- * the omc CLI caps `--timeout-ms` at 600000 ms (10 min), and the 2026-09-14
26
- * `eq_repair_record` incident was exactly the failure mode of a batch that
27
- * outlives its caller — the caller abandoned at its timeout while the batch
28
- * kept executing, and the agent's retry became a second writer in the same
29
- * environment. Stopping at a bounded budget returns a clean `uncertain` +
30
- * progressFile + resumeFromIndex while the caller is still listening.
31
- */
32
- export const DEFAULT_BATCH_BUDGET_MS = 8 * 60 * 1000;
6
+ import { appendBatchAuditLine, executeGovernedBatch } from "../batch-executor.js";
7
+ // Ticket 58 的预算算术/缺省值自 B1 起住在共享执行器里;此处 re-export 保持
8
+ // 既有测试导入路径(apply-changes-progress.test)不变。
9
+ export { batchBudgetExceeded, DEFAULT_BATCH_BUDGET_MS } from "../batch-executor.js";
33
10
  function refuseBatch(blocker, message, extra = {}) {
34
11
  return { status: "refused", blocker, message, ...extra };
35
12
  }
@@ -59,240 +36,145 @@ export function registerApplyChangesLane(tools) {
59
36
  // lint 尚未在批量预览里执行——如实声明,不能读成「整批可执行」。
60
37
  lintScope: "partial",
61
38
  lintUnchecked: ["batch-step-session-lint", "local-write-gates", "platform-side-validation", "post-write-readback"],
62
- handler: async (ctx, args) => {
63
- const changes = args.changes;
64
- // ---- 1. Structural validation (zero wire calls) --------------------
65
- if (!Array.isArray(changes) || changes.length === 0)
66
- return refuseBatch("apply-changes-invalid", "changes 必须是非空数组(每项 { tool, args })");
67
- const targets = new Map();
68
- const normalizedChanges = [];
69
- for (const change of changes) {
70
- if (!(change.tool && typeof change.tool === "string"))
71
- return refuseBatch("apply-changes-invalid", "changes 每项必须包含 tool");
72
- if (!targets.has(change.tool)) {
73
- const target = siblings.find((tool) => tool.name === change.tool);
74
- if (!target)
75
- return refuseBatch("apply-changes-unknown-tool", `changes 引用了不存在的工具 ${change.tool}`, { tool: change.tool });
76
- if (target.kind !== "write")
77
- return refuseBatch("apply-changes-tool-not-writable", `${change.tool} 不是写工具(changes 只接受写操作)`, { tool: change.tool });
78
- if (target.layer !== "low" || !target.writeExecute)
79
- return refuseBatch("apply-changes-tool-not-atomic", `${change.tool} 是高层预设(已是单调用包);changes 只接受低层原子写工具`, { tool: change.tool });
80
- if (!target.lane || !target.scope)
81
- return refuseBatch("apply-changes-tool-not-atomic", `${change.tool} 缺少 lane/scope 声明,无法通过覆盖门`, { tool: change.tool });
82
- targets.set(change.tool, target);
83
- }
84
- try {
85
- normalizedChanges.push({ tool: change.tool, args: parseToolInput(targets.get(change.tool), change.args) });
86
- }
87
- catch (error) {
88
- if (error instanceof ToolInputError)
89
- return { ...error.payload, failedBeforeApproval: true, changeTool: change.tool };
90
- throw error;
91
- }
92
- }
93
- // ---- 2. Semantic gates BEFORE the write permission gate (dry) ------
94
- try {
95
- for (const change of normalizedChanges)
96
- targets.get(change.tool).writePreflight?.(change.args);
97
- }
98
- catch (error) {
99
- if (error instanceof ToolRefusalError)
100
- return { ...error.payload, failedBeforeApproval: true };
101
- throw error;
102
- }
103
- // ---- 3. One plan, one fingerprint, per-action coverage ------------
104
- const toolPhrase = (list) => {
105
- const counts = new Map();
106
- for (const change of list)
107
- counts.set(change.tool, (counts.get(change.tool) ?? 0) + 1);
108
- return [...counts.entries()].map(([tool, count]) => (count > 1 ? `${tool}×${count}` : tool)).join("、");
109
- };
110
- const plan = {
111
- environment: "",
112
- environmentFingerprint: "",
113
- summary: args.summary ?? `即将按序执行 ${normalizedChanges.length} 项变更(${toolPhrase(normalizedChanges)})`,
114
- actions: normalizedChanges.map((change) => ({ tool: change.tool, args: plannableArgs(change.tool, change.args) })),
115
- };
116
- const coverage = {
117
- perAction: normalizedChanges.map((change) => {
118
- const target = targets.get(change.tool);
119
- return { lane: target.lane, scope: target.scope };
120
- }),
121
- };
122
- const batchResult = await executePackage(ctx, plan, coverage, args, async (session) => {
123
- const steps = [];
124
- // Ticket 58: a recoverable handle for a long batch. Every step appends
125
- // to one progress artifact, so a client-side timeout or a killed
126
- // server still leaves the exact progress on disk.
127
- const runId = randomUUID().slice(0, 8);
128
- const startedAt = Date.now();
129
- const budgetMs = args.totalTimeoutMs ?? DEFAULT_BATCH_BUDGET_MS;
130
- const batchSummary = plan.summary;
131
- const recordProgress = (status, upTo) => writeArtifact(ctx, `batch-progress-${runId}.json`, {
132
- runId,
133
- summary: batchSummary,
134
- startedAt,
135
- budgetMs: budgetMs ?? null,
136
- steps,
137
- nextIndex: upTo,
138
- status,
139
- }).detailFile;
140
- for (let index = 0; index < normalizedChanges.length; index += 1) {
141
- const change = normalizedChanges[index];
142
- const target = targets.get(change.tool);
143
- if (batchBudgetExceeded(startedAt, budgetMs, Date.now())) {
144
- const progressFile = recordProgress("STOPPED", steps.length);
145
- const stop = {
146
- status: "uncertain",
147
- steps,
148
- failedStep: { index, tool: change.tool },
149
- envelope: {
150
- blocker: "batch-timeout-budget",
151
- frozen: true,
152
- budgetMs,
153
- message: `已达整批预算 ${budgetMs}ms,在第 ${index + 1} 步(${change.tool})前停止;已完成 ${steps.length} 项(其效果真实存在)。先读 progressFile 与只读发现确认进度,再决定是否续跑——绝不盲重试`,
154
- summary: `${args.summary ? `${args.summary};` : ""}批量达预算停止于第 ${index + 1} 步前,已完成 ${steps.length} 项`,
155
- progressFile,
156
- // Ticket 81: structured recovery semantics — a timeout is NOT
157
- // failure; the server may have completed everything.
158
- nextAction: {
159
- rule: "read-back-first",
160
- steps: [
161
- "读 progressFile:拿到已完成步骤清单(其效果真实存在于环境)",
162
- "用只读发现核对每一步的权威面(discover_environment / 对应 lane 的 list/get 读回;写工具的 already-present/already-published 短路可安全复用)",
163
- `仅对缺失步骤重新组包:从 failedStep.index=${index} 起,剔除读回确认已生效的项`,
164
- ],
165
- forbidden: "盲目整批重试——已完成步骤会重复执行或触发重复码拒绝(如 listview.create 303002)",
166
- resumeFromIndex: index,
167
- },
168
- },
169
- };
170
- return stop;
171
- }
172
- try {
173
- const outcome = await target.writeExecute(session, change.args);
174
- // A step-chain write (field.update cascadeRepublish) may RETURN a
175
- // mid-chain stop instead of throwing: surface it as this batch's
176
- // stop with the inner chain preserved for audit.
177
- if ("status" in outcome) {
178
- const progressFile = recordProgress("STOPPED", steps.length);
179
- const cascadeStop = {
180
- status: outcome.status,
181
- steps,
182
- failedStep: { index, tool: change.tool },
183
- envelope: { ...outcome.envelope, message: `${String(outcome.envelope.message ?? "步骤失败")}(第 ${index + 1} 步 ${change.tool} 的内部级联中途停止)`, progressFile },
184
- };
185
- return cascadeStop;
186
- }
187
- steps.push({ step: change.tool, index, status: "ok", performed: outcome.performed, readback: outcome.readback, ...(outcome.steps !== undefined ? { chainSteps: outcome.steps } : {}) });
188
- recordProgress("RUNNING", index + 1);
189
- }
190
- catch (error) {
191
- const failedStep = { index, tool: change.tool };
192
- if (isUncertainWireError(error)) {
193
- // Per-step transport/timeout: uncertain, frozen — never success.
194
- const progressFile = recordProgress("STOPPED", steps.length);
195
- const stop = {
196
- status: "uncertain",
197
- steps,
198
- failedStep,
199
- envelope: {
200
- frozen: true,
201
- reason: `wire-transport:${wireErrorKind(error)}`,
202
- detail: error.message,
203
- message: `第 ${index + 1} 步(${change.tool})传输中断,写入结果无法判定;已冻结——先重新发现再决定重试,绝不假定为成功`,
204
- summary: `${args.summary ? `${args.summary};` : ""}批量在第 ${index + 1} 步(${change.tool})中断,已完成 ${steps.length} 项,结果不确定`,
205
- progressFile,
206
- // Ticket 81: the interrupted step itself may have taken
207
- // effect server-side — read back before any retry.
208
- nextAction: {
209
- rule: "read-back-first",
210
- steps: [
211
- "读 progressFile:拿到已完成步骤清单(其效果真实存在于环境)",
212
- `先核对第 ${index + 1} 步(${change.tool})本身是否已生效——超时≠失败,服务端可能已写入`,
213
- "用只读发现核对每一步的权威面,仅对缺失步骤重新组包执行",
214
- ],
215
- forbidden: "盲目整批重试或假定中断步骤失败——重复执行会撞重复码(如 listview.create 303002)",
216
- resumeFromIndex: index,
217
- },
218
- },
219
- };
220
- return stop;
221
- }
222
- const envelope = error instanceof ToolRefusalError
223
- ? { ...error.payload }
224
- : error instanceof WireError
225
- ? { blocker: `wire-${error.kind}`, errcode: error.errcode, message: error.message }
226
- : { blocker: "apply-changes-step-failed", message: error.message };
227
- const progressFile = recordProgress("STOPPED", steps.length);
228
- const stop = {
229
- status: "refused",
230
- steps,
231
- failedStep,
232
- envelope: {
233
- ...envelope,
234
- message: `${typeof envelope.message === "string" ? envelope.message : "步骤失败"};批量在第 ${index + 1} 步(${change.tool})停止,后续步骤未执行;已完成步骤见 steps(其效果真实存在,需要善后时按 steps 清单处理)`,
235
- summary: `${args.summary ? `${args.summary};` : ""}批量在第 ${index + 1} 步(${change.tool})停止,已完成 ${steps.length} 项`,
236
- progressFile,
237
- },
238
- };
239
- return stop;
240
- }
241
- }
242
- const executedTools = [...new Set(normalizedChanges.map((change) => change.tool))];
243
- const progressFile = recordProgress("DONE", steps.length);
39
+ handler: async (ctx, args) => executeChangesBatch(ctx, args, siblings),
40
+ }));
41
+ }
42
+ /**
43
+ * B1:apply_changes 工具面与 `intent apply` 共享的批执行管线(intent 只保留
44
+ * 自己的门:plan 完整性、baseline drift、最终读回、写锁——见
45
+ * src/intent/plan-apply.ts)。`siblings` 是完整工具注册表(工具面传 tools
46
+ * 数组闭包;intent 传 buildToolRegistry(),同一注册表)。
47
+ */
48
+ export async function executeChangesBatch(ctx, args, siblings) {
49
+ const changes = args.changes;
50
+ // ---- 1. Structural validation (zero wire calls) --------------------
51
+ if (!Array.isArray(changes) || changes.length === 0)
52
+ return refuseBatch("apply-changes-invalid", "changes 必须是非空数组(每项 { tool, args })");
53
+ const targets = new Map();
54
+ const normalizedChanges = [];
55
+ for (const change of changes) {
56
+ if (!(change.tool && typeof change.tool === "string"))
57
+ return refuseBatch("apply-changes-invalid", "changes 每项必须包含 tool");
58
+ if (!targets.has(change.tool)) {
59
+ const target = siblings.find((tool) => tool.name === change.tool);
60
+ if (!target)
61
+ return refuseBatch("apply-changes-unknown-tool", `changes 引用了不存在的工具 ${change.tool}`, { tool: change.tool });
62
+ if (target.kind !== "write")
63
+ return refuseBatch("apply-changes-tool-not-writable", `${change.tool} 不是写工具(changes 只接受写操作)`, { tool: change.tool });
64
+ if (target.layer !== "low" || !target.writeExecute)
65
+ return refuseBatch("apply-changes-tool-not-atomic", `${change.tool} 是高层预设(已是单调用包);changes 只接受低层原子写工具`, { tool: change.tool });
66
+ if (!target.lane || !target.scope)
67
+ return refuseBatch("apply-changes-tool-not-atomic", `${change.tool} 缺少 lane/scope 声明,无法通过覆盖门`, { tool: change.tool });
68
+ targets.set(change.tool, target);
69
+ }
70
+ try {
71
+ normalizedChanges.push({ tool: change.tool, args: parseToolInput(targets.get(change.tool), change.args) });
72
+ }
73
+ catch (error) {
74
+ if (error instanceof ToolInputError)
75
+ return { ...error.payload, failedBeforeApproval: true, changeTool: change.tool };
76
+ throw error;
77
+ }
78
+ }
79
+ // ---- 2. Semantic gates BEFORE the write permission gate (dry) ------
80
+ try {
81
+ for (const change of normalizedChanges)
82
+ targets.get(change.tool).writePreflight?.(change.args);
83
+ }
84
+ catch (error) {
85
+ if (error instanceof ToolRefusalError)
86
+ return { ...error.payload, failedBeforeApproval: true };
87
+ throw error;
88
+ }
89
+ // ---- 3. One plan, one fingerprint, per-action coverage ------------
90
+ const toolPhrase = (list) => {
91
+ const counts = new Map();
92
+ for (const change of list)
93
+ counts.set(change.tool, (counts.get(change.tool) ?? 0) + 1);
94
+ return [...counts.entries()].map(([tool, count]) => (count > 1 ? `${tool}×${count}` : tool)).join("、");
95
+ };
96
+ const plan = {
97
+ environment: "",
98
+ environmentFingerprint: "",
99
+ summary: args.summary ?? `即将按序执行 ${normalizedChanges.length} 项变更(${toolPhrase(normalizedChanges)})`,
100
+ actions: normalizedChanges.map((change) => ({ tool: change.tool, args: plannableArgs(change.tool, change.args) })),
101
+ };
102
+ const coverage = {
103
+ perAction: normalizedChanges.map((change) => {
104
+ const target = targets.get(change.tool);
105
+ return { lane: target.lane, scope: target.scope };
106
+ }),
107
+ };
108
+ const batchResult = await executePackage(ctx, plan, coverage, args, async (session) => {
109
+ // B1:串行/首败/超时冻结/progressFile 的状态机在共享执行器里;本面只
110
+ // 负责「怎么执行一步」(writeExecute 直调,保留各 lane 的权威读回与
111
+ // step 级 journal/before 快照)和回执投影(字段形状与 Ticket 46/58 一致)。
112
+ const executed = await executeGovernedBatch({
113
+ changes: normalizedChanges,
114
+ mode: "apply_changes",
115
+ timeoutMs: args.totalTimeoutMs,
116
+ progress: { ctx, summary: plan.summary },
117
+ summary: typeof args.summary === "string" ? args.summary : undefined,
118
+ runTool: async (change, index) => {
119
+ const target = targets.get(change.tool);
120
+ const outcome = await target.writeExecute(session, change.args);
121
+ // A step-chain write (field.update cascadeRepublish) may RETURN a
122
+ // mid-chain stop instead of throwing: the executor surfaces it as
123
+ // this batch's stop with the inner chain preserved for audit.
124
+ if ("status" in outcome)
125
+ return { kind: "stop", status: outcome.status, envelope: outcome.envelope };
244
126
  return {
245
- steps,
246
- readback: { stepCount: steps.length, tools: executedTools, allStepsOk: steps.every((step) => step.status === "ok"), progressFile },
247
- summary: args.summary ?? `已按序完成 ${steps.length} 项变更(${toolPhrase(changes)})`,
127
+ kind: "ok",
128
+ step: {
129
+ step: change.tool,
130
+ index,
131
+ status: "ok",
132
+ performed: outcome.performed,
133
+ readback: outcome.readback,
134
+ ...(outcome.steps !== undefined ? { chainSteps: outcome.steps } : {}),
135
+ },
248
136
  };
249
- });
250
- // R88 #3 审计面:批量写此前在 journal 里完全不可见(intent apply 也是
251
- // 经本工具执行的),多人共用一台机器时「谁用哪份意图改了什么、为什么」
252
- // 无处可查。这里只落**一条**批量审计行(与 configure_* 复合写同口径):
253
- // 逐步 before 快照并未捕获,所以 rollbackable:false,绝不假装能整包回滚。
254
- if (batchResult.status === "ok" && batchResult.deliveryState === "DELIVERED")
255
- await recordBatchJournal(ctx, args, batchResult);
256
- return batchResult;
257
- },
258
- }));
137
+ },
138
+ });
139
+ if (executed.kind === "stop")
140
+ return executed.outcome;
141
+ return {
142
+ steps: executed.steps,
143
+ readback: {
144
+ stepCount: executed.steps.length,
145
+ tools: executed.stepTools,
146
+ allStepsOk: executed.steps.every((step) => step.status === "ok"),
147
+ ...(executed.progressFile !== undefined ? { progressFile: executed.progressFile } : {}),
148
+ },
149
+ summary: args.summary ?? `已按序完成 ${executed.steps.length} 项变更(${toolPhrase(changes)})`,
150
+ };
151
+ });
152
+ // R88 #3 审计面:批量写此前在 journal 里完全不可见(intent apply 也是
153
+ // 经本工具执行的),多人共用一台机器时「谁用哪份意图改了什么、为什么」
154
+ // 无处可查。这里只落**一条**批量审计行(与 configure_* 复合写同口径):
155
+ // 逐步 before 快照并未捕获,所以 rollbackable:false,绝不假装能整包回滚。
156
+ if (batchResult.status === "ok" && batchResult.deliveryState === "DELIVERED")
157
+ await recordBatchJournal(ctx, args, batchResult);
158
+ return batchResult;
259
159
  }
260
160
  /** One honest journal line per delivered batch (audit only, not a rollback unit). */
261
161
  async function recordBatchJournal(ctx, args, result) {
262
162
  const steps = Array.isArray(result.steps) ? result.steps : [];
263
163
  if (steps.length === 0)
264
164
  return;
265
- const tools = [...new Set(steps.map((step) => String(step.step ?? "?")))];
266
- const target = `batch:${tools.slice(0, 3).join("+")}${tools.length > 3 ? `+${tools.length - 3}` : ""}`;
267
165
  const readback = (result.readback ?? {});
268
- const progressFile = typeof readback.progressFile === "string" ? readback.progressFile : undefined;
269
- const summary = typeof result.summary === "string" ? result.summary : undefined;
270
- let environment = typeof args.environment === "string" && args.environment.length > 0 ? args.environment : "local";
271
- let environmentFingerprint = "batch";
272
- try {
273
- // The batch itself established this session: a cache hit, never a second login.
274
- const session = await ctx.sessions.session(args.environment);
275
- environment = session.environmentName;
276
- environmentFingerprint = session.environmentFingerprint();
277
- }
278
- catch { /* journal still useful with the raw env name */ }
279
- const entry = appendJournalEntry(ctx.artifactsDir, {
280
- v: 1,
281
- environment,
282
- environmentFingerprint,
283
- tool: "apply_changes",
284
- target,
285
- beforeSha: null,
286
- rollbackable: false,
287
- note: `批量审计行(${steps.length} 步:${tools.slice(0, 6).join("、")}${summary !== undefined ? `;${summary}` : ""}):逐步 before 快照未捕获,不能整包回滚;逐项恢复请用对应单工具写面重做`,
288
- ...journalAudit(ctx.sessions.config(), environment, ctx.writeAudit?.reason),
289
- artifactFile: progressFile ?? `${target.replace(/[^\w.-]+/gu, "_")}.batch.json`,
290
- artifactId: progressFile !== undefined ? basename(progressFile) : "apply_changes-batch",
291
- artifactSha: typeof result.artifactFingerprint === "string" ? result.artifactFingerprint : "batch",
166
+ // B1:批量审计行的构造/措辞/字段统一在共享执行器模块(rollback.apply 也用
167
+ // 同一实现);此处只保留 W11C 的落行时机——executePackage 判定 DELIVERED
168
+ // 之后(artifactFingerprint 已可用),回执本身不加字段。
169
+ await appendBatchAuditLine({
170
+ ctx,
171
+ mode: "apply_changes",
172
+ environmentArg: args.environment,
173
+ reason: ctx.writeAudit?.reason,
174
+ steps,
175
+ summary: typeof result.summary === "string" ? result.summary : undefined,
176
+ progressFile: typeof readback.progressFile === "string" ? readback.progressFile : undefined,
177
+ fingerprint: typeof result.artifactFingerprint === "string" ? result.artifactFingerprint : undefined,
292
178
  });
293
- // The receipt is deliberately NOT extended (byte-for-byte stable for eval
294
- // baselines): the audit line is discoverable with
295
- // `omc rollback list --tool apply_changes`.
296
- void entry;
297
179
  }
298
180
  //# sourceMappingURL=apply-changes.js.map