bpmax-cli 0.2.1-beta.1 → 0.2.1-beta.11

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.
Files changed (23) hide show
  1. package/README.md +28 -1
  2. package/dist/bin.js +1547 -255
  3. package/dist/bin.js.map +1 -1
  4. package/package.json +1 -1
  5. package/skills/bpmax-ai-taskbook/SKILL.md +5 -1
  6. package/skills/bpmax-approval-matrix/SKILL.md +4 -1
  7. package/skills/bpmax-blueprint-doc-workflow/SKILL.md +87 -0
  8. package/skills/bpmax-blueprint-doc-workflow/agents/openai.yaml +4 -0
  9. package/skills/bpmax-blueprint-doc-workflow/references/blueprint-structure.md +60 -0
  10. package/skills/bpmax-blueprint-doc-workflow/references/per-flow-required-structure.md +98 -0
  11. package/skills/bpmax-blueprint-doc-workflow/references/sample-forbidden-term.xml +12 -0
  12. package/skills/bpmax-blueprint-doc-workflow/references/sample-mermaid-codeblock.xml +12 -0
  13. package/skills/bpmax-blueprint-doc-workflow/references/sample-missing-boundary.xml +10 -0
  14. package/skills/bpmax-blueprint-doc-workflow/references/sample-missing-whiteboard.xml +10 -0
  15. package/skills/bpmax-blueprint-doc-workflow/references/sample-pass.xml +55 -0
  16. package/skills/bpmax-blueprint-doc-workflow/scripts/lint_blueprint_doc.py +257 -0
  17. package/skills/bpmax-dataset-field-template-editor/SKILL.md +6 -3
  18. package/skills/bpmax-dataset-template-editor/SKILL.md +12 -2
  19. package/skills/bpmax-e2e-flow-config-orchestrator/SKILL.md +25 -1
  20. package/skills/bpmax-e2e-flow-test-operator/SKILL.md +13 -0
  21. package/skills/bpmax-e2e-flow-test-operator/references/ai-test-suite.md +25 -3
  22. package/skills/bpmax-flow-template-editor/SKILL.md +81 -5
  23. package/skills/bpmax-form-template-editor/SKILL.md +47 -0
package/dist/bin.js CHANGED
@@ -138,8 +138,8 @@ function maskApiKey(apiKey) {
138
138
  if (!apiKey) {
139
139
  return "(unset)";
140
140
  }
141
- if (apiKey.length <= 10) {
142
- return apiKey;
141
+ if (apiKey.length <= 16) {
142
+ return "[REDACTED]";
143
143
  }
144
144
  return `${apiKey.slice(0, 8)}****${apiKey.slice(-4)}`;
145
145
  }
@@ -231,8 +231,8 @@ function throwCliGovernanceUnsupportedIfNeeded(error, fallbackPath) {
231
231
  }
232
232
  throw error;
233
233
  }
234
- function normalizePath(path14) {
235
- let normalized = path14.split("?")[0] || "/";
234
+ function normalizePath(path15) {
235
+ let normalized = path15.split("?")[0] || "/";
236
236
  if (!normalized.startsWith("/")) {
237
237
  normalized = `/${normalized}`;
238
238
  }
@@ -242,17 +242,17 @@ function normalizePath(path14) {
242
242
  }
243
243
  return normalized.replace(/\/+$/g, "") || "/api";
244
244
  }
245
- function getNumber(value, path14) {
246
- const result = getValue(value, path14);
245
+ function getNumber(value, path15) {
246
+ const result = getValue(value, path15);
247
247
  return typeof result === "number" ? result : void 0;
248
248
  }
249
- function getString(value, path14) {
250
- const result = getValue(value, path14);
249
+ function getString(value, path15) {
250
+ const result = getValue(value, path15);
251
251
  return typeof result === "string" ? result : void 0;
252
252
  }
253
- function getValue(value, path14) {
253
+ function getValue(value, path15) {
254
254
  let current = value;
255
- for (const key of path14) {
255
+ for (const key of path15) {
256
256
  if (!current || typeof current !== "object" || !(key in current)) {
257
257
  return void 0;
258
258
  }
@@ -262,10 +262,10 @@ function getValue(value, path14) {
262
262
  }
263
263
 
264
264
  // src/core/capabilities.ts
265
- function capabilityForRequest(method, path14) {
265
+ function capabilityForRequest(method, path15) {
266
266
  const normalizedMethod = method.toUpperCase();
267
- const normalizedPath = normalizePath2(path14);
268
- const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path14);
267
+ const normalizedPath = normalizePath2(path15);
268
+ const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path15);
269
269
  if (normalizedPath === "/cli/capabilities") {
270
270
  return void 0;
271
271
  }
@@ -423,8 +423,8 @@ async function updateProfileCapabilities(profileName, cache) {
423
423
  };
424
424
  await saveConfig(config);
425
425
  }
426
- function flowPageTemplateCapabilityPrefix(path14) {
427
- const query = path14.includes("?") ? path14.slice(path14.indexOf("?") + 1) : "";
426
+ function flowPageTemplateCapabilityPrefix(path15) {
427
+ const query = path15.includes("?") ? path15.slice(path15.indexOf("?") + 1) : "";
428
428
  const type = new URLSearchParams(query).get("type");
429
429
  if (type === "2") {
430
430
  return "config.project_detail_template";
@@ -437,8 +437,8 @@ function flowPageTemplateCapabilityPrefix(path14) {
437
437
  }
438
438
  return "config.list_template";
439
439
  }
440
- function normalizePath2(path14) {
441
- let normalized = path14.split("?")[0] || "/";
440
+ function normalizePath2(path15) {
441
+ let normalized = path15.split("?")[0] || "/";
442
442
  if (!normalized.startsWith("/")) {
443
443
  normalized = `/${normalized}`;
444
444
  }
@@ -469,7 +469,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
469
469
  // package.json
470
470
  var package_default = {
471
471
  name: "bpmax-cli",
472
- version: "0.2.1-beta.1",
472
+ version: "0.2.1-beta.11",
473
473
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
474
474
  type: "module",
475
475
  bin: {
@@ -516,8 +516,8 @@ var NPM_PACKAGE = "bpmax-cli";
516
516
  // src/core/terminal.ts
517
517
  import { randomUUID } from "crypto";
518
518
  import os from "os";
519
- function isCliControlPath(path14) {
520
- const normalized = normalizeApiPath(path14);
519
+ function isCliControlPath(path15) {
520
+ const normalized = normalizeApiPath(path15);
521
521
  return normalized === "/api/cli/capabilities" || normalized === "/api/cli/terminals/register" || normalized === "/api/cli/audit/start" || normalized === "/api/cli/audit/finish" || normalized === "/api/cli/bbs_invocations/start" || normalized === "/api/cli/bbs_invocations/finish";
522
522
  }
523
523
  function commandSummary(argv = process.argv) {
@@ -681,8 +681,8 @@ async function updateProfileTerminal(profile, terminalId, status) {
681
681
  profile.config.terminal_status = status;
682
682
  profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
683
683
  }
684
- function normalizeApiPath(path14) {
685
- let normalized = path14.split("?")[0] || "/";
684
+ function normalizeApiPath(path15) {
685
+ let normalized = path15.split("?")[0] || "/";
686
686
  if (!normalized.startsWith("/")) {
687
687
  normalized = `/${normalized}`;
688
688
  }
@@ -800,14 +800,14 @@ function recordCommandAuditResult(value) {
800
800
  state.result_summary = redactAuditValue(value);
801
801
  }
802
802
  }
803
- var ensureApiPath = (path14) => {
804
- if (!path14.startsWith("/")) {
805
- path14 = `/${path14}`;
803
+ var ensureApiPath = (path15) => {
804
+ if (!path15.startsWith("/")) {
805
+ path15 = `/${path15}`;
806
806
  }
807
- if (path14.startsWith("/api/")) {
808
- return path14;
807
+ if (path15.startsWith("/api/")) {
808
+ return path15;
809
809
  }
810
- return `/api${path14}`;
810
+ return `/api${path15}`;
811
811
  };
812
812
  function normalizeWorkspaceForApi(workspace) {
813
813
  const normalized = workspace?.trim();
@@ -853,10 +853,10 @@ function createApiClient(profile) {
853
853
  });
854
854
  return instance;
855
855
  }
856
- async function apiRequest(client, method, path14, options = {}) {
856
+ async function apiRequest(client, method, path15, options = {}) {
857
857
  const profile = clientProfiles.get(client);
858
- const apiPath2 = ensureApiPath(path14);
859
- const capability = options.capability ?? capabilityForRequest(method, path14);
858
+ const apiPath2 = ensureApiPath(path15);
859
+ const capability = options.capability ?? capabilityForRequest(method, path15);
860
860
  const shouldControl = Boolean(profile?.config.api_key) && !isCliControlPath(apiPath2);
861
861
  const reqId = requestId();
862
862
  if (profile) {
@@ -1164,8 +1164,8 @@ async function parseJsonAny(input, label = "JSON input") {
1164
1164
  function isMutatingMethod(method) {
1165
1165
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
1166
1166
  }
1167
- function normalizeApiPath2(path14) {
1168
- let normalized = path14.trim();
1167
+ function normalizeApiPath2(path15) {
1168
+ let normalized = path15.trim();
1169
1169
  const queryIndex = normalized.indexOf("?");
1170
1170
  if (queryIndex >= 0) {
1171
1171
  normalized = normalized.slice(0, queryIndex);
@@ -1182,9 +1182,9 @@ function normalizeApiPath2(path14) {
1182
1182
  }
1183
1183
  return normalized;
1184
1184
  }
1185
- function pluginAgentCapabilityForRawApi(method, path14) {
1185
+ function pluginAgentCapabilityForRawApi(method, path15) {
1186
1186
  const normalizedMethod = method.toUpperCase();
1187
- const normalizedPath = normalizeApiPath2(path14);
1187
+ const normalizedPath = normalizeApiPath2(path15);
1188
1188
  const match = normalizedPath.match(/^\/(plugin_[A-Za-z0-9_]+)\/agents(?:\/|$)/);
1189
1189
  if (!match) {
1190
1190
  return void 0;
@@ -1198,19 +1198,19 @@ function pluginAgentCapabilityForRawApi(method, path14) {
1198
1198
  }
1199
1199
  return void 0;
1200
1200
  }
1201
- function parseQuery(path14) {
1202
- const queryIndex = path14.indexOf("?");
1203
- return new URLSearchParams(queryIndex >= 0 ? path14.slice(queryIndex + 1) : "");
1201
+ function parseQuery(path15) {
1202
+ const queryIndex = path15.indexOf("?");
1203
+ return new URLSearchParams(queryIndex >= 0 ? path15.slice(queryIndex + 1) : "");
1204
1204
  }
1205
- function isRawConfigPath(method, path14) {
1206
- const normalizedPath = normalizeApiPath2(path14);
1205
+ function isRawConfigPath(method, path15) {
1206
+ const normalizedPath = normalizeApiPath2(path15);
1207
1207
  if (/^\/(configuration|form_template|flow_page_template|data_set|data_set_field|api_platform|api_platform_instance|api_proxy|api_proxy_entity_binding|entity|entity_field|role|point|user_role|workspace|group|config_repository)(\/|$)/.test(normalizedPath)) {
1208
1208
  return true;
1209
1209
  }
1210
1210
  if (normalizedPath === "/flow/list/lightweight" || normalizedPath.startsWith("/flow/configuration/")) {
1211
1211
  return true;
1212
1212
  }
1213
- if (normalizedPath === "/flow" && method === "GET" && parseQuery(path14).has("draft")) {
1213
+ if (normalizedPath === "/flow" && method === "GET" && parseQuery(path15).has("draft")) {
1214
1214
  return true;
1215
1215
  }
1216
1216
  if (normalizedPath.startsWith("/flow/") && !["/flow/flow_type", "/flow/options", "/flow/batch_get"].includes(normalizedPath)) {
@@ -1221,35 +1221,35 @@ function isRawConfigPath(method, path14) {
1221
1221
  }
1222
1222
  return false;
1223
1223
  }
1224
- function assertRawApiPathAllowed(method, path14) {
1225
- if (isRawConfigPath(method, path14)) {
1224
+ function assertRawApiPathAllowed(method, path15) {
1225
+ if (isRawConfigPath(method, path15)) {
1226
1226
  throw new Error(
1227
- `Raw API ${method} ${path14} is blocked because BPMAX configuration APIs must use typed bpmax-cli config commands. Run bpmax-cli config adapters --format json to check whether the target config domain is supported.`
1227
+ `Raw API ${method} ${path15} is blocked because BPMAX configuration APIs must use typed bpmax-cli config commands. Run bpmax-cli config adapters --format json to check whether the target config domain is supported.`
1228
1228
  );
1229
1229
  }
1230
1230
  if (!isMutatingMethod(method)) {
1231
1231
  return;
1232
1232
  }
1233
- const normalizedPath = normalizeApiPath2(path14);
1233
+ const normalizedPath = normalizeApiPath2(path15);
1234
1234
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
1235
1235
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
1236
1236
  if (!isProjectPath || isAllowedProjectReadPost) {
1237
1237
  return;
1238
1238
  }
1239
1239
  throw new Error(
1240
- `Raw API ${method} ${path14} is blocked because /api/project/<id> falls back to project creation in huanpingtong-server. Do not call /project/es-search or /project/raw-es-search; huanpingtong-server does not expose those as public ES APIs. Use bpmax-cli project create --flow-id <id> --json <json> for project creation, or bpmax-cli project search / project list for project reads.`
1240
+ `Raw API ${method} ${path15} is blocked because /api/project/<id> falls back to project creation in huanpingtong-server. Do not call /project/es-search or /project/raw-es-search; huanpingtong-server does not expose those as public ES APIs. Use bpmax-cli project create --flow-id <id> --json <json> for project creation, or bpmax-cli project search / project list for project reads.`
1241
1241
  );
1242
1242
  }
1243
1243
  function registerApiCommands(program2) {
1244
- program2.command("api <method> <path>").description("Call an arbitrary BPMAX /api endpoint").option("--profile <profile>", "Profile name").option("--params <json>", "Query params JSON or @file").option("--data <json>", "Request body JSON or @file").option("--confirm-mutating", "Allow mutating API calls").option("--format <format>", "Output format", "json").action(async (method, path14, options) => {
1244
+ program2.command("api <method> <path>").description("Call an arbitrary BPMAX /api endpoint").option("--profile <profile>", "Profile name").option("--params <json>", "Query params JSON or @file").option("--data <json>", "Request body JSON or @file").option("--confirm-mutating", "Allow mutating API calls").option("--format <format>", "Output format", "json").action(async (method, path15, options) => {
1245
1245
  const normalizedMethod = method.toUpperCase();
1246
- assertRawApiPathAllowed(normalizedMethod, path14);
1246
+ assertRawApiPathAllowed(normalizedMethod, path15);
1247
1247
  if (isMutatingMethod(normalizedMethod) && options.confirmMutating !== true) {
1248
1248
  printResult(options.format, {
1249
1249
  ok: false,
1250
1250
  dry_run: true,
1251
1251
  method: normalizedMethod,
1252
- path: path14,
1252
+ path: path15,
1253
1253
  warning: "Mutating raw API calls require --confirm-mutating. Prefer typed bpmax-cli commands such as step submit."
1254
1254
  });
1255
1255
  return;
@@ -1257,8 +1257,8 @@ function registerApiCommands(program2) {
1257
1257
  const config = await loadConfig();
1258
1258
  const profile = resolveProfile(config, options.profile);
1259
1259
  const client = createApiClient(profile);
1260
- const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path14) || "api.raw";
1261
- const result = await apiRequest(client, normalizedMethod, path14, {
1260
+ const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path15) || "api.raw";
1261
+ const result = await apiRequest(client, normalizedMethod, path15, {
1262
1262
  params: options.params ? await parseJsonInput(options.params, "--params") : void 0,
1263
1263
  data: await parseJsonAny(options.data, "--data"),
1264
1264
  capability
@@ -1281,6 +1281,18 @@ function shellQuote(value) {
1281
1281
  }
1282
1282
  return `'${value.replace(/'/g, `'\\''`)}'`;
1283
1283
  }
1284
+ function toUserSummary(user) {
1285
+ if (!user || typeof user !== "object" || Array.isArray(user)) {
1286
+ return void 0;
1287
+ }
1288
+ const record = user;
1289
+ const id = typeof record.id === "number" ? record.id : typeof record.user_id === "number" ? record.user_id : void 0;
1290
+ const name = typeof record.name === "string" ? record.name : typeof record.nickname === "string" ? record.nickname : typeof record.realname === "string" ? record.realname : "";
1291
+ if (id === void 0) {
1292
+ return void 0;
1293
+ }
1294
+ return { id, name };
1295
+ }
1284
1296
  var DeviceAuthorizationError = class extends Error {
1285
1297
  code;
1286
1298
  interval;
@@ -1333,18 +1345,18 @@ function lintDeviceAuthorizationUrl(urlValue, expectedOrigin, expectedWorkspace,
1333
1345
  );
1334
1346
  }
1335
1347
  }
1336
- function apiPath(path14) {
1337
- if (path14.startsWith("/api/")) {
1338
- return path14;
1348
+ function apiPath(path15) {
1349
+ if (path15.startsWith("/api/")) {
1350
+ return path15;
1339
1351
  }
1340
- return `/api${path14.startsWith("/") ? path14 : `/${path14}`}`;
1352
+ return `/api${path15.startsWith("/") ? path15 : `/${path15}`}`;
1341
1353
  }
1342
1354
  function createDeviceRequest(origin) {
1343
1355
  const client = axios2.create({ baseURL: origin, withCredentials: false });
1344
- return async (method, path14, options) => {
1356
+ return async (method, path15, options) => {
1345
1357
  const response = await client.request({
1346
1358
  method,
1347
- url: apiPath(path14),
1359
+ url: apiPath(path15),
1348
1360
  data: options.data
1349
1361
  });
1350
1362
  const body = response.data;
@@ -1427,7 +1439,7 @@ async function completeDeviceLogin(options) {
1427
1439
  }
1428
1440
  return {
1429
1441
  apiKey,
1430
- user: response.user,
1442
+ user: toUserSummary(response.user),
1431
1443
  apiKeyCapabilities: response.capabilities && typeof response.capabilities === "object" && !Array.isArray(response.capabilities) ? response.capabilities : void 0
1432
1444
  };
1433
1445
  }
@@ -1491,7 +1503,7 @@ function updateProfileAuth(profile, result) {
1491
1503
  ...rest,
1492
1504
  ...terminalFields,
1493
1505
  api_key: result.apiKey,
1494
- user: result.user,
1506
+ user: toUserSummary(result.user),
1495
1507
  api_key_capabilities: result.apiKeyCapabilities || {}
1496
1508
  };
1497
1509
  }
@@ -1544,6 +1556,15 @@ async function fetchCurrentUserForStatus(profile) {
1544
1556
  }
1545
1557
  return body.data ?? body;
1546
1558
  }
1559
+ function minimalStatusUser(user) {
1560
+ const safe = {};
1561
+ for (const key of ["id", "user_id", "uid", "name", "nickname", "realname"]) {
1562
+ if (user[key] !== void 0 && user[key] !== null && user[key] !== "") {
1563
+ safe[key] = user[key];
1564
+ }
1565
+ }
1566
+ return safe;
1567
+ }
1547
1568
  function registerAuthCommands(program2, deps = {}) {
1548
1569
  const load = deps.loadConfig || loadConfig;
1549
1570
  const save = deps.saveConfig || saveConfig;
@@ -1579,6 +1600,7 @@ function registerAuthCommands(program2, deps = {}) {
1579
1600
  expiresIn: authorization.expires_in
1580
1601
  });
1581
1602
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
1603
+ result = { ...result, user: config.profiles[profile.name].user };
1582
1604
  await save(config);
1583
1605
  let capabilitiesProbe;
1584
1606
  let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
@@ -1643,6 +1665,7 @@ function registerAuthCommands(program2, deps = {}) {
1643
1665
  deviceCode
1644
1666
  });
1645
1667
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
1668
+ const safeUser = config.profiles[profile.name].user;
1646
1669
  await save(config);
1647
1670
  let capabilitiesProbe;
1648
1671
  let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
@@ -1664,12 +1687,12 @@ function registerAuthCommands(program2, deps = {}) {
1664
1687
  ok: true,
1665
1688
  profile: profile.name,
1666
1689
  login: "authenticated",
1667
- user: result.user,
1690
+ user: safeUser,
1668
1691
  ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
1669
1692
  ...nextCommands ? { next_commands: nextCommands } : {}
1670
1693
  });
1671
1694
  });
1672
- auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
1695
+ auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--verbose", "Include the full /api/user/current response. Default output is minimized and redacted for logs.").option("--format <format>", "Output format", "pretty").action(async (options) => {
1673
1696
  const config = await load();
1674
1697
  const profile = resolveProfile(config, options.profile);
1675
1698
  const output = {
@@ -1682,7 +1705,8 @@ function registerAuthCommands(program2, deps = {}) {
1682
1705
  if (profile.config.api_key) {
1683
1706
  try {
1684
1707
  const currentUser = await fetchCurrentUserForStatus(profile);
1685
- output.user = currentUser;
1708
+ output.user = options.verbose ? currentUser : minimalStatusUser(currentUser);
1709
+ output.user_detail = options.verbose ? "full" : "minimal";
1686
1710
  output.authenticated = true;
1687
1711
  } catch (error) {
1688
1712
  const message = error instanceof Error ? error.message : String(error);
@@ -1753,20 +1777,20 @@ function requireNumericId(value, name) {
1753
1777
  }
1754
1778
  return nextValue;
1755
1779
  }
1756
- function withQuery(path14, query) {
1780
+ function withQuery(path15, query) {
1757
1781
  const params = new URLSearchParams();
1758
1782
  for (const [key, value] of Object.entries(query)) {
1759
1783
  if (value !== void 0) {
1760
1784
  params.set(key, value);
1761
1785
  }
1762
1786
  }
1763
- return `${path14}?${params.toString()}`;
1787
+ return `${path15}?${params.toString()}`;
1764
1788
  }
1765
1789
  function buildBpmaxUrl(profile, kind, params = {}) {
1766
1790
  const origin = normalizeOrigin2(profile.config.origin);
1767
1791
  const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
1768
1792
  const basePath = `/${workspace}`;
1769
- let path14 = basePath;
1793
+ let path15 = basePath;
1770
1794
  const result = {
1771
1795
  kind,
1772
1796
  profile: profile.name,
@@ -1774,15 +1798,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
1774
1798
  workspace
1775
1799
  };
1776
1800
  if (kind === "project-list") {
1777
- path14 = `${basePath}/project`;
1801
+ path15 = `${basePath}/project`;
1778
1802
  } else if (kind === "project-detail") {
1779
1803
  const projectId = requireNumericId(params.projectId, "projectId");
1780
- path14 = `${basePath}/project_detail/0/${projectId}`;
1804
+ path15 = `${basePath}/project_detail/0/${projectId}`;
1781
1805
  result.project_id = projectId;
1782
1806
  } else if (kind === "project-step") {
1783
1807
  const projectId = requireNumericId(params.projectId, "projectId");
1784
1808
  const stepId = requireNumericId(params.stepId, "stepId");
1785
- path14 = withQuery(`${basePath}/projectContinue`, {
1809
+ path15 = withQuery(`${basePath}/projectContinue`, {
1786
1810
  id: projectId,
1787
1811
  step_id: stepId
1788
1812
  });
@@ -1799,15 +1823,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
1799
1823
  ...flowKey ? { key: flowKey } : {},
1800
1824
  ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
1801
1825
  };
1802
- path14 = withQuery(`${basePath}/project/create`, query);
1826
+ path15 = withQuery(`${basePath}/project/create`, query);
1803
1827
  result.flow_type = flowType;
1804
1828
  result.flow_key = flowKey;
1805
1829
  result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
1806
1830
  }
1807
- const url = `${origin}${path14}`;
1831
+ const url = `${origin}${path15}`;
1808
1832
  return {
1809
1833
  ...result,
1810
- path: path14,
1834
+ path: path15,
1811
1835
  url,
1812
1836
  ...kind === "project-create" ? { pc_url: url } : {}
1813
1837
  };
@@ -2717,6 +2741,8 @@ function registerCapabilitiesCommands(program2) {
2717
2741
 
2718
2742
  // src/commands/config.ts
2719
2743
  import { text as text2 } from "@clack/prompts";
2744
+ import { mkdir as mkdir8, writeFile as writeFile8 } from "fs/promises";
2745
+ import path9 from "path";
2720
2746
 
2721
2747
  // src/core/config-workflow.ts
2722
2748
  import { createHash as createHash4 } from "crypto";
@@ -3927,6 +3953,8 @@ function configAdapterMatrix() {
3927
3953
  return Object.entries(CONFIG_DOMAINS).map(([domain, definition]) => {
3928
3954
  const supportsCreate = Boolean(definition.createPath) || ["flow-template", "api-platform", "role", "nav-config"].includes(domain);
3929
3955
  const supportsDelete = Boolean(definition.deletePath) || ["workspace-flow", "api-platform", "nav-config"].includes(domain);
3956
+ const supportsPublish = domain === "dataset";
3957
+ const supportsRelationFields = domain === "dataset";
3930
3958
  return {
3931
3959
  domain,
3932
3960
  capability_prefix: definition.capability,
@@ -3939,6 +3967,29 @@ function configAdapterMatrix() {
3939
3967
  delete_capability: supportsDelete ? `${definition.capability}.delete` : null,
3940
3968
  read_endpoints: definition.readEndpoints,
3941
3969
  write_endpoints: definition.writeEndpoints,
3970
+ actions: {
3971
+ export: definition.exportStatus === "supported",
3972
+ create: supportsCreate,
3973
+ build: definition.buildStatus === "supported",
3974
+ submit: definition.submitStatus === "supported" || definition.submitStatus === "requires-platform-proxy",
3975
+ publish: supportsPublish,
3976
+ relationFields: supportsRelationFields,
3977
+ delete: supportsDelete,
3978
+ verify: definition.exportStatus === "supported",
3979
+ dry_run: definition.submitStatus === "supported" || definition.submitStatus === "requires-platform-proxy"
3980
+ },
3981
+ requires: {
3982
+ work_file: definition.buildStatus === "supported",
3983
+ meta_file_for_build: definition.buildStatus === "supported",
3984
+ payload_file_for_submit: definition.submitStatus === "supported" || definition.submitStatus === "requires-platform-proxy",
3985
+ base_hash_for_submit: domain === "workspace-flow" || domain === "dataset"
3986
+ },
3987
+ side_effects: {
3988
+ writes_workspace_binding: domain === "workspace-flow",
3989
+ full_replacement_submit: domain === "workspace-flow",
3990
+ publishes_on_submit: domain === "form-template",
3991
+ relation_fields_submit: domain === "dataset"
3992
+ },
3942
3993
  notes: definition.notes
3943
3994
  };
3944
3995
  });
@@ -3946,6 +3997,34 @@ function configAdapterMatrix() {
3946
3997
  function hashJson(value) {
3947
3998
  return createHash4("sha256").update(JSON.stringify(value)).digest("hex");
3948
3999
  }
4000
+ function flowAppContextEvidence(input) {
4001
+ const flowData = isRecord3(input.flow.data) ? input.flow.data : {};
4002
+ const flowType = firstNonEmpty(input.flow.flow_type, flowData.flow_type, input.flowId);
4003
+ const flowKey = firstNonEmpty(input.flow.key);
4004
+ const flowTemplateId = input.flow.id ?? input.flow.flow_id ?? null;
4005
+ const missing = [
4006
+ ["flow_type", flowType],
4007
+ ["form_template_id", input.formTemplateId],
4008
+ ["form_template_draft_id", input.formTemplateDraftId],
4009
+ ["workspace_binding", input.bindingFound ? "ok" : ""]
4010
+ ].filter(([, value]) => value === null || value === void 0 || String(value).trim() === "").map(([key]) => key);
4011
+ return {
4012
+ flow_type: flowType || null,
4013
+ flow_key: flowKey,
4014
+ flow_template_id: flowTemplateId,
4015
+ form_template_id: input.formTemplateId ?? null,
4016
+ form_template_draft_id: input.formTemplateDraftId ?? null,
4017
+ workspace_key: input.workspace,
4018
+ workspace_binding_found: input.bindingFound,
4019
+ workspace_readback_hash: hashJson(input.workspaceReadback),
4020
+ flow_readback_hash: hashJson(input.flow),
4021
+ form_template_readback_hash: input.formReadback ? hashJson(input.formReadback) : null,
4022
+ evidence_status: missing.length === 0 ? "verified" : "incomplete",
4023
+ missing_context: missing,
4024
+ resolved_by: input.resolvedBy,
4025
+ verified_at: (/* @__PURE__ */ new Date()).toISOString()
4026
+ };
4027
+ }
3949
4028
  function isRecord3(value) {
3950
4029
  return value !== null && typeof value === "object" && !Array.isArray(value);
3951
4030
  }
@@ -4063,9 +4142,9 @@ function summarizeOperationPlan(payload) {
4063
4142
  return "submit operation";
4064
4143
  }
4065
4144
  const method = typeof operation.method === "string" ? operation.method : "REQUEST";
4066
- const path14 = typeof operation.path === "string" ? operation.path : "";
4145
+ const path15 = typeof operation.path === "string" ? operation.path : "";
4067
4146
  const type = typeof operation.type === "string" ? ` ${operation.type}` : "";
4068
- return `submit${type}: ${method}${path14 ? ` ${path14}` : ""}`;
4147
+ return `submit${type}: ${method}${path15 ? ` ${path15}` : ""}`;
4069
4148
  }),
4070
4149
  ...skipped.slice(0, Math.max(0, 20 - operations.length)).map((operation) => {
4071
4150
  if (!isRecord3(operation)) {
@@ -4260,6 +4339,449 @@ function validateFlowTemplateStandardPageCreateFormTemplate(value, errors) {
4260
4339
  }
4261
4340
  throw new Error(message);
4262
4341
  }
4342
+ function startConditionalJumpScriptLooksLikeIndexReturn(script) {
4343
+ const text5 = script.trim();
4344
+ if (!text5) {
4345
+ return false;
4346
+ }
4347
+ const directReturns = Array.from(text5.matchAll(/\breturn\s+([^;]+)\s*;?/g));
4348
+ if (!directReturns.length) {
4349
+ return false;
4350
+ }
4351
+ return directReturns.some((match) => {
4352
+ const expression = match[1].trim();
4353
+ if (/[=!<>]=?|&&|\|\||\?/.test(expression)) {
4354
+ return false;
4355
+ }
4356
+ return /^-?\d+$/.test(expression) || /^(routeIndex|resultIndex|targetIndex|index)\b/.test(expression) || /\b(result|options)\.indexOf\s*\(/.test(expression) || /^Number(?:\.parseInt)?\s*\(/.test(expression);
4357
+ });
4358
+ }
4359
+ function startConditionalJumpScriptIsCatchAll(script) {
4360
+ const text5 = script.trim();
4361
+ return /^return\s+true\s*;?\s*$/.test(text5) || /^return\s+Boolean\s*\(\s*true\s*\)\s*;?\s*$/.test(text5);
4362
+ }
4363
+ function validateFlowTemplateStartConditionalJump(value, errors) {
4364
+ const nextErrors = [];
4365
+ const data = isRecord3(value.data) ? value.data : {};
4366
+ const meta = isRecord3(data.meta) ? data.meta : {};
4367
+ const jumps = meta.condational_jump;
4368
+ if (jumps === void 0 || jumps === null || jumps === "") {
4369
+ return;
4370
+ }
4371
+ if (!Array.isArray(jumps)) {
4372
+ nextErrors.push("data.meta.condational_jump must be an array when start conditional routing is configured.");
4373
+ } else if (jumps.length === 0) {
4374
+ return;
4375
+ }
4376
+ const nodes = Array.isArray(data.nodes) ? data.nodes.filter(isRecord3) : [];
4377
+ const firstNodeId = nodes.length ? String(nodes[0].id ?? "").trim() : "";
4378
+ const nodeIds = new Set(nodes.map((node) => String(node.id ?? "").trim()).filter(Boolean));
4379
+ if (Array.isArray(jumps) && jumps.length && !nodes.length) {
4380
+ nextErrors.push("data.meta.condational_jump is configured but data.nodes is empty; start jump targets must point to real nodes or -1.");
4381
+ }
4382
+ if (Array.isArray(jumps) && jumps.length) {
4383
+ nodes.forEach((node, index) => {
4384
+ const id = String(node.id ?? "").trim();
4385
+ if (!id) {
4386
+ nextErrors.push(`data.nodes[${index}].id is required when data.meta.condational_jump is configured.`);
4387
+ }
4388
+ });
4389
+ }
4390
+ let lastJumpScript = "";
4391
+ let lastJumpResult = "";
4392
+ if (Array.isArray(jumps)) {
4393
+ jumps.forEach((jump, index) => {
4394
+ const pathName = `data.meta.condational_jump[${index}]`;
4395
+ if (!isRecord3(jump)) {
4396
+ nextErrors.push(`${pathName} must be an object with name, result, condition_mode, and a boolean condition script.`);
4397
+ return;
4398
+ }
4399
+ const name = typeof jump.name === "string" ? jump.name.trim() : "";
4400
+ if (!name) {
4401
+ nextErrors.push(`${pathName}.name is required so every explicit start route can be audited.`);
4402
+ }
4403
+ const rawResult = jump.result;
4404
+ if (Array.isArray(rawResult) || isRecord3(rawResult) || rawResult === void 0 || rawResult === null || String(rawResult).trim() === "") {
4405
+ nextErrors.push(`${pathName}.result must be a target node id or -1; it must not be empty, an array, an object, or a node name.`);
4406
+ } else {
4407
+ const result = String(rawResult).trim();
4408
+ if (result !== "-1" && !nodeIds.has(result)) {
4409
+ nextErrors.push(`${pathName}.result (${result}) must point to an existing data.nodes[].id or -1 for success end.`);
4410
+ }
4411
+ lastJumpResult = result;
4412
+ }
4413
+ const mode = typeof jump.condition_mode === "string" && jump.condition_mode.trim() ? jump.condition_mode.trim() : "code";
4414
+ let script = "";
4415
+ if (mode === "standard") {
4416
+ if (typeof jump.standard_condition === "string" && jump.standard_condition.trim()) {
4417
+ script = jump.standard_condition.trim();
4418
+ } else {
4419
+ nextErrors.push(`${pathName}.standard_condition is required when condition_mode is standard; condition is ignored by the backend in this mode.`);
4420
+ }
4421
+ } else if (mode === "code") {
4422
+ if (typeof jump.condition === "string" && jump.condition.trim()) {
4423
+ script = jump.condition.trim();
4424
+ } else {
4425
+ nextErrors.push(`${pathName}.condition is required when condition_mode is code or omitted; standard_condition is ignored by the backend in code mode.`);
4426
+ }
4427
+ } else {
4428
+ nextErrors.push(`${pathName}.condition_mode must be code or standard.`);
4429
+ }
4430
+ if (script) {
4431
+ lastJumpScript = script;
4432
+ if (index < jumps.length - 1 && startConditionalJumpScriptIsCatchAll(script)) {
4433
+ nextErrors.push(
4434
+ `${pathName} is a catch-all start route but is not the final item; return true must only appear on the last explicit fallback route.`
4435
+ );
4436
+ }
4437
+ if (startConditionalJumpScriptLooksLikeIndexReturn(script)) {
4438
+ nextErrors.push(
4439
+ `${pathName} must return boolean/truthy for this explicit start edge, not a node-level result index; do not copy node.condational_nodes scripts such as return 0/1/-1 into data.meta.condational_jump.`
4440
+ );
4441
+ }
4442
+ }
4443
+ });
4444
+ }
4445
+ if (Array.isArray(jumps) && jumps.length && nodes.length) {
4446
+ if (!lastJumpResult || !startConditionalJumpScriptIsCatchAll(lastJumpScript)) {
4447
+ nextErrors.push(
4448
+ "data.meta.condational_jump must end with an explicit catch-all route using condition script return true; this documents the default start path instead of relying on implicit fallback."
4449
+ );
4450
+ }
4451
+ }
4452
+ if (!nextErrors.length) {
4453
+ return;
4454
+ }
4455
+ if (errors) {
4456
+ errors.push(...nextErrors);
4457
+ return;
4458
+ }
4459
+ throw new Error(`flow-template start conditional jump gate failed: ${nextErrors.join("; ")}`);
4460
+ }
4461
+ function isFlowTemplateEndpointTarget(value) {
4462
+ return /^-\d+$/.test(value.trim());
4463
+ }
4464
+ function isFlowTemplateSpecialStepTarget(value) {
4465
+ const normalized = value.trim();
4466
+ return normalized === "[source]" || normalized === "anyNode";
4467
+ }
4468
+ function isFlowTemplateBackSourceTarget(value) {
4469
+ return value.trim() === "[source]";
4470
+ }
4471
+ function isFlowTemplateConditionalTarget(value, conditionNames) {
4472
+ const match = value.trim().match(/^(.+)\[condition\]\d+$/);
4473
+ if (!match) {
4474
+ return false;
4475
+ }
4476
+ return conditionNames.has(match[1].trim());
4477
+ }
4478
+ function validateFlowTemplateActionTarget(errors, pathName, target, nodeIds, conditionNames, options = {}) {
4479
+ const normalizedTarget = target.trim();
4480
+ if (!normalizedTarget) {
4481
+ if (options.actionString) {
4482
+ errors.push(`${pathName} target step is required after "|"; use "\u6309\u94AE\u6587\u6848|\u76EE\u6807\u8282\u70B9ID" or "\u6309\u94AE\u6587\u6848|\u6761\u4EF6\u540D[condition]0".`);
4483
+ } else {
4484
+ errors.push(`${pathName} target step is required; use a node id, -1, [source], anyNode, or \u6761\u4EF6\u540D[condition]0.`);
4485
+ }
4486
+ return;
4487
+ }
4488
+ const conditionalTargetAllowed = options.allowConditionalTarget !== false;
4489
+ const specialTargetAllowed = options.allowAnyNode === false ? isFlowTemplateBackSourceTarget(normalizedTarget) : isFlowTemplateSpecialStepTarget(normalizedTarget);
4490
+ if (!nodeIds.has(normalizedTarget) && !isFlowTemplateEndpointTarget(normalizedTarget) && !specialTargetAllowed && !(conditionalTargetAllowed && isFlowTemplateConditionalTarget(normalizedTarget, conditionNames))) {
4491
+ const allowedTargets = conditionalTargetAllowed ? "an existing data.nodes[].id, an endpoint like -1, [source], anyNode, or a condational_nodes reference like \u6761\u4EF6\u540D[condition]0" : options.allowAnyNode === false ? "an existing data.nodes[].id, an endpoint like -1, or [source]" : "an existing data.nodes[].id, an endpoint like -1, [source], or anyNode";
4492
+ errors.push(`${pathName} target (${normalizedTarget}) must be ${allowedTargets}.`);
4493
+ }
4494
+ }
4495
+ function validateFlowTemplateApproveActionShape(value, errors) {
4496
+ const nextErrors = [];
4497
+ const data = isRecord3(value.data) ? value.data : {};
4498
+ const nodes = Array.isArray(data.nodes) ? data.nodes.filter(isRecord3) : [];
4499
+ const nodeIds = new Set(nodes.map((node) => String(node.id ?? "").trim()).filter(Boolean));
4500
+ nodes.forEach((node, nodeIndex) => {
4501
+ const nodeName = typeof node.name === "string" && node.name.trim() ? node.name.trim() : `nodes[${nodeIndex}]`;
4502
+ const conditionNames = /* @__PURE__ */ new Set();
4503
+ if (node.condational_nodes !== void 0 && node.condational_nodes !== null && node.condational_nodes !== "" && !Array.isArray(node.condational_nodes)) {
4504
+ nextErrors.push(`${nodeName}.condational_nodes must be an array of condition route objects.`);
4505
+ }
4506
+ const conditionalNodes = Array.isArray(node.condational_nodes) ? node.condational_nodes : [];
4507
+ conditionalNodes.forEach((conditionNode, conditionIndex) => {
4508
+ const conditionPath = `${nodeName}.condational_nodes[${conditionIndex}]`;
4509
+ if (!isRecord3(conditionNode)) {
4510
+ nextErrors.push(`${conditionPath} must be an object with name, result, condition_mode, and an index-returning condition script.`);
4511
+ return;
4512
+ }
4513
+ const conditionName = typeof conditionNode.name === "string" ? conditionNode.name.trim() : "";
4514
+ if (conditionName) {
4515
+ conditionNames.add(conditionName);
4516
+ } else {
4517
+ nextErrors.push(`${conditionPath}.name is required so approve_to_step/approve_actions can reference this condational_nodes entry.`);
4518
+ }
4519
+ const conditionMode = typeof conditionNode.condition_mode === "string" && conditionNode.condition_mode.trim() ? conditionNode.condition_mode.trim() : "code";
4520
+ if (conditionMode === "standard") {
4521
+ if (typeof conditionNode.standard_condition !== "string" || !conditionNode.standard_condition.trim()) {
4522
+ nextErrors.push(`${conditionPath}.standard_condition is required when condition_mode is standard; condition is ignored by the backend in this mode.`);
4523
+ }
4524
+ } else if (conditionMode === "code") {
4525
+ if (typeof conditionNode.condition !== "string" || !conditionNode.condition.trim()) {
4526
+ nextErrors.push(`${conditionPath}.condition is required when condition_mode is code or omitted; standard_condition is ignored by the backend in code mode.`);
4527
+ }
4528
+ } else {
4529
+ nextErrors.push(`${conditionPath}.condition_mode must be code or standard.`);
4530
+ }
4531
+ const conditionResult = conditionNode.result;
4532
+ const resultPath = `${conditionPath}.result`;
4533
+ if (!Array.isArray(conditionResult) || !conditionResult.length) {
4534
+ nextErrors.push(`${resultPath} must be a non-empty array of target node ids.`);
4535
+ return;
4536
+ }
4537
+ conditionResult.forEach((target, targetIndex) => {
4538
+ const targetPath = `${resultPath}[${targetIndex}]`;
4539
+ if (Array.isArray(target) || isRecord3(target) || target === void 0 || target === null) {
4540
+ nextErrors.push(`${targetPath} must be a target node id, endpoint like -1, or [source].`);
4541
+ return;
4542
+ }
4543
+ validateFlowTemplateActionTarget(
4544
+ nextErrors,
4545
+ targetPath,
4546
+ String(target),
4547
+ nodeIds,
4548
+ conditionNames,
4549
+ { allowConditionalTarget: false, allowAnyNode: false }
4550
+ );
4551
+ });
4552
+ });
4553
+ [
4554
+ ["approve_to_step", node.approve_to_step],
4555
+ ["approve_fail", node.approve_fail]
4556
+ ].forEach(([fieldName, fieldValue]) => {
4557
+ if (fieldValue === void 0 || fieldValue === null || fieldValue === "") {
4558
+ return;
4559
+ }
4560
+ if (Array.isArray(fieldValue) || isRecord3(fieldValue)) {
4561
+ nextErrors.push(`${nodeName}.${fieldName} must be a target node id, endpoint like -1, [source], anyNode, or \u6761\u4EF6\u540D[condition]0.`);
4562
+ return;
4563
+ }
4564
+ validateFlowTemplateActionTarget(nextErrors, `${nodeName}.${fieldName}`, String(fieldValue), nodeIds, conditionNames);
4565
+ });
4566
+ const actionGroups = [
4567
+ ["approve_actions", node.approve_actions],
4568
+ ["approve_fail_actions", node.approve_fail_actions]
4569
+ ];
4570
+ actionGroups.forEach(([fieldName, fieldValue]) => {
4571
+ if (fieldValue === void 0 || fieldValue === null || fieldValue === "") {
4572
+ return;
4573
+ }
4574
+ const pathPrefix = `${nodeName}.${fieldName}`;
4575
+ if (!Array.isArray(fieldValue)) {
4576
+ nextErrors.push(`${pathPrefix} must be an array of action strings.`);
4577
+ return;
4578
+ }
4579
+ fieldValue.forEach((action, actionIndex) => {
4580
+ const pathName = `${pathPrefix}[${actionIndex}]`;
4581
+ if (typeof action !== "string") {
4582
+ nextErrors.push(`${pathName} must be a string action in "\u6309\u94AE\u6587\u6848|\u76EE\u6807\u8282\u70B9ID" format.`);
4583
+ return;
4584
+ }
4585
+ const parts = action.split("|");
4586
+ if (parts.length < 2) {
4587
+ const raw = action.trim();
4588
+ if (raw && (nodeIds.has(raw) || isFlowTemplateEndpointTarget(raw) || isFlowTemplateSpecialStepTarget(raw) || isFlowTemplateConditionalTarget(raw, conditionNames))) {
4589
+ nextErrors.push(`${pathName} is a bare target (${raw}); action strings must be "\u6309\u94AE\u6587\u6848|\u76EE\u6807\u8282\u70B9ID", not just a node id.`);
4590
+ } else {
4591
+ nextErrors.push(`${pathName} must contain "|" and use "\u6309\u94AE\u6587\u6848|\u76EE\u6807\u8282\u70B9ID" or "\u6309\u94AE\u6587\u6848|\u6761\u4EF6\u540D[condition]0".`);
4592
+ }
4593
+ return;
4594
+ }
4595
+ const label = parts[0].trim();
4596
+ const target = parts[1].trim();
4597
+ if (!label) {
4598
+ nextErrors.push(`${pathName} label is required before "|".`);
4599
+ }
4600
+ validateFlowTemplateActionTarget(nextErrors, pathName, target, nodeIds, conditionNames, { actionString: true });
4601
+ });
4602
+ });
4603
+ });
4604
+ if (!nextErrors.length) {
4605
+ return;
4606
+ }
4607
+ if (errors) {
4608
+ errors.push(...nextErrors);
4609
+ return;
4610
+ }
4611
+ throw new Error(`flow-template approve action gate failed: ${nextErrors.join("; ")}`);
4612
+ }
4613
+ function validateOptionalBoolean(errors, value, fieldName, pathName) {
4614
+ if (value[fieldName] !== void 0 && typeof value[fieldName] !== "boolean") {
4615
+ errors.push(`${pathName}.${fieldName} must be a boolean when provided.`);
4616
+ }
4617
+ }
4618
+ function flowTemplateNodeRequiresApproval(node) {
4619
+ if (node.approve_count_required === "all") {
4620
+ return true;
4621
+ }
4622
+ const approveCount = Number(node.approve_count_required ?? 0);
4623
+ return Number.isFinite(approveCount) && approveCount > 0;
4624
+ }
4625
+ function validateFlowTemplatePluginRejectionControl(value, errors) {
4626
+ const nextErrors = [];
4627
+ const data = isRecord3(value.data) ? value.data : {};
4628
+ const meta = isRecord3(data.meta) ? data.meta : {};
4629
+ const nodes = Array.isArray(data.nodes) ? data.nodes.filter(isRecord3) : [];
4630
+ nodes.forEach((node, nodeIndex) => {
4631
+ const nodeName = typeof node.name === "string" && node.name.trim() ? node.name.trim() : `nodes[${nodeIndex}]`;
4632
+ const config = node.plugin_rejection_control;
4633
+ const pathName = `${nodeName}.plugin_rejection_control`;
4634
+ if (config === void 0 || config === null || config === "") {
4635
+ return;
4636
+ }
4637
+ if (!isRecord3(config)) {
4638
+ nextErrors.push(`${pathName} must be an object when configured.`);
4639
+ return;
4640
+ }
4641
+ validateOptionalBoolean(nextErrors, config, "enabled", pathName);
4642
+ validateOptionalBoolean(nextErrors, config, "disabled_form_validate", pathName);
4643
+ [
4644
+ "reject_to_pre",
4645
+ "reject_to_owner",
4646
+ "reject_to_specific_step",
4647
+ "reject_to_end",
4648
+ "review_default",
4649
+ "review_to_me",
4650
+ "review_to_all",
4651
+ "review_to_any_node"
4652
+ ].forEach((fieldName) => validateOptionalBoolean(nextErrors, config, fieldName, pathName));
4653
+ if (config.enabled !== true) {
4654
+ return;
4655
+ }
4656
+ if (typeof config.button_text !== "string" || !config.button_text.trim()) {
4657
+ nextErrors.push(`${pathName}.button_text is required when plugin rejection control is enabled.`);
4658
+ }
4659
+ if (!flowTemplateNodeRequiresApproval(node)) {
4660
+ nextErrors.push(`${pathName}.enabled requires an approval step with approve_count_required > 0 or "all"; the plugin replaces reject buttons on approval steps only.`);
4661
+ }
4662
+ const hasNativeRejectTarget = typeof node.approve_fail === "string" && node.approve_fail.trim() || Array.isArray(node.approve_fail_actions) && node.approve_fail_actions.length > 0;
4663
+ const hasPluginRejectMethod = config.reject_to_pre === true || config.reject_to_owner === true || config.reject_to_specific_step === true || config.reject_to_end === true;
4664
+ if (!hasNativeRejectTarget && !hasPluginRejectMethod) {
4665
+ nextErrors.push(
4666
+ `${pathName} must enable at least one reject method (reject_to_pre, reject_to_owner, reject_to_specific_step, reject_to_end) or keep a native approve_fail/approve_fail_actions target.`
4667
+ );
4668
+ }
4669
+ if (config.reject_to_owner === true && meta.allow_jump_start !== true && !hasNativeRejectTarget && config.reject_to_pre !== true && config.reject_to_specific_step !== true && config.reject_to_end !== true) {
4670
+ nextErrors.push(
4671
+ `${pathName}.reject_to_owner is the only configured reject method but requires data.meta.allow_jump_start = true; otherwise the runtime will not offer any usable plugin reject method.`
4672
+ );
4673
+ }
4674
+ });
4675
+ if (!nextErrors.length) {
4676
+ return;
4677
+ }
4678
+ if (errors) {
4679
+ errors.push(...nextErrors);
4680
+ return;
4681
+ }
4682
+ throw new Error(`flow-template plugin rejection control gate failed: ${nextErrors.join("; ")}`);
4683
+ }
4684
+ var FLOW_TEMPLATE_STANDARD_CONDITION_OPERATORS = /* @__PURE__ */ new Set([
4685
+ "eq",
4686
+ "ne",
4687
+ "gt",
4688
+ "gte",
4689
+ "lt",
4690
+ "lte",
4691
+ "contains",
4692
+ "isEmpty",
4693
+ "isNotEmpty"
4694
+ ]);
4695
+ function validateFlowTemplateStandardConditionEditorRules(value, errors) {
4696
+ const nextErrors = [];
4697
+ const data = isRecord3(value.data) ? value.data : {};
4698
+ const nodes = Array.isArray(data.nodes) ? data.nodes.filter(isRecord3) : [];
4699
+ const visitConditionGroup = (group, pathName) => {
4700
+ if (!isRecord3(group)) {
4701
+ nextErrors.push(`${pathName} must be a condition group object with logic and conditions.`);
4702
+ return;
4703
+ }
4704
+ const logic = typeof group.logic === "string" ? group.logic.trim() : "AND";
4705
+ if (logic !== "AND" && logic !== "OR") {
4706
+ nextErrors.push(`${pathName}.logic must be AND or OR.`);
4707
+ }
4708
+ if (!Array.isArray(group.conditions)) {
4709
+ nextErrors.push(`${pathName}.conditions must be an array.`);
4710
+ return;
4711
+ }
4712
+ group.conditions.forEach((condition, conditionIndex) => {
4713
+ const conditionPath = `${pathName}.conditions[${conditionIndex}]`;
4714
+ if (!isRecord3(condition)) {
4715
+ nextErrors.push(`${conditionPath} must be a condition object or nested condition group.`);
4716
+ return;
4717
+ }
4718
+ if (Array.isArray(condition.conditions) || typeof condition.logic === "string") {
4719
+ visitConditionGroup(condition, conditionPath);
4720
+ return;
4721
+ }
4722
+ const leftValue = typeof condition.leftValue === "string" ? condition.leftValue.trim() : "";
4723
+ if (!leftValue) {
4724
+ nextErrors.push(`${conditionPath}.leftValue is required and must match a form_template rule.field value.`);
4725
+ }
4726
+ const leftValueType = typeof condition.leftValueType === "string" && condition.leftValueType.trim() ? condition.leftValueType.trim() : "field";
4727
+ if (leftValueType !== "field" && leftValueType !== "constant" && leftValueType !== "variable") {
4728
+ nextErrors.push(`${conditionPath}.leftValueType must be field, constant, or variable.`);
4729
+ }
4730
+ const operator = typeof condition.operator === "string" ? condition.operator.trim() : "";
4731
+ if (!operator || !FLOW_TEMPLATE_STANDARD_CONDITION_OPERATORS.has(operator)) {
4732
+ nextErrors.push(`${conditionPath}.operator must be one of ${Array.from(FLOW_TEMPLATE_STANDARD_CONDITION_OPERATORS).join(", ")}.`);
4733
+ }
4734
+ const rightValueType = typeof condition.rightValueType === "string" && condition.rightValueType.trim() ? condition.rightValueType.trim() : "constant";
4735
+ if (rightValueType !== "field" && rightValueType !== "constant" && rightValueType !== "variable") {
4736
+ nextErrors.push(`${conditionPath}.rightValueType must be field, constant, or variable.`);
4737
+ }
4738
+ const isWewfDerived = condition._wewf_operator !== void 0 || condition._wewf_source_rule_id !== void 0 || condition._wewf_field_key !== void 0;
4739
+ if (isWewfDerived && condition._bpmax_editor_field_resolved !== true) {
4740
+ nextErrors.push(
4741
+ `${conditionPath} is WEWF-derived but does not prove BPMAX editor field resolution; leftValue must be resolved from form_template rule.field (for example main.<field_key>) before using condition_mode=standard.`
4742
+ );
4743
+ }
4744
+ if (isWewfDerived && typeof condition._wewf_field_key === "string" && condition._wewf_field_key.trim() && condition._wewf_field_key.trim() === leftValue && !leftValue.includes(".")) {
4745
+ nextErrors.push(
4746
+ `${conditionPath}.leftValue (${leftValue}) still looks like a raw WEWF field key; standard condition editor values must use the BPMAX form_template rule.field value.`
4747
+ );
4748
+ }
4749
+ });
4750
+ };
4751
+ nodes.forEach((node, nodeIndex) => {
4752
+ const nodeName = typeof node.name === "string" && node.name.trim() ? node.name.trim() : `nodes[${nodeIndex}]`;
4753
+ const conditionalNodes = Array.isArray(node.condational_nodes) ? node.condational_nodes : [];
4754
+ conditionalNodes.forEach((conditionNode, conditionIndex) => {
4755
+ if (!isRecord3(conditionNode)) {
4756
+ return;
4757
+ }
4758
+ const conditionMode = typeof conditionNode.condition_mode === "string" && conditionNode.condition_mode.trim() ? conditionNode.condition_mode.trim() : "code";
4759
+ if (conditionMode !== "standard") {
4760
+ return;
4761
+ }
4762
+ const conditionPath = `${nodeName}.condational_nodes[${conditionIndex}]`;
4763
+ if (!Array.isArray(conditionNode.condition_result_rules)) {
4764
+ nextErrors.push(`${conditionPath}.condition_result_rules must be an array when condition_mode is standard.`);
4765
+ return;
4766
+ }
4767
+ const resultLength = Array.isArray(conditionNode.result) ? conditionNode.result.length : 0;
4768
+ if (conditionNode.condition_result_rules.length !== resultLength) {
4769
+ nextErrors.push(`${conditionPath}.condition_result_rules length must equal result length (${resultLength}).`);
4770
+ }
4771
+ conditionNode.condition_result_rules.forEach((group, groupIndex) => {
4772
+ visitConditionGroup(group, `${conditionPath}.condition_result_rules[${groupIndex}]`);
4773
+ });
4774
+ });
4775
+ });
4776
+ if (!nextErrors.length) {
4777
+ return;
4778
+ }
4779
+ if (errors) {
4780
+ errors.push(...nextErrors);
4781
+ return;
4782
+ }
4783
+ throw new Error(`flow-template standard condition editor gate failed: ${nextErrors.join("; ")}`);
4784
+ }
4263
4785
  function looksLikeParseEvalFunctionBody(script) {
4264
4786
  const text5 = script.trim();
4265
4787
  if (!text5) {
@@ -4934,6 +5456,10 @@ function normalizeFlowTemplatePayload(work) {
4934
5456
  validateFlowTemplateRemoteTemplateRefs({ ...work, data });
4935
5457
  validateFlowTemplateProjectAfterCreatePath({ ...work, data });
4936
5458
  validateFlowTemplateStandardPageCreateFormTemplate({ ...work, data });
5459
+ validateFlowTemplateStartConditionalJump({ ...work, data });
5460
+ validateFlowTemplateApproveActionShape({ ...work, data });
5461
+ validateFlowTemplatePluginRejectionControl({ ...work, data });
5462
+ validateFlowTemplateStandardConditionEditorRules({ ...work, data });
4937
5463
  validateFlowTemplateCodeModeMessages({ ...work, data });
4938
5464
  validateFlowTemplateRuntimeScripts({ ...work, data });
4939
5465
  validateFlowTemplateFeishuChatPlugin({ ...work, data });
@@ -5022,13 +5548,108 @@ function normalizeDatasetPayload(work) {
5022
5548
  }
5023
5549
  return payload;
5024
5550
  }
5551
+ function firstNonEmpty(...values) {
5552
+ for (const value of values) {
5553
+ if (value === null || value === void 0) {
5554
+ continue;
5555
+ }
5556
+ const text5 = String(value).trim();
5557
+ if (text5 !== "") {
5558
+ return text5;
5559
+ }
5560
+ }
5561
+ return "";
5562
+ }
5563
+ function exactConfirmOrDryRun(confirm3, expectedConfirm, options = {}) {
5564
+ if (confirm3 === void 0 || confirm3 === "") {
5565
+ return false;
5566
+ }
5567
+ const accepted = [expectedConfirm, ...options.equivalentConfirms || []];
5568
+ if (accepted.includes(confirm3)) {
5569
+ return true;
5570
+ }
5571
+ throw new Error(`confirmation text mismatch. expected: ${expectedConfirm}. actual: ${confirm3}.`);
5572
+ }
5573
+ function configReadbackHint(domain, id) {
5574
+ if (id === void 0 || id === null || id === "") {
5575
+ return null;
5576
+ }
5577
+ const value = String(id);
5578
+ return {
5579
+ command: `bpmax-cli config ${domain} export --id ${value} --inline --format json`,
5580
+ unified_command: `bpmax-cli config readback ${domain} --id ${value} --format json`
5581
+ };
5582
+ }
5583
+ function configResponseKey(domain, payload, response, readback) {
5584
+ if (isRecord3(response)) {
5585
+ const key = response.key ?? response.field ?? response.custom_key;
5586
+ if (key !== void 0) return key;
5587
+ if (isRecord3(response.data)) {
5588
+ const nested = response.data.key ?? response.data.field ?? response.data.custom_key;
5589
+ if (nested !== void 0) return nested;
5590
+ }
5591
+ }
5592
+ if (isRecord3(readback)) {
5593
+ const key = readback.key ?? readback.field ?? readback.custom_key;
5594
+ if (key !== void 0) return key;
5595
+ }
5596
+ if (isRecord3(payload)) {
5597
+ if (domain === "dataset") return payload.custom_key ?? payload.customKey ?? null;
5598
+ return payload.key ?? payload.field ?? null;
5599
+ }
5600
+ return null;
5601
+ }
5602
+ function standardConfigWriteResponse(input) {
5603
+ const resolvedId = input.executedId ?? input.id;
5604
+ return {
5605
+ id: resolvedId,
5606
+ request_id: input.id,
5607
+ key: configResponseKey(input.domain, input.payload, input.response, input.readback),
5608
+ readback_hint: configReadbackHint(input.domain, resolvedId)
5609
+ };
5610
+ }
5611
+ function dryRunFields(expectedConfirm) {
5612
+ return {
5613
+ ok: true,
5614
+ dry_run: true,
5615
+ operation_executed: false,
5616
+ confirm_required: true,
5617
+ required_confirm: expectedConfirm,
5618
+ expected_confirm: expectedConfirm
5619
+ };
5620
+ }
5621
+ function executedFields() {
5622
+ return {
5623
+ ok: true,
5624
+ dry_run: false,
5625
+ operation_executed: true,
5626
+ confirm_required: false
5627
+ };
5628
+ }
5629
+ function validateDatasetFieldCreatePayload(payload) {
5630
+ if (!isRecord3(payload)) {
5631
+ throw new Error("dataset-field create requires an object payload.");
5632
+ }
5633
+ const missingSource = [
5634
+ ["payload.flow_type", payload.flow_type],
5635
+ ["payload.data_set_id", payload.data_set_id],
5636
+ ["payload.source_table", payload.source_table],
5637
+ ["payload.source_field", payload.source_field],
5638
+ ["payload.source_fk", payload.source_fk]
5639
+ ].filter(([, value]) => typeof value !== "string" || value.trim() === "");
5640
+ if (missingSource.length > 0) {
5641
+ throw new Error(`dataset-field create requires dataset and source mapping fields: ${missingSource.map(([key]) => key).join(", ")}.`);
5642
+ }
5643
+ }
5025
5644
  function normalizeDatasetFieldPayload(work) {
5026
5645
  const mode = work.mode;
5027
5646
  if (mode !== void 0 && mode !== "edit" && mode !== "create") {
5028
5647
  throw new Error("dataset-field typed adapter supports mode edit or create. Delete requires a dedicated adapter.");
5029
5648
  }
5030
5649
  const source = isRecord3(work.source) ? work.source : work;
5650
+ const sourcePayload = isRecord3(work.x_wewf_source_payload) ? work.x_wewf_source_payload : {};
5031
5651
  const payload = {
5652
+ data_set_id: firstNonEmpty(work.data_set_id, work.dataSetId, work.dataset_id, sourcePayload.data_set_id, sourcePayload.dataSetId, sourcePayload.dataset_id),
5032
5653
  name: work.name || "",
5033
5654
  key: work.key || work.field || "",
5034
5655
  type: work.type || "",
@@ -5056,14 +5677,7 @@ function normalizeDatasetFieldPayload(work) {
5056
5677
  payload.sourceField = payload.source_field;
5057
5678
  payload.sourceFk = payload.source_fk;
5058
5679
  if (mode === "create") {
5059
- const missingSource = [
5060
- ["source_table", payload.source_table],
5061
- ["source_field", payload.source_field],
5062
- ["source_fk", payload.source_fk]
5063
- ].filter(([, value]) => typeof value !== "string" || value.trim() === "");
5064
- if (missingSource.length > 0) {
5065
- throw new Error(`dataset-field create requires source mapping fields: ${missingSource.map(([key]) => key).join(", ")}.`);
5066
- }
5680
+ validateDatasetFieldCreatePayload(payload);
5067
5681
  }
5068
5682
  const advanced = isRecord3(work.advanced) ? work.advanced : {};
5069
5683
  if (Object.prototype.hasOwnProperty.call(advanced, "sourceComputed")) {
@@ -5438,6 +6052,118 @@ function validateFormTemplateValueValidateMaps(payload, errors) {
5438
6052
  }
5439
6053
  }
5440
6054
  }
6055
+ var FORM_TEMPLATE_VISUAL_WIDE_TYPES = /* @__PURE__ */ new Set([
6056
+ "sub_form",
6057
+ "i_textarea",
6058
+ "textarea",
6059
+ "rich_text",
6060
+ "editor",
6061
+ "upload",
6062
+ "file",
6063
+ "image",
6064
+ "images",
6065
+ "raw"
6066
+ ]);
6067
+ function shouldRunFormTemplateVisualLint(payload) {
6068
+ const lintHints = isRecord3(payload.lintHints) ? payload.lintHints : {};
6069
+ const visualReview = isRecord3(lintHints.visualReview) ? lintHints.visualReview : {};
6070
+ return visualReview.enabled === true || visualReview.required === true || payload.mode === "visual_review";
6071
+ }
6072
+ function formTemplateVisualReviewHints(payload) {
6073
+ const lintHints = isRecord3(payload.lintHints) ? payload.lintHints : {};
6074
+ return isRecord3(lintHints.visualReview) ? lintHints.visualReview : {};
6075
+ }
6076
+ function numericHint(value, fallback) {
6077
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
6078
+ }
6079
+ function formTemplateRuleTitle(rule, value) {
6080
+ const title = rule.title ?? value?.title ?? rule.label ?? value?.label;
6081
+ return typeof title === "string" ? title.trim() : "";
6082
+ }
6083
+ function formTemplateRuleWidth(rule) {
6084
+ const props = isRecord3(rule.props) ? rule.props : {};
6085
+ const candidates = [
6086
+ rule.span,
6087
+ rule.colSpan,
6088
+ rule.width,
6089
+ props.span,
6090
+ props.colSpan,
6091
+ props.width
6092
+ ];
6093
+ for (const candidate of candidates) {
6094
+ if (typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0) {
6095
+ return candidate;
6096
+ }
6097
+ if (typeof candidate === "string" && /^\d+$/.test(candidate.trim())) {
6098
+ return Number(candidate.trim());
6099
+ }
6100
+ }
6101
+ return void 0;
6102
+ }
6103
+ function validateStructuredFormTemplateVisualReview(payload, errors) {
6104
+ if (!shouldRunFormTemplateVisualLint(payload)) {
6105
+ return;
6106
+ }
6107
+ const hints = formTemplateVisualReviewHints(payload);
6108
+ if (hints.confirmedNonBehavioralProps !== true) {
6109
+ errors.push(
6110
+ "form-template visual lint requires lintHints.visualReview.confirmedNonBehavioralProps=true after confirming the diff only changes layout, label/control width, spacing, or other non-behavioral display props."
6111
+ );
6112
+ }
6113
+ if (!Array.isArray(payload.layout) || !isRecord3(payload.fields)) {
6114
+ errors.push("form-template visual lint requires structured work with layout and fields.");
6115
+ return;
6116
+ }
6117
+ const maxColumnsPerRow = Math.floor(numericHint(hints.maxColumnsPerRow, 2));
6118
+ const maxRowTitleChars = Math.floor(numericHint(hints.maxRowTitleChars, 24));
6119
+ const maxTitleCharsInMultiColumn = Math.floor(numericHint(hints.maxTitleCharsInMultiColumn, 12));
6120
+ for (const [rowIndex, row] of payload.layout.entries()) {
6121
+ if (!Array.isArray(row)) {
6122
+ errors.push(`form-template visual lint layout row ${rowIndex} must be an array.`);
6123
+ continue;
6124
+ }
6125
+ if (!row.length) {
6126
+ errors.push(`form-template visual lint layout row ${rowIndex} is empty; remove empty visual rows before submit.`);
6127
+ continue;
6128
+ }
6129
+ if (row.length > maxColumnsPerRow) {
6130
+ errors.push(`form-template visual lint layout row ${rowIndex} has ${row.length} fields; maxColumnsPerRow=${maxColumnsPerRow} for readable desktop data entry.`);
6131
+ }
6132
+ let rowTitleChars = 0;
6133
+ for (const ref of row) {
6134
+ if (typeof ref !== "string" || !ref) {
6135
+ continue;
6136
+ }
6137
+ const bundle = payload.fields[ref];
6138
+ if (!isRecord3(bundle) || !isRecord3(bundle.rule)) {
6139
+ continue;
6140
+ }
6141
+ const value = isRecord3(bundle.value) ? bundle.value : void 0;
6142
+ const rule = bundle.rule;
6143
+ const title = formTemplateRuleTitle(rule, value);
6144
+ rowTitleChars += title.length;
6145
+ const type = typeof rule.type === "string" ? rule.type : typeof value?.field_type === "string" ? value.field_type : "";
6146
+ if (row.length > 1 && FORM_TEMPLATE_VISUAL_WIDE_TYPES.has(type)) {
6147
+ errors.push(`form-template visual lint field ${ref} (${title || type}) type=${type} must be in a single-field row for readable editing.`);
6148
+ }
6149
+ if (row.length > 1 && title.length > maxTitleCharsInMultiColumn) {
6150
+ errors.push(`form-template visual lint field ${ref} title is too long for a multi-column row (${title.length} > ${maxTitleCharsInMultiColumn}); move it to a single row or shorten the visible label.`);
6151
+ }
6152
+ const width = formTemplateRuleWidth(rule);
6153
+ if (row.length > 1 && typeof width === "number" && width > 12) {
6154
+ errors.push(`form-template visual lint field ${ref} declares width/span=${width} inside a multi-column row; wide controls must be single-row or use <=12 grid width.`);
6155
+ }
6156
+ }
6157
+ if (row.length > 1 && rowTitleChars > maxRowTitleChars) {
6158
+ errors.push(`form-template visual lint layout row ${rowIndex} title length total is ${rowTitleChars}; maxRowTitleChars=${maxRowTitleChars}. Split the row for readability.`);
6159
+ }
6160
+ }
6161
+ }
6162
+ function validateFormTemplateWorkLint(payload, errors) {
6163
+ validateFormTemplateNameLength(payload, errors);
6164
+ validateFormTemplateValueValidateMaps(payload, errors);
6165
+ validateStructuredFormTemplateVisualReview(payload, errors);
6166
+ }
5441
6167
  function stripFormTemplateCreateIds(payload) {
5442
6168
  const next = { ...payload };
5443
6169
  if (Array.isArray(next.rule)) {
@@ -6609,6 +7335,10 @@ async function createFlowTemplateFromWork(config, profile, workFile, confirm3, o
6609
7335
  validateFlowTemplateRemoteTemplateRefs(work);
6610
7336
  validateFlowTemplateProjectAfterCreatePath(work);
6611
7337
  validateFlowTemplateStandardPageCreateFormTemplate(work);
7338
+ validateFlowTemplateStartConditionalJump(work);
7339
+ validateFlowTemplateApproveActionShape(work);
7340
+ validateFlowTemplatePluginRejectionControl(work);
7341
+ validateFlowTemplateStandardConditionEditorRules(work);
6612
7342
  validateFlowTemplateCodeModeMessages(work);
6613
7343
  validateFlowTemplateRuntimeScripts(work);
6614
7344
  validateFlowTemplateFeishuChatPlugin(work);
@@ -6745,6 +7475,7 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6745
7475
  }
6746
7476
  };
6747
7477
  const expectedConfirm = `create flow-app ${name} in ${workspace}`;
7478
+ const acceptedConfirmWithWorkspacePrefix = `create flow-app ${name} in w:${workspace}`;
6748
7479
  const dryRunPlan = {
6749
7480
  operations: [
6750
7481
  { step: "create_form_template", method: "POST", path: "/form_template", payload: formPayload },
@@ -6756,9 +7487,10 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6756
7487
  { step: "verify_workspace_binding", method: "GET", path: "/workspace/by_key", params: { key: workspace } }
6757
7488
  ]
6758
7489
  };
6759
- if (confirm3 !== expectedConfirm) {
7490
+ if (!exactConfirmOrDryRun(confirm3, expectedConfirm, { equivalentConfirms: [acceptedConfirmWithWorkspacePrefix] })) {
6760
7491
  return {
6761
- dry_run: true,
7492
+ ...dryRunFields(expectedConfirm),
7493
+ accepted_confirms: [expectedConfirm, acceptedConfirmWithWorkspacePrefix],
6762
7494
  domain: "flow-app",
6763
7495
  workspace,
6764
7496
  name,
@@ -6849,9 +7581,22 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6849
7581
  "/workspace/by_key",
6850
7582
  { params: { key: workspace }, capability: `${workspaceDefinition.capability}.export` }
6851
7583
  );
7584
+ const workspaceBaseHash = hashJson(workspaceInfo);
6852
7585
  const existingBindings = isRecord3(workspaceInfo) ? normalizeWorkspaceFlowItems(workspaceInfo.workspace_flow) : [];
6853
7586
  const bindingKey = buildWorkspaceFlowBindingKey(flowType, "");
6854
7587
  const nextBindings = existingBindings.some((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key) === bindingKey) ? existingBindings : [...existingBindings, { flow_type: flowType, flow_key: "", only_in_workspace: 0 }];
7588
+ const workspaceGuardReadback = await apiRequest(
7589
+ client,
7590
+ "GET",
7591
+ "/workspace/by_key",
7592
+ { params: { key: workspace }, capability: `${workspaceDefinition.capability}.export` }
7593
+ );
7594
+ const workspaceGuardHash = hashJson(workspaceGuardReadback);
7595
+ if (workspaceGuardHash !== workspaceBaseHash) {
7596
+ throw new Error(
7597
+ `flow-app create workspace-flow baseline changed for ${workspace}. Re-run flow-app context or workspace-flow export, merge the latest bindings, and retry to avoid dropping concurrent workspace bindings.`
7598
+ );
7599
+ }
6855
7600
  const workspaceBindResponse = await apiRequest(
6856
7601
  client,
6857
7602
  "PUT",
@@ -6869,21 +7614,48 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6869
7614
  if (!readbackBindings.some((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key) === bindingKey)) {
6870
7615
  throw new Error(`flow-app create workspace binding verification failed for ${workspace} ${bindingKey}.`);
6871
7616
  }
7617
+ const flowTemplateId = isRecord3(flowCreateResponse) ? isRecord3(flowCreateResponse.data) ? flowCreateResponse.data.id : flowCreateResponse.id : null;
7618
+ const evidence = {
7619
+ flow_type: flowType,
7620
+ flow_key: "",
7621
+ flow_template_id: flowTemplateId ?? flowType,
7622
+ form_template_id: publishedFormId,
7623
+ form_template_draft_id: draftFormId,
7624
+ workspace_key: workspace,
7625
+ workspace_binding_found: true,
7626
+ workspace_readback_hash: hashJson(workspaceReadback),
7627
+ evidence_status: "verified",
7628
+ verified_at: (/* @__PURE__ */ new Date()).toISOString()
7629
+ };
6872
7630
  return {
6873
- dry_run: false,
7631
+ ...executedFields(),
6874
7632
  domain: "flow-app",
6875
7633
  workspace,
6876
7634
  name,
7635
+ created_ids: {
7636
+ draft_form_id: draftFormId,
7637
+ published_form_id: publishedFormId,
7638
+ form_template_id: publishedFormId,
7639
+ form_template_draft_id: draftFormId,
7640
+ flow_type: flowType,
7641
+ flow_template_id: flowTemplateId ?? flowType,
7642
+ workspace
7643
+ },
6877
7644
  draft_form_id: draftFormId,
6878
7645
  published_form_id: publishedFormId,
7646
+ form_template_id: publishedFormId,
7647
+ form_template_draft_id: draftFormId,
6879
7648
  flow_type: flowType,
7649
+ flow_key: "",
7650
+ flow_template_id: flowTemplateId ?? flowType,
6880
7651
  form_response: formResponse,
6881
7652
  form_publish_response: formPublishResponse,
6882
7653
  flow_create_response: flowCreateResponse,
6883
7654
  flow_draft_response: flowDraftResponse,
6884
7655
  ...liveEndpoint ? { flow_live_response: flowLiveResponse, live_endpoint: liveEndpoint } : {},
6885
7656
  workspace_bind_response: workspaceBindResponse,
6886
- workspace_readback_hash: hashJson(workspaceReadback)
7657
+ workspace_readback_hash: hashJson(workspaceReadback),
7658
+ evidence
6887
7659
  };
6888
7660
  } catch (error) {
6889
7661
  const message = error instanceof Error ? error.message : String(error || "");
@@ -6900,6 +7672,115 @@ async function readBackConfigDomain(profile, domain, id, definition) {
6900
7672
  readback_hash: hashJson(data)
6901
7673
  };
6902
7674
  }
7675
+ async function readbackConfigDomain(config, profile, domain, id) {
7676
+ void config;
7677
+ const definition = CONFIG_DOMAINS[domain];
7678
+ if (!definition) {
7679
+ throw new Error(`Unknown config domain: ${domain}`);
7680
+ }
7681
+ const data = await readRemoteConfigDomain(profile, domain, id, definition);
7682
+ validateExpectedType(domain, definition, data);
7683
+ return {
7684
+ domain,
7685
+ id,
7686
+ readback_hash: hashJson(data),
7687
+ source_api: definition.exportPath ? `GET /api${definition.exportPath(id)}` : null,
7688
+ verified_at: (/* @__PURE__ */ new Date()).toISOString(),
7689
+ readback: data
7690
+ };
7691
+ }
7692
+ async function resolveFlowAppContextFlowId(profile, flow) {
7693
+ const trimmed = flow.trim();
7694
+ if (!trimmed) {
7695
+ throw new Error("flow-app context requires --flow <flow_type|flow_type:key|key:<key>|name>.");
7696
+ }
7697
+ if (/^flow\d+$/.test(trimmed) || trimmed.startsWith("flow_type:") || trimmed.startsWith("key:") || trimmed.includes("|") || trimmed.includes(":")) {
7698
+ return { id: trimmed, resolvedBy: "flow_id" };
7699
+ }
7700
+ const client = createApiClient(profile);
7701
+ const options = await apiRequest(client, "GET", "/flow/options", { capability: "flow.options" });
7702
+ const rows = extractListData(options);
7703
+ const matches = rows.filter((item) => String(item.name || item.title || "").trim() === trimmed);
7704
+ if (matches.length !== 1) {
7705
+ throw new Error(
7706
+ `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.`
7707
+ );
7708
+ }
7709
+ const match = matches[0];
7710
+ const flowType = firstNonEmpty(match.flow_type, match.flowType);
7711
+ const flowKey = firstNonEmpty(match.key, match.flow_key, match.flowKey);
7712
+ if (flowKey && flowType) {
7713
+ return { id: `${flowType}:${flowKey}`, resolvedBy: "flow_options_name" };
7714
+ }
7715
+ if (flowKey) {
7716
+ return { id: `key:${flowKey}`, resolvedBy: "flow_options_name" };
7717
+ }
7718
+ if (flowType) {
7719
+ return { id: flowType, resolvedBy: "flow_options_name" };
7720
+ }
7721
+ throw new Error(`flow-app context resolved flow name "${trimmed}" but the option row did not include flow_type or key.`);
7722
+ }
7723
+ async function inspectFlowAppContext(config, profile, options) {
7724
+ void config;
7725
+ const flowDefinition = CONFIG_DOMAINS["flow-template"];
7726
+ const formDefinition = CONFIG_DOMAINS["form-template"];
7727
+ const workspaceDefinition = CONFIG_DOMAINS["workspace-flow"];
7728
+ await ensureConfigCapability(profile, `${flowDefinition.capability}.export`);
7729
+ await ensureConfigCapability(profile, `${formDefinition.capability}.export`);
7730
+ await ensureConfigCapability(profile, `${workspaceDefinition.capability}.export`);
7731
+ const workspace = normalizeWorkspaceKey(options.workspace || profile.config.workspace);
7732
+ if (!workspace) {
7733
+ throw new Error("flow-app context requires --workspace <workspace>.");
7734
+ }
7735
+ const resolvedFlow = await resolveFlowAppContextFlowId(profile, options.flow);
7736
+ const flowReadback = await readRemoteConfigDomain(profile, "flow-template", resolvedFlow.id, flowDefinition);
7737
+ const flow = isRecord3(flowReadback) ? flowReadback : {};
7738
+ const data = isRecord3(flow.data) ? flow.data : {};
7739
+ const meta = isRecord3(data.meta) ? data.meta : {};
7740
+ const formTemplateId = firstNonEmpty(meta.form_template, meta.formTemplate, flow.meta_form_id, flow.metaFormId);
7741
+ let formReadback = null;
7742
+ let formTemplateDraftId = null;
7743
+ if (formTemplateId) {
7744
+ formReadback = await readRemoteConfigDomain(profile, "form-template", String(formTemplateId), formDefinition);
7745
+ if (isRecord3(formReadback)) {
7746
+ const originTemplateId = formReadback.origin_template_id ?? formReadback.originTemplateId;
7747
+ formTemplateDraftId = originTemplateId && String(originTemplateId) !== "0" ? originTemplateId : formReadback.id ?? formTemplateId;
7748
+ }
7749
+ }
7750
+ const workspaceReadback = await readRemoteConfigDomain(profile, "workspace-flow", workspace, workspaceDefinition);
7751
+ const bindings = isRecord3(workspaceReadback) ? normalizeWorkspaceFlowItems(workspaceReadback.workspace_flow) : [];
7752
+ const parsedIdentity = parseFlowIdentity(resolvedFlow.id);
7753
+ const flowType = firstNonEmpty(flow.flow_type, parsedIdentity.flowType);
7754
+ const flowKey = firstNonEmpty(flow.key, parsedIdentity.flowKey);
7755
+ const bindingFound = bindings.some((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key) === buildWorkspaceFlowBindingKey(flowType, flowKey));
7756
+ const evidence = flowAppContextEvidence({
7757
+ workspace,
7758
+ flow,
7759
+ flowId: resolvedFlow.id,
7760
+ formTemplateId: formTemplateId || null,
7761
+ formTemplateDraftId,
7762
+ formReadback,
7763
+ workspaceReadback,
7764
+ bindingFound,
7765
+ resolvedBy: resolvedFlow.resolvedBy
7766
+ });
7767
+ return {
7768
+ domain: "flow-app",
7769
+ workspace,
7770
+ flow: options.flow,
7771
+ target_context: evidence,
7772
+ evidence,
7773
+ source: {
7774
+ flow: flowExportPath(resolvedFlow.id),
7775
+ form_template: formTemplateId ? `/form_template/${formTemplateId}` : null,
7776
+ workspace: workspaceDefinition.exportPath ? workspaceDefinition.exportPath(workspace) : null
7777
+ },
7778
+ recommended_next_commands: evidence.missing_context.length ? [
7779
+ "If form_template_id is missing, inspect the flow data.meta.form_template and publish the form binding first.",
7780
+ "If workspace_binding is missing, rebuild workspace-flow from fresh export and submit the merged binding."
7781
+ ] : []
7782
+ };
7783
+ }
6903
7784
  function comparableSubmitPayload(domain, value, options) {
6904
7785
  const comparable2 = domain === "form-template" && options.ignoreServerFields ? stripServerFilledFields(value, FORM_TEMPLATE_SERVER_FIELD_KEYS) : value;
6905
7786
  return buildDomainSubmitPayload(domain, comparable2);
@@ -7261,7 +8142,7 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
7261
8142
  }
7262
8143
  if (domain === "form-template" && isRecord3(work)) {
7263
8144
  const errors = [];
7264
- validateFormTemplateValueValidateMaps(work, errors);
8145
+ validateFormTemplateWorkLint(work, errors);
7265
8146
  if (errors.length) {
7266
8147
  throw new Error(`form-template lint failed: ${errors.join("; ")}`);
7267
8148
  }
@@ -7340,8 +8221,7 @@ async function lintConfigWorkFile(file, options = {}) {
7340
8221
  }
7341
8222
  const shouldLintFormTemplate = options.domain ? options.domain === "form-template" : looksLikeFormTemplateWork(value);
7342
8223
  if (shouldLintFormTemplate) {
7343
- validateFormTemplateNameLength(value, errors);
7344
- validateFormTemplateValueValidateMaps(value, errors);
8224
+ validateFormTemplateWorkLint(value, errors);
7345
8225
  }
7346
8226
  if ((Object.prototype.hasOwnProperty.call(value, "content") || isRecord3(value.basic)) && pageTemplateType(value) === 1) {
7347
8227
  validateListTemplateActionGate(value, errors);
@@ -7354,6 +8234,10 @@ async function lintConfigWorkFile(file, options = {}) {
7354
8234
  validateFlowTemplateRemoteTemplateRefs(flowWork, errors);
7355
8235
  validateFlowTemplateProjectAfterCreatePath(flowWork, errors);
7356
8236
  validateFlowTemplateStandardPageCreateFormTemplate(flowWork, errors);
8237
+ validateFlowTemplateStartConditionalJump(flowWork, errors);
8238
+ validateFlowTemplateApproveActionShape(flowWork, errors);
8239
+ validateFlowTemplatePluginRejectionControl(flowWork, errors);
8240
+ validateFlowTemplateStandardConditionEditorRules(flowWork, errors);
7357
8241
  validateFlowTemplateCodeModeMessages(flowWork, errors);
7358
8242
  validateFlowTemplateRuntimeScripts(flowWork, errors);
7359
8243
  validateFlowTemplateFeishuChatPlugin(flowWork, errors);
@@ -7425,7 +8309,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7425
8309
  const expectedConfirm2 = `submit ${domain} ${id}`;
7426
8310
  if (confirm3 !== expectedConfirm2) {
7427
8311
  return {
7428
- dry_run: true,
8312
+ ...dryRunFields(expectedConfirm2),
7429
8313
  domain,
7430
8314
  id,
7431
8315
  endpoint: endpoint2,
@@ -7455,7 +8339,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7455
8339
  throw new Error(`workspace-flow submit verification failed; missing bindings: ${missingBindings.map((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key)).join(", ")}`);
7456
8340
  }
7457
8341
  return {
7458
- dry_run: false,
8342
+ ...executedFields(),
7459
8343
  domain,
7460
8344
  id,
7461
8345
  endpoint: endpoint2,
@@ -7493,7 +8377,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7493
8377
  await ensureConfigCapability(profile, `${definition.capability}.export`);
7494
8378
  if (confirm3 !== expectedConfirm2) {
7495
8379
  return {
7496
- dry_run: true,
8380
+ ...dryRunFields(expectedConfirm2),
7497
8381
  domain,
7498
8382
  id,
7499
8383
  endpoint: "/workspace",
@@ -7509,14 +8393,15 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7509
8393
  { data: submit2.payload, capability: `${definition.capability}.create` }
7510
8394
  );
7511
8395
  const readback3 = await readRemoteConfigDomain(profile, domain, `key:${workspaceKey}`, definition);
8396
+ const createdId = responseDataId(response3) ?? (isRecord3(readback3) ? readback3.id ?? null : null);
7512
8397
  return {
7513
- dry_run: false,
8398
+ ...executedFields(),
7514
8399
  domain,
7515
- id,
8400
+ ...standardConfigWriteResponse({ domain, id, executedId: createdId, payload: submit2.payload, response: response3, readback: readback3 }),
7516
8401
  endpoint: "/workspace",
7517
8402
  method: "POST",
7518
8403
  response: response3,
7519
- created_id: responseDataId(response3) ?? (isRecord3(readback3) ? readback3.id ?? null : null),
8404
+ created_id: createdId,
7520
8405
  readback_hash: hashJson(readback3)
7521
8406
  };
7522
8407
  }
@@ -7537,7 +8422,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7537
8422
  const endpoint2 = `/workspace/${encodeURIComponent(workspaceId)}`;
7538
8423
  if (confirm3 !== expectedConfirm2) {
7539
8424
  return {
7540
- dry_run: true,
8425
+ ...dryRunFields(expectedConfirm2),
7541
8426
  domain,
7542
8427
  id,
7543
8428
  endpoint: endpoint2,
@@ -7556,9 +8441,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7556
8441
  );
7557
8442
  const readback2 = await readRemoteConfigDomain(profile, domain, workspaceKey ? `key:${workspaceKey}` : workspaceId, definition);
7558
8443
  return {
7559
- dry_run: false,
8444
+ ...executedFields(),
7560
8445
  domain,
7561
- id,
8446
+ ...standardConfigWriteResponse({ domain, id, payload: submit2.payload, response: response2, readback: readback2 }),
7562
8447
  endpoint: endpoint2,
7563
8448
  method: "PUT",
7564
8449
  response: response2,
@@ -7608,7 +8493,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7608
8493
  }
7609
8494
  if (confirm3 !== expectedConfirm2) {
7610
8495
  return {
7611
- dry_run: true,
8496
+ ...dryRunFields(expectedConfirm2),
7612
8497
  domain,
7613
8498
  id,
7614
8499
  operation_plan: submit2.payload,
@@ -7618,7 +8503,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7618
8503
  };
7619
8504
  }
7620
8505
  return {
7621
- dry_run: false,
8506
+ ...executedFields(),
7622
8507
  domain,
7623
8508
  id,
7624
8509
  ...domain === "role" ? await submitRoleOperations(profile, id, submit2) : await submitAggregateConfigDomain(profile, domain, id, submit2)
@@ -7655,11 +8540,14 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7655
8540
  if (domain === "list-template") {
7656
8541
  validateListTemplateActionGate(submit.payload);
7657
8542
  }
8543
+ if (domain === "dataset-field") {
8544
+ validateDatasetFieldCreatePayload(submit.payload);
8545
+ }
7658
8546
  await ensureConfigCapability(profile, `${definition.capability}.create`);
7659
8547
  const expectedConfirm2 = `submit ${domain} ${id}`;
7660
8548
  if (confirm3 !== expectedConfirm2) {
7661
8549
  return {
7662
- dry_run: true,
8550
+ ...dryRunFields(expectedConfirm2),
7663
8551
  domain,
7664
8552
  id,
7665
8553
  endpoint: definition.createPath,
@@ -7686,9 +8574,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7686
8574
  }
7687
8575
  }
7688
8576
  return {
7689
- dry_run: false,
8577
+ ...executedFields(),
7690
8578
  domain,
7691
- id,
8579
+ ...standardConfigWriteResponse({ domain, id, executedId: createdId ?? null, payload: submit.payload, response: response2 }),
7692
8580
  created_id: createdId ?? null,
7693
8581
  endpoint: definition.createPath,
7694
8582
  method: definition.createMethod,
@@ -7702,6 +8590,10 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7702
8590
  validateFlowTemplateRemoteTemplateRefs(submit.payload);
7703
8591
  validateFlowTemplateProjectAfterCreatePath(submit.payload);
7704
8592
  validateFlowTemplateStandardPageCreateFormTemplate(submit.payload);
8593
+ validateFlowTemplateStartConditionalJump(submit.payload);
8594
+ validateFlowTemplateApproveActionShape(submit.payload);
8595
+ validateFlowTemplatePluginRejectionControl(submit.payload);
8596
+ validateFlowTemplateStandardConditionEditorRules(submit.payload);
7705
8597
  validateFlowTemplateCodeModeMessages(submit.payload);
7706
8598
  validateFlowTemplateRuntimeScripts(submit.payload);
7707
8599
  validateFlowTemplateFeishuChatPlugin(submit.payload);
@@ -7725,7 +8617,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7725
8617
  const endpoint2 = "/form_template";
7726
8618
  if (confirm3 !== expectedConfirm2) {
7727
8619
  return {
7728
- dry_run: true,
8620
+ ...dryRunFields(expectedConfirm2),
7729
8621
  domain,
7730
8622
  id,
7731
8623
  endpoint: endpoint2,
@@ -7766,9 +8658,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7766
8658
  { capability: `${definition.capability}.export` }
7767
8659
  );
7768
8660
  return {
7769
- dry_run: false,
8661
+ ...executedFields(),
7770
8662
  domain,
7771
- id,
8663
+ ...standardConfigWriteResponse({ domain, id, executedId: publishedId, payload: submit.payload, response: publishResponse2, readback: publishedReadback }),
7772
8664
  endpoint: endpoint2,
7773
8665
  method: "POST",
7774
8666
  response: response2,
@@ -7810,7 +8702,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7810
8702
  }
7811
8703
  if (confirm3 !== expectedConfirm) {
7812
8704
  return {
7813
- dry_run: true,
8705
+ ...dryRunFields(expectedConfirm),
7814
8706
  domain,
7815
8707
  id,
7816
8708
  endpoint,
@@ -7840,9 +8732,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7840
8732
  }
7841
8733
  const readback = await readBackConfigDomain(profile, domain, id, definition);
7842
8734
  return {
7843
- dry_run: false,
8735
+ ...executedFields(),
7844
8736
  domain,
7845
- id,
8737
+ ...standardConfigWriteResponse({ domain, id, payload: submitPayload, response }),
7846
8738
  endpoint,
7847
8739
  method: definition.submitMethod,
7848
8740
  ...publishMode ? { publish_mode: publishMode } : {},
@@ -7936,7 +8828,7 @@ async function runDatasetLifecycleAction(config, profile, action, id, confirm3)
7936
8828
  ];
7937
8829
  if (confirm3 !== expectedConfirm) {
7938
8830
  return {
7939
- dry_run: true,
8831
+ ...dryRunFields(expectedConfirm),
7940
8832
  domain: "dataset",
7941
8833
  id,
7942
8834
  action: commandAction,
@@ -7962,15 +8854,186 @@ async function runDatasetLifecycleAction(config, profile, action, id, confirm3)
7962
8854
  }
7963
8855
  const readback = await readRemoteConfigDomain(profile, "dataset", id, definition);
7964
8856
  return {
7965
- dry_run: false,
8857
+ ...executedFields(),
7966
8858
  domain: "dataset",
7967
8859
  id,
7968
8860
  action: commandAction,
7969
8861
  operations: executableOperations,
7970
8862
  operation_responses: responses,
8863
+ readback_hash: hashJson(readback),
8864
+ readback_hint: configReadbackHint("dataset", id),
7971
8865
  readback
7972
8866
  };
7973
8867
  }
8868
+ function normalizeConfigBatchItems(manifest) {
8869
+ if (Array.isArray(manifest)) {
8870
+ return manifest.map((raw) => ({ raw, item: isRecord3(raw) ? raw : null }));
8871
+ }
8872
+ if (!isRecord3(manifest)) {
8873
+ throw new Error("config batch manifest must be a JSON object or array.");
8874
+ }
8875
+ const items = manifest.operations ?? manifest.items ?? manifest.rows;
8876
+ if (!Array.isArray(items)) {
8877
+ throw new Error("config batch manifest requires operations, items, or rows array.");
8878
+ }
8879
+ return items.map((raw) => ({ raw, item: isRecord3(raw) ? raw : null }));
8880
+ }
8881
+ function assertBatchItemDomain(domain) {
8882
+ if (typeof domain !== "string" || !Object.prototype.hasOwnProperty.call(CONFIG_DOMAINS, domain)) {
8883
+ throw new Error(`config batch item requires a supported domain, got ${String(domain)}.`);
8884
+ }
8885
+ return domain;
8886
+ }
8887
+ async function writeOptionalBatchResponse(file, value) {
8888
+ if (typeof file !== "string" || !file.trim()) {
8889
+ return null;
8890
+ }
8891
+ await writeJsonFile(file, value);
8892
+ return file;
8893
+ }
8894
+ async function runConfigBatchSubmit(config, profile, manifestFile, options = {}) {
8895
+ const manifest = await readJsonFile(manifestFile);
8896
+ const items = normalizeConfigBatchItems(manifest);
8897
+ const results = [];
8898
+ for (let index = 0; index < items.length; index += 1) {
8899
+ const batchItem = items[index];
8900
+ const item = batchItem.item;
8901
+ if (!item) {
8902
+ const result = {
8903
+ ok: false,
8904
+ index,
8905
+ domain: null,
8906
+ id: "",
8907
+ action: "submit",
8908
+ error: "config batch submit item must be a JSON object."
8909
+ };
8910
+ results.push(result);
8911
+ if (!options.continueOnError) break;
8912
+ continue;
8913
+ }
8914
+ let domain = null;
8915
+ let id = "";
8916
+ try {
8917
+ domain = assertBatchItemDomain(item.domain);
8918
+ id = typeof item.id === "string" ? item.id : "";
8919
+ const payload = typeof item.payload === "string" ? item.payload : "";
8920
+ if (!id || !payload) {
8921
+ throw new Error("config batch submit item requires id and payload.");
8922
+ }
8923
+ const response = await submitConfigDomain(config, profile, domain, id, payload, item.confirm);
8924
+ const executed = !isRecord3(response) || response.operation_executed !== false && response.dry_run !== true;
8925
+ const result = executed ? {
8926
+ ok: true,
8927
+ index,
8928
+ domain,
8929
+ id,
8930
+ action: "submit",
8931
+ response
8932
+ } : {
8933
+ ok: false,
8934
+ index,
8935
+ domain,
8936
+ id,
8937
+ action: "submit",
8938
+ error: `config batch submit item did not execute; confirm_required=${String(isRecord3(response) ? response.required_confirm ?? response.expected_confirm ?? "" : "")}`,
8939
+ response
8940
+ };
8941
+ results.push(result);
8942
+ await writeOptionalBatchResponse(item.response_out, result);
8943
+ if (!result.ok && !options.continueOnError) break;
8944
+ } catch (error) {
8945
+ const result = {
8946
+ ok: false,
8947
+ index,
8948
+ domain,
8949
+ id,
8950
+ action: "submit",
8951
+ error: error instanceof Error ? error.message : String(error || "")
8952
+ };
8953
+ results.push(result);
8954
+ await writeOptionalBatchResponse(item.response_out, result);
8955
+ if (!options.continueOnError) break;
8956
+ }
8957
+ }
8958
+ const failures = results.filter((item) => item.ok === false);
8959
+ return {
8960
+ ok: failures.length === 0,
8961
+ manifest_file: manifestFile,
8962
+ action: "submit",
8963
+ continue_on_error: Boolean(options.continueOnError),
8964
+ total: items.length,
8965
+ completed: results.length,
8966
+ succeeded: results.length - failures.length,
8967
+ failed: failures.length,
8968
+ results
8969
+ };
8970
+ }
8971
+ async function runConfigBatchReadback(config, profile, manifestFile, options = {}) {
8972
+ const manifest = await readJsonFile(manifestFile);
8973
+ const items = normalizeConfigBatchItems(manifest);
8974
+ const results = [];
8975
+ for (let index = 0; index < items.length; index += 1) {
8976
+ const batchItem = items[index];
8977
+ const item = batchItem.item;
8978
+ if (!item) {
8979
+ const result = {
8980
+ ok: false,
8981
+ index,
8982
+ domain: null,
8983
+ id: "",
8984
+ action: "readback",
8985
+ error: "config batch readback item must be a JSON object."
8986
+ };
8987
+ results.push(result);
8988
+ if (!options.continueOnError) break;
8989
+ continue;
8990
+ }
8991
+ let domain = null;
8992
+ let id = "";
8993
+ try {
8994
+ domain = assertBatchItemDomain(item.domain);
8995
+ id = typeof item.id === "string" ? item.id : "";
8996
+ if (!id) {
8997
+ throw new Error("config batch readback item requires id.");
8998
+ }
8999
+ const response = await readbackConfigDomain(config, profile, domain, id);
9000
+ const result = {
9001
+ ok: true,
9002
+ index,
9003
+ domain,
9004
+ id,
9005
+ action: "readback",
9006
+ response
9007
+ };
9008
+ results.push(result);
9009
+ await writeOptionalBatchResponse(item.response_out, result);
9010
+ } catch (error) {
9011
+ const result = {
9012
+ ok: false,
9013
+ index,
9014
+ domain,
9015
+ id,
9016
+ action: "readback",
9017
+ error: error instanceof Error ? error.message : String(error || "")
9018
+ };
9019
+ results.push(result);
9020
+ await writeOptionalBatchResponse(item.response_out, result);
9021
+ if (!options.continueOnError) break;
9022
+ }
9023
+ }
9024
+ const failures = results.filter((item) => item.ok === false);
9025
+ return {
9026
+ ok: failures.length === 0,
9027
+ manifest_file: manifestFile,
9028
+ action: "readback",
9029
+ continue_on_error: Boolean(options.continueOnError),
9030
+ total: items.length,
9031
+ completed: results.length,
9032
+ succeeded: results.length - failures.length,
9033
+ failed: failures.length,
9034
+ results
9035
+ };
9036
+ }
7974
9037
 
7975
9038
  // src/core/config-workspace.ts
7976
9039
  import { mkdir as mkdir6, readFile as readFile9, writeFile as writeFile6 } from "fs/promises";
@@ -8067,6 +9130,7 @@ ${configEnabled ? "" : "> \u5F53\u524D profile \u7684 API Key \u5C1A\u672A\u5F00
8067
9130
  ${directoryRows}
8068
9131
 
8069
9132
  ## \u5F3A\u5236\u89C4\u5219
9133
+ - \u5F53\u524D\u76EE\u5F55\u7ED1\u5B9A Profile\uFF1A\`${display(options.profileName)}\`\u3002\u5728\u5F53\u524D\u76EE\u5F55\u6267\u884C\u7684\u6240\u6709 \`bpmax-cli\` \u547D\u4EE4\u90FD\u5FC5\u987B\u663E\u5F0F\u4F7F\u7528 \`--profile ${profileArg}\`\uFF1B\u4E0D\u5F97\u7701\u7565 profile\u3001\u4E0D\u5F97\u4F9D\u8D56\u5168\u5C40 \`current_profile\`\uFF0C\u4E5F\u4E0D\u5F97\u5207\u6362\u5230\u5176\u5B83\u73AF\u5883/profile\u3002
8070
9134
  - \u914D\u7F6E\u5199\u64CD\u4F5C\u53EA\u80FD\u4F7F\u7528 typed CLI\uFF1A\`${commandPrefix3} config <domain> submit\`\uFF1B\u63D2\u4EF6\u914D\u7F6E\u53EA\u80FD\u4F7F\u7528 \`${commandPrefix3} config plugin <domain> submit\`\u3002
8071
9135
  - \u5982\u679C CLI \u63D0\u793A\u7F3A\u5C11 capability\u3001\u5F53\u524D profile \u672A\u5F00\u542F\u914D\u7F6E\u80FD\u529B\uFF0C\u6216\u672A\u6765\u65B0\u589E domain \u5C1A\u672A\u8FDB\u5165 adapter \u77E9\u9635 / \`config plugin adapters\`\uFF0C\u5FC5\u987B\u505C\u6B62\u8FDC\u7AEF\u5199\u5165\uFF1B\u4E0D\u5F97\u624B\u5199 raw API\u3002
8072
9136
  - \u7981\u6B62\u7528 \`bpmax-cli api\`\u3001curl\u3001\u9875\u9762 fetch\u3001\u9875\u9762 axios \u6216\u65E7 submit \u811A\u672C\u76F4\u63A5\u5199\u914D\u7F6E\u3002
@@ -8086,10 +9150,10 @@ ${rows}
8086
9150
  ## \u6807\u51C6\u95ED\u73AF
8087
9151
  \`\`\`bash
8088
9152
  ${commandPrefix3} config <domain> export --id <id> --profile ${profileArg}
8089
- ${commandPrefix3} config <domain> lint --work <work-file>
9153
+ ${commandPrefix3} config <domain> lint --work <work-file> --profile ${profileArg}
8090
9154
  # build/submit must use typed CLI and an enabled config capability.
8091
9155
  # If capability is missing or the domain is not listed by config adapters, stop before remote writes.
8092
- ${commandPrefix3} config <domain> build --work <work-file> --meta <meta-file> --out <submit-file>
9156
+ ${commandPrefix3} config <domain> build --work <work-file> --meta <meta-file> --out <submit-file> --profile ${profileArg}
8093
9157
  ${commandPrefix3} config <domain> submit --id <id> --payload <submit-file> --profile ${profileArg}
8094
9158
  ${commandPrefix3} config <domain> submit --id <id> --payload <submit-file> --profile ${profileArg} --confirm "submit <domain> <id>"
8095
9159
  ${commandPrefix3} config <domain> verify --id <id> --expect <work-file> --profile ${profileArg}
@@ -9303,6 +10367,45 @@ async function pullLatestConfigEnvironment(env, options) {
9303
10367
 
9304
10368
  // src/commands/config.ts
9305
10369
  var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10370
+ function csvCell(value) {
10371
+ const text5 = value === null || value === void 0 ? "" : Array.isArray(value) || isRecord5(value) ? JSON.stringify(value) : String(value);
10372
+ return /[",\n\r]/.test(text5) ? `"${text5.replace(/"/g, '""')}"` : text5;
10373
+ }
10374
+ async function writeEvidenceOut(file, value) {
10375
+ if (!file) {
10376
+ return;
10377
+ }
10378
+ await mkdir8(path9.dirname(path9.resolve(file)), { recursive: true });
10379
+ const evidence = isRecord5(value.evidence) ? value.evidence : value;
10380
+ if (file.endsWith(".csv")) {
10381
+ const keys = [
10382
+ "flow_type",
10383
+ "flow_key",
10384
+ "flow_template_id",
10385
+ "form_template_id",
10386
+ "form_template_draft_id",
10387
+ "workspace_key",
10388
+ "workspace_binding_found",
10389
+ "workspace_readback_hash",
10390
+ "evidence_status",
10391
+ "verified_at"
10392
+ ];
10393
+ await writeFile8(file, `${keys.join(",")}
10394
+ ${keys.map((key) => csvCell(evidence[key])).join(",")}
10395
+ `, "utf8");
10396
+ return;
10397
+ }
10398
+ await writeFile8(file, `${JSON.stringify(evidence, null, 2)}
10399
+ `, "utf8");
10400
+ }
10401
+ async function writeResponseOut(file, value) {
10402
+ if (!file) {
10403
+ return;
10404
+ }
10405
+ await mkdir8(path9.dirname(path9.resolve(file)), { recursive: true });
10406
+ await writeFile8(file, `${JSON.stringify(value, null, 2)}
10407
+ `, "utf8");
10408
+ }
9306
10409
  async function resolveFlowTemplatePluginLintOptions(options) {
9307
10410
  const configData = await loadConfig();
9308
10411
  const profileName = options.profile || configData.current_profile || "default";
@@ -9441,9 +10544,16 @@ function registerConfigCommands(program2) {
9441
10544
  user: target.user || null
9442
10545
  });
9443
10546
  });
9444
- 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("--format <format>", "Output format", "table").action(async (options) => {
10547
+ 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) => {
9445
10548
  void options.profile;
9446
- printResult(options.format, configAdapterMatrix());
10549
+ const rows = configAdapterMatrix();
10550
+ const filtered = options.capability ? rows.filter((row) => Object.values(row).some((value) => {
10551
+ if (Array.isArray(value)) {
10552
+ return value.includes(options.capability);
10553
+ }
10554
+ return value === options.capability;
10555
+ })) : rows;
10556
+ printResult(options.format, filtered);
9447
10557
  });
9448
10558
  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) => {
9449
10559
  if (domain === "adapters" && !operation) {
@@ -9543,7 +10653,23 @@ function registerConfigCommands(program2) {
9543
10653
  next: `Run git -C ${environment.sysconfig_repo_path} status --short and git diff to inspect local changes.`
9544
10654
  });
9545
10655
  });
9546
- config.command("flow-app").description("Create an end-to-end BPMAX flow app from form and flow work files").command("create").description("Create a form template, create a main flow, bind the published form, and bind the flow to a workspace").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--form-work <file>", "Form-template work JSON file").requiredOption("--flow-work <file>", "Flow-template work JSON file").requiredOption("--name <name>", "Flow app name used in the confirmation text").option("--profile <profile>", "Profile name").option("--draft-only", "Save the created flow as draft only instead of publishing live").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "pretty").action(async (options) => {
10656
+ const flowApp = config.command("flow-app").description("Inspect or create an end-to-end BPMAX flow app");
10657
+ const registerFlowAppContextCommand = (name) => {
10658
+ flowApp.command(name).description("Collect target flow-app context evidence for migration").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--flow <flow>", "Flow identity: flow_type, flow_type:key, key:<key>, or exact flow name").option("--profile <profile>", "Profile name").option("--evidence-out <file>", "Write target context evidence as JSON or CSV").option("--format <format>", "Output format", "json").action(async (options) => {
10659
+ const configData = await loadConfig();
10660
+ const resolved = resolveProfile(configData, options.profile);
10661
+ const result = await inspectFlowAppContext(configData, resolved, {
10662
+ workspace: options.workspace,
10663
+ flow: options.flow
10664
+ });
10665
+ await writeEvidenceOut(options.evidenceOut, result);
10666
+ await saveConfig(configData);
10667
+ printResult(options.format, result);
10668
+ });
10669
+ };
10670
+ registerFlowAppContextCommand("context");
10671
+ registerFlowAppContextCommand("inspect");
10672
+ flowApp.command("create").description("Create a form template, create a main flow, bind the published form, and bind the flow to a workspace").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--form-work <file>", "Form-template work JSON file").requiredOption("--flow-work <file>", "Flow-template work JSON file").requiredOption("--name <name>", "Flow app name used in the confirmation text").option("--profile <profile>", "Profile name").option("--draft-only", "Save the created flow as draft only instead of publishing live").option("--confirm <text>", "Exact confirmation text").option("--evidence-out <file>", "Write apply-ready target context evidence as JSON or CSV after create").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
9547
10673
  const configData = await loadConfig();
9548
10674
  const resolved = resolveProfile(configData, options.profile);
9549
10675
  const result = await createFlowAppFromWork(
@@ -9558,6 +10684,8 @@ function registerConfigCommands(program2) {
9558
10684
  publishLive: !options.draftOnly
9559
10685
  }
9560
10686
  );
10687
+ await writeResponseOut(options.responseOut, result);
10688
+ await writeEvidenceOut(options.evidenceOut, result);
9561
10689
  await saveConfig(configData);
9562
10690
  printResult(options.format, result);
9563
10691
  });
@@ -9591,9 +10719,38 @@ function registerConfigCommands(program2) {
9591
10719
  profile: resolved
9592
10720
  }));
9593
10721
  });
10722
+ config.command("readback <domain>").description("Read back one config object with a unified hash/evidence shape").requiredOption("--id <id>", "Remote config id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (domain, options) => {
10723
+ if (!Object.prototype.hasOwnProperty.call(CONFIG_DOMAINS, domain)) {
10724
+ throw new Error(`Unknown config domain: ${domain}`);
10725
+ }
10726
+ const configData = await loadConfig();
10727
+ const resolved = resolveProfile(configData, options.profile);
10728
+ const result = await readbackConfigDomain(configData, resolved, domain, options.id);
10729
+ await saveConfig(configData);
10730
+ printResult(options.format, result);
10731
+ });
10732
+ const batch = config.command("batch").description("Run guarded typed config operations from a manifest");
10733
+ batch.command("submit").description("Submit typed config payloads from a batch manifest and keep per-row evidence").requiredOption("--manifest <file>", "Batch manifest JSON file").option("--profile <profile>", "Profile name").option("--continue-on-error", "Continue after a row fails and return a final failed summary").option("--format <format>", "Output format", "json").action(async (options) => {
10734
+ const configData = await loadConfig();
10735
+ const resolved = resolveProfile(configData, options.profile);
10736
+ const result = await runConfigBatchSubmit(configData, resolved, options.manifest, {
10737
+ continueOnError: Boolean(options.continueOnError)
10738
+ });
10739
+ await saveConfig(configData);
10740
+ printResult(options.format, result);
10741
+ });
10742
+ batch.command("readback").description("Read back typed config objects from a batch manifest and keep per-row evidence").requiredOption("--manifest <file>", "Batch manifest JSON file").option("--profile <profile>", "Profile name").option("--continue-on-error", "Continue after a row fails and return a final failed summary").option("--format <format>", "Output format", "json").action(async (options) => {
10743
+ const configData = await loadConfig();
10744
+ const resolved = resolveProfile(configData, options.profile);
10745
+ const result = await runConfigBatchReadback(configData, resolved, options.manifest, {
10746
+ continueOnError: Boolean(options.continueOnError)
10747
+ });
10748
+ await saveConfig(configData);
10749
+ printResult(options.format, result);
10750
+ });
9594
10751
  Object.keys(CONFIG_DOMAINS).forEach((domain) => {
9595
10752
  const domainCommand = domain === "workspace" ? workspace.description("Initialize local sysconfig workspaces and manage BPMAX workspace configuration") : config.command(domain).description(`Manage BPMAX ${domain} configuration`);
9596
- const createCommand = domainCommand.command("create").description(domain === "flow-template" ? "Create a new main flow template through the typed adapter" : `Create a ${domain} config object through a verified typed adapter; dry-run unless --confirm is exact`).option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, publish the created flow to live after saving draft").option("--format <format>", "Output format", "pretty");
10753
+ const createCommand = domainCommand.command("create").description(domain === "flow-template" ? "Create a new main flow template through the typed adapter" : `Create a ${domain} config object through a verified typed adapter; dry-run unless --confirm is exact`).option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, publish the created flow to live after saving draft").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty");
9597
10754
  if (domain === "flow-template") {
9598
10755
  createCommand.requiredOption("--work <file>", "Flow-template work JSON file").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex");
9599
10756
  } else {
@@ -9618,6 +10775,7 @@ function registerConfigCommands(program2) {
9618
10775
  { publishLive: Boolean(options.publishLive) }
9619
10776
  );
9620
10777
  await saveConfig(configData);
10778
+ await writeResponseOut(options.responseOut, result);
9621
10779
  printResult(options.format, result);
9622
10780
  });
9623
10781
  if (domain === "project-detail-template") {
@@ -9635,15 +10793,13 @@ function registerConfigCommands(program2) {
9635
10793
  const resolved = resolveProfile(configData, options.profile);
9636
10794
  const workFormat = options.workFormat === "structured" ? "structured" : "raw";
9637
10795
  const result = await exportConfigDomain(configData, resolved, domain, options.id, options.out, { workFormat });
9638
- if (domain === "flow-template" && (options.summary || options.inline)) {
9639
- const workFile = typeof result.work_file === "string" ? result.work_file : void 0;
9640
- const work = workFile ? await readJsonFile(workFile) : void 0;
9641
- if (options.summary) {
9642
- result.summary = summarizeFlowTemplateWork(work);
9643
- }
9644
- if (options.inline) {
9645
- result.work = work;
9646
- }
10796
+ const workFile = typeof result.work_file === "string" ? result.work_file : void 0;
10797
+ const work = (options.inline || domain === "flow-template" && options.summary) && workFile ? await readJsonFile(workFile) : void 0;
10798
+ if (domain === "flow-template" && options.summary) {
10799
+ result.summary = summarizeFlowTemplateWork(work);
10800
+ }
10801
+ if (options.inline) {
10802
+ result.work = work;
9647
10803
  }
9648
10804
  await saveConfig(configData);
9649
10805
  printResult(options.format, result);
@@ -9694,7 +10850,7 @@ function registerConfigCommands(program2) {
9694
10850
  submit_preview: submit || null
9695
10851
  });
9696
10852
  });
9697
- domainCommand.command("submit").description(`Submit a ${domain} payload when a verified domain adapter is available; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").requiredOption("--payload <file>", "Submit payload JSON file produced by build").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, submit this payload as a live publish").option("--format <format>", "Output format", "pretty").action(async (options) => {
10853
+ domainCommand.command("submit").description(`Submit a ${domain} payload when a verified domain adapter is available; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").requiredOption("--payload <file>", "Submit payload JSON file produced by build").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, submit this payload as a live publish").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
9698
10854
  const configData = await loadConfig();
9699
10855
  const resolved = resolveProfile(configData, options.profile);
9700
10856
  const result = await submitConfigDomain(
@@ -9707,6 +10863,7 @@ function registerConfigCommands(program2) {
9707
10863
  { publishLive: Boolean(options.publishLive), agent: options.agent || "codex" }
9708
10864
  );
9709
10865
  await saveConfig(configData);
10866
+ await writeResponseOut(options.responseOut, result);
9710
10867
  printResult(options.format, result);
9711
10868
  });
9712
10869
  domainCommand.command("delete").description(`Delete a ${domain} config object through a verified typed adapter; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "pretty").action(async (options) => {
@@ -9723,6 +10880,29 @@ function registerConfigCommands(program2) {
9723
10880
  printResult(options.format, result);
9724
10881
  });
9725
10882
  if (domain === "dataset") {
10883
+ const relationFields = domainCommand.command("relation-fields").description("Manage dataset relationFields through the typed dataset adapter");
10884
+ relationFields.command("submit").description("Submit dataset relationFields payload with the standard dataset evidence response").requiredOption("--id <id>", "Remote dataset id").requiredOption("--payload <file>", "Submit payload JSON file produced by config dataset build").option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
10885
+ const configData = await loadConfig();
10886
+ const resolved = resolveProfile(configData, options.profile);
10887
+ const result = await submitConfigDomain(
10888
+ configData,
10889
+ resolved,
10890
+ "dataset",
10891
+ options.id,
10892
+ options.payload,
10893
+ options.confirm
10894
+ );
10895
+ await saveConfig(configData);
10896
+ await writeResponseOut(options.responseOut, result);
10897
+ printResult(options.format, result);
10898
+ });
10899
+ relationFields.command("readback").description("Read back dataset relationFields evidence using the unified readback shape").requiredOption("--id <id>", "Remote dataset id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
10900
+ const configData = await loadConfig();
10901
+ const resolved = resolveProfile(configData, options.profile);
10902
+ const result = await readbackConfigDomain(configData, resolved, "dataset", options.id);
10903
+ await saveConfig(configData);
10904
+ printResult(options.format, result);
10905
+ });
9726
10906
  [
9727
10907
  ["publish", "Publish/start a dataset and trigger ES batch generation"],
9728
10908
  ["pause", "Pause a published or pending dataset"],
@@ -9784,8 +10964,8 @@ function registerConfigCommands(program2) {
9784
10964
 
9785
10965
  // src/commands/e2e.ts
9786
10966
  import { createHash as createHash5 } from "crypto";
9787
- import { mkdir as mkdir8, readFile as readFile11, readdir as readdir3, stat as stat5, writeFile as writeFile8 } from "fs/promises";
9788
- import path9 from "path";
10967
+ import { mkdir as mkdir9, readFile as readFile11, readdir as readdir3, stat as stat5, writeFile as writeFile9 } from "fs/promises";
10968
+ import path10 from "path";
9789
10969
 
9790
10970
  // src/core/form-schema.ts
9791
10971
  var FIELD_KEY_NAMES = [
@@ -10718,18 +11898,18 @@ function timestampSlug() {
10718
11898
  return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
10719
11899
  }
10720
11900
  async function ensureDir(dir) {
10721
- const resolved = path9.resolve(dir);
10722
- await mkdir8(resolved, { recursive: true });
11901
+ const resolved = path10.resolve(dir);
11902
+ await mkdir9(resolved, { recursive: true });
10723
11903
  return resolved;
10724
11904
  }
10725
11905
  async function writeEvidence(dir, name, value) {
10726
- const file = path9.join(await ensureDir(dir), name);
10727
- await writeFile8(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
11906
+ const file = path10.join(await ensureDir(dir), name);
11907
+ await writeFile9(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
10728
11908
  `, "utf8");
10729
11909
  return file;
10730
11910
  }
10731
11911
  function cacheRoot() {
10732
- return path9.resolve(".codex/cache/bpmax-e2e");
11912
+ return path10.resolve(".codex/cache/bpmax-e2e");
10733
11913
  }
10734
11914
  function safeSegment(value) {
10735
11915
  return value.trim().replace(/[^a-zA-Z0-9._:-]+/g, "_") || "default";
@@ -10841,7 +12021,7 @@ function buildExpectedChecks(options) {
10841
12021
  ];
10842
12022
  }
10843
12023
  function flowCachePath(profileName, flowId) {
10844
- return path9.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
12024
+ return path10.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
10845
12025
  }
10846
12026
  async function readOptionalJson(file) {
10847
12027
  try {
@@ -10930,7 +12110,7 @@ function dataProfilePath(input) {
10930
12110
  if (!input?.startsWith("@")) {
10931
12111
  return void 0;
10932
12112
  }
10933
- return path9.resolve(input.slice(1));
12113
+ return path10.resolve(input.slice(1));
10934
12114
  }
10935
12115
  function refreshedStepTemplate(options) {
10936
12116
  return {
@@ -10954,15 +12134,15 @@ function refreshedStepTemplate(options) {
10954
12134
  variables: Object.keys(options.plan.data).filter((key) => !["project_id", "action", "urgency"].includes(key)),
10955
12135
  payload_template: options.plan.data,
10956
12136
  source_evidence: {
10957
- evidence_dir: path9.resolve(options.evidenceDir),
10958
- context: path9.basename(options.contextFile)
12137
+ evidence_dir: path10.resolve(options.evidenceDir),
12138
+ context: path10.basename(options.contextFile)
10959
12139
  }
10960
12140
  };
10961
12141
  }
10962
12142
  async function writeRefreshedCache(file, template) {
10963
- const out = path9.resolve(file);
10964
- await mkdir8(path9.dirname(out), { recursive: true });
10965
- await writeFile8(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
12143
+ const out = path10.resolve(file);
12144
+ await mkdir9(path10.dirname(out), { recursive: true });
12145
+ await writeFile9(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
10966
12146
  `, "utf8");
10967
12147
  return out;
10968
12148
  }
@@ -11039,13 +12219,13 @@ test(${JSON.stringify(options.title)}, async ({ page }) => {
11039
12219
  async function writeBrowserTemplate(options) {
11040
12220
  const handoffUrl = handoffUrlFromInput(options.handoff);
11041
12221
  const assertFields = (options.assertFields ?? "").split(",").map((item) => item.trim()).filter(Boolean);
11042
- const out = path9.resolve(options.out);
11043
- await mkdir8(path9.dirname(out), { recursive: true });
11044
- await writeFile8(out, playwrightTemplate({
12222
+ const out = path10.resolve(options.out);
12223
+ await mkdir9(path10.dirname(out), { recursive: true });
12224
+ await writeFile9(out, playwrightTemplate({
11045
12225
  title: options.title ?? "BPMAX create page handoff submit",
11046
12226
  handoffUrl,
11047
12227
  assertFields,
11048
- evidenceDir: path9.resolve(options.evidenceDir)
12228
+ evidenceDir: path10.resolve(options.evidenceDir)
11049
12229
  }), "utf8");
11050
12230
  return { out, handoff_url: handoffUrl, assert_fields: assertFields };
11051
12231
  }
@@ -11208,7 +12388,7 @@ function registerE2eCommands(program2) {
11208
12388
  mode: "handoff_command_hint",
11209
12389
  browser: options.browser,
11210
12390
  next_command: `bpmax-cli project create ${flowFlag}${jsonFlag}${profileFlag} --handoff-only --format json > handoff.json`,
11211
- next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path9.resolve(options.evidenceDir)} --format json`,
12391
+ next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path10.resolve(options.evidenceDir)} --format json`,
11212
12392
  note: "create-page-submit does not raw-create a project. First generate a handoff URL, then execute the generated browser template and keep screenshots/result JSON as evidence."
11213
12393
  });
11214
12394
  return;
@@ -11227,7 +12407,7 @@ function registerE2eCommands(program2) {
11227
12407
  browser_verified: false,
11228
12408
  browser: options.browser,
11229
12409
  ...generated,
11230
- evidence_dir: path9.resolve(options.evidenceDir),
12410
+ evidence_dir: path10.resolve(options.evidenceDir),
11231
12411
  next_command: `npx playwright test ${generated.out}`,
11232
12412
  note: "This command does not raw-create a project. Run the generated Playwright script against a logged-in browser context and keep its screenshots/result JSON as browser evidence."
11233
12413
  });
@@ -11278,8 +12458,8 @@ function registerE2eCommands(program2) {
11278
12458
  template_id: result.template_id ?? result.templateId
11279
12459
  })).digest("hex").slice(0, 16);
11280
12460
  const file = flowCachePath(profile.name, options.flowId);
11281
- await mkdir8(path9.dirname(file), { recursive: true });
11282
- await writeFile8(file, `${JSON.stringify(redactAuditValue({
12461
+ await mkdir9(path10.dirname(file), { recursive: true });
12462
+ await writeFile9(file, `${JSON.stringify(redactAuditValue({
11283
12463
  cache_key: cacheKey,
11284
12464
  cached_at: (/* @__PURE__ */ new Date()).toISOString(),
11285
12465
  profile: profile.name,
@@ -11309,7 +12489,7 @@ function registerE2eCommands(program2) {
11309
12489
  printResult(options.format, {
11310
12490
  ok: true,
11311
12491
  ...generated,
11312
- evidence_dir: path9.resolve(options.evidenceDir),
12492
+ evidence_dir: path10.resolve(options.evidenceDir),
11313
12493
  next_command: `npx playwright test ${generated.out}`
11314
12494
  });
11315
12495
  });
@@ -11321,8 +12501,8 @@ function registerE2eCommands(program2) {
11321
12501
  if (inferredStepId && !contextFile && !submitFile) {
11322
12502
  throw new Error(`No step evidence files found for step ${inferredStepId} in ${options.evidenceDir}.`);
11323
12503
  }
11324
- const context = contextFile ? await readOptionalJson(path9.join(options.evidenceDir, contextFile)) : null;
11325
- const submit = submitFile ? await readOptionalJson(path9.join(options.evidenceDir, submitFile)) : null;
12504
+ const context = contextFile ? await readOptionalJson(path10.join(options.evidenceDir, contextFile)) : null;
12505
+ const submit = submitFile ? await readOptionalJson(path10.join(options.evidenceDir, submitFile)) : null;
11326
12506
  const requirements = isRecord8(context?.requirements) ? context.requirements : {};
11327
12507
  const requiredInputs = Array.isArray(requirements.required_inputs) ? requirements.required_inputs.filter(isRecord8) : [];
11328
12508
  const missingInputs = Array.isArray(requirements.missing_required_inputs) ? requirements.missing_required_inputs.filter(isRecord8) : [];
@@ -11365,16 +12545,16 @@ function registerE2eCommands(program2) {
11365
12545
  variables: Object.keys(requestData).filter((key) => !["project_id", "action", "urgency"].includes(key)),
11366
12546
  payload_template: requestData,
11367
12547
  source_evidence: {
11368
- evidence_dir: path9.resolve(options.evidenceDir),
12548
+ evidence_dir: path10.resolve(options.evidenceDir),
11369
12549
  ...contextFile ? { context: contextFile } : {},
11370
12550
  ...submitFile ? { submit: submitFile } : {}
11371
12551
  }
11372
12552
  } : {
11373
- name: options.name ?? path9.basename(path9.resolve(options.evidenceDir)),
12553
+ name: options.name ?? path10.basename(path10.resolve(options.evidenceDir)),
11374
12554
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
11375
12555
  submit_mode: "browser_evidence_bootstrap",
11376
12556
  source_evidence: {
11377
- evidence_dir: path9.resolve(options.evidenceDir),
12557
+ evidence_dir: path10.resolve(options.evidenceDir),
11378
12558
  files: evidenceFiles
11379
12559
  },
11380
12560
  reuse_requirements: [
@@ -11383,9 +12563,9 @@ function registerE2eCommands(program2) {
11383
12563
  "Do not treat API-only evidence as browser E2E proof."
11384
12564
  ]
11385
12565
  };
11386
- const out = path9.resolve(options.out);
11387
- await mkdir8(path9.dirname(out), { recursive: true });
11388
- await writeFile8(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
12566
+ const out = path10.resolve(options.out);
12567
+ await mkdir9(path10.dirname(out), { recursive: true });
12568
+ await writeFile9(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
11389
12569
  `, "utf8");
11390
12570
  printResult(options.format, {
11391
12571
  ok: true,
@@ -11545,7 +12725,7 @@ function registerFlowCommands(program2) {
11545
12725
  const client = createApiClient(profile);
11546
12726
  if (options.flowType) {
11547
12727
  const bindings = await getWorkspaceFlowBindings(client, profile, options);
11548
- const path14 = options.flowKey ? "/flow/options" : "/flow/flow_type";
12728
+ const path15 = options.flowKey ? "/flow/options" : "/flow/flow_type";
11549
12729
  const params = options.flowKey ? {
11550
12730
  detail: "1"
11551
12731
  } : {
@@ -11555,7 +12735,7 @@ function registerFlowCommands(program2) {
11555
12735
  const result2 = await apiRequest(
11556
12736
  client,
11557
12737
  "GET",
11558
- path14,
12738
+ path15,
11559
12739
  {
11560
12740
  params
11561
12741
  }
@@ -11812,10 +12992,10 @@ async function parseOptionalJson(input, label) {
11812
12992
  }
11813
12993
  return parseJsonInput(input, label);
11814
12994
  }
11815
- async function memoryRequest(options, method, path14, capability, data, params) {
12995
+ async function memoryRequest(options, method, path15, capability, data, params) {
11816
12996
  const profile = resolveProfile(await loadConfig(), options.profile);
11817
12997
  const client = createApiClient(profile);
11818
- return apiRequest(client, method, path14, {
12998
+ return apiRequest(client, method, path15, {
11819
12999
  capability,
11820
13000
  data: redactAuditValue(data),
11821
13001
  params: params ? redactAuditValue(params) : void 0
@@ -11897,15 +13077,15 @@ async function parseSeedRules(input) {
11897
13077
  });
11898
13078
  return rules;
11899
13079
  }
11900
- function collectUuidPaths(value, path14 = "$") {
13080
+ function collectUuidPaths(value, path15 = "$") {
11901
13081
  if (typeof value === "string") {
11902
- return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path14] : [];
13082
+ return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path15] : [];
11903
13083
  }
11904
13084
  if (Array.isArray(value)) {
11905
- return value.flatMap((item, index) => collectUuidPaths(item, `${path14}[${index}]`));
13085
+ return value.flatMap((item, index) => collectUuidPaths(item, `${path15}[${index}]`));
11906
13086
  }
11907
13087
  if (typeof value === "object" && value !== null) {
11908
- return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path14}.${key}`));
13088
+ return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path15}.${key}`));
11909
13089
  }
11910
13090
  return [];
11911
13091
  }
@@ -11934,16 +13114,16 @@ function dataArray(value) {
11934
13114
  if (isRecord10(value) && Array.isArray(value.data)) return value.data;
11935
13115
  return [];
11936
13116
  }
11937
- function collectMatrixOwnerPaths(value, path14 = "$") {
13117
+ function collectMatrixOwnerPaths(value, path15 = "$") {
11938
13118
  if (Array.isArray(value)) {
11939
- return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path14}[${index}]`));
13119
+ return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path15}[${index}]`));
11940
13120
  }
11941
13121
  if (!isRecord10(value)) {
11942
13122
  return [];
11943
13123
  }
11944
13124
  const matches = [];
11945
13125
  Object.entries(value).forEach(([key, child]) => {
11946
- const childPath = `${path14}.${key}`;
13126
+ const childPath = `${path15}.${key}`;
11947
13127
  if (key.includes("matrix_owner") || typeof child === "string" && child.includes("matrix_owner")) {
11948
13128
  matches.push({ path: childPath, value: child });
11949
13129
  }
@@ -12772,9 +13952,9 @@ function contextField(field, reason, options = {}) {
12772
13952
  function collectPrefillContextForFields(fields, form, result, options = {}) {
12773
13953
  for (const field of fields) {
12774
13954
  const value = form[field.key];
12775
- const path14 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
13955
+ const path15 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
12776
13956
  const fieldOptions = {
12777
- path: path14,
13957
+ path: path15,
12778
13958
  rootKey: options.rootKey ?? field.key,
12779
13959
  parentKey: options.parentKey
12780
13960
  };
@@ -13191,8 +14371,8 @@ import { spawn as spawn2 } from "child_process";
13191
14371
  import { fileURLToPath as fileURLToPath3 } from "url";
13192
14372
 
13193
14373
  // src/core/recipes.ts
13194
- import { access, mkdir as mkdir9, readdir as readdir4, readFile as readFile13, writeFile as writeFile9 } from "fs/promises";
13195
- import path10 from "path";
14374
+ import { access, mkdir as mkdir10, readdir as readdir4, readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
14375
+ import path11 from "path";
13196
14376
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
13197
14377
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
13198
14378
  function assertSafeName(kind, value) {
@@ -13216,12 +14396,12 @@ function resolveRecipeLocation(options) {
13216
14396
  workspace,
13217
14397
  workspaceDirName,
13218
14398
  recipeName: options.recipeName,
13219
- recipeDir: path10.join(profileDir, "recipes", workspaceDirName, options.recipeName)
14399
+ recipeDir: path11.join(profileDir, "recipes", workspaceDirName, options.recipeName)
13220
14400
  };
13221
14401
  }
13222
14402
  function getRecipesDir(options) {
13223
14403
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
13224
- return path10.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
14404
+ return path11.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
13225
14405
  }
13226
14406
  function isRecord13(value) {
13227
14407
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -13273,7 +14453,7 @@ function parseRecipeDefinition(input) {
13273
14453
  };
13274
14454
  }
13275
14455
  async function loadRecipe(recipeDir) {
13276
- const raw = await readFile13(path10.join(recipeDir, "recipe.json"), "utf8");
14456
+ const raw = await readFile13(path11.join(recipeDir, "recipe.json"), "utf8");
13277
14457
  return parseRecipeDefinition(JSON.parse(raw));
13278
14458
  }
13279
14459
  async function listRecipes(recipesDir) {
@@ -13291,7 +14471,7 @@ async function listRecipes(recipesDir) {
13291
14471
  if (!RECIPE_NAME_PATTERN.test(entry)) {
13292
14472
  continue;
13293
14473
  }
13294
- const recipeDir = path10.join(recipesDir, entry);
14474
+ const recipeDir = path11.join(recipesDir, entry);
13295
14475
  try {
13296
14476
  const recipe = await loadRecipe(recipeDir);
13297
14477
  summaries.push({
@@ -13357,12 +14537,12 @@ function renderTemplate(template, variables) {
13357
14537
  }
13358
14538
  function resolveRecipeFile(recipeDir, token) {
13359
14539
  const relative = token.slice(1);
13360
- if (!relative || relative.includes("..") || path10.isAbsolute(relative)) {
14540
+ if (!relative || relative.includes("..") || path11.isAbsolute(relative)) {
13361
14541
  throw new Error(`Unsafe recipe file reference: ${token}`);
13362
14542
  }
13363
- const resolved = path10.resolve(recipeDir, relative);
13364
- const root = path10.resolve(recipeDir);
13365
- if (resolved !== root && !resolved.startsWith(`${root}${path10.sep}`)) {
14543
+ const resolved = path11.resolve(recipeDir, relative);
14544
+ const root = path11.resolve(recipeDir);
14545
+ if (resolved !== root && !resolved.startsWith(`${root}${path11.sep}`)) {
13366
14546
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
13367
14547
  }
13368
14548
  return resolved;
@@ -13398,7 +14578,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
13398
14578
  }
13399
14579
  async function writeRecipeScaffold(options) {
13400
14580
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
13401
- await mkdir9(options.location.recipeDir, { recursive: true });
14581
+ await mkdir10(options.location.recipeDir, { recursive: true });
13402
14582
  const title = options.title || options.location.recipeName;
13403
14583
  const recipe = {
13404
14584
  version: 1,
@@ -13415,16 +14595,16 @@ async function writeRecipeScaffold(options) {
13415
14595
  mutating: true
13416
14596
  }
13417
14597
  };
13418
- await writeFile9(path10.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
14598
+ await writeFile10(path11.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
13419
14599
  `, "utf8");
13420
- await writeFile9(
13421
- path10.join(options.location.recipeDir, "payload.json"),
14600
+ await writeFile10(
14601
+ path11.join(options.location.recipeDir, "payload.json"),
13422
14602
  `${JSON.stringify({ form: {} }, null, 2)}
13423
14603
  `,
13424
14604
  "utf8"
13425
14605
  );
13426
- await writeFile9(
13427
- path10.join(options.location.recipeDir, "README.md"),
14606
+ await writeFile10(
14607
+ path11.join(options.location.recipeDir, "README.md"),
13428
14608
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
13429
14609
  "utf8"
13430
14610
  );
@@ -13830,8 +15010,8 @@ function registerSetupCommand(program2, deps = {}) {
13830
15010
  }
13831
15011
 
13832
15012
  // src/core/taskbook.ts
13833
- import { mkdir as mkdir10, readFile as readFile14, writeFile as writeFile10 } from "fs/promises";
13834
- import path11 from "path";
15013
+ import { mkdir as mkdir11, readFile as readFile14, writeFile as writeFile11 } from "fs/promises";
15014
+ import path12 from "path";
13835
15015
  var TaskbookError = class extends Error {
13836
15016
  };
13837
15017
  var REQUIRED_TASKBOOK_TERMS = [
@@ -14026,14 +15206,14 @@ function hasDomainWriteEvidence(domain, evidenceText, patterns) {
14026
15206
  function uuidValues(text5) {
14027
15207
  return [...new Set([...text5.matchAll(UUID_PATTERN)].map((match) => match[0]))];
14028
15208
  }
14029
- function addUuidIssues(text5, issues, path14) {
15209
+ function addUuidIssues(text5, issues, path15) {
14030
15210
  for (const value of uuidValues(text5)) {
14031
15211
  addTaskbookIssue(
14032
15212
  issues,
14033
15213
  "uuid_not_allowed",
14034
15214
  "taskbook.config.no_uuid",
14035
15215
  `BPMAX \u914D\u7F6E\u4EFB\u52A1\u4E0D\u80FD\u4F7F\u7528 UUID\uFF1A${value}\u3002`,
14036
- { path: path14, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
15216
+ { path: path15, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
14037
15217
  );
14038
15218
  }
14039
15219
  }
@@ -14065,7 +15245,7 @@ function findNavigationStrategy(text5) {
14065
15245
  const matches = [...text5.matchAll(/导航入口策略\s*[::]\s*(nav-config:(?:included|skipped:[^\s|,。]+|deferred:[^\s|,。]+))/gi)];
14066
15246
  return matches.at(-1)?.[1] || null;
14067
15247
  }
14068
- function validateNavigationStrategy(text5, issues, path14, subject) {
15248
+ function validateNavigationStrategy(text5, issues, path15, subject) {
14069
15249
  const strategy = findNavigationStrategy(text5);
14070
15250
  if (!strategy) {
14071
15251
  addTaskbookIssue(
@@ -14073,7 +15253,7 @@ function validateNavigationStrategy(text5, issues, path14, subject) {
14073
15253
  "missing_navigation_strategy",
14074
15254
  "taskbook.nav.strategy",
14075
15255
  `${subject}\u7F3A\u5C11\u660E\u786E\u7684\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u3002`,
14076
- { path: path14, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
15256
+ { path: path15, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
14077
15257
  );
14078
15258
  return null;
14079
15259
  }
@@ -14083,7 +15263,7 @@ function validateNavigationStrategy(text5, issues, path14, subject) {
14083
15263
  "empty_navigation_strategy_reason",
14084
15264
  "taskbook.nav.strategy_reason",
14085
15265
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u8DF3\u8FC7\u6216\u5EF6\u540E\u65F6\u5FC5\u987B\u5199\u660E\u539F\u56E0\u3002`,
14086
- { path: path14, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
15266
+ { path: path15, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
14087
15267
  );
14088
15268
  }
14089
15269
  if (/(待完成范围确认后回填|待确认|TODO|TBD|占位)/i.test(strategy)) {
@@ -14092,7 +15272,7 @@ function validateNavigationStrategy(text5, issues, path14, subject) {
14092
15272
  "placeholder_navigation_strategy",
14093
15273
  "taskbook.nav.strategy_placeholder",
14094
15274
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u4ECD\u662F\u5360\u4F4D\u5185\u5BB9\u3002`,
14095
- { path: path14, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
15275
+ { path: path15, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
14096
15276
  );
14097
15277
  }
14098
15278
  return strategy;
@@ -14549,8 +15729,8 @@ function taskbookTemplate(title = "BPMAX AI \u5B9E\u65BD\u7F16\u6392\u4EFB\u52A1
14549
15729
  }
14550
15730
  async function initTaskbook(outFile, title) {
14551
15731
  const content = taskbookTemplate(title);
14552
- await mkdir10(path11.dirname(outFile), { recursive: true });
14553
- await writeFile10(outFile, content, "utf8");
15732
+ await mkdir11(path12.dirname(outFile), { recursive: true });
15733
+ await writeFile11(outFile, content, "utf8");
14554
15734
  return { out: outFile, bytes: Buffer.byteLength(content) };
14555
15735
  }
14556
15736
  function splitMarkdownRow(line) {
@@ -14639,8 +15819,8 @@ async function initTaskbookProgress(source, outFile) {
14639
15819
  fields.join(","),
14640
15820
  ...rows.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
14641
15821
  ].join("\n") + "\n";
14642
- await mkdir10(path11.dirname(outFile), { recursive: true });
14643
- await writeFile10(outFile, csv, "utf8");
15822
+ await mkdir11(path12.dirname(outFile), { recursive: true });
15823
+ await writeFile11(outFile, csv, "utf8");
14644
15824
  return { source, out: outFile, task_count: rows.length };
14645
15825
  }
14646
15826
 
@@ -14686,14 +15866,14 @@ import { createHash as createHash6 } from "crypto";
14686
15866
  import {
14687
15867
  copyFile,
14688
15868
  cp as cp3,
14689
- mkdir as mkdir11,
15869
+ mkdir as mkdir12,
14690
15870
  readdir as readdir5,
14691
15871
  readFile as readFile15,
14692
15872
  rm as rm4,
14693
15873
  stat as stat6,
14694
- writeFile as writeFile11
15874
+ writeFile as writeFile12
14695
15875
  } from "fs/promises";
14696
- import path12 from "path";
15876
+ import path13 from "path";
14697
15877
  var DEFAULT_SUITE_ROOT = ".ai_test/suite";
14698
15878
  var DEFAULT_DRAFT_ROOT = ".ai_test/suite_draft";
14699
15879
  var DEFAULT_REPORT_ROOT = ".ai_test/report";
@@ -14746,6 +15926,7 @@ var CONFIG_BASIS_ALLOWED_PREFIXES = [
14746
15926
  ".codex/skills/"
14747
15927
  ];
14748
15928
  var REPORT_REQUIRED_KEYS = ["run_id:", "scenario_id:", "source_suite:", "result:"];
15929
+ var REPORT_EXECUTION_KEYS = ["planned_cases:", "executed_cases:", "precondition_check:", "state_file:", "browser_tool:"];
14749
15930
  var REPORT_REQUIRED_HEADINGS = [
14750
15931
  "## 1. \u6D4B\u8BD5\u8303\u56F4",
14751
15932
  "## 2. \u6267\u884C\u73AF\u5883",
@@ -14763,18 +15944,28 @@ var ID_AS_ENTRY_RE = /(发起表单|处理表单|表单模板|数据集|列表
14763
15944
  var URL_RE = /https?:\/\/|\/w:[^\s,,;;]+|\/project\?|\/project_detail\/|\/projectContinue\?/;
14764
15945
  var SHA_RE = /^[0-9a-f]{40}$/;
14765
15946
  var CONFIG_BASIS_REASON_RE = /(依据|覆盖|校验|验证|对应|因为|reason=|why=|=>|->)/;
14766
- var PREP_TOKEN_RE = /(账号|入口|样本|准备操作|预期|主数据|权限|自动化|依赖流程|清理策略|绑定解析|定位规则|模拟用户)=/g;
15947
+ var PREP_TOKEN_RE = /(账号|入口|样本|准备操作|预期|主数据|权限|自动化|依赖流程|清理策略|绑定解析|定位规则|模拟用户|precondition_check|browser_tool|live_draft|state_file|report_run|login_profile|mock_user|unmock_done|resume_policy)=/g;
14767
15948
  var TEST_DATA_TOKEN_RE = /(业务场景|业务逻辑|样本数据|合理性|客户口径|数据约束)=/g;
14768
15949
  var GENERIC_SAMPLE_VALUE_RE = /(^|[=,;,\s])(sample|test|mock|demo|xxx|todo|tbd|placeholder|随便|假数据|占位|待补)(?=$|[,;,\s])/i;
14769
15950
  var SENSITIVE_TEST_DATA_RE = /authorization|bearer\s+[A-Za-z0-9._-]+|cookie|set-cookie|api[-_]?key|token|password|passwd|pwd|secret|session|验证码|手机号|\b1[3-9]\d{9}\b/i;
14770
15951
  var RAW_PAYLOAD_TEST_DATA_RE = /(^|[;;]\s*)(payload|完整payload|request|请求体|headers?)\s*=/i;
14771
15952
  var PLACEHOLDER_RE = /<[^>]+>/;
15953
+ var CASE_CONTENT_GARBLED_RE = /\uFFFD|�|Ã.|Â.|â[€\u0080-\u00BF]|锛|鈥|乱码|���|\?\?\?/i;
15954
+ var HOLLOW_CASE_TEXT_RE = /(^|[=,;,\s])(todo|tbd|xxx|placeholder|占位|待补|随便写|后补|暂无|无具体步骤|略)(?=$|[,;,\s])/i;
14772
15955
  var IMAGE_RE = /!\[[^\]]*]\(([^)]+)\)/g;
14773
15956
  var YBS_NONZERO_DETAIL_RE = /https:\/\/yaditest\.yitaiyitai\.com\/w:ybs\/project_detail\/(?!0\/)\d+\//;
14774
15957
  var YBS_PC_CREATE_WRONG_RE = /https:\/\/yaditest\.yitaiyitai\.com\/w:ybs\/pages\/projectCreate\/projectCreate\?flow_type=/;
14775
15958
  var IDENTITY_MOCK_CASE_RE = /(非处理人|越权|只读|多角色|角色隔离|无权限|低权限|unauthorized|limited|readonly|permission)/;
14776
15959
  var IDENTITY_MOCK_VALUE_RE = /(mock|模拟).*(unmock|退出模拟|恢复)|bpmax-user-mock-operator/;
14777
15960
  var E2E_REUSABLE_ASSET_RE = /bpmax-cli\s+e2e|record-from-evidence|create-page-submit|step-run|browser-template|scenario\s+plan|data\s+profile|reusable\s+step|复用模板|可复用|首次运行沉淀|沉淀模板/;
15961
+ var ERROR_CAPTURE_CASE_RE = /(negative|boundary|异常|错误|失败|报错|重复|无效|非法|invalid|error|扫码.*(异常|错误|无效)|错误\s*SN|异常\s*SN|无效\s*SN)/i;
15962
+ var ERROR_CAPTURE_EVIDENCE_RE = /(expected_error_text|error_capture_required|错误提示|提示文案|报错文案|toast|校验文案).*(screenshot|截图)|截图.*(错误提示|提示文案|报错文案|toast|校验文案)/i;
15963
+ var BROWSER_TOOL_RE = /(Chrome DevTools|DevTools|Playwright|AppleScript|browser_tool=|浏览器工具)/i;
15964
+ var LIVE_DRAFT_RE = /(live|draft|已发布|草稿|发布态|live_draft=)/i;
15965
+ var MULTI_ROLE_VALUE_RE = /[,、/]\s*[^,、/\s]+|多角色|跨角色/;
15966
+ var RESUME_POLICY_VALUE_RE = /(full_rerun|checkpoint|evidence_only|从头重跑|检查点|仅补证据)/i;
15967
+ var NOT_RUN_RE = /(not[_ -]?run|未执行|未跑|跳过)/i;
15968
+ var PAGE_CONCLUSION_RE = /(页面.*(通过|已验证|真实|可见|不可见)|浏览器回归.*(通过|完成)|完整链路.*通过|真实页面.*通过)/;
14778
15969
  var TestSuiteError = class extends Error {
14779
15970
  code;
14780
15971
  rule_id;
@@ -14851,12 +16042,12 @@ function reviewSchemaExplanation() {
14851
16042
  };
14852
16043
  }
14853
16044
  function reviewFail(reviewPath, message) {
14854
- const scenarioId = path12.basename(path12.dirname(reviewPath));
16045
+ const scenarioId = path13.basename(path13.dirname(reviewPath));
14855
16046
  fail(
14856
16047
  [
14857
16048
  message,
14858
16049
  "\u8FD0\u884C `bpmax-cli test-suite review explain --format json` \u67E5\u770B\u5B8C\u6574 schema\u3002",
14859
- `\u8FD0\u884C \`bpmax-cli test-suite review repair --scenario ${scenarioId} --draft-root ${path12.dirname(path12.dirname(reviewPath))} --latest-proof <proof.json> --format json\` \u4FEE\u8865\u7F3A\u5931\u5B57\u6BB5\u3002`,
16050
+ `\u8FD0\u884C \`bpmax-cli test-suite review repair --scenario ${scenarioId} --draft-root ${path13.dirname(path13.dirname(reviewPath))} --latest-proof <proof.json> --format json\` \u4FEE\u8865\u7F3A\u5931\u5B57\u6BB5\u3002`,
14860
16051
  `\u6700\u5C0F review.json \u793A\u4F8B\uFF1A${JSON.stringify(reviewSchemaExample(scenarioId))}`
14861
16052
  ].join("\n"),
14862
16053
  {
@@ -14945,14 +16136,14 @@ function parseReadmeText(filePath, text5) {
14945
16136
  return metadata;
14946
16137
  }
14947
16138
  async function validateReadme(scenarioDir) {
14948
- const readmePath = path12.join(scenarioDir, "README.md");
16139
+ const readmePath = path13.join(scenarioDir, "README.md");
14949
16140
  if (!await exists3(readmePath)) fail(`missing README.md: ${readmePath}`);
14950
16141
  const text5 = await readText(readmePath);
14951
16142
  const metadata = parseReadmeText(readmePath, text5);
14952
16143
  for (const key of REQUIRED_README_KEYS) {
14953
16144
  if (!metadata[key]) fail(`${scenarioDir}: README.md missing \`${key}\``);
14954
16145
  }
14955
- if (metadata.scenario_id !== path12.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
16146
+ if (metadata.scenario_id !== path13.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
14956
16147
  if (!["true", "false"].includes(metadata.core.toLowerCase())) fail(`${scenarioDir}: core must be true or false`);
14957
16148
  if (!STATUSES.has(metadata.status)) fail(`${scenarioDir}: status must be one of ${JSON.stringify([...STATUSES].sort())}`);
14958
16149
  if (UUID_RE2.test(text5) || ID_AS_ENTRY_RE.test(text5)) {
@@ -15047,6 +16238,72 @@ function hasE2eReusableAsset(row) {
15047
16238
  const evidencePlan = [row.prep_data, row.steps, row.expected_result, row.evidence_required, row.tags].join(" ");
15048
16239
  return E2E_REUSABLE_ASSET_RE.test(evidencePlan);
15049
16240
  }
16241
+ function validateReadableCaseContent(filePath, caseId, row) {
16242
+ for (const field of ["title", "preconditions", "config_basis", "prep_data", "steps", "expected_result", "test_data"]) {
16243
+ const value = row[field].trim();
16244
+ if (!value) continue;
16245
+ if (CASE_CONTENT_GARBLED_RE.test(value)) {
16246
+ fail(`${filePath}:${caseId}: \`${field}\` \u5305\u542B\u4E71\u7801\u6216\u5F02\u5E38\u7F16\u7801\u7247\u6BB5\uFF1Bpromote \u524D\u5FC5\u987B\u4FEE\u590D\u6587\u672C\u7F16\u7801`, { rule_id: "test_suite.case.content_garbled" });
16247
+ }
16248
+ if (HOLLOW_CASE_TEXT_RE.test(value)) {
16249
+ fail(`${filePath}:${caseId}: \`${field}\` \u5305\u542B\u7A7A\u6D1E\u5360\u4F4D\u5185\u5BB9\uFF1B\u5FC5\u987B\u5199\u6E05\u53EF\u6267\u884C\u4E1A\u52A1\u6B65\u9AA4\u548C\u9884\u671F\u7ED3\u679C`, { rule_id: "test_suite.case.content_hollow" });
16250
+ }
16251
+ }
16252
+ if (row.steps.trim().length < 12 || !/[>;;。]|打开|点击|填写|选择|提交|等待|截图|校验|验证/.test(row.steps)) {
16253
+ fail(`${filePath}:${caseId}: \`steps\` \u5FC5\u987B\u662F\u53EF\u8BFB\u3001\u53EF\u6267\u884C\u7684\u6B65\u9AA4\uFF0C\u4E0D\u80FD\u662F\u4E00\u53E5\u6CDB\u6CDB\u5907\u6CE8`, { rule_id: "test_suite.case.content_steps" });
16254
+ }
16255
+ }
16256
+ function validatePreflightEvidence(filePath, caseId, row, prepTokens) {
16257
+ if (!prepTokens.precondition_check) {
16258
+ fail(`${filePath}:${caseId}: \`prep_data\` \u5FC5\u987B\u5305\u542B \`precondition_check=\`\uFF0C\u5426\u5219\u53EA\u80FD\u8FDB\u5165\u51C6\u5907\u9636\u6BB5\uFF0C\u4E0D\u80FD\u5F00\u59CB\u6B63\u5F0F E2E \u6267\u884C`, { rule_id: "test_suite.case.precondition_check" });
16259
+ }
16260
+ if (!prepTokens.browser_tool || !BROWSER_TOOL_RE.test(prepTokens.browser_tool)) {
16261
+ fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E\u6D4F\u89C8\u5668\u5DE5\u5177\u8BC1\u636E\uFF0C\u4F8B\u5982 \`browser_tool=Chrome DevTools\` \u6216 AppleScript fallback`, { rule_id: "test_suite.case.browser_tool" });
16262
+ }
16263
+ if (!prepTokens.live_draft || !LIVE_DRAFT_RE.test(prepTokens.live_draft)) {
16264
+ fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E\u672C\u8F6E\u76EE\u6807\u662F live \u53D1\u5E03\u6001\u8FD8\u662F draft \u8349\u7A3F\u6001`, { rule_id: "test_suite.case.live_draft" });
16265
+ }
16266
+ if (!prepTokens.state_file && !prepTokens.report_run) {
16267
+ fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E .codex/tmp/e2e_states \u72B6\u6001\u6587\u4EF6\u6216 .ai_test/report/<run> \u62A5\u544A\u8BC1\u636E\u8DEF\u5F84`, { rule_id: "test_suite.case.state_file" });
16268
+ }
16269
+ }
16270
+ function validateErrorCaptureEvidence(filePath, caseId, row) {
16271
+ const caseText = [row.type, row.title, row.preconditions, row.steps, row.expected_result, row.tags].join(" ");
16272
+ if (!ERROR_CAPTURE_CASE_RE.test(caseText)) return;
16273
+ const evidenceText = [row.prep_data, row.steps, row.expected_result, row.evidence_required].join(" ");
16274
+ if (!ERROR_CAPTURE_EVIDENCE_RE.test(evidenceText)) {
16275
+ fail(`${filePath}:${caseId}: \u8D1F\u5411/\u9519\u8BEF\u63D0\u793A\u7528\u4F8B\u5FC5\u987B\u5305\u542B expected_error_text \u6216 error_capture_required\uFF0C\u5E76\u8981\u6C42\u771F\u5B9E\u63D0\u793A\u6587\u6848\u622A\u56FE`, { rule_id: "test_suite.case.error_capture" });
16276
+ }
16277
+ }
16278
+ function validateResumePolicy(filePath, caseId, row, prepTokens) {
16279
+ const text5 = [row.preconditions, row.prep_data, row.steps, row.expected_result, row.evidence_required, row.tags].join(" ");
16280
+ if (!/(人工介入|手工|补救|续跑|dirty_resumed|resume|局部复核|partial rerun)/i.test(text5)) return;
16281
+ const policy = prepTokens.resume_policy || text5;
16282
+ if (!RESUME_POLICY_VALUE_RE.test(policy)) {
16283
+ fail(`${filePath}:${caseId}: \u4EBA\u5DE5\u4ECB\u5165\u6216\u7EED\u8DD1\u7528\u4F8B\u5FC5\u987B\u58F0\u660E \`resume_policy=full_rerun|checkpoint|evidence_only\``, { rule_id: "test_suite.case.resume_policy" });
16284
+ }
16285
+ if (!/dirty_resumed|局部复核|partial|从头重跑|检查点/.test(text5)) {
16286
+ fail(`${filePath}:${caseId}: \u4EBA\u5DE5\u4ECB\u5165\u6216\u7EED\u8DD1\u7528\u4F8B\u5FC5\u987B\u6807\u8BB0 dirty_resumed\uFF0C\u6216\u660E\u786E\u8BF4\u660E\u5C40\u90E8/\u5B8C\u6574\u91CD\u8DD1\u8303\u56F4`, { rule_id: "test_suite.case.resume_scope" });
16287
+ }
16288
+ }
16289
+ function validateMultiRoleEvidence(filePath, caseId, row, prepTokens) {
16290
+ const text5 = [row.roles, row.prep_data, row.steps, row.expected_result, row.evidence_required, row.tags].join(" ");
16291
+ if (!MULTI_ROLE_VALUE_RE.test(row.roles) && !/多角色|跨角色/.test(text5)) return;
16292
+ if (!prepTokens.login_profile) {
16293
+ fail(`${filePath}:${caseId}: \u591A\u89D2\u8272 E2E \u7528\u4F8B\u5FC5\u987B\u8BB0\u5F55\u6BCF\u4E2A\u89D2\u8272\u7684 login_profile`, { rule_id: "test_suite.case.multi_role_login_profile" });
16294
+ }
16295
+ const hasMockUser = Boolean(prepTokens.mock_user) || /bpmax-user-mock-operator|mock_user|模拟用户.*[=,,]/i.test(text5);
16296
+ if (!hasMockUser) {
16297
+ fail(`${filePath}:${caseId}: \u591A\u89D2\u8272 E2E \u7528\u4F8B\u5FC5\u987B\u8BB0\u5F55 mock_user \u6216 bpmax-user-mock-operator\uFF0C\u8BF4\u660E\u5982\u4F55\u5207\u6362\u8EAB\u4EFD`, { rule_id: "test_suite.case.multi_role_mock_user" });
16298
+ }
16299
+ const hasUnmock = Boolean(prepTokens.unmock_done) || /unmock|退出模拟|恢复身份|恢复管理员/i.test(text5);
16300
+ if (!hasUnmock) {
16301
+ fail(`${filePath}:${caseId}: \u591A\u89D2\u8272 E2E \u7528\u4F8B\u5FC5\u987B\u8BB0\u5F55 unmock_done\uFF0C\u8BF4\u660E\u6D4B\u8BD5\u7ED3\u675F\u540E\u5982\u4F55\u6062\u590D\u539F\u59CB\u8EAB\u4EFD`, { rule_id: "test_suite.case.multi_role_unmock" });
16302
+ }
16303
+ if (!/(分别截图|独立截图|每个角色|separate evidence|per-role|角色证据)/i.test(text5)) {
16304
+ fail(`${filePath}:${caseId}: \u591A\u89D2\u8272 E2E \u7528\u4F8B\u5FC5\u987B\u8981\u6C42\u6BCF\u4E2A\u89D2\u8272\u5355\u72EC\u6D4F\u89C8\u5668\u8BC1\u636E\uFF0C\u4E0D\u80FD\u590D\u7528\u622A\u56FE`, { rule_id: "test_suite.case.multi_role_screenshot" });
16305
+ }
16306
+ }
15050
16307
  function bootstrapActionForCase(row) {
15051
16308
  const rawText = [row.title, row.prep_data, row.steps, row.evidence_required, row.tags].join(" ");
15052
16309
  const text5 = rawText.toLowerCase();
@@ -15066,6 +16323,7 @@ async function validateCase(filePath, row, seen) {
15066
16323
  if (!caseId) fail(`${filePath}: case_id is required`);
15067
16324
  if (seen.has(caseId)) fail(`${filePath}: duplicate case_id \`${caseId}\``);
15068
16325
  seen.add(caseId);
16326
+ validateReadableCaseContent(filePath, caseId, row);
15069
16327
  for (const field of ["title", "config_basis", "steps", "expected_result", "status", "updated_at"]) {
15070
16328
  if (!row[field].trim()) fail(`${filePath}:${caseId}: \`${field}\` is required`);
15071
16329
  }
@@ -15109,14 +16367,18 @@ async function validateCase(filePath, row, seen) {
15109
16367
  if (UUID_RE2.test(browserText)) fail(`${filePath}:${caseId}: browser-executed cases must not use UUID as the execution entrypoint`);
15110
16368
  if (YBS_NONZERO_DETAIL_RE.test(browserText)) fail(`${filePath}:${caseId}: YBS detail URLs must use /w:ybs/project_detail/0/<project_id> unless verified otherwise`);
15111
16369
  if (YBS_PC_CREATE_WRONG_RE.test(browserText)) fail(`${filePath}:${caseId}: YBS PC create URLs must use /w:ybs/project/create?flow_type=<flow_type>`);
16370
+ validatePreflightEvidence(filePath, caseId, row, prepTokens);
16371
+ validateErrorCaptureEvidence(filePath, caseId, row);
16372
+ validateResumePolicy(filePath, caseId, row, prepTokens);
16373
+ validateMultiRoleEvidence(filePath, caseId, row, prepTokens);
15112
16374
  validateBusinessTestData(filePath, caseId, row);
15113
16375
  }
15114
16376
  async function collectE2eAccelerationGaps(root) {
15115
16377
  const dirs = await scenarioDirs(root);
15116
16378
  const gaps = [];
15117
16379
  for (const dir of dirs) {
15118
- const scenarioId = path12.basename(dir);
15119
- const casesPath = path12.join(dir, "cases.csv");
16380
+ const scenarioId = path13.basename(dir);
16381
+ const casesPath = path13.join(dir, "cases.csv");
15120
16382
  if (!await exists3(casesPath)) {
15121
16383
  continue;
15122
16384
  }
@@ -15139,11 +16401,11 @@ async function collectE2eAccelerationGaps(root) {
15139
16401
  async function scenarioDirs(root) {
15140
16402
  if (!await exists3(root)) return [];
15141
16403
  const items = await readdir5(root, { withFileTypes: true });
15142
- return items.filter((item) => item.isDirectory()).map((item) => path12.join(root, item.name)).sort();
16404
+ return items.filter((item) => item.isDirectory()).map((item) => path13.join(root, item.name)).sort();
15143
16405
  }
15144
16406
  async function validateScenario(scenarioDir) {
15145
16407
  const metadata = await validateReadme(scenarioDir);
15146
- const casesPath = path12.join(scenarioDir, "cases.csv");
16408
+ const casesPath = path13.join(scenarioDir, "cases.csv");
15147
16409
  const rows = await readCases(casesPath);
15148
16410
  if (rows.length === 0) fail(`${casesPath}: at least one case is required`);
15149
16411
  const seen = /* @__PURE__ */ new Set();
@@ -15227,9 +16489,9 @@ function validateLatestProofObject(proofPath, proof) {
15227
16489
  }
15228
16490
  function scenarioPath(root, scenario) {
15229
16491
  if (!SCENARIO_ID_RE.test(scenario)) fail(`invalid scenario id: ${scenario}`);
15230
- const rootResolved = path12.resolve(root);
15231
- const candidate = path12.resolve(root, scenario);
15232
- if (!candidate.startsWith(`${rootResolved}${path12.sep}`) && candidate !== rootResolved) {
16492
+ const rootResolved = path13.resolve(root);
16493
+ const candidate = path13.resolve(root, scenario);
16494
+ if (!candidate.startsWith(`${rootResolved}${path13.sep}`) && candidate !== rootResolved) {
15233
16495
  fail(`scenario path escapes root: ${candidate}`);
15234
16496
  }
15235
16497
  return candidate;
@@ -15238,13 +16500,13 @@ async function fileMap(root) {
15238
16500
  const result = /* @__PURE__ */ new Map();
15239
16501
  async function walk(dir) {
15240
16502
  for (const item of await readdir5(dir, { withFileTypes: true })) {
15241
- const itemPath = path12.join(dir, item.name);
15242
- const rel = path12.relative(root, itemPath);
15243
- if (rel.split(path12.sep)[0] === COPY_DIFF_DIR) continue;
16503
+ const itemPath = path13.join(dir, item.name);
16504
+ const rel = path13.relative(root, itemPath);
16505
+ if (rel.split(path13.sep)[0] === COPY_DIFF_DIR) continue;
15244
16506
  if (item.isDirectory()) {
15245
16507
  await walk(itemPath);
15246
16508
  } else if (item.isFile()) {
15247
- result.set(rel.split(path12.sep).join("/"), itemPath);
16509
+ result.set(rel.split(path13.sep).join("/"), itemPath);
15248
16510
  }
15249
16511
  }
15250
16512
  }
@@ -15315,7 +16577,7 @@ async function buildCopyDiff(src, dst, operation) {
15315
16577
  return {
15316
16578
  manifest: {
15317
16579
  operation,
15318
- scenario_id: path12.basename(src),
16580
+ scenario_id: path13.basename(src),
15319
16581
  source: src,
15320
16582
  destination: dst,
15321
16583
  generated_at: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "+00:00"),
@@ -15328,12 +16590,12 @@ async function buildCopyDiff(src, dst, operation) {
15328
16590
  };
15329
16591
  }
15330
16592
  async function writeCopyDiffArtifacts(dst, artifacts) {
15331
- const diffDir = path12.join(dst, COPY_DIFF_DIR);
15332
- await mkdir11(diffDir, { recursive: true });
15333
- await writeFile11(path12.join(diffDir, "last.diff"), artifacts.diff, "utf8");
15334
- await writeFile11(path12.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
16593
+ const diffDir = path13.join(dst, COPY_DIFF_DIR);
16594
+ await mkdir12(diffDir, { recursive: true });
16595
+ await writeFile12(path13.join(diffDir, "last.diff"), artifacts.diff, "utf8");
16596
+ await writeFile12(path13.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
15335
16597
  `, "utf8");
15336
- return path12.join(diffDir, "last.diff");
16598
+ return path13.join(diffDir, "last.diff");
15337
16599
  }
15338
16600
  function summarizeCopyDiff(artifacts) {
15339
16601
  const files = Array.isArray(artifacts.manifest.files) ? artifacts.manifest.files : [];
@@ -15359,14 +16621,14 @@ async function copyScenarioTree(src, dst, replace, operation) {
15359
16621
  artifacts = await buildCopyDiff(src, dst, operation);
15360
16622
  await rm4(dst, { recursive: true, force: true });
15361
16623
  }
15362
- await mkdir11(path12.dirname(dst), { recursive: true });
16624
+ await mkdir12(path13.dirname(dst), { recursive: true });
15363
16625
  await cp3(src, dst, { recursive: true });
15364
16626
  return artifacts ? { path: await writeCopyDiffArtifacts(dst, artifacts), summary: summarizeCopyDiff(artifacts) } : {};
15365
16627
  }
15366
16628
  async function copyDiffPreview(src, dst, operation) {
15367
- const previewDir = path12.join(DEFAULT_TMP_ROOT, `${operation}-${path12.basename(src)}-copy-diff`);
16629
+ const previewDir = path13.join(DEFAULT_TMP_ROOT, `${operation}-${path13.basename(src)}-copy-diff`);
15368
16630
  await rm4(previewDir, { recursive: true, force: true });
15369
- await mkdir11(previewDir, { recursive: true });
16631
+ await mkdir12(previewDir, { recursive: true });
15370
16632
  const artifacts = await buildCopyDiff(src, dst, operation);
15371
16633
  return { path: await writeCopyDiffArtifacts(previewDir, artifacts), summary: summarizeCopyDiff(artifacts) };
15372
16634
  }
@@ -15386,7 +16648,7 @@ async function draftUpdate(options) {
15386
16648
  return { destination: dst, copy_diff: copyDiff.path, copy_diff_summary: copyDiff.summary };
15387
16649
  }
15388
16650
  async function validateReviewGate(scenarioDir) {
15389
- const reviewPath = path12.join(scenarioDir, "review.json");
16651
+ const reviewPath = path13.join(scenarioDir, "review.json");
15390
16652
  if (!await exists3(reviewPath)) reviewFail(reviewPath, `${scenarioDir}: missing review.json; run multi-subagent SKILL review before promote`);
15391
16653
  let review;
15392
16654
  try {
@@ -15394,7 +16656,7 @@ async function validateReviewGate(scenarioDir) {
15394
16656
  } catch (error) {
15395
16657
  reviewFail(reviewPath, `${reviewPath}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
15396
16658
  }
15397
- if (review.scenario_id !== path12.basename(scenarioDir)) reviewFail(reviewPath, `${reviewPath}: scenario_id must match directory name`);
16659
+ if (review.scenario_id !== path13.basename(scenarioDir)) reviewFail(reviewPath, `${reviewPath}: scenario_id must match directory name`);
15398
16660
  if (!review.latest_proof || typeof review.latest_proof !== "object" || Array.isArray(review.latest_proof)) reviewFail(reviewPath, `${reviewPath}: latest_proof is required`);
15399
16661
  validateLatestProofObject(reviewPath, review.latest_proof);
15400
16662
  if (!REVIEW_STATUSES.has(String(review.status))) reviewFail(reviewPath, `${reviewPath}: status must be one of ${JSON.stringify([...REVIEW_STATUSES].sort())}`);
@@ -15503,9 +16765,9 @@ async function initOrRepairReview(options) {
15503
16765
  const scenarioDir = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
15504
16766
  if (!await exists3(scenarioDir)) fail(`draft scenario not found: ${scenarioDir}`);
15505
16767
  await validateReadme(scenarioDir);
15506
- const rows = await readCases(path12.join(scenarioDir, "cases.csv"));
16768
+ const rows = await readCases(path13.join(scenarioDir, "cases.csv"));
15507
16769
  const proof = await readLatestProof(options.latestProof);
15508
- const reviewPath = path12.join(scenarioDir, "review.json");
16770
+ const reviewPath = path13.join(scenarioDir, "review.json");
15509
16771
  let existing;
15510
16772
  const existed = await exists3(reviewPath);
15511
16773
  if (existed) {
@@ -15516,8 +16778,8 @@ async function initOrRepairReview(options) {
15516
16778
  existing = {};
15517
16779
  }
15518
16780
  }
15519
- const review = mergeReviewDraft(path12.basename(scenarioDir), proof, rows, existing);
15520
- await writeFile11(reviewPath, `${JSON.stringify(review, null, 2)}
16781
+ const review = mergeReviewDraft(path13.basename(scenarioDir), proof, rows, existing);
16782
+ await writeFile12(reviewPath, `${JSON.stringify(review, null, 2)}
15521
16783
  `, "utf8");
15522
16784
  return {
15523
16785
  ok: true,
@@ -15551,48 +16813,78 @@ async function nextReportDir(root = DEFAULT_REPORT_ROOT, create = false, today =
15551
16813
  String(today.getDate()).padStart(2, "0")
15552
16814
  ].join("");
15553
16815
  const dirs = await scenarioDirs(root);
15554
- const nums = dirs.map((dir) => path12.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
15555
- const reportDir = path12.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
16816
+ const nums = dirs.map((dir) => path13.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
16817
+ const reportDir = path13.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
15556
16818
  if (create) {
15557
- await mkdir11(path12.join(reportDir, "screenshots"), { recursive: true });
15558
- await writeFile11(
15559
- path12.join(reportDir, "summary.md"),
15560
- ["# BPMAX E2E \u6D4B\u8BD5\u62A5\u544A\u6C47\u603B", "", `run_id: ${path12.basename(reportDir)}`, "status: draft", "", "## \u573A\u666F\u62A5\u544A", "", "## \u603B\u7ED3", ""].join("\n"),
16819
+ await mkdir12(path13.join(reportDir, "screenshots"), { recursive: true });
16820
+ await writeFile12(
16821
+ path13.join(reportDir, "summary.md"),
16822
+ ["# BPMAX E2E \u6D4B\u8BD5\u62A5\u544A\u6C47\u603B", "", `run_id: ${path13.basename(reportDir)}`, "status: draft", "", "## \u573A\u666F\u62A5\u544A", "", "## \u603B\u7ED3", ""].join("\n"),
15561
16823
  "utf8"
15562
16824
  );
15563
16825
  }
15564
16826
  return reportDir;
15565
16827
  }
16828
+ function reportKeyValue(text5, key) {
16829
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16830
+ const match = new RegExp(`^${escaped}\\s*(.+)$`, "im").exec(text5);
16831
+ return match?.[1]?.trim() ?? "";
16832
+ }
16833
+ function reportCaseList(text5, key) {
16834
+ const value = reportKeyValue(text5, key);
16835
+ return value.split(/[,\s,、;;]+/).map((item) => item.trim()).filter((item) => /^[A-Za-z0-9_-]+$/.test(item));
16836
+ }
15566
16837
  async function lintReport(root = DEFAULT_REPORT_ROOT) {
15567
16838
  if (!await exists3(root)) return [`report root not found: ${root}`];
15568
16839
  const errors = [];
15569
16840
  for (const runDir of await scenarioDirs(root)) {
15570
- const runName = path12.basename(runDir);
16841
+ const runName = path13.basename(runDir);
15571
16842
  if (!RUN_RE.test(runName)) {
15572
16843
  errors.push(`${runDir}: run directory name must be YYYYMMDD-NNN`);
15573
16844
  continue;
15574
16845
  }
15575
- if (!await exists3(path12.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
16846
+ if (!await exists3(path13.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
15576
16847
  const files = await readdir5(runDir);
15577
16848
  const scenarioReports = files.filter((file) => file.endsWith(".md") && file !== "summary.md");
15578
16849
  if (scenarioReports.length === 0) errors.push(`${runDir}: missing scenario report markdown`);
15579
16850
  for (const reportName of scenarioReports) {
15580
- const reportPath = path12.join(runDir, reportName);
16851
+ const reportPath = path13.join(runDir, reportName);
15581
16852
  const text5 = await readText(reportPath);
15582
16853
  for (const key of REPORT_REQUIRED_KEYS) if (!text5.includes(key)) errors.push(`${reportPath}: missing \`${key}\``);
16854
+ for (const key of REPORT_EXECUTION_KEYS) if (!text5.includes(key)) errors.push(`${reportPath}: missing \`${key}\``);
15583
16855
  for (const heading of REPORT_REQUIRED_HEADINGS) if (!text5.includes(heading)) errors.push(`${reportPath}: missing \`${heading}\``);
16856
+ const plannedCases = reportCaseList(text5, "planned_cases:");
16857
+ const executedCases = reportCaseList(text5, "executed_cases:");
16858
+ const missingExecuted = plannedCases.filter((caseId) => !executedCases.includes(caseId));
16859
+ const unexpectedExecuted = executedCases.filter((caseId) => !plannedCases.includes(caseId));
16860
+ if (plannedCases.length > 0 && missingExecuted.length > 0) {
16861
+ errors.push(`[test_suite.report.case_reconciliation] ${reportPath}: planned_cases \u4E2D\u5B58\u5728\u672A\u6267\u884C\u7528\u4F8B: ${missingExecuted.join(", ")}\uFF1B\u62A5\u544A\u5FC5\u987B\u5199\u660E blocked/not run \u539F\u56E0\u5E76\u964D\u7EA7\u7ED3\u8BBA`);
16862
+ }
16863
+ if (unexpectedExecuted.length > 0) {
16864
+ errors.push(`[test_suite.report.case_reconciliation] ${reportPath}: executed_cases \u5305\u542B\u4E0D\u5728 planned_cases \u4E2D\u7684\u7528\u4F8B: ${unexpectedExecuted.join(", ")}`);
16865
+ }
16866
+ const resultValue = reportKeyValue(text5, "result:").toLowerCase();
16867
+ if (NOT_RUN_RE.test(text5) && /pass|passed|complete|success|通过|完整/.test(resultValue) && !/partial|stage|blocked|阶段|局部|不完整/.test(resultValue)) {
16868
+ errors.push(`[test_suite.report.not_run_downgrade] ${reportPath}: \u62A5\u544A\u5B58\u5728 not-run/\u672A\u6267\u884C\u7528\u4F8B\u4F46 result \u662F\u5B8C\u6574\u7ED3\u8BBA\uFF1B\u5FC5\u987B\u964D\u7EA7\u4E3A partial/stage \u6216\u8BF4\u660E\u7528\u6237\u786E\u8BA4\u7F29\u5C0F\u8303\u56F4`);
16869
+ }
16870
+ if (PAGE_CONCLUSION_RE.test(text5) && !BROWSER_TOOL_RE.test(text5)) {
16871
+ errors.push(`[test_suite.report.page_conclusion_browser] ${reportPath}: \u9875\u9762/\u6D4F\u89C8\u5668\u7ED3\u8BBA\u5FC5\u987B\u5305\u542B browser_tool \u8BC1\u636E\uFF1BAPI/readback \u4E0D\u80FD\u5192\u5145\u9875\u9762\u9A8C\u8BC1`);
16872
+ }
16873
+ if (/browser[_ -]?blocked|浏览器阻塞|无可用浏览器工具/i.test(text5) && !/browser_status:\s*blocked|页面结论停止|停止页面结论/i.test(text5)) {
16874
+ errors.push(`[test_suite.report.browser_blocked] ${reportPath}: \u6D4F\u89C8\u5668\u963B\u585E\u62A5\u544A\u5FC5\u987B\u4F7F\u7528 browser_status: blocked \u6A21\u677F\uFF0C\u5E76\u505C\u6B62\u9875\u9762\u7ED3\u8BBA`);
16875
+ }
15584
16876
  const imageRefs = [...text5.matchAll(IMAGE_RE)].map((match) => match[1]);
15585
16877
  if (imageRefs.length === 0) errors.push(`${reportPath}: missing embedded screenshot image`);
15586
- const screenshotsDir = path12.join(runDir, "screenshots");
16878
+ const screenshotsDir = path13.join(runDir, "screenshots");
15587
16879
  if (!await exists3(screenshotsDir)) errors.push(`${runDir}: missing screenshots directory`);
15588
16880
  for (const imageRef of imageRefs) {
15589
16881
  if (imageRef.includes("://")) {
15590
16882
  errors.push(`${reportPath}: screenshot must be a local file under this run's screenshots directory`);
15591
16883
  continue;
15592
16884
  }
15593
- const imagePath = path12.resolve(path12.dirname(reportPath), imageRef);
15594
- const screenshotsResolved = path12.resolve(screenshotsDir);
15595
- if (!imagePath.startsWith(`${screenshotsResolved}${path12.sep}`)) {
16885
+ const imagePath = path13.resolve(path13.dirname(reportPath), imageRef);
16886
+ const screenshotsResolved = path13.resolve(screenshotsDir);
16887
+ if (!imagePath.startsWith(`${screenshotsResolved}${path13.sep}`)) {
15596
16888
  errors.push(`${reportPath}: image reference must stay under this run's screenshots directory: ${imageRef}`);
15597
16889
  continue;
15598
16890
  }
@@ -15603,10 +16895,10 @@ async function lintReport(root = DEFAULT_REPORT_ROOT) {
15603
16895
  return errors;
15604
16896
  }
15605
16897
  async function validateCopyDiffArtifacts(scenarioDir) {
15606
- const diffDir = path12.join(scenarioDir, COPY_DIFF_DIR);
16898
+ const diffDir = path13.join(scenarioDir, COPY_DIFF_DIR);
15607
16899
  if (!await exists3(diffDir)) return;
15608
- const manifestPath = path12.join(diffDir, "last.json");
15609
- const diffPath = path12.join(diffDir, "last.diff");
16900
+ const manifestPath = path13.join(diffDir, "last.json");
16901
+ const diffPath = path13.join(diffDir, "last.diff");
15610
16902
  if (!await exists3(manifestPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.json is required when copy diff artifacts exist`);
15611
16903
  if (!await exists3(diffPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.diff is required when copy diff artifacts exist`);
15612
16904
  let manifest;
@@ -15618,7 +16910,7 @@ async function validateCopyDiffArtifacts(scenarioDir) {
15618
16910
  for (const key of ["operation", "scenario_id", "source", "destination", "generated_at", "summary", "diff_file", "files"]) {
15619
16911
  if (!(key in manifest)) fail(`${manifestPath}: missing \`${key}\``);
15620
16912
  }
15621
- if (manifest.scenario_id !== path12.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
16913
+ if (manifest.scenario_id !== path13.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
15622
16914
  if (manifest.diff_file !== "last.diff") fail(`${manifestPath}: diff_file must be last.diff`);
15623
16915
  if (!(await readText(diffPath)).trim()) fail(`${diffPath}: copy diff must not be empty`);
15624
16916
  }
@@ -15666,8 +16958,8 @@ function registerTestSuiteCommands(program2) {
15666
16958
  }
15667
16959
 
15668
16960
  // src/core/update.ts
15669
- import { access as access2, mkdir as mkdir12, readFile as readFile16, realpath, writeFile as writeFile12 } from "fs/promises";
15670
- import path13 from "path";
16961
+ import { access as access2, mkdir as mkdir13, readFile as readFile16, realpath, writeFile as writeFile13 } from "fs/promises";
16962
+ import path14 from "path";
15671
16963
  var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org/";
15672
16964
  var UPDATE_STATE_FILE = "update-state.json";
15673
16965
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -15779,7 +17071,7 @@ async function fetchLatestVersion(options = {}) {
15779
17071
  }
15780
17072
  }
15781
17073
  function updateStatePath(configDir = getConfigDir()) {
15782
- return path13.join(configDir, UPDATE_STATE_FILE);
17074
+ return path14.join(configDir, UPDATE_STATE_FILE);
15783
17075
  }
15784
17076
  async function readUpdateState(configDir) {
15785
17077
  try {
@@ -15794,8 +17086,8 @@ async function readUpdateState(configDir) {
15794
17086
  }
15795
17087
  }
15796
17088
  async function writeUpdateState(state, configDir = getConfigDir()) {
15797
- await mkdir12(configDir, { recursive: true });
15798
- await writeFile12(updateStatePath(configDir), JSON.stringify(state), "utf8");
17089
+ await mkdir13(configDir, { recursive: true });
17090
+ await writeFile13(updateStatePath(configDir), JSON.stringify(state), "utf8");
15799
17091
  }
15800
17092
  async function checkCachedUpdate(currentVersion, configDir = getConfigDir()) {
15801
17093
  if (process.env.BPMAX_CLI_NO_UPDATE_NOTIFIER) {
@@ -15847,7 +17139,7 @@ async function findNpmPath() {
15847
17139
  }
15848
17140
  function detectInstallMethod(input) {
15849
17141
  const resolvedPath = input.executablePath || "";
15850
- const method = resolvedPath.includes(`node_modules${path13.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
17142
+ const method = resolvedPath.includes(`node_modules${path14.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
15851
17143
  return {
15852
17144
  method,
15853
17145
  resolvedPath,