bpmax-cli 0.2.1-beta.30 → 0.2.1-beta.31

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.
package/dist/bin.js CHANGED
@@ -345,6 +345,20 @@ function capabilityForRequest(method, path16) {
345
345
  if (normalizedMethod === "DELETE" && /^\/role\/[^/]+$/.test(normalizedPath)) return "config.role.delete";
346
346
  if (normalizedMethod === "DELETE" && /^\/point\/[^/]+$/.test(normalizedPath)) return "config.role.delete";
347
347
  if (normalizedMethod === "DELETE" && /^\/user_role\/[^/]+$/.test(normalizedPath)) return "config.role.delete";
348
+ if (normalizedMethod === "GET" && /^\/group\/\d+$/.test(normalizedPath)) return "config.team.export";
349
+ if (normalizedMethod === "POST" && normalizedPath === "/group") return "config.team.create";
350
+ if (normalizedMethod === "PUT" && /^\/group\/\d+$/.test(normalizedPath)) return "config.team.submit";
351
+ if (normalizedMethod === "DELETE" && /^\/group\/\d+$/.test(normalizedPath)) return "config.team.delete";
352
+ if (normalizedMethod === "GET" && /^\/user\/\d+$/.test(normalizedPath)) return "config.user.export";
353
+ if (normalizedMethod === "POST" && normalizedPath === "/user") return "config.user.create";
354
+ if (normalizedMethod === "PUT" && /^\/user\/\d+$/.test(normalizedPath)) return "config.user.submit";
355
+ if (normalizedMethod === "DELETE" && /^\/user\/\d+$/.test(normalizedPath)) return "config.user.delete";
356
+ for (const [resource, capability] of [["user_model", "config.user_model"], ["group_model", "config.group_model"]]) {
357
+ if (normalizedMethod === "GET" && (normalizedPath === `/${resource}/get_by_uuid` || new RegExp(`^/${resource}/[^/]+$`).test(normalizedPath))) return `${capability}.export`;
358
+ if (normalizedMethod === "POST" && normalizedPath === `/${resource}`) return `${capability}.create`;
359
+ if (normalizedMethod === "PUT" && new RegExp(`^/${resource}/[^/]+$`).test(normalizedPath)) return `${capability}.submit`;
360
+ if (normalizedMethod === "DELETE" && new RegExp(`^/${resource}/[^/]+$`).test(normalizedPath)) return `${capability}.delete`;
361
+ }
348
362
  if (normalizedMethod === "POST" && normalizedPath === "/configuration") return "config.nav_config.create";
349
363
  if (normalizedMethod === "PUT" && /^\/configuration\/[^/]+$/.test(normalizedPath)) return "config.nav_config.submit";
350
364
  if (normalizedMethod === "DELETE" && /^\/configuration\/[^/]+$/.test(normalizedPath)) return "config.nav_config.delete";
@@ -478,15 +492,16 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
478
492
  // package.json
479
493
  var package_default = {
480
494
  name: "bpmax-cli",
481
- version: "0.2.1-beta.30",
495
+ version: "0.2.1-beta.31",
482
496
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
483
497
  type: "module",
484
498
  bin: {
485
- "bpmax-cli": "dist/bin.js"
499
+ "bpmax-cli": "scripts/run-source-cli.mjs"
486
500
  },
487
501
  files: [
488
502
  "dist",
489
503
  "scripts/install-skills.mjs",
504
+ "scripts/run-source-cli.mjs",
490
505
  "skills",
491
506
  "!skills/**/__pycache__/**",
492
507
  "!skills/**/*.py[cod]",
@@ -504,7 +519,7 @@ var package_default = {
504
519
  node: ">=18"
505
520
  },
506
521
  dependencies: {
507
- "@clack/prompts": "^1.2.0",
522
+ "@clack/prompts": "1.0.1",
508
523
  axios: "^1.9.0",
509
524
  commander: "^14.0.0",
510
525
  jszip: "^3.10.1",
@@ -2163,7 +2178,8 @@ async function checkSkillsSync(currentVersion, configDir = getConfigDir(), agent
2163
2178
  return { current: target, target, inSync: true };
2164
2179
  }
2165
2180
  const current = await readSkillsStamp(configDir);
2166
- return { current, target, inSync: current === target };
2181
+ const inSync = agent ? current === target : current === target || current.startsWith(`${target}:`);
2182
+ return { current, target, inSync };
2167
2183
  }
2168
2184
  async function resolvePackageRootFrom(entrypointPath) {
2169
2185
  const entryDir = path3.dirname(entrypointPath);
@@ -2328,9 +2344,9 @@ function validateAllowedPath(relative) {
2328
2344
  }
2329
2345
  return void 0;
2330
2346
  }
2331
- function validateSafeSkillName(name, issues, context = "Plugin skill") {
2347
+ function validateSafeSkillName(name, issues, context2 = "Plugin skill") {
2332
2348
  if (!safeSkillNamePattern.test(name)) {
2333
- issues.push(issue2("error", "invalid_name", `${context} name must match ${safeSkillNamePattern.source}: ${name}`));
2349
+ issues.push(issue2("error", "invalid_name", `${context2} name must match ${safeSkillNamePattern.source}: ${name}`));
2334
2350
  }
2335
2351
  }
2336
2352
  function assertSafeStateSegment(value, label) {
@@ -2381,33 +2397,33 @@ function normalizePluginConfigAdapterManifests(value) {
2381
2397
  version: typeof item.version === "string" || typeof item.version === "number" ? item.version : void 0
2382
2398
  })).filter((item) => item.domain && item.plugin_key && item.capability_prefix && item.adapter);
2383
2399
  }
2384
- function validatePluginConfigAdapterManifest(item, issues, context) {
2400
+ function validatePluginConfigAdapterManifest(item, issues, context2) {
2385
2401
  if (!/^[a-z][a-z0-9-]*$/.test(item.domain)) {
2386
- issues.push(issue2("error", "invalid_config_adapter_domain", `${context} config adapter domain must be kebab-case.`));
2402
+ issues.push(issue2("error", "invalid_config_adapter_domain", `${context2} config adapter domain must be kebab-case.`));
2387
2403
  }
2388
2404
  if (!/^plugin_[A-Za-z0-9_]+$/.test(item.plugin_key)) {
2389
- issues.push(issue2("error", "invalid_config_adapter_plugin_key", `${context} config adapter plugin_key must look like plugin_xxx.`));
2405
+ issues.push(issue2("error", "invalid_config_adapter_plugin_key", `${context2} config adapter plugin_key must look like plugin_xxx.`));
2390
2406
  }
2391
2407
  if (!item.capability_prefix.startsWith(`config.plugin.${item.plugin_key}.`)) {
2392
- issues.push(issue2("error", "invalid_config_adapter_capability", `${context} config adapter capability_prefix must start with config.plugin.${item.plugin_key}.`));
2408
+ issues.push(issue2("error", "invalid_config_adapter_capability", `${context2} config adapter capability_prefix must start with config.plugin.${item.plugin_key}.`));
2393
2409
  }
2394
2410
  const normalized = item.adapter.replace(/\\/g, "/");
2395
2411
  const parts = normalized.split("/");
2396
2412
  if (!normalized.startsWith("config/") || parts.some((part) => part === "" || part === "." || part === "..") || normalized.startsWith("/") || path4.isAbsolute(normalized) || !normalized.endsWith(".json")) {
2397
- issues.push(issue2("error", "invalid_config_adapter_path", `${context} config adapter path must be a config/*.json file.`));
2413
+ issues.push(issue2("error", "invalid_config_adapter_path", `${context2} config adapter path must be a config/*.json file.`));
2398
2414
  }
2399
2415
  }
2400
- function validatePluginConfigAdapterEndpoint(endpoints, pluginKey, operation, allowedMethods, issues, context) {
2416
+ function validatePluginConfigAdapterEndpoint(endpoints, pluginKey, operation, allowedMethods, issues, context2) {
2401
2417
  const endpoint = endpoints[operation];
2402
2418
  if (endpoint === void 0) return;
2403
2419
  if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint)) {
2404
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} must be an object.`));
2420
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context2} config adapter endpoint ${operation} must be an object.`));
2405
2421
  return;
2406
2422
  }
2407
2423
  const value = endpoint;
2408
2424
  const method = typeof value.method === "string" ? value.method : allowedMethods[0];
2409
2425
  if (!allowedMethods.includes(method)) {
2410
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} method must be ${allowedMethods.join(" or ")}.`));
2426
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context2} config adapter endpoint ${operation} method must be ${allowedMethods.join(" or ")}.`));
2411
2427
  }
2412
2428
  const endpointPath2 = typeof value.path === "string" ? value.path : "";
2413
2429
  const variants = [endpointPath2];
@@ -2419,7 +2435,7 @@ function validatePluginConfigAdapterEndpoint(endpoints, pluginKey, operation, al
2419
2435
  variants.push(decoded);
2420
2436
  current = decoded;
2421
2437
  } catch {
2422
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} contains malformed URL encoding.`));
2438
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context2} config adapter endpoint ${operation} contains malformed URL encoding.`));
2423
2439
  return;
2424
2440
  }
2425
2441
  }
@@ -2428,43 +2444,43 @@ function validatePluginConfigAdapterEndpoint(endpoints, pluginKey, operation, al
2428
2444
  return !variant.startsWith("/") || variant.includes("\\") || /%(?:2e|2f|5c)/i.test(variant) || endpointParts.some((part) => part === "." || part === "..");
2429
2445
  });
2430
2446
  if (hasUnsafePath) {
2431
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} contains an unsafe path.`));
2447
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context2} config adapter endpoint ${operation} contains an unsafe path.`));
2432
2448
  return;
2433
2449
  }
2434
2450
  const expectedPrefix = `/${pluginKey}`;
2435
2451
  if (!endpointPath2 || variants.some((variant) => !variant.startsWith(`${expectedPrefix}/`) && variant !== expectedPrefix)) {
2436
- issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context} config adapter endpoint ${operation} must stay under ${expectedPrefix}.`));
2452
+ issues.push(issue2("error", "invalid_config_adapter_endpoint", `${context2} config adapter endpoint ${operation} must stay under ${expectedPrefix}.`));
2437
2453
  }
2438
2454
  }
2439
- function validatePluginConfigAdapterEndpoints(endpoints, pluginKey, issues, context) {
2440
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "list", ["GET"], issues, context);
2441
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "get", ["GET"], issues, context);
2442
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "create", ["POST"], issues, context);
2443
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "update", ["PUT"], issues, context);
2444
- validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "test", ["POST"], issues, context);
2455
+ function validatePluginConfigAdapterEndpoints(endpoints, pluginKey, issues, context2) {
2456
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "list", ["GET"], issues, context2);
2457
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "get", ["GET"], issues, context2);
2458
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "create", ["POST"], issues, context2);
2459
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "update", ["PUT"], issues, context2);
2460
+ validatePluginConfigAdapterEndpoint(endpoints, pluginKey, "test", ["POST"], issues, context2);
2445
2461
  }
2446
- async function validatePluginConfigAdapterFile(skillDir, item, issues, context) {
2462
+ async function validatePluginConfigAdapterFile(skillDir, item, issues, context2) {
2447
2463
  const adapterFile = path4.join(skillDir, item.adapter);
2448
2464
  if (!await exists2(adapterFile)) {
2449
- issues.push(issue2("error", "missing_config_adapter_file", `${context} config adapter file not found: ${item.adapter}`));
2465
+ issues.push(issue2("error", "missing_config_adapter_file", `${context2} config adapter file not found: ${item.adapter}`));
2450
2466
  return;
2451
2467
  }
2452
2468
  try {
2453
2469
  const parsed = JSON.parse(await readFile6(adapterFile, "utf8"));
2454
2470
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || parsed.version !== 1 || parsed.domain !== item.domain || parsed.plugin_key !== item.plugin_key || parsed.capability_prefix !== item.capability_prefix || !parsed.endpoints || typeof parsed.endpoints !== "object" || Array.isArray(parsed.endpoints)) {
2455
- issues.push(issue2("error", "invalid_config_adapter_file", `${context} config adapter file must match manifest and declare endpoints: ${item.adapter}`));
2471
+ issues.push(issue2("error", "invalid_config_adapter_file", `${context2} config adapter file must match manifest and declare endpoints: ${item.adapter}`));
2456
2472
  return;
2457
2473
  }
2458
- validatePluginConfigAdapterEndpoints(parsed.endpoints, item.plugin_key, issues, context);
2474
+ validatePluginConfigAdapterEndpoints(parsed.endpoints, item.plugin_key, issues, context2);
2459
2475
  const capabilities = parsed.capabilities;
2460
2476
  if (capabilities !== void 0) {
2461
2477
  if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) {
2462
- issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context} config adapter capabilities must be an object: ${item.adapter}`));
2478
+ issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context2} config adapter capabilities must be an object: ${item.adapter}`));
2463
2479
  return;
2464
2480
  }
2465
2481
  for (const value of Object.values(capabilities)) {
2466
2482
  if (typeof value !== "string" || !value.startsWith(`config.plugin.${item.plugin_key}.`)) {
2467
- issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context} config adapter capabilities must stay under config.plugin.${item.plugin_key}.`));
2483
+ issues.push(issue2("error", "invalid_config_adapter_capabilities", `${context2} config adapter capabilities must stay under config.plugin.${item.plugin_key}.`));
2468
2484
  return;
2469
2485
  }
2470
2486
  }
@@ -2472,53 +2488,53 @@ async function validatePluginConfigAdapterFile(skillDir, item, issues, context)
2472
2488
  const work = parsed.work;
2473
2489
  if (work !== void 0) {
2474
2490
  if (!work || typeof work !== "object" || Array.isArray(work)) {
2475
- issues.push(issue2("error", "invalid_config_adapter_work", `${context} config adapter work must be an object: ${item.adapter}`));
2491
+ issues.push(issue2("error", "invalid_config_adapter_work", `${context2} config adapter work must be an object: ${item.adapter}`));
2476
2492
  return;
2477
2493
  }
2478
2494
  const lintPath = work.lint;
2479
2495
  if (lintPath !== void 0) {
2480
2496
  if (typeof lintPath !== "string") {
2481
- issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
2497
+ issues.push(issue2("error", "invalid_config_adapter_lint", `${context2} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
2482
2498
  return;
2483
2499
  }
2484
2500
  const normalizedLintPath = lintPath.replace(/\\/g, "/");
2485
2501
  const lintParts = normalizedLintPath.split("/");
2486
2502
  if (!normalizedLintPath.startsWith("lint/") || lintParts.some((part) => part === "" || part === "." || part === "..") || normalizedLintPath.startsWith("/") || path4.isAbsolute(normalizedLintPath) || !normalizedLintPath.endsWith(".json")) {
2487
- issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
2503
+ issues.push(issue2("error", "invalid_config_adapter_lint", `${context2} config adapter work.lint must be a lint/*.json path: ${item.adapter}`));
2488
2504
  return;
2489
2505
  }
2490
2506
  const lintFile = path4.join(skillDir, normalizedLintPath);
2491
2507
  if (!await exists2(lintFile)) {
2492
- issues.push(issue2("error", "missing_config_adapter_lint", `${context} config adapter lint file not found: ${normalizedLintPath}`));
2508
+ issues.push(issue2("error", "missing_config_adapter_lint", `${context2} config adapter lint file not found: ${normalizedLintPath}`));
2493
2509
  return;
2494
2510
  }
2495
2511
  const lint = JSON.parse(await readFile6(lintFile, "utf8"));
2496
2512
  if (!lint || typeof lint !== "object" || Array.isArray(lint) || lint.version !== 1 || lint.domain !== item.domain || lint.plugin_key !== item.plugin_key || !Array.isArray(lint.rules) || !lint.rules.length) {
2497
- issues.push(issue2("error", "invalid_config_adapter_lint", `${context} config adapter lint file must match adapter manifest and declare rules: ${normalizedLintPath}`));
2513
+ issues.push(issue2("error", "invalid_config_adapter_lint", `${context2} config adapter lint file must match adapter manifest and declare rules: ${normalizedLintPath}`));
2498
2514
  return;
2499
2515
  }
2500
2516
  }
2501
2517
  }
2502
2518
  } catch (error) {
2503
- issues.push(issue2("error", "invalid_config_adapter_file", `${context} config adapter file must be valid JSON: ${item.adapter}`));
2519
+ issues.push(issue2("error", "invalid_config_adapter_file", `${context2} config adapter file must be valid JSON: ${item.adapter}`));
2504
2520
  }
2505
2521
  }
2506
- function validatePluginLintManifest(item, issues, context) {
2522
+ function validatePluginLintManifest(item, issues, context2) {
2507
2523
  if (item.domain !== "flow-template-node") {
2508
- issues.push(issue2("error", "unsupported_lint_domain", `${context} lint domain is not supported: ${item.domain}`));
2524
+ issues.push(issue2("error", "unsupported_lint_domain", `${context2} lint domain is not supported: ${item.domain}`));
2509
2525
  }
2510
2526
  if (!/^plugin_[A-Za-z0-9_]+$/.test(item.plugin_key)) {
2511
- issues.push(issue2("error", "invalid_lint_plugin_key", `${context} lint plugin_key must look like plugin_xxx.`));
2527
+ issues.push(issue2("error", "invalid_lint_plugin_key", `${context2} lint plugin_key must look like plugin_xxx.`));
2512
2528
  }
2513
2529
  const normalized = item.path.replace(/\\/g, "/");
2514
2530
  const parts = normalized.split("/");
2515
2531
  if (!normalized.startsWith("lint/") || parts.some((part) => part === "" || part === "." || part === "..") || normalized.startsWith("/") || path4.isAbsolute(normalized) || !normalized.endsWith(".json")) {
2516
- issues.push(issue2("error", "invalid_lint_path", `${context} lint path must be a lint/*.json file.`));
2532
+ issues.push(issue2("error", "invalid_lint_path", `${context2} lint path must be a lint/*.json file.`));
2517
2533
  }
2518
2534
  if (item.paths) {
2519
2535
  item.paths.forEach((scanPath) => {
2520
2536
  if (!isAllowedPluginConfigScanPath(scanPath)) {
2521
- issues.push(issue2("error", "invalid_lint_scan_path", `${context} lint scan path is not supported: ${scanPath}`));
2537
+ issues.push(issue2("error", "invalid_lint_scan_path", `${context2} lint scan path is not supported: ${scanPath}`));
2522
2538
  }
2523
2539
  });
2524
2540
  }
@@ -3703,7 +3719,7 @@ function registerAuthCommands(program2, deps = {}) {
3703
3719
  deviceCode
3704
3720
  });
3705
3721
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
3706
- const safeUser2 = config.profiles[profile.name].user;
3722
+ const safeUser3 = config.profiles[profile.name].user;
3707
3723
  await save(config);
3708
3724
  let capabilitiesProbe;
3709
3725
  let pluginSkillUpdates;
@@ -3733,7 +3749,7 @@ function registerAuthCommands(program2, deps = {}) {
3733
3749
  ok: true,
3734
3750
  profile: profile.name,
3735
3751
  login: "authenticated",
3736
- user: safeUser2,
3752
+ user: safeUser3,
3737
3753
  ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
3738
3754
  ...pluginSkillUpdates ? { plugin_skill_updates: pluginSkillUpdates } : {},
3739
3755
  ...nextCommands ? { next_commands: nextCommands } : {}
@@ -4224,6 +4240,13 @@ import { createHash as createHash4 } from "crypto";
4224
4240
  import { mkdir as mkdir5, readdir as readdir2, readFile as readFile8, writeFile as writeFile5 } from "fs/promises";
4225
4241
  import path5 from "path";
4226
4242
  import { isDeepStrictEqual } from "util";
4243
+ function numericConfigResourcePath(resource, id, query = "") {
4244
+ const normalized = id.trim();
4245
+ if (!/^\d+$/.test(normalized) || normalized === "0") {
4246
+ throw new Error(`${resource} config id \u5FC5\u987B\u662F\u6B63\u6574\u6570\uFF1B\u8DE8\u73AF\u5883 UUID \u8BF7\u5148\u4F7F\u7528 config resolve-id\u3002`);
4247
+ }
4248
+ return `/${resource}/${encodeURIComponent(normalized)}${query}`;
4249
+ }
4227
4250
  function configWorkflowError(message, details) {
4228
4251
  return Object.assign(new Error(message), details);
4229
4252
  }
@@ -4232,6 +4255,9 @@ function errorStatus(error) {
4232
4255
  const status = Number(error.response.status);
4233
4256
  return Number.isFinite(status) ? status : void 0;
4234
4257
  }
4258
+ function workflowErrorCode(error) {
4259
+ return isRecord3(error) && typeof error.code === "string" ? error.code : void 0;
4260
+ }
4235
4261
  function isJsonParseFailure(error) {
4236
4262
  const message = error instanceof Error ? error.message : String(error ?? "");
4237
4263
  return error instanceof SyntaxError || /Unexpected end of JSON input|JSON.*(?:parse|position)|unterminated JSON/i.test(message);
@@ -4250,6 +4276,8 @@ var NAV_DEFAULT_NAME_BY_TYPE = {
4250
4276
  shortcut_mobile: "\u79FB\u52A8\u5FEB\u6377\u5165\u53E3"
4251
4277
  };
4252
4278
  var MAX_FORM_TEMPLATE_NAME_LENGTH = 20;
4279
+ var MAX_DATASET_CUSTOM_KEY_LENGTH = 20;
4280
+ var MAX_PAGE_TEMPLATE_NAME_LENGTH = 20;
4253
4281
  var FORM_TEMPLATE_ID_CONST_PATTERN = /\b(?:const|let|var)\s+[A-Za-z_$][\w$]*(?:FORM|Form|form)[A-Za-z0-9_$]*(?:TEMPLATE|Template|template)[A-Za-z0-9_$]*(?:ID|Id|id)\s*=\s*\d+\b/;
4254
4282
  var FORM_TEMPLATE_ID_PROP_PATTERN = /(?:\btemplate_id\b|['"]template_id['"])\s*:\s*\d+\b|\.template_id\s*=\s*\d+\b|\[['"]template_id['"]]\s*=\s*\d+\b/;
4255
4283
  var UUID_RE = /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/;
@@ -4272,6 +4300,10 @@ var LOCAL_UUID_DOMAIN_DIR = {
4272
4300
  dataset: "think_data_set",
4273
4301
  "dataset-field": "think_data_set_field",
4274
4302
  role: "think_role",
4303
+ team: "think_group",
4304
+ user: "think_user",
4305
+ "user-model": "think_user_model",
4306
+ "group-model": "think_group_model",
4275
4307
  workspace: "think_workspace"
4276
4308
  };
4277
4309
  var REMOTE_UUID_EXPORT_PATH = {
@@ -4280,7 +4312,9 @@ var REMOTE_UUID_EXPORT_PATH = {
4280
4312
  "filter-template": (uuid) => `/flow_page_template/get_by_uuid?uuid=${encodeURIComponent(uuid)}`,
4281
4313
  "project-detail-template": (uuid) => `/flow_page_template/get_by_uuid?uuid=${encodeURIComponent(uuid)}`,
4282
4314
  "step-detail-template": (uuid) => `/flow_page_template/get_by_uuid?uuid=${encodeURIComponent(uuid)}`,
4283
- "console-template": (uuid) => `/flow_page_template/get_by_uuid?uuid=${encodeURIComponent(uuid)}`
4315
+ "console-template": (uuid) => `/flow_page_template/get_by_uuid?uuid=${encodeURIComponent(uuid)}`,
4316
+ "user-model": (uuid) => `/user_model/get_by_uuid?uuid=${encodeURIComponent(uuid)}`,
4317
+ "group-model": (uuid) => `/group_model/get_by_uuid?uuid=${encodeURIComponent(uuid)}`
4284
4318
  };
4285
4319
  var CONFIG_DOMAINS = {
4286
4320
  "form-template": {
@@ -4489,6 +4523,70 @@ var CONFIG_DOMAINS = {
4489
4523
  writeEndpoints: ["POST /api/role", "PUT /api/role/:id", "DELETE /api/role/:id", "POST/PUT/DELETE /api/point", "POST/DELETE /api/user_role"],
4490
4524
  notes: ["Role submit executes point operations, role create/update, then member operations with role_id injection."]
4491
4525
  },
4526
+ team: {
4527
+ capability: "config.team",
4528
+ exportPath: (id) => numericConfigResourcePath("group", id),
4529
+ exportStatus: "supported",
4530
+ buildStatus: "supported",
4531
+ submitStatus: "supported",
4532
+ createPath: "/group",
4533
+ createMethod: "POST",
4534
+ deletePath: (id) => numericConfigResourcePath("group", id),
4535
+ deleteMethod: "DELETE",
4536
+ submitPath: (id) => numericConfigResourcePath("group", id),
4537
+ submitMethod: "PUT",
4538
+ readEndpoints: ["GET /api/group/:id"],
4539
+ writeEndpoints: ["POST /api/group", "PUT /api/group/:id", "DELETE /api/group/:id"],
4540
+ notes: ["Team maps to the BPMAX group tree and manages parent, model, permission, and administrator configuration."]
4541
+ },
4542
+ user: {
4543
+ capability: "config.user",
4544
+ exportPath: (id) => numericConfigResourcePath("user", id, "?only_user_role=1"),
4545
+ exportStatus: "supported",
4546
+ buildStatus: "supported",
4547
+ submitStatus: "supported",
4548
+ createPath: "/user",
4549
+ createMethod: "POST",
4550
+ deletePath: (id) => numericConfigResourcePath("user", id),
4551
+ deleteMethod: "DELETE",
4552
+ submitPath: (id) => numericConfigResourcePath("user", id),
4553
+ submitMethod: "PUT",
4554
+ readEndpoints: ["GET /api/user/:id?only_user_role=1"],
4555
+ writeEndpoints: ["POST /api/user", "PUT /api/user/:id", "DELETE /api/user/:id"],
4556
+ notes: ["User export is privacy-safe. Phone is accepted only in explicit create work and is never copied from readback into edit work."]
4557
+ },
4558
+ "user-model": {
4559
+ capability: "config.user_model",
4560
+ exportPath: (id) => numericConfigResourcePath("user_model", id, "?with_role=1"),
4561
+ exportStatus: "supported",
4562
+ buildStatus: "supported",
4563
+ submitStatus: "supported",
4564
+ createPath: "/user_model",
4565
+ createMethod: "POST",
4566
+ deletePath: (id) => numericConfigResourcePath("user_model", id),
4567
+ deleteMethod: "DELETE",
4568
+ submitPath: (id) => numericConfigResourcePath("user_model", id),
4569
+ submitMethod: "PUT",
4570
+ readEndpoints: ["GET /api/user_model/:id?with_role=1", "GET /api/user_model/get_by_uuid?uuid=:uuid"],
4571
+ writeEndpoints: ["POST /api/user_model", "PUT /api/user_model/:id", "DELETE /api/user_model/:id"],
4572
+ notes: ["User-model normalizes permission, object events, automatic flow triggers, role, form-template, and UUID fields."]
4573
+ },
4574
+ "group-model": {
4575
+ capability: "config.group_model",
4576
+ exportPath: (id) => numericConfigResourcePath("group_model", id),
4577
+ exportStatus: "supported",
4578
+ buildStatus: "supported",
4579
+ submitStatus: "supported",
4580
+ createPath: "/group_model",
4581
+ createMethod: "POST",
4582
+ deletePath: (id) => numericConfigResourcePath("group_model", id),
4583
+ deleteMethod: "DELETE",
4584
+ submitPath: (id) => numericConfigResourcePath("group_model", id),
4585
+ submitMethod: "PUT",
4586
+ readEndpoints: ["GET /api/group_model/:id", "GET /api/group_model/get_by_uuid?uuid=:uuid"],
4587
+ writeEndpoints: ["POST /api/group_model", "PUT /api/group_model/:id", "DELETE /api/group_model/:id"],
4588
+ notes: ["Group-model normalizes permission, child models, object events, automatic flow triggers, form-template, and UUID fields."]
4589
+ },
4492
4590
  "nav-config": {
4493
4591
  capability: "config.nav_config",
4494
4592
  exportStatus: "supported",
@@ -4836,7 +4934,7 @@ function validateFlowTemplateFormDrivenCreateBaseline(value, errors, options = {
4836
4934
  if (!options.force && !hasConfiguredFlowTemplateFormSource(value, meta)) {
4837
4935
  return;
4838
4936
  }
4839
- const context = options.context || "flow-template create";
4937
+ const context2 = options.context || "flow-template create";
4840
4938
  const missing = [];
4841
4939
  const hideFields = Array.isArray(meta.hide_fields) ? meta.hide_fields.map(String) : [];
4842
4940
  for (const field of FORM_DRIVEN_CREATE_HIDE_FIELDS) {
@@ -4853,7 +4951,7 @@ function validateFlowTemplateFormDrivenCreateBaseline(value, errors, options = {
4853
4951
  if (missing.length === 0) {
4854
4952
  return;
4855
4953
  }
4856
- const message = `${context} for form-driven project creation requires default system-field hiding and a project name template: ${missing.join("; ")}.`;
4954
+ const message = `${context2} for form-driven project creation requires default system-field hiding and a project name template: ${missing.join("; ")}.`;
4857
4955
  if (errors) {
4858
4956
  errors.push(message);
4859
4957
  return;
@@ -6599,6 +6697,17 @@ function lintConsoleTemplateWork(value, errors, warnings) {
6599
6697
  }
6600
6698
  });
6601
6699
  }
6700
+ function lintFilterTemplateWork(value, errors) {
6701
+ const content = parseTemplateContent(value, errors);
6702
+ if (!isRecord3(content) || !Array.isArray(content.config)) {
6703
+ return;
6704
+ }
6705
+ content.config.forEach((item, index) => {
6706
+ if (isRecord3(item) && item.console === true) {
6707
+ errors.push(`filter-template content.config[${index}].console=true is reserved for console/dashboard filters and is not allowed in ordinary filter templates.`);
6708
+ }
6709
+ });
6710
+ }
6602
6711
  function listTemplateNodeLabel(node) {
6603
6712
  return [
6604
6713
  node.title,
@@ -7244,11 +7353,32 @@ function validateExpectedType(domain, definition, data) {
7244
7353
  );
7245
7354
  }
7246
7355
  }
7356
+ function validatePageTemplateName(work, errors) {
7357
+ const basic = isRecord3(work.basic) ? work.basic : work;
7358
+ const name = normalizeText(basic.name ?? "");
7359
+ if (!name || name.length <= MAX_PAGE_TEMPLATE_NAME_LENGTH) {
7360
+ return;
7361
+ }
7362
+ const message = `page-template name is too long (${name.length} > ${MAX_PAGE_TEMPLATE_NAME_LENGTH}); BPMAX flow_page_template.name rejects longer names.`;
7363
+ if (errors) {
7364
+ errors.push(message);
7365
+ return;
7366
+ }
7367
+ throw new Error(message);
7368
+ }
7247
7369
  function normalizePageTemplatePayload(domain, work) {
7248
7370
  const definition = CONFIG_DOMAINS[domain];
7371
+ validatePageTemplateName(work);
7249
7372
  if (domain === "list-template") {
7250
7373
  validateListTemplateActionGate(work);
7251
7374
  }
7375
+ if (domain === "filter-template") {
7376
+ const errors = [];
7377
+ lintFilterTemplateWork(work, errors);
7378
+ if (errors.length) {
7379
+ throw new Error(`filter-template lint failed: ${errors.join("; ")}`);
7380
+ }
7381
+ }
7252
7382
  if (domain === "console-template") {
7253
7383
  const errors = [];
7254
7384
  const warnings = [];
@@ -7519,7 +7649,7 @@ function normalizeDatasetPayload(work) {
7519
7649
  payload.flow_key = flowKey;
7520
7650
  }
7521
7651
  const id = work.id;
7522
- if (id !== void 0 && id !== null && id !== "") {
7652
+ if (mode !== "create" && id !== void 0 && id !== null && id !== "") {
7523
7653
  payload.id = id;
7524
7654
  }
7525
7655
  validateDatasetPayload(payload, mode === "create" ? "create" : "edit");
@@ -7535,9 +7665,18 @@ function validateDatasetPayload(payload, mode) {
7535
7665
  if (required.length) {
7536
7666
  throw new Error(`dataset ${mode} requires identity fields: ${required.map(([key]) => key).join(", ")}.`);
7537
7667
  }
7668
+ const customKey = String(payload.custom_key ?? "");
7669
+ if (customKey.length > MAX_DATASET_CUSTOM_KEY_LENGTH) {
7670
+ throw new Error(
7671
+ `dataset custom_key is too long (${customKey.length} > ${MAX_DATASET_CUSTOM_KEY_LENGTH}); the BPMAX dataset storage column rejects longer identities.`
7672
+ );
7673
+ }
7538
7674
  if (mode === "edit" && (payload.id === void 0 || payload.id === null || String(payload.id).trim() === "")) {
7539
7675
  throw new Error("dataset edit requires payload.id to preserve dataset identity.");
7540
7676
  }
7677
+ if (mode === "create" && payload.id !== void 0 && payload.id !== null && String(payload.id).trim() !== "") {
7678
+ throw new Error("dataset create \u7981\u6B62\u643A\u5E26 payload.id\uFF1B\u6570\u636E\u96C6 ID \u5FC5\u987B\u7531\u5E73\u53F0\u751F\u6210\u3002");
7679
+ }
7541
7680
  if (!Array.isArray(payload.fields) || payload.fields.length === 0) {
7542
7681
  throw new Error(`dataset ${mode} requires at least one relationFields field key.`);
7543
7682
  }
@@ -7624,6 +7763,14 @@ function executedFields() {
7624
7763
  confirm_required: false
7625
7764
  };
7626
7765
  }
7766
+ function configPayloadForOutput(domain, payload) {
7767
+ if (domain !== "user") return payload;
7768
+ const result = { ...payload };
7769
+ if (Object.prototype.hasOwnProperty.call(result, "phone")) {
7770
+ result.phone = "[REDACTED]";
7771
+ }
7772
+ return result;
7773
+ }
7627
7774
  function validateDatasetFieldCreatePayload(payload) {
7628
7775
  if (!isRecord3(payload)) {
7629
7776
  throw new Error("dataset-field create requires an object payload.");
@@ -7871,11 +8018,11 @@ function extractEmbeddedSubformOrder(template, field) {
7871
8018
  if (!item || !isRecord3(item.value)) {
7872
8019
  return [];
7873
8020
  }
7874
- const rows = item.value.value;
7875
- if (Array.isArray(rows) && Array.isArray(rows[0])) {
7876
- return flattenFieldOrder(rows[0]);
8021
+ const rows2 = item.value.value;
8022
+ if (Array.isArray(rows2) && Array.isArray(rows2[0])) {
8023
+ return flattenFieldOrder(rows2[0]);
7877
8024
  }
7878
- return flattenFieldOrder(rows);
8025
+ return flattenFieldOrder(rows2);
7879
8026
  }
7880
8027
  function ordersMismatch(orders) {
7881
8028
  const comparable2 = orders.filter((order) => order.length > 0);
@@ -8766,6 +8913,327 @@ function validateWorkspaceSubmitClears(payload, current) {
8766
8913
  }
8767
8914
  }
8768
8915
  }
8916
+ var USER_SENSITIVE_CONFIG_FIELDS = [
8917
+ "password",
8918
+ "api_key",
8919
+ "authorization",
8920
+ "token",
8921
+ "cookie",
8922
+ "session",
8923
+ "create_ip",
8924
+ "last_login_ip",
8925
+ "last_login_time"
8926
+ ];
8927
+ function configSource(work) {
8928
+ return isRecord3(work.basic) ? { ...work, ...work.basic } : work;
8929
+ }
8930
+ function normalizedNumberList(value, field) {
8931
+ const values = Array.isArray(value) ? value : typeof value === "string" ? value.split(",").map((item) => item.trim()).filter(Boolean) : value === void 0 || value === null || value === "" ? [] : [value];
8932
+ const result = values.map((item) => Number(item));
8933
+ if (result.some((item) => !Number.isSafeInteger(item) || item <= 0)) {
8934
+ throw new Error(`${field} \u5FC5\u987B\u53EA\u5305\u542B\u6B63\u6574\u6570 ID\u3002`);
8935
+ }
8936
+ return [...new Set(result)];
8937
+ }
8938
+ function normalizedOptionalId(value, field, allowZero = true) {
8939
+ if (value === void 0 || value === null || value === "") return null;
8940
+ const result = Number(value);
8941
+ if (!Number.isSafeInteger(result) || result < (allowZero ? 0 : 1)) {
8942
+ throw new Error(`${field} \u5FC5\u987B\u662F${allowZero ? "\u975E\u8D1F" : "\u6B63"}\u6574\u6570 ID\u3002`);
8943
+ }
8944
+ return result;
8945
+ }
8946
+ function normalizedJsonValue(value, field, kind) {
8947
+ let parsed = value;
8948
+ if (typeof value === "string") {
8949
+ try {
8950
+ parsed = JSON.parse(value);
8951
+ } catch {
8952
+ throw new Error(`${field} \u5FC5\u987B\u662F\u6709\u6548 JSON\u3002`);
8953
+ }
8954
+ }
8955
+ if (kind === "array" && !Array.isArray(parsed)) {
8956
+ throw new Error(`${field} \u5FC5\u987B\u662F\u6570\u7EC4\u3002`);
8957
+ }
8958
+ if (kind === "object" && !isRecord3(parsed)) {
8959
+ throw new Error(`${field} \u5FC5\u987B\u662F\u5BF9\u8C61\u3002`);
8960
+ }
8961
+ return parsed;
8962
+ }
8963
+ function normalizeTeamPayload(work, raw) {
8964
+ const source = configSource(work);
8965
+ if (source.admin_users === void 0 && Array.isArray(source.admins)) {
8966
+ source.admin_users = source.admins.filter(isRecord3).map((item) => item.id);
8967
+ }
8968
+ const payload = pickDefined(source, [
8969
+ "name",
8970
+ "intro",
8971
+ "parent_id",
8972
+ "model_id",
8973
+ "platform_id",
8974
+ "permission",
8975
+ "admin_users",
8976
+ "meta_form"
8977
+ ]);
8978
+ if (work.mode === "create" && payload.platform_id !== void 0) {
8979
+ throw new Error("team create \u4E0D\u5141\u8BB8\u624B\u5DE5\u6307\u5B9A platform_id\uFF1B\u8BE5\u5916\u90E8\u7ED1\u5B9A\u5B57\u6BB5\u5FC5\u987B\u7531\u5E73\u53F0\u7BA1\u7406\u3002");
8980
+ }
8981
+ payload.name = String(payload.name ?? "").trim();
8982
+ if (!payload.name || String(payload.name).length > 100) {
8983
+ throw new Error("team.name \u5FC5\u987B\u662F 1-100 \u4E2A\u5B57\u7B26\u3002");
8984
+ }
8985
+ const parentId = normalizedOptionalId(payload.parent_id, "team.parent_id");
8986
+ payload.parent_id = parentId ?? 0;
8987
+ const currentId = normalizedOptionalId(work.id ?? source.id, "team.id", false);
8988
+ if (currentId && Number(payload.parent_id) === currentId) {
8989
+ throw new Error("team.parent_id \u4E0D\u80FD\u6307\u5411\u56E2\u961F\u81EA\u8EAB\u3002");
8990
+ }
8991
+ const modelId = normalizedOptionalId(payload.model_id, "team.model_id");
8992
+ payload.model_id = modelId || null;
8993
+ if (payload.platform_id !== void 0) {
8994
+ payload.platform_id = normalizedOptionalId(payload.platform_id, "team.platform_id");
8995
+ }
8996
+ if (raw && Object.prototype.hasOwnProperty.call(raw, "platform_id")) {
8997
+ if (payload.platform_id === void 0 || Number(payload.platform_id) !== Number(raw.platform_id)) {
8998
+ throw new Error("team edit \u5FC5\u987B\u539F\u6837\u4FDD\u7559\u5BFC\u51FA\u65F6\u7684 platform_id\uFF1B\u4E0D\u5F97\u5220\u9664\u6216\u4FEE\u6539\u5916\u90E8\u5E73\u53F0\u7ED1\u5B9A\u3002");
8999
+ }
9000
+ }
9001
+ if (payload.permission !== void 0 && payload.permission !== null) {
9002
+ payload.permission = normalizedJsonValue(payload.permission, "team.permission", "object");
9003
+ }
9004
+ if (payload.admin_users !== void 0) {
9005
+ payload.admin_users = normalizedNumberList(payload.admin_users, "team.admin_users").join(",");
9006
+ }
9007
+ if (payload.meta_form !== void 0 && payload.meta_form !== null) {
9008
+ payload.meta_form = normalizedJsonValue(payload.meta_form, "team.meta_form", "object");
9009
+ }
9010
+ return payload;
9011
+ }
9012
+ function normalizeUserPayload(work) {
9013
+ const source = configSource(work);
9014
+ for (const field of USER_SENSITIVE_CONFIG_FIELDS) {
9015
+ if (Object.prototype.hasOwnProperty.call(source, field)) {
9016
+ throw new Error(`user.${field} \u5C5E\u4E8E\u654F\u611F\u6216\u670D\u52A1\u7AEF\u7BA1\u7406\u5B57\u6BB5\uFF0Ctyped config \u4E0D\u5141\u8BB8\u5199\u5165\u3002`);
9017
+ }
9018
+ }
9019
+ const createMode = work.mode === "create";
9020
+ if (!createMode && Object.prototype.hasOwnProperty.call(source, "phone")) {
9021
+ throw new Error("user.phone \u53EA\u5141\u8BB8\u5728 mode=create \u65F6\u663E\u5F0F\u63D0\u4F9B\uFF1B\u7F16\u8F91\u7528\u6237\u8EAB\u4EFD\u65F6\u4E0D\u5F97\u901A\u8FC7\u914D\u7F6E\u6587\u4EF6\u4FEE\u6539\u624B\u673A\u53F7\u3002");
9022
+ }
9023
+ if (Object.prototype.hasOwnProperty.call(source, "hide_in_contact")) {
9024
+ throw new Error("user.hide_in_contact \u5F53\u524D\u5E73\u53F0\u63A5\u53E3\u672A\u5B9E\u73B0\uFF0Ctyped config \u4E0D\u5141\u8BB8\u63D0\u4EA4\u8BE5\u5B57\u6BB5\u3002");
9025
+ }
9026
+ const payload = pickDefined(source, [
9027
+ "name",
9028
+ "phone",
9029
+ "partner_id",
9030
+ "title",
9031
+ "email",
9032
+ "status",
9033
+ "leader_id",
9034
+ "language_preference",
9035
+ "group_ids",
9036
+ "role_ids",
9037
+ "modelList",
9038
+ "user_model_id"
9039
+ ]);
9040
+ if (payload.group_ids === void 0 && Array.isArray(source.group_list)) {
9041
+ payload.group_ids = source.group_list.filter(isRecord3).map((item) => item.id);
9042
+ }
9043
+ if (payload.role_ids === void 0 && Array.isArray(source.role)) {
9044
+ payload.role_ids = source.role.filter(isRecord3).map((item) => item.id);
9045
+ }
9046
+ if (payload.modelList === void 0 && Array.isArray(source.models)) {
9047
+ payload.modelList = source.models.filter(isRecord3).map((item) => item.id);
9048
+ }
9049
+ payload.name = String(payload.name ?? "").trim();
9050
+ if (!payload.name || String(payload.name).length > 200) {
9051
+ throw new Error("user.name \u5FC5\u987B\u662F 1-200 \u4E2A\u5B57\u7B26\u3002");
9052
+ }
9053
+ if (payload.partner_id !== void 0 && String(payload.partner_id).length > 30) {
9054
+ throw new Error("user.partner_id \u6700\u957F 30 \u4E2A\u5B57\u7B26\u3002");
9055
+ }
9056
+ if (payload.title !== void 0 && String(payload.title).length > 20) {
9057
+ throw new Error("user.title \u6700\u957F 20 \u4E2A\u5B57\u7B26\u3002");
9058
+ }
9059
+ if (payload.email !== void 0 && String(payload.email).length > 20) {
9060
+ throw new Error("user.email \u6700\u957F 20 \u4E2A\u5B57\u7B26\u3002");
9061
+ }
9062
+ if (createMode) {
9063
+ const phone = String(payload.phone ?? "").trim();
9064
+ if (!/^\+?\d{6,20}$/.test(phone)) {
9065
+ throw new Error("user.phone \u5728 mode=create \u65F6\u5FC5\u586B\uFF0C\u4E14\u5FC5\u987B\u662F 6-20 \u4F4D\u6570\u5B57\uFF0C\u53EF\u5E26\u524D\u5BFC +\u3002");
9066
+ }
9067
+ payload.phone = phone;
9068
+ const roleIds = normalizedNumberList(payload.role_ids, "user.role_ids");
9069
+ if (!roleIds.length) {
9070
+ throw new Error("user.role_ids \u5728 mode=create \u65F6\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u89D2\u8272 ID\u3002");
9071
+ }
9072
+ payload.role_ids = roleIds;
9073
+ } else {
9074
+ delete payload.phone;
9075
+ }
9076
+ for (const field of ["group_ids", "role_ids", "modelList"]) {
9077
+ if (payload[field] !== void 0) {
9078
+ payload[field] = normalizedNumberList(payload[field], `user.${field}`);
9079
+ }
9080
+ }
9081
+ if (payload.user_model_id !== void 0) {
9082
+ payload.user_model_id = normalizedOptionalId(payload.user_model_id, "user.user_model_id", false);
9083
+ }
9084
+ if (payload.leader_id !== void 0) {
9085
+ payload.leader_id = normalizedOptionalId(payload.leader_id, "user.leader_id");
9086
+ const currentId = normalizedOptionalId(work.id ?? source.id, "user.id", false);
9087
+ if (currentId && Number(payload.leader_id) === currentId) {
9088
+ throw new Error("user.leader_id \u4E0D\u80FD\u6307\u5411\u7528\u6237\u81EA\u8EAB\u3002");
9089
+ }
9090
+ }
9091
+ if (payload.status !== void 0 && ![0, 1, 2].includes(Number(payload.status))) {
9092
+ throw new Error("user.status \u53EA\u5141\u8BB8 0\u30011\u30012\u3002");
9093
+ }
9094
+ if (payload.status !== void 0) payload.status = Number(payload.status);
9095
+ return payload;
9096
+ }
9097
+ function privacySafeUserConfig(value) {
9098
+ if (!isRecord3(value)) return value;
9099
+ const result = pickDefined(value, [
9100
+ "id",
9101
+ "uuid",
9102
+ "guid",
9103
+ "name",
9104
+ "partner_id",
9105
+ "title",
9106
+ "email",
9107
+ "status",
9108
+ "leader_id",
9109
+ "hide_in_contact",
9110
+ "language_preference",
9111
+ "organization_id",
9112
+ "is_del",
9113
+ "group_ids",
9114
+ "group_list",
9115
+ "role_ids",
9116
+ "role",
9117
+ "models"
9118
+ ]);
9119
+ if (Array.isArray(result.group_list)) {
9120
+ result.group_list = result.group_list.filter(isRecord3).map((item) => pickDefined(item, ["id", "name", "path", "is_admin"]));
9121
+ }
9122
+ if (Array.isArray(result.role)) {
9123
+ result.role = result.role.filter(isRecord3).map((item) => pickDefined(item, ["id", "key", "name"]));
9124
+ }
9125
+ if (Array.isArray(result.models)) {
9126
+ result.models = result.models.filter(isRecord3).map((item) => pickDefined(item, ["id", "uuid", "key", "name", "form_id"]));
9127
+ }
9128
+ return result;
9129
+ }
9130
+ function privacySafePermission(value) {
9131
+ if (!isRecord3(value)) return value;
9132
+ const result = { ...value };
9133
+ if (isRecord3(result.config)) {
9134
+ const config = { ...result.config };
9135
+ for (const field of ["user", "group", "role"]) {
9136
+ if (Array.isArray(config[field])) {
9137
+ config[field] = config[field].filter(isRecord3).map((item) => pickDefined(item, ["id", "key", "name"]));
9138
+ }
9139
+ }
9140
+ result.config = config;
9141
+ }
9142
+ return result;
9143
+ }
9144
+ function privacySafeTeamConfig(value) {
9145
+ if (!isRecord3(value)) return value;
9146
+ const result = pickDefined(value, [
9147
+ "id",
9148
+ "uuid",
9149
+ "guid",
9150
+ "name",
9151
+ "intro",
9152
+ "parent_id",
9153
+ "path",
9154
+ "model_id",
9155
+ "platform_id",
9156
+ "meta_form_id",
9157
+ "permission",
9158
+ "admins"
9159
+ ]);
9160
+ result.permission = privacySafePermission(result.permission);
9161
+ if (Array.isArray(result.admins)) {
9162
+ result.admins = result.admins.filter(isRecord3).map((item) => pickDefined(item, ["id", "name"]));
9163
+ }
9164
+ return result;
9165
+ }
9166
+ function privacySafeModelConfig(domain, value) {
9167
+ if (!isRecord3(value)) return value;
9168
+ const fields = domain === "user-model" ? ["id", "uuid", "guid", "key", "name", "form_template_id", "object_event", "auto_trigger_flows", "permission", "role_id", "role"] : ["id", "uuid", "guid", "key", "name", "form_template_id", "object_event", "auto_trigger_flows", "permission", "sub_ids"];
9169
+ const result = pickDefined(value, fields);
9170
+ result.permission = privacySafePermission(result.permission);
9171
+ if (isRecord3(result.role)) {
9172
+ result.role = pickDefined(result.role, ["id", "key", "name"]);
9173
+ }
9174
+ return result;
9175
+ }
9176
+ async function assertTeamParentDoesNotCreateCycle(profile, id, payload, definition, current) {
9177
+ const teamId = normalizedOptionalId(id, "team.id", false);
9178
+ const parentId = normalizedOptionalId(payload.parent_id, "team.parent_id");
9179
+ if (!teamId || !parentId) return;
9180
+ if (isRecord3(current) && Number(current.parent_id || 0) === parentId) return;
9181
+ if (teamId === parentId) {
9182
+ throw new Error("team.parent_id \u4E0D\u80FD\u6307\u5411\u56E2\u961F\u81EA\u8EAB\u3002");
9183
+ }
9184
+ const parent = await readRemoteConfigDomain(profile, "team", String(parentId), definition);
9185
+ if (!isRecord3(parent) || Number(parent.id) !== parentId) {
9186
+ throw new Error(`team.parent_id ${parentId} \u4E0D\u5B58\u5728\uFF0C\u4E0D\u80FD\u63D0\u4EA4\u5C42\u7EA7\u53D8\u66F4\u3002`);
9187
+ }
9188
+ const ancestorIds = String(parent.path ?? "").split(/[|,]/).map((item) => Number(item.trim())).filter((item) => Number.isSafeInteger(item) && item > 0);
9189
+ if (ancestorIds.includes(teamId)) {
9190
+ throw new Error(`team.parent_id ${parentId} \u662F\u56E2\u961F ${teamId} \u7684\u540E\u4EE3\uFF0C\u63D0\u4EA4\u540E\u4F1A\u5F62\u6210\u7EC4\u7EC7\u6811\u5FAA\u73AF\u3002`);
9191
+ }
9192
+ }
9193
+ function normalizeModelPayload(domain, work) {
9194
+ const source = configSource(work);
9195
+ const fields = domain === "user-model" ? ["key", "name", "form_template_id", "object_event", "auto_trigger_flows", "permission", "uuid", "role_id"] : ["key", "name", "form_template_id", "object_event", "auto_trigger_flows", "permission", "sub_ids", "uuid"];
9196
+ const payload = pickDefined(source, fields);
9197
+ payload.key = String(payload.key ?? "").trim();
9198
+ payload.name = String(payload.name ?? "").trim();
9199
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,19}$/.test(String(payload.key))) {
9200
+ throw new Error(`${domain}.key \u5FC5\u987B\u4EE5\u5B57\u6BCD\u5F00\u5934\uFF0C\u957F\u5EA6 1-20\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001_\u3001-\u3002`);
9201
+ }
9202
+ const maxNameLength = domain === "group-model" ? 20 : 200;
9203
+ if (!payload.name || String(payload.name).length > maxNameLength) {
9204
+ throw new Error(`${domain}.name \u5FC5\u987B\u662F 1-${maxNameLength} \u4E2A\u5B57\u7B26\u3002`);
9205
+ }
9206
+ if (payload.form_template_id !== void 0) {
9207
+ payload.form_template_id = normalizedOptionalId(payload.form_template_id, `${domain}.form_template_id`);
9208
+ }
9209
+ if (payload.role_id !== void 0) {
9210
+ payload.role_id = normalizedOptionalId(payload.role_id, "user-model.role_id");
9211
+ }
9212
+ if (payload.object_event !== void 0 && payload.object_event !== null) {
9213
+ payload.object_event = normalizedJsonValue(payload.object_event, `${domain}.object_event`, "array");
9214
+ }
9215
+ if (payload.auto_trigger_flows !== void 0 && payload.auto_trigger_flows !== null) {
9216
+ payload.auto_trigger_flows = normalizedJsonValue(payload.auto_trigger_flows, `${domain}.auto_trigger_flows`, "object");
9217
+ }
9218
+ if (payload.permission !== void 0 && payload.permission !== null) {
9219
+ payload.permission = normalizedJsonValue(payload.permission, `${domain}.permission`, "object");
9220
+ }
9221
+ if (domain === "group-model" && payload.sub_ids !== void 0) {
9222
+ const rawSubIds = Array.isArray(payload.sub_ids) ? payload.sub_ids : typeof payload.sub_ids === "string" ? payload.sub_ids.split(",").map((item) => item.trim()).filter(Boolean) : [payload.sub_ids];
9223
+ payload.sub_ids = normalizedNumberList(payload.sub_ids, "group-model.sub_ids");
9224
+ if (rawSubIds.length !== payload.sub_ids.length) {
9225
+ throw new Error("group-model.sub_ids \u4E0D\u5141\u8BB8\u91CD\u590D ID\u3002");
9226
+ }
9227
+ const currentId = normalizedOptionalId(work.id ?? source.id, "group-model.id", false);
9228
+ if (currentId && payload.sub_ids.includes(currentId)) {
9229
+ throw new Error("group-model.sub_ids \u4E0D\u80FD\u5305\u542B\u6A21\u578B\u81EA\u8EAB\u3002");
9230
+ }
9231
+ }
9232
+ if (payload.uuid !== void 0 && payload.uuid !== null && payload.uuid !== "" && !String(payload.uuid).match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)) {
9233
+ throw new Error(`${domain}.uuid \u5FC5\u987B\u662F\u6709\u6548 UUID\u3002`);
9234
+ }
9235
+ return payload;
9236
+ }
8769
9237
  function parseApiPlatformIdentity(id) {
8770
9238
  const trimmed = id.trim();
8771
9239
  if (!trimmed) {
@@ -9329,6 +9797,15 @@ function buildDomainSubmitPayload(domain, work, options = {}, raw) {
9329
9797
  if (domain === "role") {
9330
9798
  return buildRoleSubmitPayload(work);
9331
9799
  }
9800
+ if (domain === "team") {
9801
+ return normalizeTeamPayload(work, isRecord3(raw) ? raw : void 0);
9802
+ }
9803
+ if (domain === "user") {
9804
+ return normalizeUserPayload(work);
9805
+ }
9806
+ if (domain === "user-model" || domain === "group-model") {
9807
+ return normalizeModelPayload(domain, work);
9808
+ }
9332
9809
  if (domain === "nav-config") {
9333
9810
  return buildNavConfigSubmitPayload(work, isRecord3(raw) ? raw : void 0, options);
9334
9811
  }
@@ -9687,7 +10164,7 @@ async function createFlowTemplateFromWork(config, profile, workFile, confirm3, o
9687
10164
  const expectedConfirm = `create flow-template ${createShell.name}`;
9688
10165
  if (confirm3 !== expectedConfirm) {
9689
10166
  return {
9690
- dry_run: true,
10167
+ ...dryRunFields(expectedConfirm),
9691
10168
  domain: "flow-template",
9692
10169
  create_endpoint: "/flow/flow_type",
9693
10170
  create_payload: createShell,
@@ -9747,7 +10224,7 @@ async function createFlowTemplateFromWork(config, profile, workFile, confirm3, o
9747
10224
  { capability: `${definition.capability}.export` }
9748
10225
  );
9749
10226
  return {
9750
- dry_run: false,
10227
+ ...executedFields(),
9751
10228
  domain: "flow-template",
9752
10229
  flow_type: flowType,
9753
10230
  create_response: createResponse,
@@ -10036,6 +10513,364 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
10036
10513
  throw new Error(`flow-app create failed: ${message}. Created resources: ${JSON.stringify(createdResources)}. Next recovery: fix the failing step, then rerun the corresponding typed config command or rerun flow-app create only if duplicate resources are acceptable.`);
10037
10514
  }
10038
10515
  }
10516
+ function matrixMaintenanceNode(flowWork) {
10517
+ const data = isRecord3(flowWork.data) ? flowWork.data : {};
10518
+ const nodes = Array.isArray(data.nodes) ? data.nodes.filter(isRecord3) : [];
10519
+ return nodes.find((node) => {
10520
+ const name = String(node.name ?? "").trim();
10521
+ return name === "\u751F\u6548\u4E2D" || name === "\u8FDB\u884C\u4E2D" || Number(node.status) === 1;
10522
+ });
10523
+ }
10524
+ function matrixListHasEditAction(value) {
10525
+ if (typeof value === "string") {
10526
+ return value.includes("ProjectDetailEdit");
10527
+ }
10528
+ if (Array.isArray(value)) {
10529
+ return value.some(matrixListHasEditAction);
10530
+ }
10531
+ if (isRecord3(value)) {
10532
+ return Object.entries(value).some(([key, child]) => key === "is" && child === "ProjectDetailEdit" || matrixListHasEditAction(child));
10533
+ }
10534
+ return false;
10535
+ }
10536
+ function matrixCreateMeta(domain, id, profile) {
10537
+ return {
10538
+ domain,
10539
+ id,
10540
+ mode: "create",
10541
+ profile: profile.name,
10542
+ workspace: profile.config.workspace
10543
+ };
10544
+ }
10545
+ function matrixCreatedId(response, domain, options = {}) {
10546
+ if (!isRecord3(response)) {
10547
+ throw new Error(`matrix app ${domain} create returned an invalid response.`);
10548
+ }
10549
+ if (response.readback_status !== void 0 && response.readback_status !== "verified" && !options.allowRecoverableReadbackMismatch) {
10550
+ throw new Error(`matrix app ${domain} create did not complete exact readback: ${String(response.readback_status)}.`);
10551
+ }
10552
+ const id = response.id ?? response.created_id;
10553
+ if (id === void 0 || id === null || String(id).trim() === "") {
10554
+ throw new Error(`matrix app ${domain} create did not return a created id.`);
10555
+ }
10556
+ if (!/^\d+$/.test(String(id))) {
10557
+ throw new Error(`matrix app ${domain} create returned a non-numeric config id: ${String(id)}.`);
10558
+ }
10559
+ return String(id);
10560
+ }
10561
+ function matrixDatasetFieldDefinitions(work) {
10562
+ const candidates = [work.dataSetFields, work.data_set_fields, work.fields];
10563
+ for (const candidate of candidates) {
10564
+ if (Array.isArray(candidate)) {
10565
+ return candidate.filter(isRecord3);
10566
+ }
10567
+ if (isRecord3(candidate) && Array.isArray(candidate.selected)) {
10568
+ return candidate.selected.filter(isRecord3);
10569
+ }
10570
+ }
10571
+ return [];
10572
+ }
10573
+ async function createMatrixDatasetField(config, profile, field, datasetId, flowType, index, workDir) {
10574
+ const domain = "dataset-field";
10575
+ const id = "create:dataset-field";
10576
+ const suffix = `${index + 1}-${String(field.key ?? field.field ?? "field").replace(/[^A-Za-z0-9_-]+/g, "-")}`;
10577
+ const workFile = path5.join(workDir, `dataset-field-${suffix}.work.json`);
10578
+ const metaFile = path5.join(workDir, `dataset-field-${suffix}.meta.json`);
10579
+ const submitFile = path5.join(workDir, `dataset-field-${suffix}.submit.json`);
10580
+ await writeJsonFile(workFile, {
10581
+ ...field,
10582
+ mode: "create",
10583
+ data_set_id: datasetId,
10584
+ flow_type: flowType,
10585
+ flowType
10586
+ });
10587
+ await writeJsonFile(metaFile, matrixCreateMeta(domain, id, profile));
10588
+ const lint = await lintConfigWorkFile(workFile, { domain });
10589
+ if (lint.ok !== true) {
10590
+ throw new Error(`matrix app dataset-field lint failed: ${(Array.isArray(lint.errors) ? lint.errors : []).join("; ")}`);
10591
+ }
10592
+ await buildConfigSubmitPayload(domain, workFile, submitFile, metaFile);
10593
+ return submitConfigDomain(config, profile, domain, id, submitFile, `submit ${domain} ${id}`);
10594
+ }
10595
+ function bindMatrixPageTemplateWork(work, flowType, datasetId) {
10596
+ const basic = isRecord3(work.basic) ? { ...work.basic } : void 0;
10597
+ const binding = { flow_type: flowType, flow_key: "", data_set_id: Number(datasetId) };
10598
+ return {
10599
+ ...work,
10600
+ ...binding,
10601
+ ...basic ? { basic: { ...basic, ...binding } } : {}
10602
+ };
10603
+ }
10604
+ async function createMatrixConfigObject(config, profile, domain, work, workDir) {
10605
+ const id = `create:${domain}`;
10606
+ const workFile = path5.join(workDir, `${domain}.work.json`);
10607
+ const metaFile = path5.join(workDir, `${domain}.meta.json`);
10608
+ const submitFile = path5.join(workDir, `${domain}.submit.json`);
10609
+ await writeJsonFile(workFile, { ...work, mode: "create" });
10610
+ await writeJsonFile(metaFile, matrixCreateMeta(domain, id, profile));
10611
+ const lint = await lintConfigWorkFile(workFile, { domain });
10612
+ if (lint.ok !== true) {
10613
+ throw new Error(`matrix app ${domain} lint failed: ${(Array.isArray(lint.errors) ? lint.errors : []).join("; ")}`);
10614
+ }
10615
+ await buildConfigSubmitPayload(domain, workFile, submitFile, metaFile);
10616
+ return submitConfigDomain(config, profile, domain, id, submitFile, `submit ${domain} ${id}`);
10617
+ }
10618
+ async function createMatrixAppFromWork(config, profile, formWorkFile, flowWorkFile, datasetWorkFile, listWorkFile, filterWorkFile, confirm3, options = { workspace: "", name: "" }) {
10619
+ const workspace = normalizeWorkspaceKey(options.workspace || profile.config.workspace);
10620
+ const name = options.name.trim();
10621
+ const expectedConfirm = `create matrix app ${name} in ${workspace}`;
10622
+ if (!workspace || !name) {
10623
+ throw new Error("matrix app create requires workspace and name.");
10624
+ }
10625
+ const [flowWorkValue, datasetWorkValue, listWorkValue, filterWorkValue] = await Promise.all([
10626
+ readJsonFile(flowWorkFile),
10627
+ readJsonFile(datasetWorkFile),
10628
+ readJsonFile(listWorkFile),
10629
+ readJsonFile(filterWorkFile)
10630
+ ]);
10631
+ if (![flowWorkValue, datasetWorkValue, listWorkValue, filterWorkValue].every(isRecord3)) {
10632
+ throw new Error("matrix app create work files must be JSON objects.");
10633
+ }
10634
+ const flowWork = flowWorkValue;
10635
+ const datasetWork = datasetWorkValue;
10636
+ const listWork = listWorkValue;
10637
+ const filterWork = filterWorkValue;
10638
+ const errors = [];
10639
+ if (String(flowWork.category ?? "") !== "matrix") {
10640
+ errors.push("flow-template category must be matrix.");
10641
+ }
10642
+ if (!matrixMaintenanceNode(flowWork)) {
10643
+ errors.push("flow-template requires at least one maintenance node named \u751F\u6548\u4E2D/\u8FDB\u884C\u4E2D or status=1.");
10644
+ }
10645
+ if (!matrixListHasEditAction(listWork)) {
10646
+ errors.push("list-template requires the built-in ProjectDetailEdit modification action.");
10647
+ }
10648
+ const datasetBasic = isRecord3(datasetWork.basic) ? datasetWork.basic : datasetWork;
10649
+ const datasetCustomKey = normalizeText(datasetBasic.customKey ?? datasetBasic.custom_key ?? "");
10650
+ if (datasetCustomKey.length > MAX_DATASET_CUSTOM_KEY_LENGTH) {
10651
+ errors.push(
10652
+ `dataset custom_key is too long (${datasetCustomKey.length} > ${MAX_DATASET_CUSTOM_KEY_LENGTH}); shorten it before matrix resources are created.`
10653
+ );
10654
+ }
10655
+ const datasetFieldDefinitions = matrixDatasetFieldDefinitions(datasetWork);
10656
+ if (datasetFieldDefinitions.length === 0) {
10657
+ errors.push("dataset requires inline field definitions so a newly allocated matrix flow can create its dataset-field records.");
10658
+ }
10659
+ for (const [index, field] of datasetFieldDefinitions.entries()) {
10660
+ const missing = ["key", "name", "type", "classify", "source_table", "source_field", "source_fk"].filter((key) => normalizeText(field[key]) === "");
10661
+ if (missing.length > 0) {
10662
+ errors.push(`dataset field ${index + 1} requires inline source mapping: ${missing.join(", ")}.`);
10663
+ }
10664
+ }
10665
+ const flowPreflight = await lintFlowAppWorkFiles(formWorkFile, flowWorkFile, {
10666
+ workspace,
10667
+ name,
10668
+ pluginLint: { profile, agent: options.agent || "codex", requireInstalled: true }
10669
+ });
10670
+ if (flowPreflight.ok !== true) {
10671
+ errors.push(...Array.isArray(flowPreflight.errors) ? flowPreflight.errors.map(String) : ["flow-app lint failed"]);
10672
+ }
10673
+ if (errors.length) {
10674
+ throw new Error(`matrix app create lint failed: ${errors.join("; ")}`);
10675
+ }
10676
+ if (confirm3 !== expectedConfirm) {
10677
+ return {
10678
+ ...dryRunFields(expectedConfirm),
10679
+ domain: "approval-matrix",
10680
+ action: "app.create",
10681
+ workspace,
10682
+ name,
10683
+ operation_plan: [
10684
+ "create and publish form-template",
10685
+ "create matrix flow-template with one active maintenance node",
10686
+ "bind flow to workspace",
10687
+ "create dataset and require exact readback",
10688
+ "create and bind dataset-field definitions for the generated matrix flow",
10689
+ "create list-template with ProjectDetailEdit and require exact readback",
10690
+ "create filter-template and require exact readback",
10691
+ "bind list/filter template ids into flow.data.meta and publish live",
10692
+ "publish dataset",
10693
+ "exact-readback all matrix definition objects"
10694
+ ],
10695
+ flow_app_preflight: flowPreflight,
10696
+ next: `Run again with --confirm "${expectedConfirm}" to create.`
10697
+ };
10698
+ }
10699
+ const workDir = path5.resolve(options.workDir || `.codex/tmp/matrix-app-create-${Date.now()}`);
10700
+ await mkdir5(workDir, { recursive: true });
10701
+ const createdResources = {};
10702
+ try {
10703
+ const flowApp = await createFlowAppFromWork(
10704
+ config,
10705
+ profile,
10706
+ formWorkFile,
10707
+ flowWorkFile,
10708
+ `create flow-app ${name} in ${workspace}`,
10709
+ { ...options, workspace, name }
10710
+ );
10711
+ Object.assign(createdResources, isRecord3(flowApp.created_ids) ? flowApp.created_ids : {
10712
+ form_template_id: flowApp.form_template_id,
10713
+ form_template_draft_id: flowApp.form_template_draft_id,
10714
+ flow_type: flowApp.flow_type
10715
+ });
10716
+ const flowType = String(flowApp.flow_type ?? "");
10717
+ if (!flowType) {
10718
+ throw new Error("matrix app create did not receive the generated flow_type.");
10719
+ }
10720
+ const datasetResponse = await createMatrixConfigObject(config, profile, "dataset", {
10721
+ ...datasetWork,
10722
+ flow_type: flowType,
10723
+ flowType
10724
+ }, workDir);
10725
+ const datasetId = matrixCreatedId(datasetResponse, "dataset", { allowRecoverableReadbackMismatch: true });
10726
+ createdResources.dataset_id = Number(datasetId);
10727
+ const datasetFieldResponses = [];
10728
+ for (const [index, field] of datasetFieldDefinitions.entries()) {
10729
+ const response = await createMatrixDatasetField(config, profile, field, datasetId, flowType, index, workDir);
10730
+ const datasetFieldId = matrixCreatedId(response, "dataset-field");
10731
+ datasetFieldResponses.push(response);
10732
+ createdResources.dataset_field_ids = [
10733
+ ...Array.isArray(createdResources.dataset_field_ids) ? createdResources.dataset_field_ids : [],
10734
+ Number(datasetFieldId)
10735
+ ];
10736
+ }
10737
+ const exportedDataset = await exportConfigDomain(config, profile, "dataset", datasetId, workDir);
10738
+ const exportedDatasetWork = await readJsonFile(String(exportedDataset.work_file));
10739
+ if (!isRecord3(exportedDatasetWork)) {
10740
+ throw new Error("matrix app dataset exact export did not contain work data.");
10741
+ }
10742
+ const datasetBoundWorkFile = path5.join(workDir, "dataset.bound.work.json");
10743
+ const datasetBoundSubmitFile = path5.join(workDir, "dataset.bound.submit.json");
10744
+ await writeJsonFile(datasetBoundWorkFile, {
10745
+ ...exportedDatasetWork,
10746
+ mode: "edit",
10747
+ id: Number(datasetId),
10748
+ flow_type: flowType,
10749
+ flowType,
10750
+ fields: { selected: datasetFieldDefinitions },
10751
+ dataSetFields: datasetFieldDefinitions
10752
+ });
10753
+ await buildConfigSubmitPayload(
10754
+ "dataset",
10755
+ datasetBoundWorkFile,
10756
+ datasetBoundSubmitFile,
10757
+ String(exportedDataset.meta_file)
10758
+ );
10759
+ const datasetBindResponse = await submitConfigDomain(
10760
+ config,
10761
+ profile,
10762
+ "dataset",
10763
+ datasetId,
10764
+ datasetBoundSubmitFile,
10765
+ `submit dataset ${datasetId}`
10766
+ );
10767
+ if (datasetBindResponse.readback_status !== void 0 && datasetBindResponse.readback_status !== "verified") {
10768
+ throw new Error(`matrix app dataset field binding did not complete exact readback: ${String(datasetBindResponse.readback_status)}.`);
10769
+ }
10770
+ const datasetAfterFields = await readbackConfigDomain(config, profile, "dataset", datasetId);
10771
+ const datasetReadbackValue = isRecord3(datasetAfterFields.readback) ? datasetAfterFields.readback : {};
10772
+ const attachedFields = Array.isArray(datasetReadbackValue.dataSetFields) ? datasetReadbackValue.dataSetFields.filter(isRecord3).map((field) => String(field.key ?? "")) : [];
10773
+ const expectedFields = datasetFieldDefinitions.map((field) => String(field.key ?? field.field ?? ""));
10774
+ const missingAttachedFields = expectedFields.filter((key) => key && !attachedFields.includes(key));
10775
+ if (missingAttachedFields.length > 0) {
10776
+ throw new Error(`matrix app dataset exact readback is missing attached fields: ${missingAttachedFields.join(", ")}.`);
10777
+ }
10778
+ const listResponse = await createMatrixConfigObject(
10779
+ config,
10780
+ profile,
10781
+ "list-template",
10782
+ bindMatrixPageTemplateWork(listWork, flowType, datasetId),
10783
+ workDir
10784
+ );
10785
+ const listTemplateId = matrixCreatedId(listResponse, "list-template");
10786
+ createdResources.list_template_id = Number(listTemplateId);
10787
+ const filterResponse = await createMatrixConfigObject(
10788
+ config,
10789
+ profile,
10790
+ "filter-template",
10791
+ bindMatrixPageTemplateWork(filterWork, flowType, datasetId),
10792
+ workDir
10793
+ );
10794
+ const filterTemplateId = matrixCreatedId(filterResponse, "filter-template");
10795
+ createdResources.filter_template_id = Number(filterTemplateId);
10796
+ const exportedFlow = await exportConfigDomain(config, profile, "flow-template", flowType, workDir);
10797
+ const exportedFlowWork = await readJsonFile(String(exportedFlow.work_file));
10798
+ if (!isRecord3(exportedFlowWork) || !isRecord3(exportedFlowWork.data)) {
10799
+ throw new Error("matrix app flow exact export did not contain data.");
10800
+ }
10801
+ const flowData = { ...exportedFlowWork.data };
10802
+ const flowMeta = isRecord3(flowData.meta) ? { ...flowData.meta } : {};
10803
+ flowMeta.table_list_template = Number(listTemplateId);
10804
+ flowMeta.table_filter_template = Number(filterTemplateId);
10805
+ flowData.meta = flowMeta;
10806
+ const boundFlowWorkFile = path5.join(workDir, "flow-template.bound.work.json");
10807
+ const boundFlowSubmitFile = path5.join(workDir, "flow-template.bound.submit.json");
10808
+ await writeJsonFile(boundFlowWorkFile, { ...exportedFlowWork, category: "matrix", data: flowData });
10809
+ await buildConfigSubmitPayload("flow-template", boundFlowWorkFile, boundFlowSubmitFile, String(exportedFlow.meta_file), {
10810
+ publishLive: options.publishLive !== false,
10811
+ pluginLint: { profile, agent: options.agent || "codex", requireInstalled: true }
10812
+ });
10813
+ const flowBindResponse = await submitConfigDomain(
10814
+ config,
10815
+ profile,
10816
+ "flow-template",
10817
+ flowType,
10818
+ boundFlowSubmitFile,
10819
+ `submit flow-template ${flowType}`,
10820
+ { publishLive: options.publishLive !== false, agent: options.agent || "codex" }
10821
+ );
10822
+ createdResources.flow_templates_bound = true;
10823
+ const datasetPublishResponse = options.publishLive === false ? null : await runDatasetLifecycleAction(config, profile, "publish", datasetId, `publish dataset ${datasetId}`);
10824
+ createdResources.dataset_published = options.publishLive !== false;
10825
+ const [flowReadback, formReadback, datasetReadback, listReadback, filterReadback, workspaceReadback] = await Promise.all([
10826
+ readbackConfigDomain(config, profile, "flow-template", flowType),
10827
+ readbackConfigDomain(config, profile, "form-template", String(flowApp.form_template_draft_id)),
10828
+ readbackConfigDomain(config, profile, "dataset", datasetId),
10829
+ readbackConfigDomain(config, profile, "list-template", listTemplateId),
10830
+ readbackConfigDomain(config, profile, "filter-template", filterTemplateId),
10831
+ readbackConfigDomain(config, profile, "workspace-flow", workspace)
10832
+ ]);
10833
+ return {
10834
+ ...executedFields(),
10835
+ domain: "approval-matrix",
10836
+ action: "app.create",
10837
+ workspace,
10838
+ name,
10839
+ flow_type: flowType,
10840
+ created_ids: {
10841
+ form_template_id: flowApp.form_template_id,
10842
+ form_template_draft_id: flowApp.form_template_draft_id,
10843
+ flow_type: flowType,
10844
+ dataset_id: Number(datasetId),
10845
+ dataset_field_ids: datasetFieldResponses.map((response) => Number(response.id ?? response.created_id)),
10846
+ list_template_id: Number(listTemplateId),
10847
+ filter_template_id: Number(filterTemplateId)
10848
+ },
10849
+ operations: { flow_app: flowApp, dataset: datasetResponse, dataset_fields: datasetFieldResponses, dataset_bind: datasetBindResponse, list_template: listResponse, filter_template: filterResponse, flow_bind: flowBindResponse, dataset_publish: datasetPublishResponse },
10850
+ exact_readback: { flow: flowReadback, form: formReadback, dataset: datasetReadback, list_template: listReadback, filter_template: filterReadback, workspace_flow: workspaceReadback },
10851
+ work_dir: workDir
10852
+ };
10853
+ } catch (error) {
10854
+ if (Object.keys(createdResources).length === 0) {
10855
+ throw error;
10856
+ }
10857
+ const message = error instanceof Error ? error.message : String(error || "");
10858
+ return {
10859
+ ...executedFields(),
10860
+ status: "partial_success",
10861
+ partial_success: true,
10862
+ requires_follow_up: true,
10863
+ domain: "approval-matrix",
10864
+ action: "app.create",
10865
+ workspace,
10866
+ name,
10867
+ created_ids: createdResources,
10868
+ error: message,
10869
+ work_dir: workDir,
10870
+ next_recovery: "Do not rerun the complete matrix app create command. Inspect created_ids, repair the failed stage with the corresponding typed config command, then run matrix app inspect/readback."
10871
+ };
10872
+ }
10873
+ }
10039
10874
  async function readBackConfigDomain(profile, domain, id, definition) {
10040
10875
  const data = await readRemoteConfigDomain(profile, domain, id, definition);
10041
10876
  if (domain === "form-template") {
@@ -10120,6 +10955,9 @@ function normalizeTypedReadbackComparable(domain, value) {
10120
10955
  normalized.value = canonicalFormTemplateValues(normalized.value);
10121
10956
  }
10122
10957
  if (domain === "dataset") {
10958
+ if (Object.prototype.hasOwnProperty.call(normalized, "id")) {
10959
+ normalized.id = normalizeComparableId(normalized.id);
10960
+ }
10123
10961
  normalized.refresh_setting = refreshSettingToSubmit(normalized.refresh_setting);
10124
10962
  const raw = isRecord3(value) ? value : {};
10125
10963
  normalized.fields = normalizeComparableFieldKeys(
@@ -10127,9 +10965,36 @@ function normalizeTypedReadbackComparable(domain, value) {
10127
10965
  );
10128
10966
  }
10129
10967
  if (domain === "dataset-field") {
10130
- normalized.data_set_id = normalizeComparableId(
10131
- normalized.data_set_id ?? normalized.dataSetId ?? normalized.dataset_id
10132
- );
10968
+ delete normalized.data_set_id;
10969
+ delete normalized.dataSetId;
10970
+ delete normalized.dataset_id;
10971
+ }
10972
+ if (domain === "user") {
10973
+ delete normalized.phone;
10974
+ if (normalized.user_model_id !== void 0 && normalized.modelList === void 0) {
10975
+ const modelId = normalizeComparableId(normalized.user_model_id);
10976
+ normalized.modelList = modelId === null || modelId === void 0 || modelId === "" ? [] : [modelId];
10977
+ }
10978
+ delete normalized.user_model_id;
10979
+ for (const field of ["group_ids", "role_ids", "modelList"]) {
10980
+ if (Array.isArray(normalized[field])) {
10981
+ normalized[field] = [...new Set(normalized[field].map(normalizeComparableId))].sort((left, right) => String(left).localeCompare(String(right)));
10982
+ }
10983
+ }
10984
+ }
10985
+ if (domain === "team" && typeof normalized.admin_users === "string") {
10986
+ normalized.admin_users = normalized.admin_users.split(",").map((item) => normalizeComparableId(item.trim())).filter(Boolean).sort((left, right) => String(left).localeCompare(String(right)));
10987
+ }
10988
+ if (domain === "team" && (normalized.platform_id === null || normalized.platform_id === 0 || normalized.platform_id === "0")) {
10989
+ normalized.platform_id = null;
10990
+ }
10991
+ if (domain === "user-model" || domain === "group-model") {
10992
+ for (const field of ["form_template_id", "role_id"]) {
10993
+ if (normalized[field] !== void 0 && normalized[field] !== null) normalized[field] = normalizeComparableId(normalized[field]);
10994
+ }
10995
+ if (Array.isArray(normalized.sub_ids)) {
10996
+ normalized.sub_ids = [...new Set(normalized.sub_ids.map(normalizeComparableId))].sort((left, right) => String(left).localeCompare(String(right)));
10997
+ }
10133
10998
  }
10134
10999
  if (domain === "list-template" || domain === "filter-template" || domain === "project-detail-template" || domain === "step-detail-template" || domain === "console-template") {
10135
11000
  if (Object.prototype.hasOwnProperty.call(normalized, "data_set_id")) {
@@ -10226,8 +11091,8 @@ async function resolveFlowAppContextFlowId(profile, flow) {
10226
11091
  }
10227
11092
  const client = createApiClient(profile);
10228
11093
  const options = await apiRequest(client, "GET", "/flow/options", { capability: "flow.options" });
10229
- const rows = extractListData(options);
10230
- const matches = rows.filter((item) => String(item.name || item.title || "").trim() === trimmed);
11094
+ const rows2 = extractListData(options);
11095
+ const matches = rows2.filter((item) => String(item.name || item.title || "").trim() === trimmed);
10231
11096
  if (matches.length !== 1) {
10232
11097
  throw new Error(
10233
11098
  `flow-app context could not resolve flow name "${trimmed}" (${matches.length} matches). Use --flow flow_type:<flow_type>, --flow key:<flow_key>, or run bpmax-cli flow options --name "<name>" --format json first.`
@@ -10434,15 +11299,49 @@ async function readRemoteConfigDomain(profile, domain, id, definition) {
10434
11299
  definition.exportPath(id),
10435
11300
  { capability: `${definition.capability}.export` }
10436
11301
  );
11302
+ if (domain !== "flow-template") {
11303
+ assertRemoteConfigExists(domain, id, data);
11304
+ }
11305
+ if (domain === "user") {
11306
+ return privacySafeUserConfig(data);
11307
+ }
11308
+ if (domain === "team") {
11309
+ return privacySafeTeamConfig(data);
11310
+ }
11311
+ if (domain === "user-model" || domain === "group-model") {
11312
+ return privacySafeModelConfig(domain, data);
11313
+ }
10437
11314
  if (domain !== "flow-template" || hasUsableFlowTemplateData(data)) {
11315
+ if (domain === "flow-template") assertRemoteConfigExists(domain, id, data);
10438
11316
  return data;
10439
11317
  }
10440
- return apiRequest(
11318
+ const liveData = await apiRequest(
10441
11319
  createApiClient(profile),
10442
11320
  "GET",
10443
11321
  flowLiveExportPath(id),
10444
11322
  { capability: `${definition.capability}.export` }
10445
11323
  );
11324
+ assertRemoteConfigExists(domain, id, liveData);
11325
+ return liveData;
11326
+ }
11327
+ function assertRemoteConfigExists(domain, id, value) {
11328
+ if (domain === "project-detail-template" && id === "0") return;
11329
+ const identityRequired = domain === "user" || domain === "team" || domain === "user-model" || domain === "group-model";
11330
+ const identityMissing = identityRequired && /^\d+$/.test(id) && (!isRecord3(value) || String(value.id ?? "") !== id);
11331
+ const nestedDataMissing = isRecord3(value) && Object.prototype.hasOwnProperty.call(value, "data") && value.data === null;
11332
+ const deleted = isRecord3(value) && (value.is_del === 1 || value.is_del === "1");
11333
+ const emptyObject = isRecord3(value) && Object.keys(value).length === 0;
11334
+ const emptyFormPlaceholder = domain === "form-template" && isRecord3(value) && Array.isArray(value.rule) && value.rule.length === 0 && Array.isArray(value.value) && value.value.length === 0 && Object.keys(value).every((key) => key === "rule" || key === "value");
11335
+ if (value !== null && value !== void 0 && !nestedDataMissing && !deleted && !emptyObject && !emptyFormPlaceholder && !identityMissing) {
11336
+ return;
11337
+ }
11338
+ throw configWorkflowError(`\u8FDC\u7AEF ${domain} \u914D\u7F6E ${id} \u4E0D\u5B58\u5728\u6216\u5DF2\u5220\u9664\u3002`, {
11339
+ code: "config_remote_not_found",
11340
+ rule_id: "config.readback.exists",
11341
+ domain,
11342
+ path: id,
11343
+ suggestion: "\u91CD\u65B0\u67E5\u8BE2\u6709\u6548\u914D\u7F6E ID\uFF1B\u4E0D\u8981\u628A\u7A7A\u54CD\u5E94\u3001\u5220\u9664\u6807\u8BB0\u6216\u5360\u4F4D\u5BF9\u8C61\u5F53\u6210\u6210\u529F\u56DE\u8BFB\u3002"
11344
+ });
10446
11345
  }
10447
11346
  function extractRecords(value) {
10448
11347
  if (Array.isArray(value)) return value.filter(isRecord3);
@@ -10766,7 +11665,7 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
10766
11665
  throw new Error(`step-detail-template lint failed: ${errors.join("; ")}`);
10767
11666
  }
10768
11667
  }
10769
- const payloadWork = domain === "dataset-field" && createMode && isRecord3(work) ? { ...work, mode: "create" } : work;
11668
+ const payloadWork = (domain === "dataset" || domain === "dataset-field") && createMode && isRecord3(work) ? { ...work, mode: "create" } : work;
10770
11669
  const payload = buildDomainSubmitPayload(domain, payloadWork, options, raw);
10771
11670
  if (domain === "flow-template" && options.publishLive) {
10772
11671
  payload.publish_live = true;
@@ -10925,6 +11824,13 @@ async function lintConfigWorkFile(file, options = {}) {
10925
11824
  errors.push(error instanceof Error ? error.message : String(error));
10926
11825
  }
10927
11826
  }
11827
+ if (options.domain === "team" || options.domain === "user" || options.domain === "user-model" || options.domain === "group-model") {
11828
+ try {
11829
+ buildDomainSubmitPayload(options.domain, value);
11830
+ } catch (error) {
11831
+ errors.push(error instanceof Error ? error.message : String(error));
11832
+ }
11833
+ }
10928
11834
  if (Object.prototype.hasOwnProperty.call(value, "content")) {
10929
11835
  lintTemplateFieldReferences(value, errors);
10930
11836
  }
@@ -10932,6 +11838,12 @@ async function lintConfigWorkFile(file, options = {}) {
10932
11838
  if (shouldLintFormTemplate) {
10933
11839
  validateFormTemplateWorkLint(value, errors);
10934
11840
  }
11841
+ if (options.domain === "filter-template") {
11842
+ lintFilterTemplateWork(value, errors);
11843
+ }
11844
+ if (options.domain && CONFIG_DOMAINS[options.domain].expectedType !== void 0) {
11845
+ validatePageTemplateName(value, errors);
11846
+ }
10935
11847
  if (options.domain === "step-detail-template") {
10936
11848
  stepDetailAnalysis = lintStepDetailTemplateWork(value, errors, warnings);
10937
11849
  }
@@ -10967,7 +11879,7 @@ async function lintConfigWorkFile(file, options = {}) {
10967
11879
  errors.push(...stepDetailReferenceAudit.errors.filter((error) => !errors.includes(error)));
10968
11880
  warnings.push(...stepDetailReferenceAudit.warnings);
10969
11881
  }
10970
- if (flowWork.mode === "create") {
11882
+ if (options.mode === "create" || flowWork.mode === "create") {
10971
11883
  validateFlowTemplateFormDrivenCreateBaseline(flowWork, errors, { context: "flow-template create" });
10972
11884
  } else {
10973
11885
  validateFlowTemplateStandardFlowType(flowWork, errors);
@@ -11275,6 +12187,13 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11275
12187
  }
11276
12188
  let stepDetailAnalysis;
11277
12189
  const submitMode = isRecord3(meta) ? meta.mode : void 0;
12190
+ if (domain === "team" || domain === "user" || domain === "user-model" || domain === "group-model") {
12191
+ const validationWork = { ...submit.payload, mode: submitMode };
12192
+ if (submitMode !== "create") validationWork.id = id;
12193
+ const normalizedPayload = buildDomainSubmitPayload(domain, validationWork);
12194
+ for (const key of Object.keys(submit.payload)) delete submit.payload[key];
12195
+ Object.assign(submit.payload, normalizedPayload);
12196
+ }
11278
12197
  if (submitMode === "create" && domain !== "form-template") {
11279
12198
  if (!definition.createPath || !definition.createMethod) {
11280
12199
  throw new Error(`${domain} create is not implemented in the typed adapter.`);
@@ -11282,6 +12201,13 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11282
12201
  if (domain === "list-template") {
11283
12202
  validateListTemplateActionGate(submit.payload);
11284
12203
  }
12204
+ if (domain === "filter-template") {
12205
+ const errors = [];
12206
+ lintFilterTemplateWork(submit.payload, errors);
12207
+ if (errors.length) {
12208
+ throw new Error(`filter-template lint failed: ${errors.join("; ")}`);
12209
+ }
12210
+ }
11285
12211
  if (domain === "flow-template") {
11286
12212
  validateNonEmptyFlowCreatePayload(submit.payload);
11287
12213
  }
@@ -11314,7 +12240,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11314
12240
  id,
11315
12241
  endpoint: definition.createPath,
11316
12242
  method: definition.createMethod,
11317
- payload: submit.payload,
12243
+ payload: configPayloadForOutput(domain, submit.payload),
11318
12244
  ...stepDetailAnalysis ? {
11319
12245
  step_detail_template: stepDetailAnalysisEvidence(stepDetailAnalysis),
11320
12246
  warnings: stepDetailAnalysis.warnings,
@@ -11324,12 +12250,34 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11324
12250
  };
11325
12251
  }
11326
12252
  const client2 = createApiClient(profile);
11327
- const response2 = await apiRequest(
11328
- client2,
11329
- definition.createMethod,
11330
- definition.createPath,
11331
- { data: submit.payload, capability: `${definition.capability}.create` }
11332
- );
12253
+ let response2;
12254
+ try {
12255
+ response2 = await apiRequest(
12256
+ client2,
12257
+ definition.createMethod,
12258
+ definition.createPath,
12259
+ { data: submit.payload, capability: `${definition.capability}.create` }
12260
+ );
12261
+ } catch (error) {
12262
+ const status = errorStatus(error);
12263
+ const remoteWriteState = status && status >= 400 && status < 500 ? "not_started" : "unknown";
12264
+ throw configWorkflowError(
12265
+ `${domain} \u521B\u5EFA\u8BF7\u6C42\u5931\u8D25${status ? `\uFF08HTTP ${status}\uFF09` : ""}\uFF1B\u8FDC\u7AEF\u5199\u5165\u72B6\u6001\u4E3A ${remoteWriteState}\u3002${remoteWriteState === "unknown" ? " \u4E0D\u8981\u76F4\u63A5\u91CD\u8BD5\uFF0C\u4EE5\u514D\u521B\u5EFA\u91CD\u590D\u5BF9\u8C61\u3002" : ""}`,
12266
+ {
12267
+ code: "config_remote_create_failed",
12268
+ rule_id: "config.create.remote_mutation",
12269
+ domain,
12270
+ path: definition.createPath,
12271
+ request_phase: "mutation",
12272
+ http_status: status ?? null,
12273
+ remote_error: error instanceof Error ? error.message : String(error ?? ""),
12274
+ remote_write_state: remoteWriteState,
12275
+ remote_submitted: remoteWriteState === "not_started" ? false : null,
12276
+ readback_confirmed: false,
12277
+ suggestion: remoteWriteState === "unknown" ? `\u5148\u4F7F\u7528 bpmax-cli config ${domain} export/readback \u6216\u5BF9\u5E94\u641C\u7D22\u547D\u4EE4\u786E\u8BA4\u5BF9\u8C61\u662F\u5426\u5DF2\u521B\u5EFA\uFF1B\u786E\u8BA4\u4E0D\u5B58\u5728\u540E\u518D\u91CD\u8BD5\u3002` : "\u4FEE\u6B63\u8FDC\u7AEF\u6821\u9A8C\u9519\u8BEF\u540E\u91CD\u65B0\u6267\u884C create\u3002"
12278
+ }
12279
+ );
12280
+ }
11333
12281
  const createdId = responseDataId(response2);
11334
12282
  if (createdId === void 0 || createdId === null || createdId === "") {
11335
12283
  throw new Error(`${domain} create did not return an id required for exact typed readback.`);
@@ -11440,6 +12388,13 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11440
12388
  if (domain === "list-template") {
11441
12389
  validateListTemplateActionGate(submit.payload);
11442
12390
  }
12391
+ if (domain === "filter-template") {
12392
+ const errors = [];
12393
+ lintFilterTemplateWork(submit.payload, errors);
12394
+ if (errors.length) {
12395
+ throw new Error(`filter-template lint failed: ${errors.join("; ")}`);
12396
+ }
12397
+ }
11443
12398
  if (domain === "console-template") {
11444
12399
  const errors = [];
11445
12400
  const warnings = [];
@@ -11466,7 +12421,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11466
12421
  id,
11467
12422
  endpoint: endpoint2,
11468
12423
  method: "POST",
11469
- payload: submit.payload,
12424
+ payload: configPayloadForOutput(domain, submit.payload),
11470
12425
  publish_endpoint: "/form_template/publish",
11471
12426
  next: `Run again with --confirm "${expectedConfirm2}" to submit.`
11472
12427
  };
@@ -11536,6 +12491,14 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11536
12491
  throw new Error("dataset edit refuses to change custom_key identity through relationFields.");
11537
12492
  }
11538
12493
  }
12494
+ if (domain === "team") {
12495
+ if (isRecord3(current) && Object.prototype.hasOwnProperty.call(current, "platform_id")) {
12496
+ if (submit.payload.platform_id === void 0 || Number(submit.payload.platform_id) !== Number(current.platform_id)) {
12497
+ throw new Error("team edit \u5FC5\u987B\u539F\u6837\u4FDD\u7559\u7EBF\u4E0A platform_id\uFF1B\u4E0D\u5F97\u5220\u9664\u6216\u4FEE\u6539\u5916\u90E8\u5E73\u53F0\u7ED1\u5B9A\u3002");
12498
+ }
12499
+ }
12500
+ await assertTeamParentDoesNotCreateCycle(profile, id, submit.payload, definition, current);
12501
+ }
11539
12502
  validateExpectedType(domain, definition, current);
11540
12503
  const currentHash = hashJson(current);
11541
12504
  if (currentHash !== submit.base_hash) {
@@ -11627,7 +12590,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
11627
12590
  remote_error: remoteError,
11628
12591
  changed_paths: changedPaths,
11629
12592
  remote_write_state: remoteWriteState,
11630
- remote_submitted: remoteWriteState === "confirmed",
12593
+ remote_submitted: remoteWriteState === "confirmed" ? true : remoteWriteState === "not_started" ? false : null,
11631
12594
  readback_confirmed: readbackConfirmed,
11632
12595
  ...readbackError ? { readback_error: readbackError } : {},
11633
12596
  suggestion: `\u5148\u6267\u884C bpmax-cli config ${domain} verify --id ${id} --profile ${profile.name} --format json\uFF1B\u786E\u8BA4\u7EBF\u4E0A\u72B6\u6001\u540E\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\u3002`
@@ -11720,12 +12683,53 @@ async function deleteConfigDomain(config, profile, domain, id, confirm3) {
11720
12683
  next: `Run again with --confirm "${expectedConfirm}" to delete.`
11721
12684
  };
11722
12685
  }
11723
- const response = await apiRequest(
11724
- client,
11725
- definition.deleteMethod,
11726
- endpoint,
11727
- { capability: `${definition.capability}.delete` }
11728
- );
12686
+ let response;
12687
+ try {
12688
+ response = await apiRequest(
12689
+ client,
12690
+ definition.deleteMethod,
12691
+ endpoint,
12692
+ { capability: `${definition.capability}.delete` }
12693
+ );
12694
+ } catch (error) {
12695
+ let remoteWriteState = "unknown";
12696
+ let readbackConfirmed = false;
12697
+ let readbackError;
12698
+ if (domain === "team" || domain === "user" || domain === "user-model" || domain === "group-model") {
12699
+ try {
12700
+ await readRemoteConfigDomain(profile, domain, id, definition);
12701
+ remoteWriteState = "not_started";
12702
+ } catch (readError) {
12703
+ if (workflowErrorCode(readError) === "config_remote_not_found") {
12704
+ remoteWriteState = "confirmed";
12705
+ readbackConfirmed = true;
12706
+ } else {
12707
+ readbackError = readError instanceof Error ? readError.message : String(readError ?? "");
12708
+ }
12709
+ }
12710
+ } else {
12711
+ const status2 = errorStatus(error);
12712
+ if (status2 && status2 >= 400 && status2 < 500) remoteWriteState = "not_started";
12713
+ }
12714
+ const status = errorStatus(error);
12715
+ throw configWorkflowError(
12716
+ `${domain} \u5220\u9664\u8BF7\u6C42\u5931\u8D25${status ? `\uFF08HTTP ${status}\uFF09` : ""}\uFF1B\u8FDC\u7AEF\u5199\u5165\u72B6\u6001\u4E3A ${remoteWriteState}\u3002${remoteWriteState === "unknown" ? " \u5728\u5B8C\u6210\u53EA\u8BFB\u56DE\u8BFB\u524D\u4E0D\u8981\u91CD\u590D\u5220\u9664\u3002" : ""}`,
12717
+ {
12718
+ code: "config_remote_delete_failed",
12719
+ rule_id: "config.delete.remote_mutation",
12720
+ domain,
12721
+ path: endpoint,
12722
+ request_phase: "mutation",
12723
+ http_status: status ?? null,
12724
+ remote_error: error instanceof Error ? error.message : String(error ?? ""),
12725
+ remote_write_state: remoteWriteState,
12726
+ remote_submitted: remoteWriteState === "confirmed",
12727
+ readback_confirmed: readbackConfirmed,
12728
+ ...readbackError ? { readback_error: readbackError } : {},
12729
+ suggestion: remoteWriteState === "not_started" ? "\u8FDC\u7AEF\u5BF9\u8C61\u4ECD\u5B58\u5728\uFF1B\u6392\u9664\u963B\u65AD\u539F\u56E0\u540E\u53EF\u91CD\u65B0\u6267\u884C\u5220\u9664\u3002" : `\u5148\u6267\u884C bpmax-cli config ${domain} export --id ${id} --inline --profile ${profile.name} --format json \u786E\u8BA4\u5BF9\u8C61\u72B6\u6001\u3002`
12730
+ }
12731
+ );
12732
+ }
11729
12733
  return {
11730
12734
  dry_run: false,
11731
12735
  domain,
@@ -12005,6 +13009,10 @@ var CONFIG_DOMAINS2 = [
12005
13009
  ["dataset-field", "bpmax-dataset-field-template-editor", "\u6570\u636E\u96C6\u5B57\u6BB5"],
12006
13010
  ["api-platform", "bpmax-api-platform-editor", "API \u5E73\u53F0"],
12007
13011
  ["role", "bpmax-role-editor", "\u89D2\u8272\u6743\u9650"],
13012
+ ["team", "bpmax-team-editor", "\u56E2\u961F\u4E0E\u7EC4\u7EC7\u6811"],
13013
+ ["user", "bpmax-user", "\u7528\u6237\u4E0E\u7EC4\u7EC7\u5173\u7CFB"],
13014
+ ["user-model", "bpmax-user-model-editor", "\u7528\u6237\u6A21\u578B"],
13015
+ ["group-model", "bpmax-group-model-editor", "\u56E2\u961F\u6A21\u578B"],
12008
13016
  ["nav-config", "bpmax-nav-config-editor", "\u5BFC\u822A\u914D\u7F6E"]
12009
13017
  ];
12010
13018
  var CONFIG_DIRECTORY_PURPOSES = [
@@ -12018,6 +13026,10 @@ var CONFIG_DIRECTORY_PURPOSES = [
12018
13026
  ["think_api_proxy/", "API proxy configurations"],
12019
13027
  ["think_workspace/", "Workspace definitions"],
12020
13028
  ["think_role/", "Role definitions"],
13029
+ ["think_group/", "Team hierarchy and organization-unit definitions"],
13030
+ ["think_user/", "Organization user definitions and relation bindings"],
13031
+ ["think_user_model/", "User model definitions"],
13032
+ ["think_group_model/", "Team model definitions"],
12021
13033
  ["think_category/", "Category definitions"]
12022
13034
  ];
12023
13035
  async function hasExpectedWorkspaceEntry(root, entry) {
@@ -12180,7 +13192,7 @@ function renderConfigWorkspaceGuide(options) {
12180
13192
  const profileArg = shellQuote3(options.profileName);
12181
13193
  const envArg = shellQuote3(options.env);
12182
13194
  const commandPrefix3 = options.commandPrefix || "bpmax-cli";
12183
- const rows = CONFIG_DOMAINS2.map(
13195
+ const rows2 = CONFIG_DOMAINS2.map(
12184
13196
  ([domain, skill, label]) => `| ${label} | \`${skill}\` | \`${commandPrefix3} config ${domain} ...\` |`
12185
13197
  ).join("\n");
12186
13198
  const directoryRows = CONFIG_DIRECTORY_PURPOSES.map(
@@ -12225,7 +13237,7 @@ ${directoryRows}
12225
13237
  ## Skill \u8DEF\u7531
12226
13238
  | \u914D\u7F6E\u7C7B\u578B | Skill | CLI |
12227
13239
  | --- | --- | --- |
12228
- ${rows}
13240
+ ${rows2}
12229
13241
  | \u63D2\u4EF6 typed config | \u63D2\u4EF6\u4E13\u9879 skill | \`${commandPrefix3} config plugin <domain> ...\` |
12230
13242
  | \u6700\u65B0\u914D\u7F6E\u540C\u6B65 | \`bpmax-config-latest\` | \`${commandPrefix3} config latest pull ${options.env}\` |
12231
13243
  | \u957F\u671F\u8BB0\u5FC6 | \`bpmax-memory-protocol\` | \`${commandPrefix3} memory search --scope all --query "<env> <flow_type> <task>"\` |
@@ -13656,7 +14668,7 @@ function registerConfigCommands(program2) {
13656
14668
  });
13657
14669
  profile.command("list").description("List profiles").option("--format <format>", "Output format", "table").action(async (options) => {
13658
14670
  const configData = await loadConfig();
13659
- const rows = Object.entries(configData.profiles).map(([name, profileConfig]) => ({
14671
+ const rows2 = Object.entries(configData.profiles).map(([name, profileConfig]) => ({
13660
14672
  name,
13661
14673
  current: configData.current_profile === name,
13662
14674
  origin: profileConfig.origin,
@@ -13664,7 +14676,7 @@ function registerConfigCommands(program2) {
13664
14676
  language: profileConfig.language || DEFAULT_LANGUAGE,
13665
14677
  api_key: maskApiKey(profileConfig.api_key)
13666
14678
  }));
13667
- printResult(options.format, rows);
14679
+ printResult(options.format, rows2);
13668
14680
  });
13669
14681
  profile.command("use <name>").description("Set the active profile").action(async (name) => {
13670
14682
  const configData = await loadConfig();
@@ -13711,13 +14723,13 @@ function registerConfigCommands(program2) {
13711
14723
  });
13712
14724
  config.command("adapters").description("Show typed config domain adapter coverage and verified API surfaces").option("--profile <profile>", "Profile name (accepted for consistency; adapter coverage is local and profile-independent)").option("--capability <capability>", "Filter by capability name, e.g. config.dataset_field.create").option("--format <format>", "Output format", "table").action(async (options) => {
13713
14725
  void options.profile;
13714
- const rows = configAdapterMatrix();
13715
- const filtered = options.capability ? rows.filter((row) => Object.values(row).some((value) => {
14726
+ const rows2 = configAdapterMatrix();
14727
+ const filtered = options.capability ? rows2.filter((row) => Object.values(row).some((value) => {
13716
14728
  if (Array.isArray(value)) {
13717
14729
  return value.includes(options.capability);
13718
14730
  }
13719
14731
  return value === options.capability;
13720
- })) : rows;
14732
+ })) : rows2;
13721
14733
  printResult(options.format, filtered);
13722
14734
  });
13723
14735
  config.command("plugin").description("Manage plugin-provided typed config adapters").argument("[domain]", "Plugin typed config domain, or adapters").argument("[operation]", "Operation: export, lint, build, diff, submit, verify, test").option("--id <id>", "Remote plugin config id, list/all, or create:<stable-key>").option("--work <file>", "Work JSON file").option("--base <file>", "Optional raw baseline JSON for lifecycle rules").option("--out <file>", "Output file or directory").option("--meta <file>", "Export meta JSON file").option("--submit <file>", "Submit JSON file for diff").option("--payload <file>", "Submit payload JSON file produced by build").option("--expect <file>", "Expected work JSON file").option("--message <message>", "Smoke test message").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin adapter discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "pretty").action(async (domain, operation, options) => {
@@ -13987,7 +14999,10 @@ function registerConfigCommands(program2) {
13987
14999
  await saveConfig(configData);
13988
15000
  printResult(options.format, result);
13989
15001
  });
13990
- domainCommand.command("lint").description(`Lint a ${domain} work file`).requiredOption("--work <file>", "Work JSON file").option("--profile <profile>", "Profile name for plugin lint discovery").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--format <format>", "Output format", "pretty").action(async (options) => {
15002
+ domainCommand.command("lint").description(`Lint a ${domain} work file`).requiredOption("--work <file>", "Work JSON file").option("--mode <mode>", "Lint mode: create | edit").option("--profile <profile>", "Profile name for plugin lint discovery").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--format <format>", "Output format", "pretty").action(async (options) => {
15003
+ if (options.mode && options.mode !== "create" && options.mode !== "edit") {
15004
+ throw new Error("--mode \u53EA\u5141\u8BB8 create \u6216 edit\u3002");
15005
+ }
13991
15006
  let pluginLint;
13992
15007
  if (domain === "flow-template") {
13993
15008
  pluginLint = await resolveFlowTemplatePluginLintOptions({
@@ -13996,7 +15011,11 @@ function registerConfigCommands(program2) {
13996
15011
  requireInstalled: true
13997
15012
  });
13998
15013
  }
13999
- const result = await lintConfigWorkFile(options.work, { domain, pluginLint });
15014
+ const result = await lintConfigWorkFile(options.work, {
15015
+ domain,
15016
+ mode: options.mode,
15017
+ pluginLint
15018
+ });
14000
15019
  if (!result.ok) {
14001
15020
  printResult(options.format, result);
14002
15021
  throw new Error(`Config lint failed for ${options.work}`);
@@ -14146,6 +15165,9 @@ function registerConfigCommands(program2) {
14146
15165
  );
14147
15166
  await saveConfig(configData);
14148
15167
  printResult(options.format, result);
15168
+ if (result.ok === false) {
15169
+ process.exitCode = 1;
15170
+ }
14149
15171
  });
14150
15172
  });
14151
15173
  }
@@ -14445,8 +15467,8 @@ function csvValue(value) {
14445
15467
  const text5 = String(value ?? "");
14446
15468
  return /[",\r\n]/.test(text5) ? `"${text5.replace(/"/g, '""')}"` : text5;
14447
15469
  }
14448
- function csvText(fields, rows) {
14449
- return `${[fields.join(","), ...rows.map((row) => fields.map((field) => csvValue(row[field])).join(","))].join("\n")}
15470
+ function csvText(fields, rows2) {
15471
+ return `${[fields.join(","), ...rows2.map((row) => fields.map((field) => csvValue(row[field])).join(","))].join("\n")}
14450
15472
  `;
14451
15473
  }
14452
15474
  async function readCases(filePath) {
@@ -14612,10 +15634,10 @@ function keywordCandidates(value) {
14612
15634
  return [...new Set(value.split(/[、,,;;\s>,。::/]+/).map((word) => word.trim()).filter((word) => word.length >= 2).flatMap((word) => word.length >= 4 ? [word, word.slice(0, 4)] : [word]))].slice(0, 12);
14613
15635
  }
14614
15636
  function businessScenarioAlignmentMessage(filePath, caseId, row, steps, scenarioValue) {
14615
- const context = [row.title, row.preconditions, row.prep_data, caseStepText(steps), row.expected_result].join(" ");
14616
- const contextKeywords = keywordCandidates(context);
15637
+ const context2 = [row.title, row.preconditions, row.prep_data, caseStepText(steps), row.expected_result].join(" ");
15638
+ const contextKeywords = keywordCandidates(context2);
14617
15639
  const scenarioKeywords = keywordCandidates(scenarioValue);
14618
- const unmatched = scenarioKeywords.filter((word) => !context.includes(word));
15640
+ const unmatched = scenarioKeywords.filter((word) => !context2.includes(word));
14619
15641
  const suggestion = `\u4E1A\u52A1\u573A\u666F=${row.title || "<\u5BA2\u6237\u4E1A\u52A1\u52A8\u4F5C>"};\u4E1A\u52A1\u903B\u8F91=<\u8BF4\u660E\u8BE5\u573A\u666F\u9A8C\u8BC1\u7684\u6D41\u7A0B/\u6570\u636E/\u5BA1\u6279\u89C4\u5219>;\u6837\u672C\u6570\u636E=<\u8BF4\u660E\u771F\u5B9E\u4E1A\u52A1\u6837\u672C\u5C5E\u6027>;\u5408\u7406\u6027=<\u8BF4\u660E\u6837\u672C\u7B26\u5408\u5BA2\u6237\u4E1A\u52A1\u89C4\u5219>`;
14620
15642
  return [
14621
15643
  `${filePath}:${caseId}: \`test_data\` token \`\u4E1A\u52A1\u573A\u666F=\` must align with the case title, preconditions, steps, or expected result.`,
@@ -14887,10 +15909,10 @@ async function collectE2eAccelerationGaps(root) {
14887
15909
  if (!await exists3(casesPath)) {
14888
15910
  continue;
14889
15911
  }
14890
- const rows = await readCases(casesPath);
15912
+ const rows2 = await readCases(casesPath);
14891
15913
  const steps = await readCaseSteps(path10.join(dir, "case_steps.csv"));
14892
- const stepsByCase = validateCaseSteps(path10.join(dir, "case_steps.csv"), rows, steps);
14893
- for (const row of rows) {
15914
+ const stepsByCase = validateCaseSteps(path10.join(dir, "case_steps.csv"), rows2, steps);
15915
+ for (const row of rows2) {
14894
15916
  const caseSteps = stepsByCase.get(row.case_id.trim()) ?? [];
14895
15917
  if (row.status === "deprecated" || hasE2eReusableAsset(row, caseSteps)) {
14896
15918
  continue;
@@ -14914,18 +15936,18 @@ async function scenarioDirs(root) {
14914
15936
  async function validateScenario(scenarioDir) {
14915
15937
  const metadata = await validateReadme(scenarioDir);
14916
15938
  const casesPath = path10.join(scenarioDir, "cases.csv");
14917
- const rows = await readCases(casesPath);
15939
+ const rows2 = await readCases(casesPath);
14918
15940
  const caseStepsPath = path10.join(scenarioDir, "case_steps.csv");
14919
15941
  const caseSteps = await readCaseSteps(caseStepsPath);
14920
- const stepsByCase = validateCaseSteps(caseStepsPath, rows, caseSteps);
14921
- if (rows.length === 0) fail(`${casesPath}: at least one case is required`);
15942
+ const stepsByCase = validateCaseSteps(caseStepsPath, rows2, caseSteps);
15943
+ if (rows2.length === 0) fail(`${casesPath}: at least one case is required`);
14922
15944
  const seen = /* @__PURE__ */ new Set();
14923
- for (const row of rows) await validateCase(casesPath, row, stepsByCase.get(row.case_id.trim()) ?? [], seen);
14924
- const activeRows = rows.filter((row) => row.status === "active");
14925
- const availableRows = rows.filter((row) => row.status !== "deprecated");
15945
+ for (const row of rows2) await validateCase(casesPath, row, stepsByCase.get(row.case_id.trim()) ?? [], seen);
15946
+ const activeRows = rows2.filter((row) => row.status === "active");
15947
+ const availableRows = rows2.filter((row) => row.status !== "deprecated");
14926
15948
  if (metadata.status === "active" && activeRows.length === 0) fail(`${scenarioDir}: active scenario must contain active cases`);
14927
15949
  if (metadata.core.toLowerCase() === "true" && metadata.status !== "deprecated") {
14928
- const hasCorePositive = rows.some((row) => row.status !== "deprecated" && row.priority === "P0" && row.type === "positive");
15950
+ const hasCorePositive = rows2.some((row) => row.status !== "deprecated" && row.priority === "P0" && row.type === "positive");
14929
15951
  if (!hasCorePositive) fail(`${scenarioDir}: non-deprecated core scenario requires a non-deprecated P0 positive case`);
14930
15952
  }
14931
15953
  await validateCopyDiffArtifacts(scenarioDir);
@@ -14937,10 +15959,10 @@ async function validateScenario(scenarioDir) {
14937
15959
  core: metadata.core,
14938
15960
  status: metadata.status,
14939
15961
  summary: metadata.summary,
14940
- case_count: rows.length,
15962
+ case_count: rows2.length,
14941
15963
  active_case_count: activeRows.length,
14942
15964
  available_case_count: availableRows.length,
14943
- tags: [...new Set(rows.flatMap((row) => row.tags.split(",").map((tag) => tag.trim()).filter(Boolean)))].sort()
15965
+ tags: [...new Set(rows2.flatMap((row) => row.tags.split(",").map((tag) => tag.trim()).filter(Boolean)))].sort()
14944
15966
  };
14945
15967
  }
14946
15968
  async function lintSuite(root = DEFAULT_SUITE_ROOT) {
@@ -15392,11 +16414,11 @@ function currentManifestStep(manifest) {
15392
16414
  async function startTestSuiteRun(options) {
15393
16415
  const scenarioDir = scenarioPath(options.suiteRoot ?? DEFAULT_SUITE_ROOT, options.scenario);
15394
16416
  await validateScenario(scenarioDir);
15395
- const rows = await readCases(path10.join(scenarioDir, "cases.csv"));
15396
- const row = rows.find((item) => item.case_id === options.caseId && item.status !== "deprecated");
16417
+ const rows2 = await readCases(path10.join(scenarioDir, "cases.csv"));
16418
+ const row = rows2.find((item) => item.case_id === options.caseId && item.status !== "deprecated");
15397
16419
  if (!row) fail(`${scenarioDir}: active case not found: ${options.caseId}`, { rule_id: "test_suite.run.case_not_found" });
15398
16420
  const allSteps = await readCaseSteps(path10.join(scenarioDir, "case_steps.csv"));
15399
- const grouped = validateCaseSteps(path10.join(scenarioDir, "case_steps.csv"), rows, allSteps);
16421
+ const grouped = validateCaseSteps(path10.join(scenarioDir, "case_steps.csv"), rows2, allSteps);
15400
16422
  const selectedSteps = grouped.get(options.caseId) ?? [];
15401
16423
  const reportDir = await nextReportDir(options.reportRoot ?? DEFAULT_REPORT_ROOT, true);
15402
16424
  const runId = path10.basename(reportDir);
@@ -15827,9 +16849,9 @@ async function validateReviewGate(scenarioDir) {
15827
16849
  if (!Array.isArray(review.fixes) || review.fixes.length === 0) reviewFail(reviewPath, `${reviewPath}: fixes must be a non-empty list`);
15828
16850
  }
15829
16851
  async function validateExecutionOperabilityReview(reviewPath, scenarioDir, item) {
15830
- const rows = await readCases(path10.join(scenarioDir, "cases.csv"));
16852
+ const rows2 = await readCases(path10.join(scenarioDir, "cases.csv"));
15831
16853
  const steps = await readCaseSteps(path10.join(scenarioDir, "case_steps.csv"));
15832
- const activeCases = new Set(rows.filter((row) => row.status !== "deprecated").map((row) => row.case_id));
16854
+ const activeCases = new Set(rows2.filter((row) => row.status !== "deprecated").map((row) => row.case_id));
15833
16855
  const required = steps.filter((step) => activeCases.has(step.case_id)).map((step) => `${step.case_id}/${step.step_id}`);
15834
16856
  const judgments = item.step_judgments;
15835
16857
  if (!Array.isArray(judgments) || judgments.length === 0) {
@@ -15876,8 +16898,8 @@ async function validateConfigConsistencyReview(reviewPath, item) {
15876
16898
  function asRecord(value) {
15877
16899
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
15878
16900
  }
15879
- function defaultCaseJudgments(rows) {
15880
- return rows.map((row) => {
16901
+ function defaultCaseJudgments(rows2) {
16902
+ return rows2.map((row) => {
15881
16903
  const locations = configBasisLocations(row.config_basis).filter((location) => {
15882
16904
  try {
15883
16905
  return location.length > 0;
@@ -15901,7 +16923,7 @@ function defaultStepJudgments(steps) {
15901
16923
  evidence: "Initialized by bpmax-cli; reviewer must confirm this one-row step is independently executable before promote."
15902
16924
  }));
15903
16925
  }
15904
- function mergeReviewDraft(scenarioId, proof, rows, steps, existing) {
16926
+ function mergeReviewDraft(scenarioId, proof, rows2, steps, existing) {
15905
16927
  const existingPerspectives = Array.isArray(existing?.perspectives) ? existing.perspectives.filter((item) => item && typeof item === "object") : [];
15906
16928
  const byName = new Map(existingPerspectives.map((item) => [String(item.name || ""), item]));
15907
16929
  const configConsistency = asRecord(byName.get("config_consistency"));
@@ -15929,7 +16951,7 @@ function mergeReviewDraft(scenarioId, proof, rows, steps, existing) {
15929
16951
  reviewer: configConsistency.reviewer || "subagent-config",
15930
16952
  status: configConsistency.status || "fixed",
15931
16953
  summary: configConsistency.summary || "Initialized by bpmax-cli; replace with actual config consistency summary.",
15932
- case_judgments: Array.isArray(configConsistency.case_judgments) && configConsistency.case_judgments.length > 0 ? configConsistency.case_judgments : defaultCaseJudgments(rows),
16954
+ case_judgments: Array.isArray(configConsistency.case_judgments) && configConsistency.case_judgments.length > 0 ? configConsistency.case_judgments : defaultCaseJudgments(rows2),
15933
16955
  missing_case_review: asRecord(configConsistency.missing_case_review).summary ? configConsistency.missing_case_review : { needed: false, summary: "Initialized by bpmax-cli; reviewer must confirm whether any P0/P1 cases are missing." }
15934
16956
  };
15935
16957
  });
@@ -15952,7 +16974,7 @@ async function initOrRepairReview(options) {
15952
16974
  const scenarioDir = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
15953
16975
  if (!await exists3(scenarioDir)) fail(`draft scenario not found: ${scenarioDir}`);
15954
16976
  await validateReadme(scenarioDir);
15955
- const rows = await readCases(path10.join(scenarioDir, "cases.csv"));
16977
+ const rows2 = await readCases(path10.join(scenarioDir, "cases.csv"));
15956
16978
  const steps = await readCaseSteps(path10.join(scenarioDir, "case_steps.csv"));
15957
16979
  const proof = await readLatestProof(options.latestProof);
15958
16980
  const reviewPath = path10.join(scenarioDir, "review.json");
@@ -15966,7 +16988,7 @@ async function initOrRepairReview(options) {
15966
16988
  existing = {};
15967
16989
  }
15968
16990
  }
15969
- const review = mergeReviewDraft(path10.basename(scenarioDir), proof, rows, steps, existing);
16991
+ const review = mergeReviewDraft(path10.basename(scenarioDir), proof, rows2, steps, existing);
15970
16992
  await writeFile9(reviewPath, `${JSON.stringify(review, null, 2)}
15971
16993
  `, "utf8");
15972
16994
  return {
@@ -17326,27 +18348,27 @@ function registerStepCommands(program2) {
17326
18348
  const config = await loadConfig();
17327
18349
  const profile = resolveProfile(config, options.profile);
17328
18350
  const client = createApiClient(profile);
17329
- const context = await buildStepContext(profile, client, id, options.projectId);
18351
+ const context2 = await buildStepContext(profile, client, id, options.projectId);
17330
18352
  printResult(options.format, {
17331
- project_id: context.project_id,
17332
- step_id: context.step_id,
17333
- current_flow_node: context.current_flow_node,
17334
- actions: context.actions,
17335
- identity_unverified: context.identity_unverified,
17336
- risk_warnings: context.risk_warnings
18353
+ project_id: context2.project_id,
18354
+ step_id: context2.step_id,
18355
+ current_flow_node: context2.current_flow_node,
18356
+ actions: context2.actions,
18357
+ identity_unverified: context2.identity_unverified,
18358
+ risk_warnings: context2.risk_warnings
17337
18359
  });
17338
18360
  });
17339
18361
  step.command("requirements <id>").description("List required step inputs before submitting").requiredOption("--project-id <projectId>", "Project id").option("--data <json>", "Additional submit payload JSON or @file").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (id, options) => {
17340
18362
  const config = await loadConfig();
17341
18363
  const profile = resolveProfile(config, options.profile);
17342
18364
  const client = createApiClient(profile);
17343
- const context = await buildStepContext(profile, client, id, options.projectId);
18365
+ const context2 = await buildStepContext(profile, client, id, options.projectId);
17344
18366
  const data = await loadSubmitData(options.data);
17345
- const requirements = buildStepRequirements(context.step, context.current_flow_node, data);
18367
+ const requirements = buildStepRequirements(context2.step, context2.current_flow_node, data);
17346
18368
  printResult(options.format, {
17347
- project_id: context.project_id,
17348
- step_id: context.step_id,
17349
- url: context.url,
18369
+ project_id: context2.project_id,
18370
+ step_id: context2.step_id,
18371
+ url: context2.url,
17350
18372
  requirements
17351
18373
  });
17352
18374
  });
@@ -17354,9 +18376,9 @@ function registerStepCommands(program2) {
17354
18376
  const config = await loadConfig();
17355
18377
  const profile = resolveProfile(config, options.profile);
17356
18378
  const client = createApiClient(profile);
17357
- const context = await buildStepContext(profile, client, id, options.projectId);
18379
+ const context2 = await buildStepContext(profile, client, id, options.projectId);
17358
18380
  const data = await loadSubmitData(options.data);
17359
- const requirements = buildStepRequirements(context.step, context.current_flow_node, data);
18381
+ const requirements = buildStepRequirements(context2.step, context2.current_flow_node, data);
17360
18382
  const payload = {
17361
18383
  ...data,
17362
18384
  project_id: Number(options.projectId),
@@ -17379,27 +18401,27 @@ function registerStepCommands(program2) {
17379
18401
  dry_run: true,
17380
18402
  request,
17381
18403
  context: {
17382
- project_id: context.project_id,
17383
- step_id: context.step_id,
17384
- url: context.url,
17385
- identity_unverified: context.identity_unverified,
17386
- current_user_can_process: context.current_user_can_process,
17387
- step_finished: context.step_finished,
18404
+ project_id: context2.project_id,
18405
+ step_id: context2.step_id,
18406
+ url: context2.url,
18407
+ identity_unverified: context2.identity_unverified,
18408
+ current_user_can_process: context2.current_user_can_process,
18409
+ step_finished: context2.step_finished,
17388
18410
  requirements,
17389
- risk_warnings: context.risk_warnings
18411
+ risk_warnings: context2.risk_warnings
17390
18412
  },
17391
18413
  next_command_hint: requirements.can_submit ? "Re-run with --confirm after verifying project identity, target action, and payload." : "Fill missing required step input(s) in --data before confirming."
17392
18414
  });
17393
18415
  return;
17394
18416
  }
17395
- if (context.identity_unverified) {
18417
+ if (context2.identity_unverified) {
17396
18418
  throw new Error("Refusing to submit: project identity is unverified because project and step form evidence is empty.");
17397
18419
  }
17398
- if (context.step_finished) {
18420
+ if (context2.step_finished) {
17399
18421
  throw new Error("Refusing to submit: step appears to be finished.");
17400
18422
  }
17401
- if (context.current_user_can_process === false) {
17402
- throw new Error(`Refusing to submit: ${context.current_user_reason}`);
18423
+ if (context2.current_user_can_process === false) {
18424
+ throw new Error(`Refusing to submit: ${context2.current_user_reason}`);
17403
18425
  }
17404
18426
  if (!requirements.can_submit) {
17405
18427
  throw new Error(`Refusing to submit: missing required step input(s): ${requirements.missing_required_inputs.map((field) => field.key).join(", ")}`);
@@ -17415,12 +18437,22 @@ function registerStepCommands(program2) {
17415
18437
  result,
17416
18438
  project_id: options.projectId,
17417
18439
  step_id: id,
17418
- url: context.url
18440
+ url: context2.url
17419
18441
  });
17420
18442
  });
17421
18443
  }
17422
18444
 
17423
18445
  // src/commands/e2e.ts
18446
+ var BrowserSessionRejectedError = class extends Error {
18447
+ constructor(message, status, apiCode) {
18448
+ super(message);
18449
+ this.status = status;
18450
+ this.apiCode = apiCode;
18451
+ this.name = "BrowserSessionRejectedError";
18452
+ }
18453
+ status;
18454
+ apiCode;
18455
+ };
17424
18456
  async function requireE2eExecutionBinding(options, runners, evidenceDir) {
17425
18457
  if (options.diagnostic) return;
17426
18458
  if (!options.executionManifest || !options.caseId || !options.caseStepId) {
@@ -17572,10 +18604,17 @@ async function browserSessionRequest(profile, cookie, method, apiPath2, data, hr
17572
18604
  });
17573
18605
  const body = response.data;
17574
18606
  if (response.status >= 400) {
17575
- throw new Error(`e2e.identity.http_error: HTTP ${response.status} ${apiPath2}\u3002`);
18607
+ throw new BrowserSessionRejectedError(
18608
+ `e2e.identity.http_error: HTTP ${response.status} ${apiPath2}\u3002`,
18609
+ response.status
18610
+ );
17576
18611
  }
17577
18612
  if (isRecord8(body) && typeof body.code === "number" && body.code !== 0) {
17578
- throw new Error(`e2e.identity.api_error: ${String(body.msg ?? body.message ?? body.code)}`);
18613
+ throw new BrowserSessionRejectedError(
18614
+ `e2e.identity.api_error: ${String(body.msg ?? body.message ?? body.code)}`,
18615
+ response.status,
18616
+ body.code
18617
+ );
17579
18618
  }
17580
18619
  return isRecord8(body) && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
17581
18620
  }
@@ -17628,16 +18667,16 @@ function normalizeExpectedChecks(value) {
17628
18667
  ...Array.isArray(item.values) ? { values: item.values } : {}
17629
18668
  })).filter((item) => item.path);
17630
18669
  }
17631
- function expectationTarget(context, requirements) {
18670
+ function expectationTarget(context2, requirements) {
17632
18671
  return {
17633
18672
  context: {
17634
- current_user_can_process: context.current_user_can_process,
17635
- identity_unverified: context.identity_unverified,
17636
- step_finished: context.step_finished,
17637
- current_user_reason: context.current_user_reason,
17638
- actions: context.actions.map((action) => action.action),
17639
- action_labels: context.actions.map((action) => action.label),
17640
- owner_sources: context.owner_diagnostics.owner_sources
18673
+ current_user_can_process: context2.current_user_can_process,
18674
+ identity_unverified: context2.identity_unverified,
18675
+ step_finished: context2.step_finished,
18676
+ current_user_reason: context2.current_user_reason,
18677
+ actions: context2.actions.map((action) => action.action),
18678
+ action_labels: context2.actions.map((action) => action.label),
18679
+ owner_sources: context2.owner_diagnostics.owner_sources
17641
18680
  },
17642
18681
  requirements: {
17643
18682
  can_submit: requirements.can_submit,
@@ -17818,14 +18857,14 @@ async function writeRefreshedCache(file, template) {
17818
18857
  `, "utf8");
17819
18858
  return out;
17820
18859
  }
17821
- function blockedReason(context, canSubmit) {
17822
- if (context.identity_unverified) {
18860
+ function blockedReason(context2, canSubmit) {
18861
+ if (context2.identity_unverified) {
17823
18862
  return "identity_unverified";
17824
18863
  }
17825
- if (context.step_finished) {
18864
+ if (context2.step_finished) {
17826
18865
  return "step_finished";
17827
18866
  }
17828
- if (context.current_user_can_process === false) {
18867
+ if (context2.current_user_can_process === false) {
17829
18868
  return "current_user_cannot_process";
17830
18869
  }
17831
18870
  if (!canSubmit) {
@@ -17960,14 +18999,24 @@ function registerE2eCommands(program2) {
17960
18999
  const before = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
17961
19000
  let after = null;
17962
19001
  try {
17963
- await browserSessionRequest(profile, cookie, "PUT", `/user/${userId}`, { mock: true }, options.hrefPath);
17964
- after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
19002
+ await browserSessionRequest(profile, cookie, "PUT", `/user/${userId}?identity_action=mock`, { mock: true }, options.hrefPath);
17965
19003
  } catch (error) {
17966
- await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
19004
+ if (error instanceof BrowserSessionRejectedError) {
19005
+ throw new Error(
19006
+ `e2e.identity.mock_rejected: mock \u8BF7\u6C42\u88AB\u5E73\u53F0\u660E\u786E\u62D2\u7EDD\uFF0Cremote_submitted=false\u3002${error.message}`
19007
+ );
19008
+ }
19009
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
17967
19010
  throw new Error(`e2e.identity.mock_outcome_unknown: mock \u8BF7\u6C42\u6216\u5199\u540E\u56DE\u8BFB\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\uFF1B\u4E0D\u5F97\u91CD\u590D\u6267\u884C\u5F53\u524D\u6B65\u9AA4\uFF0C\u5148\u8FD0\u884C identity status \u786E\u8BA4\u4F1A\u8BDD\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
17968
19011
  }
19012
+ try {
19013
+ after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
19014
+ } catch (error) {
19015
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
19016
+ throw new Error(`e2e.identity.mock_outcome_unknown: mock \u5DF2\u63D0\u4EA4\u4F46\u5199\u540E\u56DE\u8BFB\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\uFF1B\u4E0D\u5F97\u91CD\u590D\u6267\u884C\u5F53\u524D\u6B65\u9AA4\uFF0C\u5148\u8FD0\u884C identity status \u786E\u8BA4\u4F1A\u8BDD\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
19017
+ }
17969
19018
  if (!after || Number(after.id) !== userId || after.mock !== true) {
17970
- await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
19019
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
17971
19020
  throw new Error("e2e.identity.mock_verify_failed: \u8FDC\u7A0B mock \u8BF7\u6C42\u5DF2\u63D0\u4EA4\uFF0C\u4F46\u5F53\u524D\u4F1A\u8BDD\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25\uFF1BCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\u3002");
17972
19021
  }
17973
19022
  let evidence;
@@ -17983,13 +19032,13 @@ function registerE2eCommands(program2) {
17983
19032
  target_user_id: userId
17984
19033
  });
17985
19034
  } catch (error) {
17986
- await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
19035
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
17987
19036
  throw new Error(`e2e.identity.evidence_failed: mock \u540E\u8BC1\u636E\u5199\u5165\u5931\u8D25\uFF0C\u5DF2\u5C1D\u8BD5\u6062\u590D\u539F\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
17988
19037
  }
17989
19038
  try {
17990
19039
  await appendE2eExecutionEvidence(options, evidence, ["browser"]);
17991
19040
  } catch (error) {
17992
- await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
19041
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
17993
19042
  throw new Error(`e2e.identity.manifest_evidence_failed: mock \u5DF2\u6267\u884C\u4F46\u7528\u4F8B\u8BC1\u636E\u767B\u8BB0\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\u3002${error instanceof Error ? error.message : String(error)}`);
17994
19043
  }
17995
19044
  printResult(options.format, {
@@ -18014,7 +19063,7 @@ function registerE2eCommands(program2) {
18014
19063
  remote_submitted: false
18015
19064
  });
18016
19065
  const before = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
18017
- await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath);
19066
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath);
18018
19067
  const after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
18019
19068
  if (!after || after.mock === true || before?.mock_by_user && Number(after.id) !== Number(before.mock_by_user)) {
18020
19069
  throw new Error("e2e.identity.unmock_verify_failed: unmock \u5DF2\u63D0\u4EA4\uFF0C\u4F46\u672A\u786E\u8BA4\u6062\u590D\u539F\u59CB\u8EAB\u4EFD\uFF0C\u5FC5\u987B\u505C\u6B62\u540E\u7EED\u7528\u4F8B\u3002");
@@ -18069,15 +19118,15 @@ function registerE2eCommands(program2) {
18069
19118
  break;
18070
19119
  }
18071
19120
  const prefix = `${String(index + 1).padStart(2, "0")}-step-${plan.step_id}`;
18072
- const context = await buildStepContext(profile, client, plan.step_id, options.projectId);
18073
- const requirements = buildStepRequirements(context.step, context.current_flow_node, plan.data);
19121
+ const context2 = await buildStepContext(profile, client, plan.step_id, options.projectId);
19122
+ const requirements = buildStepRequirements(context2.step, context2.current_flow_node, plan.data);
18074
19123
  const payload = buildSubmitPayload(options.projectId, plan);
18075
19124
  const contextFile = await writeEvidence(evidenceDir, `${prefix}-context.json`, {
18076
- ...context,
19125
+ ...context2,
18077
19126
  requirements
18078
19127
  });
18079
19128
  if (options.dataProfile) {
18080
- const target = expectationTarget(context, requirements);
19129
+ const target = expectationTarget(context2, requirements);
18081
19130
  const checkResults = evaluateExpectedChecks(plan.expected_checks, target);
18082
19131
  const failedChecks = checkResults.filter((check) => !check.ok);
18083
19132
  const missingChecks = plan.expected_checks.length === 0;
@@ -18094,7 +19143,7 @@ function registerE2eCommands(program2) {
18094
19143
  name: plan.label ?? `step-${plan.step_id}`,
18095
19144
  projectId: options.projectId,
18096
19145
  plan,
18097
- context,
19146
+ context: context2,
18098
19147
  requirements,
18099
19148
  evidenceDir,
18100
19149
  contextFile
@@ -18122,7 +19171,7 @@ function registerE2eCommands(program2) {
18122
19171
  params: { action: plan.action },
18123
19172
  data: payload
18124
19173
  };
18125
- const block = blockedReason(context, requirements.can_submit);
19174
+ const block = blockedReason(context2, requirements.can_submit);
18126
19175
  if (block) {
18127
19176
  stopped = true;
18128
19177
  steps.push({
@@ -18161,7 +19210,7 @@ function registerE2eCommands(program2) {
18161
19210
  } catch (error) {
18162
19211
  readbackError = error instanceof Error ? error.message : String(error);
18163
19212
  }
18164
- const readbackConfirmed2 = Boolean(readback && stepReadbackConfirmed(context, readback));
19213
+ const readbackConfirmed2 = Boolean(readback && stepReadbackConfirmed(context2, readback));
18165
19214
  let submitFile;
18166
19215
  let evidenceError;
18167
19216
  try {
@@ -18375,15 +19424,15 @@ function registerE2eCommands(program2) {
18375
19424
  if (inferredStepId && !contextFile && !submitFile) {
18376
19425
  throw new Error(`No step evidence files found for step ${inferredStepId} in ${options.evidenceDir}.`);
18377
19426
  }
18378
- const context = contextFile ? await readOptionalJson(path11.join(options.evidenceDir, contextFile)) : null;
19427
+ const context2 = contextFile ? await readOptionalJson(path11.join(options.evidenceDir, contextFile)) : null;
18379
19428
  const submit = submitFile ? await readOptionalJson(path11.join(options.evidenceDir, submitFile)) : null;
18380
- const requirements = isRecord8(context?.requirements) ? context.requirements : {};
19429
+ const requirements = isRecord8(context2?.requirements) ? context2.requirements : {};
18381
19430
  const requiredInputs = Array.isArray(requirements.required_inputs) ? requirements.required_inputs.filter(isRecord8) : [];
18382
19431
  const missingInputs = Array.isArray(requirements.missing_required_inputs) ? requirements.missing_required_inputs.filter(isRecord8) : [];
18383
19432
  const requestData = isRecord8(submit?.request) && isRecord8(submit.request.data) ? submit.request.data : {};
18384
19433
  const recordedAction = stringValue3(requestData.action);
18385
19434
  const expectedChecks = buildExpectedChecks({
18386
- context,
19435
+ context: context2,
18387
19436
  requirements: {
18388
19437
  required_inputs: requiredInputs,
18389
19438
  missing_required_inputs: submitFile ? [] : missingInputs
@@ -19300,10 +20349,10 @@ async function fetchAllMatrixRuleRecords(client, flowType) {
19300
20349
  data: { flow_type: flowType, page, page_size: pageSize },
19301
20350
  capability: "project.list"
19302
20351
  });
19303
- const rows = dataArray(result).filter(isRecord10);
19304
- records.push(...rows);
20352
+ const rows2 = dataArray(result).filter(isRecord10);
20353
+ records.push(...rows2);
19305
20354
  const total = Number(result.count ?? result.total ?? records.length);
19306
- if (rows.length < pageSize || records.length >= total) break;
20355
+ if (rows2.length < pageSize || records.length >= total) break;
19307
20356
  if (records.length >= maxRecords) {
19308
20357
  truncated = true;
19309
20358
  break;
@@ -19360,13 +20409,14 @@ function flowCategory(flow) {
19360
20409
  function hasIdentifier(value) {
19361
20410
  return value !== void 0 && value !== null && String(value).trim() !== "" && String(value) !== "0";
19362
20411
  }
19363
- function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], workspaceBound = false) {
20412
+ function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], datasets = [], workspaceBound = false) {
19364
20413
  const data = isRecord10(flow.data) ? flow.data : {};
19365
20414
  const meta = isRecord10(data.meta) ? data.meta : {};
19366
20415
  const refs = {
19367
20416
  form_template_id: meta.form_template ?? flow.form_template_id,
19368
20417
  list_template_ids: listTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier),
19369
- filter_template_ids: filterTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier)
20418
+ filter_template_ids: filterTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier),
20419
+ dataset_ids: datasets.map((item) => item.id ?? item.data_set_id).filter(hasIdentifier)
19370
20420
  };
19371
20421
  const errors = [];
19372
20422
  if (flowCategory(flow) !== "matrix") {
@@ -19402,12 +20452,91 @@ function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], worksp
19402
20452
  suggestion: "\u4ECE\u6700\u65B0 workspace-flow \u56DE\u8BFB merge \u540E\u901A\u8FC7 typed CLI \u63D0\u4EA4\u7ED1\u5B9A\u3002"
19403
20453
  });
19404
20454
  }
19405
- return { category: flowCategory(flow), template_refs: refs, workspace_bound: workspaceBound, errors };
20455
+ const nodes = dataArray(data.nodes).filter(isRecord10);
20456
+ const activeNodes = nodes.filter((node) => {
20457
+ const name = String(node.name ?? "").trim();
20458
+ return name === "\u751F\u6548\u4E2D" || name === "\u8FDB\u884C\u4E2D" || Number(node.status) === 1;
20459
+ });
20460
+ if (!activeNodes.length) {
20461
+ errors.push({
20462
+ code: "matrix.app.active_maintenance_node_required",
20463
+ rule_id: "matrix.app.active_maintenance_node_required",
20464
+ domain: "approval-matrix",
20465
+ path: "$.data.nodes",
20466
+ message: "\u77E9\u9635\u6D41\u7A0B\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u201C\u751F\u6548\u4E2D/\u8FDB\u884C\u4E2D\u201D\u7684\u7EF4\u62A4\u73AF\u8282\u3002",
20467
+ suggestion: "\u4FDD\u7559\u4E00\u4E2A\u77E9\u9635\u6570\u636E\u7EF4\u62A4\u73AF\u8282\u5373\u53EF\uFF0C\u4E0D\u9700\u8981\u642D\u5EFA\u591A\u73AF\u8282\u5BA1\u6279\u94FE\u3002"
20468
+ });
20469
+ }
20470
+ const hasEditAction = listTemplates.some((template) => JSON.stringify(template).includes("ProjectDetailEdit"));
20471
+ if (!hasEditAction) {
20472
+ errors.push({
20473
+ code: "matrix.app.list_edit_action_required",
20474
+ rule_id: "matrix.app.list_edit_action_required",
20475
+ domain: "approval-matrix",
20476
+ path: "$.list_template.content",
20477
+ message: "\u77E9\u9635\u5217\u8868\u7F3A\u5C11\u5185\u7F6E\u4FEE\u6539\u64CD\u4F5C ProjectDetailEdit\u3002",
20478
+ suggestion: "\u5728\u64CD\u4F5C\u5217\u52A0\u5165 ProjectDetailEdit\uFF0C\u4F7F\u89C4\u5219\u884C\u53EF\u901A\u8FC7\u62BD\u5C49\u4FEE\u6539\u3002"
20479
+ });
20480
+ }
20481
+ return {
20482
+ category: flowCategory(flow),
20483
+ template_refs: refs,
20484
+ workspace_bound: workspaceBound,
20485
+ maintenance_nodes: activeNodes.map((node) => ({ id: node.id ?? null, name: node.name ?? null, status: node.status ?? null })),
20486
+ list_edit_action: hasEditAction ? "ProjectDetailEdit" : null,
20487
+ errors
20488
+ };
20489
+ }
20490
+ function matrixHash(value) {
20491
+ return hashJson(value);
20492
+ }
20493
+ function uniqueIds(values) {
20494
+ return [...new Set(values.filter(hasIdentifier).map((value) => String(value)))];
20495
+ }
20496
+ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeRaw = false, strict = true) {
20497
+ const client = createApiClient(profile);
20498
+ const [flow, listResult, filterResult, workspaceResult] = await Promise.all([
20499
+ apiRequest(client, "GET", "/flow", { params: { flow_type: flowType, draft: 0, skip_i18n: true } }),
20500
+ apiRequest(client, "GET", "/flow_page_template", { params: { type: 1, flow_type: flowType, flow_key: "", skip_i18n: true }, capability: "config.list_template.export" }),
20501
+ apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: flowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
20502
+ apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
20503
+ ]);
20504
+ const flowData = isRecord10(flow.data) ? flow.data : {};
20505
+ const meta = isRecord10(flowData.meta) ? flowData.meta : {};
20506
+ const listRows = dataArray(listResult).filter(isRecord10);
20507
+ const filterRows = dataArray(filterResult).filter(isRecord10);
20508
+ const listIds = uniqueIds([meta.table_list_template, ...listRows.map((item) => item.id ?? item.flow_page_template_id)]);
20509
+ const filterIds = uniqueIds([meta.table_filter_template, ...filterRows.map((item) => item.id ?? item.flow_page_template_id)]);
20510
+ const formId = String(meta.form_template ?? flow.form_template_id ?? "");
20511
+ const [form, listTemplates, filterTemplates] = await Promise.all([
20512
+ formId ? apiRequest(client, "GET", `/form_template/${encodeURIComponent(formId)}`, { capability: "config.form_template.export" }) : Promise.resolve({}),
20513
+ Promise.all(listIds.map((id) => apiRequest(client, "GET", `/flow_page_template/${encodeURIComponent(id)}?skip_i18n=true`, { capability: "config.list_template.export" }))),
20514
+ Promise.all(filterIds.map((id) => apiRequest(client, "GET", `/flow_page_template/${encodeURIComponent(id)}?skip_i18n=true`, { capability: "config.filter_template.export" })))
20515
+ ]);
20516
+ const datasetIds = uniqueIds([
20517
+ ...listTemplates.map((item) => item.data_set_id),
20518
+ ...filterTemplates.map((item) => item.data_set_id)
20519
+ ]);
20520
+ const datasets = await Promise.all(datasetIds.map((id) => apiRequest(client, "GET", `/data_set/${encodeURIComponent(id)}`, { capability: "config.dataset.export" })));
20521
+ const summary = matrixAppSummary(flow, listTemplates, filterTemplates, datasets, workspaceHasFlow(workspaceResult, flowType));
20522
+ if (strict) {
20523
+ assertNoMatrixErrors(summary.errors);
20524
+ }
20525
+ const formRecord = isRecord10(form) ? form : {};
20526
+ const exactReadback = {
20527
+ flow: { id: flowType, readback_hash: matrixHash(flow), ...includeRaw ? { readback: flow } : {} },
20528
+ form_template: { id: formId, draft_id: formRecord.origin_template_id ?? formRecord.id ?? null, readback_hash: matrixHash(formRecord), ...includeRaw ? { readback: formRecord } : {} },
20529
+ datasets: datasets.map((item, index) => ({ id: datasetIds[index], readback_hash: matrixHash(item), ...includeRaw ? { readback: item } : {} })),
20530
+ list_templates: listTemplates.map((item, index) => ({ id: listIds[index], readback_hash: matrixHash(item), ...includeRaw ? { readback: item } : {} })),
20531
+ filter_templates: filterTemplates.map((item, index) => ({ id: filterIds[index], readback_hash: matrixHash(item), ...includeRaw ? { readback: item } : {} })),
20532
+ workspace_flow: { id: workspace, readback_hash: matrixHash(workspaceResult), ...includeRaw ? { readback: workspaceResult } : {} }
20533
+ };
20534
+ return { ok: summary.errors.length === 0, domain: "approval-matrix", action: "app.inspect", flow_type: flowType, workspace, ...summary, exact_readback: exactReadback };
19406
20535
  }
19407
20536
  function workspaceHasFlow(value, flowType) {
19408
20537
  if (!isRecord10(value)) return false;
19409
- const rows = Array.isArray(value.workspace_flow) ? value.workspace_flow.filter(isRecord10) : isRecord10(value.data) && Array.isArray(value.data.workspace_flow) ? value.data.workspace_flow.filter(isRecord10) : [];
19410
- return rows.some((item) => String(item.flow_type ?? "") === flowType && Number(item.is_del ?? 0) === 0);
20538
+ const rows2 = Array.isArray(value.workspace_flow) ? value.workspace_flow.filter(isRecord10) : isRecord10(value.data) && Array.isArray(value.data.workspace_flow) ? value.data.workspace_flow.filter(isRecord10) : [];
20539
+ return rows2.some((item) => String(item.flow_type ?? "") === flowType && Number(item.is_del ?? 0) === 0);
19411
20540
  }
19412
20541
  function matrixConsumerSummary(node, expectedMatrixFlowType) {
19413
20542
  const errors = [];
@@ -19471,6 +20600,23 @@ function collectUserIds(value) {
19471
20600
  const direct = Number(value);
19472
20601
  return Number.isSafeInteger(direct) && direct > 0 ? [direct] : [];
19473
20602
  }
20603
+ async function readMatrixApprovers(client, ids) {
20604
+ const users = [];
20605
+ for (let index = 0; index < ids.length; index += 100) {
20606
+ const chunk = ids.slice(index, index + 100);
20607
+ const result = await apiRequest(client, "GET", "/user", {
20608
+ params: {
20609
+ ids: chunk.join(","),
20610
+ page: 1,
20611
+ page_size: 100,
20612
+ field_filter: "id,name,status,is_del,organization_id"
20613
+ },
20614
+ capability: "user.readback"
20615
+ });
20616
+ users.push(...dataArray(result).filter(isRecord10));
20617
+ }
20618
+ return users;
20619
+ }
19474
20620
  function assertNoMatrixErrors(errors) {
19475
20621
  if (!errors.length) return;
19476
20622
  throw new Error(`Matrix validation failed:
@@ -19587,27 +20733,102 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19587
20733
  ]
19588
20734
  });
19589
20735
  });
19590
- const app = matrix.command("app").description("Inspect approval matrix application configuration");
19591
- app.command("inspect").requiredOption("--flow-type <flowType>", "Matrix flow type").option("--workspace <workspace>", "Workspace binding to verify; defaults to profile workspace").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
20736
+ const app = matrix.command("app").description("Create, edit, inspect, and delete approval matrix application definitions");
20737
+ const registerAppInspect = (name) => app.command(name).description("Exact-readback matrix flow, form, dataset, list, filter, and workspace binding").requiredOption("--flow-type <flowType>", "Matrix flow type").option("--workspace <workspace>", "Workspace binding to verify; defaults to profile workspace").option("--profile <profile>", "Profile name").option("--include-raw", "Include full config readback objects in JSON output").option("--format <format>", "Output format", "json").action(async (options) => {
19592
20738
  const config = await loadConfig();
19593
20739
  const profile = resolveProfile(config, options.profile);
19594
- const client = createApiClient(profile);
19595
20740
  const workspace = String(options.workspace || profile.config.workspace || "").replace(/^w:/, "");
19596
20741
  if (!workspace) throw new Error("matrix.app.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u9A8C\u8BC1\u77E9\u9635\u5E94\u7528\u7ED1\u5B9A\u3002");
19597
- const [flow, listResult, filterResult, workspaceResult] = await Promise.all([
19598
- apiRequest(client, "GET", "/flow", { params: { flow_type: options.flowType, draft: 0, skip_i18n: true } }),
19599
- apiRequest(client, "GET", "/flow_page_template", { params: { type: 1, flow_type: options.flowType, flow_key: "", skip_i18n: true }, capability: "config.list_template.export" }),
19600
- apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: options.flowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
19601
- apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
19602
- ]);
19603
- const summary = matrixAppSummary(
19604
- flow,
19605
- dataArray(listResult).filter(isRecord10),
19606
- dataArray(filterResult).filter(isRecord10),
19607
- workspaceHasFlow(workspaceResult, options.flowType)
20742
+ const result = await inspectMatrixAppDefinition(profile, options.flowType, workspace, Boolean(options.includeRaw));
20743
+ printResult(options.format, { ...result, action: `app.${name}` });
20744
+ });
20745
+ registerAppInspect("inspect");
20746
+ registerAppInspect("readback");
20747
+ app.command("create").description("Create a complete matrix definition: form, flow, dataset, editable list, filter, and workspace binding").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--name <name>", "Matrix application name").requiredOption("--form-work <file>", "Form-template create work JSON").requiredOption("--flow-work <file>", "Matrix flow-template create work JSON").requiredOption("--dataset-work <file>", "Dataset create work JSON").requiredOption("--list-work <file>", "List-template create work JSON containing ProjectDetailEdit").requiredOption("--filter-work <file>", "Filter-template create work JSON").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--draft-only", "Create configuration without publishing the flow and dataset live").option("--confirm <text>", "Exact confirmation text").option("--work-dir <dir>", "Directory for generated typed submit/readback evidence").option("--format <format>", "Output format", "json").action(async (options) => {
20748
+ const config = await loadConfig();
20749
+ const profile = resolveProfile(config, options.profile);
20750
+ const result = await createMatrixAppFromWork(
20751
+ config,
20752
+ profile,
20753
+ options.formWork,
20754
+ options.flowWork,
20755
+ options.datasetWork,
20756
+ options.listWork,
20757
+ options.filterWork,
20758
+ options.confirm,
20759
+ {
20760
+ workspace: options.workspace,
20761
+ name: options.name,
20762
+ publishLive: !options.draftOnly,
20763
+ agent: options.agent,
20764
+ workDir: options.workDir
20765
+ }
19608
20766
  );
19609
- assertNoMatrixErrors(summary.errors);
19610
- printResult(options.format, { ok: true, domain: "approval-matrix", action: "app.inspect", flow_type: options.flowType, ...summary });
20767
+ await saveConfig(config);
20768
+ printResult(options.format, result);
20769
+ });
20770
+ app.command("update").description("Update matrix definition objects through a typed config batch manifest, then exact-readback the complete app").requiredOption("--flow-type <flowType>", "Matrix flow type").requiredOption("--manifest <file>", "Typed config batch submit manifest").option("--workspace <workspace>", "Workspace binding to verify; defaults to profile workspace").option("--profile <profile>", "Profile name").option("--continue-on-error", "Continue after a failed manifest row").option("--format <format>", "Output format", "json").action(async (options) => {
20771
+ const config = await loadConfig();
20772
+ const profile = resolveProfile(config, options.profile);
20773
+ const workspace = String(options.workspace || profile.config.workspace || "").replace(/^w:/, "");
20774
+ if (!workspace) throw new Error("matrix.app.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u9A8C\u8BC1\u77E9\u9635\u5E94\u7528\u7ED1\u5B9A\u3002");
20775
+ const batch = await runConfigBatchSubmit(config, profile, options.manifest, { continueOnError: Boolean(options.continueOnError) });
20776
+ if (batch.ok !== true) {
20777
+ printResult(options.format, { ok: false, domain: "approval-matrix", action: "app.update", batch });
20778
+ throw new Error("matrix app update failed; exact readback was not executed.");
20779
+ }
20780
+ const readback = await inspectMatrixAppDefinition(profile, options.flowType, workspace, false);
20781
+ await saveConfig(config);
20782
+ printResult(options.format, { ok: true, domain: "approval-matrix", action: "app.update", batch, exact_readback: readback });
20783
+ });
20784
+ app.command("delete").description("Delete a complete matrix definition in dependency order").requiredOption("--flow-type <flowType>", "Matrix flow type").option("--workspace <workspace>", "Workspace binding to remove; defaults to profile workspace").option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "json").action(async (options) => {
20785
+ const config = await loadConfig();
20786
+ const profile = resolveProfile(config, options.profile);
20787
+ const workspace = String(options.workspace || profile.config.workspace || "").replace(/^w:/, "");
20788
+ if (!workspace) throw new Error("matrix.app.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u5220\u9664\u77E9\u9635\u5E94\u7528\u3002");
20789
+ const definition = await inspectMatrixAppDefinition(profile, options.flowType, workspace, true, false);
20790
+ const exact = definition.exact_readback;
20791
+ const listItems = Array.isArray(exact.list_templates) ? exact.list_templates.filter(isRecord10) : [];
20792
+ const filterItems = Array.isArray(exact.filter_templates) ? exact.filter_templates.filter(isRecord10) : [];
20793
+ const datasetItems = Array.isArray(exact.datasets) ? exact.datasets.filter(isRecord10) : [];
20794
+ const datasetFieldIds = uniqueIds(datasetItems.flatMap((item) => {
20795
+ const readback = isRecord10(item.readback) ? item.readback : {};
20796
+ return Array.isArray(readback.dataSetFields) ? readback.dataSetFields.filter(isRecord10).map((field) => field.id) : [];
20797
+ }));
20798
+ const formItem = isRecord10(exact.form_template) ? exact.form_template : {};
20799
+ const formDraftId = String(formItem.draft_id ?? formItem.id ?? "");
20800
+ const expectedConfirm = `delete matrix app ${options.flowType} from ${workspace}`;
20801
+ const plan = [
20802
+ { domain: "workspace-flow", id: `${workspace}|${options.flowType}|` },
20803
+ ...listItems.map((item) => ({ domain: "list-template", id: String(item.id) })),
20804
+ ...filterItems.map((item) => ({ domain: "filter-template", id: String(item.id) })),
20805
+ ...datasetFieldIds.map((id) => ({ domain: "dataset-field", id })),
20806
+ ...datasetItems.map((item) => ({ domain: "dataset", id: String(item.id) })),
20807
+ { domain: "flow-template", id: options.flowType },
20808
+ ...formDraftId ? [{ domain: "form-template", id: formDraftId }] : []
20809
+ ];
20810
+ if (options.confirm !== expectedConfirm) {
20811
+ printResult(options.format, {
20812
+ ok: true,
20813
+ dry_run: true,
20814
+ operation_executed: false,
20815
+ domain: "approval-matrix",
20816
+ action: "app.delete",
20817
+ flow_type: options.flowType,
20818
+ workspace,
20819
+ exact_readback: definition,
20820
+ operation_plan: plan,
20821
+ required_confirm: expectedConfirm
20822
+ });
20823
+ return;
20824
+ }
20825
+ const results = [];
20826
+ for (const item of plan) {
20827
+ const domain = item.domain;
20828
+ results.push(await deleteConfigDomain(config, profile, domain, item.id, `delete ${domain} ${item.id}`));
20829
+ }
20830
+ await saveConfig(config);
20831
+ printResult(options.format, { ok: true, domain: "approval-matrix", action: "app.delete", flow_type: options.flowType, workspace, deleted: results });
19611
20832
  });
19612
20833
  const consumer = matrix.command("consumer").description("Lint a business-flow matrix owner or CC consumer node");
19613
20834
  consumer.command("lint").requiredOption("--flow-type <flowType>", "Business flow type").requiredOption("--node <nodeId>", "Consumer node id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
@@ -19636,12 +20857,13 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19636
20857
  apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: options.matrixFlowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
19637
20858
  apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
19638
20859
  ]);
19639
- const appSummary = matrixAppSummary(
19640
- matrixFlow,
19641
- dataArray(listResult).filter(isRecord10),
19642
- dataArray(filterResult).filter(isRecord10),
19643
- workspaceHasFlow(workspaceResult, options.matrixFlowType)
19644
- );
20860
+ const listRows = dataArray(listResult).filter(isRecord10);
20861
+ const filterRows = dataArray(filterResult).filter(isRecord10);
20862
+ const listTemplates = await Promise.all(uniqueIds(listRows.map((item) => item.id ?? item.flow_page_template_id)).map((id) => apiRequest(client, "GET", `/flow_page_template/${encodeURIComponent(id)}?skip_i18n=true`, { capability: "config.list_template.export" })));
20863
+ const filterTemplates = await Promise.all(uniqueIds(filterRows.map((item) => item.id ?? item.flow_page_template_id)).map((id) => apiRequest(client, "GET", `/flow_page_template/${encodeURIComponent(id)}?skip_i18n=true`, { capability: "config.filter_template.export" })));
20864
+ const datasetIds = uniqueIds([...listTemplates.map((item) => item.data_set_id), ...filterTemplates.map((item) => item.data_set_id)]);
20865
+ const datasets = await Promise.all(datasetIds.map((id) => apiRequest(client, "GET", `/data_set/${encodeURIComponent(id)}`, { capability: "config.dataset.export" })));
20866
+ const appSummary = matrixAppSummary(matrixFlow, listTemplates, filterTemplates, datasets, workspaceHasFlow(workspaceResult, options.matrixFlowType));
19645
20867
  const consumerNode = findFlowNode2(consumerFlow, options.node);
19646
20868
  const consumerSummary = matrixConsumerSummary(consumerNode, options.matrixFlowType);
19647
20869
  const records = await hydrateMatrixRuleRecords(client, listedRecords);
@@ -19664,11 +20886,7 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19664
20886
  });
19665
20887
  let approvers = [];
19666
20888
  if (approverIds.size) {
19667
- const usersResult = await apiRequest(client, "GET", "/user", {
19668
- params: { ids: [...approverIds].join(","), field_filter: "id,name,status,is_del,organization_id" },
19669
- capability: "user.readback"
19670
- });
19671
- approvers = dataArray(usersResult).filter(isRecord10);
20889
+ approvers = await readMatrixApprovers(client, [...approverIds]);
19672
20890
  const activeIds = new Set(approvers.filter((user) => Number(user.status) === 0 && Number(user.is_del ?? 0) === 0).map((user) => Number(user.id)));
19673
20891
  [...approverIds].filter((id) => !activeIds.has(id)).forEach((id) => errors.push({ code: "matrix.rules.approver_inactive", rule_id: "matrix.rules.approver_inactive", domain: "approval-matrix", path: "$.rules", message: `\u5BA1\u6279\u4EBA ${id} \u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6709\u6548\u5728\u804C\u72B6\u6001\u3002`, suggestion: "\u91CD\u65B0\u7ED1\u5B9A\u6709\u6548 BPMAX \u7528\u6237\u3002" }));
19674
20892
  }
@@ -19697,6 +20915,326 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19697
20915
  });
19698
20916
  }
19699
20917
 
20918
+ // src/commands/organization.ts
20919
+ function isRecord11(value) {
20920
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20921
+ }
20922
+ function rows(value) {
20923
+ if (Array.isArray(value)) return value.filter(isRecord11);
20924
+ if (!isRecord11(value)) return [];
20925
+ if (Array.isArray(value.data)) return value.data.filter(isRecord11);
20926
+ return value.id ? [value] : [];
20927
+ }
20928
+ function positiveId(value, errorCode) {
20929
+ const id = Number(value);
20930
+ if (!Number.isSafeInteger(id) || id <= 0) {
20931
+ throw new Error(`${errorCode}: id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u3002`);
20932
+ }
20933
+ return id;
20934
+ }
20935
+ function safeDepartment(group) {
20936
+ return {
20937
+ id: group.id,
20938
+ name: group.name,
20939
+ parent_id: group.parent_id ?? null,
20940
+ path: group.path ?? null,
20941
+ model_id: group.model_id ?? null,
20942
+ partner_id: group.partner_id ?? null,
20943
+ is_deleted: group.is_del === void 0 ? null : Number(group.is_del) !== 0
20944
+ };
20945
+ }
20946
+ function departmentRows(value) {
20947
+ const result = [];
20948
+ const visit = (item) => {
20949
+ if (!isRecord11(item)) return;
20950
+ if (item.id !== void 0) result.push(safeDepartment(item));
20951
+ if (Array.isArray(item.children)) item.children.forEach(visit);
20952
+ };
20953
+ rows(value).forEach(visit);
20954
+ return result;
20955
+ }
20956
+ function relationDepartments(value) {
20957
+ if (!Array.isArray(value)) return [];
20958
+ return value.filter(isRecord11).map(safeDepartment);
20959
+ }
20960
+ function safeUser(user) {
20961
+ const status = user.status === void 0 ? null : Number(user.status);
20962
+ const isDeleted = user.is_del === void 0 ? null : Number(user.is_del) !== 0;
20963
+ return {
20964
+ id: user.id,
20965
+ name: user.name,
20966
+ employee_no: user.partner_id ?? null,
20967
+ organization_id: user.organization_id ?? null,
20968
+ position: user.title ?? null,
20969
+ leader_id: user.leader_id ?? null,
20970
+ status,
20971
+ is_deleted: isDeleted,
20972
+ active: status === 0 && isDeleted === false,
20973
+ departments: relationDepartments(user.group_list),
20974
+ managed_departments: relationDepartments(user.admin_list)
20975
+ };
20976
+ }
20977
+ async function fetchUsers(client, params, capability) {
20978
+ const result = await apiRequest(client, "GET", "/user", {
20979
+ params: {
20980
+ ...params,
20981
+ subRelations: "group",
20982
+ field_filter: "id,name,partner_id,title,leader_id,partner_leader_id,status,is_del,organization_id"
20983
+ },
20984
+ capability
20985
+ });
20986
+ return rows(result).map((raw) => ({ raw, safe: safeUser(raw) }));
20987
+ }
20988
+ async function readUser(client, userId) {
20989
+ const users = await fetchUsers(client, { ids: String(userId) }, "user.readback");
20990
+ const matched = users.find((user) => Number(user.safe.id) === userId);
20991
+ if (!matched) throw new Error(`organization.user.not_found: \u672A\u627E\u5230\u7528\u6237 ${userId}\u3002`);
20992
+ return matched;
20993
+ }
20994
+ async function readDepartments(client, ids) {
20995
+ if (ids.length === 0) return [];
20996
+ const result = await apiRequest(client, "GET", "/group/get_group_info", {
20997
+ params: { ids: ids.join(",") },
20998
+ capability: "user.readback"
20999
+ });
21000
+ return departmentRows(result);
21001
+ }
21002
+ function pathIds(departments) {
21003
+ const ids = /* @__PURE__ */ new Set();
21004
+ for (const department of departments) {
21005
+ const path16 = String(department.path ?? "");
21006
+ for (const part of path16.split(/[|,]/)) {
21007
+ const id = Number(part);
21008
+ if (Number.isSafeInteger(id) && id > 0) ids.add(id);
21009
+ }
21010
+ }
21011
+ return [...ids];
21012
+ }
21013
+ function mainDepartmentId(raw) {
21014
+ for (const key of ["main_department_id", "main_group_id", "main_department"]) {
21015
+ const value = raw[key];
21016
+ if (isRecord11(value)) {
21017
+ const id2 = Number(value.id);
21018
+ if (Number.isSafeInteger(id2) && id2 > 0) return id2;
21019
+ }
21020
+ const id = Number(value);
21021
+ if (Number.isSafeInteger(id) && id > 0) return id;
21022
+ }
21023
+ return null;
21024
+ }
21025
+ function branchId(raw) {
21026
+ for (const key of ["branch_id", "branch_group_id", "branch"]) {
21027
+ const value = raw[key];
21028
+ if (isRecord11(value)) {
21029
+ const id2 = Number(value.id);
21030
+ if (Number.isSafeInteger(id2) && id2 > 0) return id2;
21031
+ }
21032
+ const id = Number(value);
21033
+ if (Number.isSafeInteger(id) && id > 0) return id;
21034
+ }
21035
+ return null;
21036
+ }
21037
+ async function directSuperiorChain(client, userId, maxLevels) {
21038
+ const chain = [];
21039
+ const visited = /* @__PURE__ */ new Set([userId]);
21040
+ let current = await readUser(client, userId);
21041
+ let stopReason = "max_levels_reached";
21042
+ for (let level = 1; level <= maxLevels; level += 1) {
21043
+ const leaderId = Number(current.safe.leader_id);
21044
+ if (!Number.isSafeInteger(leaderId) || leaderId <= 0) {
21045
+ stopReason = "no_further_superior";
21046
+ break;
21047
+ }
21048
+ if (visited.has(leaderId)) {
21049
+ stopReason = "cycle_detected";
21050
+ break;
21051
+ }
21052
+ visited.add(leaderId);
21053
+ current = await readUser(client, leaderId);
21054
+ chain.push({ level, ...current.safe });
21055
+ }
21056
+ return { chain, stop_reason: stopReason };
21057
+ }
21058
+ async function context(profileName) {
21059
+ const config = await loadConfig();
21060
+ const profile = resolveProfile(config, profileName);
21061
+ return { profile, client: createApiClient(profile) };
21062
+ }
21063
+ function registerOrganizationCommands(program2) {
21064
+ const organization = program2.command("organization").description("Typed organization directory queries and authoritative readback");
21065
+ const department = organization.command("department").description("Department queries");
21066
+ department.command("search").description("Search departments by name").requiredOption("--query <query>", "Department name query").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21067
+ const query = options.query.trim();
21068
+ if (!query) throw new Error("organization.department.search.query_required: --query \u4E0D\u80FD\u4E3A\u7A7A\u3002");
21069
+ const { client } = await context(options.profile);
21070
+ const result = await apiRequest(client, "GET", "/group/tree", {
21071
+ params: { name: query, parent_id: 0, recursive: 1, with_model_form_template: 0 },
21072
+ capability: "user.search"
21073
+ });
21074
+ const departments = departmentRows(result);
21075
+ printResult(options.format, {
21076
+ ok: true,
21077
+ domain: "organization.department",
21078
+ action: "search",
21079
+ authority: "platform_group_directory",
21080
+ query,
21081
+ count: departments.length,
21082
+ departments
21083
+ });
21084
+ });
21085
+ department.command("readback").description("Read one department by exact BPMAX group id").requiredOption("--id <id>", "BPMAX group id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21086
+ const id = positiveId(options.id, "organization.department.readback.invalid_id");
21087
+ const { client } = await context(options.profile);
21088
+ const departments = await readDepartments(client, [id]);
21089
+ const matched = departments.find((item) => Number(item.id) === id);
21090
+ if (!matched) throw new Error(`organization.department.readback.not_found: \u672A\u627E\u5230\u90E8\u95E8 ${id}\u3002`);
21091
+ printResult(options.format, {
21092
+ ok: true,
21093
+ domain: "organization.department",
21094
+ action: "readback",
21095
+ authority: "platform_group_directory",
21096
+ department: matched
21097
+ });
21098
+ });
21099
+ department.command("memberships").description("Read authoritative department memberships for one user").requiredOption("--user-id <userId>", "BPMAX user id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21100
+ const userId = positiveId(options.userId, "organization.department.memberships.invalid_user_id");
21101
+ const { client } = await context(options.profile);
21102
+ const user = await readUser(client, userId);
21103
+ printResult(options.format, {
21104
+ ok: true,
21105
+ domain: "organization.department",
21106
+ action: "memberships",
21107
+ authority: "platform_user_group_relation",
21108
+ user: user.safe,
21109
+ departments: user.safe.departments,
21110
+ managed_departments: user.safe.managed_departments
21111
+ });
21112
+ });
21113
+ organization.command("main-department").description("Read the authoritative main department for one user when the platform exposes it").requiredOption("--user-id <userId>", "BPMAX user id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21114
+ const userId = positiveId(options.userId, "organization.main_department.invalid_user_id");
21115
+ const { client } = await context(options.profile);
21116
+ const user = await readUser(client, userId);
21117
+ const id = mainDepartmentId(user.raw);
21118
+ const matches = id ? await readDepartments(client, [id]) : [];
21119
+ printResult(options.format, {
21120
+ ok: true,
21121
+ domain: "organization.main_department",
21122
+ action: "readback",
21123
+ authoritative: Boolean(id),
21124
+ status: id ? "verified" : "platform_authority_required",
21125
+ user: user.safe,
21126
+ main_department: matches.find((item) => Number(item.id) === id) ?? null,
21127
+ candidates: user.safe.departments,
21128
+ ...!id ? {
21129
+ reason: "\u5F53\u524D\u5E73\u53F0\u7528\u6237\u6A21\u578B\u672A\u8FD4\u56DE\u4E3B\u90E8\u95E8\u6807\u8BC6\uFF1BCLI \u4E0D\u4F1A\u628A\u7B2C\u4E00\u4E2A\u90E8\u95E8\u731C\u4F5C\u4E3B\u90E8\u95E8\u3002",
21130
+ platform_change_required: true
21131
+ } : {}
21132
+ });
21133
+ });
21134
+ organization.command("branch").description("Read branch mapping candidates without guessing a business branch").requiredOption("--user-id <userId>", "BPMAX user id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21135
+ const userId = positiveId(options.userId, "organization.branch.invalid_user_id");
21136
+ const { client } = await context(options.profile);
21137
+ const user = await readUser(client, userId);
21138
+ const departments = user.safe.departments;
21139
+ const id = branchId(user.raw);
21140
+ const matches = id ? await readDepartments(client, [id]) : [];
21141
+ const ancestors = id ? [] : await readDepartments(client, pathIds(departments));
21142
+ printResult(options.format, {
21143
+ ok: true,
21144
+ domain: "organization.branch",
21145
+ action: "readback",
21146
+ authoritative: Boolean(id),
21147
+ status: id ? "verified" : "platform_authority_required",
21148
+ user: user.safe,
21149
+ branch: matches.find((item) => Number(item.id) === id) ?? null,
21150
+ department_ancestors: ancestors,
21151
+ ...!id ? {
21152
+ reason: "\u5F53\u524D\u5E73\u53F0\u6CA1\u6709\u7EDF\u4E00\u7684\u5206\u90E8\u7C7B\u578B\u6216 branch_id\uFF1BCLI \u53EA\u8FD4\u56DE\u90E8\u95E8\u7956\u5148\u5019\u9009\uFF0C\u4E0D\u6309\u5C42\u7EA7\u6216\u540D\u79F0\u731C\u6D4B\u5206\u90E8\u3002",
21153
+ platform_change_required: true
21154
+ } : {}
21155
+ });
21156
+ });
21157
+ organization.command("position").description("Read the authoritative position/title field for one user").requiredOption("--user-id <userId>", "BPMAX user id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21158
+ const userId = positiveId(options.userId, "organization.position.invalid_user_id");
21159
+ const { client } = await context(options.profile);
21160
+ const user = await readUser(client, userId);
21161
+ printResult(options.format, {
21162
+ ok: true,
21163
+ domain: "organization.position",
21164
+ action: "readback",
21165
+ authority: "platform_user.title",
21166
+ user_id: userId,
21167
+ position: user.safe.position
21168
+ });
21169
+ });
21170
+ organization.command("direct-superior").description("Read the exact direct superior for one user").requiredOption("--user-id <userId>", "BPMAX user id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21171
+ const userId = positiveId(options.userId, "organization.direct_superior.invalid_user_id");
21172
+ const { client } = await context(options.profile);
21173
+ const user = await readUser(client, userId);
21174
+ const leaderId = Number(user.safe.leader_id);
21175
+ const superior = Number.isSafeInteger(leaderId) && leaderId > 0 ? (await readUser(client, leaderId)).safe : null;
21176
+ printResult(options.format, {
21177
+ ok: true,
21178
+ domain: "organization.direct_superior",
21179
+ action: "readback",
21180
+ authority: "platform_user.leader_id",
21181
+ user: user.safe,
21182
+ superior
21183
+ });
21184
+ });
21185
+ organization.command("superior-chain").description("Read a cycle-safe continuous direct-superior chain").requiredOption("--user-id <userId>", "BPMAX user id").option("--levels <levels>", "Maximum superior levels", "20").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21186
+ const userId = positiveId(options.userId, "organization.superior_chain.invalid_user_id");
21187
+ const levels = positiveId(options.levels, "organization.superior_chain.invalid_levels");
21188
+ if (levels > 100) throw new Error("organization.superior_chain.invalid_levels: --levels \u4E0D\u80FD\u8D85\u8FC7 100\u3002");
21189
+ const { client } = await context(options.profile);
21190
+ const result = await directSuperiorChain(client, userId, levels);
21191
+ printResult(options.format, {
21192
+ ok: true,
21193
+ domain: "organization.superior_chain",
21194
+ action: "readback",
21195
+ authority: "platform_user.leader_id",
21196
+ user_id: userId,
21197
+ requested_levels: levels,
21198
+ count: result.chain.length,
21199
+ superiors: result.chain,
21200
+ stop_reason: result.stop_reason
21201
+ });
21202
+ });
21203
+ organization.command("readback").description("Read an organization mapping readiness snapshot for one user").requiredOption("--user-id <userId>", "BPMAX user id").option("--levels <levels>", "Maximum direct-superior levels", "20").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
21204
+ const userId = positiveId(options.userId, "organization.readback.invalid_user_id");
21205
+ const levels = positiveId(options.levels, "organization.readback.invalid_levels");
21206
+ if (levels > 100) throw new Error("organization.readback.invalid_levels: --levels \u4E0D\u80FD\u8D85\u8FC7 100\u3002");
21207
+ const { client } = await context(options.profile);
21208
+ const user = await readUser(client, userId);
21209
+ const chain = await directSuperiorChain(client, userId, levels);
21210
+ const mainId = mainDepartmentId(user.raw);
21211
+ const resolvedBranchId = branchId(user.raw);
21212
+ const mainDepartments = mainId ? await readDepartments(client, [mainId]) : [];
21213
+ const branches = resolvedBranchId ? await readDepartments(client, [resolvedBranchId]) : [];
21214
+ printResult(options.format, {
21215
+ ok: true,
21216
+ domain: "organization",
21217
+ action: "readback",
21218
+ user: user.safe,
21219
+ departments: { authoritative: true, value: user.safe.departments },
21220
+ main_department: {
21221
+ authoritative: Boolean(mainId),
21222
+ value: mainDepartments.find((item) => Number(item.id) === mainId) ?? null,
21223
+ status: mainId ? "verified" : "platform_authority_required"
21224
+ },
21225
+ branch: {
21226
+ authoritative: Boolean(resolvedBranchId),
21227
+ value: branches.find((item) => Number(item.id) === resolvedBranchId) ?? null,
21228
+ status: resolvedBranchId ? "verified" : "platform_authority_required"
21229
+ },
21230
+ position: { authoritative: true, value: user.safe.position },
21231
+ direct_superior: { authoritative: true, value: chain.chain[0] ?? null },
21232
+ superior_chain: { authoritative: true, value: chain.chain, stop_reason: chain.stop_reason },
21233
+ platform_change_required: !mainId || !resolvedBranchId
21234
+ });
21235
+ });
21236
+ }
21237
+
19700
21238
  // src/commands/plugin.ts
19701
21239
  function defaultAgent2(options) {
19702
21240
  return options.agent || process.env.BPMAX_CLI_AGENT || "codex";
@@ -20005,15 +21543,15 @@ async function promptProjectCreateForm(input) {
20005
21543
  }
20006
21544
 
20007
21545
  // src/core/project-form.ts
20008
- function isRecord11(value) {
21546
+ function isRecord12(value) {
20009
21547
  return typeof value === "object" && value !== null && !Array.isArray(value);
20010
21548
  }
20011
21549
  function clone(value) {
20012
21550
  return JSON.parse(JSON.stringify(value));
20013
21551
  }
20014
21552
  function getFlowFormTemplateId(flowDetail) {
20015
- const data = isRecord11(flowDetail?.data) ? flowDetail.data : void 0;
20016
- const meta = isRecord11(data?.meta) ? data.meta : void 0;
21553
+ const data = isRecord12(flowDetail?.data) ? flowDetail.data : void 0;
21554
+ const meta = isRecord12(data?.meta) ? data.meta : void 0;
20017
21555
  const templateId = meta?.form_template;
20018
21556
  if (typeof templateId === "number" && Number.isFinite(templateId)) {
20019
21557
  return templateId;
@@ -20038,7 +21576,7 @@ function hasAutoInitLambda(value, seen = /* @__PURE__ */ new WeakSet()) {
20038
21576
  if (Array.isArray(value)) {
20039
21577
  return value.some((item) => hasAutoInitLambda(item, seen));
20040
21578
  }
20041
- if (!isRecord11(value)) {
21579
+ if (!isRecord12(value)) {
20042
21580
  return false;
20043
21581
  }
20044
21582
  if (seen.has(value)) {
@@ -20053,14 +21591,14 @@ function hasAutoInitLambda(value, seen = /* @__PURE__ */ new WeakSet()) {
20053
21591
  function setControlValue(control, value) {
20054
21592
  const next = clone(control);
20055
21593
  next.value = {
20056
- ...isRecord11(next.value) ? next.value : {},
21594
+ ...isRecord12(next.value) ? next.value : {},
20057
21595
  type: next.value?.type ?? next.field_type,
20058
21596
  value
20059
21597
  };
20060
21598
  return next;
20061
21599
  }
20062
21600
  function applyRowValues(rowTemplate, rowValue) {
20063
- const source = isRecord11(rowValue) ? rowValue : {};
21601
+ const source = isRecord12(rowValue) ? rowValue : {};
20064
21602
  return rowTemplate.map((control) => {
20065
21603
  if (control.key && Object.prototype.hasOwnProperty.call(source, control.key)) {
20066
21604
  return setControlValue(control, source[control.key]);
@@ -20079,8 +21617,8 @@ function buildProjectFormValue(template, form) {
20079
21617
  if (control.field_type === "sub_form") {
20080
21618
  const subFormRows = control.value?.value;
20081
21619
  const rowTemplate = Array.isArray(subFormRows) && Array.isArray(subFormRows[0]) ? subFormRows[0] : [];
20082
- const rows = Array.isArray(inputValue) ? inputValue.map((row) => applyRowValues(rowTemplate, row)) : [];
20083
- return setControlValue(control, rows);
21620
+ const rows2 = Array.isArray(inputValue) ? inputValue.map((row) => applyRowValues(rowTemplate, row)) : [];
21621
+ return setControlValue(control, rows2);
20084
21622
  }
20085
21623
  return setControlValue(control, inputValue);
20086
21624
  });
@@ -20099,7 +21637,7 @@ async function buildProjectFormPayload(client, flowDetail, form, knownTemplate)
20099
21637
  }
20100
21638
 
20101
21639
  // src/commands/project.ts
20102
- function projectCreateErrorDiagnostic(error, context) {
21640
+ function projectCreateErrorDiagnostic(error, context2) {
20103
21641
  const baseMessage = error instanceof Error ? error.message : String(error || "");
20104
21642
  const response = typeof error === "object" && error !== null && "response" in error ? error.response : void 0;
20105
21643
  const status = response?.status;
@@ -20108,12 +21646,12 @@ function projectCreateErrorDiagnostic(error, context) {
20108
21646
  const summary = bodyText.length > 1e3 ? `${bodyText.slice(0, 1e3)}...` : bodyText;
20109
21647
  return new Error([
20110
21648
  `Project create failed${status ? ` with status ${String(status)}` : ""}: ${baseMessage}`,
20111
- `local_form_validation=${context.localFormValidation}`,
20112
- `direct_body=${context.usedBody ? "true" : "false"}`,
20113
- `no_interactive=${context.noInteractive ? "true" : "false"}`,
20114
- `handoff_available=${context.handoffAvailable ? "true" : "false"}`,
21649
+ `local_form_validation=${context2.localFormValidation}`,
21650
+ `direct_body=${context2.usedBody ? "true" : "false"}`,
21651
+ `no_interactive=${context2.noInteractive ? "true" : "false"}`,
21652
+ `handoff_available=${context2.handoffAvailable ? "true" : "false"}`,
20115
21653
  summary ? `server_error_summary=${summary}` : "",
20116
- context.handoffAvailable ? "next_action=Use the generated form handoff path unless the template is proven safe for direct create." : "next_action=Check field keys/types and server error body; do not bypass with raw API."
21654
+ context2.handoffAvailable ? "next_action=Use the generated form handoff path unless the template is proven safe for direct create." : "next_action=Check field keys/types and server error body; do not bypass with raw API."
20117
21655
  ].filter(Boolean).join("\n"));
20118
21656
  }
20119
21657
  async function parseProjectJson(input, label = "--json") {
@@ -20618,8 +22156,8 @@ function fieldsForValidation(flowDetail, projectFormTemplate) {
20618
22156
  }));
20619
22157
  }
20620
22158
  function metaUsesTemplateProjectName(flowDetail) {
20621
- const data = isRecord12(flowDetail?.data) ? flowDetail.data : void 0;
20622
- const meta = isRecord12(data?.meta) ? data.meta : void 0;
22159
+ const data = isRecord13(flowDetail?.data) ? flowDetail.data : void 0;
22160
+ const meta = isRecord13(data?.meta) ? data.meta : void 0;
20623
22161
  const hideFields = Array.isArray(meta?.hide_fields) ? meta.hide_fields.map(String) : [];
20624
22162
  return meta?.use_template_project_name === true || hideFields.includes("project.name");
20625
22163
  }
@@ -20728,7 +22266,7 @@ function collectPrefillContextForFields(fields, form, result, options = {}) {
20728
22266
  result.filled_fields.push(contextField(field, "prefilled", fieldOptions));
20729
22267
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
20730
22268
  value.forEach((row, index) => {
20731
- if (isRecord12(row)) {
22269
+ if (isRecord13(row)) {
20732
22270
  collectPrefillContextForFields(field.children ?? [], row, result, {
20733
22271
  prefix: `${field.key}[${index}]`,
20734
22272
  rootKey: field.key,
@@ -20755,7 +22293,7 @@ function buildPrefillContext(fields, form) {
20755
22293
  }
20756
22294
  };
20757
22295
  }
20758
- function isRecord12(value) {
22296
+ function isRecord13(value) {
20759
22297
  return typeof value === "object" && value !== null && !Array.isArray(value);
20760
22298
  }
20761
22299
  function isEndedStep(step) {
@@ -20778,7 +22316,7 @@ function stepIdOf(step) {
20778
22316
  function pickStepFormPayload(step) {
20779
22317
  const formList = Array.isArray(step.formList) ? step.formList : [];
20780
22318
  const forms = Array.isArray(step.forms) ? step.forms : [];
20781
- const metaForm = isRecord12(step.metaForm) ? step.metaForm : void 0;
22319
+ const metaForm = isRecord13(step.metaForm) ? step.metaForm : void 0;
20782
22320
  return {
20783
22321
  step_id: step.id,
20784
22322
  flow_step_id: step.flow_step_id,
@@ -20795,7 +22333,7 @@ function pickStepFormPayload(step) {
20795
22333
  }
20796
22334
  async function buildApprovalContext(client, projectId, options) {
20797
22335
  const projectDetail = await apiRequest(client, "GET", `/project/${projectId}`);
20798
- const steps = Array.isArray(projectDetail.steps) ? projectDetail.steps.filter(isRecord12) : [];
22336
+ const steps = Array.isArray(projectDetail.steps) ? projectDetail.steps.filter(isRecord13) : [];
20799
22337
  const targetStepIds = /* @__PURE__ */ new Set();
20800
22338
  for (const step of steps) {
20801
22339
  const id = stepIdOf(step);
@@ -20821,7 +22359,7 @@ async function buildApprovalContext(client, projectId, options) {
20821
22359
  }
20822
22360
  return {
20823
22361
  project: projectDetail,
20824
- project_form: isRecord12(projectDetail.metaForm) ? projectDetail.metaForm : null,
22362
+ project_form: isRecord13(projectDetail.metaForm) ? projectDetail.metaForm : null,
20825
22363
  inspected_step_count: stepForms.length,
20826
22364
  step_forms: stepForms,
20827
22365
  failed_steps: failedSteps
@@ -20915,10 +22453,10 @@ function registerProjectCommands(program2) {
20915
22453
  const config = await loadConfig();
20916
22454
  const profile = resolveProfile(config, options.profile);
20917
22455
  const client = createApiClient(profile);
20918
- const context = await buildApprovalContext(client, projectId, { stepId: options.stepId });
22456
+ const context2 = await buildApprovalContext(client, projectId, { stepId: options.stepId });
20919
22457
  printResult(options.format, {
20920
- ...context,
20921
- project: attachProjectDetailUrl(profile, context.project)
22458
+ ...context2,
22459
+ project: attachProjectDetailUrl(profile, context2.project)
20922
22460
  });
20923
22461
  });
20924
22462
  const handoff = project.command("handoff").description("Inspect BPMAX project create-page handoff state");
@@ -21184,7 +22722,7 @@ function getRecipesDir(options) {
21184
22722
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
21185
22723
  return path12.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
21186
22724
  }
21187
- function isRecord13(value) {
22725
+ function isRecord14(value) {
21188
22726
  return typeof value === "object" && value !== null && !Array.isArray(value);
21189
22727
  }
21190
22728
  function asString(value, fieldName) {
@@ -21194,7 +22732,7 @@ function asString(value, fieldName) {
21194
22732
  return value;
21195
22733
  }
21196
22734
  function parseRecipeDefinition(input) {
21197
- if (!isRecord13(input)) {
22735
+ if (!isRecord14(input)) {
21198
22736
  throw new Error("recipe.json must be a JSON object.");
21199
22737
  }
21200
22738
  if (input.version !== 1) {
@@ -21202,7 +22740,7 @@ function parseRecipeDefinition(input) {
21202
22740
  }
21203
22741
  const name = asString(input.name, "recipe.name");
21204
22742
  assertSafeName("Recipe name", name);
21205
- if (!isRecord13(input.command)) {
22743
+ if (!isRecord14(input.command)) {
21206
22744
  throw new Error("recipe.command must be an object.");
21207
22745
  }
21208
22746
  const argv = input.command.argv;
@@ -21210,7 +22748,7 @@ function parseRecipeDefinition(input) {
21210
22748
  throw new Error("recipe.command.argv must be a non-empty string array.");
21211
22749
  }
21212
22750
  const variables = Array.isArray(input.variables) ? input.variables.map((item, index) => {
21213
- if (!isRecord13(item)) {
22751
+ if (!isRecord14(item)) {
21214
22752
  throw new Error(`recipe.variables[${index}] must be an object.`);
21215
22753
  }
21216
22754
  const variableName = asString(item.name, `recipe.variables[${index}].name`);
@@ -21286,7 +22824,7 @@ function parseVarsJson(input) {
21286
22824
  return {};
21287
22825
  }
21288
22826
  const parsed = JSON.parse(input);
21289
- if (!isRecord13(parsed)) {
22827
+ if (!isRecord14(parsed)) {
21290
22828
  throw new Error("--vars must be a JSON object.");
21291
22829
  }
21292
22830
  const variables = {};
@@ -21449,8 +22987,8 @@ function registerRecipeCommands(program2, deps = {}) {
21449
22987
  const configData = await load();
21450
22988
  const target = resolveTargetProfile(configData, options.profile);
21451
22989
  const workspace = options.workspace || target.workspace;
21452
- const rows = await listRecipes(getRecipesDir({ profileName: target.name, workspace, getProfileDir }));
21453
- printResult(options.format, rows);
22990
+ const rows2 = await listRecipes(getRecipesDir({ profileName: target.name, workspace, getProfileDir }));
22991
+ printResult(options.format, rows2);
21454
22992
  });
21455
22993
  recipe.command("show <name>").description("Show a recipe definition").option("--profile <profile>", "Profile name").option("--workspace <workspace>", "Workspace override").option("--format <format>", "Output format", "pretty").action(async (name, options) => {
21456
22994
  const configData = await load();
@@ -21609,6 +23147,22 @@ var schemaEntries = [
21609
23147
  { name: "config.role.create", description: "Create roles, custom points, and role members through typed operation plans.", method: "POST", path: "/api/role + /api/point + /api/user_role" },
21610
23148
  { name: "config.role.delete", description: "Delete roles, custom points, or role members through typed adapters.", method: "DELETE", path: "/api/role/:id + /api/point/:id + /api/user_role/:id" },
21611
23149
  { name: "config.role.submit", description: "Submit role operation plan through a verified typed adapter.", method: "POST/PUT/DELETE", path: "/api/role + /api/point + /api/user_role" },
23150
+ { name: "config.team.export", description: "Export one BPMAX team with hierarchy, model, permission, and administrator readback.", method: "GET", path: "/api/group/:id" },
23151
+ { name: "config.team.create", description: "Create one BPMAX team through the typed group adapter.", method: "POST", path: "/api/group" },
23152
+ { name: "config.team.delete", description: "Delete one BPMAX team through the typed group adapter.", method: "DELETE", path: "/api/group/:id" },
23153
+ { name: "config.team.submit", description: "Submit one BPMAX team edit through the typed group adapter.", method: "PUT", path: "/api/group/:id" },
23154
+ { name: "config.user.export", description: "Export one BPMAX user with privacy-safe identity and relation readback.", method: "GET", path: "/api/user/:id?only_user_role=1" },
23155
+ { name: "config.user.create", description: "Create one BPMAX organization user through the typed adapter.", method: "POST", path: "/api/user" },
23156
+ { name: "config.user.delete", description: "Delete one BPMAX organization user through the typed adapter.", method: "DELETE", path: "/api/user/:id" },
23157
+ { name: "config.user.submit", description: "Submit safe BPMAX user and organization relation edits.", method: "PUT", path: "/api/user/:id" },
23158
+ { name: "config.user_model.export", description: "Export one BPMAX user model by id or UUID.", method: "GET", path: "/api/user_model/:id + /api/user_model/get_by_uuid" },
23159
+ { name: "config.user_model.create", description: "Create one BPMAX user model through the typed adapter.", method: "POST", path: "/api/user_model" },
23160
+ { name: "config.user_model.delete", description: "Delete one BPMAX user model through the typed adapter.", method: "DELETE", path: "/api/user_model/:id" },
23161
+ { name: "config.user_model.submit", description: "Submit one BPMAX user model edit through the typed adapter.", method: "PUT", path: "/api/user_model/:id" },
23162
+ { name: "config.group_model.export", description: "Export one BPMAX group model by id or UUID.", method: "GET", path: "/api/group_model/:id + /api/group_model/get_by_uuid" },
23163
+ { name: "config.group_model.create", description: "Create one BPMAX group model through the typed adapter.", method: "POST", path: "/api/group_model" },
23164
+ { name: "config.group_model.delete", description: "Delete one BPMAX group model through the typed adapter.", method: "DELETE", path: "/api/group_model/:id" },
23165
+ { name: "config.group_model.submit", description: "Submit one BPMAX group model edit through the typed adapter.", method: "PUT", path: "/api/group_model/:id" },
21612
23166
  { name: "config.nav_config.export", description: "Export all workspace navigation config records.", method: "GET", path: "/api/configuration?q_type=:type&is_default_action=1" },
21613
23167
  { name: "config.nav_config.create", description: "Create workspace navigation config records through a typed operation plan.", method: "POST", path: "/api/configuration?is_default_action=1" },
21614
23168
  { name: "config.nav_config.delete", description: "Delete workspace navigation config records through a typed operation plan.", method: "DELETE", path: "/api/configuration/:id?is_default_action=1" },
@@ -21851,7 +23405,7 @@ var PROMPT_REQUIRED_TERMS = [
21851
23405
  "\u8FDB\u5EA6 CSV"
21852
23406
  ];
21853
23407
  var BPMAX_SKILL_PATTERN = /bpmax-[a-z0-9-]+|form-control-library|bpmax-memory-protocol/;
21854
- var FLOW_LOCK_PATTERN = /\bflow:([A-Za-z0-9_-]+)/g;
23408
+ var FLOW_LOCK_PATTERN = /(?<![A-Za-z0-9_-])flow:([A-Za-z0-9_-]+)/g;
21855
23409
  var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/gi;
21856
23410
  var CONFIG_TASK_RULES = [
21857
23411
  {
@@ -22101,9 +23655,9 @@ function hasForbiddenListDeleteStepGuard(value) {
22101
23655
  }
22102
23656
  function validateTaskbookNavigationAndListGates(text5, issues) {
22103
23657
  const strategy = validateNavigationStrategy(text5, issues, "navigation_strategy", "\u4EFB\u52A1\u4E66");
22104
- const rows = extractTaskRows(text5);
22105
- const navRows = rows.filter((row) => /bpmax-nav-config-editor/.test(row.required_skills || ""));
22106
- const listRows = rows.filter((row) => /bpmax-list-template-editor/.test(row.required_skills || ""));
23658
+ const rows2 = extractTaskRows(text5);
23659
+ const navRows = rows2.filter((row) => /bpmax-nav-config-editor/.test(row.required_skills || ""));
23660
+ const listRows = rows2.filter((row) => /bpmax-list-template-editor/.test(row.required_skills || ""));
22107
23661
  if (strategy === "nav-config:included" && navRows.length === 0) {
22108
23662
  addTaskbookIssue(
22109
23663
  issues,
@@ -22271,8 +23825,8 @@ function validateConfigRuleForTaskRow(row, rule, issues) {
22271
23825
  }
22272
23826
  }
22273
23827
  function validateTaskbookConfigSkillGates(text5, issues) {
22274
- const rows = extractTaskRows(text5);
22275
- for (const row of rows) {
23828
+ const rows2 = extractTaskRows(text5);
23829
+ for (const row of rows2) {
22276
23830
  for (const rule of CONFIG_TASK_RULES) {
22277
23831
  validateConfigRuleForTaskRow(row, rule, issues);
22278
23832
  }
@@ -22622,7 +24176,7 @@ function csvEscape(value) {
22622
24176
  }
22623
24177
  function extractTaskRows(text5) {
22624
24178
  const lines = text5.split(/\r?\n/);
22625
- const rows = [];
24179
+ const rows2 = [];
22626
24180
  for (let index = 0; index < lines.length; index += 1) {
22627
24181
  const line = lines[index];
22628
24182
  if (!line.trim().startsWith("|")) {
@@ -22647,17 +24201,17 @@ function extractTaskRows(text5) {
22647
24201
  row[header] = cells[cellIndex] || "";
22648
24202
  });
22649
24203
  if (row.task_id) {
22650
- rows.push(row);
24204
+ rows2.push(row);
22651
24205
  }
22652
24206
  cursor += 1;
22653
24207
  }
22654
24208
  }
22655
- return rows;
24209
+ return rows2;
22656
24210
  }
22657
24211
  async function initTaskbookProgress(source, outFile) {
22658
24212
  const text5 = await readTaskbookText(source);
22659
- const rows = extractTaskRows(text5);
22660
- if (rows.length === 0) {
24213
+ const rows2 = extractTaskRows(text5);
24214
+ if (rows2.length === 0) {
22661
24215
  throw new TaskbookError("Taskbook progress init could not find an AI task table with task_id/status/subagent_mode columns.");
22662
24216
  }
22663
24217
  const fields = [
@@ -22678,11 +24232,11 @@ async function initTaskbookProgress(source, outFile) {
22678
24232
  ];
22679
24233
  const csv = [
22680
24234
  fields.join(","),
22681
- ...rows.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
24235
+ ...rows2.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
22682
24236
  ].join("\n") + "\n";
22683
24237
  await mkdir12(path13.dirname(outFile), { recursive: true });
22684
24238
  await writeFile12(outFile, csv, "utf8");
22685
- return { source, out: outFile, task_count: rows.length };
24239
+ return { source, out: outFile, task_count: rows2.length };
22686
24240
  }
22687
24241
 
22688
24242
  // src/commands/taskbook.ts
@@ -23232,17 +24786,17 @@ function registerUrlCommands(program2, deps = {}) {
23232
24786
  }
23233
24787
 
23234
24788
  // src/commands/user.ts
23235
- function isRecord14(value) {
24789
+ function isRecord15(value) {
23236
24790
  return typeof value === "object" && value !== null && !Array.isArray(value);
23237
24791
  }
23238
24792
  function userRows(value) {
23239
- if (Array.isArray(value)) return value.filter(isRecord14);
23240
- if (!isRecord14(value)) return [];
23241
- if (Array.isArray(value.data)) return value.data.filter(isRecord14);
24793
+ if (Array.isArray(value)) return value.filter(isRecord15);
24794
+ if (!isRecord15(value)) return [];
24795
+ if (Array.isArray(value.data)) return value.data.filter(isRecord15);
23242
24796
  return value.id ? [value] : [];
23243
24797
  }
23244
- function safeUser(user) {
23245
- const roles = Array.isArray(user.role) ? user.role.filter(isRecord14).map((role) => ({
24798
+ function safeUser2(user) {
24799
+ const roles = Array.isArray(user.role) ? user.role.filter(isRecord15).map((role) => ({
23246
24800
  id: role.id,
23247
24801
  key: role.key,
23248
24802
  name: role.name
@@ -23252,7 +24806,7 @@ function safeUser(user) {
23252
24806
  return {
23253
24807
  id: user.id,
23254
24808
  name: user.name,
23255
- employee_no: user.partner_id ?? user.workcode ?? null,
24809
+ employee_no: user.partner_id ?? null,
23256
24810
  organization_id: user.organization_id,
23257
24811
  status,
23258
24812
  is_deleted: isDeleted,
@@ -23260,16 +24814,16 @@ function safeUser(user) {
23260
24814
  roles
23261
24815
  };
23262
24816
  }
23263
- async function fetchUsers(client, params, capability = "user.search") {
24817
+ async function fetchUsers2(client, params, capability = "user.search") {
23264
24818
  const result = await apiRequest(client, "GET", "/user", {
23265
24819
  params: {
23266
24820
  ...params,
23267
24821
  subRelations: "role",
23268
- field_filter: "id,name,partner_id,workcode,status,is_del,organization_id"
24822
+ field_filter: "id,name,partner_id,status,is_del,organization_id"
23269
24823
  },
23270
24824
  capability
23271
24825
  });
23272
- return userRows(result).map(safeUser);
24826
+ return userRows(result).map(safeUser2);
23273
24827
  }
23274
24828
  function registerUserCommands(program2) {
23275
24829
  const user = program2.command("user").description("User commands");
@@ -23288,7 +24842,7 @@ function registerUserCommands(program2) {
23288
24842
  if (!query) throw new Error("user.search.query_required: --query \u4E0D\u80FD\u4E3A\u7A7A\u3002");
23289
24843
  const config = await loadConfig();
23290
24844
  const profile = resolveProfile(config, options.profile);
23291
- let users = await fetchUsers(createApiClient(profile), { querystring: query });
24845
+ let users = await fetchUsers2(createApiClient(profile), { querystring: query });
23292
24846
  if (options.activeOnly) users = users.filter((user2) => user2.active === true);
23293
24847
  printResult(options.format, {
23294
24848
  ok: true,
@@ -23306,7 +24860,7 @@ function registerUserCommands(program2) {
23306
24860
  }
23307
24861
  const config = await loadConfig();
23308
24862
  const profile = resolveProfile(config, options.profile);
23309
- const users = await fetchUsers(createApiClient(profile), { ids: String(id) }, "user.readback");
24863
+ const users = await fetchUsers2(createApiClient(profile), { ids: String(id) }, "user.readback");
23310
24864
  const matched = users.find((user2) => Number(user2.id) === id);
23311
24865
  if (!matched) throw new Error(`user.readback.not_found: \u672A\u627E\u5230\u7528\u6237 ${id}\u3002`);
23312
24866
  printResult(options.format, {
@@ -23325,7 +24879,7 @@ function registerUserCommands(program2) {
23325
24879
  const config = await loadConfig();
23326
24880
  const profile = resolveProfile(config, options.profile);
23327
24881
  const query = employeeNo || name || "";
23328
- const users = await fetchUsers(createApiClient(profile), { querystring: query });
24882
+ const users = await fetchUsers2(createApiClient(profile), { querystring: query });
23329
24883
  const exact = users.filter((user2) => (!name || String(user2.name ?? "") === name) && (!employeeNo || String(user2.employee_no ?? "") === employeeNo));
23330
24884
  if (exact.length === 0) {
23331
24885
  throw new Error("user.resolve.not_found: \u672A\u627E\u5230\u7B26\u5408\u7CBE\u786E\u59D3\u540D/\u5DE5\u53F7\u6761\u4EF6\u7684 BPMAX \u7528\u6237\u3002");
@@ -23592,6 +25146,7 @@ registerFlowCommands(program);
23592
25146
  registerIssueCommands(program);
23593
25147
  registerMemoryCommands(program);
23594
25148
  registerMatrixCommands(program);
25149
+ registerOrganizationCommands(program);
23595
25150
  registerPluginCommands(program);
23596
25151
  registerProjectCommands(program);
23597
25152
  registerStepCommands(program);