@stalfh233/omc-cli 0.6.54 → 0.6.55

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.
@@ -1313,7 +1313,7 @@
1313
1313
  "capability": "Application package (app) lifecycle: list, create, update (group move), admin delete",
1314
1314
  "status": "executable",
1315
1315
  "scope": "Application package list create update delete absence",
1316
- "excluded_or_unsupported_reason": "Design-time test environments only; production environments permanently refuse writes. App publish and environment-wide release remain unsupported boundary items.",
1316
+ "excluded_or_unsupported_reason": "Design-time test environments only; production environments permanently refuse writes. App PUBLISH stays an out-of-boundary manual designer action (publish is not modelled as a CLI write); app-package and environment-wide export ARE covered by the r64b item below (read-only).",
1317
1317
  "version_family": "8.6",
1318
1318
  "anchor_version": "8.6.26",
1319
1319
  "evidence": [
@@ -1340,6 +1340,34 @@
1340
1340
  "app package delete absence"
1341
1341
  ]
1342
1342
  },
1343
+ {
1344
+ "capability": "r64b application package export",
1345
+ "status": "executable",
1346
+ "scope": "App package export (single app) and environment-wide lifecycle export (all app packages + app groups + biz services + datasources), binary ZIP landed with bytes/sha256/entry/asset readback",
1347
+ "version_family": "8.6",
1348
+ "anchor_version": "8.6.26",
1349
+ "evidence": [
1350
+ {
1351
+ "path": "packages/omc-cli/src/lanes/app.ts",
1352
+ "anchor": "app.export"
1353
+ },
1354
+ {
1355
+ "path": "packages/omc-cli/test/r64b-app-export.test.ts",
1356
+ "anchor": "contract tests"
1357
+ },
1358
+ {
1359
+ "path": "packages/omc-cli/src/wire.ts",
1360
+ "anchor": "wireDownloadPackageStream (ZIP stream vs HTTP-200 JSON refusal)"
1361
+ }
1362
+ ],
1363
+ "lane": "app-management",
1364
+ "tools": [
1365
+ "app.export"
1366
+ ],
1367
+ "scopes": [
1368
+ "app package export"
1369
+ ]
1370
+ },
1343
1371
  {
1344
1372
  "capability": "R1 report page and BI chart lifecycle",
1345
1373
  "status": "executable",
@@ -1544,4 +1572,4 @@
1544
1572
  "revision_note": "r64(2026-11-14)新增:用户需求的流程运维三件套,真机全链实证(workflow_operation approval 对象形状 / adjust_workItem=加签面 / finish=正常完结语义)。定位=测试提速:运维过的实例不能用于真实流程/权限验证。"
1545
1573
  }
1546
1574
  ]
1547
- }
1575
+ }
@@ -32,11 +32,11 @@ const SURFACES = [
32
32
  id: "app",
33
33
  title: "应用包(app)",
34
34
  lane: LANES.app,
35
- description: "应用包(app.*)生命周期:列出、创建、更新(分组移动)、admin 删除。不是应用内的目录节点——目录用 folder。",
36
- operations: ["create", "update", "delete"],
35
+ description: "应用包(app.*)生命周期:列出、创建、更新(分组移动)、admin 删除、应用包导出(单应用/整环境备份)。不是应用内的目录节点——目录用 folder。",
36
+ operations: ["create", "update", "delete", "export"],
37
37
  requires: [],
38
38
  intent: { level: "none", note: "未覆盖;用 omc call app.*。" },
39
- notes: "环境已带默认 applicationCode,建模不必先建应用。新建应用平台会自动塞一个默认分组(folder.isDefault);有模型/报表等非目录节点时 app.delete 拒 app-not-empty。",
39
+ notes: "环境已带默认 applicationCode,建模不必先建应用。新建应用平台会自动塞一个默认分组(folder.isDefault);有模型/报表等非目录节点时 app.delete 拒 app-not-empty。r64b 导出:省略 applicationCode = 环境级生命周期包(全部应用包+应用分组+业务集成+数据源;平台固定空 references,环境级字典/组织/角色不在包内);指定 applicationCode = 单应用包,includeDependencies 可把引用的字典/角色/业务集成/数据源一起打进去。ZIP 同步返回,工具核 PK 头与条目数后落盘并回 bytes/sha256;平台无按资产类型筛选参数。",
40
40
  },
41
41
  {
42
42
  id: "folder",
package/dist/endpoints.js CHANGED
@@ -11,6 +11,38 @@ export const ENDPOINTS = {
11
11
  applicationUpdate: "/api/api/app/apppackage/update",
12
12
  applicationDelete: "/api/api/app/apppackage/delete",
13
13
  applicationTree: "/api/api/app/apppackage/trees",
14
+ /**
15
+ * App package export/import (AppImportExportController, decompiled
16
+ * AI-Platform-v1.1.25 / 8.6 family: @RequestMapping("/api/app/apppackage")
17
+ * + @PostMapping("/export")). exportApp(AppExportParamVO) streams a ZIP
18
+ * (Content-Type application/octet-stream); refusals still arrive HTTP 200 +
19
+ * JSON envelope (10005 应用编码不能为空 / 600005 应用不存在!). body:
20
+ * {appCode, references:{relativeDictionary, relativeRole,
21
+ * relativeBizService, relativeAdvanceDataSource,
22
+ * relativeReportAdvanceDataSource}}; the five keys are exactly the design
23
+ * UI's refTabsKey selection (admin bundle exportApp → {appCode, references}).
24
+ *
25
+ * The dependency picker reads GET /dependencies?appCode= (live 1.1.25:
26
+ * relativeApps/relativeSchemas/relativeDepartment/relativeUser/relativeRole/
27
+ * relativeDictionary/relativeBizService/relativeEnvironment/relativeAppPage/
28
+ * relativeDashboard/relativeAdvanceDataSource/relativeReportAdvanceDataSource/
29
+ * inheritSchemas/templateSchema/relativeCustomPage).
30
+ */
31
+ appPackageExport: "/api/api/app/apppackage/export",
32
+ appPackageDependencies: "/api/api/app/apppackage/dependencies",
33
+ /**
34
+ * Environment-wide lifecycle export (LifeCycleImportExportController:
35
+ * @RequestMapping("/api/lifeCycle/apppackage") + @PostMapping
36
+ * ("/lifeCycleExport")). LifeCycleIEFacadeImpl.exportLifeCycle enumerates
37
+ * getAppPackageListByDeleteStatus(false) and writes every app package under
38
+ * metadata/app/applist/<appCode>/, plus appgroup.json, ALL biz services
39
+ * (metadata/bizservice/manifest.json + servicegroup.json), datasources, and
40
+ * the root metadata/manifest.json; the zipped download is named
41
+ * metadata.zip. body {name?,version?,description?,author?} (all optional —
42
+ * the root manifest still carries the platform lifecycle version); GET
43
+ * answers 40007 请求方法不正确. There is no per-app or per-asset filter.
44
+ */
45
+ environmentLifeCycleExport: "/api/api/lifeCycle/apppackage/lifeCycleExport",
14
46
  modelList: "/api/api/app/bizmodels/list_schema",
15
47
  modelGet: "/api/api/app/bizmodels/get_all",
16
48
  modelCreate: "/api/api/app/bizmodels/create",
@@ -1,5 +1,5 @@
1
1
  import { FIELD_PROPERTY_TYPES } from "./field-families.js";
2
- import { assertFormConditions, assertNumericalScale, assertFieldOptionsAllowed, buildChildTableSubSchema, buildFieldOptions, ensureRelationDisplayFieldOptions, normalizeFieldPropertyType, optionShapeFamily, relationDisplayFieldCode, withLegacyOptionSetKeys, } from "./field-families.js";
2
+ import { assertFormConditions, assertNumericalScale, assertFieldOptionsAllowed, buildChildTableSubSchema, buildFieldOptions, canonicalNumericalFormat, ensureRelationDisplayFieldOptions, normalizeFieldPropertyType, optionShapeFamily, relationDisplayFieldCode, withLegacyOptionSetKeys, } from "./field-families.js";
3
3
  import { nameI18nJson } from "./field-families.js";
4
4
  import { decodeJsonObjectColumn } from "./json-column.js";
5
5
  import { normalizeFormConditionOptions } from "./lanes/datarule-protocol.js";
@@ -38,6 +38,25 @@ function assertRelationTargetPresent(propertyType, options, relativeCode, code)
38
38
  message: "关联字段缺少目标模型:options.schemaCode 与顶层 relativeCode 都为空。平台建字段时接受它,但 field.publish 会以 300010『数据模型编码不能为空』拒绝,之后该列不可用。请传 relativeCode:'<目标模型code>'(工具会自动补全 options.schemaCode/queryCode),或在 options 里直接给 schemaCode",
39
39
  });
40
40
  }
41
+ /**
42
+ * r64b (live 2026-11-14): NUMERICAL `options.format` is read LITERALLY by the
43
+ * runtime — a semantic word (`percent`, `currency`, `¥`) stored on the field
44
+ * row is not understood and the portal renders the raw decimal. Canonicalise at
45
+ * the write seam so callers can keep using the semantic aliases while the wire
46
+ * carries the designer's constant (`ratio.percentile`, `RMB.percentile`, …).
47
+ */
48
+ function canonicaliseNumericalFormat(propertyType, options, requested) {
49
+ if (propertyType !== FIELD_PROPERTY_TYPES.NUMERICAL)
50
+ return undefined;
51
+ if (requested === undefined)
52
+ return undefined;
53
+ const to = canonicalNumericalFormat(requested, options.scale);
54
+ if (to === undefined)
55
+ return undefined;
56
+ options.format = to;
57
+ const from = String(requested);
58
+ return from === to ? undefined : { from, to };
59
+ }
41
60
  /** Normalize one field change and run every reproduced write gate exactly once. */
42
61
  export function prepareFieldChange(input) {
43
62
  const propertyType = normalizeFieldPropertyType({ propertyType: input.propertyType });
@@ -58,13 +77,17 @@ export function prepareFieldChange(input) {
58
77
  assertNumericalScale(propertyType, raw);
59
78
  assertFormConditions(raw);
60
79
  const options = ensureRelationDisplayFieldOptions(propertyType, raw);
80
+ const formatNormalized = canonicaliseNumericalFormat(propertyType, options, raw.format);
61
81
  const displayCode = relationDisplayFieldCode(propertyType, options);
62
82
  const optionRelationTarget = typeof options.schemaCode === "string" ? options.schemaCode.trim() : "";
63
83
  const normalizedRelation = (propertyType === FIELD_PROPERTY_TYPES.WORK_SHEET || propertyType === FIELD_PROPERTY_TYPES.MULT_WORK_SHEET) &&
64
84
  optionRelationTarget.length > 0 && !(typeof input.relativeCode === "string" && input.relativeCode.trim().length > 0)
65
85
  ? { relationTarget: "options.schemaCode→relativeCode" }
66
86
  : undefined;
67
- return { propertyType, isChildTable, options, ...(displayCode ? { displayCode } : {}), ...(normalizedRelation ? { normalized: normalizedRelation } : {}) };
87
+ const normalized = normalizedRelation === undefined && formatNormalized === undefined
88
+ ? undefined
89
+ : { ...(normalizedRelation ?? {}), ...(formatNormalized ? { format: formatNormalized } : {}) };
90
+ return { propertyType, isChildTable, options, ...(displayCode ? { displayCode } : {}), ...(normalized ? { normalized } : {}) };
68
91
  }
69
92
  /** The single platform wire body for a field create. */
70
93
  export function fieldChangeWireBody(input, prepared) {
@@ -193,6 +216,7 @@ export function prepareFieldUpdate(input) {
193
216
  : rebuiltOptions;
194
217
  if (!isChildTable && !effectiveOptions && !input.choices)
195
218
  Object.assign(nextOptions, currentOptions);
219
+ const formatNormalized = isChildTable ? undefined : canonicaliseNumericalFormat(recordType, nextOptions, effectiveOptions?.format);
196
220
  if (!isChildTable) {
197
221
  // An update that touches a relation's options must keep a resolvable target:
198
222
  // backfill schemaCode from relativeCode (top-level or already stored) so
@@ -214,7 +238,7 @@ export function prepareFieldUpdate(input) {
214
238
  : input.name !== undefined
215
239
  ? nameI18nJson(input.name)
216
240
  : (typeof input.base.name_i18n === "string" ? input.base.name_i18n : undefined);
217
- return { propertyType: recordType, isChildTable, options: nextOptions, ...(conditionCompiled.length > 0 ? { conditionCompiled } : {}), ...(displayCode !== undefined ? { displayCode } : {}), ...(name !== undefined ? { name } : {}), ...(nameI18n !== undefined ? { nameI18n } : {}) };
241
+ return { propertyType: recordType, isChildTable, options: nextOptions, ...(conditionCompiled.length > 0 ? { conditionCompiled } : {}), ...(formatNormalized ? { formatNormalized } : {}), ...(displayCode !== undefined ? { displayCode } : {}), ...(name !== undefined ? { name } : {}), ...(nameI18n !== undefined ? { nameI18n } : {}) };
218
242
  }
219
243
  /** The single field-update wire body: the stored row spread with changed keys. */
220
244
  export function fieldUpdateWireBody(input, prepared) {
@@ -191,6 +191,7 @@ export const fieldOptionsArg = z
191
191
  // assertNumericalScale (not zod min/max) so scale:9 still returns the
192
192
  // teaching refusal, not a generic tool-input-invalid.
193
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
195
  nested: z.boolean().optional().describe("nested child-table metadata — refused (coverage boundary)"),
195
196
  relationLinkage: z.boolean().optional().describe("advanced relation linkage — refused (coverage boundary)"),
196
197
  })
@@ -500,19 +501,120 @@ const RATIO_DECIMALS_FORMAT = Object.freeze({
500
501
  1: "ratio.tenths",
501
502
  2: "ratio.percentile",
502
503
  });
503
- function numericalFormatPrefix(format) {
504
- const value = String(format ?? "").toLowerCase();
505
- if (value === "currency" || value === "rmb" || value === "¥")
506
- return "RMB.";
507
- if (value === "dollar" || value === "$")
508
- return "dollar.";
509
- if (value === "euro" || value === "€")
510
- return "euro.";
504
+ /**
505
+ * THE platform's numeric display-format enum, as the designer itself emits it
506
+ * (r64b live 2026-11-14, Playwright on the real designer at
507
+ * `/admin#/apps/model/<app>/<schema>/data/dataModel` → 数据项 Edit → DataItem
508
+ * Attributes → Default Format; the same 47-option list also backs the form
509
+ * control's Display Format select).
510
+ *
511
+ * The decimals word is the SECOND half of the constant; the family prefix is
512
+ * the first. `format` stored on the field row (`bizproperty.options.format`)
513
+ * is this constant VERBATIM, e.g. `ratio.percentile` for `20.00%`,
514
+ * `RMB.percentile` for `¥2,000.00`. The runtime reads it literally: a
515
+ * non-canonical word there is not "unknown → fall back", it renders the raw
516
+ * decimal (proved by nf_h/nf_i: field `format:"percent"` → portal shows 0.5).
517
+ */
518
+ export const NUMERICAL_FORMAT_DECIMALS = Object.freeze({
519
+ integer: 0,
520
+ tenths: 1,
521
+ percentile: 2,
522
+ Millimeter: 3,
523
+ tenThousand: 4,
524
+ hundredThousand: 5,
525
+ millionDecimals: 6,
526
+ tenMillionDecimals: 7,
527
+ billionDecimals: 8,
528
+ });
529
+ /** Family prefixes as spelled by the designer (case matters on the wire). */
530
+ export const NUMERICAL_FORMAT_PREFIXES = Object.freeze({
531
+ ratio: "ratio.",
532
+ rmb: "RMB.",
533
+ dollar: "dollar.",
534
+ euro: "euro.",
535
+ hk: "HK.",
536
+ });
537
+ /** `none` = the designer's "Null" option: no grouping, no forced decimals. */
538
+ export const NUMERICAL_FORMAT_NONE = "none";
539
+ /**
540
+ * The currency families are NOT offered below two decimals by the designer
541
+ * (its 47-item list starts each currency at `<CUR>.percentile` = ¥2,000.00);
542
+ * a 0/1-decimal currency request therefore clamps up to `percentile` instead of
543
+ * emitting `RMB.tenths`, which the runtime would not render.
544
+ */
545
+ const CURRENCY_MIN_DECIMALS = 2;
546
+ const NUMERICAL_DECIMALS_BY_LOWER = new Map(Object.entries(NUMERICAL_FORMAT_DECIMALS).map(([word, decimals]) => [word.toLowerCase(), { word, decimals }]));
547
+ /** Semantic aliases the CLI accepts as sugar; canonicalised before the wire. */
548
+ function numericalAliasFamily(value) {
549
+ if (value === "percent" || value === "percentage" || value === "ratio" || value === "%" || value === "percentile")
550
+ return undefined; // `percentile` alone = 2-decimals, handled below
551
+ if (value === "currency" || value === "rmb" || value === "cny" || value === "¥" || value === "¥")
552
+ return "rmb";
553
+ if (value === "dollar" || value === "usd" || value === "$")
554
+ return "dollar";
555
+ if (value === "euro" || value === "eur" || value === "€")
556
+ return "euro";
511
557
  if (value === "hk" || value === "hkd" || value === "hk$")
512
- return "HK.";
513
- if (value === "percent" || value === "percentage" || value === "ratio")
514
- return "ratio.";
515
- return "";
558
+ return "hk";
559
+ if (value === "decimal" || value === "number" || value === "numeric" || value === "none")
560
+ return "";
561
+ return undefined;
562
+ }
563
+ /**
564
+ * Normalise a caller-supplied numeric `format` to the platform constant the
565
+ * runtime actually understands.
566
+ *
567
+ * - a canonical constant passes through (case-corrected: `ratio.percentile`,
568
+ * `RMB.percentile`, `Millimeter`, …) — so `ratio.Millimeter` (20.000%, a
569
+ * value the live designer offers) survives;
570
+ * - semantic aliases (`percent` / `currency` / `¥` / `dollar` / `euro` / `hk`)
571
+ * compose from `scale`; percent clamps to the three documented `ratio.*`
572
+ * values so 8.6.26 stays inside its evidenced domain;
573
+ * - `none`/absent stays `none`.
574
+ *
575
+ * Returns `undefined` when there is no format to write (leave the key out).
576
+ */
577
+ /** Compose `<family><decimals-word>` with the currency floors the designer offers. */
578
+ function numericalFamilyFormat(family, decimals) {
579
+ const floored = family === "" || family === "ratio." ? decimals : Math.max(decimals, CURRENCY_MIN_DECIMALS);
580
+ return `${family}${NUMERICAL_DECIMALS_FORMAT[floored] ?? NUMERICAL_DECIMALS_FORMAT[2]}`;
581
+ }
582
+ export function canonicalNumericalFormat(format, scale) {
583
+ if (format === undefined || format === null)
584
+ return undefined;
585
+ const raw = String(format).trim();
586
+ if (raw === "")
587
+ return undefined;
588
+ const lower = raw.toLowerCase();
589
+ if (lower === NUMERICAL_FORMAT_NONE)
590
+ return NUMERICAL_FORMAT_NONE;
591
+ const decimals = isNumericalScale(scale) ? scale : 0;
592
+ // Canonical constant, optionally family-prefixed.
593
+ const dot = raw.indexOf(".");
594
+ if (dot > 0) {
595
+ const family = NUMERICAL_FORMAT_PREFIXES[lower.slice(0, dot)];
596
+ const word = NUMERICAL_DECIMALS_BY_LOWER.get(lower.slice(dot + 1));
597
+ if (family !== undefined && word !== undefined) {
598
+ // An explicit word always wins over `scale`; only the currency floor applies.
599
+ return numericalFamilyFormat(family, word.decimals);
600
+ }
601
+ }
602
+ const bare = NUMERICAL_DECIMALS_BY_LOWER.get(lower);
603
+ if (bare !== undefined)
604
+ return bare.word;
605
+ // Semantic aliases.
606
+ if (lower === "percent" || lower === "percentage" || lower === "ratio" || lower === "%") {
607
+ return RATIO_DECIMALS_FORMAT[Math.min(decimals, 2)];
608
+ }
609
+ const alias = numericalAliasFamily(lower);
610
+ if (alias === undefined)
611
+ return raw; // unknown value: leave the caller's word (fail-open like the wire, documented)
612
+ return numericalFamilyFormat(alias === "" ? "" : NUMERICAL_FORMAT_PREFIXES[alias], decimals);
613
+ }
614
+ function numericalFormatPrefix(format) {
615
+ const canonical = canonicalNumericalFormat(format, 2) ?? "";
616
+ const dot = canonical.indexOf(".");
617
+ return dot > 0 ? canonical.slice(0, dot + 1) : "";
516
618
  }
517
619
  export function numericalControlFormat(fieldOptions) {
518
620
  const scale = fieldOptions?.scale;
@@ -522,7 +624,22 @@ export function numericalControlFormat(fieldOptions) {
522
624
  // rebuild silently turn existing integer money fields into "2,000.00".
523
625
  const valid = isNumericalScale(scale);
524
626
  const decimals = valid ? scale : 0;
525
- const prefix = numericalFormatPrefix(fieldOptions?.format);
627
+ const format = fieldOptions?.format;
628
+ // r64b: the Designer itself stores the canonical constant on the field row
629
+ // (`ratio.percentile`, `RMB.percentile`, …). Pass it through untouched —
630
+ // re-deriving from `scale` here used to turn `ratio.percentile` into plain
631
+ // `percentile`, so a rebuilt form showed 2,000.00 where the field asked 20.00%.
632
+ const canonical = canonicalNumericalFormat(format, decimals);
633
+ if (canonical === NUMERICAL_FORMAT_NONE)
634
+ return NUMERICAL_FORMAT_NONE;
635
+ if (canonical !== undefined) {
636
+ const dot = canonical.indexOf(".");
637
+ if (dot > 0)
638
+ return canonical;
639
+ if (canonical === "ratio" || NUMERICAL_DECIMALS_BY_LOWER.has(canonical.toLowerCase()))
640
+ return canonical;
641
+ }
642
+ const prefix = numericalFormatPrefix(format);
526
643
  if (prefix === "ratio.")
527
644
  return RATIO_DECIMALS_FORMAT[Math.min(decimals, 2)];
528
645
  return `${prefix}${NUMERICAL_DECIMALS_FORMAT[decimals]}`;
@@ -14,6 +14,10 @@ export const APP_WIRE = Object.freeze({
14
14
  deleteBody: "apppackage/delete?appCode=; APP_PACKAGE_HAS_NODE / 600006 refuses when the app still has non-Folder nodes (models/reports/pages); tool pre-checks folder.tree and refuses app-not-empty with children[{id,type,path}] + nextCommand folder.tree (empty folders including isDefault default group do NOT block)",
15
15
  deletePoll: "apppackage/list polls to exact absence",
16
16
  defaultFolderSeed: "apppackage/create seeds one top-level Folder with name_i18n.en=defaultGroup (display「默认分组」); app.create readback surfaces defaultFolder{id,path,isDefault:true}; folder.tree marks the same node isDefault:true",
17
+ exportBody: "apppackage/export POST body {appCode, references} (AppImportExportController.exportApp(AppExportParamVO) — decompiled AI-Platform-v1.1.25) streams a ZIP: <appCode>-<uuid>/manifest.json + meta/{dm,form,view,workflow,report} + dependencies/platform/*; refusals stay HTTP 200 JSON envelopes (10005 应用编码不能为空, 600005 应用不存在!)",
18
+ exportReferences: "references accepts the design UI's five refTabsKey arrays (relativeDictionary/relativeRole/relativeBizService/relativeAdvanceDataSource/relativeReportAdvanceDataSource) taken verbatim from apppackage/dependencies?appCode=; {} (or omitted) exports zero selected dependencies",
19
+ exportBinaryStream: "both exporters answer a non-envelope ZIP stream (Content-Type application/octet-stream) on success; a JSON body on a 200 is a refusal/malformed answer, never a package — bytes are validated for the PK local-header magic and non-zero entry count before reporting success",
20
+ environmentExport: "lifeCycle/apppackage/lifeCycleExport POST {} → metadata.zip (LifeCycleIEFacadeImpl.exportLifeCycle): metadata/app/applist/<appCode>/… for EVERY app + metadata/app/appgroup.json + ALL biz services (metadata/bizservice/manifest.json + servicegroup.json) + bizdatasource.json + metadata/manifest.json; GET answers 40007 请求方法不正确; no per-app/per-asset filter, per-app packages use empty references",
17
21
  });
18
22
  export const APP_LANE_CONTRACT = Object.freeze({
19
23
  lane: LANES.app,
@@ -26,6 +30,9 @@ export const APP_LANE_CONTRACT = Object.freeze({
26
30
  create: "applicationCreate",
27
31
  update: "applicationUpdate",
28
32
  delete: "applicationDelete",
33
+ export: "appPackageExport",
34
+ exportDependencies: "appPackageDependencies",
35
+ environmentExport: "environmentLifeCycleExport",
29
36
  }),
30
37
  wire: Object.freeze({
31
38
  createBody: APP_WIRE.createBody,
@@ -36,6 +43,10 @@ export const APP_LANE_CONTRACT = Object.freeze({
36
43
  deleteBody: APP_WIRE.deleteBody,
37
44
  deletePoll: APP_WIRE.deletePoll,
38
45
  defaultFolderSeed: APP_WIRE.defaultFolderSeed,
46
+ exportBody: APP_WIRE.exportBody,
47
+ exportReferences: APP_WIRE.exportReferences,
48
+ exportBinaryStream: APP_WIRE.exportBinaryStream,
49
+ environmentExport: APP_WIRE.environmentExport,
39
50
  }),
40
51
  wireBindings: Object.freeze({
41
52
  createBody: Object.freeze([behaviorBinding("test/app-management.test.ts#app.create plans, executes under approval, and reads back presence", assertAppContract)]),
@@ -46,6 +57,10 @@ export const APP_LANE_CONTRACT = Object.freeze({
46
57
  deleteBody: Object.freeze([behaviorBinding("test/app-management.test.ts#app.delete removes the app via the admin delete endpoint", assertAppContract)]),
47
58
  deletePoll: Object.freeze([behaviorBinding("test/app-management.test.ts#app.delete of an absent app is a no-op with proven absence", assertAppContract)]),
48
59
  defaultFolderSeed: Object.freeze([behaviorBinding("test/app-folder-and-model-move.test.ts#r28d F2: app.create surfaces defaultFolder; folder.tree marks isDefault", assertAppContract)]),
60
+ exportBody: Object.freeze([behaviorBinding("test/r64b-app-export.test.ts#app.export writes a single-app package and verifies bytes/sha256/entries", assertAppContract)]),
61
+ exportReferences: Object.freeze([behaviorBinding("test/r64b-app-export.test.ts#app.export includeDependencies selects the five refTabsKey arrays", assertAppContract)]),
62
+ exportBinaryStream: Object.freeze([behaviorBinding("test/r64b-app-export.test.ts#app.export refuses a 200 JSON envelope instead of reporting a fake package", assertAppContract)]),
63
+ environmentExport: Object.freeze([behaviorBinding("test/r64b-app-export.test.ts#app.export without applicationCode writes the environment lifecycle package", assertAppContract)]),
49
64
  }),
50
65
  evidence: Object.freeze([
51
66
  "packages/omc-cli/test/app-management.test.ts",
@@ -70,6 +85,10 @@ export const APP_LANE_CONTRACT = Object.freeze({
70
85
  scope: "app package delete absence",
71
86
  description: "删除一个应用包(apppackage/delete?appCode=,管理员面)。应用下还有模型/报表/自定义页等非目录节点时以 app-not-empty(平台 APP_PACKAGE_HAS_NODE / 600006)拒绝,回执列 children[{id,type,path}] 且 nextCommand 指向 folder.tree;空目录(含默认分组)不挡删除。以 apppackage/list 轮询读回精确缺席。必须显式传 `code`,没有默认应用,避免误删。",
72
87
  }),
88
+ "app.export": Object.freeze({
89
+ scope: "app package export",
90
+ description: "导出配置包(备份/迁移):applicationCode 省略 → 环境级生命周期包(/lifeCycle/apppackage/lifeCycleExport,全部应用包+应用分组+业务集成服务+数据源,metadata/…)。指定 applicationCode → 单应用包(apppackage/export,body {appCode,references},meta/{dm,form,view,workflow,report}+dependencies/platform/*)。includeDependencies 仅单应用有效:先读 apppackage/dependencies,把引用全选后传 references;环境包平台固定空引用,故环境范围传 true 直接拒。ZIP 同步返回(实测 1–3s;超时回 uncertain,勿当成功)。产物落盘:默认会话 artifacts,out 指定配置根内路径(0600)。回执只给 outPath/bytes/sha256/条目清单/资产计数,永不内联包内容。平台没有按资产类型筛选的参数,不收 assetTypes。",
91
+ }),
73
92
  }),
74
93
  });
75
94
  export function assertAppContract() {
@@ -82,6 +101,7 @@ export function assertAppContract() {
82
101
  throw new Error("app contract must pin the zero-wire prerequisite refusal");
83
102
  assertDescriptionCarries(APP_LANE_CONTRACT, "app.update", ["apppackage/update", "groupId", "enabled", "原样保留", "AppPackageController.update"]);
84
103
  assertDescriptionCarries(APP_LANE_CONTRACT, "app.delete", ["apppackage/delete", "APP_PACKAGE_HAS_NODE", "app-not-empty", "缺席"]);
104
+ assertDescriptionCarries(APP_LANE_CONTRACT, "app.export", ["lifeCycle/apppackage/lifeCycleExport", "apppackage/export", "references", "sha256", "assetTypes"]);
85
105
  if (!APP_WIRE.createBody.includes("apppackage/create"))
86
106
  throw new Error("app contract must pin the create endpoint");
87
107
  if (!APP_WIRE.defaultGroupResolution.includes("auto-first-group"))
@@ -98,5 +118,17 @@ export function assertAppContract() {
98
118
  throw new Error("app contract must pin the delete absence poll");
99
119
  if (!APP_WIRE.defaultFolderSeed.includes("defaultGroup"))
100
120
  throw new Error("app contract must pin the default-folder seed token");
121
+ if (!APP_WIRE.exportBody.includes("AppExportParamVO"))
122
+ throw new Error("app contract must pin the export VO and body shape");
123
+ if (!APP_WIRE.exportBody.includes("600005"))
124
+ throw new Error("app contract must pin the export refusal errcode");
125
+ if (!APP_WIRE.exportReferences.includes("relativeDictionary"))
126
+ throw new Error("app contract must pin the references keys");
127
+ if (!APP_WIRE.exportBinaryStream.includes("PK local-header magic"))
128
+ throw new Error("app contract must pin the ZIP validation");
129
+ if (!APP_WIRE.environmentExport.includes("EVERY app"))
130
+ throw new Error("app contract must pin the environment export scope");
131
+ if (!APP_WIRE.environmentExport.includes("40007"))
132
+ throw new Error("app contract must pin the lifecycle GET refusal");
101
133
  }
102
134
  //# sourceMappingURL=app-contract.js.map
@@ -12,5 +12,10 @@ export const APP_COVERAGE = declareLaneCoverage(APP_LANE_CONTRACT.lane, [
12
12
  claim("app.delete", T["app.delete"].scope),
13
13
  ],
14
14
  },
15
+ {
16
+ capability: "r64b application package export",
17
+ evidence: ["packages/omc-cli/test/r64b-app-export.test.ts", "packages/omc-cli/src/lanes/app.ts"],
18
+ tools: [claim("app.export", T["app.export"].scope)],
19
+ },
15
20
  ]);
16
21
  //# sourceMappingURL=app-coverage.js.map
package/dist/lanes/app.js CHANGED
@@ -1,15 +1,253 @@
1
1
  import { z } from "zod";
2
+ import { createHash } from "node:crypto";
3
+ import { chmodSync, existsSync, lstatSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
4
+ import { basename, dirname, join, resolve } from "node:path";
2
5
  import { ENDPOINTS } from "../endpoints.js";
3
6
  import { capabilityArg, environmentArg } from "../args.js";
4
7
  import { governedRead } from "../read.js";
5
8
  import { writeTool } from "../write.js";
6
9
  import { defineTool, ToolRefusalError } from "../tool-types.js";
7
- import { wireCall, wireRows, WireError } from "../wire.js";
10
+ import { wireCall, wireDownloadPackageStream, wireRows, WireError } from "../wire.js";
11
+ import { isWithinRoot } from "../artifacts.js";
12
+ import { readZipEntries } from "../zip.js";
8
13
  import { resolveApplicationScope } from "../support.js";
9
14
  import { APP_LANE_CONTRACT } from "./app-contract.js";
10
15
  import { readAppTree } from "./folder.js";
11
16
  const APP_LANE = APP_LANE_CONTRACT.lane;
12
17
  const APP_TOOLS = APP_LANE_CONTRACT.tools;
18
+ /**
19
+ * r64b export support. The platform has exactly two package faces (decompiled
20
+ * AppImportExportController / LifeCycleImportExportController, live-proven on
21
+ * AI-Platform-v1.1.25):
22
+ *
23
+ * - single app: POST /app/apppackage/export {appCode, references} → ZIP with
24
+ * `<appCode>-<uuid>/manifest.json` + meta/{dm,form,view,workflow,report} +
25
+ * dependencies/platform/*.
26
+ * - whole environment: POST /lifeCycle/apppackage/lifeCycleExport → metadata.zip
27
+ * with metadata/app/applist/<appCode>/… for EVERY app, appgroup.json, ALL
28
+ * biz services + datasources, and the root manifest.
29
+ *
30
+ * Both are synchronous (live 1–3 s for 0.2–0.7 MB packages) and both answer
31
+ * business refusals as HTTP 200 JSON envelopes, which the wire helper classifies
32
+ * before anything is written.
33
+ */
34
+ const REFERENCE_KEYS = [
35
+ "relativeDictionary",
36
+ "relativeRole",
37
+ "relativeBizService",
38
+ "relativeAdvanceDataSource",
39
+ "relativeReportAdvanceDataSource",
40
+ ];
41
+ const PACKAGE_MAGIC_LOCAL_HEADER = 0x04034b50;
42
+ function configRootForExport() {
43
+ return resolve(process.env.OMC_CONFIG_HOME ?? process.cwd());
44
+ }
45
+ /**
46
+ * Resolve the on-disk target for one package. `out` is a path inside the
47
+ * configuration root (same containment rule as --args-file / intent plans):
48
+ * a `*.zip` path is the file itself, anything else is a directory the file is
49
+ * written into. Omitting `out` keeps the CLI's artifact convention.
50
+ */
51
+ function resolveExportTarget(input) {
52
+ if (input.out === undefined)
53
+ return join(input.artifactsDir, input.defaultFileName);
54
+ const root = configRootForExport();
55
+ const candidate = resolve(root, input.out);
56
+ if (!isWithinRoot(root, candidate))
57
+ throw new ToolRefusalError({
58
+ status: "refused",
59
+ blocker: "app-export-out-outside-root",
60
+ out: input.out,
61
+ message: `out 必须位于配置根内(配置根 ${root});本次解析为 ${candidate}。省略 out 落到会话 artifacts,或用配置根内相对路径(如 .omc/backups/)。`,
62
+ });
63
+ const asDirectory = input.out.endsWith("/") || input.out.endsWith("\\") || (existsSync(candidate) && lstatSync(candidate).isDirectory());
64
+ const target = asDirectory ? join(candidate, input.directoryFileName) : candidate;
65
+ // Lexical containment is not enough: a symlinked ancestor could still point
66
+ // outside the root, so re-check the REAL path of the nearest existing
67
+ // directory before writing. (The CLI's own artifacts dir is exempt: it is a
68
+ // trusted default, not a caller-supplied path.)
69
+ let ancestor = dirname(target);
70
+ while (!existsSync(ancestor)) {
71
+ const parent = dirname(ancestor);
72
+ if (parent === ancestor)
73
+ break;
74
+ ancestor = parent;
75
+ }
76
+ if (existsSync(ancestor) && existsSync(root)) {
77
+ const realRoot = realpathSync(root);
78
+ const realAncestor = realpathSync(ancestor);
79
+ if (realAncestor !== realRoot && !isWithinRoot(realRoot, realAncestor))
80
+ throw new ToolRefusalError({
81
+ status: "refused",
82
+ blocker: "app-export-out-outside-root",
83
+ out: input.out,
84
+ outPath: target,
85
+ message: `out 的上级目录解析后落在配置根之外(符号链接逃逸):${ancestor} → ${realAncestor};拒绝写入。`,
86
+ });
87
+ }
88
+ return target;
89
+ }
90
+ function writeExportPackage(target, content, label) {
91
+ try {
92
+ mkdirSync(dirname(target), { recursive: true });
93
+ if (existsSync(target) && lstatSync(target).isSymbolicLink())
94
+ throw new ToolRefusalError({
95
+ status: "refused",
96
+ blocker: "app-export-out-symbolic-link",
97
+ outPath: target,
98
+ message: `导出目标 ${target} 是符号链接;拒绝写入(备份产物不得落到链接目标)`,
99
+ });
100
+ writeFileSync(target, content, { mode: 0o600 });
101
+ chmodSync(target, 0o600);
102
+ }
103
+ catch (error) {
104
+ if (error instanceof ToolRefusalError)
105
+ throw error;
106
+ throw new ToolRefusalError({
107
+ status: "refused",
108
+ blocker: "app-export-write-failed",
109
+ outPath: target,
110
+ message: `${label}写入失败:${error.message}`,
111
+ });
112
+ }
113
+ }
114
+ /** Read the ZIP once; a 200 body that is not a non-empty ZIP is never reported as success. */
115
+ function readExportPackage(bytes, endpoint) {
116
+ if (bytes.length < 4 || bytes.readUInt32LE(0) !== PACKAGE_MAGIC_LOCAL_HEADER)
117
+ throw new ToolRefusalError({
118
+ status: "refused",
119
+ blocker: "app-export-package-invalid",
120
+ endpoint,
121
+ bytes: bytes.length,
122
+ message: `平台返回 ${bytes.length}B 但不是一个 ZIP(缺少 PK\\x03\\x04 头);拒绝把非包响应当成功。检查读写权限或稍后重试。`,
123
+ });
124
+ try {
125
+ const entries = readZipEntries(bytes);
126
+ if (entries.size === 0)
127
+ throw new ToolRefusalError({
128
+ status: "refused",
129
+ blocker: "app-export-package-invalid",
130
+ endpoint,
131
+ bytes: bytes.length,
132
+ message: "平台返回的 ZIP 是空包(0 条目);拒绝当成功。",
133
+ });
134
+ return { entries, entryCount: entries.size };
135
+ }
136
+ catch (error) {
137
+ if (error instanceof ToolRefusalError)
138
+ throw error;
139
+ throw new ToolRefusalError({
140
+ status: "refused",
141
+ blocker: "app-export-package-invalid",
142
+ endpoint,
143
+ bytes: bytes.length,
144
+ message: `平台返回的 ZIP 无法解析:${error.message}`,
145
+ });
146
+ }
147
+ }
148
+ function parseJsonBuffer(buffer) {
149
+ if (buffer === undefined)
150
+ return undefined;
151
+ try {
152
+ return JSON.parse(buffer.toString("utf8"));
153
+ }
154
+ catch {
155
+ return undefined;
156
+ }
157
+ }
158
+ function jsonEntry(entries, name) {
159
+ const parsed = parseJsonBuffer(entries.get(name));
160
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
161
+ }
162
+ function arrayLength(value) {
163
+ return Array.isArray(value) ? value.length : 0;
164
+ }
165
+ function nameLength(value) {
166
+ return typeof value === "string" && value !== "" ? value : null;
167
+ }
168
+ /** First path segment of the package (the staging dir the controller zipped). */
169
+ function packageRootOf(entries) {
170
+ for (const name of entries.keys()) {
171
+ const slash = name.indexOf("/");
172
+ if (slash > 0)
173
+ return name.slice(0, slash);
174
+ }
175
+ return "";
176
+ }
177
+ function appPackageAssets(entries, root) {
178
+ const manifest = jsonEntry(entries, `${root}/manifest.json`);
179
+ const depends = (area) => jsonEntry(entries, `${root}/dependencies/platform/${area}/${area}.json`);
180
+ const dictionary = depends("dictionary");
181
+ const role = depends("role");
182
+ const bizMethod = depends("bizMethod");
183
+ const datasource = depends("datasource");
184
+ const methodsMap = bizMethod?.methodsMap;
185
+ const bizMethodCount = methodsMap && typeof methodsMap === "object"
186
+ ? Object.values(methodsMap).reduce((sum, methods) => sum + arrayLength(methods), 0)
187
+ : 0;
188
+ const dataSourceCount = arrayLength(datasource?.relativeAdvanceDataSource) + arrayLength(datasource?.relativeReportAdvanceDataSource);
189
+ return {
190
+ appCode: nameLength(manifest?.code),
191
+ appName: nameLength(manifest?.name),
192
+ bizModels: arrayLength(manifest?.bizModels),
193
+ modelGroups: arrayLength(manifest?.modelGroups),
194
+ reportModels: arrayLength(manifest?.reportModels),
195
+ customPages: arrayLength(manifest?.customPages),
196
+ appPages: arrayLength(manifest?.appPages),
197
+ dependencies: {
198
+ dictionaries: arrayLength(dictionary?.dictionaries),
199
+ roles: arrayLength(role?.roles),
200
+ bizServices: arrayLength(bizMethod?.services),
201
+ bizMethods: bizMethodCount,
202
+ dataSources: dataSourceCount,
203
+ },
204
+ packageVersion: nameLength(manifest?.systemVersion) ?? nameLength(entries.get(`${root}/version.md`)?.toString("utf8").trim()),
205
+ };
206
+ }
207
+ function environmentPackageAssets(entries) {
208
+ const applicationCodes = [...entries.keys()]
209
+ .map((name) => /^metadata\/app\/applist\/([^/]+)\//.exec(name)?.[1])
210
+ .filter((code) => typeof code === "string" && code !== "");
211
+ const uniqueCodes = [...new Set(applicationCodes)].sort();
212
+ const manifest = jsonEntry(entries, "metadata/manifest.json");
213
+ const version = manifest?.version;
214
+ const appGroups = parseJsonBuffer(entries.get("metadata/app/appgroup.json"));
215
+ const bizManifest = jsonEntry(entries, "metadata/bizservice/manifest.json");
216
+ const methodsMap = bizManifest?.methodsMap;
217
+ const bizMethodCount = methodsMap && typeof methodsMap === "object"
218
+ ? Object.values(methodsMap).reduce((sum, methods) => sum + arrayLength(methods), 0)
219
+ : 0;
220
+ const dataSources = jsonEntry(entries, "metadata/bizservice/bizdatasource.json");
221
+ const areaOf = (name) => {
222
+ if (name.startsWith("metadata/app/applist/"))
223
+ return "appPackages";
224
+ if (name.startsWith("metadata/app/"))
225
+ return "appGroups";
226
+ if (name.startsWith("metadata/bizservice/"))
227
+ return "bizServices";
228
+ return "manifest";
229
+ };
230
+ const byArea = {};
231
+ for (const [name, content] of entries) {
232
+ const area = areaOf(name);
233
+ const bucket = (byArea[area] ??= { files: 0, bytes: 0 });
234
+ bucket.files += 1;
235
+ bucket.bytes += content.length;
236
+ }
237
+ return {
238
+ applicationCount: uniqueCodes.length,
239
+ applicationCodes: uniqueCodes,
240
+ appGroups: arrayLength(appGroups),
241
+ bizServices: arrayLength(bizManifest?.services),
242
+ bizMethods: bizMethodCount,
243
+ dataSources: arrayLength(dataSources?.relativeAdvanceDataSource) + arrayLength(dataSources?.relativeReportAdvanceDataSource),
244
+ packageVersion: nameLength(version?.cloudpivot) ?? nameLength(manifest?.systemVersion),
245
+ byArea,
246
+ };
247
+ }
248
+ function sha256Of(content) {
249
+ return createHash("sha256").update(content).digest("hex");
250
+ }
13
251
  export async function resolveValidatedApplicationScope(session, requested) {
14
252
  const scope = await resolveApplicationScope(session, requested);
15
253
  const availableApps = wireRows((await wireCall(session, { path: ENDPOINTS.applicationList, query: {} })).data)
@@ -316,5 +554,162 @@ export function registerAppLane(tools) {
316
554
  },
317
555
  rollback: appRollbackSpec("app.delete"),
318
556
  });
557
+ tools.push(defineTool({
558
+ name: "app.export",
559
+ search: {
560
+ intents: [
561
+ "导出应用",
562
+ "导出应用包",
563
+ "备份应用配置",
564
+ "备份整个环境",
565
+ "整体导出配置",
566
+ "环境配置备份",
567
+ "迁移打包",
568
+ "下载应用包",
569
+ ],
570
+ },
571
+ layer: "low",
572
+ kind: "read",
573
+ lane: APP_LANE,
574
+ scope: APP_TOOLS["app.export"].scope,
575
+ description: APP_TOOLS["app.export"].description,
576
+ inputSchema: {
577
+ environment: environmentArg,
578
+ applicationCode: z
579
+ .string()
580
+ .min(1)
581
+ .optional()
582
+ .describe("要导出的应用编码(app.list 的 code)。省略 = 导出整个环境(全部应用包 + 应用分组 + 业务集成服务 + 数据源)"),
583
+ includeDependencies: z
584
+ .boolean()
585
+ .optional()
586
+ .describe("仅单应用有效:true 时先读 apppackage/dependencies,把引用的字典/角色/业务集成/数据源一并打进包;环境包平台固定空引用,故环境范围传 true 会被拒"),
587
+ out: z
588
+ .string()
589
+ .min(1)
590
+ .optional()
591
+ .describe("配置根内落盘路径:以 .zip 结尾视为文件;其它视为目录(写入 <应用码>-app-package.zip / environment-lifecycle.zip)。省略落到会话 artifacts"),
592
+ capability: capabilityArg,
593
+ },
594
+ handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
595
+ const applications = wireRows((await wireCall(session, { path: ENDPOINTS.applicationList, query: {} })).data).map((row) => ({
596
+ code: String(row.appCode ?? row.code ?? ""),
597
+ name: String(row.appName ?? row.name ?? row.appCode ?? row.code ?? ""),
598
+ })).filter((row) => row.code !== "");
599
+ const requested = args.applicationCode;
600
+ if (requested === undefined && args.includeDependencies === true)
601
+ throw new ToolRefusalError({
602
+ status: "refused",
603
+ blocker: "app-export-option-unsupported",
604
+ option: "includeDependencies",
605
+ message: "环境级生命周期包(lifeCycleExport)固定使用空 references,平台不接受依赖选择——includeDependencies 只对单应用生效。" +
606
+ "需要把某应用的字典/角色/业务集成一起迁走时,改用 applicationCode + includeDependencies:true 单独导出该应用。",
607
+ });
608
+ let scope;
609
+ let selected;
610
+ let references;
611
+ let bytes;
612
+ if (requested !== undefined) {
613
+ selected = applications.find((row) => row.code === requested);
614
+ if (!selected) {
615
+ const available = applications.map((row) => row.code);
616
+ throw new ToolRefusalError({
617
+ status: "refused",
618
+ blocker: "app-export-app-not-found",
619
+ applicationCode: requested,
620
+ availableApplications: available.slice(0, 40),
621
+ message: `应用「${requested}」不在租户应用清单里(平台会回 600005 应用不存在!)。可用:${available.slice(0, 12).join("、")}${available.length > 12 ? " 等" : ""};零导出调用。`,
622
+ });
623
+ }
624
+ scope = "application";
625
+ references = {};
626
+ if (args.includeDependencies === true) {
627
+ const dependencyData = (await wireCall(session, {
628
+ path: ENDPOINTS.appPackageDependencies,
629
+ query: { appCode: selected.code },
630
+ })).data;
631
+ for (const key of REFERENCE_KEYS) {
632
+ const value = dependencyData?.[key];
633
+ if (Array.isArray(value) && value.length > 0)
634
+ references[key] = value;
635
+ }
636
+ }
637
+ bytes = await wireDownloadPackageStream(session, {
638
+ path: ENDPOINTS.appPackageExport,
639
+ body: { appCode: selected.code, references },
640
+ });
641
+ }
642
+ else {
643
+ if (applications.length === 0)
644
+ throw new ToolRefusalError({
645
+ status: "refused",
646
+ blocker: "app-export-no-applications",
647
+ message: "租户没有可导出的应用(apppackage/list 为空);环境包无从导出。先用 app.create 或核对环境。",
648
+ });
649
+ scope = "environment";
650
+ // All VO fields are optional (probe: empty body exports the same
651
+ // metadata.zip); fixed body keeps the request deterministic.
652
+ bytes = await wireDownloadPackageStream(session, {
653
+ path: ENDPOINTS.environmentLifeCycleExport,
654
+ body: {},
655
+ });
656
+ }
657
+ const endpoint = scope === "application" ? ENDPOINTS.appPackageExport : ENDPOINTS.environmentLifeCycleExport;
658
+ const pkg = readExportPackage(bytes, endpoint);
659
+ const sha256 = sha256Of(bytes);
660
+ const root = packageRootOf(pkg.entries);
661
+ const assets = scope === "application" ? appPackageAssets(pkg.entries, root) : environmentPackageAssets(pkg.entries);
662
+ const defaultFileName = scope === "application" ? `${selected.code}-app-package-${sha256.slice(0, 8)}.zip` : `environment-lifecycle-${sha256.slice(0, 8)}.zip`;
663
+ const directoryFileName = scope === "application" ? `${selected.code}-app-package.zip` : "environment-lifecycle.zip";
664
+ const outPath = resolveExportTarget({ artifactsDir: ctx.artifactsDir, out: args.out, defaultFileName, directoryFileName });
665
+ writeExportPackage(outPath, bytes, "应用包导出");
666
+ const referenceCounts = references === undefined
667
+ ? undefined
668
+ : Object.fromEntries(Object.entries(references).map(([key, value]) => [key, arrayLength(value)]));
669
+ return {
670
+ scope,
671
+ endpoint,
672
+ ...(selected !== undefined
673
+ ? { application: { code: selected.code, name: selected.name } }
674
+ : { environment: { applicationCount: applications.length, applicationCodes: applications.map((row) => row.code) } }),
675
+ ...(referenceCounts !== undefined ? { includeDependencies: args.includeDependencies === true, references: referenceCounts } : {}),
676
+ outPath,
677
+ // CLI stdout sanitises local paths (ticket 103: the machine envelope
678
+ // must not leak host layout), so the basename is the stable handle an
679
+ // agent can combine with its cwd / the `out` it passed.
680
+ outFileName: basename(outPath),
681
+ bytes: bytes.length,
682
+ sha256,
683
+ entryCount: pkg.entryCount,
684
+ ...(scope === "application"
685
+ ? { entries: [...pkg.entries].map(([name, content]) => ({ name, bytes: content.length })) }
686
+ : { byArea: assets.byArea }),
687
+ assets,
688
+ notIncluded: scope === "application"
689
+ ? [
690
+ "未在 references 中选中的依赖(字典/角色/业务集成/数据源)——includeDependencies:true 才随包",
691
+ "运行数据(业务数据行)与环境级设置(组织/用户/许可证)",
692
+ ]
693
+ : [
694
+ "环境级数据字典/组织/角色/用户:环境包对每个应用固定使用空 references,只带被引用依赖之外的零依赖包",
695
+ "环境设置、许可证、登录配置与运行数据(业务数据行)",
696
+ ],
697
+ source: "platform app-package / lifecycle export (同步返回 ZIP;产物已落盘并校验字节数与 sha256)",
698
+ };
699
+ }, {
700
+ target: "app.export",
701
+ compact: (result) => {
702
+ const entries = Array.isArray(result.entries) ? result.entries : [];
703
+ if (entries.length <= 15)
704
+ return result;
705
+ return {
706
+ ...result,
707
+ entries: entries.slice(0, 15),
708
+ entriesOmitted: entries.length - 15,
709
+ entriesHint: "entries 只内联前 15 条;完整条目名与大小在 detailArtifactId(omc artifact get <id> --jq entries)",
710
+ };
711
+ },
712
+ }),
713
+ }));
319
714
  }
320
715
  //# sourceMappingURL=app.js.map
@@ -99,6 +99,30 @@ export const FIELD_RELEVANCE_WIRE = Object.freeze({
99
99
  options: '{"relevanceField":"<local WORK_SHEET field code>","referenceField":"<referenced field code>","referenceFieldPropertyType":<int>}',
100
100
  semantics: "references another field through a local WORK_SHEET field; NOT a model relation (no schemaCode/mappings)",
101
101
  });
102
+ /**
103
+ * NUMERICAL(2) display-format family — the designer's 47-option enum, captured
104
+ * live from the real designer on 2026-11-14 (r64b, Playwright: 数据模型 →
105
+ * 数据项 Edit → DataItem Attributes → Default Format, and the form control's
106
+ * Control Attributes → Display Format; both selects render the same 47 items).
107
+ *
108
+ * Every entry's INTERNAL value (read from the live Option components) is
109
+ * `<family><decimals-word>`; the field row stores it VERBATIM as
110
+ * `options.format` and the portal form reads it literally. The designer's own
111
+ * bizproperty/update body proves the storage shape:
112
+ * `options={"dictionaryData":"","virtualField":false,"scale":2,"format":"ratio.percentile"}`.
113
+ *
114
+ * Value semantics (portal-verified, same round): the stored value is a RATIO.
115
+ * 0.5 rendered as 50.00%, 50 rendered as 5000.00% — never store 50 for 50%.
116
+ */
117
+ export const FIELD_NUMERICAL_FORMAT_WIRE = Object.freeze({
118
+ decimalsWords: "0=integer(2000) · 1=tenths(2,000.0) · 2=percentile(2,000.00) · 3=Millimeter · 4=tenThousand · 5=hundredThousand · 6=millionDecimals · 7=tenMillionDecimals · 8=billionDecimals",
119
+ families: "no prefix=plain number · ratio.<word>=percentage (ratio=20%, ratio.tenths=20.0%, ratio.percentile=20.00%, …) · RMB.<word>=¥ · dollar.<word>=$ · euro.<word>=€ · HK.<word>=HK$ · none=raw value (no grouping, no forced decimals)",
120
+ valueSemantics: "options.format holds the platform constant verbatim (e.g. \"ratio.percentile\"); the value stays a ratio — 0.5 renders 50.00%, 50 renders 5000.00%. scale is the storage decimal count and should match the format's decimals word (scale 2 ↔ percentile / ratio.percentile).",
121
+ runtimePrecedence: "portal form resolves: FIELD ROW bizproperty.options.format (if the key is present) > form control bizsheet attributesJson[<code>].options.format > raw decimal. Live proof: control=integer + field=ratio.percentile rendered 987654.00%; field=absent + control=RMB.percentile rendered ¥9,876.54; field=\"percent\" (non-canonical) rendered the RAW 0.5 even though the control asked percent.",
122
+ normalization: "CLI accepts the canonical constants plus semantic aliases (percent/percentage/ratio, currency/rmb/¥, dollar/$, euro/€, hk/hkd/hk$) and rewrites aliases to the canonical constant before the wire (percent+scale:2 → ratio.percentile). Unknown words are passed through unchanged (the platform persists them, the portal then shows raw) — use the canonical values.",
123
+ listView: "list views carry a SEPARATE enum `displayFormat` on the column (percent 4/5/6/13/14, currency ¥ 7/15/16/31..34, dollar 8); listview.configure derives it from the field (scale + this format family). List-face rendering of percent was NOT exercised this round (no portal page permission on the probe app) — verify the list column after configuring.",
124
+ designerFaces: "数据模型 数据项 Edit → DataItem Attributes → Default Format writes bizproperty.options (field row). 表单设计 选中数值控件 → Model Attributes → Default Format writes bizsheet attributesJson[<code>].options (form control), and publishes format1=format. Control Attributes → Display Format is the synced mirror (disabled while 「Synchronize Default Format」/syncFormate=true).",
125
+ });
102
126
  /** Control-code classification for the 8.6.26 family (FIELD_CONTROL_CODES source of truth). */
103
127
  export const FIELD_CONTROL_CODE_STATUS = Object.freeze({
104
128
  known: Object.keys(FIELD_CONTROL_CODES).filter((code) => FIELD_CONTROL_CODES[Number(code)].status === "known").join(","),
@@ -127,6 +151,7 @@ export const FIELD_LANE_CONTRACT = Object.freeze({
127
151
  formulaConfig: FIELD_FORMULA_WIRE.innerConfig,
128
152
  formulaRuntimeVerification: FIELD_FORMULA_WIRE.runtimeVerification,
129
153
  relevanceDataOptions: FIELD_RELEVANCE_WIRE.options,
154
+ numericalFormat: JSON.stringify(FIELD_NUMERICAL_FORMAT_WIRE, null, 2),
130
155
  publishScope: "model",
131
156
  controlEmissionPolicy: "ticket 101: controls PHONE(24)/PHOTO(10) are blocked for creation (no BizPropertyType maps to them — BizPropertyType.java:27-54); Tab(500) is a layout container (DataModelInitUtils.java:61-75 recurses panels, never a field); CreatedDeptId(102) is a system-field projection (DefaultPropertyType.java:18-21 → DEPARTMENT_SELECTOR 60, BizMainSystemPropertyRegistry.java:88-101); the scaffold SKIPS any field type without a control mapping — unknown/blocked control types are never auto-created (fail-closed)",
132
157
  fieldRowDefaultPolicy: "ticket 108 determination (live 8.6.26 write+read 2026-09-15 + fwb 8.6.39 readback): the 2026-09-14 key unions are MULTI-FIELD UNIONS of designer rows, not per-field required keys — the platform accepts-and-persists minimal rows, so the minimal default + caller passthrough is the INTENTIONAL boundary. Selection families 12/13/14/15 MUST-FIXED to omit dictionaryData (designer rows carry none; live proves the platform merely accepts the extra key — omc_mcp_t108dd readback carried it only because we sent it). Families 0/1/2/9/11/17 keep the designer-carried {dictionaryData:\"\"}; DATE(3) keeps required format (BizObjectFacadeImpl.java:2949); ATTACHMENT(6) stays intentionally empty (system rows often have no options)",
@@ -141,6 +166,7 @@ export const FIELD_LANE_CONTRACT = Object.freeze({
141
166
  formulaConfig: Object.freeze([behaviorBinding("test/field-families.test.ts#field.create FORMULA persists formulaConfig + persistent", assertFieldContract)]),
142
167
  formulaRuntimeVerification: Object.freeze([behaviorBinding("test/field-families.test.ts#field.create FORMULA ACCEPTS aggregation written as an EXPRESSION (form 计算控件 subtable SUM; UI+runtime-verified 2026-10-07)", assertFieldContract)]),
143
168
  relevanceDataOptions: Object.freeze([behaviorBinding("test/field-families.test.ts#field.create RELEVANCE_DATA persists the referenceField options", assertFieldContract)]),
169
+ numericalFormat: Object.freeze([behaviorBinding("test/r64b-numeric-format.test.ts#numeric format: field.create canonicalises the alias before the wire (percent → ratio.percentile)", assertFieldContract)]),
144
170
  publishScope: Object.freeze([behaviorBinding("test/field-publish-batch.test.ts#field.publish batch: a single call publishes every draft field", assertFieldContract)]),
145
171
  controlEmissionPolicy: Object.freeze([behaviorBinding("test/ticket-101-control-coverage.test.ts#controls 24 (PHONE) and 10 (PHOTO) are declared blocked", assertFieldContract)]),
146
172
  fieldRowDefaultPolicy: Object.freeze([behaviorBinding("test/ticket-108-field-row-defaults.test.ts#intentional minimal defaults are pinned per the determination table", assertFieldContract)]),
@@ -172,7 +198,7 @@ export const FIELD_LANE_CONTRACT = Object.freeze({
172
198
  "For single/multi-select pass `choices` (e.g. [\"A\",\"B\",\"C\"]) or `options.optionsSet` with optionsType custom/dictionary/businessModel; dictionary uses checkedDictionary/checkedDictionaryCode, businessModel uses schemaCode/sheetDataItem.",
173
199
  "For a relation pass `relativeCode` and `options` (schemaCode/displayField/...). `searchFormula` and `conditions` are JSON strings for the relation data restriction/query conditions.",
174
200
  "For a relation display field the tool writes the field-row top-level `relativePropertyCode` = options.displayField (the runtime reads THAT key, not options.displayField — QueryRuntimeController.java:1214-1226) and defaults options.displayFieldType:0 + displayFieldFormat:\"\".",
175
- "For FORMULA pass `options.formulaConfig` (nested JSON string) + `options.persistent:true`; for RELEVANCE_DATA pass `options.relevanceField` + `options.referenceField` + `options.referenceFieldPropertyType`. 数值字段的小数位写 `options.scale`;顶层 `precision` 不被读取,若误传请改为 `precision→options.scale(数值小数位)`。",
201
+ "For FORMULA pass `options.formulaConfig` (nested JSON string) + `options.persistent:true`; for RELEVANCE_DATA pass `options.relevanceField` + `options.referenceField` + `options.referenceFieldPropertyType`. 数值字段的小数位写 `options.scale`;顶层 `precision` 不被读取,若误传请改为 `precision→options.scale(数值小数位)`。数值显示格式写 `options.format`(`ratio.percentile`=20.00%、`RMB.percentile`=¥2,000.00、`percentile`=2,000.00;**百分比存比值** 0.5→50.00%;别名 percent/currency 归一;全表见 contract 的 numericalFormat)。",
176
202
  "org 选人族(STAFF_SELECTOR 等 5/50/51/60/61)字段行 options 自动写成实例观测的发布安全形状(yst/fwb 发布面 2656 行:null 或 {defaultValue, mappings, virtualField[, noRepeat]};单选 defaultValue \"\",多选 [])。deptVisible/multi 是**表单控件面**判别键(disposeUpdateType/updateSelectionType 读 control.options,票 69 已由表单脚手架写入控件面),不出现在字段行。",
177
203
  ]),
178
204
  }),
@@ -183,6 +209,7 @@ export const FIELD_LANE_CONTRACT = Object.freeze({
183
209
  "字典-backed 可用 `syncDictionary:true` 重填 useDictionariesData;readback 带 face:\"draft\"。",
184
210
  "Use it to add relation `mappings` (source/target carry-through) or change field options. **关联填充映射的事实源是字段行 `options.mappings`**(真机 2026-10-14 中冶实证:改表单控件属性里的 mappings 会被平台按字段重算覆盖、回读不生效)。改映射的正确链:`field.update` 按完整 options 提交(只改 mappings,其余键 queryCode/displayField/schemaCode/conditions… 原值保留)→ `field.publish` → 已发布表单重派生一次:`form.draft`(**rebuild:false**,保留现有布局与已挂在线JS)重存 → `form.publish` → 回读核对。**不要用 field.update 的 cascadeRepublish 刷已带自定义布局/在线JS 的表单**——它会 rebuild 脚手架,可能动到现有自定义布局(rebuild:false 手动链才安全)。",
185
211
  "A relation's display field is the field-row top-level `relativePropertyCode` (options.displayField is mirrored but not what the runtime reads); the tool rewrites it when you pass a new displayField.",
212
+ "数值显示格式可改:`options.format`(白名单)用平台常量 `ratio.percentile`=20.00%、`RMB.percentile`=¥2,000.00、`integer/percentile`=普通数字,别名 percent/currency 会归一。字段行 format 优先于表单控件,改完 `field.publish` 即生效(真机 r64b 无需重建表单)。",
186
213
  "表单条件(`options.requiredFormula`(必填)/`readonlyCondition`(只读)/`displayFormula`(显示))会**自动配对**一条 `bizdatarule` type3/4/5 行:门户**运行时**读字段 options,表单设计器**设计态** Set/Unset 读 `bizdatarule/list`——只写 options 会让设计器显示 Unset。readback.formConditionSync 报 created/updated/deleted/skipped;清空条件传空串(如 requiredFormula:\"\")会同时删规则行;字段未发布时只写 options 并在 skipped 说明原因。",
187
214
  "Re-publish with field.publish for the change to take effect — or pass `cascadeRepublish:true` for the one-call chain: field.update → field.publish → form.draft(rebuild) → form.publish(force). The cascade re-scaffolds the default form from the published fields (non-structural control options are preserved); there is no cross-endpoint transaction, so a mid-chain failure is reported honestly as partial (status:partial) with steps/failedStep/envelope (the completed prefix stays).",
188
215
  "form.publish(rebuild:true) is the same form-side refresh without re-touching the field: it discards the existing draft, re-scaffolds from the published face, and force-promotes.",
@@ -207,6 +234,8 @@ export function assertFieldContract() {
207
234
  throw new Error("field contract must carry the FORMULA formulaConfig wire facts");
208
235
  if (!String(FIELD_LANE_CONTRACT.wire.relevanceDataOptions).includes("relevanceField"))
209
236
  throw new Error("field contract must carry the RELEVANCE_DATA referenceField wire facts");
237
+ if (!String(FIELD_LANE_CONTRACT.wire.numericalFormat).includes("ratio.percentile") || !String(FIELD_LANE_CONTRACT.wire.numericalFormat).includes("0.5 renders 50.00%"))
238
+ throw new Error("field contract must carry the NUMERICAL display-format enum and the ratio value semantics");
210
239
  if (!String(FIELD_LANE_CONTRACT.wire.controlEmissionPolicy).includes("BizPropertyType.java:27-54"))
211
240
  throw new Error("field contract must carry the ticket-101 control-emission policy with its enum evidence");
212
241
  if (!String(FIELD_LANE_CONTRACT.wire.fieldRowDefaultPolicy).includes("MUST-FIXED"))
@@ -217,7 +246,7 @@ export function assertFieldContract() {
217
246
  throw new Error("field contract must carry the blocked families");
218
247
  if (FIELD_LANE_CONTRACT.wire.publishScope !== "model")
219
248
  throw new Error("field contract pins the publish scope to model");
220
- assertDescriptionCarries(FIELD_LANE_CONTRACT, "field.create", ["bizproperty/create", "OCR/ELECTRONIC_SIGN", "`choices`", "options.optionsSet", "`relativeCode`", "searchFormula", "`options.formulaConfig`", "`options.relevanceField`", "precision→options.scale", "code_reserved", "WORK_SHEET"]);
249
+ assertDescriptionCarries(FIELD_LANE_CONTRACT, "field.create", ["bizproperty/create", "OCR/ELECTRONIC_SIGN", "`choices`", "options.optionsSet", "`relativeCode`", "searchFormula", "`options.formulaConfig`", "`options.relevanceField`", "precision→options.scale", "code_reserved", "WORK_SHEET", "options.format", "百分比存比值", "numericalFormat"]);
221
250
  assertDescriptionCarries(FIELD_LANE_CONTRACT, "field.update", ["bizproperty/update", "`options`", "field.publish", "cascadeRepublish", "form.draft(rebuild)", "form.publish(force)", "published fields", "non-structural", "partial"]);
222
251
  assertDescriptionCarries(FIELD_LANE_CONTRACT, "field.publish", ["bizproperty/publish", "published", "Model-scoped", "publishedCodes", "unpublishedRequested", "nonexistentCodes", "stillDraftCodes"]);
223
252
  assertDescriptionCarries(FIELD_LANE_CONTRACT, "field.delete", ["bizproperty/force_delete", "absence"]);
@@ -527,7 +527,7 @@ export function registerFieldLane(tools) {
527
527
  writeTool({
528
528
  tools,
529
529
  name: "field.create",
530
- search: { intents: ["加字段", "新增字段", "添加字段", "加一个字段", "单据号字段", "序列号字段", "编号规则字段"] },
530
+ search: { intents: ["加字段", "新增字段", "添加字段", "加一个字段", "单据号字段", "序列号字段", "编号规则字段", "百分比字段", "占比字段", "百分号显示"] },
531
531
  lane: FIELD_LANE,
532
532
  scope: FIELD_TOOLS["field.create"].scope,
533
533
  description: FIELD_TOOLS["field.create"].description,
@@ -1255,6 +1255,11 @@ async function runFieldUpdate(session, args) {
1255
1255
  "dictionaryData", "optionsSet", "mappings", "schemaCode", "queryCode", "displayField", "displayFieldType", "displayFieldFormat",
1256
1256
  "relativePropertyMatchCode", "relativePropertyCode", "linkMode", "showStyle", "searchFormula", "conditions",
1257
1257
  "requiredFormula", "readonlyCondition", "displayFormula", "readonlyFormula", "scale",
1258
+ // r64b (live 2026-11-14): the numeric DISPLAY FORMAT. The designer writes it
1259
+ // to this very row (数据项 Edit → Default Format → bizproperty/update
1260
+ // options.format="ratio.percentile"), and the portal form reads it with
1261
+ // priority over the form control's own format. Canonicalised before the wire.
1262
+ "format",
1258
1263
  ]);
1259
1264
  const changedOptionKeys = requestedChanges.filter((field) => field.startsWith("options.")).map((field) => field.slice("options.".length));
1260
1265
  const immutableOptionKeys = changedOptionKeys.filter((key) => !mutableOptionKeys.has(key));
@@ -1365,6 +1370,7 @@ async function runFieldUpdate(session, args) {
1365
1370
  face: "draft",
1366
1371
  impact,
1367
1372
  fieldPresent: after !== undefined,
1373
+ ...(prepared.formatNormalized !== undefined ? { formatNormalized: prepared.formatNormalized } : {}),
1368
1374
  ...(after?.name !== undefined || prepared.name !== undefined || record.name !== undefined || record.propertyName !== undefined
1369
1375
  ? { name: after?.name ?? prepared.name ?? record.name ?? record.propertyName }
1370
1376
  : {}),
@@ -9,7 +9,7 @@ import { defineTool, ToolInputError, ToolRefusalError } from "../tool-types.js";
9
9
  import { wireCall, wireRows, WireError } from "../wire.js";
10
10
  import { QUERY_ACTION_TYPE } from "omc-core/list-view-wire";
11
11
  import { resolveModelTreeNode } from "./model.js";
12
- import { SYSTEM_FIELD_CODES } from "../field-families.js";
12
+ import { NUMERICAL_FORMAT_DECIMALS, SYSTEM_FIELD_CODES, canonicalNumericalFormat } from "../field-families.js";
13
13
  import { LIST_VIEW_LANE_CONTRACT } from "./list-view-contract.js";
14
14
  import { assertListViewConfigureShape, decodeActionRow, decodeButtonRow, decodeConditionRow, decodeGantt, decodePresentation, decodeSortRow, listViewActionArg, listViewButtonArg, listViewConditionArg, listViewGanttArg, listViewMultiTableHeaderArg, listViewOptionsArg, listViewPresentationArg, listViewQueryLayerArg, listViewSortArg, mergeActions, PLATFORM_DEFAULT_LIST_ACTIONS, normalizeActions, normalizeButtons, normalizeConditions, normalizeGantt, normalizePresentation, normalizeSorts, parseConditionOptions, presentationTypeArg, readArray, resolveFieldRef, buttonsRenderCompat, columnsRenderCompat, } from "./list-view-shapes.js";
15
15
  // Ticket 53: every shape (enum/zod/encode/decode/lint) lives once in
@@ -73,11 +73,31 @@ function conditionValueEqual(left, right) {
73
73
  */
74
74
  export function numericDisplayFormat(options) {
75
75
  const opts = fieldOptions(options);
76
- const format = String(opts.format ?? "decimal");
77
76
  const scale = Number(opts.scale ?? 0) || 0;
78
77
  const decimalByScale = { 0: 1, 1: 2, 2: 3, 3: 11, 4: 12, 5: 27, 6: 28, 7: 29, 8: 30 };
79
78
  const currencyByScale = { 2: 7, 3: 15, 4: 16, 5: 31, 6: 32, 7: 33, 8: 34 };
80
79
  const percentByScale = { 0: 4, 1: 5, 2: 6, 3: 13, 4: 14 };
80
+ // r64b (live 2026-11-14): the field row may carry the designer's canonical
81
+ // constant (`ratio.percentile`, `RMB.percentile`, …) instead of a semantic
82
+ // word — the designer writes exactly that. Resolve the family + decimals from
83
+ // the constant before the legacy alias checks.
84
+ const canonical = canonicalNumericalFormat(opts.format, scale);
85
+ if (canonical !== undefined && canonical !== "none") {
86
+ const dot = canonical.indexOf(".");
87
+ const family = dot > 0 ? canonical.slice(0, dot).toLowerCase() : canonical === "ratio" ? "ratio" : "";
88
+ const word = dot > 0 ? canonical.slice(dot + 1) : canonical;
89
+ const decimals = NUMERICAL_FORMAT_DECIMALS[word];
90
+ const effective = decimals ?? (canonical === "ratio" ? 0 : scale);
91
+ if (family === "ratio")
92
+ return percentByScale[effective] ?? 6;
93
+ if (family === "rmb")
94
+ return currencyByScale[effective] ?? 7;
95
+ if (family === "dollar")
96
+ return 8;
97
+ if (family === "")
98
+ return decimalByScale[effective] ?? 3;
99
+ }
100
+ const format = String(opts.format ?? "decimal");
81
101
  if (format === "currency" || format === "rmb" || format === "¥")
82
102
  return currencyByScale[scale] ?? 7;
83
103
  if (format === "percent" || format === "percentage")
@@ -108,11 +108,41 @@ const numericTwoDecimals = Object.freeze({
108
108
  tool: "field.create",
109
109
  args: { environment, schemaCode: model, code: "applyAmount", name: "申请金额", propertyType: "NUMERICAL", options: { scale: 2 } },
110
110
  preconditions: ["模型已存在"],
111
- conditionalRequirements: ["NUMERICAL 必须显式 options.scale:scale = 小数位数(0=整数, 1=1位, 2=2位 … 8=8位);缺 scale 门户显示裸 decimal 且工具会拒绝。"],
111
+ conditionalRequirements: [
112
+ "NUMERICAL 必须显式 options.scale:scale = 小数位数(0=整数, 1=1位, 2=2位 … 8=8位);缺 scale 门户显示裸 decimal 且工具会拒绝。",
113
+ "要**千分位/百分比/货币符号**再加 `options.format`(平台常量:普通数字 `tenths/percentile/…`、百分比 `ratio.*`、货币 `RMB.*`);百分比见 recipe `numeric-percent`。注意 `percentile` 是「两位小数」不是百分比。",
114
+ ],
112
115
  priorToolReferences: [{ tool: "discover_environment", args: { environment }, purpose: "确认目标模型已存在" }],
113
116
  dryRun: { supported: true, command: `omc call field.create --env ${environment} --dry-run --args '<recipe.args>'`, notes: "dry-run 校验 propertyType/scale/治理,不创建" },
114
117
  expectedReadback: { readback: { draftFieldPresent: true }, next: ["field.publish"] },
115
- refusalRecovery: [{ code: "field-options-shape", action: "NUMERICAL 必须带 options.scale;金额两位小数用 scale:2,整数用 scale:0" }, ...commonRecovery],
118
+ refusalRecovery: [{ code: "field-options-shape", action: "NUMERICAL 必须带 options.scale;金额两位小数用 scale:2,整数用 scale:0。要百分比/千分位/货币加 options.format(见 recipe numeric-percent)" }, ...commonRecovery],
119
+ requiresEnvironmentDerivedIds: false,
120
+ });
121
+ const numericPercent = Object.freeze({
122
+ id: "numeric-percent",
123
+ title: "数值字段:百分比(存比值 0.5=50.00%,format 用 ratio.<小数位>)",
124
+ status: "offline-valid",
125
+ aliases: ["百分位", "百分比", "按百分号显示", "占比字段", "百分比字段", "百分之", "比率字段", "percent"],
126
+ tool: "field.create",
127
+ args: { environment, schemaCode: model, code: "completionRate", name: "完成率", propertyType: "NUMERICAL", options: { scale: 2, format: "ratio.percentile" } },
128
+ preconditions: [
129
+ "普通数值字段 + 显示格式(不是公式字段/文字字段)。",
130
+ "**存比值不存百分数**:真机门户 0.5→`50.00%`、50→`5000.00%`;来源给百分数先 ÷100。",
131
+ ],
132
+ conditionalRequirements: [
133
+ "`options.format` 必须是平台常量:百分比 `ratio`(20%)/`ratio.tenths`(20.0%)/`ratio.percentile`(20.00%),普通数字 `integer/tenths/percentile…`,货币 `RMB./dollar./euro./HK.` 前缀,`none`=裸值;`percentile` 是两位小数**不是**百分比。全表见 `omc contract field-families` 的 numericalFormat。",
134
+ "`scale` 与小数据对齐(两位百分比 = `scale:2`+`ratio.percentile`);只写 scale 门户显示 `2,000.00` 普通数字。别名 percent/currency/¥ 由 CLI 归一为常量再落库;**别绕过 CLI 把 `percent` 写进字段行**——平台字面读不懂,门户跌回裸值(真机 r64b:format:\"percent\" → `0.5`)。",
135
+ "生效:字段行 format 优先于表单控件 format,`field.publish` 后即生效(无需重建表单);列表是另一套列枚举,配完看一眼列表列。",
136
+ ],
137
+ priorToolReferences: [
138
+ { tool: "field.list", args: { environment, schemaCode: model, code: "completionRate", full: true }, purpose: "确认 code 未占用(默认清单面不回 options)" },
139
+ ],
140
+ dryRun: { supported: true, command: `omc call field.create --env ${environment} --dry-run --args '<recipe.args>'`, notes: "dry-run 校验 propertyType/scale/format 归一化,不创建" },
141
+ expectedReadback: { performed: { errcode: 0 }, readback: { draftFieldPresent: true, normalized: { format: { from: "percent", to: "ratio.percentile" } } }, verification: "field.list {full:true} 回读 options.format=ratio.percentile;门户 0.5 → 50.00%", next: ["field.publish", "门户表单核对 0.5→50.00%"] },
142
+ refusalRecovery: [
143
+ { code: "field-options-shape", action: "百分比用 `options:{scale:2,format:\"ratio.percentile\"}`;只写 scale 只得到 2,000.00 的普通数字" },
144
+ ...commonRecovery,
145
+ ],
116
146
  requiresEnvironmentDerivedIds: false,
117
147
  });
118
148
  const dictionarySelection = Object.freeze({
@@ -389,6 +419,6 @@ const externalLookupModel = Object.freeze({
389
419
  });
390
420
  export const FIELD_METADATA = Object.freeze({
391
421
  "field.update": Object.freeze({ recipes: [formConditionalRequired, formAlwaysReadonly, formConditionalReadonly], relatedTools: ["field.list", "field.publish", "form.draft", "form.publish"] }),
392
- "field.create": Object.freeze({ recipes: [fieldSerialNumber, numericTwoDecimals, dictionarySelection, dictionaryMultiSelection, childTable, businessModelDropdown, formulaAggregationCrossModel, formulaExpressionSameModel, externalLookupModel], relatedTools: ["dictionary.names", "dictionary.records", "discover_environment", "field.list", "field.publish", "form.draft", "configure_form", "form.publish"] }),
422
+ "field.create": Object.freeze({ recipes: [fieldSerialNumber, numericTwoDecimals, numericPercent, dictionarySelection, dictionaryMultiSelection, childTable, businessModelDropdown, formulaAggregationCrossModel, formulaExpressionSameModel, externalLookupModel], relatedTools: ["dictionary.names", "dictionary.records", "discover_environment", "field.list", "field.publish", "form.draft", "configure_form", "form.publish"] }),
393
423
  });
394
424
  //# sourceMappingURL=field.js.map
package/dist/wire.js CHANGED
@@ -313,6 +313,63 @@ export async function wireDownloadBuffer(session, call) {
313
313
  throw new WireError("malformed-envelope", `empty or non-buffer body for ${call.path} (POST)`);
314
314
  return response.body;
315
315
  }
316
+ /**
317
+ * r64b — binary POST download whose refusals stay ENVELOPES.
318
+ *
319
+ * The app-package exporters (`/app/apppackage/export`,
320
+ * `/lifeCycle/apppackage/lifeCycleExport`) stream a ZIP on success, but every
321
+ * business refusal is still `HTTP 200 + application/json` with
322
+ * `{errcode, errmsg}` (live 1.1.25: 10005 应用编码不能为空, 600005 应用不存在!,
323
+ * 40007 请求方法不正确 — the admin UI re-parses the arraybuffer as JSON for
324
+ * exactly this reason). Treating any 200 body as a package would hand back a
325
+ * "successful" 100-byte artifact that is not a zip, so the JSON-envelope face
326
+ * is classified FIRST: errcode≠0 → business refusal (definitive, no retry);
327
+ * errcode=0 JSON → malformed (an exporter must not answer an envelope).
328
+ */
329
+ export async function wireDownloadPackageStream(session, call) {
330
+ const response = await session
331
+ .request({ path: call.path, method: "POST", ...(call.body === undefined ? {} : { body: call.body }), responseType: "buffer" })
332
+ .catch((error) => {
333
+ if (error instanceof CloudPivotRequestTimeoutError)
334
+ throw new WireError("transport", error.message);
335
+ throw error;
336
+ });
337
+ if (response.status < 200 || response.status >= 300)
338
+ throw new WireError("http-status", `HTTP ${response.status} for ${call.path} (POST)`, undefined, { httpStatus: response.status });
339
+ const classifyEnvelope = (value) => {
340
+ if (typeof value.errcode !== "number")
341
+ throw new WireError("malformed-envelope", `${call.path} (POST) answered a JSON body without a numeric errcode`);
342
+ const message = typeof value.errmsg === "string" ? value.errmsg : "CloudPivot refused the export";
343
+ if (value.errcode !== 0)
344
+ throw new WireError("business", `errcode ${value.errcode} for ${call.path}: ${message}`, value.errcode);
345
+ throw new WireError("malformed-envelope", `${call.path} (POST) answered a JSON envelope (errcode 0) instead of a ZIP stream`);
346
+ };
347
+ // An in-process transport (tests, MCP shims) may hand back the decoded
348
+ // envelope object instead of bytes; classify it exactly like the JSON body
349
+ // an HTTP transport would deliver.
350
+ if (!Buffer.isBuffer(response.body)) {
351
+ if (response.body && typeof response.body === "object")
352
+ return classifyEnvelope(response.body);
353
+ throw new WireError("malformed-envelope", `empty or non-buffer body for ${call.path} (POST)`);
354
+ }
355
+ if (response.body.length === 0)
356
+ throw new WireError("malformed-envelope", `empty or non-buffer body for ${call.path} (POST)`);
357
+ if (response.body[0] === 0x7b) {
358
+ const text = response.body.toString("utf8");
359
+ let envelope;
360
+ try {
361
+ envelope = JSON.parse(text);
362
+ }
363
+ catch {
364
+ // A body that merely starts with `{` (never a valid zip either) keeps the
365
+ // malformed classification below; do not guess a business errcode.
366
+ envelope = undefined;
367
+ }
368
+ if (envelope && typeof envelope === "object")
369
+ return classifyEnvelope(envelope);
370
+ }
371
+ return response.body;
372
+ }
316
373
  /**
317
374
  * Ticket 106 — multipart file upload (POST /runtime/query/upload_file). The
318
375
  * endpoint answers a PLAIN STRING refId (not an envelope;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.6.54",
3
+ "version": "0.6.55",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "commander": "14.0.3",
59
- "omc-core": "0.6.54",
59
+ "omc-core": "0.6.55",
60
60
  "proper-lockfile": "4.1.2",
61
61
  "write-file-atomic": "6.0.0",
62
62
  "zod": "^3.23.8",
@@ -74,6 +74,6 @@
74
74
  "directory": "packages/omc-cli"
75
75
  },
76
76
  "optionalDependencies": {
77
- "@stalfh233/omc-fake-platform": "0.6.54"
77
+ "@stalfh233/omc-fake-platform": "0.6.55"
78
78
  }
79
79
  }
@@ -25,7 +25,7 @@ only the section for the capability you need —
25
25
  | 能力 | 一句话 | 能做哪些事(需求线索) | 读哪节 |
26
26
  | --- | --- | --- | --- |
27
27
  | 环境治理 `environment` | 环境发现/指纹/就绪 | 环境、指纹、版本、连接、登录、就绪、发现 | [环境治理](#环境治理-environment) |
28
- | 应用 `app` | 应用包生命周期 | 应用、门户、分组、app 建删移 | [应用](#应用-app) |
28
+ | 应用 `app` | 应用包生命周期 + 导出备份 | 应用、门户、分组、app 建删移、**导出应用/导出应用包/环境备份/迁移** | [应用](#应用-app) |
29
29
  | 应用目录(分组)`folder` | 应用树目录/分组 | 目录、分组、文件夹、应用树、移动模型到目录 | [应用目录](#应用目录分组-folder) |
30
30
  | 数据字典 `dictionary` | 字典与字典记录 | 字典、选项来源、树型、键值、字段下拉来源 | [数据字典](#数据字典-dictionary) |
31
31
  | 业务模型 `model` | 模型生命周期 | 模型、对象、表、主数据、改名、物理删除 | [业务模型](#业务模型-model) |
@@ -56,8 +56,9 @@ only the section for the capability you need —
56
56
 
57
57
  ## 应用 `app`
58
58
 
59
- - **能做哪些事**:列出应用包、创建、改名/分组移动、删除(删除级联其模型);**应用树目录(分组)的建/改名/挂载/删**,以及把模型放进目录。
60
- - **工具**:`app.list`、`app.create`、`app.update`、`app.delete`、`folder.tree`、`folder.create`、`folder.update`、`folder.delete`
59
+ - **能做哪些事**:列出应用包、创建、改名/分组移动、删除(删除级联其模型);**导出配置包做备份/迁移**(单应用包或整环境生命周期包);**应用树目录(分组)的建/改名/挂载/删**,以及把模型放进目录。
60
+ - **工具**:`app.list`、`app.create`、`app.update`、`app.delete`、`app.export`、`folder.tree`、`folder.create`、`folder.update`、`folder.delete`
61
+ - **导出(r64b)**:`app.export` 省略 `applicationCode` = **整环境**(平台 lifeCycleExport:全部应用包 + 应用分组 + 业务集成服务 + 数据源,`metadata/…` 结构);指定 `applicationCode` = 单个应用包(`meta/{dm,form,view,workflow,report}` + `dependencies/platform/*`)。`includeDependencies:true` 只对单应用有效,把该应用引用的字典/角色/业务集成/数据源一并打进包;环境包平台固定空引用(所以环境范围传 true 会被拒)。ZIP 同步返回,工具核 `PK` 头与条目数后才落盘(默认会话 artifacts,`out` 指定配置根内路径,0600),回执给 `outPath/bytes/sha256/条目清单/资产计数`。平台**没有按资产类型筛选**的参数(不收 `assetTypes`);环境级数据字典/组织/角色/用户不在环境包里。
61
62
  - **边界 / 陷阱**:**目录(分组)是应用树节点**:`folder.create` 省略 `parentId` 建的是顶层目录(平台默认挂应用根)、平台**不校验重名**(工具默认按同父同名拒绝)、`folder.delete` **非递归**(有子节点回 `DIRECTORY_NOT_EMPTY`)、树是嵌套 `children`(`folder.tree` 已递归展平给 `path/depth`,只看顶层会误判“没建成”)。模型进目录用 `model.move`。环境已带默认 `applicationCode`,建模**不必**先建应用;`app` 未进 intent 声明式面。**要把 intent 落到新应用**:`omc call app.create`(原子面)→ 把该环境的 `applicationCode` 指向新应用(`omc setup` 重配或改 `~/.config/omc/` 环境配置)→ 再 `intent plan/apply`,模型即落在新应用(用户实测摩擦:曾误以为应用能进 intent)。
62
63
 
63
64
  ## 应用目录(分组)`folder`