bpmax-cli 0.1.44-beta.12 → 0.1.44-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -231,8 +231,8 @@ function throwCliGovernanceUnsupportedIfNeeded(error, fallbackPath) {
231
231
  }
232
232
  throw error;
233
233
  }
234
- function normalizePath(path9) {
235
- let normalized = path9.split("?")[0] || "/";
234
+ function normalizePath(path11) {
235
+ let normalized = path11.split("?")[0] || "/";
236
236
  if (!normalized.startsWith("/")) {
237
237
  normalized = `/${normalized}`;
238
238
  }
@@ -242,17 +242,17 @@ function normalizePath(path9) {
242
242
  }
243
243
  return normalized.replace(/\/+$/g, "") || "/api";
244
244
  }
245
- function getNumber(value, path9) {
246
- const result = getValue(value, path9);
245
+ function getNumber(value, path11) {
246
+ const result = getValue(value, path11);
247
247
  return typeof result === "number" ? result : void 0;
248
248
  }
249
- function getString(value, path9) {
250
- const result = getValue(value, path9);
249
+ function getString(value, path11) {
250
+ const result = getValue(value, path11);
251
251
  return typeof result === "string" ? result : void 0;
252
252
  }
253
- function getValue(value, path9) {
253
+ function getValue(value, path11) {
254
254
  let current = value;
255
- for (const key of path9) {
255
+ for (const key of path11) {
256
256
  if (!current || typeof current !== "object" || !(key in current)) {
257
257
  return void 0;
258
258
  }
@@ -262,10 +262,10 @@ function getValue(value, path9) {
262
262
  }
263
263
 
264
264
  // src/core/capabilities.ts
265
- function capabilityForRequest(method, path9) {
265
+ function capabilityForRequest(method, path11) {
266
266
  const normalizedMethod = method.toUpperCase();
267
- const normalizedPath = normalizePath2(path9);
268
- const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path9);
267
+ const normalizedPath = normalizePath2(path11);
268
+ const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path11);
269
269
  if (normalizedPath === "/cli/capabilities") {
270
270
  return void 0;
271
271
  }
@@ -281,6 +281,11 @@ function capabilityForRequest(method, path9) {
281
281
  if (normalizedMethod === "DELETE" && /^\/cli\/memory\/[^/]+$/.test(normalizedPath)) return "memory.delete";
282
282
  if (normalizedMethod === "GET" && normalizedPath === "/user/current") return "user.current";
283
283
  if (normalizedMethod === "GET" && normalizedPath === "/workspace/by_key") return "config.workspace_flow.export";
284
+ if (normalizedMethod === "PUT" && normalizedPath === "/workspace/workspace_flow") return "config.workspace_flow.submit";
285
+ if (normalizedMethod === "GET" && /^\/workspace\/[^/]+$/.test(normalizedPath)) return "config.workspace.export";
286
+ if (normalizedMethod === "POST" && normalizedPath === "/workspace") return "config.workspace.create";
287
+ if (normalizedMethod === "PUT" && /^\/workspace\/[^/]+$/.test(normalizedPath)) return "config.workspace.submit";
288
+ if (normalizedMethod === "DELETE" && /^\/workspace\/[^/]+$/.test(normalizedPath)) return "config.workspace.delete";
284
289
  if (normalizedMethod === "GET" && normalizedPath === "/flow/flow_type") return "flow.list";
285
290
  if (normalizedMethod === "POST" && normalizedPath === "/flow/flow_type") return "config.flow_template.create";
286
291
  if (normalizedMethod === "GET" && normalizedPath === "/flow/options") return "flow.options";
@@ -331,7 +336,6 @@ function capabilityForRequest(method, path9) {
331
336
  if (normalizedMethod === "POST" && normalizedPath === "/configuration") return "config.nav_config.create";
332
337
  if (normalizedMethod === "PUT" && /^\/configuration\/[^/]+$/.test(normalizedPath)) return "config.nav_config.submit";
333
338
  if (normalizedMethod === "DELETE" && /^\/configuration\/[^/]+$/.test(normalizedPath)) return "config.nav_config.delete";
334
- if (normalizedMethod === "PUT" && normalizedPath === "/workspace/workspace_flow") return "config.workspace_flow.submit";
335
339
  if (normalizedMethod === "POST" && normalizedPath === "/project_staging/prefill") return "project.create";
336
340
  if (normalizedMethod === "POST" && normalizedPath === "/project/search") return "project.search";
337
341
  if (normalizedMethod === "POST" && normalizedPath === "/project/list") return "project.list";
@@ -412,8 +416,8 @@ async function updateProfileCapabilities(profileName, cache) {
412
416
  };
413
417
  await saveConfig(config);
414
418
  }
415
- function flowPageTemplateCapabilityPrefix(path9) {
416
- const query = path9.includes("?") ? path9.slice(path9.indexOf("?") + 1) : "";
419
+ function flowPageTemplateCapabilityPrefix(path11) {
420
+ const query = path11.includes("?") ? path11.slice(path11.indexOf("?") + 1) : "";
417
421
  const type = new URLSearchParams(query).get("type");
418
422
  if (type === "2") {
419
423
  return "config.project_detail_template";
@@ -426,8 +430,8 @@ function flowPageTemplateCapabilityPrefix(path9) {
426
430
  }
427
431
  return "config.list_template";
428
432
  }
429
- function normalizePath2(path9) {
430
- let normalized = path9.split("?")[0] || "/";
433
+ function normalizePath2(path11) {
434
+ let normalized = path11.split("?")[0] || "/";
431
435
  if (!normalized.startsWith("/")) {
432
436
  normalized = `/${normalized}`;
433
437
  }
@@ -444,7 +448,7 @@ function normalizePath2(path9) {
444
448
  // package.json
445
449
  var package_default = {
446
450
  name: "bpmax-cli",
447
- version: "0.1.44-beta.12",
451
+ version: "0.1.44-beta.14",
448
452
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
449
453
  type: "module",
450
454
  bin: {
@@ -491,8 +495,8 @@ var NPM_PACKAGE = "bpmax-cli";
491
495
  // src/core/terminal.ts
492
496
  import { randomUUID } from "crypto";
493
497
  import os from "os";
494
- function isCliControlPath(path9) {
495
- const normalized = normalizeApiPath(path9);
498
+ function isCliControlPath(path11) {
499
+ const normalized = normalizeApiPath(path11);
496
500
  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";
497
501
  }
498
502
  function commandSummary(argv = process.argv) {
@@ -656,8 +660,8 @@ async function updateProfileTerminal(profile, terminalId, status) {
656
660
  profile.config.terminal_status = status;
657
661
  profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
658
662
  }
659
- function normalizeApiPath(path9) {
660
- let normalized = path9.split("?")[0] || "/";
663
+ function normalizeApiPath(path11) {
664
+ let normalized = path11.split("?")[0] || "/";
661
665
  if (!normalized.startsWith("/")) {
662
666
  normalized = `/${normalized}`;
663
667
  }
@@ -775,14 +779,14 @@ function recordCommandAuditResult(value) {
775
779
  state.result_summary = redactAuditValue(value);
776
780
  }
777
781
  }
778
- var ensureApiPath = (path9) => {
779
- if (!path9.startsWith("/")) {
780
- path9 = `/${path9}`;
782
+ var ensureApiPath = (path11) => {
783
+ if (!path11.startsWith("/")) {
784
+ path11 = `/${path11}`;
781
785
  }
782
- if (path9.startsWith("/api/")) {
783
- return path9;
786
+ if (path11.startsWith("/api/")) {
787
+ return path11;
784
788
  }
785
- return `/api${path9}`;
789
+ return `/api${path11}`;
786
790
  };
787
791
  function normalizeWorkspaceForApi(workspace) {
788
792
  const normalized = workspace?.trim();
@@ -828,10 +832,10 @@ function createApiClient(profile) {
828
832
  });
829
833
  return instance;
830
834
  }
831
- async function apiRequest(client, method, path9, options = {}) {
835
+ async function apiRequest(client, method, path11, options = {}) {
832
836
  const profile = clientProfiles.get(client);
833
- const apiPath2 = ensureApiPath(path9);
834
- const capability = options.capability ?? capabilityForRequest(method, path9);
837
+ const apiPath2 = ensureApiPath(path11);
838
+ const capability = options.capability ?? capabilityForRequest(method, path11);
835
839
  const shouldControl = Boolean(profile?.config.api_key) && !isCliControlPath(apiPath2);
836
840
  const reqId = requestId();
837
841
  if (profile) {
@@ -1139,8 +1143,8 @@ async function parseJsonAny(input, label = "JSON input") {
1139
1143
  function isMutatingMethod(method) {
1140
1144
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
1141
1145
  }
1142
- function normalizeApiPath2(path9) {
1143
- let normalized = path9.trim();
1146
+ function normalizeApiPath2(path11) {
1147
+ let normalized = path11.trim();
1144
1148
  const queryIndex = normalized.indexOf("?");
1145
1149
  if (queryIndex >= 0) {
1146
1150
  normalized = normalized.slice(0, queryIndex);
@@ -1157,19 +1161,19 @@ function normalizeApiPath2(path9) {
1157
1161
  }
1158
1162
  return normalized;
1159
1163
  }
1160
- function parseQuery(path9) {
1161
- const queryIndex = path9.indexOf("?");
1162
- return new URLSearchParams(queryIndex >= 0 ? path9.slice(queryIndex + 1) : "");
1164
+ function parseQuery(path11) {
1165
+ const queryIndex = path11.indexOf("?");
1166
+ return new URLSearchParams(queryIndex >= 0 ? path11.slice(queryIndex + 1) : "");
1163
1167
  }
1164
- function isRawConfigPath(method, path9) {
1165
- const normalizedPath = normalizeApiPath2(path9);
1168
+ function isRawConfigPath(method, path11) {
1169
+ const normalizedPath = normalizeApiPath2(path11);
1166
1170
  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)) {
1167
1171
  return true;
1168
1172
  }
1169
1173
  if (normalizedPath === "/flow/list/lightweight" || normalizedPath.startsWith("/flow/configuration/")) {
1170
1174
  return true;
1171
1175
  }
1172
- if (normalizedPath === "/flow" && method === "GET" && parseQuery(path9).has("draft")) {
1176
+ if (normalizedPath === "/flow" && method === "GET" && parseQuery(path11).has("draft")) {
1173
1177
  return true;
1174
1178
  }
1175
1179
  if (normalizedPath.startsWith("/flow/") && !["/flow/flow_type", "/flow/options", "/flow/batch_get"].includes(normalizedPath)) {
@@ -1180,35 +1184,35 @@ function isRawConfigPath(method, path9) {
1180
1184
  }
1181
1185
  return false;
1182
1186
  }
1183
- function assertRawApiPathAllowed(method, path9) {
1184
- if (isRawConfigPath(method, path9)) {
1187
+ function assertRawApiPathAllowed(method, path11) {
1188
+ if (isRawConfigPath(method, path11)) {
1185
1189
  throw new Error(
1186
- `Raw API ${method} ${path9} 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.`
1190
+ `Raw API ${method} ${path11} 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.`
1187
1191
  );
1188
1192
  }
1189
1193
  if (!isMutatingMethod(method)) {
1190
1194
  return;
1191
1195
  }
1192
- const normalizedPath = normalizeApiPath2(path9);
1196
+ const normalizedPath = normalizeApiPath2(path11);
1193
1197
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
1194
1198
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
1195
1199
  if (!isProjectPath || isAllowedProjectReadPost) {
1196
1200
  return;
1197
1201
  }
1198
1202
  throw new Error(
1199
- `Raw API ${method} ${path9} 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.`
1203
+ `Raw API ${method} ${path11} 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.`
1200
1204
  );
1201
1205
  }
1202
1206
  function registerApiCommands(program2) {
1203
- 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, path9, options) => {
1207
+ 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, path11, options) => {
1204
1208
  const normalizedMethod = method.toUpperCase();
1205
- assertRawApiPathAllowed(normalizedMethod, path9);
1209
+ assertRawApiPathAllowed(normalizedMethod, path11);
1206
1210
  if (isMutatingMethod(normalizedMethod) && options.confirmMutating !== true) {
1207
1211
  printResult(options.format, {
1208
1212
  ok: false,
1209
1213
  dry_run: true,
1210
1214
  method: normalizedMethod,
1211
- path: path9,
1215
+ path: path11,
1212
1216
  warning: "Mutating raw API calls require --confirm-mutating. Prefer typed bpmax-cli commands such as step submit."
1213
1217
  });
1214
1218
  return;
@@ -1216,7 +1220,7 @@ function registerApiCommands(program2) {
1216
1220
  const config = await loadConfig();
1217
1221
  const profile = resolveProfile(config, options.profile);
1218
1222
  const client = createApiClient(profile);
1219
- const result = await apiRequest(client, normalizedMethod, path9, {
1223
+ const result = await apiRequest(client, normalizedMethod, path11, {
1220
1224
  params: options.params ? await parseJsonInput(options.params, "--params") : void 0,
1221
1225
  data: await parseJsonAny(options.data, "--data"),
1222
1226
  capability: "api.raw"
@@ -1291,18 +1295,18 @@ function lintDeviceAuthorizationUrl(urlValue, expectedOrigin, expectedWorkspace,
1291
1295
  );
1292
1296
  }
1293
1297
  }
1294
- function apiPath(path9) {
1295
- if (path9.startsWith("/api/")) {
1296
- return path9;
1298
+ function apiPath(path11) {
1299
+ if (path11.startsWith("/api/")) {
1300
+ return path11;
1297
1301
  }
1298
- return `/api${path9.startsWith("/") ? path9 : `/${path9}`}`;
1302
+ return `/api${path11.startsWith("/") ? path11 : `/${path11}`}`;
1299
1303
  }
1300
1304
  function createDeviceRequest(origin) {
1301
1305
  const client = axios2.create({ baseURL: origin, withCredentials: false });
1302
- return async (method, path9, options) => {
1306
+ return async (method, path11, options) => {
1303
1307
  const response = await client.request({
1304
1308
  method,
1305
- url: apiPath(path9),
1309
+ url: apiPath(path11),
1306
1310
  data: options.data
1307
1311
  });
1308
1312
  const body = response.data;
@@ -1711,20 +1715,20 @@ function requireNumericId(value, name) {
1711
1715
  }
1712
1716
  return nextValue;
1713
1717
  }
1714
- function withQuery(path9, query) {
1718
+ function withQuery(path11, query) {
1715
1719
  const params = new URLSearchParams();
1716
1720
  for (const [key, value] of Object.entries(query)) {
1717
1721
  if (value !== void 0) {
1718
1722
  params.set(key, value);
1719
1723
  }
1720
1724
  }
1721
- return `${path9}?${params.toString()}`;
1725
+ return `${path11}?${params.toString()}`;
1722
1726
  }
1723
1727
  function buildBpmaxUrl(profile, kind, params = {}) {
1724
1728
  const origin = normalizeOrigin2(profile.config.origin);
1725
1729
  const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
1726
1730
  const basePath = `/${workspace}`;
1727
- let path9 = basePath;
1731
+ let path11 = basePath;
1728
1732
  const result = {
1729
1733
  kind,
1730
1734
  profile: profile.name,
@@ -1732,15 +1736,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
1732
1736
  workspace
1733
1737
  };
1734
1738
  if (kind === "project-list") {
1735
- path9 = `${basePath}/project`;
1739
+ path11 = `${basePath}/project`;
1736
1740
  } else if (kind === "project-detail") {
1737
1741
  const projectId = requireNumericId(params.projectId, "projectId");
1738
- path9 = `${basePath}/project_detail/0/${projectId}`;
1742
+ path11 = `${basePath}/project_detail/0/${projectId}`;
1739
1743
  result.project_id = projectId;
1740
1744
  } else if (kind === "project-step") {
1741
1745
  const projectId = requireNumericId(params.projectId, "projectId");
1742
1746
  const stepId = requireNumericId(params.stepId, "stepId");
1743
- path9 = withQuery(`${basePath}/projectContinue`, {
1747
+ path11 = withQuery(`${basePath}/projectContinue`, {
1744
1748
  id: projectId,
1745
1749
  step_id: stepId
1746
1750
  });
@@ -1757,15 +1761,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
1757
1761
  ...flowKey ? { key: flowKey } : {},
1758
1762
  ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
1759
1763
  };
1760
- path9 = withQuery(`${basePath}/project/create`, query);
1764
+ path11 = withQuery(`${basePath}/project/create`, query);
1761
1765
  result.flow_type = flowType;
1762
1766
  result.flow_key = flowKey;
1763
1767
  result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
1764
1768
  }
1765
- const url = `${origin}${path9}`;
1769
+ const url = `${origin}${path11}`;
1766
1770
  return {
1767
1771
  ...result,
1768
- path: path9,
1772
+ path: path11,
1769
1773
  url,
1770
1774
  ...kind === "project-create" ? { pc_url: url } : {}
1771
1775
  };
@@ -2427,8 +2431,8 @@ function registerBbsCommands(program2) {
2427
2431
  printResult(options.format, report);
2428
2432
  });
2429
2433
  bbs.command("create").requiredOption("--zip <path>", "Skill zip path").option("--name <name>", "BBS display name").option("--key <key>", "BBS key").option("--scene <scene>", "BBS scene").option("--description <description>", "BBS description").option("--allow-lint-errors", "Allow upload even when local BBS lint reports errors").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
2430
- const lintReport = await lintBusinessSkillZip(options.zip);
2431
- assertLintPassed(lintReport, options.allowLintErrors);
2434
+ const lintReport2 = await lintBusinessSkillZip(options.zip);
2435
+ assertLintPassed(lintReport2, options.allowLintErrors);
2432
2436
  const profile = resolveProfile(await loadConfig(), options.profile);
2433
2437
  const data = {
2434
2438
  ...await zipPayload(options.zip),
@@ -2440,16 +2444,16 @@ function registerBbsCommands(program2) {
2440
2444
  const result = await apiRequest(createApiClient(profile), "POST", "/business_skill", { data });
2441
2445
  printResult(options.format, {
2442
2446
  ...typeof result === "object" && result !== null ? result : { result },
2443
- lint_report: lintReport,
2444
- ...options.allowLintErrors && !lintReport.ok ? { lint_bypassed: true } : {}
2447
+ lint_report: lintReport2,
2448
+ ...options.allowLintErrors && !lintReport2.ok ? { lint_bypassed: true } : {}
2445
2449
  });
2446
2450
  });
2447
2451
  bbs.command("upgrade <keyOrId>").requiredOption("--zip <path>", "Skill zip path").option("--release-note <text>", "Release note").option("--allow-lint-errors", "Allow upload even when local BBS lint reports errors").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
2448
2452
  const profile = resolveProfile(await loadConfig(), options.profile);
2449
2453
  const client = createApiClient(profile);
2450
2454
  const skill = await fetchBusinessSkillByKeyOrId(client, keyOrId);
2451
- const lintReport = await lintBusinessSkillZip(options.zip, { latestVersion: skill.latest_version });
2452
- assertLintPassed(lintReport, options.allowLintErrors);
2455
+ const lintReport2 = await lintBusinessSkillZip(options.zip, { latestVersion: skill.latest_version });
2456
+ assertLintPassed(lintReport2, options.allowLintErrors);
2453
2457
  const data = {
2454
2458
  ...await zipPayload(options.zip),
2455
2459
  release_note: options.releaseNote
@@ -2457,8 +2461,8 @@ function registerBbsCommands(program2) {
2457
2461
  const result = await apiRequest(client, "POST", `/business_skill/${skill.id}/versions`, { data });
2458
2462
  printResult(options.format, {
2459
2463
  ...typeof result === "object" && result !== null ? result : { result },
2460
- lint_report: lintReport,
2461
- ...options.allowLintErrors && !lintReport.ok ? { lint_bypassed: true } : {}
2464
+ lint_report: lintReport2,
2465
+ ...options.allowLintErrors && !lintReport2.ok ? { lint_bypassed: true } : {}
2462
2466
  });
2463
2467
  });
2464
2468
  bbs.command("gate <keyOrId>").requiredOption("--stage <stage>", "Gate stage, for example preflight or verify").requiredOption("--input <json>", "Gate input JSON or @file").option("--skill-dir <path>", "Installed skill directory override").option("--agent <agent>", "Agent adapter", "openclaw").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (keyOrId, options) => {
@@ -2584,8 +2588,8 @@ function registerBbsCommands(program2) {
2584
2588
  const state = await readBusinessSkillState(profile.name, agent);
2585
2589
  const installed = state.skills[skill.key];
2586
2590
  if (installed) {
2587
- const { rm: rm3 } = await import("fs/promises");
2588
- await rm3(installed.install_path, { recursive: true, force: true });
2591
+ const { rm: rm4 } = await import("fs/promises");
2592
+ await rm4(installed.install_path, { recursive: true, force: true });
2589
2593
  await updateBusinessSkillState(profile.name, agent, (current) => {
2590
2594
  delete current.skills[skill.key];
2591
2595
  });
@@ -2649,6 +2653,18 @@ var NAV_DEFAULT_NAME_BY_TYPE = {
2649
2653
  navmenu_mobile: "\u79FB\u52A8\u5BFC\u822A",
2650
2654
  shortcut_mobile: "\u79FB\u52A8\u5FEB\u6377\u5165\u53E3"
2651
2655
  };
2656
+ var MAX_FORM_TEMPLATE_NAME_LENGTH = 20;
2657
+ var FORM_TEMPLATE_ID_CONST_PATTERN = /\b(?:const|let|var)\s+[A-Za-z_$][\w$]*(?:FORM|Form|form)[A-Za-z0-9_$]*(?:TEMPLATE|Template|template)[A-Za-z0-9_$]*(?:ID|Id|id)\s*=\s*\d+\b/;
2658
+ var FORM_TEMPLATE_ID_PROP_PATTERN = /(?:\btemplate_id\b|['"]template_id['"])\s*:\s*\d+\b|\.template_id\s*=\s*\d+\b|\[['"]template_id['"]]\s*=\s*\d+\b/;
2659
+ var FEISHU_CHAT_UPDATE_REQUIRED_KEYS = [
2660
+ "name",
2661
+ "object_type",
2662
+ "object_model",
2663
+ "object_event",
2664
+ "action_type",
2665
+ "params_script",
2666
+ "mapping_script"
2667
+ ];
2652
2668
  var CONFIG_DOMAINS = {
2653
2669
  "form-template": {
2654
2670
  capability: "config.form_template",
@@ -2680,6 +2696,22 @@ var CONFIG_DOMAINS = {
2680
2696
  writeEndpoints: ["POST /api/flow/flow_type", "PUT /api/flow?flow_type=:flow_type&publish=2", "PUT /api/flow?key=:key&publish=2", "PUT /api/flow?flow_type=:flow_type&publish=1", "PUT /api/flow?key=:key&publish=1", "DELETE /api/flow?flow_type=:flow_type&key=:key"],
2681
2697
  notes: ["Flow config is keyed by flow_type for main flows or key for subflows. Export id format: flow_type, flow_type:<type>, or key:<subflowKey>. Submit writes draft by default and only publishes when payload.publish_live=true. Create first asks the platform for a flow<number> and never accepts a hand-authored main flow_type."]
2682
2698
  },
2699
+ workspace: {
2700
+ capability: "config.workspace",
2701
+ exportPath: workspaceExportPath,
2702
+ exportStatus: "supported",
2703
+ buildStatus: "supported",
2704
+ submitStatus: "supported",
2705
+ createPath: "/workspace",
2706
+ createMethod: "POST",
2707
+ deletePath: (id) => `/workspace/${id}`,
2708
+ deleteMethod: "DELETE",
2709
+ submitPath: (id) => `/workspace/${id}`,
2710
+ submitMethod: "PUT",
2711
+ readEndpoints: ["GET /api/workspace/:id", "GET /api/workspace/by_key?key=:key"],
2712
+ writeEndpoints: ["POST /api/workspace", "PUT /api/workspace/:id", "DELETE /api/workspace/:id"],
2713
+ notes: ["Workspace config creates and edits BPMAX platform workspaces. Export id supports numeric id or key:<workspace_key>; create/submit verify by workspace key."]
2714
+ },
2683
2715
  "workspace-flow": {
2684
2716
  capability: "config.workspace_flow",
2685
2717
  exportPath: (id) => `/workspace/by_key?key=${encodeURIComponent(normalizeWorkspaceKey(id))}`,
@@ -2957,9 +2989,9 @@ function summarizeOperationPlan(payload) {
2957
2989
  return "submit operation";
2958
2990
  }
2959
2991
  const method = typeof operation.method === "string" ? operation.method : "REQUEST";
2960
- const path9 = typeof operation.path === "string" ? operation.path : "";
2992
+ const path11 = typeof operation.path === "string" ? operation.path : "";
2961
2993
  const type = typeof operation.type === "string" ? ` ${operation.type}` : "";
2962
- return `submit${type}: ${method}${path9 ? ` ${path9}` : ""}`;
2994
+ return `submit${type}: ${method}${path11 ? ` ${path11}` : ""}`;
2963
2995
  }),
2964
2996
  ...skipped.slice(0, Math.max(0, 20 - operations.length)).map((operation) => {
2965
2997
  if (!isRecord3(operation)) {
@@ -3159,11 +3191,14 @@ function looksLikeParseEvalFunctionBody(script) {
3159
3191
  }
3160
3192
  function addCodeModeMessageScriptError(errors, pathName) {
3161
3193
  errors.push(
3162
- `${pathName} is code-mode message content but is not a parseEvalFunction body; wrap literal text as a JS return script, for example: return "\u8BF7\u5904\u7406...";`
3194
+ `${pathName} is code-mode message content but is not a parseEvalFunction body; wrap literal text as a JS return script, for example: return "\u8BF7\u5904\u7406..."; use return ""; to suppress default message sending.`
3163
3195
  );
3164
3196
  }
3165
3197
  function validateCodeModeMessageScript(errors, pathName, value) {
3166
3198
  if (value === void 0 || value === null || value === "") {
3199
+ errors.push(
3200
+ `${pathName} is code-mode message content but is empty; empty message_template triggers backend default message sending. Use return ""; to suppress outbound messages.`
3201
+ );
3167
3202
  return;
3168
3203
  }
3169
3204
  if (typeof value !== "string" || !looksLikeParseEvalFunctionBody(value)) {
@@ -3233,6 +3268,128 @@ function validateFlowTemplateCodeModeMessages(value, errors) {
3233
3268
  }
3234
3269
  throw new Error(`flow-template code-mode message gate failed: ${nextErrors.join("; ")}`);
3235
3270
  }
3271
+ function collectStringValues(value, result = []) {
3272
+ if (typeof value === "string") {
3273
+ result.push(value);
3274
+ return result;
3275
+ }
3276
+ if (Array.isArray(value)) {
3277
+ value.forEach((item) => collectStringValues(item, result));
3278
+ return result;
3279
+ }
3280
+ if (isRecord3(value)) {
3281
+ Object.values(value).forEach((item) => collectStringValues(item, result));
3282
+ }
3283
+ return result;
3284
+ }
3285
+ function validateFlowTemplateRuntimeScripts(value, errors) {
3286
+ const scripts = collectStringValues(value);
3287
+ const nextErrors = scripts.filter((script) => FORM_TEMPLATE_ID_CONST_PATTERN.test(script) || FORM_TEMPLATE_ID_PROP_PATTERN.test(script)).slice(0, 5).map(() => "flow-template runtime scripts must not hardcode form template auto IDs; for createProject omit form.template_id and rely on the target flow published meta.form_template, for patchFormField omit form.template_id and update the existing project form by key_to_value.");
3288
+ if (!nextErrors.length) {
3289
+ return;
3290
+ }
3291
+ if (errors) {
3292
+ errors.push(...nextErrors);
3293
+ return;
3294
+ }
3295
+ throw new Error(`flow-template runtime script gate failed: ${nextErrors.join("; ")}`);
3296
+ }
3297
+ function isEnabledFeishuChatConfig(config) {
3298
+ return config.enabled === true || config.enabled === 1 || config.enabled === "true";
3299
+ }
3300
+ function validateFeishuChatScriptShape(errors, pathName, value, kind) {
3301
+ if (typeof value !== "string" || !value.trim()) {
3302
+ errors.push(`${pathName} must be a non-empty script.`);
3303
+ return;
3304
+ }
3305
+ const text5 = value.trim();
3306
+ if ((kind === "message" || kind === "send_message") && /^return\s+["'`]/.test(text5)) {
3307
+ errors.push(`${pathName} must return a card/message payload object, not a raw string literal.`);
3308
+ }
3309
+ if (kind === "member" && /\b(open_id|union_id)\b/i.test(text5)) {
3310
+ errors.push(`${pathName} should return BPMAX user_id values; open_id/union_id based member scripts are not portable.`);
3311
+ }
3312
+ if (kind === "add_users" && !/\buser_ids\b/.test(text5)) {
3313
+ errors.push(`${pathName} for add_users must include user_ids.`);
3314
+ }
3315
+ }
3316
+ function validateFeishuChatConfig(config, pathName, errors) {
3317
+ if (!isEnabledFeishuChatConfig(config)) {
3318
+ return;
3319
+ }
3320
+ const type = String(config.type || "");
3321
+ const platformId = config.platform_id;
3322
+ if (typeof platformId !== "string" && typeof platformId !== "number") {
3323
+ errors.push(`${pathName}.platform_id is required when Feishu chat plugin is enabled.`);
3324
+ } else if (!String(platformId).trim()) {
3325
+ errors.push(`${pathName}.platform_id is required when Feishu chat plugin is enabled.`);
3326
+ }
3327
+ const triggerMode = String(config.triggerMode || "");
3328
+ if (type === "step" && triggerMode && !["manual", "step_active", "step_finish"].includes(triggerMode)) {
3329
+ errors.push(`${pathName}.triggerMode must be one of manual, step_active, step_finish.`);
3330
+ }
3331
+ const chatRange = String(config.chatRange || "");
3332
+ if (type === "step" && chatRange && !["project", "current_step", "script"].includes(chatRange)) {
3333
+ errors.push(`${pathName}.chatRange must be one of project, current_step, script.`);
3334
+ }
3335
+ if (chatRange === "script") {
3336
+ validateFeishuChatScriptShape(errors, `${pathName}.member_script`, config.member_script, "member");
3337
+ }
3338
+ if (config.autoSendMessage === true || config.autoSendMessage === 1 || config.autoSendMessage === "true") {
3339
+ validateFeishuChatScriptShape(errors, `${pathName}.messageContent`, config.messageContent, "message");
3340
+ }
3341
+ if (config.enable_update === true || config.enable_update === 1 || config.enable_update === "true") {
3342
+ const updates = Array.isArray(config.update_chat_configs) ? config.update_chat_configs : [];
3343
+ if (!updates.length) {
3344
+ errors.push(`${pathName}.update_chat_configs must be a non-empty array when enable_update=true.`);
3345
+ }
3346
+ updates.forEach((item, index) => {
3347
+ if (!isRecord3(item)) {
3348
+ errors.push(`${pathName}.update_chat_configs[${index}] must be an object.`);
3349
+ return;
3350
+ }
3351
+ FEISHU_CHAT_UPDATE_REQUIRED_KEYS.forEach((key) => {
3352
+ if (item[key] === void 0 || item[key] === null || item[key] === "") {
3353
+ errors.push(`${pathName}.update_chat_configs[${index}].${key} is required.`);
3354
+ }
3355
+ });
3356
+ const actionType = String(item.action_type || "");
3357
+ if (actionType && !["add_users", "send_message"].includes(actionType)) {
3358
+ errors.push(`${pathName}.update_chat_configs[${index}].action_type must be add_users or send_message.`);
3359
+ }
3360
+ if (actionType === "add_users") {
3361
+ validateFeishuChatScriptShape(errors, `${pathName}.update_chat_configs[${index}].params_script`, item.params_script, "add_users");
3362
+ }
3363
+ if (actionType === "send_message") {
3364
+ validateFeishuChatScriptShape(errors, `${pathName}.update_chat_configs[${index}].params_script`, item.params_script, "send_message");
3365
+ }
3366
+ });
3367
+ }
3368
+ }
3369
+ function validateFlowTemplateFeishuChatPlugin(value, errors) {
3370
+ const nextErrors = [];
3371
+ const data = isRecord3(value.data) ? value.data : {};
3372
+ const meta = isRecord3(data.meta) ? data.meta : {};
3373
+ if (isRecord3(meta.plugin_create_feishu_chat)) {
3374
+ validateFeishuChatConfig(meta.plugin_create_feishu_chat, "data.meta.plugin_create_feishu_chat", nextErrors);
3375
+ }
3376
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
3377
+ nodes.forEach((node, index) => {
3378
+ if (!isRecord3(node) || !isRecord3(node.plugin_create_feishu_chat)) {
3379
+ return;
3380
+ }
3381
+ const nodeName = typeof node.name === "string" && node.name.trim() ? node.name.trim() : `nodes[${index}]`;
3382
+ validateFeishuChatConfig(node.plugin_create_feishu_chat, `${nodeName}.plugin_create_feishu_chat`, nextErrors);
3383
+ });
3384
+ if (!nextErrors.length) {
3385
+ return;
3386
+ }
3387
+ if (errors) {
3388
+ errors.push(...nextErrors);
3389
+ return;
3390
+ }
3391
+ throw new Error(`flow-template Feishu chat plugin gate failed: ${nextErrors.join("; ")}`);
3392
+ }
3236
3393
  function isEmptyTemplateReference(value) {
3237
3394
  return value === void 0 || value === null || value === "" || value === 0 || value === "0";
3238
3395
  }
@@ -3557,6 +3714,11 @@ function validateListTemplateActionGate(value, errors) {
3557
3714
  throw new Error(`list-template action gate failed: ${nextErrors.join("; ")}`);
3558
3715
  }
3559
3716
  function validateExpectedType(domain, definition, data) {
3717
+ if (domain === "workspace") {
3718
+ if (!isRecord3(data) || typeof data.key !== "string" || !data.key.trim() || typeof data.name !== "string" || !data.name.trim()) {
3719
+ throw new Error("Config domain workspace expects a workspace record with key and name.");
3720
+ }
3721
+ }
3560
3722
  if (definition.expectedType === void 0) {
3561
3723
  return;
3562
3724
  }
@@ -3671,6 +3833,8 @@ function normalizeFlowTemplatePayload(work) {
3671
3833
  validateFlowTemplateProjectAfterCreatePath({ ...work, data });
3672
3834
  validateFlowTemplateStandardPageCreateFormTemplate({ ...work, data });
3673
3835
  validateFlowTemplateCodeModeMessages({ ...work, data });
3836
+ validateFlowTemplateRuntimeScripts({ ...work, data });
3837
+ validateFlowTemplateFeishuChatPlugin({ ...work, data });
3674
3838
  const payload = pickDefined(work, [
3675
3839
  "name",
3676
3840
  "flow_type",
@@ -3952,6 +4116,29 @@ function buildStructuredFormTemplatePayload(work) {
3952
4116
  value: valueItems
3953
4117
  };
3954
4118
  }
4119
+ function formTemplateName(value) {
4120
+ const basic = isRecord3(value.basic) ? value.basic : {};
4121
+ const name = value.name ?? basic.name;
4122
+ return typeof name === "string" ? name : "";
4123
+ }
4124
+ function validateFormTemplateNameLength(value, errors) {
4125
+ const name = formTemplateName(value);
4126
+ if (!name || name.length <= MAX_FORM_TEMPLATE_NAME_LENGTH) {
4127
+ return;
4128
+ }
4129
+ const message = `form-template name is too long (${name.length} > ${MAX_FORM_TEMPLATE_NAME_LENGTH}); BPMAX form_template.name may fail with ER_DATA_TOO_LONG. Use a shorter template name and put full business meaning in desc.`;
4130
+ if (errors) {
4131
+ errors.push(message);
4132
+ return;
4133
+ }
4134
+ throw new Error(message);
4135
+ }
4136
+ function looksLikeFormTemplateWork(value) {
4137
+ if (Object.prototype.hasOwnProperty.call(value, "rule") || Object.prototype.hasOwnProperty.call(value, "value")) {
4138
+ return true;
4139
+ }
4140
+ return isRecord3(value.basic) && Array.isArray(value.layout) && isRecord3(value.fields);
4141
+ }
3955
4142
  function stripFormTemplateCreateIds(payload) {
3956
4143
  const next = { ...payload };
3957
4144
  if (Array.isArray(next.rule)) {
@@ -4167,7 +4354,7 @@ function normalizeMemberDetail(member) {
4167
4354
  }
4168
4355
  function flowPermissionKeys(permissions) {
4169
4356
  const result = /* @__PURE__ */ new Set();
4170
- const collect = (flowPermissions) => {
4357
+ const collect2 = (flowPermissions) => {
4171
4358
  if (!isRecord3(flowPermissions)) {
4172
4359
  return;
4173
4360
  }
@@ -4179,11 +4366,11 @@ function flowPermissionKeys(permissions) {
4179
4366
  }
4180
4367
  }
4181
4368
  };
4182
- collect(permissions.flow);
4369
+ collect2(permissions.flow);
4183
4370
  if (isRecord3(permissions.workspace)) {
4184
4371
  for (const workspacePermissions of Object.values(permissions.workspace)) {
4185
4372
  if (isRecord3(workspacePermissions)) {
4186
- collect(workspacePermissions.flow);
4373
+ collect2(workspacePermissions.flow);
4187
4374
  }
4188
4375
  }
4189
4376
  }
@@ -4198,6 +4385,79 @@ function normalizeWorkspaceId(id, profile) {
4198
4385
  const raw = id.trim() || profile.config.workspace || "";
4199
4386
  return raw.startsWith("w:") ? raw.slice(2) : raw;
4200
4387
  }
4388
+ function normalizeWorkspaceConfigKey(key) {
4389
+ const raw = String(key ?? "").trim();
4390
+ return raw.startsWith("w:") ? raw.slice(2).trim() : raw;
4391
+ }
4392
+ function isWorkspaceKeyId(id) {
4393
+ const trimmed = id.trim();
4394
+ return trimmed.startsWith("key:") || trimmed.startsWith("w:") || !/^\d+$/.test(trimmed);
4395
+ }
4396
+ function workspaceExportPath(id) {
4397
+ const trimmed = id.trim();
4398
+ if (!trimmed) {
4399
+ throw new Error("workspace id is required. Use a numeric id or key:<workspace_key>.");
4400
+ }
4401
+ if (isWorkspaceKeyId(trimmed)) {
4402
+ const key = normalizeWorkspaceConfigKey(trimmed.startsWith("key:") ? trimmed.slice("key:".length) : trimmed);
4403
+ if (!key) {
4404
+ throw new Error("workspace key export id must include a key.");
4405
+ }
4406
+ return `/workspace/by_key?key=${encodeURIComponent(key)}`;
4407
+ }
4408
+ return `/workspace/${encodeURIComponent(trimmed)}`;
4409
+ }
4410
+ function validateWorkspacePayload(payload) {
4411
+ const name = String(payload.name ?? "").trim();
4412
+ const key = normalizeWorkspaceConfigKey(payload.key);
4413
+ const entryPath = String(payload.entry_path ?? "").trim();
4414
+ if (name.length < 2 || name.length > 20) {
4415
+ throw new Error("workspace name must be 2-20 characters.");
4416
+ }
4417
+ if (!/^[A-Za-z][A-Za-z0-9_-]{1,19}$/.test(key)) {
4418
+ throw new Error('workspace key must be 2-20 characters, start with a letter, and contain only letters, numbers, "_" or "-".');
4419
+ }
4420
+ if (!entryPath) {
4421
+ throw new Error("workspace entry_path is required.");
4422
+ }
4423
+ }
4424
+ function normalizeWorkspacePayload(work) {
4425
+ const source = isRecord3(work.basic) ? { ...work, ...work.basic } : work;
4426
+ const payload = pickDefined(source, [
4427
+ "id",
4428
+ "name",
4429
+ "key",
4430
+ "logo",
4431
+ "bg_img",
4432
+ "icon",
4433
+ "description",
4434
+ "is_system_admin",
4435
+ "admin_ids",
4436
+ "entry_path",
4437
+ "m_entry_path",
4438
+ "origin",
4439
+ "white_list"
4440
+ ]);
4441
+ payload.name = String(payload.name ?? "").trim();
4442
+ payload.key = normalizeWorkspaceConfigKey(payload.key);
4443
+ payload.entry_path = String(payload.entry_path ?? "/myProject").trim() || "/myProject";
4444
+ if (payload.m_entry_path === void 0) {
4445
+ payload.m_entry_path = "";
4446
+ }
4447
+ if (payload.is_system_admin === void 0) {
4448
+ payload.is_system_admin = 1;
4449
+ } else {
4450
+ payload.is_system_admin = normalizeInt(payload.is_system_admin);
4451
+ }
4452
+ if (payload.admin_ids === void 0) {
4453
+ payload.admin_ids = [];
4454
+ }
4455
+ if (payload.white_list === void 0) {
4456
+ payload.white_list = { range: "all" };
4457
+ }
4458
+ validateWorkspacePayload(payload);
4459
+ return payload;
4460
+ }
4201
4461
  function parseApiPlatformIdentity(id) {
4202
4462
  const trimmed = id.trim();
4203
4463
  if (!trimmed) {
@@ -4627,6 +4887,7 @@ function buildDomainSubmitPayload(domain, work, options = {}, raw) {
4627
4887
  throw new Error("Config work file must be a JSON object.");
4628
4888
  }
4629
4889
  if (domain === "form-template") {
4890
+ validateFormTemplateNameLength(work);
4630
4891
  if (isRecord3(work.basic) && Array.isArray(work.layout) && isRecord3(work.fields)) {
4631
4892
  return buildStructuredFormTemplatePayload(work);
4632
4893
  }
@@ -4639,6 +4900,9 @@ function buildDomainSubmitPayload(domain, work, options = {}, raw) {
4639
4900
  if (domain === "workspace-flow") {
4640
4901
  return buildWorkspaceFlowSubmitPayload(work);
4641
4902
  }
4903
+ if (domain === "workspace") {
4904
+ return normalizeWorkspacePayload(work);
4905
+ }
4642
4906
  if (domain === "dataset") {
4643
4907
  return normalizeDatasetPayload(work);
4644
4908
  }
@@ -4889,6 +5153,8 @@ async function createFlowTemplateFromWork(config, profile, workFile, confirm3, o
4889
5153
  validateFlowTemplateProjectAfterCreatePath(work);
4890
5154
  validateFlowTemplateStandardPageCreateFormTemplate(work);
4891
5155
  validateFlowTemplateCodeModeMessages(work);
5156
+ validateFlowTemplateRuntimeScripts(work);
5157
+ validateFlowTemplateFeishuChatPlugin(work);
4892
5158
  validateFlowTemplateFormDrivenCreateBaseline(work, void 0, { context: "flow-template create" });
4893
5159
  const createShell = {
4894
5160
  name: String(work.name || ""),
@@ -5296,11 +5562,15 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
5296
5562
  throw new Error(`Config build produced an empty payload for ${domain}.`);
5297
5563
  }
5298
5564
  validateExpectedType(domain, definition, payload);
5565
+ const submitMeta = isRecord3(meta) ? { ...meta } : {};
5566
+ if (createMode) {
5567
+ submitMeta.mode = "create";
5568
+ }
5299
5569
  const result = {
5300
5570
  domain,
5301
5571
  built_at: (/* @__PURE__ */ new Date()).toISOString(),
5302
- meta,
5303
- base_hash: typeof meta.base_hash === "string" ? meta.base_hash : null,
5572
+ meta: submitMeta,
5573
+ base_hash: createMode ? null : typeof meta.base_hash === "string" ? meta.base_hash : null,
5304
5574
  payload
5305
5575
  };
5306
5576
  await writeJsonFile(outFile, result);
@@ -5318,6 +5588,9 @@ async function lintConfigWorkFile(file) {
5318
5588
  if (Object.prototype.hasOwnProperty.call(value, "content")) {
5319
5589
  lintTemplateFieldReferences(value, errors);
5320
5590
  }
5591
+ if (looksLikeFormTemplateWork(value)) {
5592
+ validateFormTemplateNameLength(value, errors);
5593
+ }
5321
5594
  if ((Object.prototype.hasOwnProperty.call(value, "content") || isRecord3(value.basic)) && pageTemplateType(value) === 1) {
5322
5595
  validateListTemplateActionGate(value, errors);
5323
5596
  }
@@ -5327,6 +5600,8 @@ async function lintConfigWorkFile(file) {
5327
5600
  validateFlowTemplateProjectAfterCreatePath(flowWork, errors);
5328
5601
  validateFlowTemplateStandardPageCreateFormTemplate(flowWork, errors);
5329
5602
  validateFlowTemplateCodeModeMessages(flowWork, errors);
5603
+ validateFlowTemplateRuntimeScripts(flowWork, errors);
5604
+ validateFlowTemplateFeishuChatPlugin(flowWork, errors);
5330
5605
  if (flowWork.mode === "create") {
5331
5606
  validateFlowTemplateFormDrivenCreateBaseline(flowWork, errors, { context: "flow-template create" });
5332
5607
  } else {
@@ -5422,6 +5697,106 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
5422
5697
  readback_hash: hashJson(readback2)
5423
5698
  };
5424
5699
  }
5700
+ if (domain === "workspace") {
5701
+ if (definition.submitStatus !== "supported") {
5702
+ throw new Error(`${CONFIG_SUBMIT_UNSUPPORTED_MESSAGE} Domain: ${domain}.`);
5703
+ }
5704
+ const submit2 = await readJsonFile(submitFile);
5705
+ if (!isRecord3(submit2) || submit2.domain !== domain || !isRecord3(submit2.payload)) {
5706
+ throw new Error("Config submit requires a payload produced by `bpmax-cli config <domain> build`.");
5707
+ }
5708
+ const meta2 = submit2.meta;
5709
+ if (!isRecord3(meta2)) {
5710
+ throw new Error("Config submit payload is missing export metadata. Export the remote config first, then rebuild with --meta.");
5711
+ }
5712
+ if (meta2.domain !== domain) {
5713
+ throw new Error(`Config submit metadata domain mismatch. Expected ${domain}, got ${String(meta2.domain)}.`);
5714
+ }
5715
+ if (meta2.profile !== profile.name) {
5716
+ throw new Error(`Config submit metadata profile mismatch. Expected ${profile.name}, got ${String(meta2.profile)}.`);
5717
+ }
5718
+ const createMode = meta2.mode === "create";
5719
+ const workspaceKey = normalizeWorkspaceConfigKey(submit2.payload.key);
5720
+ const confirmId = workspaceKey || id;
5721
+ const expectedConfirm2 = `submit ${domain} ${confirmId}`;
5722
+ const client2 = createApiClient(profile);
5723
+ if (createMode) {
5724
+ await ensureConfigCapability(profile, `${definition.capability}.create`);
5725
+ await ensureConfigCapability(profile, `${definition.capability}.export`);
5726
+ if (confirm3 !== expectedConfirm2) {
5727
+ return {
5728
+ dry_run: true,
5729
+ domain,
5730
+ id,
5731
+ endpoint: "/workspace",
5732
+ method: "POST",
5733
+ payload: submit2.payload,
5734
+ next: `Run again with --confirm "${expectedConfirm2}" to submit.`
5735
+ };
5736
+ }
5737
+ const response3 = await apiRequest(
5738
+ client2,
5739
+ "POST",
5740
+ "/workspace",
5741
+ { data: submit2.payload, capability: `${definition.capability}.create` }
5742
+ );
5743
+ const readback3 = await readRemoteConfigDomain(profile, domain, `key:${workspaceKey}`, definition);
5744
+ return {
5745
+ dry_run: false,
5746
+ domain,
5747
+ id,
5748
+ endpoint: "/workspace",
5749
+ method: "POST",
5750
+ response: response3,
5751
+ created_id: responseDataId(response3) ?? (isRecord3(readback3) ? readback3.id ?? null : null),
5752
+ readback_hash: hashJson(readback3)
5753
+ };
5754
+ }
5755
+ if (String(meta2.id || "") !== id) {
5756
+ throw new Error(`Config submit metadata id mismatch. Expected ${id}, got ${String(meta2.id || "")}.`);
5757
+ }
5758
+ await ensureConfigCapability(profile, `${definition.capability}.submit`);
5759
+ await ensureConfigCapability(profile, `${definition.capability}.export`);
5760
+ const current2 = await readRemoteConfigDomain(profile, domain, id, definition);
5761
+ const currentHash2 = hashJson(current2);
5762
+ if (currentHash2 !== submit2.base_hash) {
5763
+ throw new Error("Remote config changed after export. Re-export before submitting.");
5764
+ }
5765
+ const workspaceId = isRecord3(current2) && current2.id !== void 0 && current2.id !== null && current2.id !== "" ? String(current2.id) : /^\d+$/.test(id) ? id : "";
5766
+ if (!workspaceId) {
5767
+ throw new Error("workspace submit requires a numeric workspace id from export readback.");
5768
+ }
5769
+ const endpoint2 = `/workspace/${encodeURIComponent(workspaceId)}`;
5770
+ if (confirm3 !== expectedConfirm2) {
5771
+ return {
5772
+ dry_run: true,
5773
+ domain,
5774
+ id,
5775
+ endpoint: endpoint2,
5776
+ method: "PUT",
5777
+ payload: submit2.payload,
5778
+ diff: diffJsonNormalized(domain, current2, submit2.payload),
5779
+ current_hash: currentHash2,
5780
+ next: `Run again with --confirm "${expectedConfirm2}" to submit.`
5781
+ };
5782
+ }
5783
+ const response2 = await apiRequest(
5784
+ client2,
5785
+ "PUT",
5786
+ endpoint2,
5787
+ { data: submit2.payload, capability: `${definition.capability}.submit` }
5788
+ );
5789
+ const readback2 = await readRemoteConfigDomain(profile, domain, workspaceKey ? `key:${workspaceKey}` : workspaceId, definition);
5790
+ return {
5791
+ dry_run: false,
5792
+ domain,
5793
+ id,
5794
+ endpoint: endpoint2,
5795
+ method: "PUT",
5796
+ response: response2,
5797
+ readback_hash: hashJson(readback2)
5798
+ };
5799
+ }
5425
5800
  if (domain === "role" || domain === "api-platform" || domain === "nav-config") {
5426
5801
  if (definition.submitStatus !== "supported") {
5427
5802
  throw new Error(`${CONFIG_SUBMIT_UNSUPPORTED_MESSAGE} Domain: ${domain}.`);
@@ -5560,6 +5935,8 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
5560
5935
  validateFlowTemplateProjectAfterCreatePath(submit.payload);
5561
5936
  validateFlowTemplateStandardPageCreateFormTemplate(submit.payload);
5562
5937
  validateFlowTemplateCodeModeMessages(submit.payload);
5938
+ validateFlowTemplateRuntimeScripts(submit.payload);
5939
+ validateFlowTemplateFeishuChatPlugin(submit.payload);
5563
5940
  validateFlowTemplateStandardFlowType(submit.payload);
5564
5941
  validateFlowTemplateIdentityStandard(id, submit.payload);
5565
5942
  }
@@ -6749,7 +7126,7 @@ function registerConfigCommands(program2) {
6749
7126
  printResult(options.format, result);
6750
7127
  });
6751
7128
  Object.keys(CONFIG_DOMAINS).forEach((domain) => {
6752
- const domainCommand = config.command(domain).description(`Manage BPMAX ${domain} configuration`);
7129
+ const domainCommand = domain === "workspace" ? workspace.description("Initialize local sysconfig workspaces and manage BPMAX workspace configuration") : config.command(domain).description(`Manage BPMAX ${domain} configuration`);
6753
7130
  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");
6754
7131
  if (domain === "flow-template") {
6755
7132
  createCommand.requiredOption("--work <file>", "Flow-template work JSON file");
@@ -7011,7 +7388,7 @@ function registerFlowCommands(program2) {
7011
7388
  const client = createApiClient(profile);
7012
7389
  if (options.flowType) {
7013
7390
  const bindings = await getWorkspaceFlowBindings(client, profile, options);
7014
- const path9 = options.flowKey ? "/flow/options" : "/flow/flow_type";
7391
+ const path11 = options.flowKey ? "/flow/options" : "/flow/flow_type";
7015
7392
  const params = options.flowKey ? {
7016
7393
  detail: "1"
7017
7394
  } : {
@@ -7021,7 +7398,7 @@ function registerFlowCommands(program2) {
7021
7398
  const result2 = await apiRequest(
7022
7399
  client,
7023
7400
  "GET",
7024
- path9,
7401
+ path11,
7025
7402
  {
7026
7403
  params
7027
7404
  }
@@ -7348,10 +7725,10 @@ async function parseOptionalJson(input, label) {
7348
7725
  }
7349
7726
  return parseJsonInput(input, label);
7350
7727
  }
7351
- async function memoryRequest(options, method, path9, capability, data, params) {
7728
+ async function memoryRequest(options, method, path11, capability, data, params) {
7352
7729
  const profile = resolveProfile(await loadConfig(), options.profile);
7353
7730
  const client = createApiClient(profile);
7354
- return apiRequest(client, method, path9, {
7731
+ return apiRequest(client, method, path11, {
7355
7732
  capability,
7356
7733
  data: redactAuditValue(data),
7357
7734
  params: params ? redactAuditValue(params) : void 0
@@ -8289,9 +8666,9 @@ function contextField(field, reason, options = {}) {
8289
8666
  function collectPrefillContextForFields(fields, form, result, options = {}) {
8290
8667
  for (const field of fields) {
8291
8668
  const value = form[field.key];
8292
- const path9 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
8669
+ const path11 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
8293
8670
  const fieldOptions = {
8294
- path: path9,
8671
+ path: path11,
8295
8672
  rootKey: options.rootKey ?? field.key,
8296
8673
  parentKey: options.parentKey
8297
8674
  };
@@ -9031,6 +9408,10 @@ var schemaEntries = [
9031
9408
  { name: "config.flow_template.create", description: "Create a platform-generated main flow shell through a verified typed adapter.", method: "POST", path: "/api/flow/flow_type" },
9032
9409
  { name: "config.flow_template.delete", description: "Delete a flow template by flow_type or key through a verified typed adapter.", method: "DELETE", path: "/api/flow?flow_type=:flow_type&key=:key" },
9033
9410
  { name: "config.flow_template.submit", description: "Submit flow template config when a verified draft-aware adapter is available.", method: "PUT", path: "/api/flow?flow_type=:flow_type&key=:key&publish=:publish" },
9411
+ { name: "config.workspace.export", description: "Export BPMAX workspace config by id or key.", method: "GET", path: "/api/workspace/:id + /api/workspace/by_key?key=:key" },
9412
+ { name: "config.workspace.create", description: "Create a BPMAX workspace through the verified typed adapter.", method: "POST", path: "/api/workspace" },
9413
+ { name: "config.workspace.delete", description: "Delete a BPMAX workspace through a typed adapter.", method: "DELETE", path: "/api/workspace/:id" },
9414
+ { name: "config.workspace.submit", description: "Submit BPMAX workspace edits through the verified typed adapter.", method: "PUT", path: "/api/workspace/:id" },
9034
9415
  { name: "config.workspace_flow.export", description: "Export workspace-bound flow relations.", method: "GET", path: "/api/workspace/by_key?key=:workspace" },
9035
9416
  { name: "config.workspace_flow.create", description: "Create one workspace-flow binding through the verified workspace-flow adapter.", method: "PUT", path: "/api/workspace/workspace_flow" },
9036
9417
  { name: "config.workspace_flow.delete", description: "Delete one workspace-flow binding through a typed adapter.", method: "PUT", path: "/api/workspace/workspace_flow" },
@@ -9080,6 +9461,12 @@ var schemaEntries = [
9080
9461
  { name: "config.repository.sync", description: "Run platform sysconfigdiff pullcommit/extract/pushcommit steps.", method: "POST", path: "/api/config_repository/:env?action=sync" },
9081
9462
  { name: "config.latest.pull", description: "Sync latest BPMAX sysconfig repositories for a configured environment.", method: "external", path: "external:sysconfigdiff + git" },
9082
9463
  { name: "config.e2e.run", description: "Run BPMAX config end-to-end validation orchestration.", method: "local+remote", path: "cli:e2e" },
9464
+ { name: "test_suite.lint", description: "Lint local BPMAX AI test case suite scenarios under .ai_test.", method: "local", path: ".ai_test/suite" },
9465
+ { name: "test_suite.index", description: "Index local BPMAX AI test case suite scenarios under .ai_test.", method: "local", path: ".ai_test/suite" },
9466
+ { name: "test_suite.draft_update", description: "Copy a formal BPMAX AI test scenario into suite_draft with copy-diff guard.", method: "local", path: ".ai_test/suite -> .ai_test/suite_draft" },
9467
+ { name: "test_suite.promote", description: "Promote a reviewed BPMAX AI test scenario draft into the formal suite.", method: "local", path: ".ai_test/suite_draft -> .ai_test/suite" },
9468
+ { name: "test_suite.next_report_dir", description: "Create or print the next local BPMAX E2E test report run directory.", method: "local", path: ".ai_test/report" },
9469
+ { name: "test_suite.lint_report", description: "Lint local BPMAX E2E report evidence artifacts.", method: "local", path: ".ai_test/report" },
9083
9470
  { name: "memory.status", description: "Check BPMAX memory backend status.", method: "GET", path: "/api/cli/memory/status" },
9084
9471
  { name: "memory.search", description: "Search BPMAX memory for the current API-key agent.", method: "POST", path: "/api/cli/memory/search" },
9085
9472
  { name: "memory.add", description: "Add BPMAX memory for the current API-key agent.", method: "POST", path: "/api/cli/memory" },
@@ -9764,9 +10151,978 @@ function registerStepCommands(program2) {
9764
10151
  });
9765
10152
  }
9766
10153
 
9767
- // src/core/update.ts
9768
- import { access as access2, mkdir as mkdir8, readFile as readFile10, realpath, writeFile as writeFile8 } from "fs/promises";
10154
+ // src/core/taskbook.ts
10155
+ import { mkdir as mkdir8, readFile as readFile10, writeFile as writeFile8 } from "fs/promises";
9769
10156
  import path8 from "path";
10157
+ var TaskbookError = class extends Error {
10158
+ };
10159
+ var REQUIRED_TASKBOOK_TERMS = [
10160
+ "\u76EE\u6807\u4E0E\u8FB9\u754C",
10161
+ "\u5E76\u884C\u62C6\u89E3\u786C\u89C4\u5219",
10162
+ "\u9636\u6BB5\u603B\u89C8",
10163
+ "\u5BF9\u8C61\u9501\u8868",
10164
+ "AI \u6700\u5C0F\u4EFB\u52A1\u5355\u5143",
10165
+ "\u9A8C\u6536\u95E8\u7981",
10166
+ "\u505C\u673A\u70B9",
10167
+ "\u5BF9\u8C61\u9501\u91CD\u590D",
10168
+ "\u53EA\u8BFB\u4EFB\u52A1",
10169
+ "\u53D1\u5E03",
10170
+ "\u5355\u7EBF",
10171
+ "subagent_mode",
10172
+ "\u4E1A\u52A1\u76EE\u6807\u573A\u666F",
10173
+ "required_skills",
10174
+ "\u8FDB\u5EA6 CSV",
10175
+ "\u4E0D\u5F97\u76F4\u63A5\u6539\u98DE\u4E66\u6587\u6863"
10176
+ ];
10177
+ var GENERATED_FLOW_TYPE_TERMS = ["BPMAX", "\u751F\u6210", "\u771F\u5B9E flow_type", "\u56DE\u586B"];
10178
+ var SUBAGENT_TERMS = [
10179
+ "none",
10180
+ "readonly",
10181
+ "draft-only",
10182
+ "exclusive-write",
10183
+ "\u65B0\u6D41\u7A0B\u521B\u5EFA",
10184
+ "\u53D1\u5E03\u96C6\u6210",
10185
+ "\u6700\u7EC8\u540C\u6B65",
10186
+ "\u7981\u6B62\u4FDD\u5B58",
10187
+ "\u7981\u6B62\u53D1\u5E03"
10188
+ ];
10189
+ var PROMPT_REQUIRED_TERMS = [
10190
+ "\u4E1A\u52A1\u76EE\u6807\u573A\u666F",
10191
+ "required_skills",
10192
+ "\u5BF9\u8C61\u9501",
10193
+ "subagent_mode",
10194
+ "\u5141\u8BB8\u64CD\u4F5C",
10195
+ "\u4E0D\u5F97\u4FEE\u6539",
10196
+ "\u8F93\u5165\u4F9D\u8D56",
10197
+ "\u8F93\u51FA\u7269",
10198
+ "\u9A8C\u6536\u65B9\u5F0F",
10199
+ "\u8FDB\u5EA6 CSV"
10200
+ ];
10201
+ var BPMAX_SKILL_PATTERN = /bpmax-[a-z0-9-]+|form-control-library|bpmax-memory-protocol/;
10202
+ var FLOW_LOCK_PATTERN = /\bflow:([A-Za-z0-9_-]+)/g;
10203
+ async function readTaskbookText(file) {
10204
+ const raw = await readFile10(file, "utf8");
10205
+ try {
10206
+ const parsed = JSON.parse(raw);
10207
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
10208
+ const root = parsed;
10209
+ const document = root.data?.document;
10210
+ if (document && typeof document === "object" && !Array.isArray(document)) {
10211
+ const content = document.content;
10212
+ if (typeof content === "string") {
10213
+ return content;
10214
+ }
10215
+ }
10216
+ }
10217
+ } catch {
10218
+ }
10219
+ return raw;
10220
+ }
10221
+ function uniqueErrors(errors) {
10222
+ return [...new Set(errors)];
10223
+ }
10224
+ function missingTermErrors(text5, terms, prefix) {
10225
+ return terms.filter((term) => !text5.includes(term)).map((term) => `${prefix}: ${term}`);
10226
+ }
10227
+ async function lintTaskbook(file, options = {}) {
10228
+ const text5 = await readTaskbookText(file);
10229
+ const errors = [
10230
+ ...missingTermErrors(text5, REQUIRED_TASKBOOK_TERMS, "missing required term"),
10231
+ ...missingTermErrors(text5, options.requireTerms || [], "missing required term")
10232
+ ];
10233
+ for (const term of options.forbidTerms || []) {
10234
+ if (term && text5.includes(term)) {
10235
+ errors.push(`forbidden term present: ${term}`);
10236
+ }
10237
+ }
10238
+ if (!options.allowGeneratedFlowTypeMissing) {
10239
+ errors.push(...missingTermErrors(text5, GENERATED_FLOW_TYPE_TERMS, "missing generated flow_type rule term"));
10240
+ }
10241
+ errors.push(...missingTermErrors(text5, SUBAGENT_TERMS, "missing subagent rule term"));
10242
+ for (const match of text5.matchAll(FLOW_LOCK_PATTERN)) {
10243
+ const value = match[1] || "";
10244
+ if (value.startsWith("flow") && /^flow\d+$/.test(value)) {
10245
+ continue;
10246
+ }
10247
+ errors.push(`possible self-defined flow_type object lock: flow:${value}; use new-flow:<name> before creation, then flow:<generated flow_type>`);
10248
+ }
10249
+ return {
10250
+ ok: errors.length === 0,
10251
+ file,
10252
+ errors: uniqueErrors(errors),
10253
+ checked_at: (/* @__PURE__ */ new Date()).toISOString()
10254
+ };
10255
+ }
10256
+ async function lintTaskPrompt(file, options = {}) {
10257
+ const text5 = await readTaskbookText(file);
10258
+ const errors = [
10259
+ ...missingTermErrors(text5, PROMPT_REQUIRED_TERMS, "prompt missing required term"),
10260
+ ...missingTermErrors(text5, options.requireTerms || [], "prompt missing required term")
10261
+ ];
10262
+ if (!BPMAX_SKILL_PATTERN.test(text5)) {
10263
+ errors.push("prompt missing BPMAX related skill name in required_skills");
10264
+ }
10265
+ for (const term of options.forbidTerms || []) {
10266
+ if (term && text5.includes(term)) {
10267
+ errors.push(`prompt forbidden term present: ${term}`);
10268
+ }
10269
+ }
10270
+ return {
10271
+ ok: errors.length === 0,
10272
+ file,
10273
+ errors: uniqueErrors(errors),
10274
+ checked_at: (/* @__PURE__ */ new Date()).toISOString()
10275
+ };
10276
+ }
10277
+ function taskbookTemplate(title = "BPMAX AI \u5B9E\u65BD\u7F16\u6392\u4EFB\u52A1\u4E66") {
10278
+ return [
10279
+ `# ${title}`,
10280
+ "",
10281
+ "## \u76EE\u6807\u4E0E\u8FB9\u754C",
10282
+ "",
10283
+ "- \u660E\u786E\u672C\u6B21\u4E1A\u52A1\u76EE\u6807\u3001\u76EE\u6807\u5DE5\u4F5C\u533A\u3001\u8303\u56F4\u5185\u914D\u7F6E\u5BF9\u8C61\u548C\u4E0D\u5F97\u4FEE\u6539\u5BF9\u8C61\u3002",
10284
+ "",
10285
+ "## \u5E76\u884C\u62C6\u89E3\u786C\u89C4\u5219",
10286
+ "",
10287
+ "- \u5BF9\u8C61\u9501\u91CD\u590D\u4E0D\u5F97\u5E76\u884C\u3002",
10288
+ "- \u53EA\u8BFB\u4EFB\u52A1\u53EF\u4EE5\u5E76\u884C\uFF0C\u4F46\u7981\u6B62\u4FDD\u5B58\u3001\u7981\u6B62\u53D1\u5E03\u3001\u7981\u6B62\u63D0\u4EA4 payload\u3002",
10289
+ "- \u53D1\u5E03\u96C6\u6210\u548C\u6700\u7EC8\u540C\u6B65\u5FC5\u987B\u5355\u7EBF\u3002",
10290
+ "- \u65B0\u6D41\u7A0B\u521B\u5EFA\u524D\u53EA\u80FD\u4F7F\u7528 `new-flow:<\u6D41\u7A0B\u540D\u79F0>`\uFF1BBPMAX \u751F\u6210\u771F\u5B9E flow_type \u540E\u5FC5\u987B\u56DE\u586B\u4E3A `flow:<\u771F\u5B9E flow_type>`\u3002",
10291
+ "",
10292
+ "## \u9636\u6BB5\u603B\u89C8",
10293
+ "",
10294
+ "| \u72B6\u6001 | \u9636\u6BB5 | \u6267\u884C\u65B9\u5F0F | \u9636\u6BB5\u76EE\u6807 |",
10295
+ "|---|---|---|---|",
10296
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 0 | \u5355\u7EBF | \u7EBF\u4E0A\u57FA\u7EBF\u786E\u8BA4 |",
10297
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 1 | \u53EA\u8BFB\u5E76\u884C | \u914D\u7F6E\u5BF9\u8C61\u8C03\u7814 |",
10298
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 2 | \u5355\u7EBF | \u5408\u5E76\u5BF9\u8C61\u9501\u548C\u4EFB\u52A1\u961F\u5217 |",
10299
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 3 | \u5BF9\u8C61\u72EC\u5360\u914D\u7F6E | \u72EC\u5360\u4FEE\u6539\u914D\u7F6E\u5BF9\u8C61 |",
10300
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 4 | \u5355\u7EBF | \u53D1\u5E03\u96C6\u6210 |",
10301
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 5 | \u53EA\u8BFB\u5E76\u884C | \u6D4F\u89C8\u5668\u548C\u63A5\u53E3\u9A8C\u6536 |",
10302
+ "| \u672A\u5F00\u59CB | \u9636\u6BB5 6 | \u5355\u7EBF | \u6700\u7EC8\u540C\u6B65\u548C\u6C89\u6DC0 |",
10303
+ "",
10304
+ "## \u5BF9\u8C61\u9501\u8868",
10305
+ "",
10306
+ "| \u5BF9\u8C61\u9501 | \u5BF9\u8C61\u540D\u79F0 | \u5141\u8BB8\u64CD\u4F5C | \u7981\u6B62\u5E76\u884C\u52A8\u4F5C |",
10307
+ "|---|---|---|---|",
10308
+ "| global:baseline | \u7EBF\u4E0A\u57FA\u7EBF | \u53EA\u8BFB | \u4FDD\u5B58\u6216\u53D1\u5E03 |",
10309
+ "| new-flow:<\u6D41\u7A0B\u540D\u79F0> | \u65B0\u6D41\u7A0B\u521B\u5EFA\u524D\u903B\u8F91\u9501 | \u521B\u5EFA\u524D\u6392\u4ED6 | \u5F53\u6210\u771F\u5B9E flow_type \u4F7F\u7528 |",
10310
+ "| flow:<BPMAX\u751F\u6210\u7684\u771F\u5B9Eflow_type> | \u6D41\u7A0B | \u914D\u7F6E\u548C\u53D1\u5E03 | \u5176\u4ED6\u4EFB\u52A1\u540C\u65F6\u4FDD\u5B58\u53D1\u5E03 |",
10311
+ "",
10312
+ "## AI \u6700\u5C0F\u4EFB\u52A1\u5355\u5143",
10313
+ "",
10314
+ "| task_id | status | phase | parallel_type | subagent_mode | business_goal | required_skills | object_lock | dependencies | owner | evidence | notes |",
10315
+ "|---|---|---|---|---|---|---|---|---|---|---|---|",
10316
+ "| T00 | \u672A\u5F00\u59CB | 0 | \u5355\u7EBF | none | \u786E\u8BA4\u7EBF\u4E0A\u57FA\u7EBF\u548C\u8303\u56F4 | bpmax-e2e-flow-config-orchestrator | global:baseline | | \u4E3B\u7EBF\u7A0B | | |",
10317
+ "| T01 | \u672A\u5F00\u59CB | 1 | \u53EA\u8BFB\u5E76\u884C | readonly | \u8C03\u7814\u76EE\u6807\u6D41\u7A0B\u548C\u8868\u5355 | bpmax-flow-template-editor,bpmax-form-template-editor | readonly:flow | T00 | \u5F85\u5206\u914D | | |",
10318
+ "",
10319
+ "- \u6BCF\u4E2A\u4EFB\u52A1\u7684 `business_goal` \u90FD\u5FC5\u987B\u5199\u6E05\u695A\u4E1A\u52A1\u76EE\u6807\u573A\u666F\u3002",
10320
+ "- \u6BCF\u4E2A\u4EFB\u52A1\u7684 `required_skills` \u90FD\u5FC5\u987B\u5217\u51FA\u5B9E\u9645\u8981\u4F7F\u7528\u7684 BPMAX skill\u3002",
10321
+ "",
10322
+ "## \u8FDB\u5EA6 CSV",
10323
+ "",
10324
+ "- \u6267\u884C\u524D\u521D\u59CB\u5316\u72EC\u7ACB\u8FDB\u5EA6 CSV\u3002",
10325
+ "- \u6267\u884C\u8FC7\u7A0B\u4E2D\u53EA\u66F4\u65B0 CSV\uFF0C\u4E0D\u5F97\u76F4\u63A5\u6539\u98DE\u4E66\u6587\u6863\u8FDB\u5EA6\u3002",
10326
+ "- CSV \u521D\u59CB\u72B6\u6001\u5168\u90E8\u4E3A `\u672A\u5F00\u59CB`\u3002",
10327
+ "",
10328
+ "## Subagent \u89C4\u5219",
10329
+ "",
10330
+ "- `none`\uFF1A\u65B0\u6D41\u7A0B\u521B\u5EFA\u3001\u53D1\u5E03\u96C6\u6210\u3001\u6700\u7EC8\u540C\u6B65\u3002",
10331
+ "- `readonly`\uFF1A\u53EA\u8BFB\u8C03\u7814\u548C\u9A8C\u8BC1\uFF0C\u7981\u6B62\u4FDD\u5B58\uFF0C\u7981\u6B62\u53D1\u5E03\u3002",
10332
+ "- `draft-only`\uFF1A\u53EA\u4EA7\u51FA\u8349\u7A3F\u3002",
10333
+ "- `exclusive-write`\uFF1A\u5FC5\u987B\u6709\u552F\u4E00\u5BF9\u8C61\u9501\u3002",
10334
+ "",
10335
+ "## \u9A8C\u6536\u95E8\u7981",
10336
+ "",
10337
+ "- \u914D\u7F6E\u5BF9\u8C61\u7EBF\u4E0A\u56DE\u8BFB\u901A\u8FC7\u3002",
10338
+ "- \u6D4F\u89C8\u5668 E2E \u9A8C\u8BC1\u901A\u8FC7\u3002",
10339
+ "- \u6D4B\u8BD5\u62A5\u544A\u548C\u622A\u56FE\u8BC1\u636E\u5B8C\u6574\u3002",
10340
+ "",
10341
+ "## \u505C\u673A\u70B9",
10342
+ "",
10343
+ "- \u65E0\u6CD5\u786E\u8BA4\u7EBF\u4E0A\u57FA\u7EBF\u3002",
10344
+ "- \u5BF9\u8C61\u9501\u51B2\u7A81\u3002",
10345
+ "- \u5173\u952E\u6743\u9650\u6216 capability \u7F3A\u5931\u3002",
10346
+ "- \u98DE\u4E66\u6587\u6863\u521B\u5EFA\u6216\u56DE\u8BFB\u5931\u8D25\u3002",
10347
+ ""
10348
+ ].join("\n");
10349
+ }
10350
+ async function initTaskbook(outFile, title) {
10351
+ const content = taskbookTemplate(title);
10352
+ await mkdir8(path8.dirname(outFile), { recursive: true });
10353
+ await writeFile8(outFile, content, "utf8");
10354
+ return { out: outFile, bytes: Buffer.byteLength(content) };
10355
+ }
10356
+ function splitMarkdownRow(line) {
10357
+ return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((item) => item.trim());
10358
+ }
10359
+ function normalizeHeader(value) {
10360
+ const normalized = value.trim();
10361
+ const mapping = {
10362
+ \u7F16\u53F7: "task_id",
10363
+ \u72B6\u6001: "status",
10364
+ \u9636\u6BB5: "phase",
10365
+ \u5E76\u884C\u5C5E\u6027: "parallel_type",
10366
+ \u4E1A\u52A1\u76EE\u6807\u573A\u666F: "business_goal",
10367
+ \u5BF9\u8C61\u9501: "object_lock",
10368
+ \u8F93\u5165\u4F9D\u8D56: "dependencies",
10369
+ \u8F93\u51FA\u7269: "evidence"
10370
+ };
10371
+ return mapping[normalized] || normalized;
10372
+ }
10373
+ function isSeparatorRow(cells) {
10374
+ return cells.length > 0 && cells.every((cell) => /^:?-{3,}:?$/.test(cell));
10375
+ }
10376
+ function csvEscape(value) {
10377
+ if (/[",\n\r]/.test(value)) {
10378
+ return `"${value.replace(/"/g, '""')}"`;
10379
+ }
10380
+ return value;
10381
+ }
10382
+ function extractTaskRows(text5) {
10383
+ const lines = text5.split(/\r?\n/);
10384
+ const rows = [];
10385
+ for (let index = 0; index < lines.length; index += 1) {
10386
+ const line = lines[index];
10387
+ if (!line.trim().startsWith("|")) {
10388
+ continue;
10389
+ }
10390
+ const headers = splitMarkdownRow(line).map(normalizeHeader);
10391
+ if (!headers.includes("task_id") || !headers.includes("status") || !headers.includes("subagent_mode")) {
10392
+ continue;
10393
+ }
10394
+ let cursor = index + 1;
10395
+ if (cursor < lines.length && isSeparatorRow(splitMarkdownRow(lines[cursor]))) {
10396
+ cursor += 1;
10397
+ }
10398
+ while (cursor < lines.length && lines[cursor].trim().startsWith("|")) {
10399
+ const cells = splitMarkdownRow(lines[cursor]);
10400
+ if (isSeparatorRow(cells)) {
10401
+ cursor += 1;
10402
+ continue;
10403
+ }
10404
+ const row = {};
10405
+ headers.forEach((header, cellIndex) => {
10406
+ row[header] = cells[cellIndex] || "";
10407
+ });
10408
+ if (row.task_id) {
10409
+ rows.push(row);
10410
+ }
10411
+ cursor += 1;
10412
+ }
10413
+ }
10414
+ return rows;
10415
+ }
10416
+ async function initTaskbookProgress(source, outFile) {
10417
+ const text5 = await readTaskbookText(source);
10418
+ const rows = extractTaskRows(text5);
10419
+ if (rows.length === 0) {
10420
+ throw new TaskbookError("Taskbook progress init could not find an AI task table with task_id/status/subagent_mode columns.");
10421
+ }
10422
+ const fields = [
10423
+ "task_id",
10424
+ "status",
10425
+ "phase",
10426
+ "parallel_type",
10427
+ "subagent_mode",
10428
+ "business_goal",
10429
+ "required_skills",
10430
+ "object_lock",
10431
+ "dependencies",
10432
+ "owner",
10433
+ "started_at",
10434
+ "finished_at",
10435
+ "evidence",
10436
+ "notes"
10437
+ ];
10438
+ const csv = [
10439
+ fields.join(","),
10440
+ ...rows.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
10441
+ ].join("\n") + "\n";
10442
+ await mkdir8(path8.dirname(outFile), { recursive: true });
10443
+ await writeFile8(outFile, csv, "utf8");
10444
+ return { source, out: outFile, task_count: rows.length };
10445
+ }
10446
+
10447
+ // src/commands/taskbook.ts
10448
+ function collect(value, previous = []) {
10449
+ previous.push(value);
10450
+ return previous;
10451
+ }
10452
+ function registerTaskbookCommands(program2) {
10453
+ const taskbook = program2.command("taskbook").description("Manage BPMAX AI implementation taskbooks and prompt gates");
10454
+ taskbook.command("init").description("Create a local BPMAX AI implementation taskbook template").requiredOption("--out <file>", "Output taskbook markdown file").option("--title <title>", "Taskbook title").option("--format <format>", "Output format", "pretty").action(async (options) => {
10455
+ printResult(options.format, await initTaskbook(options.out, options.title));
10456
+ });
10457
+ taskbook.command("lint").description("Lint a BPMAX AI implementation taskbook").requiredOption("--source <file>", "Taskbook markdown/xml/text or fetched Lark Docx JSON").option("--require-term <term>", "Additional required term", collect, []).option("--forbid-term <term>", "Forbidden term", collect, []).option("--allow-generated-flow-type-missing", "Skip generated flow_type rule for taskbooks that do not create flows").option("--format <format>", "Output format", "pretty").action(async (options) => {
10458
+ const result = await lintTaskbook(options.source, {
10459
+ requireTerms: options.requireTerm,
10460
+ forbidTerms: options.forbidTerm,
10461
+ allowGeneratedFlowTypeMissing: Boolean(options.allowGeneratedFlowTypeMissing)
10462
+ });
10463
+ printResult(options.format, result);
10464
+ if (!result.ok) {
10465
+ throw new Error(`Taskbook lint failed for ${options.source}`);
10466
+ }
10467
+ });
10468
+ taskbook.command("lint-prompt").description("Lint a single AI/subagent task prompt before dispatch").requiredOption("--prompt-source <file>", "Task prompt markdown/text file").option("--require-term <term>", "Additional required term", collect, []).option("--forbid-term <term>", "Forbidden term", collect, []).option("--format <format>", "Output format", "pretty").action(async (options) => {
10469
+ const result = await lintTaskPrompt(options.promptSource, {
10470
+ requireTerms: options.requireTerm,
10471
+ forbidTerms: options.forbidTerm
10472
+ });
10473
+ printResult(options.format, result);
10474
+ if (!result.ok) {
10475
+ throw new Error(`Task prompt lint failed for ${options.promptSource}`);
10476
+ }
10477
+ });
10478
+ const progress = taskbook.command("progress").description("Manage taskbook execution progress artifacts");
10479
+ progress.command("init").description("Initialize a progress CSV from a taskbook AI task table").requiredOption("--source <file>", "Taskbook markdown/xml/text file").requiredOption("--out <file>", "Progress CSV output file").option("--format <format>", "Output format", "pretty").action(async (options) => {
10480
+ printResult(options.format, await initTaskbookProgress(options.source, options.out));
10481
+ });
10482
+ }
10483
+
10484
+ // src/core/test-suite.ts
10485
+ import { createHash as createHash4 } from "crypto";
10486
+ import {
10487
+ copyFile,
10488
+ cp as cp2,
10489
+ mkdir as mkdir9,
10490
+ readdir as readdir2,
10491
+ readFile as readFile11,
10492
+ rm as rm3,
10493
+ stat as stat4,
10494
+ writeFile as writeFile9
10495
+ } from "fs/promises";
10496
+ import path9 from "path";
10497
+ var DEFAULT_SUITE_ROOT = ".ai_test/suite";
10498
+ var DEFAULT_DRAFT_ROOT = ".ai_test/suite_draft";
10499
+ var DEFAULT_REPORT_ROOT = ".ai_test/report";
10500
+ var DEFAULT_TMP_ROOT = ".codex/tmp/ai_test_suite";
10501
+ var COPY_DIFF_DIR = ".copy_diff";
10502
+ var CASE_FIELDS = [
10503
+ "case_id",
10504
+ "priority",
10505
+ "type",
10506
+ "title",
10507
+ "preconditions",
10508
+ "config_basis",
10509
+ "prep_data",
10510
+ "steps",
10511
+ "expected_result",
10512
+ "test_data",
10513
+ "roles",
10514
+ "evidence_required",
10515
+ "tags",
10516
+ "status",
10517
+ "updated_at"
10518
+ ];
10519
+ var REQUIRED_README_KEYS = ["scenario_id", "workspace", "flow_type", "core", "status"];
10520
+ var PRIORITIES = /* @__PURE__ */ new Set(["P0", "P1", "P2"]);
10521
+ var CASE_TYPES = /* @__PURE__ */ new Set(["positive", "negative", "boundary", "permission", "data_consistency", "regression"]);
10522
+ var STATUSES = /* @__PURE__ */ new Set(["active", "deprecated", "draft"]);
10523
+ var REVIEW_STATUSES = /* @__PURE__ */ new Set(["passed", "fixed"]);
10524
+ var REVIEW_REQUIRED_PERSPECTIVES = /* @__PURE__ */ new Set([
10525
+ "structure_lint",
10526
+ "business_coverage",
10527
+ "execution_operability",
10528
+ "config_consistency"
10529
+ ]);
10530
+ var CONFIG_CONSISTENCY_STATUSES = /* @__PURE__ */ new Set(["correct", "needs_update", "deprecated", "split_or_add", "blocked"]);
10531
+ var CONFIG_BASIS_ALLOWED_PREFIXES = [
10532
+ "think_flow/",
10533
+ "think_form_template/",
10534
+ "think_data_set/",
10535
+ "think_data_set_field/",
10536
+ "think_flow_page_template/",
10537
+ "think_configuration/",
10538
+ "think_role/",
10539
+ "think_category/",
10540
+ "think_api_platform/",
10541
+ "think_api_proxy/",
10542
+ "think_workspace/",
10543
+ "skills/",
10544
+ ".ai_test/",
10545
+ ".codex/skills/"
10546
+ ];
10547
+ var REPORT_REQUIRED_KEYS = ["run_id:", "scenario_id:", "source_suite:", "result:"];
10548
+ var REPORT_REQUIRED_HEADINGS = [
10549
+ "## 1. \u6D4B\u8BD5\u8303\u56F4",
10550
+ "## 2. \u6267\u884C\u73AF\u5883",
10551
+ "## 3. \u7528\u4F8B\u6267\u884C\u7ED3\u679C",
10552
+ "## 4. \u622A\u56FE\u8BC1\u636E",
10553
+ "## 5. \u63A5\u53E3 / \u6570\u636E\u56DE\u8BFB\u8BC1\u636E",
10554
+ "## 6. \u53D1\u73B0\u95EE\u9898",
10555
+ "## 7. \u7528\u4F8B\u8D44\u4EA7\u53CD\u9988"
10556
+ ];
10557
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
10558
+ var RUN_RE = /^\d{8}-(\d{3})$/;
10559
+ var SCENARIO_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
10560
+ var UUID_RE = /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/;
10561
+ var ID_AS_ENTRY_RE = /(发起表单|处理表单|表单模板|数据集|列表模板|详情模板)\s*(UUID|uuid|ID|id|:|:)/;
10562
+ var URL_RE = /https?:\/\/|\/w:[^\s,,;;]+|\/project\?|\/project_detail\/|\/projectContinue\?/;
10563
+ var SHA_RE = /^[0-9a-f]{40}$/;
10564
+ var CONFIG_BASIS_REASON_RE = /(依据|覆盖|校验|验证|对应|因为|reason=|why=|=>|->)/;
10565
+ var PREP_TOKEN_RE = /(账号|入口|样本|准备操作|预期|主数据|权限|自动化|依赖流程|清理策略|绑定解析|定位规则|模拟用户)=/g;
10566
+ var PLACEHOLDER_RE = /<[^>]+>/;
10567
+ var IMAGE_RE = /!\[[^\]]*]\(([^)]+)\)/g;
10568
+ var YBS_NONZERO_DETAIL_RE = /https:\/\/yaditest\.yitaiyitai\.com\/w:ybs\/project_detail\/(?!0\/)\d+\//;
10569
+ var YBS_PC_CREATE_WRONG_RE = /https:\/\/yaditest\.yitaiyitai\.com\/w:ybs\/pages\/projectCreate\/projectCreate\?flow_type=/;
10570
+ var IDENTITY_MOCK_CASE_RE = /(非处理人|越权|只读|多角色|角色隔离|无权限|低权限|unauthorized|limited|readonly|permission)/;
10571
+ var IDENTITY_MOCK_VALUE_RE = /(mock|模拟).*(unmock|退出模拟|恢复)|bpmax-user-mock-operator/;
10572
+ var TestSuiteError = class extends Error {
10573
+ };
10574
+ async function exists2(filePath) {
10575
+ try {
10576
+ await stat4(filePath);
10577
+ return true;
10578
+ } catch {
10579
+ return false;
10580
+ }
10581
+ }
10582
+ async function readText(filePath) {
10583
+ return readFile11(filePath, "utf8");
10584
+ }
10585
+ function fail(message) {
10586
+ throw new TestSuiteError(message);
10587
+ }
10588
+ function splitCsvLine(line) {
10589
+ const values = [];
10590
+ let current = "";
10591
+ let inQuotes = false;
10592
+ for (let index = 0; index < line.length; index += 1) {
10593
+ const char = line[index];
10594
+ if (char === '"') {
10595
+ if (inQuotes && line[index + 1] === '"') {
10596
+ current += '"';
10597
+ index += 1;
10598
+ } else {
10599
+ inQuotes = !inQuotes;
10600
+ }
10601
+ continue;
10602
+ }
10603
+ if (char === "," && !inQuotes) {
10604
+ values.push(current);
10605
+ current = "";
10606
+ continue;
10607
+ }
10608
+ current += char;
10609
+ }
10610
+ values.push(current);
10611
+ return values;
10612
+ }
10613
+ async function readCases(filePath) {
10614
+ if (!await exists2(filePath)) fail(`missing cases.csv: ${filePath}`);
10615
+ const text5 = (await readText(filePath)).replace(/^\uFEFF/, "");
10616
+ const lines = text5.split(/\r?\n/).filter((line) => line.length > 0);
10617
+ if (lines.length === 0) fail(`${filePath}: CSV fields must be exactly ${JSON.stringify(CASE_FIELDS)}`);
10618
+ const fields = splitCsvLine(lines[0]);
10619
+ if (JSON.stringify(fields) !== JSON.stringify(CASE_FIELDS)) {
10620
+ fail(`${filePath}: CSV fields must be exactly ${JSON.stringify(CASE_FIELDS)}`);
10621
+ }
10622
+ return lines.slice(1).map((line) => {
10623
+ const values = splitCsvLine(line);
10624
+ const row = {};
10625
+ CASE_FIELDS.forEach((field, index) => {
10626
+ row[field] = values[index] ?? "";
10627
+ });
10628
+ return row;
10629
+ });
10630
+ }
10631
+ function parseReadmeText(filePath, text5) {
10632
+ const metadata = {};
10633
+ let title = "";
10634
+ const summary = [];
10635
+ let inSummary = false;
10636
+ for (const raw of text5.split(/\r?\n/)) {
10637
+ const line = raw.trim();
10638
+ if (line.startsWith("# ") && !title) {
10639
+ title = line.slice(2).trim();
10640
+ continue;
10641
+ }
10642
+ if (line.includes(":") && !line.startsWith("#") && !line.startsWith("-")) {
10643
+ const [key, ...rest] = line.split(":");
10644
+ if ([...REQUIRED_README_KEYS, "owner_skill", "tags"].includes(key.trim())) {
10645
+ metadata[key.trim()] = rest.join(":").trim();
10646
+ }
10647
+ continue;
10648
+ }
10649
+ if (line.startsWith("## \u573A\u666F\u7B80\u4ECB")) {
10650
+ inSummary = true;
10651
+ continue;
10652
+ }
10653
+ if (line.startsWith("## ") && inSummary) {
10654
+ inSummary = false;
10655
+ continue;
10656
+ }
10657
+ if (inSummary && line) summary.push(line);
10658
+ }
10659
+ metadata.title = title;
10660
+ metadata.summary = summary.join(" ").trim();
10661
+ if (!metadata.title) fail(`${filePath}: README.md missing title`);
10662
+ if (!metadata.summary) fail(`${filePath}: README.md missing scenario summary`);
10663
+ return metadata;
10664
+ }
10665
+ async function validateReadme(scenarioDir) {
10666
+ const readmePath = path9.join(scenarioDir, "README.md");
10667
+ if (!await exists2(readmePath)) fail(`missing README.md: ${readmePath}`);
10668
+ const text5 = await readText(readmePath);
10669
+ const metadata = parseReadmeText(readmePath, text5);
10670
+ for (const key of REQUIRED_README_KEYS) {
10671
+ if (!metadata[key]) fail(`${scenarioDir}: README.md missing \`${key}\``);
10672
+ }
10673
+ if (metadata.scenario_id !== path9.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
10674
+ if (!["true", "false"].includes(metadata.core.toLowerCase())) fail(`${scenarioDir}: core must be true or false`);
10675
+ if (!STATUSES.has(metadata.status)) fail(`${scenarioDir}: status must be one of ${JSON.stringify([...STATUSES].sort())}`);
10676
+ if (UUID_RE.test(text5) || ID_AS_ENTRY_RE.test(text5)) {
10677
+ fail(`${scenarioDir}: README must use browser URLs as execution entrypoints, not UUID/ID identifiers`);
10678
+ }
10679
+ return metadata;
10680
+ }
10681
+ function configBasisLocations(configBasis) {
10682
+ return configBasis.replace(/,/g, ";").replace(/,/g, ";").split(";").map((chunk) => chunk.trim().replace(/^`|`$/g, "").split(/\s+/)[0]?.replace(/^`|`$/g, "")).filter((chunk) => chunk && CONFIG_BASIS_ALLOWED_PREFIXES.some((prefix) => chunk.startsWith(prefix)));
10683
+ }
10684
+ async function validateConfigBasis(filePath, caseId, configBasis) {
10685
+ if (!configBasis.trim()) fail(`${filePath}:${caseId}: \`config_basis\` is required`);
10686
+ const locations = configBasisLocations(configBasis);
10687
+ if (locations.length === 0) {
10688
+ fail(`${filePath}:${caseId}: \`config_basis\` must include at least one related config location`);
10689
+ }
10690
+ if (!CONFIG_BASIS_REASON_RE.test(configBasis)) fail(`${filePath}:${caseId}: \`config_basis\` must explain why`);
10691
+ const missing = [];
10692
+ for (const location of locations) {
10693
+ if (!await exists2(location)) missing.push(location);
10694
+ }
10695
+ if (missing.length > 0) fail(`${filePath}:${caseId}: \`config_basis\` references missing config location(s): ${missing.join(", ")}`);
10696
+ }
10697
+ function parsePrepData(value) {
10698
+ const matches = [...value.matchAll(PREP_TOKEN_RE)];
10699
+ const tokens = {};
10700
+ matches.forEach((match, index) => {
10701
+ const start = (match.index ?? 0) + match[0].length;
10702
+ const end = index + 1 < matches.length ? (matches[index + 1].index ?? value.length) - 1 : value.length;
10703
+ tokens[match[1]] = value.slice(start, end).trim().replace(/;$/, "");
10704
+ });
10705
+ return tokens;
10706
+ }
10707
+ async function validateCase(filePath, row, seen) {
10708
+ const caseId = row.case_id.trim();
10709
+ if (!caseId) fail(`${filePath}: case_id is required`);
10710
+ if (seen.has(caseId)) fail(`${filePath}: duplicate case_id \`${caseId}\``);
10711
+ seen.add(caseId);
10712
+ for (const field of ["title", "config_basis", "steps", "expected_result", "status", "updated_at"]) {
10713
+ if (!row[field].trim()) fail(`${filePath}:${caseId}: \`${field}\` is required`);
10714
+ }
10715
+ await validateConfigBasis(filePath, caseId, row.config_basis.trim());
10716
+ const prepData = row.prep_data.trim();
10717
+ if (!prepData) fail(`${filePath}:${caseId}: \`prep_data\` is required`);
10718
+ const requiredTokens = ["\u8D26\u53F7", "\u5165\u53E3", "\u6837\u672C", "\u51C6\u5907\u64CD\u4F5C", "\u9884\u671F"];
10719
+ const prepTokens = parsePrepData(prepData);
10720
+ const missingTokens = requiredTokens.filter((token) => !prepTokens[token]);
10721
+ if (missingTokens.length > 0) fail(`${filePath}:${caseId}: \`prep_data\` must include ${requiredTokens.map((token) => `${token}=`).join(", ")}`);
10722
+ for (const chunk of prepData.split(";")) {
10723
+ if (chunk.trim() && !chunk.includes("=")) fail(`${filePath}:${caseId}: every \`prep_data\` segment must be key=value`);
10724
+ }
10725
+ if (!URL_RE.test(prepTokens["\u5165\u53E3"])) fail(`${filePath}:${caseId}: \`prep_data\` token \`\u5165\u53E3=\` must be a browser URL or runtime route`);
10726
+ if (PLACEHOLDER_RE.test(prepTokens["\u5165\u53E3"]) && !prepTokens["\u7ED1\u5B9A\u89E3\u6790"]) {
10727
+ fail(`${filePath}:${caseId}: placeholder runtime entrypoints must include \`\u7ED1\u5B9A\u89E3\u6790=\` in \`prep_data\``);
10728
+ }
10729
+ if (/(auto-through|subflow)/.test(row.tags) && !prepTokens["\u5B9A\u4F4D\u89C4\u5219"]) {
10730
+ fail(`${filePath}:${caseId}: auto-through/subflow cases must include \`\u5B9A\u4F4D\u89C4\u5219=\` in \`prep_data\``);
10731
+ }
10732
+ const identityText = [row.type, row.title, row.preconditions, row.roles, row.tags].join(" ");
10733
+ if (IDENTITY_MOCK_CASE_RE.test(identityText)) {
10734
+ if (!prepTokens["\u6A21\u62DF\u7528\u6237"]) fail(`${filePath}:${caseId}: permission/multi-role cases must include \`\u6A21\u62DF\u7528\u6237=\` in \`prep_data\``);
10735
+ if (!IDENTITY_MOCK_VALUE_RE.test(prepTokens["\u6A21\u62DF\u7528\u6237"])) {
10736
+ fail(`${filePath}:${caseId}: \`\u6A21\u62DF\u7528\u6237=\` must describe mock and unmock/restore with bpmax-user-mock-operator`);
10737
+ }
10738
+ }
10739
+ if (row.roles.includes(";")) fail(`${filePath}:${caseId}: \`roles\` must use comma-separated values, not semicolons`);
10740
+ if (!PRIORITIES.has(row.priority)) fail(`${filePath}:${caseId}: priority must be one of ${JSON.stringify([...PRIORITIES].sort())}`);
10741
+ if (!CASE_TYPES.has(row.type)) fail(`${filePath}:${caseId}: type must be one of ${JSON.stringify([...CASE_TYPES].sort())}`);
10742
+ if (!STATUSES.has(row.status)) fail(`${filePath}:${caseId}: status must be one of ${JSON.stringify([...STATUSES].sort())}`);
10743
+ if (!DATE_RE.test(row.updated_at)) fail(`${filePath}:${caseId}: updated_at must be YYYY-MM-DD`);
10744
+ const evidence = row.evidence_required.toLowerCase();
10745
+ if (["page", "\u9875\u9762", "screenshot", "visible", "frontend"].some((word) => evidence.includes(word)) && !evidence.includes("screenshot")) {
10746
+ fail(`${filePath}:${caseId}: page evidence must include screenshot`);
10747
+ }
10748
+ const browserText = [row.preconditions, row.prep_data, row.steps, row.expected_result].join(" ");
10749
+ if (["screenshot", "project_detail", "list"].some((word) => evidence.includes(word)) && !URL_RE.test(browserText)) {
10750
+ fail(`${filePath}:${caseId}: browser-executed cases must include a concrete browser URL or route in preconditions/steps/expected_result`);
10751
+ }
10752
+ if (UUID_RE.test(browserText)) fail(`${filePath}:${caseId}: browser-executed cases must not use UUID as the execution entrypoint`);
10753
+ 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`);
10754
+ 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>`);
10755
+ }
10756
+ async function scenarioDirs(root) {
10757
+ if (!await exists2(root)) return [];
10758
+ const items = await readdir2(root, { withFileTypes: true });
10759
+ return items.filter((item) => item.isDirectory()).map((item) => path9.join(root, item.name)).sort();
10760
+ }
10761
+ async function validateScenario(scenarioDir) {
10762
+ const metadata = await validateReadme(scenarioDir);
10763
+ const casesPath = path9.join(scenarioDir, "cases.csv");
10764
+ const rows = await readCases(casesPath);
10765
+ if (rows.length === 0) fail(`${casesPath}: at least one case is required`);
10766
+ const seen = /* @__PURE__ */ new Set();
10767
+ for (const row of rows) await validateCase(casesPath, row, seen);
10768
+ const activeRows = rows.filter((row) => row.status === "active");
10769
+ const availableRows = rows.filter((row) => row.status !== "deprecated");
10770
+ if (metadata.status === "active" && activeRows.length === 0) fail(`${scenarioDir}: active scenario must contain active cases`);
10771
+ if (metadata.core.toLowerCase() === "true" && metadata.status !== "deprecated") {
10772
+ const hasCorePositive = rows.some((row) => row.status !== "deprecated" && row.priority === "P0" && row.type === "positive");
10773
+ if (!hasCorePositive) fail(`${scenarioDir}: non-deprecated core scenario requires a non-deprecated P0 positive case`);
10774
+ }
10775
+ await validateCopyDiffArtifacts(scenarioDir);
10776
+ return {
10777
+ scenario_id: metadata.scenario_id,
10778
+ title: metadata.title,
10779
+ workspace: metadata.workspace,
10780
+ flow_type: metadata.flow_type,
10781
+ core: metadata.core,
10782
+ status: metadata.status,
10783
+ summary: metadata.summary,
10784
+ case_count: rows.length,
10785
+ active_case_count: activeRows.length,
10786
+ available_case_count: availableRows.length,
10787
+ tags: [...new Set(rows.flatMap((row) => row.tags.split(",").map((tag) => tag.trim()).filter(Boolean)))].sort()
10788
+ };
10789
+ }
10790
+ async function lintSuite(root = DEFAULT_SUITE_ROOT) {
10791
+ const dirs = await scenarioDirs(root);
10792
+ const results = [];
10793
+ for (const dir of dirs) results.push(await validateScenario(dir));
10794
+ return results;
10795
+ }
10796
+ async function indexSuite(root = DEFAULT_SUITE_ROOT, includeInactive = false) {
10797
+ const items = await lintSuite(root);
10798
+ return includeInactive ? items : items.filter((item) => item.status === "active");
10799
+ }
10800
+ async function requireLatestProof(proofPath) {
10801
+ if (!proofPath) fail("--latest-proof is required");
10802
+ if (!await exists2(proofPath)) fail(`latest proof is required before this command: ${proofPath}`);
10803
+ let proof;
10804
+ try {
10805
+ proof = JSON.parse(await readText(proofPath));
10806
+ } catch (error) {
10807
+ fail(`${proofPath}: invalid latest proof JSON: ${error instanceof Error ? error.message : String(error)}`);
10808
+ }
10809
+ validateLatestProofObject(proofPath, proof);
10810
+ }
10811
+ function validateLatestProofObject(proofPath, proof) {
10812
+ if (!String(proof.method || "").startsWith("latest-")) fail(`${proofPath}: method must start with latest-`);
10813
+ if (proof.allow_dirty !== true) fail(`${proofPath}: allow_dirty must be true`);
10814
+ for (const key of ["before", "after", "head"]) {
10815
+ if (!SHA_RE.test(String(proof[key] || ""))) fail(`${proofPath}: ${key} must be a 40-character git sha`);
10816
+ }
10817
+ if (!("status_short" in proof)) fail(`${proofPath}: status_short is required`);
10818
+ }
10819
+ function scenarioPath(root, scenario) {
10820
+ if (!SCENARIO_ID_RE.test(scenario)) fail(`invalid scenario id: ${scenario}`);
10821
+ const rootResolved = path9.resolve(root);
10822
+ const candidate = path9.resolve(root, scenario);
10823
+ if (!candidate.startsWith(`${rootResolved}${path9.sep}`) && candidate !== rootResolved) {
10824
+ fail(`scenario path escapes root: ${candidate}`);
10825
+ }
10826
+ return candidate;
10827
+ }
10828
+ async function fileMap(root) {
10829
+ const result = /* @__PURE__ */ new Map();
10830
+ async function walk(dir) {
10831
+ for (const item of await readdir2(dir, { withFileTypes: true })) {
10832
+ const itemPath = path9.join(dir, item.name);
10833
+ const rel = path9.relative(root, itemPath);
10834
+ if (rel.split(path9.sep)[0] === COPY_DIFF_DIR) continue;
10835
+ if (item.isDirectory()) {
10836
+ await walk(itemPath);
10837
+ } else if (item.isFile()) {
10838
+ result.set(rel.split(path9.sep).join("/"), itemPath);
10839
+ }
10840
+ }
10841
+ }
10842
+ await walk(root);
10843
+ return result;
10844
+ }
10845
+ async function sha256(filePath) {
10846
+ return createHash4("sha256").update(await readFile11(filePath)).digest("hex");
10847
+ }
10848
+ async function readForDiff(filePath) {
10849
+ const buffer = await readFile11(filePath);
10850
+ if (buffer.includes(0)) return [`<binary sha256=${createHash4("sha256").update(buffer).digest("hex")}>
10851
+ `];
10852
+ return buffer.toString("utf8").split(/(?<=\n)/);
10853
+ }
10854
+ function unifiedDiff(oldLines, newLines, oldName, newName) {
10855
+ if (oldLines.join("") === newLines.join("")) return "";
10856
+ return [`--- ${oldName}
10857
+ `, `+++ ${newName}
10858
+ `, ...oldLines.map((line) => `-${line}`), ...newLines.map((line) => `+${line}`)].join("");
10859
+ }
10860
+ async function buildCopyDiff(src, dst, operation) {
10861
+ const srcFiles = await fileMap(src);
10862
+ const dstFiles = await fileMap(dst);
10863
+ const rels = [.../* @__PURE__ */ new Set([...srcFiles.keys(), ...dstFiles.keys()])].sort();
10864
+ const summary = { added: 0, modified: 0, removed: 0, unchanged: 0 };
10865
+ const files = [];
10866
+ let diff = "";
10867
+ for (const rel of rels) {
10868
+ const srcPath = srcFiles.get(rel);
10869
+ const dstPath = dstFiles.get(rel);
10870
+ const source_sha256 = srcPath ? await sha256(srcPath) : null;
10871
+ const destination_sha256 = dstPath ? await sha256(dstPath) : null;
10872
+ let status;
10873
+ if (srcPath && !dstPath) status = "added";
10874
+ else if (!srcPath && dstPath) status = "removed";
10875
+ else if (source_sha256 === destination_sha256) status = "unchanged";
10876
+ else status = "modified";
10877
+ summary[status] += 1;
10878
+ files.push({ path: rel, status, source_sha256, destination_sha256 });
10879
+ if (status !== "unchanged") {
10880
+ diff += unifiedDiff(
10881
+ dstPath ? await readForDiff(dstPath) : [],
10882
+ srcPath ? await readForDiff(srcPath) : [],
10883
+ `destination/${rel}`,
10884
+ `source/${rel}`
10885
+ );
10886
+ }
10887
+ }
10888
+ return {
10889
+ manifest: {
10890
+ operation,
10891
+ scenario_id: path9.basename(src),
10892
+ source: src,
10893
+ destination: dst,
10894
+ generated_at: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "+00:00"),
10895
+ summary,
10896
+ diff_file: "last.diff",
10897
+ files
10898
+ },
10899
+ diff: diff || "# No file content changes between source and destination.\n"
10900
+ };
10901
+ }
10902
+ async function writeCopyDiffArtifacts(dst, artifacts) {
10903
+ const diffDir = path9.join(dst, COPY_DIFF_DIR);
10904
+ await mkdir9(diffDir, { recursive: true });
10905
+ await writeFile9(path9.join(diffDir, "last.diff"), artifacts.diff, "utf8");
10906
+ await writeFile9(path9.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
10907
+ `, "utf8");
10908
+ return path9.join(diffDir, "last.diff");
10909
+ }
10910
+ async function copyScenarioTree(src, dst, replace, operation) {
10911
+ if (!await exists2(src)) fail(`source scenario not found: ${src}`);
10912
+ let artifacts;
10913
+ if (await exists2(dst)) {
10914
+ if (!replace) fail(`destination already exists, pass --replace: ${dst}`);
10915
+ artifacts = await buildCopyDiff(src, dst, operation);
10916
+ await rm3(dst, { recursive: true, force: true });
10917
+ }
10918
+ await mkdir9(path9.dirname(dst), { recursive: true });
10919
+ await cp2(src, dst, { recursive: true });
10920
+ return artifacts ? writeCopyDiffArtifacts(dst, artifacts) : void 0;
10921
+ }
10922
+ async function copyDiffPreview(src, dst, operation) {
10923
+ const previewDir = path9.join(DEFAULT_TMP_ROOT, `${operation}-${path9.basename(src)}-copy-diff`);
10924
+ await rm3(previewDir, { recursive: true, force: true });
10925
+ await mkdir9(previewDir, { recursive: true });
10926
+ return writeCopyDiffArtifacts(previewDir, await buildCopyDiff(src, dst, operation));
10927
+ }
10928
+ async function draftUpdate(options) {
10929
+ const src = scenarioPath(options.suiteRoot ?? DEFAULT_SUITE_ROOT, options.scenario);
10930
+ const dst = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
10931
+ if (options.replace && !options.diffReviewed && await exists2(dst)) {
10932
+ return {
10933
+ copy_diff: await copyDiffPreview(src, dst, "draft-update"),
10934
+ preview: true,
10935
+ message: "destination was not changed; review the diff, then rerun with --diff-reviewed to apply the overwrite"
10936
+ };
10937
+ }
10938
+ return { destination: dst, copy_diff: await copyScenarioTree(src, dst, Boolean(options.replace), "draft-update") };
10939
+ }
10940
+ async function validateReviewGate(scenarioDir) {
10941
+ const reviewPath = path9.join(scenarioDir, "review.json");
10942
+ if (!await exists2(reviewPath)) fail(`${scenarioDir}: missing review.json; run multi-subagent SKILL review before promote`);
10943
+ let review;
10944
+ try {
10945
+ review = JSON.parse(await readText(reviewPath));
10946
+ } catch (error) {
10947
+ fail(`${reviewPath}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
10948
+ }
10949
+ if (review.scenario_id !== path9.basename(scenarioDir)) fail(`${reviewPath}: scenario_id must match directory name`);
10950
+ if (!review.latest_proof || typeof review.latest_proof !== "object" || Array.isArray(review.latest_proof)) fail(`${reviewPath}: latest_proof is required`);
10951
+ validateLatestProofObject(reviewPath, review.latest_proof);
10952
+ if (!REVIEW_STATUSES.has(String(review.status))) fail(`${reviewPath}: status must be one of ${JSON.stringify([...REVIEW_STATUSES].sort())}`);
10953
+ if (!DATE_RE.test(String(review.reviewed_at || ""))) fail(`${reviewPath}: reviewed_at must be YYYY-MM-DD`);
10954
+ const perspectives = review.perspectives;
10955
+ if (!Array.isArray(perspectives)) fail(`${reviewPath}: perspectives must be a list`);
10956
+ const perspectiveNames = new Set(perspectives.map((item) => item?.name));
10957
+ const missing = [...REVIEW_REQUIRED_PERSPECTIVES].filter((name) => !perspectiveNames.has(name));
10958
+ if (missing.length > 0) fail(`${reviewPath}: missing required review perspectives: ${missing.join(", ")}`);
10959
+ for (const item of perspectives) {
10960
+ if (!item?.reviewer) fail(`${reviewPath}: perspective \`${item?.name ?? ""}\` missing reviewer`);
10961
+ if (!REVIEW_STATUSES.has(String(item.status))) fail(`${reviewPath}: perspective \`${item?.name ?? ""}\` status must be one of ${JSON.stringify([...REVIEW_STATUSES].sort())}`);
10962
+ if (!item.summary) fail(`${reviewPath}: perspective \`${item?.name ?? ""}\` missing summary`);
10963
+ if (item.name === "config_consistency") await validateConfigConsistencyReview(reviewPath, item);
10964
+ }
10965
+ const unresolved = review.unresolved;
10966
+ if (!unresolved || typeof unresolved !== "object" || Array.isArray(unresolved)) fail(`${reviewPath}: unresolved must be an object`);
10967
+ if (unresolved.P0 !== 0 || unresolved.P1 !== 0) {
10968
+ fail(`${reviewPath}: unresolved P0/P1 findings must be 0 before promote`);
10969
+ }
10970
+ if (!Array.isArray(review.fixes) || review.fixes.length === 0) fail(`${reviewPath}: fixes must be a non-empty list`);
10971
+ }
10972
+ async function validateConfigConsistencyReview(reviewPath, item) {
10973
+ const judgments = item.case_judgments;
10974
+ if (!Array.isArray(judgments) || judgments.length === 0) fail(`${reviewPath}: config_consistency must include non-empty case_judgments`);
10975
+ for (const judgment of judgments) {
10976
+ if (!judgment?.case_id) fail(`${reviewPath}: config_consistency case_judgments item missing case_id`);
10977
+ if (!CONFIG_CONSISTENCY_STATUSES.has(String(judgment.status))) {
10978
+ fail(`${reviewPath}: config_consistency judgment \`${judgment.case_id}\` status must be one of ${JSON.stringify([...CONFIG_CONSISTENCY_STATUSES].sort())}`);
10979
+ }
10980
+ if (!Array.isArray(judgment.config_basis_checked) || judgment.config_basis_checked.length === 0) {
10981
+ fail(`${reviewPath}: config_consistency judgment \`${judgment.case_id}\` must include config_basis_checked`);
10982
+ }
10983
+ const missing = [];
10984
+ for (const location of judgment.config_basis_checked) {
10985
+ if (typeof location !== "string" || !await exists2(location)) missing.push(String(location));
10986
+ }
10987
+ if (missing.length > 0) fail(`${reviewPath}: config_consistency judgment \`${judgment.case_id}\` references missing checked location(s): ${missing.join(", ")}`);
10988
+ if (!judgment.evidence) fail(`${reviewPath}: config_consistency judgment \`${judgment.case_id}\` missing evidence`);
10989
+ }
10990
+ const missingCaseReview = item.missing_case_review;
10991
+ if (!missingCaseReview || typeof missingCaseReview !== "object" || Array.isArray(missingCaseReview)) fail(`${reviewPath}: config_consistency must include missing_case_review`);
10992
+ const missingCaseReviewObject = missingCaseReview;
10993
+ if (typeof missingCaseReviewObject.needed !== "boolean") fail(`${reviewPath}: config_consistency missing_case_review.needed must be boolean`);
10994
+ if (!missingCaseReviewObject.summary) fail(`${reviewPath}: config_consistency missing_case_review.summary is required`);
10995
+ }
10996
+ async function promoteScenario(options) {
10997
+ const src = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
10998
+ const metadata = await validateScenario(src);
10999
+ await validateReviewGate(src);
11000
+ if (metadata.status === "draft") fail(`${src}: cannot promote README status draft; set status to active or deprecated`);
11001
+ const dst = scenarioPath(options.suiteRoot ?? DEFAULT_SUITE_ROOT, options.scenario);
11002
+ if (options.replace && !options.diffReviewed && await exists2(dst)) {
11003
+ return {
11004
+ copy_diff: await copyDiffPreview(src, dst, "promote"),
11005
+ preview: true,
11006
+ message: "destination was not changed; review the diff, then rerun with --diff-reviewed to apply the overwrite"
11007
+ };
11008
+ }
11009
+ return { destination: dst, copy_diff: await copyScenarioTree(src, dst, Boolean(options.replace), "promote") };
11010
+ }
11011
+ async function nextReportDir(root = DEFAULT_REPORT_ROOT, create = false, today = /* @__PURE__ */ new Date()) {
11012
+ const prefix = [
11013
+ today.getFullYear(),
11014
+ String(today.getMonth() + 1).padStart(2, "0"),
11015
+ String(today.getDate()).padStart(2, "0")
11016
+ ].join("");
11017
+ const dirs = await scenarioDirs(root);
11018
+ const nums = dirs.map((dir) => path9.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
11019
+ const reportDir = path9.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
11020
+ if (create) {
11021
+ await mkdir9(path9.join(reportDir, "screenshots"), { recursive: true });
11022
+ await writeFile9(
11023
+ path9.join(reportDir, "summary.md"),
11024
+ ["# BPMAX E2E \u6D4B\u8BD5\u62A5\u544A\u6C47\u603B", "", `run_id: ${path9.basename(reportDir)}`, "status: draft", "", "## \u573A\u666F\u62A5\u544A", "", "## \u603B\u7ED3", ""].join("\n"),
11025
+ "utf8"
11026
+ );
11027
+ }
11028
+ return reportDir;
11029
+ }
11030
+ async function lintReport(root = DEFAULT_REPORT_ROOT) {
11031
+ if (!await exists2(root)) return [`report root not found: ${root}`];
11032
+ const errors = [];
11033
+ for (const runDir of await scenarioDirs(root)) {
11034
+ const runName = path9.basename(runDir);
11035
+ if (!RUN_RE.test(runName)) {
11036
+ errors.push(`${runDir}: run directory name must be YYYYMMDD-NNN`);
11037
+ continue;
11038
+ }
11039
+ if (!await exists2(path9.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
11040
+ const files = await readdir2(runDir);
11041
+ const scenarioReports = files.filter((file) => file.endsWith(".md") && file !== "summary.md");
11042
+ if (scenarioReports.length === 0) errors.push(`${runDir}: missing scenario report markdown`);
11043
+ for (const reportName of scenarioReports) {
11044
+ const reportPath = path9.join(runDir, reportName);
11045
+ const text5 = await readText(reportPath);
11046
+ for (const key of REPORT_REQUIRED_KEYS) if (!text5.includes(key)) errors.push(`${reportPath}: missing \`${key}\``);
11047
+ for (const heading of REPORT_REQUIRED_HEADINGS) if (!text5.includes(heading)) errors.push(`${reportPath}: missing \`${heading}\``);
11048
+ const imageRefs = [...text5.matchAll(IMAGE_RE)].map((match) => match[1]);
11049
+ if (imageRefs.length === 0) errors.push(`${reportPath}: missing embedded screenshot image`);
11050
+ const screenshotsDir = path9.join(runDir, "screenshots");
11051
+ if (!await exists2(screenshotsDir)) errors.push(`${runDir}: missing screenshots directory`);
11052
+ for (const imageRef of imageRefs) {
11053
+ if (imageRef.includes("://")) {
11054
+ errors.push(`${reportPath}: screenshot must be a local file under this run's screenshots directory`);
11055
+ continue;
11056
+ }
11057
+ const imagePath = path9.resolve(path9.dirname(reportPath), imageRef);
11058
+ const screenshotsResolved = path9.resolve(screenshotsDir);
11059
+ if (!imagePath.startsWith(`${screenshotsResolved}${path9.sep}`)) {
11060
+ errors.push(`${reportPath}: image reference must stay under this run's screenshots directory: ${imageRef}`);
11061
+ continue;
11062
+ }
11063
+ if (!await exists2(imagePath)) errors.push(`${reportPath}: missing image file: ${imageRef}`);
11064
+ }
11065
+ }
11066
+ }
11067
+ return errors;
11068
+ }
11069
+ async function validateCopyDiffArtifacts(scenarioDir) {
11070
+ const diffDir = path9.join(scenarioDir, COPY_DIFF_DIR);
11071
+ if (!await exists2(diffDir)) return;
11072
+ const manifestPath = path9.join(diffDir, "last.json");
11073
+ const diffPath = path9.join(diffDir, "last.diff");
11074
+ if (!await exists2(manifestPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.json is required when copy diff artifacts exist`);
11075
+ if (!await exists2(diffPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.diff is required when copy diff artifacts exist`);
11076
+ let manifest;
11077
+ try {
11078
+ manifest = JSON.parse(await readText(manifestPath));
11079
+ } catch (error) {
11080
+ fail(`${manifestPath}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
11081
+ }
11082
+ for (const key of ["operation", "scenario_id", "source", "destination", "generated_at", "summary", "diff_file", "files"]) {
11083
+ if (!(key in manifest)) fail(`${manifestPath}: missing \`${key}\``);
11084
+ }
11085
+ if (manifest.scenario_id !== path9.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
11086
+ if (manifest.diff_file !== "last.diff") fail(`${manifestPath}: diff_file must be last.diff`);
11087
+ if (!(await readText(diffPath)).trim()) fail(`${diffPath}: copy diff must not be empty`);
11088
+ }
11089
+
11090
+ // src/commands/test-suite.ts
11091
+ function registerTestSuiteCommands(program2) {
11092
+ const suite = program2.command("test-suite").description("Manage local BPMAX AI test case suites under .ai_test");
11093
+ suite.command("lint").description("Lint BPMAX AI test case suite scenarios").option("--root <path>", "Suite root directory", DEFAULT_SUITE_ROOT).requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
11094
+ await requireLatestProof(options.latestProof);
11095
+ const scenarios = await lintSuite(options.root);
11096
+ printResult(options.format, { ok: true, scenario_count: scenarios.length });
11097
+ });
11098
+ suite.command("index").description("Print the BPMAX AI test case suite index").option("--root <path>", "Suite root directory", DEFAULT_SUITE_ROOT).option("--include-inactive", "Include draft and deprecated scenarios").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
11099
+ await requireLatestProof(options.latestProof);
11100
+ printResult(options.format, await indexSuite(options.root, Boolean(options.includeInactive)));
11101
+ });
11102
+ suite.command("draft-update").description("Copy one formal suite scenario to the draft suite for editing").requiredOption("--scenario <id>", "Scenario id").option("--suite-root <path>", "Formal suite root directory", DEFAULT_SUITE_ROOT).option("--draft-root <path>", "Draft suite root directory", DEFAULT_DRAFT_ROOT).option("--replace", "Allow replacing an existing draft scenario").option("--diff-reviewed", "Confirm the copy diff preview was reviewed").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
11103
+ await requireLatestProof(options.latestProof);
11104
+ printResult(options.format, await draftUpdate(options));
11105
+ });
11106
+ suite.command("promote").description("Promote one reviewed draft scenario to the formal suite").requiredOption("--scenario <id>", "Scenario id").option("--draft-root <path>", "Draft suite root directory", DEFAULT_DRAFT_ROOT).option("--suite-root <path>", "Formal suite root directory", DEFAULT_SUITE_ROOT).option("--replace", "Allow replacing an existing formal scenario").option("--diff-reviewed", "Confirm the copy diff preview was reviewed").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
11107
+ await requireLatestProof(options.latestProof);
11108
+ printResult(options.format, await promoteScenario(options));
11109
+ });
11110
+ suite.command("next-report-dir").description("Print or create the next BPMAX E2E test report run directory").option("--root <path>", "Report root directory", DEFAULT_REPORT_ROOT).option("--create", "Create the report directory, screenshots directory, and summary.md").option("--format <format>", "Output format", "json").action(async (options) => {
11111
+ const reportDir = await nextReportDir(options.root, Boolean(options.create));
11112
+ printResult(options.format, { path: reportDir });
11113
+ });
11114
+ suite.command("lint-report").description("Lint BPMAX E2E test report artifacts").option("--root <path>", "Report root directory", DEFAULT_REPORT_ROOT).option("--format <format>", "Output format", "json").action(async (options) => {
11115
+ const errors = await lintReport(options.root);
11116
+ if (errors.length > 0) {
11117
+ throw new Error(errors.join("\n"));
11118
+ }
11119
+ printResult(options.format, { ok: true });
11120
+ });
11121
+ }
11122
+
11123
+ // src/core/update.ts
11124
+ import { access as access2, mkdir as mkdir10, readFile as readFile12, realpath, writeFile as writeFile10 } from "fs/promises";
11125
+ import path10 from "path";
9770
11126
  var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org/";
9771
11127
  var UPDATE_STATE_FILE = "update-state.json";
9772
11128
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -9878,11 +11234,11 @@ async function fetchLatestVersion(options = {}) {
9878
11234
  }
9879
11235
  }
9880
11236
  function updateStatePath(configDir = getConfigDir()) {
9881
- return path8.join(configDir, UPDATE_STATE_FILE);
11237
+ return path10.join(configDir, UPDATE_STATE_FILE);
9882
11238
  }
9883
11239
  async function readUpdateState(configDir) {
9884
11240
  try {
9885
- const raw = await readFile10(updateStatePath(configDir), "utf8");
11241
+ const raw = await readFile12(updateStatePath(configDir), "utf8");
9886
11242
  const parsed = JSON.parse(raw);
9887
11243
  if (typeof parsed.latest_version !== "string" || typeof parsed.checked_at !== "number") {
9888
11244
  return null;
@@ -9893,8 +11249,8 @@ async function readUpdateState(configDir) {
9893
11249
  }
9894
11250
  }
9895
11251
  async function writeUpdateState(state, configDir = getConfigDir()) {
9896
- await mkdir8(configDir, { recursive: true });
9897
- await writeFile8(updateStatePath(configDir), JSON.stringify(state), "utf8");
11252
+ await mkdir10(configDir, { recursive: true });
11253
+ await writeFile10(updateStatePath(configDir), JSON.stringify(state), "utf8");
9898
11254
  }
9899
11255
  async function checkCachedUpdate(currentVersion, configDir = getConfigDir()) {
9900
11256
  if (process.env.BPMAX_CLI_NO_UPDATE_NOTIFIER) {
@@ -9946,7 +11302,7 @@ async function findNpmPath() {
9946
11302
  }
9947
11303
  function detectInstallMethod(input) {
9948
11304
  const resolvedPath = input.executablePath || "";
9949
- const method = resolvedPath.includes(`node_modules${path8.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
11305
+ const method = resolvedPath.includes(`node_modules${path10.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
9950
11306
  return {
9951
11307
  method,
9952
11308
  resolvedPath,
@@ -10311,6 +11667,8 @@ registerFlowCommands(program);
10311
11667
  registerMemoryCommands(program);
10312
11668
  registerProjectCommands(program);
10313
11669
  registerStepCommands(program);
11670
+ registerTaskbookCommands(program);
11671
+ registerTestSuiteCommands(program);
10314
11672
  registerRecipeCommands(program);
10315
11673
  registerUrlCommands(program);
10316
11674
  registerSetupCommand(program);