@stalfh233/omc-cli 0.8.36 → 0.8.37

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.
@@ -3,6 +3,8 @@ import { ENDPOINTS } from "./endpoints.js";
3
3
  import { ToolRefusalError } from "./tool-types.js";
4
4
  import { resolveModelTreeNode } from "./lanes/model.js";
5
5
  import { listInstanceActivities, wireString } from "./workflow-support.js";
6
+ import { dateFormatRegex } from "./lanes/runtime-data/date-format.js";
7
+ import { parseOptions } from "./lanes/runtime-data/field-options.js";
6
8
  /**
7
9
  * Ticket 78 — map the two same-root-cause platform failures of an
8
10
  * UNPUBLISHED application to the explicit `app-not-published` blocker:
@@ -94,7 +96,62 @@ export const CHILD_TABLE_PROPERTY_TYPE = 8;
94
96
  * read ONLY on failure (zero cost on the success path); when nothing matches,
95
97
  * or the failure is a corroborated refusal, the ORIGINAL error is rethrown.
96
98
  */
97
- export async function diagnoseRelationShapeFailure(session, schemaCode, errcode, error, formData) {
99
+ const STAFF_PROPERTY_TYPES = new Set([50, 51, 52]);
100
+ const MULTI_SELECT_PROPERTY_TYPES = new Set([11, 50, 51, 52, 5, 8]);
101
+ function likelyShapeFields(rows, formData) {
102
+ const findings = [];
103
+ const typeOf = (row) => Number(row.propertyType ?? row.type);
104
+ for (const row of rows) {
105
+ const code = String(row.code ?? row.propertyCode ?? "");
106
+ const value = formData[code];
107
+ if (!code || value === null || value === undefined)
108
+ continue;
109
+ const type = typeOf(row);
110
+ const push = (problem, detail) => {
111
+ findings.push({ field: code, propertyType: type, problem, value: Array.isArray(value) ? `array[${value.length}]` : String(value), detail });
112
+ };
113
+ if (type === 3 || type === 28) {
114
+ const format = typeof parseOptions(row.options).format === "string" ? String(parseOptions(row.options).format) : undefined;
115
+ if (typeof value === "number")
116
+ push("date-number", `${type === 28 ? "时间" : "日期"}字段收到数字(毫秒时间戳)——平台接受但静默落 NULL`);
117
+ else if (typeof value === "string" && format) {
118
+ const re = dateFormatRegex(format);
119
+ if (re && !re.test(value.trim()))
120
+ push("date-format", `值不匹配字段 format "${format}"——平台直接回 50000`);
121
+ }
122
+ continue;
123
+ }
124
+ if (type === SINGLE_RELATION_PROPERTY_TYPE && Array.isArray(value) && value.length > 0) {
125
+ push("single-relation-array", "单选关联只接受 id 字符串或 {id};数组稳定 50000");
126
+ continue;
127
+ }
128
+ if (type === 11 && Array.isArray(value) && value.some((entry) => entry !== null && typeof entry === "object")) {
129
+ push("multi-relation-object-array", "多选关联写侧是分号串 \"id1;id2\";对象数组是读回形状");
130
+ continue;
131
+ }
132
+ if (STAFF_PROPERTY_TYPES.has(type) && Array.isArray(value) && value.some((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry) && entry.type === undefined)) {
133
+ push("staff-missing-type", "人员/组织数组元素必须带 type(1=部门/3=用户);缺 type 会 50000");
134
+ continue;
135
+ }
136
+ if (type === CHILD_TABLE_PROPERTY_TYPE && Array.isArray(value) && value.some((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry) && String(entry.id ?? "").trim() === "" && String(entry.rowStatus ?? "").trim() === "")) {
137
+ push("child-row-missing-id", "子表行没有 id 也没有 rowStatus:更新会按新增插入(重复行)");
138
+ continue;
139
+ }
140
+ if (Array.isArray(value) && !MULTI_SELECT_PROPERTY_TYPES.has(type)) {
141
+ push("scalar-array", "标量字段收到数组;标量写侧只接受单值(多选 11/人员组织 50/51/52 才用数组)");
142
+ }
143
+ }
144
+ return findings;
145
+ }
146
+ /**
147
+ * On a still-unexplained 50000 the platform gives no detail. With the already
148
+ * available field.list metadata, name every VALUE SHAPE that is known to
149
+ * produce it (issue #77.5): date format/number, single relation array,
150
+ * multi-relation object array, staff element missing `type`, id-less child
151
+ * rows, scalar array. The refusal carries a copy-paste `nextCommand` that
152
+ * omits the first suspect group so the caller can bisect without guessing.
153
+ */
154
+ export async function diagnoseRelationShapeFailure(session, schemaCode, errcode, error, formData, retry) {
98
155
  if (!(error instanceof WireError && error.kind === "business" && error.errcode === errcode))
99
156
  throw error;
100
157
  let rows;
@@ -104,38 +161,59 @@ export async function diagnoseRelationShapeFailure(session, schemaCode, errcode,
104
161
  catch {
105
162
  throw error;
106
163
  }
107
- const culprits = [];
164
+ const findings = likelyShapeFields(rows, formData);
165
+ // Child-row nested single relations are still named explicitly (the shape
166
+ // gate above only inspects top-level fields).
108
167
  const typeOf = (row) => Number(row.propertyType ?? row.type);
109
168
  for (const row of rows) {
110
169
  const code = String(row.code ?? row.propertyCode ?? "");
111
170
  const value = formData[code];
112
- if (typeOf(row) === SINGLE_RELATION_PROPERTY_TYPE && Array.isArray(value) && value.length > 0) {
113
- culprits.push(code);
171
+ if (typeOf(row) !== CHILD_TABLE_PROPERTY_TYPE || !Array.isArray(value))
114
172
  continue;
115
- }
116
- if (typeOf(row) === CHILD_TABLE_PROPERTY_TYPE && Array.isArray(value)) {
117
- const subSchema = row.subSchema;
118
- const singleChildren = new Set((subSchema?.properties ?? []).filter((property) => typeOf(property) === SINGLE_RELATION_PROPERTY_TYPE).map((property) => String(property.code ?? property.propertyCode ?? "")));
119
- for (const entry of value) {
120
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
121
- continue;
122
- for (const childCode of singleChildren) {
123
- const childValue = entry[childCode];
124
- if (Array.isArray(childValue) && childValue.length > 0)
125
- culprits.push(`${code}.${childCode}`);
126
- }
173
+ const subSchema = row.subSchema;
174
+ const singleChildren = new Set((subSchema?.properties ?? []).filter((property) => typeOf(property) === SINGLE_RELATION_PROPERTY_TYPE).map((property) => String(property.code ?? property.propertyCode ?? "")));
175
+ for (const entry of value) {
176
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
177
+ continue;
178
+ for (const childCode of singleChildren) {
179
+ const childValue = entry[childCode];
180
+ if (Array.isArray(childValue) && childValue.length > 0 && !findings.some((finding) => finding.field === `${code}.${childCode}`))
181
+ findings.push({ field: `${code}.${childCode}`, propertyType: SINGLE_RELATION_PROPERTY_TYPE, problem: "single-relation-array", value: `array[${childValue.length}]`, detail: "子表行内单选关联传了数组" });
127
182
  }
128
183
  }
129
184
  }
130
- if (culprits.length === 0)
185
+ if (findings.length === 0)
131
186
  throw error;
187
+ const relationOnly = findings.every((finding) => finding.problem === "single-relation-array");
188
+ if (relationOnly) {
189
+ throw new ToolRefusalError({
190
+ status: "refused",
191
+ blocker: "relation-single-array-shape",
192
+ schemaCode,
193
+ errcode,
194
+ fields: findings.map((finding) => finding.field),
195
+ message: `errcode ${errcode}——根因:单选关联字段 ${findings.map((finding) => finding.field).join(", ")} 传了数组(WORK_SHEET/propertyType 9 只接受 id 字符串或 {id};数组会稳定 ${errcode})。多选关联(11)与人员/组织(50/51)才用数组`,
196
+ });
197
+ }
198
+ // Omit the first suspect group (top-level field + its `_key` companion) and
199
+ // give a runnable retry — the caller can then re-add fields one by one.
200
+ const first = findings[0].field.split(".")[0];
201
+ const retryFormData = { ...formData };
202
+ delete retryFormData[first];
203
+ delete retryFormData[`${first}_key`];
204
+ const toolName = retry?.toolName ?? "data.save";
205
+ const nextCommand = `omc call ${toolName} --env <env> --args '${JSON.stringify({ schemaCode, ...(retry?.extraArgs ?? {}), formData: retryFormData })}'`;
132
206
  throw new ToolRefusalError({
133
207
  status: "refused",
134
- blocker: "relation-single-array-shape",
208
+ blocker: "runtime-write-shape-50000",
135
209
  schemaCode,
136
210
  errcode,
137
- fields: culprits,
138
- message: `errcode ${errcode}——根因:单选关联字段 ${culprits.join(", ")} 传了数组(WORK_SHEET/propertyType 9 只接受 id 字符串或 {id};数组会稳定 ${errcode})。多选关联(11)与人员/组织(50/51)才用数组`,
211
+ likelyFields: findings,
212
+ omittedOnRetry: [first],
213
+ nextCommand,
214
+ message: `errcode ${errcode}(平台无明细)——按已发布 field.list 推断最可能的形状问题:` +
215
+ findings.map((finding) => `${finding.field}(${finding.problem}:${finding.detail})`).join(";") +
216
+ `。先按 nextCommand 省略 ${first} 重试(data.update 用 bizObjectId、data.submit 用其自身参数);仍 50000 就逐个加回,命中的那组就是根因。`,
139
217
  });
140
218
  }
141
219
  /**
package/dist/tools.js CHANGED
@@ -222,6 +222,7 @@ function registerRequestStatusTool(tools) {
222
222
  const latest = hits[hits.length - 1];
223
223
  const artifact = latest.artifact;
224
224
  const performed = (artifact.performed ?? {});
225
+ const uncertain = artifact.deliveryState === "UNCERTAIN";
225
226
  return {
226
227
  status: "ok",
227
228
  found: true,
@@ -231,6 +232,17 @@ function registerRequestStatusTool(tools) {
231
232
  deliveryState: artifact.deliveryState,
232
233
  completedAt: artifact.recordedAt,
233
234
  requestFingerprint: artifact.requestFingerprint,
235
+ // issue #77.6:uncertain 写也会留本机记录(不存 args)。这里明确标出
236
+ // 「找到了,但结果未定」——found:true 不等于完成。
237
+ ...(uncertain
238
+ ? {
239
+ uncertain: true,
240
+ pending: true,
241
+ ...(typeof artifact.errorKind === "string" ? { errorKind: artifact.errorKind } : {}),
242
+ ...(typeof artifact.endpoint === "string" ? { endpoint: artifact.endpoint } : {}),
243
+ ...(typeof artifact.gateway404Class === "string" ? { gateway404Class: artifact.gateway404Class } : {}),
244
+ }
245
+ : {}),
234
246
  result: {
235
247
  ...(typeof performed.bizObjectId === "string" ? { bizObjectId: performed.bizObjectId } : {}),
236
248
  ...(performed.skipped !== undefined ? { skipped: performed.skipped } : {}),
@@ -240,6 +252,12 @@ function registerRequestStatusTool(tools) {
240
252
  artifactFile: latest.file,
241
253
  matches: hits.length,
242
254
  ...(hits.length > 1 ? { hint: `同 id ${hits.length} 条;以上为最后一条` } : {}),
255
+ ...(uncertain
256
+ ? {
257
+ hint: "该 requestId 只有 UNCERTAIN 记录:写可能已生效(也可能没发出)。先按业务键 data.list 查重;确认前勿用同一 requestId 换参重发,也不要用新 requestId 盲目重放。",
258
+ nextAction: "data.list 按业务键(单号/编码)查重;命中即成功,未命中再决定是否重发",
259
+ }
260
+ : {}),
243
261
  };
244
262
  },
245
263
  }));
package/dist/wire.js CHANGED
@@ -7,6 +7,15 @@ import { classifyTransportFailure, recordWireFailure } from "./wire-failure.js";
7
7
  * failures: business errors are definitive refusals; transport failures are
8
8
  * UNCERTAIN — callers must freeze, never assume success.
9
9
  */
10
+ /**
11
+ * 网关 HTML 404 的**可判定**子类(issue #77.6):
12
+ * - `platform-api-up-route-not-found`:健康探测 200,平台进程在线,404 属
13
+ * 网关/路由未命中(值得重试、可查路由);
14
+ * - `platform-api-down`:健康探测失败/非 2xx,平台不可用(先 doctor/等恢复)。
15
+ * 旧回执只说「网关抖动」,两种情况学不到该不该重试。
16
+ */
17
+ export const PLATFORM_API_UP_ROUTE_NOT_FOUND = "platform-api-up-route-not-found";
18
+ export const PLATFORM_API_DOWN = "platform-api-down";
10
19
  export class WireError extends Error {
11
20
  kind;
12
21
  errcode;
@@ -77,7 +86,101 @@ export const GATEWAY_HTML_404_PREFIX = "网关返回了 HTML 404(不是平台
77
86
  export function gatewayHtml404Message(input) {
78
87
  const method = input.method ?? "GET";
79
88
  const contentType = input.contentType && input.contentType !== "unknown" ? input.contentType : "HTML";
80
- return `${GATEWAY_HTML_404_PREFIX}:${method} ${input.path}(响应体 ${contentType})——通常是路由/网关瞬时抖动,可重试 1–2 次(同一载荷);连续复现(同一端点 ≥2 次)再查 readiness/部署(omc doctor)。`;
89
+ const base = `${GATEWAY_HTML_404_PREFIX}:${method} ${input.path}(响应体 ${contentType})`;
90
+ if (input.diagnosis === undefined)
91
+ return `${base}——通常是路由/网关瞬时抖动,可重试 1–2 次(同一载荷);连续复现(同一端点 ≥2 次)再查 readiness/部署(omc doctor)。`;
92
+ const probePath = input.health?.probe ?? ENDPOINTS.publicHealthz;
93
+ if (input.diagnosis === PLATFORM_API_UP_ROUTE_NOT_FOUND) {
94
+ const status = input.health?.status !== undefined ? `返回 ${input.health.status}` : "可达";
95
+ return `${base}——健康探测 GET ${probePath} ${status}:平台 API 在线,404 是网关/路由未命中(${PLATFORM_API_UP_ROUTE_NOT_FOUND});可重试 1–2 次(同一载荷),连续复现再查网关路由/部署(omc doctor)。`;
96
+ }
97
+ const reason = input.health?.error !== undefined
98
+ ? `失败(${input.health.error})`
99
+ : input.health?.status !== undefined
100
+ ? `返回 ${input.health.status}`
101
+ : "未通过";
102
+ return `${base}——健康探测 GET ${probePath} ${reason}:平台 API 不可用(${PLATFORM_API_DOWN}),先 omc doctor / 等平台恢复;恢复后可重试 1–2 次(同一载荷)。`;
103
+ }
104
+ /**
105
+ * Health-probe cache: one anonymous GET per session per 5s (flapping 404s must
106
+ * not multiply probes).
107
+ *
108
+ * 缓存的是 **Promise** 而不是已解析结果:并发 404 在同一 tick 里都看到冷缓存,
109
+ * 若各发一笔探测,抖动会被放大成并发探测风暴。首个调用同步登记 in-flight
110
+ * promise,其余调用者 await 同一笔;窗口内后到的调用复用已解析结果。
111
+ */
112
+ const HEALTH_PROBE_TTL_MS = 5_000;
113
+ const HEALTH_PROBE_TIMEOUT_MS = 3_000;
114
+ let healthProbeCache = new WeakMap();
115
+ let healthClock = () => Date.now();
116
+ /** Test seam for the 5s cache window. */
117
+ export function __setGatewayHealthClockForTests(override) {
118
+ healthClock = override ?? (() => Date.now());
119
+ }
120
+ /** Test seam: forget every cached probe (WeakMap has no clear()). */
121
+ export function __resetGatewayHealthCacheForTests() {
122
+ healthProbeCache = new WeakMap();
123
+ }
124
+ function boundedErrorMessage(error) {
125
+ // Never echo the raw message: the probe failure can itself be the gateway's
126
+ // HTML 404 wording ("勿重试/不可达") and pasting it back would recreate the
127
+ // very misinformation B1 removed. Only a transport code / error name is safe.
128
+ const facts = classifyTransportFailure(error);
129
+ const label = facts.causeCode ?? (error instanceof Error && error.name ? error.name : facts.failureKind);
130
+ return label.length > 160 ? `${label.slice(0, 160)}…` : label;
131
+ }
132
+ /**
133
+ * Anonymous存活探测(issue #77.6):404 时判断「平台在线但路由没到」还是
134
+ * 「平台本身不可用」。短超时(3s)+ 5s 缓存 + **失败不抛**——探测永远不能
135
+ * 把一次可重试的 404 变成本地异常。`session.request` 复用会话 adapter(测试
136
+ * 注入的 fake 也能命中),登录态已存在时它只是一笔普通 GET。
137
+ *
138
+ * 并发安全(复审建议):缓存 in-flight `Promise`,同一会话的并发 404 只发一笔
139
+ * 探测。`performHealthProbe` 是 total 的(内部 catch → up:false),所以失败会
140
+ * 作为「平台不可用」的已解析结果在窗口内复用,避免抖动放大;防御性地,若
141
+ * promise 真的 reject(未来改动/注入异常),缓存条目会被清掉,下一次调用立即
142
+ * 重新探测,而不是把 rejected promise 留给后来者。
143
+ */
144
+ async function performHealthProbe(session) {
145
+ try {
146
+ const response = await session.request({ path: ENDPOINTS.publicHealthz, method: "GET", timeoutMs: HEALTH_PROBE_TIMEOUT_MS });
147
+ const up = response.status >= 200 && response.status < 300;
148
+ return {
149
+ up,
150
+ probe: ENDPOINTS.publicHealthz,
151
+ status: response.status,
152
+ ...(up ? {} : { error: `HTTP ${response.status}` }),
153
+ cached: false,
154
+ };
155
+ }
156
+ catch (error) {
157
+ return { up: false, probe: ENDPOINTS.publicHealthz, error: boundedErrorMessage(error), cached: false };
158
+ }
159
+ }
160
+ export async function probePlatformHealth(session) {
161
+ const now = healthClock();
162
+ const cached = healthProbeCache.get(session);
163
+ if (cached !== undefined && now - cached.at < HEALTH_PROBE_TTL_MS) {
164
+ try {
165
+ return { ...(await cached.pending), cached: true };
166
+ }
167
+ catch {
168
+ // 失败清理:rejected promise 不能污染 5s 窗口——删掉后走新探测。
169
+ if (healthProbeCache.get(session) === cached)
170
+ healthProbeCache.delete(session);
171
+ }
172
+ }
173
+ const entry = { at: now, pending: performHealthProbe(session) };
174
+ healthProbeCache.set(session, entry);
175
+ try {
176
+ return await entry.pending;
177
+ }
178
+ catch (error) {
179
+ // performHealthProbe 不会 reject;这里保留失败清理路径以守住「不缓存拒绝态」。
180
+ if (healthProbeCache.get(session) === entry)
181
+ healthProbeCache.delete(session);
182
+ return { up: false, probe: ENDPOINTS.publicHealthz, error: boundedErrorMessage(error), cached: false };
183
+ }
81
184
  }
82
185
  /** Recognise the omc-core non-JSON-HTTP failure that B1 must not read as "unreachable". */
83
186
  function gatewayHtmlResponseOf(error) {
@@ -97,7 +200,7 @@ function gatewayHtmlResponseOf(error) {
97
200
  return { path: match[1], status, contentType };
98
201
  }
99
202
  /** Re-throw a gateway HTML 404 as a retryable transport failure; other errors pass through. */
100
- function throwIfGatewayHtml404(error) {
203
+ async function throwIfGatewayHtml404(session, error) {
101
204
  const hit = gatewayHtmlResponseOf(error);
102
205
  if (hit === undefined)
103
206
  return;
@@ -110,7 +213,12 @@ function throwIfGatewayHtml404(error) {
110
213
  // this version family → try the alternate path" checks
111
214
  // (wireCallWith404Fallback / model-record / form.list / rule-lifecycle).
112
215
  // Those checks still see real JSON 404s exactly as before.
113
- const failure = new WireError("transport", gatewayHtml404Message(hit), undefined, { httpStatus: hit.status });
216
+ //
217
+ // issue #77.6: 判定的**子类**来自匿名 healthz 探测(5s 缓存、失败不抛)。
218
+ // 探测不是版本族下探:它只回答「平台进程是否在线」,不尝试任何业务端点。
219
+ const health = await probePlatformHealth(session);
220
+ const diagnosis = health.up ? PLATFORM_API_UP_ROUTE_NOT_FOUND : PLATFORM_API_DOWN;
221
+ const failure = new WireError("transport", gatewayHtml404Message({ ...hit, diagnosis, health }), undefined, { httpStatus: hit.status, health });
114
222
  recordWireFailure(failure, { endpoint: hit.path, failureKind: "http", httpStatus: hit.status });
115
223
  throw failure;
116
224
  }
@@ -342,7 +450,7 @@ export async function wireCall(session, call) {
342
450
  ...(call.body === undefined ? {} : { body: call.body }),
343
451
  ...(call.headers === undefined ? {} : { headers: call.headers }),
344
452
  ...(call.timeoutMs === undefined ? {} : { timeoutMs: call.timeoutMs }),
345
- }).catch((error) => {
453
+ }).catch(async (error) => {
346
454
  // B3(0.8.4):把「到底哪一跳、哪一类失败」记在错误上再抛——读面回执要带
347
455
  // endpoint / lastFailureKind / lastFailureCause。判定不变(仍是未分类原错,
348
456
  // 由 isUncertainWireError 的老规则兜住),只是不再把 undici 的 cause 丢掉。
@@ -356,7 +464,7 @@ export async function wireCall(session, call) {
356
464
  }
357
465
  // B1: a gateway HTML 404 is a retryable transport blip, never "endpoint
358
466
  // absent / do not retry". Every other status keeps its original error.
359
- throwIfGatewayHtml404(error);
467
+ await throwIfGatewayHtml404(session, error);
360
468
  throw error;
361
469
  });
362
470
  if (response.status < 200 || response.status >= 300) {
@@ -459,10 +567,10 @@ export function wireRows(value) {
459
567
  export async function wireDownloadBuffer(session, call) {
460
568
  const response = await session
461
569
  .request({ path: call.path, method: "POST", ...(call.body === undefined ? {} : { body: call.body }), responseType: "buffer" })
462
- .catch((error) => {
570
+ .catch(async (error) => {
463
571
  if (error instanceof CloudPivotRequestTimeoutError)
464
572
  throw new WireError("transport", error.message);
465
- throwIfGatewayHtml404(error);
573
+ await throwIfGatewayHtml404(session, error);
466
574
  throw error;
467
575
  });
468
576
  if (response.status < 200 || response.status >= 300)
@@ -487,10 +595,10 @@ export async function wireDownloadBuffer(session, call) {
487
595
  export async function wireDownloadPackageStream(session, call) {
488
596
  const response = await session
489
597
  .request({ path: call.path, method: "POST", ...(call.body === undefined ? {} : { body: call.body }), responseType: "buffer" })
490
- .catch((error) => {
598
+ .catch(async (error) => {
491
599
  if (error instanceof CloudPivotRequestTimeoutError)
492
600
  throw new WireError("transport", error.message);
493
- throwIfGatewayHtml404(error);
601
+ await throwIfGatewayHtml404(session, error);
494
602
  throw error;
495
603
  });
496
604
  if (response.status < 200 || response.status >= 300)
@@ -544,10 +652,10 @@ export async function wireDownloadPackageStream(session, call) {
544
652
  export async function wireUploadFile(session, path, filename, content, contentType = "application/zip") {
545
653
  const response = await session
546
654
  .request({ path, method: "POST", multipart: { filename, contentType, content }, responseType: "buffer" })
547
- .catch((error) => {
655
+ .catch(async (error) => {
548
656
  if (error instanceof CloudPivotRequestTimeoutError)
549
657
  throw new WireError("transport", error.message);
550
- throwIfGatewayHtml404(error);
658
+ await throwIfGatewayHtml404(session, error);
551
659
  throw error;
552
660
  });
553
661
  if (response.status < 200 || response.status >= 300)
package/dist/write.js CHANGED
@@ -16,6 +16,7 @@ import { isPackageStopOutcome } from "./package.js";
16
16
  import { writeSummary } from "./human-summary.js";
17
17
  import { planFor } from "./plan.js";
18
18
  import { isUncertainWireError, sha256, wireErrorKind, writeArtifact } from "./support.js";
19
+ import { describeWireFailure } from "./wire-failure.js";
19
20
  import { refusalFromWireError } from "./wire-refusal.js";
20
21
  import { appendJournalEntry } from "./journal.js";
21
22
  import { journalAudit } from "./write-audit.js";
@@ -27,7 +28,7 @@ import { validateBusinessCode, validateFieldEntryCodes } from "./code-rules.js";
27
28
  import { hardLayoutViolations, validateFormLayout } from "./form-layout.js";
28
29
  import { prepareRuleGraph, validateRuleNodeGraph } from "./lanes/rule-graph.js";
29
30
  import { assertRuleNamePlatformAcceptable } from "./rule-support.js";
30
- import { WireError } from "./wire.js";
31
+ import { WireError, PLATFORM_API_UP_ROUTE_NOT_FOUND, PLATFORM_API_DOWN } from "./wire.js";
31
32
  import { reduceWriteOutcome, toWriteReceipt, writeOutcomeVerdict } from "./write-outcome.js";
32
33
  // The readback gate lives with the verdict it drives (write-outcome.ts) so there
33
34
  // is exactly one place that answers "does this readback certify the write?".
@@ -148,32 +149,92 @@ lintDeclaration = { lintScope: "partial", lintUnchecked: [] }) {
148
149
  executed = await execute(session);
149
150
  }
150
151
  catch (error) {
151
- if (isUncertainWireError(error))
152
+ if (isUncertainWireError(error)) {
153
+ // issue #77.6:uncertain 必须可回查。旧回执只带 detail,requestId 丢了、
154
+ // 本机也没有任何记录,`request.status` 只能回 found:false——调用方无法
155
+ // 证明「这笔写到底发出去过」。这里落一条 deliveryState:"UNCERTAIN" 的
156
+ // 本机产物(tool/env/requestId/fingerprint/errorKind/endpoint/recordedAt,
157
+ // **不存 args**),request.status 因此可见 found:true + 未完成证据。
158
+ const facts = describeWireFailure(error);
159
+ const health = error instanceof WireError ? error.diagnostic?.health : undefined;
160
+ const diagnosis = health === undefined ? undefined : health.up ? PLATFORM_API_UP_ROUTE_NOT_FOUND : PLATFORM_API_DOWN;
161
+ let environmentFingerprint;
162
+ try {
163
+ environmentFingerprint = session.environmentFingerprint();
164
+ }
165
+ catch {
166
+ environmentFingerprint = undefined;
167
+ }
168
+ const uncertainArtifact = {
169
+ tool: tool.name,
170
+ ...(args.requestId ? { requestId: args.requestId, requestFingerprint } : {}),
171
+ environment: session.environmentName,
172
+ ...(environmentFingerprint !== undefined ? { environmentFingerprint } : {}),
173
+ deliveryState: "UNCERTAIN",
174
+ errorKind: wireErrorKind(error),
175
+ ...(facts.endpoint !== undefined ? { endpoint: facts.endpoint } : {}),
176
+ ...(facts.failureKind !== undefined ? { lastFailureKind: facts.failureKind } : {}),
177
+ ...(facts.httpStatus !== undefined ? { httpStatus: facts.httpStatus } : {}),
178
+ ...(diagnosis !== undefined ? { gateway404Class: diagnosis } : {}),
179
+ ...(health !== undefined ? { healthProbe: health } : {}),
180
+ recordedAt: new Date().toISOString(),
181
+ };
182
+ let artifactRef;
183
+ try {
184
+ artifactRef = writeArtifact(ctx, `${tool.name}-${randomUUID().slice(0, 8)}.json`, uncertainArtifact);
185
+ }
186
+ catch {
187
+ // Artifact hygiene is best-effort; the receipt below must still print.
188
+ artifactRef = undefined;
189
+ }
190
+ const envFlag = ` --env ${session.environmentName}`;
191
+ const statusCommand = args.requestId
192
+ ? `omc call request.status${envFlag} --args '{"requestId":"${args.requestId}"}'`
193
+ : undefined;
194
+ const authStatus = error instanceof WireError && error.kind === "http-status" && (error.diagnostic?.httpStatus === 401 || error.diagnostic?.httpStatus === 403);
152
195
  return {
153
196
  status: "uncertain",
154
197
  frozen: true,
198
+ // 写面的 reason 名的是 WireError 类别(http-status / transport),
199
+ // 契约与 t17 都依赖它点名 http-status;B3 的真实分类只进
200
+ // lastFailureKind(新增字段),不要拿它替换 reason。
155
201
  reason: `wire-transport:${wireErrorKind(error)}`,
156
202
  detail: error.message,
203
+ ...(args.requestId ? { requestId: args.requestId } : {}),
157
204
  // issue 2026-11 F5:同读面——把环境名与 baseUrl 一起回出来,避免
158
205
  // 「cwd 落到全局 default 的另一台主机」被误判成参数问题。
159
206
  environment: session.environmentName,
160
207
  baseUrl: session.profile.baseUrl,
208
+ ...(environmentFingerprint !== undefined ? { environmentFingerprint } : {}),
209
+ ...(facts.endpoint !== undefined ? { endpoint: facts.endpoint } : {}),
210
+ ...(facts.failureKind !== undefined ? { lastFailureKind: facts.failureKind } : {}),
211
+ ...(diagnosis !== undefined ? { gateway404Class: diagnosis } : {}),
212
+ ...(health !== undefined ? { healthProbe: health } : {}),
213
+ deliveryState: "UNCERTAIN",
214
+ ...(artifactRef !== undefined ? { artifact: artifactRef } : {}),
215
+ ...(statusCommand !== undefined
216
+ ? {
217
+ nextCommand: statusCommand,
218
+ nextAction: `先 ${statusCommand} 看本机 UNCERTAIN 记录,再按业务键查重(data.list)确认是否已生效;确认前勿用同一 requestId 换参重发,也不要用新 requestId 盲目重放`,
219
+ }
220
+ : { nextAction: "本次未带 requestId,无法按 id 回查;确认结果走业务键查重(data.list),确认前勿盲目重放。下次写请带 --request-id 以留下可查记录" }),
161
221
  environmentHint: "env 清单随 cwd 变(项目根 .omc-env/.omc-envs + 配置根);`omc env list` 首行回显 configRoot/projectRoot",
162
222
  // 2.1.5 起管理端点统一 @AdminOnly(8.6 是 @RequireAdmin):401/403 往往
163
223
  // 不是 token 坏了,而是该端点在新版要求管理员。不要笼统说「传输失败」。
164
- ...(error instanceof WireError && error.kind === "http-status" && (error.diagnostic?.httpStatus === 401 || error.diagnostic?.httpStatus === 403)
224
+ ...(authStatus
165
225
  ? {
166
226
  message: `HTTP ${error.diagnostic?.httpStatus}:写请求被拒(结果未知,先别重放)。2.1.5 起管理端点(programming.*、workflow.publish/update、license/info)统一为 @AdminOnly,普通应用管理员可能不再放行;先确认账号,再区分「端点要求管理员」与「平台未开该功能」。`,
167
- nextAction: "换管理员账号复验;仍 403 就查平台侧功能开关(如 cloudpivot.programming.enable),不要把 403 当 token 过期反复重登",
227
+ nextAction: `换管理员账号复验;仍 403 就查平台侧功能开关(如 cloudpivot.programming.enable),不要把 403 当 token 过期反复重登${statusCommand !== undefined ? `。本机记录可回查:${statusCommand}` : ""}`,
168
228
  }
169
229
  : {}),
170
- message: error instanceof WireError && error.kind === "http-status" && (error.diagnostic?.httpStatus === 401 || error.diagnostic?.httpStatus === 403)
230
+ message: authStatus
171
231
  ? `HTTP ${error.diagnostic?.httpStatus}:写请求被拒(结果未知,先别重放)。2.1.5 起管理端点(programming.*、workflow.publish/update、license/info)统一为 @AdminOnly;先确认账号与功能开关。`
172
232
  : "write outcome cannot be established; frozen — re-discover before retrying; never assume success",
173
233
  // r46 实证:data.submit 传输中断但平台已落行,按回执盲重试产生重复数据
174
234
  // 再连锁清理。uncertain ≠ 失败——先按业务键查重再决定。
175
235
  hint: "uncertain 不是失败:写可能已生效。data.submit/data.save 先 data.list 按业务键(单号/编码)查重,命中即成功勿重发;未命中再重试。",
176
236
  };
237
+ }
177
238
  if (error instanceof ToolRefusalError)
178
239
  throw error;
179
240
  // 平台拒绝:回执就是那张唯一翻译表的产物,原样序列化(union 的 refused 分支)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.8.36",
3
+ "version": "0.8.37",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "commander": "14.0.3",
61
- "omc-core": "0.8.36",
61
+ "omc-core": "0.8.37",
62
62
  "proper-lockfile": "4.1.2",
63
63
  "write-file-atomic": "6.0.0",
64
64
  "zod": "^3.23.8",
@@ -76,6 +76,6 @@
76
76
  "directory": "packages/omc-cli"
77
77
  },
78
78
  "optionalDependencies": {
79
- "@stalfh233/omc-fake-platform": "0.8.36"
79
+ "@stalfh233/omc-fake-platform": "0.8.37"
80
80
  }
81
81
  }