@stalfh233/omc-cli 0.8.2 → 0.8.3

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.
@@ -139,7 +139,7 @@ export const subFieldArg = z
139
139
  * Field options. The shape depends on `propertyType`:
140
140
  * - relation families WORK_SHEET(9) / MULT_WORK_SHEET(11):
141
141
  * { schemaCode:<target model>, queryCode:<target model>, displayField:"name",
142
- * mappings:'[{"source":<target field code>,"target":<this-model field code>}]' }
142
+ * mappings:'[{"source":<关联侧字段/父模型字段/子表code.字段code>,"target":<本模型字段 code>}]' }
143
143
  * - RELEVANCE_DATA(16) — a *reference to another field*, NOT a model relation
144
144
  * (8.6.26 `RelevanceDataOptions`, admin field serializer):
145
145
  * { relevanceField:<local WORK_SHEET field code>,
@@ -173,7 +173,8 @@ export const fieldOptionsArg = z
173
173
  mappings: z
174
174
  .union([z.string(), z.array(z.object({ source: z.string(), target: z.string() }))])
175
175
  .optional()
176
- .describe('relation mappings:[{"source":"<目标字段>","target":"<本模型字段>"}] 或 JSON 串([]/""=无映射)。仅门户选取时回填;data.save/update 不触发;data.load 是快照,上游改名不跟随'),
176
+ .describe('relation mappings:[{"source":"<关联侧字段>","target":"<本模型字段>"}] 或 JSON 串([]/""=无映射)。source=关联侧字段/父模型字段/子表code.字段code;target 只用本模型裸 code。仅门户选取回填;data.save/update 不跑;data.load 不跟随上游改名'),
177
+ mainTableCode: z.string().optional().describe("关联目标为子表时的主表模型 code(设计器键;运行期认 parentCode;拒绝回执看 relationParentCode)"),
177
178
  searchFormula: jsonString().optional().describe("WORK_SHEET / MULT_WORK_SHEET data restriction range JSON"),
178
179
  conditions: jsonString().optional().describe("WORK_SHEET / MULT_WORK_SHEET query conditions JSON"),
179
180
  optionsSet: optionsSetArg.optional().describe("selection source: custom, dictionary, or businessModel"),
@@ -190,8 +191,8 @@ export const fieldOptionsArg = z
190
191
  // surface the constraint before preflight. Bounds stay in
191
192
  // assertNumericalScale (not zod min/max) so scale:9 still returns the
192
193
  // teaching refusal, not a generic tool-input-invalid.
193
- scale: z.number().optional().describe("NUMERICAL 必填:小数位数(0=整数,1=1位,2=2位 … 8=8位)。金额两位小数用 2;不是 listview displayFormat 枚举"),
194
- format: z.unknown().optional().describe("NUMERICAL 显示格式族(平台常量):`ratio`/`ratio.tenths`/`ratio.percentile`=20%/20.0%/20.00%,`integer`/`tenths`/`percentile`=普通数字,`RMB.*`/`dollar.*`/`HK.*` 等=货币,`none`=裸值。**百分比存比值** 0.5→50.00%(存 50 显示 5000.00%),`scale` 与小数位对齐。别名 percent/currency/¥ 由 CLI 归一;字段行 format 优先于表单控件"),
194
+ scale: z.number().optional().describe("NUMERICAL 必填:小数位数(0=整数 … 8=8位)。金额用 2;不是 listview displayFormat 枚举"),
195
+ format: z.unknown().optional().describe("NUMERICAL 显示格式族(平台常量,全表见 contract 的 numericalFormat):**百分比存比值** 0.5→50.00%(存 50 显示 5000.00%),`scale` 与小数位对齐;别名 percent/currency/¥ 由 CLI 归一;字段行 format 优先于表单控件"),
195
196
  nested: z.boolean().optional().describe("nested child-table metadata — refused (coverage boundary)"),
196
197
  relationLinkage: z.boolean().optional().describe("advanced relation linkage — refused (coverage boundary)"),
197
198
  })
@@ -784,7 +785,12 @@ export function normalizeMappingsOption(options) {
784
785
  if (!("mappings" in options) || options.mappings === undefined)
785
786
  return { options };
786
787
  const mappings = options.mappings;
787
- const mappingsError = (detail) => refuseFieldOptions(`relation mappings fail the reproduced protocol`, `rejected: options.mappings ${detail};合法形状:JSON 字符串 [{"source":"<来源字段>","target":"<目标字段>"}] 或等价数组;无映射用 ""(不是 "[]"——"[]" 会让设计器显示"已设置"但弹窗无映射行)`);
788
+ const mappingsError = (detail) => refuseFieldOptions(`relation mappings fail the reproduced protocol`, `rejected: options.mappings ${detail};合法形状:JSON 字符串 [{"source":"<来源字段>","target":"<目标字段>"}] 或等价数组。source 用裸字段 code,关联目标是子表时也可用 子表code.字段code(平台存储形态,如 contract_payment_items.collectionItemName);target 只用本模型字段 code,不带前缀。无映射用 ""(不是 "[]"——"[]" 会让设计器显示"已设置"但弹窗无映射行)`);
789
+ /** `子表code.字段code`(单点号、两段非空);`模型.字段` 仍按原协议拒绝。 */
790
+ const sheetColumnSource = (source) => {
791
+ const dot = source.indexOf(".");
792
+ return dot > 0 && dot < source.length - 1 && !source.slice(dot + 1).includes(".");
793
+ };
788
794
  let normalized;
789
795
  if (Array.isArray(mappings)) {
790
796
  if (mappings.length === 0)
@@ -798,8 +804,10 @@ export function normalizeMappingsOption(options) {
798
804
  const target = record.target;
799
805
  if (typeof source !== "string" || source.trim() === "" || typeof target !== "string" || target.trim() === "")
800
806
  mappingsError("每项的 source/target 必须是非空字符串");
801
- if (source.includes(".") || target.includes("."))
802
- mappingsError("source/target 应为目标模型字段 code,不带模型前缀(不要使用 模型.字段)");
807
+ if (target.includes("."))
808
+ mappingsError("target 只用本模型字段 code,不带前缀");
809
+ if (source.includes(".") && !sheetColumnSource(source))
810
+ mappingsError("source 的点号形态只允许 子表code.字段code(关联目标是子表时);其它情况用裸字段 code");
803
811
  return { source: source.trim(), target: target.trim() };
804
812
  });
805
813
  normalized = JSON.stringify(rows);
@@ -819,8 +827,10 @@ export function normalizeMappingsOption(options) {
819
827
  }
820
828
  if (!Array.isArray(parsed) || parsed.some((row) => row === null || typeof row !== "object" || Array.isArray(row) || typeof row.source !== "string" || typeof row.target !== "string" || row.source === "" || row.target === ""))
821
829
  mappingsError("解析结果必须是 [{source,target}] 形状(source/target 非空字符串)");
822
- if (parsed.some((row) => String(row.source).includes(".") || String(row.target).includes(".")))
823
- mappingsError("source/target 应为目标模型字段 code,不带模型前缀(不要使用 模型.字段)");
830
+ if (parsed.some((row) => String(row.target).includes(".")))
831
+ mappingsError("target 只用本模型字段 code,不带前缀");
832
+ if (parsed.some((row) => String(row.source).includes(".") && !sheetColumnSource(String(row.source))))
833
+ mappingsError("source 的点号形态只允许 子表code.字段code(关联目标是子表时);其它情况用裸字段 code");
824
834
  normalized = JSON.stringify(parsed.map(({ source, target }) => ({ source: source.trim(), target: target.trim() })));
825
835
  }
826
836
  }
@@ -31,7 +31,13 @@ export const SOFT_LAYOUT_CLASSIFICATIONS = new Set();
31
31
  export function hardLayoutViolations(violations) {
32
32
  return violations.filter((violation) => !SOFT_LAYOUT_CLASSIFICATIONS.has(violation.classification));
33
33
  }
34
- /** Child-table (Sheet 201) column keys, which must live on `columns`, never in rows. */
34
+ /**
35
+ * Child-table (Sheet 201) column keys. These normally live on the 201 control's
36
+ * `columns`; a key here is NOT by itself proof of a leak, because the same code
37
+ * can legitimately be a TOP-LEVEL control of this form (a main-table field that
38
+ * shares a child column's code — issue 2026-11-25 A2). The control map's own
39
+ * keys are the ledger that disambiguates; see `validateFormLayoutShape`.
40
+ */
35
41
  function childColumnKeys(attrs) {
36
42
  const keys = new Set();
37
43
  for (const control of Object.values(attrs)) {
@@ -51,7 +57,8 @@ function childColumnKeys(attrs) {
51
57
  * on string". Healthy platform forms carry object options only (0/43 sampled).
52
58
  * - a non-string viewJson cell.
53
59
  * - a child-table column key used as a layout row (child keys stay on the 201
54
- * control's `columns`).
60
+ * control's `columns`) — but only when that code is NOT also a top-level
61
+ * control of this form (see below).
55
62
  * Tolerant of a one-sided layout (only rows or only attributes supplied).
56
63
  */
57
64
  export function validateFormLayoutShape(rows, attributes) {
@@ -78,9 +85,17 @@ export function validateFormLayoutShape(rows, attributes) {
78
85
  });
79
86
  const childKeys = childColumnKeys(attrs);
80
87
  if (childKeys.size > 0) {
81
- const leaked = [...new Set(rows.flat().filter((cell) => typeof cell === "string" && childKeys.has(cell)))];
88
+ // A layout row is rendered ONLY when its cell is a key of the top-level
89
+ // control map: the renderer resolves each cell via `controls[k]` and
90
+ // drops unknown keys (`cloudpivot-form/renderer/components/
91
+ // form-renderer-helper.ts:503-515` mapAndFilter; group detection uses the
92
+ // same lookup at :1383-1391). So a code registered as a control here is a
93
+ // legal row even when the same code is also listed as a 201 column — the
94
+ // main-table-field/child-column name collision from issue 2026-11-25 A2.
95
+ // Only "not a top-level control AND a 201 column" is a child-column leak.
96
+ const leaked = [...new Set(rows.flat().filter((cell) => typeof cell === "string" && childKeys.has(cell) && !Object.prototype.hasOwnProperty.call(attrs, cell)))];
82
97
  if (leaked.length > 0)
83
- violations.push({ classification: "child_column_in_rows", field: leaked.join("、"), message: `子表列 key 不能进 viewJson(应只挂在 201 控件的 columns 上):${leaked.join("、")}` });
98
+ violations.push({ classification: "child_column_in_rows", field: leaked.join("、"), message: `子表列 key 不能进 viewJson(控件表里没有同名顶层控件,应只挂在 201 控件的 columns 上):${leaked.join("、")}` });
84
99
  }
85
100
  }
86
101
  return violations;
@@ -876,13 +876,36 @@ export async function lintFormPublishReadOnly(session, args) {
876
876
  note: "降级门与真写同一函数;alreadyPublished:true 时真写会短路(不改发布面)",
877
877
  };
878
878
  }
879
+ /** A3 (issue 2026-11-25): the non-layout args that make a no-layout write an explicit, bounded intent. */
880
+ function hasExplicitDraftIntent(args) {
881
+ const nonEmpty = (value) => Array.isArray(value) && value.length > 0;
882
+ if (args.rebuild === true || args.refreshFromFields === true)
883
+ return true;
884
+ if (nonEmpty(args.fieldCodes) || nonEmpty(args.childColumns))
885
+ return true;
886
+ if (typeof args.draftHtmlJson === "string" && args.draftHtmlJson.trim() !== "")
887
+ return true;
888
+ if (nonEmpty(args.buttons) || nonEmpty(args.buttonScripts) || nonEmpty(args.removeButtonCodes))
889
+ return true;
890
+ return typeof args.customButtonJson === "string" && args.customButtonJson.trim() !== "";
891
+ }
879
892
  /**
880
- * Shared form.draft write body — read the current sheet, compose a scaffold
881
- * from published fields when the form is empty, and POST the proven payload
882
- * to bizsheet/update. Used by the form.draft write tool AND by configure_form,
883
- * so the high-level orchestrator never bypasses the scaffold.
893
+ * Ticket 74 + A3 (issue 2026-11-25) pure gate (no session, zero wire):
894
+ * 1. caller-provided "[]"/"{}" face → `form-empty-layout`;
895
+ * 2. BOTH layout faces absent and no other explicit draft intent →
896
+ * `form-draft-empty-layout`.
897
+ *
898
+ * (2) is the A3 incident: `form.draft --args '{"schemaCode":"m"}'` carries no
899
+ * layout intent at all, so the executor falls back to the stored draft — and
900
+ * when that draft is empty (the platform designer's Save is not lossless, and
901
+ * `draftViewJson` may even be "") it re-scaffolds from fields, silently
902
+ * dropping every non-field control (approval-info widgets, HTML, buttons'
903
+ * layout). dry-run reads no environment, so it cannot tell whether the stored
904
+ * draft is empty; it must refuse before any wire call instead of promising
905
+ * `wouldChange:true`. One layout face alone IS a legitimate partial update, and
906
+ * explicit intents (rebuild / refreshFromFields / fieldCodes / childColumns /
907
+ * draftHtmlJson / button edits) stay allowed.
884
908
  */
885
- /** Ticket 74 pure gate (no session): caller-provided "[]"/"{}" layouts refuse. */
886
909
  export function refuseEmptyCallerLayout(args) {
887
910
  if (args.allowEmptyLayout === true)
888
911
  return;
@@ -891,15 +914,30 @@ export function refuseEmptyCallerLayout(args) {
891
914
  emptyFaces.push("draftViewJson");
892
915
  if (typeof args.draftAttributesJson === "string" && isEmptyLayoutJson(args.draftAttributesJson))
893
916
  emptyFaces.push("draftAttributesJson");
894
- if (emptyFaces.length === 0)
917
+ if (emptyFaces.length > 0) {
918
+ throw new ToolRefusalError({
919
+ status: "refused",
920
+ blocker: "form-empty-layout",
921
+ schemaCode: args.schemaCode,
922
+ sheetCode: args.sheetCode,
923
+ faces: emptyFaces,
924
+ message: `显式提供的 ${emptyFaces.join("、")} 是空布局("[]"/"{}")——平台设计器 Save 会把草稿清成该形态(非无损),照写会丢控件。若确要清空布局请显式传 allowEmptyLayout:true;若是设计器 Save 后的修复,先用表单版本历史(/api/api/app/bizsheet/history/list)取回完好版本原文再写回`,
925
+ });
926
+ }
927
+ if (args.draftViewJson !== undefined || args.draftAttributesJson !== undefined)
928
+ return;
929
+ if (hasExplicitDraftIntent(args))
895
930
  return;
896
931
  throw new ToolRefusalError({
897
932
  status: "refused",
898
- blocker: "form-empty-layout",
933
+ blocker: "form-draft-empty-layout",
899
934
  schemaCode: args.schemaCode,
900
935
  sheetCode: args.sheetCode,
901
- faces: emptyFaces,
902
- message: `显式提供的 ${emptyFaces.join("、")} 是空布局("[]"/"{}")——平台设计器 Save 会把草稿清成该形态(非无损),照写会丢控件。若确要清空布局请显式传 allowEmptyLayout:true;若是设计器 Save 后的修复,先用表单版本历史(/api/api/app/bizsheet/history/list)取回完好版本原文再写回`,
936
+ missingFaces: ["draftViewJson", "draftAttributesJson"],
937
+ message: "没有 draftViewJson / draftAttributesJson:这次调用没有任何布局意图。写入以环境里现存的草稿为准——草稿面为空(缺失、\"[]\"/\"{}\"、空串)时会按已发布字段重搭或落一份空/残布局,审批信息/HTML/按钮区等非字段控件全部消失,等于清空表单布局。平台不会替你把关:bizsheet/update 不校验空布局,publish 只校验数据项存在就把草稿原样提拔成发布面;dry-run 又不读环境,因此在任何 wire 之前拒绝。"
938
+ + "部分更新只传其中一个布局键即可(只传 draftAttributesJson 或只传 draftViewJson 都合法);确认按已发布字段整表重搭请显式传 rebuild:true;只刷新字段派生配置传 refreshFromFields:true。"
939
+ + `最小可用示例见 nextCommand(rebuild 重搭);带布局的写法:--args '{"schemaCode":"${args.schemaCode}","draftViewJson":"[[\\"name\\"]]","draftAttributesJson":"{\\"name\\":{\\"key\\":\\"name\\",\\"type\\":1,\\"options\\":{\\"name\\":\\"名称\\"}}}"}'`,
940
+ nextCommand: `omc call form.draft --args '{"schemaCode":"${args.schemaCode}","rebuild":true}'`,
903
941
  });
904
942
  }
905
943
  /**
@@ -1189,6 +1227,31 @@ export function customButtonJsonStoredShape(options) {
1189
1227
  return "absent";
1190
1228
  }
1191
1229
  export const CUSTOM_BUTTON_JSON_STRING_SHAPE_WARNING = "customButtonJson 被存为字符串(双重编码)——前端按钮不渲染,设计器形状=数组+actionConfig 对象(线上 #38);用 form.draft/form.publish 重写 buttons 即自愈";
1230
+ export function resolveEffectiveFormFace(input) {
1231
+ const { draftPresent, publishedPresent, inSync } = input;
1232
+ if (publishedPresent) {
1233
+ if (draftPresent && inSync === false)
1234
+ return {
1235
+ effectiveFace: "both",
1236
+ effectiveFaceNote: "线上=published 面;draft 有未发布改动,发布后才生效",
1237
+ };
1238
+ return {
1239
+ effectiveFace: "published",
1240
+ effectiveFaceNote: "线上=published 面(draft 为空或与发布面一致)",
1241
+ };
1242
+ }
1243
+ if (draftPresent)
1244
+ return {
1245
+ effectiveFace: "draft",
1246
+ effectiveFaceNote: "只有 draft 面,线上读不到(published*Json 为空),需 form.publish",
1247
+ };
1248
+ return {
1249
+ effectiveFace: "none",
1250
+ effectiveFaceNote: "两面皆空,线上不可读",
1251
+ };
1252
+ }
1253
+ /** 旗标与内容矛盾时的「以谁为准」一句话(B5;拼进 flagNote,不另开长键)。 */
1254
+ export const FORM_FLAG_AUTHORITY_NOTE = "以 faces/effectiveFace 为准:published*Json 内容才是运行时面,published/existDraft 旗标会滞后";
1192
1255
  /** The caller's buttons from a READ face (parsed array, or null when absent).
1193
1256
  * #39/#38: decodes BOTH stored forms — the designer's ARRAY (authoritative;
1194
1257
  * the read face used to be blind to it and answered null while the store
@@ -1210,6 +1273,12 @@ export function readFormButtons(options) {
1210
1273
  }
1211
1274
  return Array.isArray(parsed) ? parsed : null;
1212
1275
  }
1276
+ /**
1277
+ * Shared form.draft write body — read the current sheet, compose a scaffold
1278
+ * from published fields when the form is empty, and POST the proven payload
1279
+ * to bizsheet/update. Used by the form.draft write tool AND by configure_form,
1280
+ * so the high-level orchestrator never bypasses the scaffold.
1281
+ */
1213
1282
  export async function executeFormDraftWrite(session, args) {
1214
1283
  // 兼容别名:`fieldCodes:["items.category"]` 等价于
1215
1284
  // `childColumns:[{parent:"items",fieldCodes:["category"]}]`(issue #24)。
package/dist/graph.js CHANGED
@@ -62,6 +62,31 @@ export const GRAPH_SCHEMA_VERSION = "9";
62
62
  const STALE_LOCK_MS = 15 * 60 * 1000;
63
63
  export const DEFAULT_PULL_CONCURRENCY = 16;
64
64
  export const MAX_PULL_CONCURRENCY = 32;
65
+ /** B4:总超时(真机 `graph pull` 曾无输出挂起,只能手 kill)。 */
66
+ export const DEFAULT_GRAPH_PULL_TIMEOUT_MS = 120_000;
67
+ export const MAX_GRAPH_PULL_TIMEOUT_MS = 600_000;
68
+ /** B4:deadline 已过时,后续每一跳直接失败(由各面的 catch 记成 gap)。 */
69
+ class GraphPullDeadlineError extends Error {
70
+ constructor(path, deadline) {
71
+ super(`graph pull deadline exceeded before ${path} (deadline ${new Date(deadline).toISOString()})`);
72
+ this.name = "GraphPullDeadlineError";
73
+ }
74
+ }
75
+ /** B4:总超时抛出(索引未发布;lock/staging 由 withGraphPullLock 清理)。 */
76
+ export class GraphPullTimeoutError extends Error {
77
+ elapsedMs;
78
+ timeoutMs;
79
+ progressSnapshot;
80
+ constructor(elapsedMs, timeoutMs, progressSnapshot) {
81
+ super(`graph pull 超时(${Math.round(elapsedMs / 1000)}s ≥ ${Math.round(timeoutMs / 1000)}s):已完成 ${progressSnapshot.applicationsDone}/${progressSnapshot.applicationsTotal} 个应用`
82
+ + `${progressSnapshot.currentApplication !== undefined ? `(卡在 app=${progressSnapshot.currentApplication})` : ""};索引未发布。`
83
+ + `恢复:缩小范围重跑 \`--application-codes <a,b>\`,或显式放宽 \`--timeout-ms ${Math.min(timeoutMs * 2, MAX_GRAPH_PULL_TIMEOUT_MS)}\`。`);
84
+ this.elapsedMs = elapsedMs;
85
+ this.timeoutMs = timeoutMs;
86
+ this.progressSnapshot = progressSnapshot;
87
+ this.name = "GraphPullTimeoutError";
88
+ }
89
+ }
65
90
  /** 索引超过这个天数就提示刷新(配置类查询,1 天足够新)。 */
66
91
  export const STALE_INDEX_DAYS = 1;
67
92
  export const STALE_AFTER_MINUTES = STALE_INDEX_DAYS * 24 * 60;
@@ -559,12 +584,27 @@ export function extractFormEdges(schemaCode, sheet, knownFieldCodes) {
559
584
  * `datarule-list`) and vice versa (`rule-list`). Output is sorted so the
560
585
  * published DB is byte-stable regardless of completion order.
561
586
  */
562
- export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRENCY, requestedApplication, root) {
587
+ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRENCY, requestedApplication, root, hooks) {
563
588
  const identity = session.environmentFingerprint();
564
589
  const pulledAtIso = new Date().toISOString();
565
590
  const totalStart = Date.now();
566
591
  let listMs = 0;
567
592
  let readMs = 0;
593
+ // B4:进度行(stderr)+ 总超时倒计时。`appIndex` 让多应用轮次能打 3/13。
594
+ const appName = requestedApplication ?? session.profile.applicationCode ?? "(default)";
595
+ const appLabel = hooks?.appIndex !== undefined ? `${hooks.appIndex.index}/${hooks.appIndex.total} app=${appName}` : `app=${appName}`;
596
+ const progress = (stage) => hooks?.progress?.(`[graph] ${appLabel} ${stage}`);
597
+ /** Deadline-aware wire: every hop gets the remaining budget, never the full default. */
598
+ const wire = async (path, query) => {
599
+ if (hooks?.deadline !== undefined) {
600
+ const remaining = hooks.deadline - Date.now();
601
+ if (remaining <= 0)
602
+ throw new GraphPullDeadlineError(path, hooks.deadline);
603
+ return wireCall(session, { path, query, timeoutMs: remaining });
604
+ }
605
+ return wireCall(session, { path, query });
606
+ };
607
+ progress("phase=app-tree");
568
608
  // Model enumeration mirrors the governed `model.list` tool exactly: the
569
609
  // application tree flattened to BizModel rows. The bare `modelList` endpoint
570
610
  // returns EMPTY data on a real platform (works only against the fake face)
@@ -573,18 +613,19 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
573
613
  const scope = await resolveApplicationScope(session, requestedApplication).catch(() => undefined);
574
614
  const applicationCode = scope?.code ?? "";
575
615
  const gaps = [];
576
- const treeRows = flattenTreeRows(wireRows((await wireCall(session, { path: ENDPOINTS.applicationTree, query: { appCode: applicationCode } })).data));
616
+ const treeRows = flattenTreeRows(wireRows((await wire(ENDPOINTS.applicationTree, { appCode: applicationCode })).data));
577
617
  const modelEntities = treeRows.filter((row) => row.type === "BizModel" && typeof row.code === "string" && row.code !== "").map((row) => ({ schemaCode: String(row.code), name: String(row.name ?? row.code), applicationCode })).sort((a, b) => a.schemaCode.localeCompare(b.schemaCode));
618
+ progress(`phase=models models=${modelEntities.length}`);
578
619
  const schemaCodes = modelEntities.map((row) => row.schemaCode);
579
620
  const fields = [];
580
621
  const services = [];
581
622
  await Promise.all(schemaCodes.map(async (schemaCode) => {
582
623
  try {
583
- let rows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish: "true" } })).data);
624
+ let rows = wireRows((await wire(ENDPOINTS.fieldList, { schemaCode, isPublish: "true" })).data);
584
625
  // Several applications expose fields only on the draft face. An empty
585
626
  // published response is not evidence that the model has no fields.
586
627
  if (rows.length === 0)
587
- rows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish: "false" } })).data);
628
+ rows = wireRows((await wire(ENDPOINTS.fieldList, { schemaCode, isPublish: "false" })).data);
588
629
  if (rows.length === 0)
589
630
  gaps.push({ kind: "field-list", ref: schemaCode, note: "published and draft faces are empty" });
590
631
  for (const row of rows) {
@@ -597,6 +638,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
597
638
  gaps.push({ kind: "field-list", ref: schemaCode, note: error instanceof Error ? error.message : String(error) });
598
639
  }
599
640
  }));
641
+ progress(`phase=fields fields=${fields.length}`);
600
642
  // r75:form 控件边按「码在该模型 fieldList 里」过滤——这里是已知字段的按模型
601
643
  // 索引(fields 收集在上面 await 完成,此时已齐)。
602
644
  const knownFields = new Map();
@@ -606,8 +648,8 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
606
648
  knownFields.set(field.schemaCode, codes);
607
649
  }
608
650
  try {
609
- await wireCall(session, { path: ENDPOINTS.bizServiceCategoryList });
610
- const rows = wireRows((await wireCall(session, { path: ENDPOINTS.bizServiceListByCategoryId, query: { categoryId: "" } })).data);
651
+ await wire(ENDPOINTS.bizServiceCategoryList, {});
652
+ const rows = wireRows((await wire(ENDPOINTS.bizServiceListByCategoryId, { categoryId: "" })).data);
611
653
  for (const row of rows) {
612
654
  const code = String(row.code ?? "");
613
655
  if (code)
@@ -617,6 +659,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
617
659
  catch (error) {
618
660
  gaps.push({ kind: "service-list", ref: "all", note: error instanceof Error ? error.message : String(error) });
619
661
  }
662
+ progress(`phase=services services=${services.length}`);
620
663
  const rules = [];
621
664
  const edges = [];
622
665
  let parseFailures = 0;
@@ -639,6 +682,9 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
639
682
  resolveAll();
640
683
  };
641
684
  const submit = (task) => {
685
+ // B4:deadline 已过就不再排新任务(在途的会被 timeoutMs 收紧的请求自己结束)。
686
+ if (hooks?.deadline !== undefined && Date.now() >= hooks.deadline)
687
+ return;
642
688
  inflight += 1;
643
689
  void (async () => {
644
690
  await semaphore.acquire();
@@ -663,7 +709,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
663
709
  let rows = [];
664
710
  let ruleListOk = true;
665
711
  try {
666
- rows = wireRows((await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode } })).data);
712
+ rows = wireRows((await wire(ENDPOINTS.businessRuleListBySchemaCode, { schemaCode })).data);
667
713
  }
668
714
  catch (error) {
669
715
  ruleListOk = false;
@@ -671,7 +717,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
671
717
  }
672
718
  let dataruleRows = [];
673
719
  try {
674
- dataruleRows = wireRows((await wireCall(session, { path: ENDPOINTS.dataRuleList, query: { schemaCode } })).data);
720
+ dataruleRows = wireRows((await wire(ENDPOINTS.dataRuleList, { schemaCode })).data);
675
721
  dataruleCount += dataruleRows.length;
676
722
  for (const row of dataruleRows)
677
723
  edges.push(...extractDataRuleEdges(schemaCode, row).map((edge) => ({ ...edge, applicationCode })));
@@ -680,7 +726,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
680
726
  gaps.push({ kind: "datarule-list", ref: schemaCode, note: error instanceof Error ? error.message : String(error) });
681
727
  }
682
728
  try {
683
- const views = wireRows((await wireCall(session, { path: ENDPOINTS.listQueryList, query: { schemaCode, clientType: "PC" } })).data);
729
+ const views = wireRows((await wire(ENDPOINTS.listQueryList, { schemaCode, clientType: "PC" })).data);
684
730
  for (const view of views) {
685
731
  const viewCode = typeof view.code === "string" ? view.code : "";
686
732
  if (viewCode === "")
@@ -696,8 +742,8 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
696
742
  // isWorkflowAbsent 同语义——该函数未导出,这里局部判定)。读失败记
697
743
  // workflow-read gap,不静默。
698
744
  try {
699
- if ((await wireCall(session, { path: ENDPOINTS.workflowIsWorkflow, query: { schemaCode } })).data === true) {
700
- const linked = (await wireCall(session, { path: ENDPOINTS.workflowGetBySchema, query: { schemaCode } })).data;
745
+ if ((await wire(ENDPOINTS.workflowIsWorkflow, { schemaCode })).data === true) {
746
+ const linked = (await wire(ENDPOINTS.workflowGetBySchema, { schemaCode })).data;
701
747
  const workflowCode = linked !== null && typeof linked.workflowCode === "string" && linked.workflowCode !== "" ? linked.workflowCode : "";
702
748
  if (workflowCode === "") {
703
749
  gaps.push({ kind: "workflow-read", ref: schemaCode, note: "isworkflow=true 但 getWorkflow 未返回 workflowCode" });
@@ -707,7 +753,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
707
753
  //(发布标记不阻断采集,草稿独有差异不追——见 r75 调查报告)。
708
754
  let published = null;
709
755
  try {
710
- published = (await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode } })).data;
756
+ published = (await wire(ENDPOINTS.workflowGetPublished, { workflowCode })).data;
711
757
  }
712
758
  catch (error) {
713
759
  if (!(error instanceof WireError && error.kind === "business" && error.errcode === 401001))
@@ -727,7 +773,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
727
773
  // 表单」的模型回 data:null——缺席不是缺口。多表单模型的其它槽位
728
774
  //(sheetCode≠schemaCode)无清单端点,只扫默认槽(GRAPH_COVERAGE.note 声明)。
729
775
  try {
730
- const sheet = (await wireCall(session, { path: ENDPOINTS.sheetGet, query: { schemaCode, sheetCode: schemaCode } })).data;
776
+ const sheet = (await wire(ENDPOINTS.sheetGet, { schemaCode, sheetCode: schemaCode })).data;
731
777
  if (sheet !== null) {
732
778
  formCount += 1;
733
779
  edges.push(...extractFormEdges(schemaCode, sheet, knownFields.get(schemaCode) ?? new Set()).map((edge) => ({ ...edge, applicationCode })));
@@ -757,7 +803,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
757
803
  const runRuleRead = async (schemaCode, ruleCode, ruleId) => {
758
804
  const start = Date.now();
759
805
  try {
760
- const record = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id: ruleId } })).data;
806
+ const record = (await wire(ENDPOINTS.businessRuleGet, { id: ruleId })).data;
761
807
  if (!record) {
762
808
  gaps.push({ kind: "rule-get", ref: `${schemaCode}/${ruleCode}`, note: "empty readback" });
763
809
  return;
@@ -792,7 +838,7 @@ export async function pullRuleGraph(session, concurrency = DEFAULT_PULL_CONCURRE
792
838
  };
793
839
  const runListViewRead = async (schemaCode, viewCode) => {
794
840
  try {
795
- const got = (await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode, code: viewCode, clientType: "PC" } })).data;
841
+ const got = (await wire(ENDPOINTS.listQueryGet, { schemaCode, code: viewCode, clientType: "PC" })).data;
796
842
  if (got === null || !got.id) {
797
843
  gaps.push({ kind: "listview-get", ref: `${schemaCode}/${viewCode}`, note: "empty readback" });
798
844
  return;
@@ -923,26 +969,102 @@ async function withGraphPullLock(dbPath, run) {
923
969
  }
924
970
  /** Wholesalerebuild + atomic publish (staging file + rename), 0600. */
925
971
  export async function publishGraphPull(session, concurrency = DEFAULT_PULL_CONCURRENCY, options = {}) {
972
+ // B4(0.8.4):总超时 + 进度行(默认 stderr)。真机 `graph pull` 曾「进程存活、
973
+ // CPU 0.28、输出为空、无超时」——agent 只能手 kill,再 `graph status` 拿
974
+ // graph-index-absent。这里:默认 120s 总超时(`--timeout-ms` 覆盖)、每应用
975
+ // start/done/failed 一行到 stderr(stdout 仍是单信封)、单应用失败只进
976
+ // failedApps[] 不拖垮整轮(成功部分照常发布,CLI 以 partial/退出码 1 说明)。
977
+ const timeoutMs = options.timeoutMs ?? DEFAULT_GRAPH_PULL_TIMEOUT_MS;
978
+ const progress = options.progress ?? ((line) => { process.stderr.write(`${line}\n`); });
979
+ const snapshot = { applicationsDone: 0, applicationsTotal: 0 };
926
980
  // The environment decides the file: one project can index `test` and `prod`
927
981
  // side by side, so the target is not known until the session resolves.
928
982
  const dbPath = graphDbPath(options.root, session.environmentName);
929
983
  try {
930
984
  return await withGraphPullLock(dbPath, async () => {
931
985
  const requested = options.applicationCodes?.length ? options.applicationCodes : [undefined];
932
- const parts = await Promise.all(requested.map((application) => pullRuleGraph(session, concurrency, application, options.root)));
933
- const first = parts[0];
934
- const data = parts.length === 1 ? first : {
935
- ...first,
936
- meta: { ...first.meta, applicationCode: "*", applicationResolution: { code: "*", source: "wildcard" }, coverage: { applicationCodes: parts.flatMap((part) => part.meta.coverage.applicationCodes), tenantApplications: parts.flatMap((part) => part.meta.coverage.applicationCodes) } },
937
- rules: parts.flatMap((part) => part.rules),
938
- edges: parts.flatMap((part) => part.edges),
939
- models: parts.flatMap((part) => part.models),
940
- fields: parts.flatMap((part) => part.fields),
941
- services: parts.flatMap((part) => part.services),
942
- gaps: parts.flatMap((part) => part.gaps),
943
- scanned: parts.reduce((sum, part) => ({ models: sum.models + part.scanned.models, rules: sum.rules + part.scanned.rules, datarules: sum.datarules + part.scanned.datarules, views: sum.views + part.scanned.views, workflows: sum.workflows + part.scanned.workflows, forms: sum.forms + part.scanned.forms, parseFailures: sum.parseFailures + part.scanned.parseFailures }), { models: 0, rules: 0, datarules: 0, views: 0, workflows: 0, forms: 0, parseFailures: 0 }),
944
- timings: { listMs: parts.reduce((n, part) => n + part.timings.listMs, 0), readMs: parts.reduce((n, part) => n + part.timings.readMs, 0), totalMs: parts.reduce((n, part) => n + part.timings.totalMs, 0) },
945
- };
986
+ snapshot.applicationsTotal = requested.length;
987
+ const startedAt = Date.now();
988
+ const deadline = startedAt + timeoutMs;
989
+ let timer;
990
+ const timeout = new Promise((_, reject) => {
991
+ timer = setTimeout(() => {
992
+ // 断掉在途 fetch(真实会话):否则 race 丢掉 pull 协程后 socket 仍挂着,
993
+ // 进程继续「活着没输出」——正是真机形态。注入 adapter 的测试里是 no-op。
994
+ session.abortInFlight("graph-pull-timeout");
995
+ reject(new GraphPullTimeoutError(Date.now() - startedAt, timeoutMs, { ...snapshot }));
996
+ }, Math.max(1, timeoutMs));
997
+ });
998
+ const pull = (async () => {
999
+ const parts = [];
1000
+ const failedApps = [];
1001
+ let firstError;
1002
+ for (let index = 0; index < requested.length; index += 1) {
1003
+ const application = requested[index];
1004
+ const label = application ?? session.profile.applicationCode ?? "(default)";
1005
+ snapshot.currentApplication = label;
1006
+ progress(`[graph] ${index + 1}/${requested.length} app=${label} start`);
1007
+ try {
1008
+ const part = await pullRuleGraph(session, concurrency, application, options.root, {
1009
+ deadline,
1010
+ progress,
1011
+ appIndex: { index: index + 1, total: requested.length },
1012
+ });
1013
+ parts.push(part);
1014
+ // B4:`applicationsDone` 是**成功**拉取数(超时回执说「已完成 N/M」
1015
+ // 时不能把失败应用也算进去,否则会出现「已完成 1/1(卡在 app=test)」)。
1016
+ snapshot.applicationsDone = parts.length;
1017
+ progress(`[graph] ${index + 1}/${requested.length} app=${label} done models=${part.scanned.models} rules=${part.scanned.rules} edges=${part.edges.length} ${(part.timings.totalMs / 1000).toFixed(1)}s`);
1018
+ }
1019
+ catch (error) {
1020
+ firstError ??= error;
1021
+ const reason = (error instanceof Error ? error.message : String(error)).slice(0, 300);
1022
+ failedApps.push({ applicationCode: label, reason });
1023
+ progress(`[graph] ${index + 1}/${requested.length} app=${label} failed err=${reason}`);
1024
+ }
1025
+ }
1026
+ // 全部失败 = 整轮失败(保留原来的 uncertain 语义);部分失败仍发布索引。
1027
+ if (parts.length === 0)
1028
+ throw firstError ?? new Error("graph pull failed for every requested application");
1029
+ const first = parts[0];
1030
+ const data = parts.length === 1 && failedApps.length === 0 ? first : {
1031
+ ...first,
1032
+ meta: { ...first.meta, applicationCode: failedApps.length === 0 && parts.length > 1 ? "*" : (parts.length === 1 ? first.meta.applicationCode : "*"), applicationResolution: parts.length > 1 ? { code: "*", source: "wildcard" } : first.meta.applicationResolution, coverage: { applicationCodes: parts.flatMap((part) => part.meta.coverage.applicationCodes), tenantApplications: parts.flatMap((part) => part.meta.coverage.applicationCodes) } },
1033
+ rules: parts.flatMap((part) => part.rules),
1034
+ edges: parts.flatMap((part) => part.edges),
1035
+ models: parts.flatMap((part) => part.models),
1036
+ fields: parts.flatMap((part) => part.fields),
1037
+ services: parts.flatMap((part) => part.services),
1038
+ gaps: parts.flatMap((part) => part.gaps),
1039
+ ...(failedApps.length > 0 ? { failedApps } : {}),
1040
+ scanned: parts.reduce((sum, part) => ({ models: sum.models + part.scanned.models, rules: sum.rules + part.scanned.rules, datarules: sum.datarules + part.scanned.datarules, views: sum.views + part.scanned.views, workflows: sum.workflows + part.scanned.workflows, forms: sum.forms + part.scanned.forms, parseFailures: sum.parseFailures + part.scanned.parseFailures }), { models: 0, rules: 0, datarules: 0, views: 0, workflows: 0, forms: 0, parseFailures: 0 }),
1041
+ timings: { listMs: parts.reduce((n, part) => n + part.timings.listMs, 0), readMs: parts.reduce((n, part) => n + part.timings.readMs, 0), totalMs: parts.reduce((n, part) => n + part.timings.totalMs, 0) },
1042
+ };
1043
+ return data;
1044
+ })();
1045
+ // 超时先赢时 pull 仍在跑:挂一个空的 catch,避免 unhandled rejection。
1046
+ pull.catch(() => undefined);
1047
+ let data;
1048
+ try {
1049
+ data = await Promise.race([pull, timeout]);
1050
+ }
1051
+ catch (error) {
1052
+ // 超时与 pull 的 deadline 检查是两条路径,谁先到都必须回**同一个**
1053
+ // graph-pull-timeout 语义。CPU 被占满时(全量测试并发、宿主负载),
1054
+ // pull 的微任务先恢复、`Date.now() >= deadline` 先命中,会抛内部
1055
+ // GraphPullDeadlineError;直接漏出去会让 CLI 走 emitThrown → code=internal
1056
+ // /exit 15,丢掉 blocker、已拉数量与恢复指引(真机 --timeout-ms 的可见
1057
+ // 症状就是不稳定的「内部错误」而不是超时)。
1058
+ if (error instanceof GraphPullDeadlineError) {
1059
+ throw new GraphPullTimeoutError(Date.now() - startedAt, timeoutMs, { ...snapshot });
1060
+ }
1061
+ throw error;
1062
+ }
1063
+ finally {
1064
+ if (timer)
1065
+ clearTimeout(timer);
1066
+ }
1067
+ progress(`[graph] publish env=${session.environmentName} apps=${data.meta.coverage.applicationCodes.length}${data.failedApps !== undefined && data.failedApps.length > 0 ? ` failedApps=${data.failedApps.length}` : ""}`);
946
1068
  const staging = `${dbPath}.staging-${process.pid}`;
947
1069
  rmSync(staging, { force: true });
948
1070
  const DatabaseSyncCtor = nodeSqlite().DatabaseSync;
package/dist/lanes/app.js CHANGED
@@ -10,7 +10,7 @@ import { defineTool, ToolRefusalError } from "../tool-types.js";
10
10
  import { wireCall, wireDownloadPackageStream, wireRows, WireError } from "../wire.js";
11
11
  import { isWithinRoot } from "../artifacts.js";
12
12
  import { readZipEntries } from "../zip.js";
13
- import { resolveApplicationScope } from "../support.js";
13
+ import { resolveApplicationScope, mapBounded } from "../support.js";
14
14
  import { APP_LANE_CONTRACT } from "./app-contract.js";
15
15
  import { readAppTree } from "./folder.js";
16
16
  const APP_LANE = APP_LANE_CONTRACT.lane;
@@ -299,12 +299,30 @@ export function registerAppLane(tools) {
299
299
  description: APP_TOOLS["app.list"].description,
300
300
  inputSchema: { environment: environmentArg, capability: capabilityArg },
301
301
  handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
302
- const applications = await Promise.all(wireRows((await wireCall(session, { path: ENDPOINTS.applicationList, query: {} })).data).map(async (row) => {
302
+ const rows = wireRows((await wireCall(session, { path: ENDPOINTS.applicationList, query: {} })).data);
303
+ // B3(0.8.4 真机):旧实现是 `Promise.all` **无界**扇出——每个应用一条
304
+ // `/apppackage/trees`,13 个应用=13 条并发(每跳后端还会 bindWorkflow 递归
305
+ // 查流程模板)。真机同会话 `model.list --allApplications`(同一 list 端点、
306
+ // trees 并发限 4)全正常,只有 app.list 连续 8 次 `fetch failed`。
307
+ // 并发限到 4(与 model.list 同口径),并让**单个应用**失败只进 failed[],
308
+ // 不再拖垮整条读。全部失败才抛(读面回 uncertain + 端点/分类诊断)。
309
+ const failed = [];
310
+ let firstError;
311
+ const applications = await mapBounded(rows, 4, async (row) => {
303
312
  const code = String(row.appCode ?? row.code);
304
- const tree = await readAppTree(session, code);
305
- const modelCount = tree.reduce((count, node) => count + (node.type === "BizModel" ? 1 : 0), 0);
306
- return { code, name: row.appName ?? row.name, groupId: row.groupId, modelCount };
307
- }));
313
+ try {
314
+ const tree = await readAppTree(session, code);
315
+ const modelCount = tree.reduce((count, node) => count + (node.type === "BizModel" ? 1 : 0), 0);
316
+ return { code, name: row.appName ?? row.name, groupId: row.groupId, modelCount };
317
+ }
318
+ catch (error) {
319
+ firstError ??= error;
320
+ failed.push({ applicationCode: code, reason: (error instanceof Error ? error.message : String(error)).slice(0, 300) });
321
+ return { code, name: row.appName ?? row.name, groupId: row.groupId };
322
+ }
323
+ });
324
+ if (failed.length > 0 && failed.length === rows.length)
325
+ throw firstError;
308
326
  // r29f F2:与 discover_environment 同构——一眼判断「内联是否全集」。
309
327
  // 应用通常个位数,默认内联 + omitted:false;大租户由 governedRead 外置时
310
328
  // 仍保留 applicationsCount,并由 diet 路径标 omitted。
@@ -312,6 +330,14 @@ export function registerAppLane(tools) {
312
330
  applications,
313
331
  applicationsCount: applications.length,
314
332
  omitted: false,
333
+ ...(failed.length > 0
334
+ ? {
335
+ applicationsFailed: failed.length,
336
+ failed,
337
+ partial: true,
338
+ hint: `${failed.length}/${applications.length} 个应用的目录树读取失败(见 failed[]):applications 清单仍完整,但这些应用的 modelCount 缺失;先按 reason 重查或走 model.list --allApplications。`,
339
+ }
340
+ : {}),
315
341
  };
316
342
  }, {
317
343
  target: "app.list",
@@ -321,6 +347,8 @@ export function registerAppLane(tools) {
321
347
  applicationsCount: apps.length,
322
348
  omitted: true,
323
349
  applications: apps.slice(0, 20),
350
+ // B3:部分失败是结论本身(哪个应用读不到),diet 不得吞掉。
351
+ ...(result.applicationsFailed !== undefined ? { applicationsFailed: result.applicationsFailed, failed: result.failed, partial: true, hint: result.hint } : {}),
324
352
  tablesHint: "applications 已截断内联前 20 条(omitted:true);全集在 detailArtifactId,用 --jq applications[].code 或 artifact get 取回。",
325
353
  };
326
354
  },