bpmax-cli 0.2.1-beta.58 → 0.2.1-beta.59

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
@@ -233,8 +233,8 @@ function throwCliGovernanceUnsupportedIfNeeded(error, fallbackPath) {
233
233
  }
234
234
  throw error;
235
235
  }
236
- function normalizePath(path25) {
237
- let normalized = path25.split("?")[0] || "/";
236
+ function normalizePath(path27) {
237
+ let normalized = path27.split("?")[0] || "/";
238
238
  if (!normalized.startsWith("/")) {
239
239
  normalized = `/${normalized}`;
240
240
  }
@@ -244,17 +244,17 @@ function normalizePath(path25) {
244
244
  }
245
245
  return normalized.replace(/\/+$/g, "") || "/api";
246
246
  }
247
- function getNumber(value, path25) {
248
- const result = getValue(value, path25);
247
+ function getNumber(value, path27) {
248
+ const result = getValue(value, path27);
249
249
  return typeof result === "number" ? result : void 0;
250
250
  }
251
- function getString(value, path25) {
252
- const result = getValue(value, path25);
251
+ function getString(value, path27) {
252
+ const result = getValue(value, path27);
253
253
  return typeof result === "string" ? result : void 0;
254
254
  }
255
- function getValue(value, path25) {
255
+ function getValue(value, path27) {
256
256
  let current = value;
257
- for (const key of path25) {
257
+ for (const key of path27) {
258
258
  if (!current || typeof current !== "object" || !(key in current)) {
259
259
  return void 0;
260
260
  }
@@ -264,10 +264,10 @@ function getValue(value, path25) {
264
264
  }
265
265
 
266
266
  // src/core/capabilities.ts
267
- function capabilityForRequest(method, path25) {
267
+ function capabilityForRequest(method, path27) {
268
268
  const normalizedMethod = method.toUpperCase();
269
- const normalizedPath = normalizePath2(path25);
270
- const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path25);
269
+ const normalizedPath = normalizePath2(path27);
270
+ const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path27);
271
271
  if (normalizedPath === "/cli/capabilities") {
272
272
  return void 0;
273
273
  }
@@ -285,6 +285,8 @@ function capabilityForRequest(method, path25) {
285
285
  if (normalizedMethod === "GET" && /^\/cli\/plugins\/[^/]+$/.test(normalizedPath)) return "plugin.skills.show";
286
286
  if (normalizedMethod === "GET" && /^\/cli\/plugins\/[^/]+\/skills$/.test(normalizedPath)) return "plugin.skills.list";
287
287
  if (normalizedMethod === "GET" && /^\/cli\/plugins\/[^/]+\/skills\/[^/]+\/download$/.test(normalizedPath)) return "config.plugin.skill.download";
288
+ if (normalizedMethod === "GET" && normalizedPath === "/plugin/activation_overview") return "config.plugin.activation.export";
289
+ if (normalizedMethod === "PUT" && normalizedPath === "/plugin/activation") return "config.plugin.activation.submit";
288
290
  const pluginAgentCapability = pluginAgentCapabilityForRequest(normalizedMethod, normalizedPath);
289
291
  if (pluginAgentCapability) return pluginAgentCapability;
290
292
  if (normalizedMethod === "GET" && normalizedPath === "/user/current") return "user.current";
@@ -447,8 +449,8 @@ async function updateProfileCapabilities(profileName, cache) {
447
449
  };
448
450
  await saveConfig(config);
449
451
  }
450
- function flowPageTemplateCapabilityPrefix(path25) {
451
- const query = path25.includes("?") ? path25.slice(path25.indexOf("?") + 1) : "";
452
+ function flowPageTemplateCapabilityPrefix(path27) {
453
+ const query = path27.includes("?") ? path27.slice(path27.indexOf("?") + 1) : "";
452
454
  const type = new URLSearchParams(query).get("type");
453
455
  if (type === "2") {
454
456
  return "config.project_detail_template";
@@ -467,8 +469,8 @@ function flowPageTemplateCapabilityPrefix(path25) {
467
469
  }
468
470
  return "config.list_template";
469
471
  }
470
- function normalizePath2(path25) {
471
- let normalized = path25.split("?")[0] || "/";
472
+ function normalizePath2(path27) {
473
+ let normalized = path27.split("?")[0] || "/";
472
474
  if (!normalized.startsWith("/")) {
473
475
  normalized = `/${normalized}`;
474
476
  }
@@ -499,7 +501,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
499
501
  // package.json
500
502
  var package_default = {
501
503
  name: "bpmax-cli",
502
- version: "0.2.1-beta.58",
504
+ version: "0.2.1-beta.59",
503
505
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
504
506
  type: "module",
505
507
  bin: {
@@ -551,8 +553,8 @@ var NPM_PACKAGE = "bpmax-cli";
551
553
  // src/core/terminal.ts
552
554
  import { randomUUID } from "crypto";
553
555
  import os from "os";
554
- function isCliControlPath(path25) {
555
- const normalized = normalizeApiPath(path25);
556
+ function isCliControlPath(path27) {
557
+ const normalized = normalizeApiPath(path27);
556
558
  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";
557
559
  }
558
560
  function commandSummary(argv = process.argv) {
@@ -716,8 +718,8 @@ async function updateProfileTerminal(profile, terminalId, status) {
716
718
  profile.config.terminal_status = status;
717
719
  profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
718
720
  }
719
- function normalizeApiPath(path25) {
720
- let normalized = path25.split("?")[0] || "/";
721
+ function normalizeApiPath(path27) {
722
+ let normalized = path27.split("?")[0] || "/";
721
723
  if (!normalized.startsWith("/")) {
722
724
  normalized = `/${normalized}`;
723
725
  }
@@ -771,6 +773,10 @@ function emitTextNotice() {
771
773
  function printResult(format, value) {
772
774
  resultRecorder?.(value);
773
775
  switch (format) {
776
+ case "summary":
777
+ console.log(JSON.stringify(summarizeResult(value), null, 2));
778
+ emitTextNotice();
779
+ return;
774
780
  case "json":
775
781
  console.log(JSON.stringify(withJsonNotice(value), null, 2));
776
782
  if (!isRecord(value)) {
@@ -807,6 +813,74 @@ function printResult(format, value) {
807
813
  console.log(JSON.stringify(value, null, 2));
808
814
  }
809
815
  }
816
+ var LARGE_RESULT_KEYS = /* @__PURE__ */ new Set(["content", "raw", "payload", "response", "detail", "html", "body"]);
817
+ var SUMMARY_KEYS = /* @__PURE__ */ new Set([
818
+ "ok",
819
+ "action",
820
+ "domain",
821
+ "id",
822
+ "status",
823
+ "env",
824
+ "profile",
825
+ "name",
826
+ "current",
827
+ "origin",
828
+ "language",
829
+ "workspace",
830
+ "workspace_dir",
831
+ "config_dir",
832
+ "cloned",
833
+ "profile_saved",
834
+ "git_branch",
835
+ "agents_file",
836
+ "path",
837
+ "updated",
838
+ "dry_run",
839
+ "changed_paths",
840
+ "mismatch_count",
841
+ "remote_write_state",
842
+ "remote_submitted",
843
+ "readback_confirmed",
844
+ "readback_error",
845
+ "next",
846
+ "next_commands",
847
+ "receipt",
848
+ "content_file",
849
+ "skills",
850
+ "capabilities_probe",
851
+ "authorization",
852
+ "profile_isolated",
853
+ "context_isolated",
854
+ "count",
855
+ "content_bytes",
856
+ "content_sha256",
857
+ "error",
858
+ "code",
859
+ "rule_id",
860
+ "suggestion",
861
+ "truncated"
862
+ ]);
863
+ function summarizeValue(value, key) {
864
+ if (key && LARGE_RESULT_KEYS.has(key)) {
865
+ if (typeof value === "string") return { omitted: true, chars: value.length };
866
+ if (Array.isArray(value)) return { omitted: true, items: value.length };
867
+ return { omitted: true };
868
+ }
869
+ if (Array.isArray(value)) return value.length > 20 ? { omitted: true, items: value.length } : value.map((item) => summarizeValue(item));
870
+ if (isRecord(value)) {
871
+ const result = {};
872
+ for (const [entryKey, entryValue] of Object.entries(value)) {
873
+ if (SUMMARY_KEYS.has(entryKey) || entryKey === "_notice") {
874
+ result[entryKey] = summarizeValue(entryValue, entryKey);
875
+ }
876
+ }
877
+ return result;
878
+ }
879
+ return value;
880
+ }
881
+ function summarizeResult(value) {
882
+ return summarizeValue(value);
883
+ }
810
884
 
811
885
  // src/core/http.ts
812
886
  var clientProfiles = /* @__PURE__ */ new WeakMap();
@@ -840,14 +914,14 @@ function recordCommandAuditResult(value) {
840
914
  state.result_summary = redactAuditValue(value);
841
915
  }
842
916
  }
843
- var ensureApiPath = (path25) => {
844
- if (!path25.startsWith("/")) {
845
- path25 = `/${path25}`;
917
+ var ensureApiPath = (path27) => {
918
+ if (!path27.startsWith("/")) {
919
+ path27 = `/${path27}`;
846
920
  }
847
- if (path25.startsWith("/api/")) {
848
- return path25;
921
+ if (path27.startsWith("/api/")) {
922
+ return path27;
849
923
  }
850
- return `/api${path25}`;
924
+ return `/api${path27}`;
851
925
  };
852
926
  function normalizeWorkspaceForApi(workspace) {
853
927
  const normalized = workspace?.trim();
@@ -893,10 +967,10 @@ function createApiClient(profile) {
893
967
  });
894
968
  return instance;
895
969
  }
896
- async function apiRequest(client, method, path25, options = {}) {
970
+ async function apiRequest(client, method, path27, options = {}) {
897
971
  const profile = clientProfiles.get(client);
898
- const apiPath2 = ensureApiPath(path25);
899
- const capability = options.capability ?? capabilityForRequest(method, path25);
972
+ const apiPath2 = ensureApiPath(path27);
973
+ const capability = options.capability ?? capabilityForRequest(method, path27);
900
974
  const shouldControl = Boolean(profile?.config.api_key) && !isCliControlPath(apiPath2);
901
975
  const reqId = requestId();
902
976
  if (profile) {
@@ -1223,8 +1297,8 @@ async function parseJsonAny(input, label = "JSON input") {
1223
1297
  function isMutatingMethod(method) {
1224
1298
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
1225
1299
  }
1226
- function normalizeApiPath2(path25) {
1227
- let normalized = path25.trim();
1300
+ function normalizeApiPath2(path27) {
1301
+ let normalized = path27.trim();
1228
1302
  const queryIndex = normalized.indexOf("?");
1229
1303
  if (queryIndex >= 0) {
1230
1304
  normalized = normalized.slice(0, queryIndex);
@@ -1241,9 +1315,9 @@ function normalizeApiPath2(path25) {
1241
1315
  }
1242
1316
  return normalized;
1243
1317
  }
1244
- function pluginAgentCapabilityForRawApi(method, path25) {
1318
+ function pluginAgentCapabilityForRawApi(method, path27) {
1245
1319
  const normalizedMethod = method.toUpperCase();
1246
- const normalizedPath = normalizeApiPath2(path25);
1320
+ const normalizedPath = normalizeApiPath2(path27);
1247
1321
  const match = normalizedPath.match(/^\/(plugin_[A-Za-z0-9_]+)\/agents(?:\/|$)/);
1248
1322
  if (!match) {
1249
1323
  return void 0;
@@ -1257,19 +1331,19 @@ function pluginAgentCapabilityForRawApi(method, path25) {
1257
1331
  }
1258
1332
  return void 0;
1259
1333
  }
1260
- function parseQuery(path25) {
1261
- const queryIndex = path25.indexOf("?");
1262
- return new URLSearchParams(queryIndex >= 0 ? path25.slice(queryIndex + 1) : "");
1334
+ function parseQuery(path27) {
1335
+ const queryIndex = path27.indexOf("?");
1336
+ return new URLSearchParams(queryIndex >= 0 ? path27.slice(queryIndex + 1) : "");
1263
1337
  }
1264
- function isRawConfigPath(method, path25) {
1265
- const normalizedPath = normalizeApiPath2(path25);
1338
+ function isRawConfigPath(method, path27) {
1339
+ const normalizedPath = normalizeApiPath2(path27);
1266
1340
  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)) {
1267
1341
  return true;
1268
1342
  }
1269
1343
  if (normalizedPath === "/flow/list/lightweight" || normalizedPath.startsWith("/flow/configuration/")) {
1270
1344
  return true;
1271
1345
  }
1272
- if (normalizedPath === "/flow" && method === "GET" && parseQuery(path25).has("draft")) {
1346
+ if (normalizedPath === "/flow" && method === "GET" && parseQuery(path27).has("draft")) {
1273
1347
  return true;
1274
1348
  }
1275
1349
  if (normalizedPath.startsWith("/flow/") && !["/flow/flow_type", "/flow/options", "/flow/batch_get"].includes(normalizedPath)) {
@@ -1280,35 +1354,35 @@ function isRawConfigPath(method, path25) {
1280
1354
  }
1281
1355
  return false;
1282
1356
  }
1283
- function assertRawApiPathAllowed(method, path25) {
1284
- if (isRawConfigPath(method, path25)) {
1357
+ function assertRawApiPathAllowed(method, path27) {
1358
+ if (isRawConfigPath(method, path27)) {
1285
1359
  throw new Error(
1286
- `Raw API ${method} ${path25} 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.`
1360
+ `Raw API ${method} ${path27} 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.`
1287
1361
  );
1288
1362
  }
1289
1363
  if (!isMutatingMethod(method)) {
1290
1364
  return;
1291
1365
  }
1292
- const normalizedPath = normalizeApiPath2(path25);
1366
+ const normalizedPath = normalizeApiPath2(path27);
1293
1367
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
1294
1368
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
1295
1369
  if (!isProjectPath || isAllowedProjectReadPost) {
1296
1370
  return;
1297
1371
  }
1298
1372
  throw new Error(
1299
- `Raw API ${method} ${path25} 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.`
1373
+ `Raw API ${method} ${path27} 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.`
1300
1374
  );
1301
1375
  }
1302
1376
  function registerApiCommands(program2) {
1303
- 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, path25, options) => {
1377
+ 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, path27, options) => {
1304
1378
  const normalizedMethod = method.toUpperCase();
1305
- assertRawApiPathAllowed(normalizedMethod, path25);
1379
+ assertRawApiPathAllowed(normalizedMethod, path27);
1306
1380
  if (isMutatingMethod(normalizedMethod) && options.confirmMutating !== true) {
1307
1381
  printResult(options.format, {
1308
1382
  ok: false,
1309
1383
  dry_run: true,
1310
1384
  method: normalizedMethod,
1311
- path: path25,
1385
+ path: path27,
1312
1386
  warning: "Mutating raw API calls require --confirm-mutating. Prefer typed bpmax-cli commands such as step submit."
1313
1387
  });
1314
1388
  return;
@@ -1316,8 +1390,8 @@ function registerApiCommands(program2) {
1316
1390
  const config = await loadConfig();
1317
1391
  const profile = resolveProfile(config, options.profile);
1318
1392
  const client = createApiClient(profile);
1319
- const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path25) || "api.raw";
1320
- const result = await apiRequest(client, normalizedMethod, path25, {
1393
+ const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path27) || "api.raw";
1394
+ const result = await apiRequest(client, normalizedMethod, path27, {
1321
1395
  params: options.params ? await parseJsonInput(options.params, "--params") : void 0,
1322
1396
  data: await parseJsonAny(options.data, "--data"),
1323
1397
  capability
@@ -1344,9 +1418,9 @@ function toUserSummary(user) {
1344
1418
  if (!user || typeof user !== "object" || Array.isArray(user)) {
1345
1419
  return void 0;
1346
1420
  }
1347
- const record = user;
1348
- const id = typeof record.id === "number" ? record.id : typeof record.user_id === "number" ? record.user_id : void 0;
1349
- const name = typeof record.name === "string" ? record.name : typeof record.nickname === "string" ? record.nickname : typeof record.realname === "string" ? record.realname : "";
1421
+ const record2 = user;
1422
+ const id = typeof record2.id === "number" ? record2.id : typeof record2.user_id === "number" ? record2.user_id : void 0;
1423
+ const name = typeof record2.name === "string" ? record2.name : typeof record2.nickname === "string" ? record2.nickname : typeof record2.realname === "string" ? record2.realname : "";
1350
1424
  if (id === void 0) {
1351
1425
  return void 0;
1352
1426
  }
@@ -1416,18 +1490,18 @@ function normalizeDeviceAuthorizationUrl(urlValue, workspace) {
1416
1490
  }
1417
1491
  return url.toString();
1418
1492
  }
1419
- function apiPath(path25) {
1420
- if (path25.startsWith("/api/")) {
1421
- return path25;
1493
+ function apiPath(path27) {
1494
+ if (path27.startsWith("/api/")) {
1495
+ return path27;
1422
1496
  }
1423
- return `/api${path25.startsWith("/") ? path25 : `/${path25}`}`;
1497
+ return `/api${path27.startsWith("/") ? path27 : `/${path27}`}`;
1424
1498
  }
1425
1499
  function createDeviceRequest(origin) {
1426
1500
  const client = axios2.create({ baseURL: origin, withCredentials: false });
1427
- return async (method, path25, options) => {
1501
+ return async (method, path27, options) => {
1428
1502
  const response = await client.request({
1429
1503
  method,
1430
- url: apiPath(path25),
1504
+ url: apiPath(path27),
1431
1505
  data: options.data
1432
1506
  });
1433
1507
  const body = response.data;
@@ -2294,8 +2368,19 @@ async function resolvePackageRootFrom(entrypointPath) {
2294
2368
  }
2295
2369
  return path3.resolve(entryDir, "..", "..");
2296
2370
  }
2371
+ async function resolveRuntimePackageRoot(entrypointPath = process.argv[1], modulePath = fileURLToPath(import.meta.url)) {
2372
+ if (entrypointPath) {
2373
+ const entryDir = path3.dirname(path3.resolve(entrypointPath));
2374
+ const entryName = path3.basename(entrypointPath);
2375
+ const parentName = path3.basename(entryDir);
2376
+ if (entryName === "bin.js" && parentName === "dist" || entryName === "bin.ts" && parentName === "src") {
2377
+ return resolvePackageRootFrom(path3.resolve(entrypointPath));
2378
+ }
2379
+ }
2380
+ return resolvePackageRootFrom(modulePath);
2381
+ }
2297
2382
  async function defaultPackageRoot() {
2298
- return resolvePackageRootFrom(fileURLToPath(import.meta.url));
2383
+ return resolveRuntimePackageRoot();
2299
2384
  }
2300
2385
  async function runSkillsInstall(options = {}) {
2301
2386
  const runner = options.runner || runCommand;
@@ -3979,20 +4064,20 @@ function requireNumericId(value, name) {
3979
4064
  }
3980
4065
  return nextValue;
3981
4066
  }
3982
- function withQuery(path25, query) {
4067
+ function withQuery(path27, query) {
3983
4068
  const params = new URLSearchParams();
3984
4069
  for (const [key, value] of Object.entries(query)) {
3985
4070
  if (value !== void 0) {
3986
4071
  params.set(key, value);
3987
4072
  }
3988
4073
  }
3989
- return `${path25}?${params.toString()}`;
4074
+ return `${path27}?${params.toString()}`;
3990
4075
  }
3991
4076
  function buildBpmaxUrl(profile, kind, params = {}) {
3992
4077
  const origin = normalizeOrigin2(profile.config.origin);
3993
4078
  const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
3994
4079
  const basePath = `/${workspace}`;
3995
- let path25 = basePath;
4080
+ let path27 = basePath;
3996
4081
  const result = {
3997
4082
  kind,
3998
4083
  profile: profile.name,
@@ -4000,15 +4085,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
4000
4085
  workspace
4001
4086
  };
4002
4087
  if (kind === "project-list") {
4003
- path25 = `${basePath}/project`;
4088
+ path27 = `${basePath}/project`;
4004
4089
  } else if (kind === "project-detail") {
4005
4090
  const projectId = requireNumericId(params.projectId, "projectId");
4006
- path25 = `${basePath}/project_detail/0/${projectId}`;
4091
+ path27 = `${basePath}/project_detail/0/${projectId}`;
4007
4092
  result.project_id = projectId;
4008
4093
  } else if (kind === "project-step") {
4009
4094
  const projectId = requireNumericId(params.projectId, "projectId");
4010
4095
  const stepId = requireNumericId(params.stepId, "stepId");
4011
- path25 = withQuery(`${basePath}/projectContinue`, {
4096
+ path27 = withQuery(`${basePath}/projectContinue`, {
4012
4097
  id: projectId,
4013
4098
  step_id: stepId,
4014
4099
  prefill_token: params.prefillToken
@@ -4026,15 +4111,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
4026
4111
  ...flowKey ? { key: flowKey } : {},
4027
4112
  ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
4028
4113
  };
4029
- path25 = withQuery(`${basePath}/project/create`, query);
4114
+ path27 = withQuery(`${basePath}/project/create`, query);
4030
4115
  result.flow_type = flowType;
4031
4116
  result.flow_key = flowKey;
4032
4117
  result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
4033
4118
  }
4034
- const url = `${origin}${path25}`;
4119
+ const url = `${origin}${path27}`;
4035
4120
  return {
4036
4121
  ...result,
4037
- path: path25,
4122
+ path: path27,
4038
4123
  url,
4039
4124
  ...kind === "project-create" ? { pc_url: url } : {}
4040
4125
  };
@@ -4415,17 +4500,17 @@ function containsOuterReturn(value, root = true) {
4415
4500
  return containsOuterReturn(child, false);
4416
4501
  });
4417
4502
  }
4418
- function validateExpression(expression, path25, errors) {
4503
+ function validateExpression(expression, path27, errors) {
4419
4504
  try {
4420
4505
  const program2 = parse(`async function __bpmaxReport(ctx) {
4421
4506
  ${expression}
4422
4507
  }`, { ecmaVersion: "latest" });
4423
4508
  const reportFunction = program2.body[0];
4424
4509
  if (!containsOuterReturn(reportFunction)) {
4425
- errors.push(`${path25} \u662F\u5E73\u53F0\u5F02\u6B65\u51FD\u6570\u4F53\uFF0C\u5FC5\u987B\u663E\u5F0F return\uFF0C\u4E14 return \u5FC5\u987B\u4F4D\u4E8E\u5916\u5C42\u51FD\u6570\u4E2D\uFF1B\u5426\u5219\u62A5\u544A\u5B57\u6BB5\u4F1A\u751F\u6210\u7A7A\u503C\u3002`);
4510
+ errors.push(`${path27} \u662F\u5E73\u53F0\u5F02\u6B65\u51FD\u6570\u4F53\uFF0C\u5FC5\u987B\u663E\u5F0F return\uFF0C\u4E14 return \u5FC5\u987B\u4F4D\u4E8E\u5916\u5C42\u51FD\u6570\u4E2D\uFF1B\u5426\u5219\u62A5\u544A\u5B57\u6BB5\u4F1A\u751F\u6210\u7A7A\u503C\u3002`);
4426
4511
  }
4427
4512
  } catch (error) {
4428
- errors.push(`${path25} \u4E0D\u662F\u5408\u6CD5\u7684 JavaScript \u5F02\u6B65\u51FD\u6570\u4F53\uFF1A${error instanceof Error ? error.message : String(error)}\u3002`);
4513
+ errors.push(`${path27} \u4E0D\u662F\u5408\u6CD5\u7684 JavaScript \u5F02\u6B65\u51FD\u6570\u4F53\uFF1A${error instanceof Error ? error.message : String(error)}\u3002`);
4429
4514
  }
4430
4515
  }
4431
4516
  function analyzeFlowReportTemplate(value, options = {}) {
@@ -5220,9 +5305,9 @@ function summarizeOperationPlan(payload) {
5220
5305
  return "submit operation";
5221
5306
  }
5222
5307
  const method = typeof operation.method === "string" ? operation.method : "REQUEST";
5223
- const path25 = typeof operation.path === "string" ? operation.path : "";
5308
+ const path27 = typeof operation.path === "string" ? operation.path : "";
5224
5309
  const type = typeof operation.type === "string" ? ` ${operation.type}` : "";
5225
- return `submit${type}: ${method}${path25 ? ` ${path25}` : ""}`;
5310
+ return `submit${type}: ${method}${path27 ? ` ${path27}` : ""}`;
5226
5311
  }),
5227
5312
  ...skipped.slice(0, Math.max(0, 20 - operations.length)).map((operation) => {
5228
5313
  if (!isRecord4(operation)) {
@@ -5585,14 +5670,14 @@ function analyzeDatasetMapping(value) {
5585
5670
  walkAst(root, (node) => {
5586
5671
  if (node.type === "AssignmentExpression" || node.type === "UpdateExpression") {
5587
5672
  const target = node.type === "AssignmentExpression" ? node.left : node.argument;
5588
- const path25 = astMemberPath(target);
5589
- if (path25?.length) mutableBindings.add(String(path25[0]));
5673
+ const path27 = astMemberPath(target);
5674
+ if (path27?.length) mutableBindings.add(String(path27[0]));
5590
5675
  else if (target.type === "Identifier") mutableBindings.add(String(target.name));
5591
5676
  return;
5592
5677
  }
5593
5678
  if (node.type === "UnaryExpression" && node.operator === "delete") {
5594
- const path25 = astMemberPath(node.argument);
5595
- if (path25?.length) mutableBindings.add(String(path25[0]));
5679
+ const path27 = astMemberPath(node.argument);
5680
+ if (path27?.length) mutableBindings.add(String(path27[0]));
5596
5681
  return;
5597
5682
  }
5598
5683
  if (node.type !== "CallExpression") return;
@@ -5652,13 +5737,13 @@ function analyzeDatasetMapping(value) {
5652
5737
  });
5653
5738
  walkAst(root, (node) => {
5654
5739
  if (node.type === "UnaryExpression" && node.operator === "delete") {
5655
- const path25 = astMemberPath(node.argument);
5656
- if (path25?.[0] !== "ctx" || path25[1] !== "mapping") return;
5657
- if (path25.length === 2 || path25.length === 3 && path25[2] === "properties") {
5740
+ const path27 = astMemberPath(node.argument);
5741
+ if (path27?.[0] !== "ctx" || path27[1] !== "mapping") return;
5742
+ if (path27.length === 2 || path27.length === 3 && path27[2] === "properties") {
5658
5743
  errors.push("[dataset.mapping.destructive_delete] post_es_mapping must not delete ctx.mapping or ctx.mapping.properties.");
5659
- } else if (path25.length === 4 && path25[2] === "properties" && typeof path25[3] === "string") {
5660
- if (DATASET_PLATFORM_RESERVED_MAPPING_TYPES.has(path25[3])) {
5661
- errors.push(`[dataset.mapping.reserved_field.deleted] reserved mapping field ${path25[3]} must not be deleted.`);
5744
+ } else if (path27.length === 4 && path27[2] === "properties" && typeof path27[3] === "string") {
5745
+ if (DATASET_PLATFORM_RESERVED_MAPPING_TYPES.has(path27[3])) {
5746
+ errors.push(`[dataset.mapping.reserved_field.deleted] reserved mapping field ${path27[3]} must not be deleted.`);
5662
5747
  } else {
5663
5748
  analyzable = false;
5664
5749
  }
@@ -7605,11 +7690,11 @@ function flowCategoryRecords(value) {
7605
7690
  }
7606
7691
  return [];
7607
7692
  }
7608
- function usableFlowCategory(record) {
7609
- const type = String(record.type ?? "flow").trim();
7610
- const deleted = record.is_del === 1 || record.is_del === "1" || record.deleted === true;
7611
- const disabled = record.enabled === false || record.status === 0 || record.status === "0";
7612
- return type === "flow" && !deleted && !disabled && typeof record.key === "string" && record.key.trim().length > 0;
7693
+ function usableFlowCategory(record2) {
7694
+ const type = String(record2.type ?? "flow").trim();
7695
+ const deleted = record2.is_del === 1 || record2.is_del === "1" || record2.deleted === true;
7696
+ const disabled = record2.enabled === false || record2.status === 0 || record2.status === "0";
7697
+ return type === "flow" && !deleted && !disabled && typeof record2.key === "string" && record2.key.trim().length > 0;
7613
7698
  }
7614
7699
  async function auditFlowCategoryReference(flowWork, profile) {
7615
7700
  const configuredKey = String(flowWork.category ?? "").trim() || "system";
@@ -7621,7 +7706,7 @@ async function auditFlowCategoryReference(flowWork, profile) {
7621
7706
  { capability: "flow.list" }
7622
7707
  );
7623
7708
  const categories = flowCategoryRecords(response).filter(usableFlowCategory);
7624
- const availableKeys = [...new Set(categories.map((record) => String(record.key).trim()))].sort();
7709
+ const availableKeys = [...new Set(categories.map((record2) => String(record2.key).trim()))].sort();
7625
7710
  if (!availableKeys.length) {
7626
7711
  return {
7627
7712
  errors: ["$.category cannot be validated because the current profile returned no active flow categories."],
@@ -7657,11 +7742,11 @@ function flowCategoryReferenceEvidence(audit) {
7657
7742
  configured_key: audit.configuredKey,
7658
7743
  status: audit.status,
7659
7744
  available_keys: audit.availableKeys,
7660
- categories: audit.categories.map((record) => ({
7661
- id: record.id ?? null,
7662
- key: record.key,
7663
- name: record.name ?? null,
7664
- type: record.type ?? "flow"
7745
+ categories: audit.categories.map((record2) => ({
7746
+ id: record2.id ?? null,
7747
+ key: record2.key,
7748
+ name: record2.name ?? null,
7749
+ type: record2.type ?? "flow"
7665
7750
  }))
7666
7751
  };
7667
7752
  }
@@ -7864,23 +7949,23 @@ function lintConsoleTemplateDataSource(dataSource, moduleLabel, errors) {
7864
7949
  errors.push(`${moduleLabel} \u4E0D\u80FD\u76F4\u63A5\u4F7F\u7528 /bpmax/project/list\u3001/api/project/list \u6216 ESProjectList\uFF1B\u5982\u786E\u9700\u7528\u6237\u8303\u56F4\u67E5\u8BE2\uFF0C\u811A\u672C\u4E2D\u5FC5\u987B\u5199\u660E bpmax-allow-user-scope-project-list: <reason>\u3002`);
7865
7950
  }
7866
7951
  }
7867
- function lintConsoleTemplateWildcardFallback(value, path25, errors) {
7952
+ function lintConsoleTemplateWildcardFallback(value, path27, errors) {
7868
7953
  if (typeof value === "string") {
7869
7954
  const scriptedWildcard = /(?:wildcard|value)\s*:\s*(['\"])(\*{1,2})\1(?=\s*(?:[,};)\]]|$))/i.exec(value);
7870
7955
  if (scriptedWildcard) {
7871
- errors.push(`${path25}.wildcard \u4E0D\u80FD\u7528 ${scriptedWildcard[2]} \u4F5C\u4E3A\u975E\u7A7A\u6216\u515C\u5E95\u7ED3\u679C\uFF1B\u8BF7\u5199\u660E\u786E\u7684\u7A7A\u6001\u3001\u6761\u4EF6\u6216\u805A\u5408\u7ED3\u679C\u3002`);
7956
+ errors.push(`${path27}.wildcard \u4E0D\u80FD\u7528 ${scriptedWildcard[2]} \u4F5C\u4E3A\u975E\u7A7A\u6216\u515C\u5E95\u7ED3\u679C\uFF1B\u8BF7\u5199\u660E\u786E\u7684\u7A7A\u6001\u3001\u6761\u4EF6\u6216\u805A\u5408\u7ED3\u679C\u3002`);
7872
7957
  }
7873
7958
  return;
7874
7959
  }
7875
7960
  if (Array.isArray(value)) {
7876
- value.forEach((item, index) => lintConsoleTemplateWildcardFallback(item, `${path25}[${index}]`, errors));
7961
+ value.forEach((item, index) => lintConsoleTemplateWildcardFallback(item, `${path27}[${index}]`, errors));
7877
7962
  return;
7878
7963
  }
7879
7964
  if (!isRecord4(value)) {
7880
7965
  return;
7881
7966
  }
7882
7967
  Object.entries(value).forEach(([key, item]) => {
7883
- const nextPath = `${path25}.${key}`;
7968
+ const nextPath = `${path27}.${key}`;
7884
7969
  if ((key === "wildcard" || key === "value") && (item === "*" || item === "**")) {
7885
7970
  errors.push(`${nextPath} \u4E0D\u80FD\u7528 ${String(item)} \u4F5C\u4E3A\u975E\u7A7A\u6216\u515C\u5E95\u7ED3\u679C\uFF1B\u8BF7\u5199\u660E\u786E\u7684\u7A7A\u6001\u3001\u6761\u4EF6\u6216\u805A\u5408\u7ED3\u679C\u3002`);
7886
7971
  }
@@ -8433,6 +8518,40 @@ function nodeIcon(node) {
8433
8518
  const inlineIcon = findInlineIconClass(node.children);
8434
8519
  return directIcon || propsIcon || inlineIcon;
8435
8520
  }
8521
+ function isValidListTemplateIconClass(icon) {
8522
+ return /^ri ri_[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/.test(icon.trim());
8523
+ }
8524
+ function validateListTemplateIcons(columns, errors) {
8525
+ const recordColumns = columns.filter(isRecord4);
8526
+ const operationColumns = recordColumns.filter(isListTemplateOperationColumn);
8527
+ const dataColumns = recordColumns.filter((column) => !isListTemplateUtilityColumn(column));
8528
+ let ordinaryIconColumnCount = 0;
8529
+ dataColumns.forEach((column, index) => {
8530
+ const icon = typeof column.icon === "string" ? column.icon.trim() : "";
8531
+ if (!icon) return;
8532
+ ordinaryIconColumnCount += 1;
8533
+ if (!isValidListTemplateIconClass(icon)) {
8534
+ errors.push(`\u5217\u8868\u6A21\u677F\u666E\u901A\u5217\u201C${listTemplateColumnLabel(column, index)}\u201D\u7684 icon \u5FC5\u987B\u662F\u5B8C\u6574 class\uFF0C\u4F8B\u5982 ri ri_bank-line\u3002`);
8535
+ }
8536
+ });
8537
+ if (ordinaryIconColumnCount < 1 || ordinaryIconColumnCount > 3) {
8538
+ errors.push(`\u5217\u8868\u6A21\u677F\u666E\u901A\u6570\u636E\u5217\u5FC5\u987B\u6709 1 \u5230 3 \u5217\u914D\u7F6E icon\uFF1B\u5F53\u524D\u4E3A ${ordinaryIconColumnCount} \u5217\u3002`);
8539
+ }
8540
+ operationColumns.forEach((column) => {
8541
+ if (column.icon !== void 0 || column.iconColor !== void 0) {
8542
+ errors.push("\u5217\u8868\u6A21\u677F\u64CD\u4F5C\u5217\u5217\u6839\u4E0D\u5F97\u914D\u7F6E icon/iconColor\uFF1B\u8BF7\u628A icon \u914D\u7F6E\u5728\u6BCF\u4E2A\u64CD\u4F5C\u6309\u94AE\u4E0A\u3002");
8543
+ }
8544
+ collectListTemplateActionNodes(column.createElement).forEach((item) => {
8545
+ const label = listTemplateNodeLabel(item.node).trim() || "<unnamed>";
8546
+ const icon = nodeIcon(item.node);
8547
+ if (!icon.trim()) {
8548
+ errors.push(`\u5217\u8868\u6A21\u677F\u64CD\u4F5C\u6309\u94AE\u201C${label}\u201D\u5FC5\u987B\u914D\u7F6E\u6309\u94AE\u7EA7 icon\u3002`);
8549
+ } else if (!isValidListTemplateIconClass(icon)) {
8550
+ errors.push(`\u5217\u8868\u6A21\u677F\u64CD\u4F5C\u6309\u94AE\u201C${label}\u201D\u7684 icon \u5FC5\u987B\u662F\u5B8C\u6574 class\uFF0C\u4F8B\u5982 ri ri_eye-line\u3002`);
8551
+ }
8552
+ });
8553
+ });
8554
+ }
8436
8555
  function findInlineIconClass(value) {
8437
8556
  if (Array.isArray(value)) {
8438
8557
  for (const item of value) {
@@ -9009,6 +9128,7 @@ function validateListTemplateActionGate(value, errors, warnings) {
9009
9128
  }
9010
9129
  lintListTemplateQuerySafety(content, nextErrors);
9011
9130
  validateListTemplateColumnWidths(columns, nextErrors);
9131
+ validateListTemplateIcons(columns, nextErrors);
9012
9132
  const operationColumn = columns.filter(isRecord4).find(isListTemplateOperationColumn);
9013
9133
  if (!operationColumn) {
9014
9134
  nextErrors.push("list-template action gate requires an operation column when content.config has columns.");
@@ -9201,15 +9321,18 @@ function flowLiveExportPath(id) {
9201
9321
  function hasUsableFlowTemplateData(value) {
9202
9322
  return isRecord4(value) && isRecord4(value.data) && Object.keys(value.data).length > 0;
9203
9323
  }
9204
- function validateFlowTemplateHardGates(work) {
9324
+ function validateFlowTemplateNonExemptHardGates(work) {
9205
9325
  validateFlowTemplateRemoteTemplateRefs(work);
9206
9326
  validateFlowTemplateExpectedChildFlows(work);
9207
9327
  validateFlowTemplateStandardPageCreateFormTemplate(work);
9208
9328
  validateFlowTemplatePluginRejectionControl(work);
9209
- validateFlowTemplateCodeModeMessages(work);
9210
9329
  validateFlowTemplateRuntimeScripts(work);
9211
9330
  validateFlowTemplateFeishuChatPlugin(work);
9212
9331
  }
9332
+ function validateFlowTemplateHardGates(work) {
9333
+ validateFlowTemplateNonExemptHardGates(work);
9334
+ validateFlowTemplateCodeModeMessages(work);
9335
+ }
9213
9336
  function collectFlowTemplateLintErrors(work) {
9214
9337
  const errors = [];
9215
9338
  validateFlowTemplateStandardFlowType(work, errors);
@@ -9278,7 +9401,7 @@ function subtractUnchangedLintErrors(current, baseline) {
9278
9401
  return { errors: fresh, ignored };
9279
9402
  }
9280
9403
  function evaluateFlowTemplateBaselineLint(work, raw) {
9281
- validateFlowTemplateHardGates(work);
9404
+ validateFlowTemplateNonExemptHardGates(work);
9282
9405
  return subtractUnchangedLintErrors(collectFlowTemplateLintEvidence(work), collectFlowTemplateLintEvidence(raw));
9283
9406
  }
9284
9407
  async function validateFlowTemplateSubmitLintExemption(submit) {
@@ -10179,6 +10302,61 @@ function validateRadioFormTemplateControl(field, rule, value, errors, warnings,
10179
10302
  function subFormFixedFields(props, snakeKey, camelKey) {
10180
10303
  return [props[snakeKey], props[camelKey]].filter(Array.isArray).flatMap((value) => value.filter((item) => typeof item === "string" && item.trim().length > 0));
10181
10304
  }
10305
+ function positiveIntegerId(value) {
10306
+ const id = numericId(value);
10307
+ return id !== void 0 && Number.isInteger(id) && id > 0 ? id : void 0;
10308
+ }
10309
+ function validateSubFormTemplateBinding(field, rule, errors) {
10310
+ if (!rule) {
10311
+ return;
10312
+ }
10313
+ const props = isRecord4(rule.props) ? rule.props : {};
10314
+ const binding = props.form_template;
10315
+ if (binding === void 0 || binding === null) {
10316
+ return;
10317
+ }
10318
+ if (!isRecord4(binding)) {
10319
+ errors.push(
10320
+ `[form.sub_form.template_binding_shape] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u7684 props.form_template \u5FC5\u987B\u662F\u5B8C\u6574\u7684\u6A21\u677F\u7ED1\u5B9A\u5BF9\u8C61\uFF0C\u6216\u5728\u672A\u9009\u62E9\u6A21\u677F\u65F6\u7701\u7565\u3002`
10321
+ );
10322
+ return;
10323
+ }
10324
+ if (Object.keys(binding).length === 0) {
10325
+ return;
10326
+ }
10327
+ const publishedId = positiveIntegerId(binding.id);
10328
+ const originTemplateId = positiveIntegerId(binding.origin_template_id);
10329
+ const uuid = typeof binding.uuid === "string" ? binding.uuid.trim() : "";
10330
+ if (publishedId === void 0) {
10331
+ errors.push(
10332
+ `[form.sub_form.template_published_id_required] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u5DF2\u9009\u62E9\u5B50\u8868\u6A21\u677F\uFF0Cprops.form_template.id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u53D1\u5E03\u6001 ID\u3002`
10333
+ );
10334
+ }
10335
+ if (originTemplateId === void 0) {
10336
+ errors.push(
10337
+ `[form.sub_form.template_origin_id_required] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u5DF2\u9009\u62E9\u5B50\u8868\u6A21\u677F\uFF0Cprops.form_template.origin_template_id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u8349\u7A3F\u6765\u6E90 ID\u3002`
10338
+ );
10339
+ }
10340
+ if (!uuid || !isUuidValue(uuid)) {
10341
+ errors.push(
10342
+ `[form.sub_form.template_uuid_required] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u5DF2\u9009\u62E9\u5B50\u8868\u6A21\u677F\uFF0Cprops.form_template.uuid \u5FC5\u987B\u662F\u6709\u6548 UUID\uFF0C\u4EE5\u4FBF\u6821\u9A8C\u53D1\u5E03\u6001\u4E0E\u8349\u7A3F\u6765\u6E90\u5C5E\u4E8E\u540C\u4E00\u6A21\u677F\u3002`
10343
+ );
10344
+ }
10345
+ if (publishedId !== void 0 && originTemplateId !== void 0 && publishedId === originTemplateId) {
10346
+ errors.push(
10347
+ `[form.sub_form.template_id_conflict] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u7684\u53D1\u5E03\u6001 ID \u4E0E\u8349\u7A3F\u6765\u6E90 ID \u4E0D\u5F97\u76F8\u540C\uFF1B\u8BF7\u91CD\u65B0\u9009\u62E9\u5DF2\u53D1\u5E03\u7684\u5B50\u8868\u6A21\u677F\u3002`
10348
+ );
10349
+ }
10350
+ if (Object.prototype.hasOwnProperty.call(binding, "status")) {
10351
+ const status = binding.status;
10352
+ const publishedStatus = status === 1 || status === "1" || status === true || status === "published" || status === "online";
10353
+ if (!publishedStatus) {
10354
+ errors.push(
10355
+ `[form.sub_form.template_status_published] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u7684 props.form_template.status \u5FC5\u987B\u8868\u793A\u5DF2\u53D1\u5E03\u72B6\u6001\u3002`
10356
+ );
10357
+ }
10358
+ }
10359
+ }
10182
10360
  function validateSubFormAdaptiveColumn(field, rule, errors) {
10183
10361
  if (!rule) {
10184
10362
  return;
@@ -10223,6 +10401,7 @@ function validateFormTemplateControlContracts(payload, errors, warnings, mode) {
10223
10401
  validateRadioFormTemplateControl(field, rule, value, errors, warnings, mode);
10224
10402
  }
10225
10403
  if (type === "sub_form") {
10404
+ validateSubFormTemplateBinding(field, rule, errors);
10226
10405
  validateSubFormAdaptiveColumn(field, rule, errors);
10227
10406
  }
10228
10407
  if (rule?.lambda === "ctx.userInfo?.name || ''") {
@@ -10877,6 +11056,78 @@ function validateFormTemplateSubmitPayload(payload, mode) {
10877
11056
  throw new Error(`form-template lint failed: ${errors.join("; ")}`);
10878
11057
  }
10879
11058
  }
11059
+ function collectSubFormTemplateBindings(payload) {
11060
+ const bindings = /* @__PURE__ */ new Map();
11061
+ for (const entry of collectFormTemplateRuleEntries(payload)) {
11062
+ const props = isRecord4(entry.rule.props) ? entry.rule.props : {};
11063
+ if (entry.rule.type !== "sub_form" && !Object.prototype.hasOwnProperty.call(props, "form_template")) {
11064
+ continue;
11065
+ }
11066
+ const binding = isRecord4(props.form_template) ? props.form_template : void 0;
11067
+ const id = positiveIntegerId(binding?.id);
11068
+ const originTemplateId = positiveIntegerId(binding?.origin_template_id);
11069
+ const uuid = typeof binding?.uuid === "string" ? binding.uuid.trim() : "";
11070
+ if (id === void 0 || originTemplateId === void 0 || !isUuidValue(uuid)) {
11071
+ continue;
11072
+ }
11073
+ const key = `${entry.field}:${id}:${originTemplateId}:${uuid.toLowerCase()}`;
11074
+ bindings.set(key, { field: entry.field, path: entry.path, id, originTemplateId, uuid });
11075
+ }
11076
+ return [...bindings.values()];
11077
+ }
11078
+ async function auditSubFormTemplateReferences(payload, profile) {
11079
+ const bindings = collectSubFormTemplateBindings(payload);
11080
+ if (!bindings.length) {
11081
+ return { errors: [], status: "not_applicable", references: [] };
11082
+ }
11083
+ await ensureConfigCapability(profile, `${CONFIG_DOMAINS["form-template"].capability}.export`);
11084
+ const client = createApiClient(profile);
11085
+ const errors = [];
11086
+ const references = [];
11087
+ const remoteByUuid = /* @__PURE__ */ new Map();
11088
+ for (const binding of bindings) {
11089
+ const uuidKey = binding.uuid.toLowerCase();
11090
+ let remote = remoteByUuid.get(uuidKey);
11091
+ if (remote === void 0) {
11092
+ try {
11093
+ const response = await apiRequest(
11094
+ client,
11095
+ "GET",
11096
+ `/form_template/get_by_uuid?uuid=${encodeURIComponent(binding.uuid)}`,
11097
+ { capability: `${CONFIG_DOMAINS["form-template"].capability}.export` }
11098
+ );
11099
+ const record2 = isRecord4(response) && isRecord4(response.data) ? response.data : response;
11100
+ remote = isRecord4(record2) && Object.keys(record2).length > 0 ? record2 : null;
11101
+ } catch {
11102
+ remote = null;
11103
+ }
11104
+ remoteByUuid.set(uuidKey, remote);
11105
+ }
11106
+ if (!remote) {
11107
+ const message = `[form.sub_form.template_reference_unresolved] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${binding.field} \u7684\u5B50\u8868\u6A21\u677F UUID ${binding.uuid} \u65E0\u6CD5\u901A\u8FC7\u5F53\u524D profile \u56DE\u8BFB\uFF1B\u5F15\u7528\u53EF\u80FD\u5DF2\u5220\u9664\u6216\u4E0D\u53EF\u7528\u3002`;
11108
+ errors.push(message);
11109
+ references.push({ ...binding, status: "unresolved" });
11110
+ continue;
11111
+ }
11112
+ const remoteId = positiveIntegerId(remote.id);
11113
+ const remoteOriginTemplateId = positiveIntegerId(remote.origin_template_id);
11114
+ const remoteUuid = typeof remote.uuid === "string" ? remote.uuid.trim() : "";
11115
+ const matches = remoteId === binding.id && remoteOriginTemplateId === binding.originTemplateId && (!remoteUuid || remoteUuid.toLowerCase() === uuidKey);
11116
+ if (!matches) {
11117
+ errors.push(
11118
+ `[form.sub_form.template_reference_mismatch] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${binding.field} \u7684\u5B50\u8868\u6A21\u677F\u7ED1\u5B9A\u4E0E UUID \u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1B\u5DE5\u4F5C\u6587\u4EF6 id=${binding.id}, origin_template_id=${binding.originTemplateId}, uuid=${binding.uuid}\uFF1B\u5F53\u524D\u53D1\u5E03\u5173\u7CFB id=${String(remote.id ?? "\u7F3A\u5931")}, origin_template_id=${String(remote.origin_template_id ?? "\u7F3A\u5931")}, uuid=${String(remote.uuid ?? "\u7F3A\u5931")}\u3002`
11119
+ );
11120
+ references.push({ ...binding, status: "mismatch", remote_id: remoteId ?? null, remote_origin_template_id: remoteOriginTemplateId ?? null, remote_uuid: remoteUuid || null });
11121
+ continue;
11122
+ }
11123
+ references.push({ ...binding, status: "verified" });
11124
+ }
11125
+ return {
11126
+ errors,
11127
+ status: errors.length ? "invalid" : "verified",
11128
+ references
11129
+ };
11130
+ }
10880
11131
  function stripFormTemplateCreateIds(payload) {
10881
11132
  const next = { ...payload };
10882
11133
  if (Array.isArray(next.rule)) {
@@ -11113,7 +11364,7 @@ function normalizeMemberDetail(member) {
11113
11364
  }
11114
11365
  function flowPermissionKeys(permissions) {
11115
11366
  const result = /* @__PURE__ */ new Set();
11116
- const collect4 = (flowPermissions) => {
11367
+ const collect5 = (flowPermissions) => {
11117
11368
  if (!isRecord4(flowPermissions)) {
11118
11369
  return;
11119
11370
  }
@@ -11125,11 +11376,11 @@ function flowPermissionKeys(permissions) {
11125
11376
  }
11126
11377
  }
11127
11378
  };
11128
- collect4(permissions.flow);
11379
+ collect5(permissions.flow);
11129
11380
  if (isRecord4(permissions.workspace)) {
11130
11381
  for (const workspacePermissions of Object.values(permissions.workspace)) {
11131
11382
  if (isRecord4(workspacePermissions)) {
11132
- collect4(workspacePermissions.flow);
11383
+ collect5(workspacePermissions.flow);
11133
11384
  }
11134
11385
  }
11135
11386
  }
@@ -13371,24 +13622,24 @@ function normalizeTypedReadbackComparable(domain, value) {
13371
13622
  }
13372
13623
  function jsonSubsetMismatches(expected, actual) {
13373
13624
  const mismatches = [];
13374
- const compare = (left, right, path25 = "") => {
13625
+ const compare = (left, right, path27 = "") => {
13375
13626
  if (Array.isArray(left)) {
13376
13627
  if (!Array.isArray(right) || left.length !== right.length) {
13377
- mismatches.push(path25 || "/");
13628
+ mismatches.push(path27 || "/");
13378
13629
  return;
13379
13630
  }
13380
- left.forEach((item, index) => compare(item, right[index], `${path25}/${index}`));
13631
+ left.forEach((item, index) => compare(item, right[index], `${path27}/${index}`));
13381
13632
  return;
13382
13633
  }
13383
13634
  if (isRecord4(left)) {
13384
13635
  if (!isRecord4(right)) {
13385
- mismatches.push(path25 || "/");
13636
+ mismatches.push(path27 || "/");
13386
13637
  return;
13387
13638
  }
13388
- for (const [key, item] of Object.entries(left)) compare(item, right[key], `${path25}/${key}`);
13639
+ for (const [key, item] of Object.entries(left)) compare(item, right[key], `${path27}/${key}`);
13389
13640
  return;
13390
13641
  }
13391
- if (JSON.stringify(left) !== JSON.stringify(right)) mismatches.push(path25 || "/");
13642
+ if (JSON.stringify(left) !== JSON.stringify(right)) mismatches.push(path27 || "/");
13392
13643
  };
13393
13644
  compare(expected, actual);
13394
13645
  return mismatches;
@@ -13473,17 +13724,17 @@ async function listFlowDetailTemplates(profile, options) {
13473
13724
  endpoint,
13474
13725
  { capability: `${definition.capability}.export` }
13475
13726
  );
13476
- const templates = extractListData(response).filter((record) => Number(record.type) === 5).map((record) => ({
13477
- id: record.id ?? null,
13478
- uuid: record.uuid ?? null,
13479
- name: record.name ?? "",
13480
- desc: record.desc ?? "",
13481
- status: record.status ?? null,
13482
- flow_type: record.flow_type ?? "",
13483
- flow_key: record.flow_key ?? "",
13484
- create_time: record.create_time ?? null,
13485
- update_time: record.update_time ?? null,
13486
- readback_hash: hashJson(record)
13727
+ const templates = extractListData(response).filter((record2) => Number(record2.type) === 5).map((record2) => ({
13728
+ id: record2.id ?? null,
13729
+ uuid: record2.uuid ?? null,
13730
+ name: record2.name ?? "",
13731
+ desc: record2.desc ?? "",
13732
+ status: record2.status ?? null,
13733
+ flow_type: record2.flow_type ?? "",
13734
+ flow_key: record2.flow_key ?? "",
13735
+ create_time: record2.create_time ?? null,
13736
+ update_time: record2.update_time ?? null,
13737
+ readback_hash: hashJson(record2)
13487
13738
  }));
13488
13739
  const pagination = isRecord4(response) ? pickDefined(response, ["currentPage", "pageSize", "totalPages", "count"]) : {};
13489
13740
  return {
@@ -13595,11 +13846,11 @@ async function inspectFlowReportTemplateUsage(profile, id) {
13595
13846
  const detailResponse = flowType ? await apiRequest(createApiClient(profile), "GET", `/flow_page_template?${params.toString()}`, {
13596
13847
  capability: "config.project_detail_template.export"
13597
13848
  }) : [];
13598
- const projectDetailReferences = extractListData(detailResponse).filter((record) => Number(record.type) === 2).filter((record) => containsGenerateReportSection(parseTemplateContent(record))).map((record) => ({
13599
- id: record.id ?? null,
13600
- name: record.name ?? null,
13601
- flow_type: record.flow_type ?? "",
13602
- flow_key: record.flow_key ?? "",
13849
+ const projectDetailReferences = extractListData(detailResponse).filter((record2) => Number(record2.type) === 2).filter((record2) => containsGenerateReportSection(parseTemplateContent(record2))).map((record2) => ({
13850
+ id: record2.id ?? null,
13851
+ name: record2.name ?? null,
13852
+ flow_type: record2.flow_type ?? "",
13853
+ flow_key: record2.flow_key ?? "",
13603
13854
  reference_kind: "generate-report-section",
13604
13855
  note: "\u8BE5\u5165\u53E3\u6309\u6D41\u7A0B\u8303\u56F4\u5217\u51FA type=5 \u6A21\u677F\uFF0C\u4E0D\u76F4\u63A5\u7ED1\u5B9A\u5355\u4E2A\u6A21\u677F ID\u3002"
13605
13856
  }));
@@ -13951,8 +14202,8 @@ function extractRecords(value) {
13951
14202
  if (Array.isArray(value.rows)) return value.rows.filter(isRecord4);
13952
14203
  return [];
13953
14204
  }
13954
- function recordId(record) {
13955
- const value = record.id ?? record.template_id ?? record.flow_page_template_id;
14205
+ function recordId(record2) {
14206
+ const value = record2.id ?? record2.template_id ?? record2.flow_page_template_id;
13956
14207
  return value === void 0 || value === null ? void 0 : String(value);
13957
14208
  }
13958
14209
  function numericIdString(value) {
@@ -14015,20 +14266,20 @@ async function resolveLocalUuidConfigId(options) {
14015
14266
  const matches = [];
14016
14267
  for (const filePath of files) {
14017
14268
  try {
14018
- const record = JSON.parse(await readFile8(filePath, "utf8"));
14019
- if (!isRecord4(record)) continue;
14020
- if (String(record.uuid || "").toLowerCase() !== options.uuid.toLowerCase()) continue;
14269
+ const record2 = JSON.parse(await readFile8(filePath, "utf8"));
14270
+ if (!isRecord4(record2)) continue;
14271
+ if (String(record2.uuid || "").toLowerCase() !== options.uuid.toLowerCase()) continue;
14021
14272
  const filenameId = numericIdString(path5.basename(filePath, path5.extname(filePath)));
14022
- const id = numericIdString(record.id) ?? numericIdString(record.origin_template_id) ?? numericIdString(record.template_id) ?? filenameId ?? null;
14273
+ const id = numericIdString(record2.id) ?? numericIdString(record2.origin_template_id) ?? numericIdString(record2.template_id) ?? filenameId ?? null;
14023
14274
  matches.push({
14024
14275
  domain: options.domain,
14025
14276
  uuid: options.uuid,
14026
14277
  id,
14027
14278
  path: filePath,
14028
- name: record.name ?? record.title ?? null,
14029
- type: record.type ?? null,
14030
- flow_type: record.flow_type ?? null,
14031
- flow_key: record.flow_key ?? null
14279
+ name: record2.name ?? record2.title ?? null,
14280
+ type: record2.type ?? null,
14281
+ flow_type: record2.flow_type ?? null,
14282
+ flow_key: record2.flow_key ?? null
14032
14283
  });
14033
14284
  } catch {
14034
14285
  }
@@ -14254,6 +14505,7 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
14254
14505
  ignoredPreexistingLintErrors = evaluated.ignored;
14255
14506
  }
14256
14507
  let formTemplateWarnings = [];
14508
+ let formTemplateReferenceAudit;
14257
14509
  let flowDetailTemplateWarnings = [];
14258
14510
  let stepDetailReferenceAudit;
14259
14511
  let stepDetailAnalysis;
@@ -14294,6 +14546,12 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
14294
14546
  if (errors.length) {
14295
14547
  throw new Error(`form-template lint failed: ${errors.join("; ")}`);
14296
14548
  }
14549
+ if (options.pluginLint?.profile) {
14550
+ formTemplateReferenceAudit = await auditSubFormTemplateReferences(work, options.pluginLint.profile);
14551
+ if (formTemplateReferenceAudit.errors.length) {
14552
+ throw new Error(`form-template reference gate failed: ${formTemplateReferenceAudit.errors.join("; ")}`);
14553
+ }
14554
+ }
14297
14555
  }
14298
14556
  if (domain === "console-template" && isRecord4(work)) {
14299
14557
  const errors = [];
@@ -14383,6 +14641,7 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
14383
14641
  ...datasetMapping ? { dataset_mapping: datasetMapping } : {},
14384
14642
  ...flowCategoryReferenceAudit ? { flow_category_reference: flowCategoryReferenceEvidence(flowCategoryReferenceAudit) } : {},
14385
14643
  ...formTemplateWarnings.length ? { form_template_warnings: formTemplateWarnings } : {},
14644
+ ...formTemplateReferenceAudit ? { form_template_reference_audit: formTemplateReferenceAudit } : {},
14386
14645
  ...flowDetailTemplateWarnings.length ? { flow_detail_template_warnings: flowDetailTemplateWarnings } : {},
14387
14646
  ...stepDetailReferenceAudit ? {
14388
14647
  step_detail_references: stepDetailReferenceAudit.references,
@@ -14425,6 +14684,7 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
14425
14684
  } : {},
14426
14685
  ...datasetFieldWarnings.length ? { warnings: datasetFieldWarnings } : {},
14427
14686
  ...formTemplateWarnings.length ? { warnings: formTemplateWarnings } : {},
14687
+ ...formTemplateReferenceAudit ? { form_template_reference_audit: formTemplateReferenceAudit } : {},
14428
14688
  ...flowDetailTemplateWarnings.length ? { warnings: flowDetailTemplateWarnings } : {},
14429
14689
  ...stepDetailReferenceAudit ? {
14430
14690
  step_detail_references: stepDetailReferenceAudit.references,
@@ -14556,6 +14816,7 @@ async function lintConfigWorkFile(file, options = {}) {
14556
14816
  let flowReportAnalysis;
14557
14817
  let flowReportReferenceAudit;
14558
14818
  let datasetMapping;
14819
+ let formTemplateReferenceAudit;
14559
14820
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
14560
14821
  errors.push("Config work file must be a JSON object.");
14561
14822
  } else {
@@ -14586,6 +14847,13 @@ async function lintConfigWorkFile(file, options = {}) {
14586
14847
  if (shouldLintFormTemplate) {
14587
14848
  const formMode = options.mode ?? (value.mode === "create" ? "create" : "edit");
14588
14849
  validateFormTemplateWorkLint(value, errors, warnings, formMode);
14850
+ if (options.pluginLint?.profile && errors.length === 0) {
14851
+ formTemplateReferenceAudit = await auditSubFormTemplateReferences(
14852
+ value,
14853
+ options.pluginLint.profile
14854
+ );
14855
+ errors.push(...formTemplateReferenceAudit.errors);
14856
+ }
14589
14857
  }
14590
14858
  if (options.domain === "filter-template") {
14591
14859
  lintFilterTemplateWork(value, errors, options.usage);
@@ -14654,6 +14922,7 @@ async function lintConfigWorkFile(file, options = {}) {
14654
14922
  ok: errors.length === 0,
14655
14923
  errors,
14656
14924
  warnings,
14925
+ ...formTemplateReferenceAudit ? { form_template_reference_audit: formTemplateReferenceAudit } : {},
14657
14926
  ...stepDetailAnalysis ? {
14658
14927
  step_detail_template: {
14659
14928
  modules: stepDetailAnalysis.moduleNames,
@@ -15268,6 +15537,10 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
15268
15537
  if (domain === "form-template" && submitMode === "create") {
15269
15538
  validateNonEmptyFormCreatePayload(submit.payload);
15270
15539
  validateFormTemplateSubmitPayload(submit.payload, "create");
15540
+ const formTemplateReferenceAudit = await auditSubFormTemplateReferences(submit.payload, profile);
15541
+ if (formTemplateReferenceAudit.errors.length) {
15542
+ throw new Error(`form-template reference gate failed: ${formTemplateReferenceAudit.errors.join("; ")}`);
15543
+ }
15271
15544
  await ensureConfigCapability(profile, `${definition.capability}.create`);
15272
15545
  const expectedConfirm2 = `submit ${domain} ${id}`;
15273
15546
  const endpoint2 = "/form_template";
@@ -15335,6 +15608,10 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
15335
15608
  validateNonDestructiveFormEdit(submit.payload, current);
15336
15609
  }
15337
15610
  validateFormTemplateSubmitPayload(submit.payload, "edit");
15611
+ const formTemplateReferenceAudit = await auditSubFormTemplateReferences(submit.payload, profile);
15612
+ if (formTemplateReferenceAudit.errors.length) {
15613
+ throw new Error(`form-template reference gate failed: ${formTemplateReferenceAudit.errors.join("; ")}`);
15614
+ }
15338
15615
  assertFormTemplateDraftId(id, current, "submit");
15339
15616
  }
15340
15617
  if (domain === "flow-template" && isRecord4(current)) {
@@ -15344,8 +15621,12 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
15344
15621
  if (isRecord4(current) && String(current.id) !== id) {
15345
15622
  throw new Error(`dataset edit identity mismatch; request id, payload.id, and readback id must all equal ${id}.`);
15346
15623
  }
15347
- if (isRecord4(current) && String(current.custom_key ?? "") !== String(submit.payload.custom_key ?? "")) {
15348
- throw new Error("dataset edit refuses to change custom_key identity through relationFields.");
15624
+ const currentCustomKey = normalizeText(isRecord4(current) ? current.custom_key : "").trim();
15625
+ const proposedCustomKey = normalizeText(submit.payload.custom_key).trim();
15626
+ if (currentCustomKey !== proposedCustomKey) {
15627
+ if (currentCustomKey || !proposedCustomKey || !options.initializeDatasetCustomKey) {
15628
+ throw new Error("dataset edit refuses to change custom_key identity through relationFields. For a legacy empty custom_key, re-run with --initialize-custom-key and the exact initialization confirmation.");
15629
+ }
15349
15630
  }
15350
15631
  }
15351
15632
  if (domain === "team") {
@@ -15388,9 +15669,11 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
15388
15669
  submitPayload = flowPayload;
15389
15670
  }
15390
15671
  const mutationDiff = diffJsonNormalized(domain, current, submitPayload);
15391
- if (confirm3 !== expectedConfirm) {
15672
+ const datasetCustomKeyInitialization = domain === "dataset" && isRecord4(current) && !normalizeText(current.custom_key).trim() && Boolean(normalizeText(submit.payload.custom_key).trim()) && options.initializeDatasetCustomKey;
15673
+ const requiredConfirm = datasetCustomKeyInitialization ? `initialize dataset custom_key ${id} ${normalizeText(submit.payload.custom_key).trim()}` : expectedConfirm;
15674
+ if (confirm3 !== requiredConfirm) {
15392
15675
  return {
15393
- ...dryRunFields(expectedConfirm),
15676
+ ...dryRunFields(requiredConfirm),
15394
15677
  domain,
15395
15678
  id,
15396
15679
  endpoint,
@@ -15429,9 +15712,17 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
15429
15712
  }
15430
15713
  } : {},
15431
15714
  ...flowReportActivation ? { activation_collateral: flowReportActivation } : {},
15715
+ ...datasetCustomKeyInitialization ? {
15716
+ dataset_custom_key_initialization: {
15717
+ one_time: true,
15718
+ previous_custom_key: "",
15719
+ custom_key: normalizeText(submit.payload.custom_key).trim(),
15720
+ impact_required: true
15721
+ }
15722
+ } : {},
15432
15723
  diff: mutationDiff,
15433
15724
  current_hash: currentHash,
15434
- next: `Run again with --confirm "${expectedConfirm}" to submit.`
15725
+ next: `Run again with --confirm "${requiredConfirm}" to submit.`
15435
15726
  };
15436
15727
  }
15437
15728
  const client = createApiClient(profile);
@@ -16200,8 +16491,8 @@ function collectChangedIdentifiers(raw, work) {
16200
16491
  "step_detail_id",
16201
16492
  "search_temp_id"
16202
16493
  ]);
16203
- const recordIdentifiers = (record) => [...new Set(
16204
- Object.entries(record).filter(([key]) => identifierKeys.has(key.toLowerCase())).map(([, value]) => stableString(value)).filter(Boolean)
16494
+ const recordIdentifiers = (record2) => [...new Set(
16495
+ Object.entries(record2).filter(([key]) => identifierKeys.has(key.toLowerCase())).map(([, value]) => stableString(value)).filter(Boolean)
16205
16496
  )];
16206
16497
  const visitDifference = (before, after, currentPath) => {
16207
16498
  if (normalizeComparable(before) === normalizeComparable(after)) {
@@ -16480,6 +16771,7 @@ async function analyzeConfigImpact(options) {
16480
16771
  }
16481
16772
 
16482
16773
  // src/core/config-workspace.ts
16774
+ import { createHash as createHash6 } from "crypto";
16483
16775
  import { mkdir as mkdir6, readFile as readFile10, realpath, stat as stat6, writeFile as writeFile6 } from "fs/promises";
16484
16776
  import path7 from "path";
16485
16777
  var DEFAULT_AGENT_GUIDE_FILE = "AGENTS.md";
@@ -16744,6 +17036,20 @@ ${directoryRows}
16744
17036
  - \u5982\u679C CLI \u63D0\u793A\u7F3A\u5C11 capability\u3001\u5F53\u524D profile \u672A\u5F00\u542F\u914D\u7F6E\u80FD\u529B\uFF0C\u6216\u672A\u6765\u65B0\u589E domain \u5C1A\u672A\u8FDB\u5165 adapter \u77E9\u9635 / \`config plugin adapters\`\uFF0C\u5FC5\u987B\u505C\u6B62\u8FDC\u7AEF\u5199\u5165\uFF1B\u4E0D\u5F97\u624B\u5199 raw API\u3002
16745
17037
  - \u7981\u6B62\u7528 \`bpmax-cli api\`\u3001curl\u3001\u9875\u9762 fetch\u3001\u9875\u9762 axios \u6216\u65E7 submit \u811A\u672C\u76F4\u63A5\u5199\u914D\u7F6E\u3002
16746
17038
  - \u63D0\u4EA4\u524D\u5FC5\u987B\u5B8C\u6210 export\u3001work \u4FEE\u6539\u3001lint\u3001build\u3001dry-run\u3001\u7CBE\u786E \`--confirm\`\u3001verify \u548C\u9875\u9762\u9A8C\u6536\u3002
17039
+ ## Token \u4E0E\u4E0A\u4E0B\u6587\u63A7\u5236
17040
+
17041
+ - \u6BCF\u4E2A\u903B\u8F91\u56DE\u5408\u53EA\u5904\u7406\u4E00\u4E2A\u95ED\u73AF\uFF1Aworkspace \u521D\u59CB\u5316\u3001\u914D\u7F6E\u62C9\u53D6\u3001\u5355\u5BF9\u8C61\u4FEE\u6539\u3001\u6D4F\u89C8\u5668\u9A8C\u6536\u6216\u6B63\u5F0F E2E\uFF1B\u5B8C\u6210\u540E\u5199 checkpoint \u5E76\u6536\u53E3\u3002
17042
+ - \u521D\u59CB\u5316\u3001export\u3001readback\u3001lint\u3001verify \u548C\u6D4B\u8BD5\u62A5\u544A\u4F18\u5148\u4F7F\u7528 \`--format summary\`\u3002
17043
+ - \u5B8C\u6574 JSON\u3001\u6A21\u677F\u3001diff\u3001\u7F51\u7EDC\u54CD\u5E94\u3001\u65E5\u5FD7\u548C\u622A\u56FE\u5FC5\u987B\u5199\u5165 \`.codex/tmp/\`\uFF1B\u5BF9\u8BDD\u4E2D\u53EA\u8FD4\u56DE\u6587\u4EF6\u8DEF\u5F84\u3001\u72B6\u6001\u3001hash\u3001changed_paths \u548C\u5FC5\u8981\u5B57\u6BB5\u3002
17044
+ - \u5927 JSON \u5148\u7528 \`jq\` \u63D0\u53D6\u76EE\u6807\u5B57\u6BB5\uFF1B\u641C\u7D22\u5148\u8FD4\u56DE\u6587\u4EF6\u540D\uFF0C\u518D\u8BFB\u53D6\u6709\u9650\u8303\u56F4\uFF1B\u7981\u6B62\u65E0\u8FB9\u754C \`find\`\u3001\u5927\u8303\u56F4 \`rg\` \u548C\u5168\u6587\u6253\u5370\u5927\u578B\u6587\u4EF6\u3002
17045
+ - \u622A\u56FE\u3001\u89C6\u9891\u5E27\u3001HAR \u548C\u4E8C\u8FDB\u5236\u54CD\u5E94\u5FC5\u987B\u843D\u76D8\uFF0C\u7981\u6B62\u628A base64 \u6216\u5B8C\u6574\u4E8C\u8FDB\u5236\u5185\u5BB9\u8FD4\u56DE\u5230\u4E0A\u4E0B\u6587\u3002
17046
+ - \u6D4F\u89C8\u5668\u8BCA\u65AD\u6309\u201C\u8F7B\u91CF snapshot \u2192 \u76EE\u6807\u63A5\u53E3 \u2192 \u4FEE\u6539 \u2192 reload \u2192 \u4E00\u6B21\u9A8C\u6536 snapshot\u201D\u6267\u884C\u3002
17047
+ - \u540C\u4E00\u52A8\u4F5C\u5931\u8D25\u4E24\u6B21\u540E\u66F4\u6362\u65B9\u6CD5\u6216\u8BB0\u5F55 blocker\uFF0C\u4E0D\u5728\u5927\u4E0A\u4E0B\u6587\u4E2D\u76F2\u76EE\u91CD\u8BD5\u3002
17048
+ - \u5B8C\u6210 submit + verify \u540E\u7ACB\u5373\u8BB0\u5F55 checkpoint \u5E76\u7ED3\u675F\u5F53\u524D\u56DE\u5408\u3002
17049
+ - \u53D1\u751F\u4E0A\u4E0B\u6587\u538B\u7F29\u540E\u53EA\u5B8C\u6210\u5F53\u524D\u9636\u6BB5\u9A8C\u8BC1\uFF0C\u4E0D\u6062\u590D\u65E0\u5173\u5386\u53F2\u6216\u6269\u5927\u8303\u56F4\u3002
17050
+ - \u6BCF\u4E2A\u903B\u8F91\u56DE\u5408\u53EA\u8BFB\u53D6\u4E00\u6B21\u5F53\u524D\u5BF9\u8C61\u5FC5\u9700\u7684 Skill \u548C reference\uFF1Bmemory \u67E5\u8BE2\u9650\u5236\u8FD4\u56DE\u6570\u91CF\uFF0C\u53EA\u643A\u5E26\u76F8\u5173\u7ED3\u8BBA\u3002
17051
+ - \u4E0D\u5F97\u4E3A\u4E86\u8282\u7EA6 token \u8DF3\u8FC7 export\u3001lint\u3001dry-run\u3001confirm\u3001verify\u3001readback \u6216\u6B63\u5F0F E2E\u3002
17052
+ - token\u3001API Key\u3001Authorization\u3001cookie\u3001\u5BC6\u7801\u3001\u9A8C\u8BC1\u7801\u3001\u624B\u673A\u53F7\u548C\u5B8C\u6574\u654F\u611F\u54CD\u5E94\u4E0D\u5F97\u5199\u5165 checkpoint\u3001receipt\u3001AGENTS.md\u3001memory\u3001\u622A\u56FE\u6216 Git\u3002
16747
17053
  - \u4E0D\u8981\u5728\u5BF9\u8BDD\u6216\u6587\u4EF6\u4E2D\u5199\u5165 API Key\u3001Authorization\u3001token\u3001password\u3001\u9A8C\u8BC1\u7801\u3001\u624B\u673A\u53F7\u7B49\u654F\u611F\u660E\u6587\u3002
16748
17054
 
16749
17055
  ## Skill \u8DEF\u7531
@@ -16855,14 +17161,17 @@ async function initConfigWorkspaceGuide(options) {
16855
17161
  await mkdir6(path7.dirname(targetFile), { recursive: true });
16856
17162
  await writeFile6(targetFile, content, "utf8");
16857
17163
  }
16858
- return {
17164
+ const result = {
16859
17165
  dry_run: Boolean(options.dryRun),
16860
17166
  path: targetFile,
16861
17167
  env: options.env,
16862
17168
  profile: options.profile.name,
16863
17169
  updated: content !== existing,
16864
- content
17170
+ content_bytes: Buffer.byteLength(content, "utf8"),
17171
+ content_sha256: createHash6("sha256").update(content, "utf8").digest("hex")
16865
17172
  };
17173
+ if (options.includeContent !== false) result.content = content;
17174
+ return result;
16866
17175
  }
16867
17176
 
16868
17177
  // src/core/plugin-config-adapters.ts
@@ -17094,22 +17403,31 @@ function lintPluginWork(work, rules, base) {
17094
17403
  if (!conditionMatches(work, rule.when)) continue;
17095
17404
  const pathSelector = rule.path || "";
17096
17405
  const values = getPathValues(work, pathSelector);
17406
+ const firstValue = pathSelector ? firstPathValue(work, pathSelector) : work;
17097
17407
  const message = rule.message || `${pathSelector || "<root>"} failed ${rule.type || "validation"}`;
17408
+ if (rule.optional && (firstValue === void 0 || firstValue === null || firstValue === "")) {
17409
+ continue;
17410
+ }
17098
17411
  if (rule.type === "object") {
17099
- const value = pathSelector ? firstPathValue(work, pathSelector) : work;
17100
- if (!isRecord6(value)) errors.push(message);
17412
+ if (!isRecord6(firstValue)) errors.push(message);
17101
17413
  } else if (rule.type === "nonEmptyString") {
17102
17414
  if (!values.length || values.some((value) => typeof value !== "string" || !value.trim())) errors.push(message);
17103
17415
  } else if (rule.type === "nonEmptyArray") {
17104
- const value = firstPathValue(work, pathSelector);
17105
- if (!Array.isArray(value) || !value.length) errors.push(message);
17416
+ if (!Array.isArray(firstValue) || !firstValue.length) errors.push(message);
17417
+ } else if (rule.type === "arrayLength") {
17418
+ if (!Array.isArray(firstValue) || Number.isInteger(rule.minItems) && firstValue.length < Number(rule.minItems) || Number.isInteger(rule.maxItems) && firstValue.length > Number(rule.maxItems)) {
17419
+ errors.push(message);
17420
+ }
17421
+ } else if (rule.type === "arrayPositiveNumber") {
17422
+ if (!Array.isArray(firstValue) || firstValue.some(
17423
+ (item) => typeof item !== "number" || !Number.isInteger(item) || item <= 0
17424
+ )) {
17425
+ errors.push(message);
17426
+ }
17106
17427
  } else if (rule.type === "enum") {
17107
- const value = firstPathValue(work, pathSelector);
17108
- if ((value === void 0 || value === null || value === "") && rule.optional) continue;
17109
- if (!rule.values?.includes(value)) errors.push(message);
17428
+ if (!rule.values?.includes(firstValue)) errors.push(message);
17110
17429
  } else if (rule.type === "arrayEnum") {
17111
- const value = firstPathValue(work, pathSelector);
17112
- if (!Array.isArray(value) || value.some((item) => !rule.values?.includes(item))) errors.push(message);
17430
+ if (!Array.isArray(firstValue) || firstValue.some((item) => !rule.values?.includes(item))) errors.push(message);
17113
17431
  } else if (rule.type === "noNewArrayItem") {
17114
17432
  if (!base) continue;
17115
17433
  const before = firstPathValue(base, pathSelector);
@@ -17140,9 +17458,27 @@ function normalizeWorkFromRaw(raw, adapter) {
17140
17458
  work.mode ||= "edit";
17141
17459
  return work;
17142
17460
  }
17461
+ function pluginConfigHashPayload(raw, adapter) {
17462
+ const result = JSON.parse(JSON.stringify(raw));
17463
+ for (const selector of adapter.work?.ignore_fields || []) {
17464
+ const parts = selector.split(".").filter(Boolean);
17465
+ if (!parts.length) continue;
17466
+ let current = result;
17467
+ for (const part of parts.slice(0, -1)) {
17468
+ const child = current?.[part];
17469
+ if (!isRecord6(child)) {
17470
+ current = void 0;
17471
+ break;
17472
+ }
17473
+ current = child;
17474
+ }
17475
+ if (current) delete current[parts[parts.length - 1]];
17476
+ }
17477
+ return result;
17478
+ }
17143
17479
  function responseId(response) {
17144
- const record = unwrapRecord(response);
17145
- return record.id ?? record.local_id ?? record.record_id;
17480
+ const record2 = unwrapRecord(response);
17481
+ return record2.id ?? record2.local_id ?? record2.record_id;
17146
17482
  }
17147
17483
  async function readPluginConfigRecord(profile, adapter, id) {
17148
17484
  const client = createApiClient(profile);
@@ -17164,7 +17500,7 @@ async function exportPluginConfigDomain(profile, domain, id, outDir, agent = "co
17164
17500
  const rawFile = path8.join(outDir, `${domain}-${id}-raw.json`);
17165
17501
  const workFile = path8.join(outDir, `${domain}-${id}-work.json`);
17166
17502
  const metaFile = path8.join(outDir, `${domain}-${id}-meta.json`);
17167
- const rawForHash = raw;
17503
+ const rawForHash = Array.isArray(raw) ? raw : pluginConfigHashPayload(unwrapRecord(raw), resolved.adapter);
17168
17504
  const work = Array.isArray(raw) ? raw : normalizeWorkFromRaw(unwrapRecord(raw), resolved.adapter);
17169
17505
  await writeJsonFile(rawFile, raw);
17170
17506
  await writeJsonFile(workFile, work);
@@ -17281,7 +17617,7 @@ async function submitPluginConfigDomain(profile, domain, id, submitFile, confirm
17281
17617
  let currentHash = null;
17282
17618
  if (mode !== "create") {
17283
17619
  const current = await readPluginConfigRecord(profile, resolved.adapter, id);
17284
- currentHash = hashJson(current);
17620
+ currentHash = hashJson(pluginConfigHashPayload(current, resolved.adapter));
17285
17621
  if (currentHash !== submit.base_hash) {
17286
17622
  throw new Error("Remote plugin config changed after export. Re-export before submitting.");
17287
17623
  }
@@ -18304,12 +18640,14 @@ function registerConfigCommands(program2) {
18304
18640
  });
18305
18641
  const latest = config.command("latest").description("Sync latest BPMAX sysconfig repositories");
18306
18642
  const workspace = config.command("workspace").description("Initialize local BPMAX sysconfig workspaces");
18307
- workspace.command("init <env>").description("Clone or bind a local sysconfig workspace from the BPMAX platform config repository").requiredOption("--workspace-dir <workspaceDir>", "Local sysconfig workspace directory").option("--profile <profile>", "Profile name").option("--force", "Bind an existing git workspace even when its origin remote differs").option("--format <format>", "Output format", "pretty").action(async (env, options) => {
18643
+ workspace.command("init <env>").description("Clone or bind a local sysconfig workspace from the BPMAX platform config repository").requiredOption("--workspace-dir <workspaceDir>", "Local sysconfig workspace directory").option("--profile <profile>", "Profile name").option("--force", "Bind an existing git workspace even when its origin remote differs").option("--receipt <file>", "Write the complete non-secret result to a file").option("--format <format>", "Output format", "pretty").action(async (env, options) => {
18308
18644
  const result = await initConfigWorkspaceFromPlatform(env, {
18309
18645
  profile: options.profile,
18310
18646
  workspaceDir: options.workspaceDir,
18311
18647
  force: options.force
18312
18648
  });
18649
+ await writeResponseOut(options.receipt, result);
18650
+ if (options.receipt) result.receipt = path10.resolve(options.receipt);
18313
18651
  printResult(options.format, result);
18314
18652
  });
18315
18653
  const repository = config.command("repository").description("Inspect and sync BPMAX sysconfig repositories");
@@ -18397,7 +18735,7 @@ function registerConfigCommands(program2) {
18397
18735
  printResult(options.format, result);
18398
18736
  });
18399
18737
  const init = config.command("init").description("Initialize BPMAX configuration helper files");
18400
- init.command("workspace").description("Create or update an AGENTS.md BPMAX configuration guide in a workspace directory").requiredOption("--env <env>", "Configuration environment key").option("--profile <profile>", "Profile name").option("--cwd <dir>", "Target workspace directory", process.cwd()).option("--file <file>", "Agent guide file name", DEFAULT_AGENT_GUIDE_FILE).option("--dry-run", "Print the generated content without writing the file").option("--format <format>", "Output format", "pretty").action(async (options) => {
18738
+ init.command("workspace").description("Create or update an AGENTS.md BPMAX configuration guide in a workspace directory").requiredOption("--env <env>", "Configuration environment key").option("--profile <profile>", "Profile name").option("--cwd <dir>", "Target workspace directory", process.cwd()).option("--file <file>", "Agent guide file name", DEFAULT_AGENT_GUIDE_FILE).option("--out <file>", "Write generated guide content to a file").option("--include-content", "Include the complete generated guide in output").option("--dry-run", "Print the generated content without writing the file").option("--format <format>", "Output format", "pretty").action(async (options) => {
18401
18739
  const configData = await loadConfig();
18402
18740
  const resolved = resolveProfile(configData, options.profile);
18403
18741
  const result = await initConfigWorkspaceGuide({
@@ -18406,8 +18744,14 @@ function registerConfigCommands(program2) {
18406
18744
  env: options.env,
18407
18745
  cwd: options.cwd,
18408
18746
  file: options.file,
18409
- dryRun: options.dryRun
18747
+ dryRun: options.dryRun,
18748
+ includeContent: Boolean(options.includeContent || options.out || options.format !== "summary")
18410
18749
  });
18750
+ if (options.out) {
18751
+ await writeResponseOut(options.out, { content: result.content || void 0 });
18752
+ delete result.content;
18753
+ result.content_file = path10.resolve(options.out);
18754
+ }
18411
18755
  printResult(options.format, result);
18412
18756
  });
18413
18757
  config.command("resolve-id").description("Resolve a local sysconfig UUID to a platform numeric config id").requiredOption("--domain <domain>", "Config domain, e.g. form-template or project-detail-template").requiredOption("--uuid <uuid>", "Local sysconfig UUID").option("--repo <path>", "Local sysconfig repository path").option("--profile <profile>", "Profile name; when present, also query supported BPMAX get_by_uuid endpoints").option("--format <format>", "Output format", "json").action(async (options) => {
@@ -18547,7 +18891,7 @@ function registerConfigCommands(program2) {
18547
18891
  await saveConfig(configData);
18548
18892
  printResult(options.format, result);
18549
18893
  });
18550
- domainCommand.command("lint").description(`Lint a ${domain} work file`).requiredOption("--work <file>", "Work JSON file").option("--mode <mode>", "Lint mode: create | edit").option("--usage <usage>", "Filter-template usage: ordinary | console | dashboard").option("--profile <profile>", "Profile name for plugin lint discovery").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--format <format>", "Output format", "pretty").action(async (options) => {
18894
+ domainCommand.command("lint").description(`Lint a ${domain} work file`).requiredOption("--work <file>", "Work JSON file").option("--mode <mode>", "Lint mode: create | edit").option("--usage <usage>", "Filter-template usage: ordinary | console | dashboard").option("--profile <profile>", "Profile name for plugin lint discovery and remote reference audits").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--format <format>", "Output format", "pretty").action(async (options) => {
18551
18895
  if (options.mode && options.mode !== "create" && options.mode !== "edit") {
18552
18896
  throw new Error("--mode \u53EA\u5141\u8BB8 create \u6216 edit\u3002");
18553
18897
  }
@@ -18555,11 +18899,11 @@ function registerConfigCommands(program2) {
18555
18899
  throw new Error("--usage \u53EA\u5141\u8BB8 ordinary\u3001console \u6216 dashboard\u3002");
18556
18900
  }
18557
18901
  let pluginLint;
18558
- if (domain === "flow-template") {
18902
+ if (domain === "flow-template" || domain === "form-template") {
18559
18903
  pluginLint = await resolveFlowTemplatePluginLintOptions({
18560
18904
  profile: options.profile,
18561
18905
  agent: options.agent,
18562
- requireInstalled: true
18906
+ requireInstalled: domain === "flow-template"
18563
18907
  });
18564
18908
  }
18565
18909
  const result = await lintConfigWorkFile(options.work, {
@@ -18574,7 +18918,7 @@ function registerConfigCommands(program2) {
18574
18918
  }
18575
18919
  printResult(options.format, result);
18576
18920
  });
18577
- const buildCommand = domainCommand.command("build").description(`Build a submit payload for ${domain} when a verified domain adapter is available`).requiredOption("--work <file>", "Work JSON file").requiredOption("--out <file>", "Submit payload output file").option("--meta <file>", "Export meta JSON file").option("--all-records", "For aggregate domains, submit every record instead of only changed records").option("--publish-live", "For flow-template, build a live publish payload instead of draft save").option("--usage <usage>", "Filter-template usage: ordinary | console | dashboard").option("--profile <profile>", "Profile name for plugin lint discovery").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--format <format>", "Output format", "pretty");
18921
+ const buildCommand = domainCommand.command("build").description(`Build a submit payload for ${domain} when a verified domain adapter is available`).requiredOption("--work <file>", "Work JSON file").requiredOption("--out <file>", "Submit payload output file").option("--meta <file>", "Export meta JSON file").option("--all-records", "For aggregate domains, submit every record instead of only changed records").option("--publish-live", "For flow-template, build a live publish payload instead of draft save").option("--usage <usage>", "Filter-template usage: ordinary | console | dashboard").option("--profile <profile>", "Profile name for plugin lint discovery and remote reference audits").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--format <format>", "Output format", "pretty");
18578
18922
  if (domain === "flow-template") {
18579
18923
  buildCommand.option("--allow-preexisting-lint-errors", "Allow unchanged non-hard lint errors already present in the verified raw export baseline");
18580
18924
  }
@@ -18583,11 +18927,11 @@ function registerConfigCommands(program2) {
18583
18927
  throw new Error("--usage \u53EA\u5141\u8BB8 ordinary\u3001console \u6216 dashboard\u3002");
18584
18928
  }
18585
18929
  let pluginLint;
18586
- if (domain === "flow-template") {
18930
+ if (domain === "flow-template" || domain === "form-template") {
18587
18931
  pluginLint = await resolveFlowTemplatePluginLintOptions({
18588
18932
  profile: options.profile,
18589
18933
  agent: options.agent,
18590
- requireInstalled: true
18934
+ requireInstalled: domain === "flow-template"
18591
18935
  });
18592
18936
  }
18593
18937
  const result = await buildConfigSubmitPayload(domain, options.work, options.out, options.meta, {
@@ -18641,7 +18985,7 @@ function registerConfigCommands(program2) {
18641
18985
  await writeResponseOut(options.out, output);
18642
18986
  printResult(options.format, output);
18643
18987
  });
18644
- domainCommand.command("submit").description(`Submit a ${domain} payload when a verified domain adapter is available; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").requiredOption("--payload <file>", "Submit payload JSON file produced by build").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, submit this payload as a live publish").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
18988
+ domainCommand.command("submit").description(`Submit a ${domain} payload when a verified domain adapter is available; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").requiredOption("--payload <file>", "Submit payload JSON file produced by build").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, submit this payload as a live publish").option("--initialize-custom-key", "For a legacy dataset only, permit one-time empty custom_key initialization with an exact confirmation").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
18645
18989
  const configData = await loadConfig();
18646
18990
  const resolved = resolveProfile(configData, options.profile);
18647
18991
  const result = await submitConfigDomain(
@@ -18651,7 +18995,11 @@ function registerConfigCommands(program2) {
18651
18995
  options.id,
18652
18996
  options.payload,
18653
18997
  options.confirm,
18654
- { publishLive: Boolean(options.publishLive), agent: options.agent || "codex" }
18998
+ {
18999
+ publishLive: Boolean(options.publishLive),
19000
+ agent: options.agent || "codex",
19001
+ initializeDatasetCustomKey: Boolean(options.initializeCustomKey)
19002
+ }
18655
19003
  );
18656
19004
  await saveConfig(configData);
18657
19005
  await writeResponseOut(options.responseOut, result);
@@ -18672,7 +19020,7 @@ function registerConfigCommands(program2) {
18672
19020
  });
18673
19021
  if (domain === "dataset") {
18674
19022
  const relationFields = domainCommand.command("relation-fields").description("Manage dataset relationFields through the typed dataset adapter");
18675
- relationFields.command("submit").description("Submit dataset relationFields payload with the standard dataset evidence response").requiredOption("--id <id>", "Remote dataset id").requiredOption("--payload <file>", "Submit payload JSON file produced by config dataset build").option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
19023
+ relationFields.command("submit").description("Submit dataset relationFields payload with the standard dataset evidence response").requiredOption("--id <id>", "Remote dataset id").requiredOption("--payload <file>", "Submit payload JSON file produced by config dataset build").option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--initialize-custom-key", "Permit one-time initialization when the remote dataset custom_key is empty").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
18676
19024
  const configData = await loadConfig();
18677
19025
  const resolved = resolveProfile(configData, options.profile);
18678
19026
  const result = await submitConfigDomain(
@@ -18681,7 +19029,8 @@ function registerConfigCommands(program2) {
18681
19029
  "dataset",
18682
19030
  options.id,
18683
19031
  options.payload,
18684
- options.confirm
19032
+ options.confirm,
19033
+ { initializeDatasetCustomKey: Boolean(options.initializeCustomKey) }
18685
19034
  );
18686
19035
  await saveConfig(configData);
18687
19036
  await writeResponseOut(options.responseOut, result);
@@ -18775,6 +19124,8 @@ var SUPPORTED_ACTIONS = {
18775
19124
  user_select: ["form.select_option", "form.select_user"],
18776
19125
  group_select: ["form.select_option"],
18777
19126
  ecology_browser_review: ["form.select_option"],
19127
+ cascader: ["cascader.search_select"],
19128
+ el_cascader: ["cascader.search_select"],
18778
19129
  sub_form: ["detail.add_row", "detail.set_value"]
18779
19130
  };
18780
19131
  var SELECTOR_CONTROLS = /* @__PURE__ */ new Set([
@@ -19110,18 +19461,18 @@ function registerDoctorCommands(program2) {
19110
19461
  }
19111
19462
 
19112
19463
  // src/commands/e2e.ts
19113
- import { createHash as createHash13 } from "crypto";
19464
+ import { createHash as createHash14 } from "crypto";
19114
19465
  import { mkdir as mkdir14, readFile as readFile18, readdir as readdir6, realpath as realpath8, stat as stat13, writeFile as writeFile14 } from "fs/promises";
19115
19466
  import path19 from "path";
19116
19467
  import axios7 from "axios";
19117
19468
 
19118
19469
  // src/core/e2e-scenario-orchestrator.ts
19119
- import { createHash as createHash11 } from "crypto";
19470
+ import { createHash as createHash12 } from "crypto";
19120
19471
  import { chmod as chmod3, mkdir as mkdir12, readFile as readFile16, realpath as realpath6, rename as rename4, rm as rm6, stat as stat11, writeFile as writeFile12 } from "fs/promises";
19121
19472
  import path17 from "path";
19122
19473
 
19123
19474
  // src/core/e2e-automation-schema.ts
19124
- import { createHash as createHash6 } from "crypto";
19475
+ import { createHash as createHash7 } from "crypto";
19125
19476
  import { readFile as readFile12 } from "fs/promises";
19126
19477
  import path12 from "path";
19127
19478
  var BROWSER_ACTION_TYPES = [
@@ -19130,6 +19481,7 @@ var BROWSER_ACTION_TYPES = [
19130
19481
  "form.set_value",
19131
19482
  "form.set_date_range",
19132
19483
  "form.select_option",
19484
+ "cascader.search_select",
19133
19485
  "form.select_user",
19134
19486
  "form.set_punishment",
19135
19487
  "form.draw_signature",
@@ -19207,6 +19559,7 @@ var RESOLUTION_READ_ONLY_ACTION_TYPES = /* @__PURE__ */ new Set([
19207
19559
  "form.set_value",
19208
19560
  "form.set_date_range",
19209
19561
  "form.select_option",
19562
+ "cascader.search_select",
19210
19563
  "form.assert_value",
19211
19564
  "button.click",
19212
19565
  "wait.visible",
@@ -19247,11 +19600,17 @@ function canonicalJson(value) {
19247
19600
  }
19248
19601
  return JSON.stringify(value);
19249
19602
  }
19603
+ function containsDeferredGatePlaceholder(value) {
19604
+ if (typeof value === "string") return /^DEFERRED_GATE(?:\b|:)/i.test(value.trim());
19605
+ if (Array.isArray(value)) return value.some(containsDeferredGatePlaceholder);
19606
+ if (isRecord8(value)) return Object.values(value).some(containsDeferredGatePlaceholder);
19607
+ return false;
19608
+ }
19250
19609
  function browserAutomationStepSha256(step) {
19251
- return createHash6("sha256").update(canonicalJson(step)).digest("hex");
19610
+ return createHash7("sha256").update(canonicalJson(step)).digest("hex");
19252
19611
  }
19253
19612
  function browserAutomationDocumentSha256(document2) {
19254
- return createHash6("sha256").update(canonicalJson({
19613
+ return createHash7("sha256").update(canonicalJson({
19255
19614
  version: document2.version,
19256
19615
  scenario: document2.scenario,
19257
19616
  operation_flow: document2.operation_flow,
@@ -19638,6 +19997,7 @@ function actionIssues(action, stepKey, index, check, resolutionOutcome) {
19638
19997
  "form.set_value",
19639
19998
  "form.set_date_range",
19640
19999
  "form.select_option",
20000
+ "cascader.search_select",
19641
20001
  "form.select_user",
19642
20002
  "form.set_punishment",
19643
20003
  "form.draw_signature",
@@ -19656,6 +20016,25 @@ function actionIssues(action, stepKey, index, check, resolutionOutcome) {
19656
20016
  message: `${stepKey} action[${index}] form.set_date_range requires value=[start,end] with two non-empty strings`
19657
20017
  });
19658
20018
  }
20019
+ if (type === "cascader.search_select") {
20020
+ const value = isRecord8(action.value) ? action.value : {};
20021
+ const search = stringValue2(value.search);
20022
+ const path27 = Array.isArray(value.path) ? value.path.map(stringValue2) : [];
20023
+ if (!search || path27.length < 2 || path27.some((segment) => !segment) || path27[path27.length - 1] !== search) {
20024
+ issues.push({
20025
+ rule_id: "test_suite.automation.cascader_value_invalid",
20026
+ step_key: stepKey,
20027
+ message: `${stepKey} action[${index}] cascader.search_select requires value={search, path:[...]} with a non-empty complete path ending in search`
20028
+ });
20029
+ }
20030
+ if (isRecord8(action.target) && action.target.nth !== void 0) {
20031
+ issues.push({
20032
+ rule_id: "test_suite.automation.cascader_target_not_unique",
20033
+ step_key: stepKey,
20034
+ message: `${stepKey} action[${index}] cascader.search_select must not use target.nth; the outer semantic control must be unique`
20035
+ });
20036
+ }
20037
+ }
19659
20038
  if (type === "form.select_user" && !stringValue2(action.option)) {
19660
20039
  issues.push({
19661
20040
  rule_id: "test_suite.automation.user_option_missing",
@@ -19910,6 +20289,13 @@ function actionIssues(action, stepKey, index, check, resolutionOutcome) {
19910
20289
  message: `${stepKey} action[${index}] list.assert_record count must be a non-negative integer`
19911
20290
  });
19912
20291
  }
20292
+ if (type === "list.assert_record" && action.count === 0 && (!isRecord8(action.target) || !stringValue2(action.target.css) && !stringValue2(action.target.test_id))) {
20293
+ issues.push({
20294
+ rule_id: "test_suite.automation.list_record_absence_target_missing",
20295
+ step_key: stepKey,
20296
+ message: `${stepKey} action[${index}] list.assert_record count=0 requires target.css or target.test_id for one explicit list container`
20297
+ });
20298
+ }
19913
20299
  if (hasDynamicRuntimeId(stringValue2(action.route)) || hasDynamicRuntimeId(stringValue2(action.value))) {
19914
20300
  issues.push({
19915
20301
  rule_id: "test_suite.automation.dynamic_id_hardcoded",
@@ -19980,6 +20366,13 @@ function validateBrowserAutomationDocument(value, options = {}) {
19980
20366
  issues.push({ rule_id: "test_suite.automation.runner_invalid", step_key: stepKey, message: `${stepKey} runner must be browser_action` });
19981
20367
  continue;
19982
20368
  }
20369
+ if (containsDeferredGatePlaceholder(rawStep)) {
20370
+ issues.push({
20371
+ rule_id: "test_suite.automation.deferred_gate_placeholder",
20372
+ step_key: stepKey,
20373
+ message: `${stepKey} contains a DEFERRED_GATE placeholder and must be regenerated and reviewed before reuse`
20374
+ });
20375
+ }
19983
20376
  if (options.requiredV2StepKeys?.has(stepKey)) {
19984
20377
  const surface = stringValue2(rawStep.surface);
19985
20378
  if (!["pc", "h5"].includes(surface)) {
@@ -19997,6 +20390,21 @@ function validateBrowserAutomationDocument(value, options = {}) {
19997
20390
  message: `${stepKey} declares surface=${surface}, but the selected case is explicitly ${expectedSurface}`
19998
20391
  });
19999
20392
  }
20393
+ const viewport = isRecord8(rawStep.viewport) ? rawStep.viewport : {};
20394
+ const viewportValid = Number.isSafeInteger(viewport.width) && Number(viewport.width) >= 320 && Number(viewport.width) <= 2560 && Number.isSafeInteger(viewport.height) && Number(viewport.height) >= 320 && Number(viewport.height) <= 2560;
20395
+ if (surface === "h5" && !viewportValid) {
20396
+ issues.push({
20397
+ rule_id: "test_suite.automation.h5_viewport_missing",
20398
+ step_key: stepKey,
20399
+ message: `${stepKey} surface=h5 requires viewport.width and viewport.height integers between 320 and 2560`
20400
+ });
20401
+ } else if (rawStep.viewport !== void 0 && !viewportValid) {
20402
+ issues.push({
20403
+ rule_id: "test_suite.automation.viewport_invalid",
20404
+ step_key: stepKey,
20405
+ message: `${stepKey} viewport width and height must be integers between 320 and 2560`
20406
+ });
20407
+ }
20000
20408
  }
20001
20409
  if (!isRecord8(rawStep.page_fingerprint) || Object.keys(rawStep.page_fingerprint).length === 0) {
20002
20410
  issues.push({
@@ -20190,7 +20598,7 @@ function validateBrowserAutomationDataProfile(step, data, stepKey) {
20190
20598
  }
20191
20599
 
20192
20600
  // src/core/e2e-browser-runner.ts
20193
- import { createHash as createHash10 } from "crypto";
20601
+ import { createHash as createHash11 } from "crypto";
20194
20602
  import { chmod as chmod2, lstat as lstat3, mkdir as mkdir11, readFile as readFile15, realpath as realpath5, rename as rename3, stat as stat10, writeFile as writeFile11 } from "fs/promises";
20195
20603
  import path16 from "path";
20196
20604
  import {
@@ -20198,7 +20606,7 @@ import {
20198
20606
  } from "playwright-core";
20199
20607
 
20200
20608
  // src/core/test-suite.ts
20201
- import { createHash as createHash9, randomBytes as randomBytes3 } from "crypto";
20609
+ import { createHash as createHash10, randomBytes as randomBytes3 } from "crypto";
20202
20610
  import {
20203
20611
  copyFile,
20204
20612
  cp as cp3,
@@ -20217,7 +20625,7 @@ import path15 from "path";
20217
20625
  import { inflateSync } from "zlib";
20218
20626
 
20219
20627
  // src/core/test-fixture-contract.ts
20220
- import { createHash as createHash7 } from "crypto";
20628
+ import { createHash as createHash8 } from "crypto";
20221
20629
  function isRecord9(value) {
20222
20630
  return typeof value === "object" && value !== null && !Array.isArray(value);
20223
20631
  }
@@ -20229,7 +20637,7 @@ function canonicalJson2(value) {
20229
20637
  return JSON.stringify(value);
20230
20638
  }
20231
20639
  function fixtureManifestSha256(value) {
20232
- return createHash7("sha256").update(canonicalJson2(value)).digest("hex");
20640
+ return createHash8("sha256").update(canonicalJson2(value)).digest("hex");
20233
20641
  }
20234
20642
 
20235
20643
  // src/core/e2e-operation-lock.ts
@@ -20237,7 +20645,7 @@ import { lstat, realpath as realpath3 } from "fs/promises";
20237
20645
  import path14 from "path";
20238
20646
 
20239
20647
  // src/core/process-lock.ts
20240
- import { createHash as createHash8, randomBytes as randomBytes2 } from "crypto";
20648
+ import { createHash as createHash9, randomBytes as randomBytes2 } from "crypto";
20241
20649
  import { mkdir as mkdir9, readFile as readFile13, rename, rm as rm4, stat as stat8, writeFile as writeFile9 } from "fs/promises";
20242
20650
  import path13 from "path";
20243
20651
  var ProcessLockError = class extends Error {
@@ -20266,7 +20674,7 @@ async function readOwner(lockPath, kind) {
20266
20674
  if (Number.isSafeInteger(legacy.pid) && Number(legacy.pid) > 0 && !Number.isNaN(Date.parse(String(legacy.created_at || "")))) {
20267
20675
  return {
20268
20676
  version: 1,
20269
- owner_token: createHash8("sha256").update(content).digest("hex").slice(0, 32),
20677
+ owner_token: createHash9("sha256").update(content).digest("hex").slice(0, 32),
20270
20678
  pid: Number(legacy.pid),
20271
20679
  created_at: String(legacy.created_at)
20272
20680
  };
@@ -20682,6 +21090,9 @@ function runtimeRoute(runtimeUrl) {
20682
21090
  params: hashRoute?.searchParams || url.searchParams
20683
21091
  };
20684
21092
  }
21093
+ function normalizeRuntimeWorkspace(workspace) {
21094
+ return workspace.trim().replace(/^w:/i, "");
21095
+ }
20685
21096
  async function exists3(filePath) {
20686
21097
  try {
20687
21098
  await stat9(filePath);
@@ -21208,7 +21619,7 @@ async function validateScenarioAutomation(scenarioDir, steps, selectedCaseIds) {
21208
21619
  suggestion: "Run test-suite automation init and compile. Do not hand-edit runner=browser_action or fabricate compile metadata."
21209
21620
  });
21210
21621
  }
21211
- const currentCaseStepsSha256 = createHash9("sha256").update(await readFile14(path15.join(scenarioDir, "case_steps.csv"))).digest("hex");
21622
+ const currentCaseStepsSha256 = createHash10("sha256").update(await readFile14(path15.join(scenarioDir, "case_steps.csv"))).digest("hex");
21212
21623
  if (automation.compile.case_steps_sha256 !== currentCaseStepsSha256) {
21213
21624
  fail(`${automationPath}: compiled case_steps.csv hash does not match the current scenario`, {
21214
21625
  rule_id: "test_suite.automation.compiled_case_steps_stale",
@@ -21301,7 +21712,7 @@ async function automationStatus(options) {
21301
21712
  message: `runner contract ${String(document2.compile.contract_version)} is not compatible with v2`
21302
21713
  });
21303
21714
  }
21304
- const caseStepsSha256 = createHash9("sha256").update(await readFile14(path15.join(scenarioDir, "case_steps.csv"))).digest("hex");
21715
+ const caseStepsSha256 = createHash10("sha256").update(await readFile14(path15.join(scenarioDir, "case_steps.csv"))).digest("hex");
21305
21716
  if (document2.compile.case_steps_sha256 !== caseStepsSha256) {
21306
21717
  changedInputs.push({
21307
21718
  rule_id: "test_suite.automation.compiled_case_steps_stale",
@@ -21383,9 +21794,9 @@ async function automationStatus(options) {
21383
21794
  }
21384
21795
  async function readAutomationCheckpoint(checkpoint) {
21385
21796
  const checkpointPath = path15.resolve(checkpoint);
21386
- let record;
21797
+ let record2;
21387
21798
  try {
21388
- record = JSON.parse(await readText(checkpointPath));
21799
+ record2 = JSON.parse(await readText(checkpointPath));
21389
21800
  } catch (error) {
21390
21801
  fail(`${checkpointPath}: automation checkpoint is not readable JSON`, {
21391
21802
  rule_id: "test_suite.automation.checkpoint_invalid",
@@ -21393,13 +21804,13 @@ async function readAutomationCheckpoint(checkpoint) {
21393
21804
  suggestion: error instanceof Error ? error.message : String(error)
21394
21805
  });
21395
21806
  }
21396
- if (record.version !== 1 || record.kind !== "bpmax_e2e_automation_checkpoint" || !record.scenario_id || !record.case_id || !record.case_step_id) {
21807
+ if (record2.version !== 1 || record2.kind !== "bpmax_e2e_automation_checkpoint" || !record2.scenario_id || !record2.case_id || !record2.case_step_id) {
21397
21808
  fail(`${checkpointPath}: invalid automation checkpoint binding`, {
21398
21809
  rule_id: "test_suite.automation.checkpoint_invalid",
21399
21810
  path: checkpointPath
21400
21811
  });
21401
21812
  }
21402
- return { path: checkpointPath, record };
21813
+ return { path: checkpointPath, record: record2 };
21403
21814
  }
21404
21815
  async function automationCheckpoint(options) {
21405
21816
  const checkpointPath = path15.resolve(options.checkpoint);
@@ -21419,7 +21830,7 @@ async function automationCheckpoint(options) {
21419
21830
  }
21420
21831
  }
21421
21832
  const now = (/* @__PURE__ */ new Date()).toISOString();
21422
- const record2 = {
21833
+ const record3 = {
21423
21834
  version: 1,
21424
21835
  kind: "bpmax_e2e_automation_checkpoint",
21425
21836
  scenario_id: options.scenario,
@@ -21432,44 +21843,44 @@ async function automationCheckpoint(options) {
21432
21843
  updated_at: now
21433
21844
  };
21434
21845
  await mkdir10(path15.dirname(checkpointPath), { recursive: true });
21435
- await writeAtomicJson(checkpointPath, record2);
21436
- return { ok: true, checkpoint: checkpointPath, ...record2 };
21846
+ await writeAtomicJson(checkpointPath, record3);
21847
+ return { ok: true, checkpoint: checkpointPath, ...record3 };
21437
21848
  }
21438
- const { record } = await readAutomationCheckpoint(checkpointPath);
21849
+ const { record: record2 } = await readAutomationCheckpoint(checkpointPath);
21439
21850
  if (options.operation === "status") {
21440
21851
  return {
21441
21852
  ok: true,
21442
21853
  checkpoint: checkpointPath,
21443
- ...record,
21444
- resume_allowed: !record.mutation || ["committed", "not_committed"].includes(record.mutation_state)
21854
+ ...record2,
21855
+ resume_allowed: !record2.mutation || ["committed", "not_committed"].includes(record2.mutation_state)
21445
21856
  };
21446
21857
  }
21447
21858
  if (options.operation === "resolve") {
21448
- if (!record.mutation || record.mutation_state !== "prepared" || !options.outcome) {
21859
+ if (!record2.mutation || record2.mutation_state !== "prepared" || !options.outcome) {
21449
21860
  fail(`${checkpointPath}: resolve requires a prepared mutation and committed|not_committed outcome`, {
21450
21861
  rule_id: "test_suite.automation.checkpoint_resolution_invalid",
21451
21862
  path: checkpointPath
21452
21863
  });
21453
21864
  }
21454
- record.status = "resolved";
21455
- record.mutation_state = options.outcome;
21456
- record.updated_at = (/* @__PURE__ */ new Date()).toISOString();
21457
- await writeAtomicJson(checkpointPath, record);
21458
- return { ok: true, checkpoint: checkpointPath, ...record, resume_allowed: true };
21865
+ record2.status = "resolved";
21866
+ record2.mutation_state = options.outcome;
21867
+ record2.updated_at = (/* @__PURE__ */ new Date()).toISOString();
21868
+ await writeAtomicJson(checkpointPath, record2);
21869
+ return { ok: true, checkpoint: checkpointPath, ...record2, resume_allowed: true };
21459
21870
  }
21460
- if (record.mutation && record.mutation_state === "prepared") {
21871
+ if (record2.mutation && record2.mutation_state === "prepared") {
21461
21872
  if (!options.outcome) {
21462
21873
  fail(`${checkpointPath}: mutation completion requires committed|not_committed readback`, {
21463
21874
  rule_id: "test_suite.automation.checkpoint_mutation_resolution_required",
21464
21875
  path: checkpointPath
21465
21876
  });
21466
21877
  }
21467
- record.mutation_state = options.outcome;
21878
+ record2.mutation_state = options.outcome;
21468
21879
  }
21469
- record.status = "complete";
21470
- record.updated_at = (/* @__PURE__ */ new Date()).toISOString();
21471
- await writeAtomicJson(checkpointPath, record);
21472
- return { ok: true, checkpoint: checkpointPath, ...record, resume_allowed: true };
21880
+ record2.status = "complete";
21881
+ record2.updated_at = (/* @__PURE__ */ new Date()).toISOString();
21882
+ await writeAtomicJson(checkpointPath, record2);
21883
+ return { ok: true, checkpoint: checkpointPath, ...record2, resume_allowed: true };
21473
21884
  }
21474
21885
  function validateReadableCaseContent(filePath, caseId, row) {
21475
21886
  for (const field of ["title", "preconditions", "config_basis", "prep_data", "expected_result", "test_data"]) {
@@ -22042,10 +22453,18 @@ async function initScenarioAutomationCompile(options) {
22042
22453
  expectedSurfaceByStepKey: expectedSurfaceByStep(cases, deterministicSteps)
22043
22454
  });
22044
22455
  const metadata = validation.document ? validateBrowserAutomationCompileMetadataDetailed(validation.document) : { issues: [], warnings: [] };
22045
- const currentCaseStepsSha256 = createHash9("sha256").update(await readFile14(stepsPath)).digest("hex");
22456
+ const currentCaseStepsSha256 = createHash10("sha256").update(await readFile14(stepsPath)).digest("hex");
22046
22457
  const hashesMatch = validation.document?.compile.case_steps_sha256 === currentCaseStepsSha256 && validation.document?.compile.compiled_suite_sha256 === await compiledScenarioSha256(scenarioDir);
22047
- if (validation.document && validation.issues.length === 0 && metadata.issues.length === 0 && hashesMatch) {
22048
- reusableStepKeys = new Set(Object.keys(validation.document.steps));
22458
+ if (validation.document && hashesMatch) {
22459
+ const globalInvalid = [...validation.issues, ...metadata.issues].some((issue3) => !issue3.step_key);
22460
+ if (!globalInvalid) {
22461
+ const invalidStepKeys = new Set(
22462
+ [...validation.issues, ...metadata.issues].map((issue3) => issue3.step_key).filter((stepKey) => Boolean(stepKey))
22463
+ );
22464
+ reusableStepKeys = new Set(
22465
+ Object.keys(validation.document.steps).filter((stepKey) => !invalidStepKeys.has(stepKey))
22466
+ );
22467
+ }
22049
22468
  }
22050
22469
  } catch {
22051
22470
  reusableStepKeys = /* @__PURE__ */ new Set();
@@ -22269,7 +22688,7 @@ async function compileScenarioAutomationUnlocked(options) {
22269
22688
  suggestion: "Complete the pre-run read-only discovery or platform-source review; do not start a formal run or click through the case manually."
22270
22689
  });
22271
22690
  }
22272
- const sourceSha256 = createHash9("sha256").update(await readFile14(sourcePath)).digest("hex");
22691
+ const sourceSha256 = createHash10("sha256").update(await readFile14(sourcePath)).digest("hex");
22273
22692
  const nextSteps = steps.map((step) => requiredKeys.has(automationStepKey(step.case_id, step.step_id)) ? { ...step, runner: "browser_action" } : step);
22274
22693
  const nextStepsText = csvText(CASE_STEP_FIELDS, nextSteps);
22275
22694
  const compiledAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -22289,7 +22708,7 @@ async function compileScenarioAutomationUnlocked(options) {
22289
22708
  source_sha256: sourceSha256,
22290
22709
  source_suite_sha256: currentSourceSha256,
22291
22710
  compiled_suite_sha256: await compiledScenarioSha256(scenarioDir, nextStepsText),
22292
- case_steps_sha256: createHash9("sha256").update(nextStepsText).digest("hex"),
22711
+ case_steps_sha256: createHash10("sha256").update(nextStepsText).digest("hex"),
22293
22712
  automation_sha256: "",
22294
22713
  compiled_at: compiledAt,
22295
22714
  formal_execution_performed: false,
@@ -22353,7 +22772,7 @@ async function assertAutomationDraftRoot(root) {
22353
22772
  }
22354
22773
  }
22355
22774
  async function automationCompileSourceSha256(scenarioDir) {
22356
- const hash = createHash9("sha256");
22775
+ const hash = createHash10("sha256");
22357
22776
  for (const file of ["README.md", "cases.csv", "case_steps.csv"]) {
22358
22777
  hash.update(file);
22359
22778
  hash.update("\0");
@@ -22363,7 +22782,7 @@ async function automationCompileSourceSha256(scenarioDir) {
22363
22782
  return hash.digest("hex");
22364
22783
  }
22365
22784
  async function compiledScenarioSha256(scenarioDir, caseStepsText) {
22366
- const hash = createHash9("sha256");
22785
+ const hash = createHash10("sha256");
22367
22786
  for (const file of ["README.md", "cases.csv"]) {
22368
22787
  hash.update(file);
22369
22788
  hash.update("\0");
@@ -22626,8 +23045,8 @@ async function applyReviewedAutomationRepairUnlocked(options) {
22626
23045
  const previousAutomationText = await readText(runAutomationPath);
22627
23046
  const nextAutomationText = `${JSON.stringify(candidate, null, 2)}
22628
23047
  `;
22629
- const previousAutomationSha256 = createHash9("sha256").update(previousAutomationText).digest("hex");
22630
- const nextAutomationSha256 = createHash9("sha256").update(nextAutomationText).digest("hex");
23048
+ const previousAutomationSha256 = createHash10("sha256").update(previousAutomationText).digest("hex");
23049
+ const nextAutomationSha256 = createHash10("sha256").update(nextAutomationText).digest("hex");
22631
23050
  const reviewPath = await repairRealpath(
22632
23051
  path15.join(candidateScenarioDir, "review.json"),
22633
23052
  "test_suite.automation.repair_candidate_invalid",
@@ -22643,7 +23062,7 @@ async function applyReviewedAutomationRepairUnlocked(options) {
22643
23062
  }
22644
23063
  await assertAutomationRepairGuardSources(guard);
22645
23064
  const expectedReceiptText = automationRepairReceiptText(manifestPath, manifest, guard);
22646
- if (createHash9("sha256").update(expectedReceiptText).digest("hex") !== guard.receipt_sha256) {
23065
+ if (createHash10("sha256").update(expectedReceiptText).digest("hex") !== guard.receipt_sha256) {
22647
23066
  fail("anchored automation repair receipt hash is inconsistent", {
22648
23067
  rule_id: "test_suite.automation.repair_receipt_invalid",
22649
23068
  path: guard.receipt
@@ -22719,7 +23138,7 @@ async function applyReviewedAutomationRepairUnlocked(options) {
22719
23138
  anchored_manifest_revision: (manifest.revision ?? 0) + 1
22720
23139
  };
22721
23140
  const repairReceiptText = automationRepairReceiptText(manifestPath, manifest, guard);
22722
- guard.receipt_sha256 = createHash9("sha256").update(repairReceiptText).digest("hex");
23141
+ guard.receipt_sha256 = createHash10("sha256").update(repairReceiptText).digest("hex");
22723
23142
  manifest.automation_repair_guard = guard;
22724
23143
  await writeExecutionManifest(manifestPath, manifest, true);
22725
23144
  await writeAtomicText(runAutomationPath, nextAutomationText);
@@ -22806,7 +23225,7 @@ async function consumeReviewedAutomationRepair(options) {
22806
23225
  path: automationPath
22807
23226
  });
22808
23227
  }
22809
- const automationSha256 = createHash9("sha256").update(await readFile14(automationPath)).digest("hex");
23228
+ const automationSha256 = createHash10("sha256").update(await readFile14(automationPath)).digest("hex");
22810
23229
  const guard = manifest.automation_repair_guard;
22811
23230
  if (!guard && manifest.automation_hash === automationSha256) {
22812
23231
  return { ok: true, consumed: false, automation_sha256: automationSha256 };
@@ -22832,7 +23251,7 @@ async function consumeReviewedAutomationRepair(options) {
22832
23251
  });
22833
23252
  }
22834
23253
  const expectedReceiptText = automationRepairReceiptText(manifestPath, manifest, guard);
22835
- if (createHash9("sha256").update(expectedReceiptText).digest("hex") !== guard.receipt_sha256 || await readText(guard.receipt) !== expectedReceiptText) {
23254
+ if (createHash10("sha256").update(expectedReceiptText).digest("hex") !== guard.receipt_sha256 || await readText(guard.receipt) !== expectedReceiptText) {
22836
23255
  fail("automation repair receipt content does not match the manifest anchor", {
22837
23256
  rule_id: "test_suite.automation.repair_receipt_invalid",
22838
23257
  path: guard.receipt
@@ -22862,7 +23281,7 @@ async function consumeReviewedAutomationRepair(options) {
22862
23281
  });
22863
23282
  }
22864
23283
  async function suiteHash(scenarioDir, includeAutomation = true) {
22865
- const hash = createHash9("sha256");
23284
+ const hash = createHash10("sha256");
22866
23285
  hash.update(await readText(path15.join(scenarioDir, "README.md")));
22867
23286
  hash.update(await readText(path15.join(scenarioDir, "cases.csv")));
22868
23287
  hash.update(await readText(path15.join(scenarioDir, "case_steps.csv")));
@@ -22873,14 +23292,14 @@ async function suiteHash(scenarioDir, includeAutomation = true) {
22873
23292
  return hash.digest("hex");
22874
23293
  }
22875
23294
  async function v2ConfirmationAssetHash(scenarioDir) {
22876
- const hash = createHash9("sha256");
23295
+ const hash = createHash10("sha256");
22877
23296
  hash.update(await suiteHash(scenarioDir));
22878
23297
  const reviewPath = path15.join(scenarioDir, "review.json");
22879
23298
  if (await exists3(reviewPath)) hash.update(await readText(reviewPath));
22880
23299
  return hash.digest("hex");
22881
23300
  }
22882
23301
  function v2ConfirmationDigest(value) {
22883
- return createHash9("sha256").update(JSON.stringify(value)).digest("hex");
23302
+ return createHash10("sha256").update(JSON.stringify(value)).digest("hex");
22884
23303
  }
22885
23304
  function normalizedCaseIds(caseIds = []) {
22886
23305
  return [...new Set(caseIds.map((id) => id.trim()).filter(Boolean))].sort();
@@ -23059,7 +23478,7 @@ async function validateV2Confirmation(options) {
23059
23478
  async function automationFileHash(scenarioDir) {
23060
23479
  const automationPath = path15.join(scenarioDir, "automation.json");
23061
23480
  if (!await exists3(automationPath)) return void 0;
23062
- return createHash9("sha256").update(await readFile14(automationPath)).digest("hex");
23481
+ return createHash10("sha256").update(await readFile14(automationPath)).digest("hex");
23063
23482
  }
23064
23483
  async function writePromotionReceipt(sourceScenarioDir, promotedScenarioDir, finalScenarioDir = promotedScenarioDir) {
23065
23484
  const automationHash = await automationFileHash(promotedScenarioDir);
@@ -23103,7 +23522,7 @@ async function validatePromotionReceipt(scenarioDir) {
23103
23522
  }
23104
23523
  }
23105
23524
  function executionManifestHash(manifest) {
23106
- return createHash9("sha256").update(JSON.stringify(manifest)).digest("hex");
23525
+ return createHash10("sha256").update(JSON.stringify(manifest)).digest("hex");
23107
23526
  }
23108
23527
  function executionManifestIntegrityPaths(manifestPath) {
23109
23528
  const resolved = path15.resolve(manifestPath);
@@ -23135,11 +23554,11 @@ async function readExecutionManifestIntegrityJournal(journalPath, transaction) {
23135
23554
  const finalIncompleteTail = index === lines.length - 1 && !hasTrailingNewline;
23136
23555
  const previous = records.at(-1);
23137
23556
  if (!finalIncompleteTail || !transaction || transaction.previous_revision !== (previous?.revision ?? -1) || transaction.previous_hash !== (previous?.hash ?? null)) throw new Error("invalid journal record");
23138
- await writeFile10(journalPath, records.length ? `${records.map((record) => JSON.stringify(record)).join("\n")}
23557
+ await writeFile10(journalPath, records.length ? `${records.map((record2) => JSON.stringify(record2)).join("\n")}
23139
23558
  ` : "", "utf8");
23140
23559
  }
23141
23560
  }
23142
- if (records.some((record, index) => record.version !== 1 || !Number.isInteger(record.revision) || !/^[a-f0-9]{64}$/.test(record.hash) || index > 0 && record.revision !== records[index - 1].revision + 1)) throw new Error("invalid journal sequence");
23561
+ if (records.some((record2, index) => record2.version !== 1 || !Number.isInteger(record2.revision) || !/^[a-f0-9]{64}$/.test(record2.hash) || index > 0 && record2.revision !== records[index - 1].revision + 1)) throw new Error("invalid journal sequence");
23143
23562
  return records;
23144
23563
  } catch {
23145
23564
  fail("execution manifest integrity journal is invalid", {
@@ -23149,7 +23568,7 @@ async function readExecutionManifestIntegrityJournal(journalPath, transaction) {
23149
23568
  }
23150
23569
  }
23151
23570
  async function appendExecutionManifestIntegrityRecord(journalPath, revision, hash) {
23152
- const record = {
23571
+ const record2 = {
23153
23572
  version: 1,
23154
23573
  revision,
23155
23574
  hash,
@@ -23160,7 +23579,7 @@ async function appendExecutionManifestIntegrityRecord(journalPath, revision, has
23160
23579
  const content = await readText(journalPath);
23161
23580
  if (content && !/(?:\r?\n)$/.test(content)) separator = "\n";
23162
23581
  }
23163
- await writeFile10(journalPath, `${separator}${JSON.stringify(record)}
23582
+ await writeFile10(journalPath, `${separator}${JSON.stringify(record2)}
23164
23583
  `, { encoding: "utf8", flag: "a" });
23165
23584
  }
23166
23585
  async function readExecutionManifestTransaction(transactionPath) {
@@ -23734,22 +24153,22 @@ async function assertExecutionPreconditionRecord(manifest, manifestPath, require
23734
24153
  path: recordPath
23735
24154
  });
23736
24155
  }
23737
- let record;
24156
+ let record2;
23738
24157
  try {
23739
- record = JSON.parse(await readText(recordPath));
24158
+ record2 = JSON.parse(await readText(recordPath));
23740
24159
  } catch {
23741
24160
  fail("precondition record is not valid JSON", {
23742
24161
  rule_id: "test_suite.run.precondition_invalid",
23743
24162
  path: recordPath
23744
24163
  });
23745
24164
  }
23746
- if (record.schema_version !== 1 || record.kind !== "bpmax_e2e_precondition_record" || record.state !== anchor.state || record.run_id !== manifest.run_id || record.evidence_nonce !== manifest.evidence_nonce || record.scenario_id !== manifest.scenario_id || record.case_id !== manifest.case_id || record.profile !== manifest.profile || record.created_at !== manifest.started_at) {
24165
+ if (record2.schema_version !== 1 || record2.kind !== "bpmax_e2e_precondition_record" || record2.state !== anchor.state || record2.run_id !== manifest.run_id || record2.evidence_nonce !== manifest.evidence_nonce || record2.scenario_id !== manifest.scenario_id || record2.case_id !== manifest.case_id || record2.profile !== manifest.profile || record2.created_at !== manifest.started_at) {
23747
24166
  fail("precondition record identity does not match the current execution manifest", {
23748
24167
  rule_id: "test_suite.run.precondition_binding_mismatch",
23749
24168
  path: recordPath
23750
24169
  });
23751
24170
  }
23752
- if (record.state !== "passed") {
24171
+ if (record2.state !== "passed") {
23753
24172
  if (requirePassed) {
23754
24173
  fail("formal execution is blocked until the current-run precondition checks are recorded as passed", {
23755
24174
  rule_id: "test_suite.run.precondition_pending",
@@ -23757,12 +24176,12 @@ async function assertExecutionPreconditionRecord(manifest, manifestPath, require
23757
24176
  suggestion: `Run \`bpmax-cli test-suite run precondition --manifest ${manifestPath} --evidence <current-run-precondition-evidence.json> --format json\` after checking the real test data and environment.`
23758
24177
  });
23759
24178
  }
23760
- return record;
24179
+ return record2;
23761
24180
  }
23762
- const checks = preconditionChecks(record.checks);
23763
- const evidenceValue = String(record.evidence || "");
23764
- const evidenceSha256 = String(record.evidence_sha256 || "");
23765
- if (!checks || !evidenceValue || !/^[a-f0-9]{64}$/.test(evidenceSha256) || record.recorded_at !== anchor.recorded_at || evidenceValue !== anchor.evidence || evidenceSha256 !== anchor.evidence_sha256) {
24181
+ const checks = preconditionChecks(record2.checks);
24182
+ const evidenceValue = String(record2.evidence || "");
24183
+ const evidenceSha256 = String(record2.evidence_sha256 || "");
24184
+ if (!checks || !evidenceValue || !/^[a-f0-9]{64}$/.test(evidenceSha256) || record2.recorded_at !== anchor.recorded_at || evidenceValue !== anchor.evidence || evidenceSha256 !== anchor.evidence_sha256) {
23766
24185
  fail("passed precondition record is missing its manifest-anchored evidence and checks", {
23767
24186
  rule_id: "test_suite.run.precondition_invalid",
23768
24187
  path: recordPath
@@ -23775,7 +24194,7 @@ async function assertExecutionPreconditionRecord(manifest, manifestPath, require
23775
24194
  path: recordPath
23776
24195
  });
23777
24196
  }
23778
- return record;
24197
+ return record2;
23779
24198
  }
23780
24199
  async function evidenceTexts(evidencePath) {
23781
24200
  const info = await stat9(evidencePath);
@@ -23814,6 +24233,8 @@ async function browserEvidenceScreenshots(manifest, manifestPath, step, evidence
23814
24233
  const jsonRecords = await evidenceJsonRecords(evidencePath);
23815
24234
  const screenshotPaths = [];
23816
24235
  let matchedRecord = false;
24236
+ let workspaceMismatch;
24237
+ let workspaceCompatibleRecord = false;
23817
24238
  for (const { value, source } of jsonRecords) {
23818
24239
  if (recordFilter && !recordFilter(value)) continue;
23819
24240
  if (value.run_id !== manifest.run_id || value.evidence_nonce !== manifest.evidence_nonce) continue;
@@ -23832,7 +24253,15 @@ async function browserEvidenceScreenshots(manifest, manifestPath, step, evidence
23832
24253
  if (runtimeEnvironment === "profile" && profileOrigin && runtimeOrigin !== profileOrigin) continue;
23833
24254
  if (runtimeEnvironment === "local-browser" && !/^(?:localhost|127\.0\.0\.1|\[::1\])$/.test(parsed.url.hostname)) continue;
23834
24255
  const workspaceMatch = /^\/w:([^/]+)(?:\/|$)/i.exec(parsed.path);
23835
- if (manifest.workspace && workspaceMatch && decodeURIComponent(workspaceMatch[1]) !== manifest.workspace) continue;
24256
+ if (manifest.workspace && workspaceMatch) {
24257
+ const manifestWorkspace = normalizeRuntimeWorkspace(manifest.workspace);
24258
+ const runtimeWorkspace = normalizeRuntimeWorkspace(decodeURIComponent(workspaceMatch[1]));
24259
+ if (runtimeWorkspace !== manifestWorkspace) {
24260
+ workspaceMismatch ??= { manifest: manifestWorkspace, runtime: runtimeWorkspace };
24261
+ continue;
24262
+ }
24263
+ }
24264
+ workspaceCompatibleRecord = true;
23836
24265
  } catch {
23837
24266
  continue;
23838
24267
  }
@@ -23864,6 +24293,12 @@ async function browserEvidenceScreenshots(manifest, manifestPath, step, evidence
23864
24293
  screenshotPaths.push(screenshotPath);
23865
24294
  }
23866
24295
  if (!matchedRecord) {
24296
+ if (workspaceMismatch && !workspaceCompatibleRecord) {
24297
+ fail(
24298
+ `browser ${expectedResult} evidence workspace mismatch: manifest workspace "${workspaceMismatch.manifest}" does not match runtime URL workspace "${workspaceMismatch.runtime}"`,
24299
+ { rule_id: "test_suite.run.workspace_mismatch", path: evidencePath }
24300
+ );
24301
+ }
23867
24302
  fail(
23868
24303
  `browser ${expectedResult} evidence must match the current case/step and include browser_verified=true, runtime_url, a valid current-run screenshot, and result-aligned assertions`,
23869
24304
  { rule_id: "test_suite.run.unexecuted_evidence", path: evidencePath }
@@ -23913,7 +24348,7 @@ async function assertRunnerEvidenceFileManifest(manifest, manifestPath, evidence
23913
24348
  await assertCurrentRunPathScope(path15.dirname(manifestPath), artifactPath, "runner evidence artifact must stay inside the current report run directory");
23914
24349
  await assertCurrentRunArtifact(manifest, artifactPath);
23915
24350
  const content = await readFile14(artifactPath);
23916
- if (entry.sha256 !== createHash9("sha256").update(content).digest("hex") || Number(entry.size) !== content.length) {
24351
+ if (entry.sha256 !== createHash10("sha256").update(content).digest("hex") || Number(entry.size) !== content.length) {
23917
24352
  fail("runner evidence artifact does not match its CLI-generated evidence-files.json hash record", {
23918
24353
  rule_id: "test_suite.run.resolution_source_invalid",
23919
24354
  path: artifactPath
@@ -24223,6 +24658,47 @@ async function previousBrowserScreenshotHashes(manifest, step) {
24223
24658
  }
24224
24659
  return hashes;
24225
24660
  }
24661
+ async function assertBrowserActionViewportEvidence(manifest, manifestPath, step, evidencePath) {
24662
+ if (step.runner !== "browser_action" || !manifest.automation_file) return;
24663
+ const automation = await loadBrowserAutomation(path15.resolve(manifest.automation_file));
24664
+ const definition = automation.steps[automationStepKey(step.case_id, step.step_id)];
24665
+ const expected = definition?.viewport;
24666
+ if (!expected) return;
24667
+ const records = await evidenceJsonRecords(evidencePath);
24668
+ const boundRecords = records.filter(({ value }) => value.run_id === manifest.run_id && value.evidence_nonce === manifest.evidence_nonce && value.case_id === step.case_id && value.case_step_id === step.step_id);
24669
+ if (boundRecords.length === 0) return;
24670
+ for (const { value, source } of boundRecords) {
24671
+ const viewport = asRecord(value.viewport);
24672
+ if (viewport.width !== expected.width || viewport.height !== expected.height) {
24673
+ fail("browser_action viewport evidence must match the reviewed automation step viewport", {
24674
+ rule_id: Object.keys(viewport).length === 0 ? "test_suite.run.viewport_evidence_missing" : "test_suite.run.viewport_evidence_mismatch",
24675
+ path: source
24676
+ });
24677
+ }
24678
+ const domSnapshot = typeof value.dom_snapshot === "string" ? value.dom_snapshot.trim() : "";
24679
+ if (!domSnapshot) {
24680
+ fail("browser_action viewport evidence requires a DOM snapshot with actual inner dimensions", {
24681
+ rule_id: "test_suite.run.viewport_evidence_missing",
24682
+ path: source
24683
+ });
24684
+ }
24685
+ const domPath = path15.resolve(path15.dirname(source), domSnapshot);
24686
+ await assertCurrentRunPathScope(path15.dirname(manifestPath), domPath, "browser viewport DOM evidence must stay inside the current report run directory");
24687
+ await assertCurrentRunArtifact(manifest, domPath);
24688
+ let domViewport;
24689
+ try {
24690
+ domViewport = asRecord(asRecord(JSON.parse(await readText(domPath))).viewport);
24691
+ } catch {
24692
+ domViewport = {};
24693
+ }
24694
+ if (domViewport.width !== expected.width || domViewport.height !== expected.height) {
24695
+ fail("browser_action DOM viewport must match the reviewed automation step and runner evidence", {
24696
+ rule_id: Object.keys(domViewport).length === 0 ? "test_suite.run.viewport_evidence_missing" : "test_suite.run.viewport_evidence_mismatch",
24697
+ path: domPath
24698
+ });
24699
+ }
24700
+ }
24701
+ }
24226
24702
  async function assertFormalExecutionEvidence(manifest, manifestPath, step, evidencePath) {
24227
24703
  const texts = await evidenceTexts(evidencePath);
24228
24704
  const joined = texts.join("\n");
@@ -24289,6 +24765,7 @@ async function assertFormalExecutionEvidence(manifest, manifestPath, step, evide
24289
24765
  }
24290
24766
  }
24291
24767
  if (step.runner === "browser" || step.runner === "browser_action" || step.runner === "e2e_create_page") {
24768
+ await assertBrowserActionViewportEvidence(manifest, manifestPath, step, evidencePath);
24292
24769
  const screenshots = await browserEvidenceScreenshots(manifest, manifestPath, step, evidencePath);
24293
24770
  const previousHashes = await previousBrowserScreenshotHashes(manifest, step);
24294
24771
  for (const screenshot of screenshots) {
@@ -24299,22 +24776,46 @@ async function assertFormalExecutionEvidence(manifest, manifestPath, step, evide
24299
24776
  }
24300
24777
  if (step.runner === "observe") {
24301
24778
  let validObservation = false;
24302
- for (const { value, source } of jsonRecords) {
24303
- if (value.run_id !== manifest.run_id || value.evidence_nonce !== manifest.evidence_nonce) continue;
24304
- if (value.case_id !== step.case_id || value.case_step_id !== step.step_id) continue;
24305
- const observed = value.observed === true || ["passed", "observed", "verified"].includes(String(value.status || ""));
24779
+ const boundObservationRecords = jsonRecords.filter(({ value }) => value.run_id === manifest.run_id && value.evidence_nonce === manifest.evidence_nonce && value.case_id === step.case_id && value.case_step_id === step.step_id);
24780
+ const observeRecords = boundObservationRecords.filter(({ value }) => value.kind === "bpmax_e2e_observe_evidence");
24781
+ if (observeRecords.length === 0) {
24782
+ fail("observe evidence kind must be bpmax_e2e_observe_evidence", {
24783
+ rule_id: "test_suite.run.observe_kind_invalid",
24784
+ path: evidencePath,
24785
+ suggestion: "Use the observe evidence JSON schema documented in bpmax-e2e-flow-test-operator/references/ai-test-suite.md."
24786
+ });
24787
+ }
24788
+ for (const { value, source } of observeRecords) {
24789
+ if (String(value.status || "").toLowerCase() !== "observed") {
24790
+ fail("observe evidence status must be observed; manifest PASS is recorded separately by test-suite run record", {
24791
+ rule_id: "test_suite.run.observe_status_invalid",
24792
+ path: source
24793
+ });
24794
+ }
24795
+ if (value.observed !== true) {
24796
+ fail("observe evidence observed must be true", { rule_id: "test_suite.run.observe_flag_missing", path: source });
24797
+ }
24306
24798
  const assertions = Array.isArray(value.assertions) ? value.assertions.map(asRecord).filter((assertion) => Object.keys(assertion).length > 0) : [];
24307
24799
  const sourceEvidence = typeof value.source_evidence === "string" ? value.source_evidence : "";
24308
24800
  const sourceCaseStepId = typeof value.source_case_step_id === "string" ? value.source_case_step_id : "";
24309
24801
  const declaredSource = step.input_data.match(OBSERVE_SOURCE_STEP_RE);
24310
- if (!observed || assertions.length === 0 || !assertions.every((assertion) => assertion.passed === true) || !sourceEvidence || !declaredSource || sourceCaseStepId !== `${declaredSource[1]}/${declaredSource[2]}`) continue;
24802
+ if (assertions.length === 0 || !assertions.every((assertion) => assertion.passed === true)) fail("observe evidence assertions must be non-empty and all passed=true", { rule_id: "test_suite.run.observe_assertions_invalid", path: source });
24803
+ if (!declaredSource || sourceCaseStepId !== `${declaredSource[1]}/${declaredSource[2]}`) {
24804
+ fail("observe evidence source_case_step_id must match the source declared by the current step", { rule_id: "test_suite.run.observe_source_binding_invalid", path: source });
24805
+ }
24806
+ if (!sourceEvidence) fail("observe evidence source_evidence must name the earlier registered evidence file", { rule_id: "test_suite.run.observe_source_missing", path: source });
24311
24807
  await assertCurrentRunArtifact(manifest, source);
24312
24808
  const sourcePath = path15.resolve(path15.dirname(source), sourceEvidence);
24313
24809
  const runDir = path15.dirname(path15.resolve(manifestPath));
24314
24810
  if (!pathInside(runDir, sourcePath)) {
24315
24811
  fail("observe source_evidence must stay inside the current report run directory", { rule_id: "test_suite.run.evidence_scope", path: sourcePath });
24316
24812
  }
24317
- if (!await exists3(sourcePath) || !(await stat9(sourcePath)).isFile()) continue;
24813
+ if (!await exists3(sourcePath) || !(await stat9(sourcePath)).isFile()) {
24814
+ fail("observe source_evidence must resolve to an existing regular file", {
24815
+ rule_id: "test_suite.run.observe_source_missing",
24816
+ path: sourcePath
24817
+ });
24818
+ }
24318
24819
  const [realRunDir, realSourcePath] = await Promise.all([realpath4(runDir), realpath4(sourcePath)]);
24319
24820
  if (!pathInside(realRunDir, realSourcePath)) {
24320
24821
  fail("observe source_evidence must stay inside the current report run directory", { rule_id: "test_suite.run.evidence_scope", path: sourcePath });
@@ -24448,7 +24949,7 @@ function manifestCurrentCaseId(manifest) {
24448
24949
  function activeRunLeaseKey(options) {
24449
24950
  const origin = String(options.profileOrigin || "").trim().replace(/\/+$/, "").toLowerCase();
24450
24951
  const stableScope = origin ? `origin:${origin}\0workspace:${options.workspace || ""}\0scenario:${options.scenarioId}` : `fallback:${options.scenarioRealpath}\0profile:${options.profile}\0scenario:${options.scenarioId}`;
24451
- return createHash9("sha256").update(stableScope).digest("hex");
24952
+ return createHash10("sha256").update(stableScope).digest("hex");
24452
24953
  }
24453
24954
  function activeRunLeaseDir(options) {
24454
24955
  return options.profileOrigin ? path15.join(getConfigDir(), "e2e-active-runs", options.key) : path15.join(path15.dirname(options.scenarioRealpath), ".bpmax-active-runs", options.key);
@@ -24745,7 +25246,7 @@ async function startTestSuiteRunUnlocked(options) {
24745
25246
  suite_hash_mode: "semantic_v2",
24746
25247
  ...hasAutomation ? {
24747
25248
  automation_file: path15.resolve(runAutomationPath),
24748
- automation_hash: createHash9("sha256").update(await readFile14(runAutomationPath)).digest("hex")
25249
+ automation_hash: createHash10("sha256").update(await readFile14(runAutomationPath)).digest("hex")
24749
25250
  } : {},
24750
25251
  ...hasFixtureManifest ? {
24751
25252
  fixture_manifest: {
@@ -24979,11 +25480,11 @@ async function recordTestSuiteRunPrecondition(options) {
24979
25480
  path: recordPath
24980
25481
  });
24981
25482
  }
24982
- let record;
25483
+ let record2;
24983
25484
  const currentRecordSha256 = await sha256(recordPath);
24984
25485
  if (currentRecordSha256 === anchor.record_sha256) {
24985
25486
  await assertExecutionPreconditionRecord(manifest, manifestPath, false);
24986
- record = {
25487
+ record2 = {
24987
25488
  schema_version: 1,
24988
25489
  kind: "bpmax_e2e_precondition_record",
24989
25490
  state: "passed",
@@ -24998,17 +25499,17 @@ async function recordTestSuiteRunPrecondition(options) {
24998
25499
  checks: evidence.checks,
24999
25500
  recorded_at: (/* @__PURE__ */ new Date()).toISOString()
25000
25501
  };
25001
- await writeAtomicJson(recordPath, record);
25502
+ await writeAtomicJson(recordPath, record2);
25002
25503
  } else {
25003
25504
  try {
25004
- record = JSON.parse(await readText(recordPath));
25505
+ record2 = JSON.parse(await readText(recordPath));
25005
25506
  } catch {
25006
25507
  fail("precondition record changed before it could be anchored in the manifest", {
25007
25508
  rule_id: "test_suite.run.precondition_hash_mismatch",
25008
25509
  path: recordPath
25009
25510
  });
25010
25511
  }
25011
- if (record.schema_version !== 1 || record.kind !== "bpmax_e2e_precondition_record" || record.state !== "passed" || record.run_id !== manifest.run_id || record.evidence_nonce !== manifest.evidence_nonce || record.scenario_id !== manifest.scenario_id || record.case_id !== manifest.case_id || record.profile !== manifest.profile || record.created_at !== manifest.started_at || resolveRunArtifactPath(runDir, String(record.evidence || "")) !== evidence.path || record.evidence_sha256 !== evidence.sha256 || JSON.stringify(preconditionChecks(record.checks)) !== JSON.stringify(evidence.checks) || Number.isNaN(Date.parse(String(record.recorded_at || "")))) {
25512
+ if (record2.schema_version !== 1 || record2.kind !== "bpmax_e2e_precondition_record" || record2.state !== "passed" || record2.run_id !== manifest.run_id || record2.evidence_nonce !== manifest.evidence_nonce || record2.scenario_id !== manifest.scenario_id || record2.case_id !== manifest.case_id || record2.profile !== manifest.profile || record2.created_at !== manifest.started_at || resolveRunArtifactPath(runDir, String(record2.evidence || "")) !== evidence.path || record2.evidence_sha256 !== evidence.sha256 || JSON.stringify(preconditionChecks(record2.checks)) !== JSON.stringify(evidence.checks) || Number.isNaN(Date.parse(String(record2.recorded_at || "")))) {
25012
25513
  fail("precondition record changed before it could be anchored in the manifest", {
25013
25514
  rule_id: "test_suite.run.precondition_hash_mismatch",
25014
25515
  path: recordPath
@@ -25021,7 +25522,7 @@ async function recordTestSuiteRunPrecondition(options) {
25021
25522
  record_sha256: await sha256(recordPath),
25022
25523
  evidence: evidence.path,
25023
25524
  evidence_sha256: evidence.sha256,
25024
- recorded_at: record.recorded_at
25525
+ recorded_at: record2.recorded_at
25025
25526
  };
25026
25527
  await writeExecutionManifest(manifestPath, manifest, true);
25027
25528
  return {
@@ -25108,7 +25609,7 @@ async function validateExecutionAutomationBinding(options) {
25108
25609
  path: actualAutomation
25109
25610
  });
25110
25611
  }
25111
- const automationSha256 = createHash9("sha256").update(await readFile14(actualAutomation)).digest("hex");
25612
+ const automationSha256 = createHash10("sha256").update(await readFile14(actualAutomation)).digest("hex");
25112
25613
  if (manifest.automation_hash && automationSha256 !== manifest.automation_hash && options.allowAutomationChange !== true) {
25113
25614
  fail("formal execution automation changed after run start; only a paused_repairable scenario checkpoint may authorize a current/future-step repair", {
25114
25615
  rule_id: "test_suite.run.automation_changed",
@@ -25402,11 +25903,11 @@ async function fileMap(root) {
25402
25903
  return result;
25403
25904
  }
25404
25905
  async function sha256(filePath) {
25405
- return createHash9("sha256").update(await readFile14(filePath)).digest("hex");
25906
+ return createHash10("sha256").update(await readFile14(filePath)).digest("hex");
25406
25907
  }
25407
25908
  async function readForDiff(filePath) {
25408
25909
  const buffer = await readFile14(filePath);
25409
- if (buffer.includes(0)) return [`<binary sha256=${createHash9("sha256").update(buffer).digest("hex")}>
25910
+ if (buffer.includes(0)) return [`<binary sha256=${createHash10("sha256").update(buffer).digest("hex")}>
25410
25911
  `];
25411
25912
  return buffer.toString("utf8").split(/(?<=\n)/);
25412
25913
  }
@@ -26198,7 +26699,9 @@ function reportRuntimeEvidenceInvalid(text5) {
26198
26699
  const runtimeParams = parsed.params;
26199
26700
  const isWorkspacePageRoute = runtimeScope === "page" && /^\/w:[^/]+(?:\/.*)?$/i.test(runtimePath);
26200
26701
  const workspaceMatch = /^\/w:([^/]+)(?:\/|$)/i.exec(runtimePath);
26201
- if (workspaceMatch && decodeURIComponent(workspaceMatch[1]) !== runtimeWorkspace) invalid.push("runtime_url/workspace");
26702
+ if (workspaceMatch && normalizeRuntimeWorkspace(decodeURIComponent(workspaceMatch[1])) !== normalizeRuntimeWorkspace(runtimeWorkspace)) {
26703
+ invalid.push("runtime_url/workspace");
26704
+ }
26202
26705
  const isSupportedUiRoute = /(?:\/project(?:$|\/|\?|_detail)|\/myProject|\/projectContinue|\/pages\/)/i.test(runtimePath) || /^\/w:[^/]+\/(?:userManagement|console)(?:\/|$)/i.test(runtimePath) || isWorkspacePageRoute;
26203
26706
  if (/(^|\.)example\.(?:com|org|net)$/i.test(url.hostname) || /\/(?:api|bpmax)(?:\/|$)/i.test(runtimePath) || !isSupportedUiRoute) {
26204
26707
  invalid.push("runtime_url/ui_route");
@@ -26929,6 +27432,15 @@ async function waitForBrowserAssertion(options) {
26929
27432
  function browserListRecordCountMatches(actualCount, expectedCount) {
26930
27433
  return expectedCount === void 0 ? actualCount > 0 : actualCount === expectedCount;
26931
27434
  }
27435
+ async function applyBrowserStepViewport(page, viewport) {
27436
+ if (!viewport) return void 0;
27437
+ await page.setViewportSize(viewport);
27438
+ const actual = page.viewportSize();
27439
+ if (!actual || actual.width !== viewport.width || actual.height !== viewport.height) {
27440
+ throw new Error(`e2e.browser.viewport_mismatch: expected ${viewport.width}x${viewport.height}, got ${actual ? `${actual.width}x${actual.height}` : "unavailable"}`);
27441
+ }
27442
+ return actual;
27443
+ }
26932
27444
  function browserUploadFixtureList(value) {
26933
27445
  const values = Array.isArray(value) ? value : [value];
26934
27446
  if (values.length === 0) throw new Error("form.upload_file requires one or more reviewed fixture objects");
@@ -26989,7 +27501,7 @@ async function validateBrowserUploadFixtures(value, scenarioRoot) {
26989
27501
  name: path16.basename(realFile),
26990
27502
  size: content.byteLength,
26991
27503
  mime: uploadMimeFromContent(realFile, content),
26992
- sha256: createHash10("sha256").update(content).digest("hex")
27504
+ sha256: createHash11("sha256").update(content).digest("hex")
26993
27505
  };
26994
27506
  if (actual.size !== fixture.size || actual.mime !== fixture.mime || actual.sha256 !== fixture.sha256) {
26995
27507
  throw new Error(`form.upload_file fixture metadata mismatch for ${actual.name}`);
@@ -27018,7 +27530,7 @@ async function captureBrowserDownload(options) {
27018
27530
  throw new Error(`download file too small: expected at least ${options.minSize}, got ${fileStat.size}`);
27019
27531
  }
27020
27532
  const content = await readFile15(destination);
27021
- const sha2563 = createHash10("sha256").update(content).digest("hex");
27533
+ const sha2563 = createHash11("sha256").update(content).digest("hex");
27022
27534
  if (options.expectedSha256 && sha2563 !== options.expectedSha256) {
27023
27535
  throw new Error(`download sha256 mismatch: expected ${options.expectedSha256}, got ${sha2563}`);
27024
27536
  }
@@ -27182,11 +27694,11 @@ function messageUrlParameter(url, name) {
27182
27694
  function browserMessageDeliveryMatches(records, expected) {
27183
27695
  const projectId = String(expected.project_id ?? "").trim();
27184
27696
  const stepId = String(expected.step_id ?? "").trim();
27185
- return records.filter((record) => {
27186
- const urlProjectId = messageUrlParameter(record.url, "id");
27187
- const urlStepId = messageUrlParameter(record.url, "step_id");
27697
+ return records.filter((record2) => {
27698
+ const urlProjectId = messageUrlParameter(record2.url, "id");
27699
+ const urlStepId = messageUrlParameter(record2.url, "step_id");
27188
27700
  const requiresStepLink = String(expected.url_pattern ?? "").includes("projectContinue");
27189
- return record.recipient_id === String(expected.recipient_id ?? "").trim() && boundMessageTextMatches(record.title, expected.title) && boundMessageTextMatches(record.content, expected.content) && boundMessageTextMatches(record.url, expected.url_pattern) && urlProjectId === projectId && (!stepId || urlStepId === stepId) && (!requiresStepLink || /^\d+$/.test(urlStepId));
27701
+ return record2.recipient_id === String(expected.recipient_id ?? "").trim() && boundMessageTextMatches(record2.title, expected.title) && boundMessageTextMatches(record2.content, expected.content) && boundMessageTextMatches(record2.url, expected.url_pattern) && urlProjectId === projectId && (!stepId || urlStepId === stepId) && (!requiresStepLink || /^\d+$/.test(urlStepId));
27190
27702
  });
27191
27703
  }
27192
27704
  function responsePathEndsWith(responseUrl, endpoint) {
@@ -27377,6 +27889,17 @@ async function visibleTargetLocator(page, target) {
27377
27889
  const locator = targetLocatorByIndex(await locatorForTarget(page, target), target);
27378
27890
  return await firstVisibleLocator(locator) ?? locator.first();
27379
27891
  }
27892
+ async function uniqueVisibleTargetLocator(page, target) {
27893
+ if (target.nth !== void 0) throw new Error("cascader.search_select requires a unique semantic target and does not allow target.nth");
27894
+ const locator = await locatorForTarget(page, target);
27895
+ const visible = [];
27896
+ for (let index = 0; index < await locator.count(); index += 1) {
27897
+ const candidate = locator.nth(index);
27898
+ if (await candidate.isVisible().catch(() => false)) visible.push(candidate);
27899
+ }
27900
+ if (visible.length !== 1) throw new Error(`cascader.search_select requires exactly one visible semantic outer control; found ${visible.length}`);
27901
+ return visible[0];
27902
+ }
27380
27903
  var PUNISHMENT_TYPE_SPECS = {
27381
27904
  criticism_education: { label: "\u6574\u6539" },
27382
27905
  contract_termination: { label: "\u89E3\u9664\u5408\u540C" },
@@ -27438,6 +27961,54 @@ async function selectVisibleOption(page, control, optionText, timeout) {
27438
27961
  throw new Error(`visible option not found or not clickable: ${optionText}`);
27439
27962
  }
27440
27963
  }
27964
+ async function selectBrowserCascader(page, semanticTarget, value, timeout) {
27965
+ const spec = value && typeof value === "object" && !Array.isArray(value) ? value : {};
27966
+ const search = String(spec.search ?? "").trim();
27967
+ const path27 = Array.isArray(spec.path) ? spec.path.map((item) => String(item).trim()) : [];
27968
+ if (!search || path27.length < 2 || path27.some((item) => !item) || path27.at(-1) !== search) {
27969
+ throw new Error("cascader.search_select requires value={search, path:[...]} ending in search");
27970
+ }
27971
+ const outerInput = await editableLocator(semanticTarget);
27972
+ if (!await outerInput.isVisible().catch(() => false)) throw new Error("cascader.search_select semantic outer control is not visible");
27973
+ await outerInput.click({ timeout });
27974
+ const popupId = String(
27975
+ await outerInput.getAttribute("aria-controls") ?? await outerInput.getAttribute("aria-owns") ?? ""
27976
+ ).trim();
27977
+ if (!popupId) {
27978
+ throw new Error("cascader.search_select outer control does not expose an aria-controls or aria-owns popup binding");
27979
+ }
27980
+ const panel = await firstVisibleLocator(
27981
+ page.locator(`xpath=//*[@id=${JSON.stringify(popupId)} and (contains(concat(" ", normalize-space(@class), " "), " el-cascader__dropdown ") or contains(concat(" ", normalize-space(@class), " "), " el-cascader-panel "))]`),
27982
+ timeout
27983
+ );
27984
+ if (!panel) throw new Error("cascader.search_select bound Element UI cascader popup is not visible");
27985
+ const searchInput = await firstVisibleLocator(panel.locator('input.el-cascader__search-input, input[placeholder*="\u641C\u7D22"], input[placeholder*="Search"]'), timeout);
27986
+ if (!searchInput) throw new Error("cascader.search_select internal search input not found");
27987
+ await searchInput.fill(search);
27988
+ const expectedPath = path27.join(" / ");
27989
+ const candidates = panel.locator(".el-cascader__suggestion-item:not(.is-disabled), .el-cascader-node:not(.is-disabled)");
27990
+ const matched = [];
27991
+ for (let index = 0; index < await candidates.count(); index += 1) {
27992
+ const candidate = candidates.nth(index);
27993
+ if (!await candidate.isVisible().catch(() => false)) continue;
27994
+ const label = String(await candidate.textContent() ?? "").replace(/\s+/g, " ").trim();
27995
+ const title = String(await candidate.getAttribute("title") ?? "").replace(/\s+/g, " ").trim();
27996
+ const ariaLabel = String(await candidate.getAttribute("aria-label") ?? "").replace(/\s+/g, " ").trim();
27997
+ const candidatePath = [ariaLabel, title].find((candidatePathValue) => candidatePathValue === expectedPath);
27998
+ if (label.includes(search) && candidatePath) matched.push(candidate);
27999
+ }
28000
+ if (matched.length !== 1) {
28001
+ throw new Error(`cascader.search_select requires exactly one visible candidate for complete path ${path27.join(" / ")}; found ${matched.length}`);
28002
+ }
28003
+ await matched[0].hover({ timeout });
28004
+ await matched[0].click({ timeout });
28005
+ const selected = String(await outerInput.inputValue().catch(() => "")).replace(/\s+/g, " ").trim();
28006
+ const tagText = String(await nearestFormItem(semanticTarget).locator(".el-tag, .el-cascader__tags").textContent().catch(() => "")).replace(/\s+/g, " ").trim();
28007
+ if (![selected, tagText].some((text5) => text5.includes(search))) {
28008
+ throw new Error(`cascader.search_select readback does not contain selected leaf ${search}`);
28009
+ }
28010
+ return { search, path: path27, selected: tagText || selected };
28011
+ }
27441
28012
  function punishmentTypeFromDisplay(value) {
27442
28013
  const normalized = value.replace(/\s+/g, " ").trim();
27443
28014
  return Object.entries(PUNISHMENT_TYPE_SPECS).find(([, spec]) => normalized.includes(spec.label))?.[0];
@@ -27613,8 +28184,63 @@ function browserDateRangeValues(value) {
27613
28184
  if (!start || !end) throw new Error("form.set_date_range requires non-empty start and end values");
27614
28185
  return [start, end];
27615
28186
  }
27616
- function browserListRecordEffectiveCount(visibleRowCount, visibleTextCount) {
27617
- return visibleRowCount > 0 ? visibleRowCount : visibleTextCount;
28187
+ function browserListContainerKind(descriptor) {
28188
+ const classes = new Set(descriptor.class_name.split(/\s+/).filter(Boolean));
28189
+ if (classes.has("el-table")) return "element_table";
28190
+ if (descriptor.tag === "table") return "table";
28191
+ if (descriptor.role === "rowgroup") return "rowgroup";
28192
+ if (/(?:^|[-_])(list|table|records)(?:$|[-_])/i.test(descriptor.test_id) || classes.has("project-list") || classes.has("list-container")) return "known_list";
28193
+ return void 0;
28194
+ }
28195
+ async function visibleBrowserRecords(records) {
28196
+ const visible = [];
28197
+ const count = await records.count();
28198
+ for (let index = 0; index < count; index += 1) {
28199
+ const record2 = records.nth(index);
28200
+ if (await record2.isVisible().catch(() => false)) visible.push(record2);
28201
+ }
28202
+ return visible;
28203
+ }
28204
+ async function firstVisibleBrowserRecordGroup(candidates) {
28205
+ for (const candidate of candidates) {
28206
+ const visible = await visibleBrowserRecords(candidate);
28207
+ if (visible.length > 0) return visible;
28208
+ }
28209
+ return [];
28210
+ }
28211
+ async function explicitListContainer(page, target) {
28212
+ const containers = await locatorForTarget(page, target);
28213
+ const visible = await visibleBrowserRecords(containers);
28214
+ if (visible.length !== 1) {
28215
+ throw new Error(`list.assert_record target must resolve to exactly one visible list container, got ${visible.length}`);
28216
+ }
28217
+ const container = visible[0];
28218
+ const descriptor = await container.evaluate((element) => ({
28219
+ tag: element.tagName.toLowerCase(),
28220
+ role: String(element.getAttribute("role") || "").toLowerCase(),
28221
+ class_name: String(element.getAttribute("class") || ""),
28222
+ test_id: String(element.getAttribute("data-testid") || "")
28223
+ }));
28224
+ const kind = browserListContainerKind(descriptor);
28225
+ if (!kind) {
28226
+ throw new Error("list.assert_record target is visible but is not a supported list container");
28227
+ }
28228
+ return { container, kind, descriptor };
28229
+ }
28230
+ function browserListRecordCandidates(container, kind) {
28231
+ if (kind === "element_table") {
28232
+ return [container.locator(".el-table__body-wrapper:not(.el-table__fixed-body-wrapper) tbody tr")];
28233
+ }
28234
+ if (kind === "table") return [container.locator("tbody tr")];
28235
+ if (kind === "rowgroup") return [container.locator('[role="row"]')];
28236
+ return [
28237
+ container.locator(".el-table__body-wrapper:not(.el-table__fixed-body-wrapper) tbody tr"),
28238
+ container.locator("table:not(.el-table table) tbody tr"),
28239
+ container.locator('[role="rowgroup"] [role="row"]'),
28240
+ container.locator('[data-testid*="record"], [data-testid*="list-item"]'),
28241
+ container.locator(".project-item, .el-card"),
28242
+ container.locator(".list-item")
28243
+ ];
27618
28244
  }
27619
28245
  async function dateRangeInputLocators(locator) {
27620
28246
  const inputSelector = "input:not([type=hidden])";
@@ -27775,6 +28401,11 @@ async function executeAction(page, action, variables, runtime) {
27775
28401
  await selectVisibleOption(page, editable, String(next.option ?? next.value ?? ""), timeout);
27776
28402
  return {};
27777
28403
  }
28404
+ case "cascader.search_select": {
28405
+ const target = next.target ?? { field: next.field };
28406
+ const actual = await selectBrowserCascader(page, await uniqueVisibleTargetLocator(page, target), next.value, timeout);
28407
+ return { assertion: { type: next.type, passed: true, target, actual } };
28408
+ }
27778
28409
  case "form.select_user": {
27779
28410
  await selectBrowserUser(
27780
28411
  page,
@@ -28019,28 +28650,50 @@ async function executeAction(page, action, variables, runtime) {
28019
28650
  }
28020
28651
  case "list.assert_record": {
28021
28652
  const expected = String(next.value ?? next.text ?? "");
28022
- const tableRows = page.locator(".el-table__body tr, tbody tr").filter({ hasText: expected });
28023
- const rowCount = await tableRows.count();
28024
- let visibleCount = 0;
28025
- for (let index = 0; index < rowCount; index += 1) {
28026
- if (await tableRows.nth(index).isVisible().catch(() => false)) visibleCount += 1;
28027
- }
28028
- let visibleTextCount = 0;
28029
- if (visibleCount === 0) {
28030
- const matches = page.getByText(expected, { exact: false });
28031
- const matchCount = await matches.count();
28032
- for (let index = 0; index < matchCount; index += 1) {
28033
- if (await matches.nth(index).isVisible().catch(() => false)) visibleTextCount += 1;
28034
- }
28035
- }
28036
- visibleCount = browserListRecordEffectiveCount(visibleCount, visibleTextCount);
28037
28653
  const expectedCount = Number.isInteger(next.count) ? Number(next.count) : void 0;
28654
+ let visibleRecords = [];
28655
+ let containerEvidence;
28656
+ if (expectedCount === 0) {
28657
+ const explicit = await explicitListContainer(page, next.target ?? {});
28658
+ containerEvidence = { ...explicit.descriptor, kind: explicit.kind };
28659
+ visibleRecords = await firstVisibleBrowserRecordGroup(
28660
+ browserListRecordCandidates(explicit.container, explicit.kind).map((candidates) => candidates.filter({ hasText: expected }))
28661
+ );
28662
+ } else {
28663
+ const recordNodeCandidates = [
28664
+ page.locator(".el-table__body-wrapper:not(.el-table__fixed-body-wrapper) tbody tr"),
28665
+ page.locator("table:not(.el-table__fixed) tbody tr"),
28666
+ page.locator('[role="rowgroup"] [role="row"]'),
28667
+ page.locator('[data-testid*="record"], [data-testid*="list-item"]'),
28668
+ page.locator(".project-list .project-item, .project-list .el-card"),
28669
+ page.locator(".list-container .list-item")
28670
+ ];
28671
+ visibleRecords = await firstVisibleBrowserRecordGroup(
28672
+ recordNodeCandidates.map((candidates) => candidates.filter({ hasText: expected }))
28673
+ );
28674
+ }
28675
+ const visibleCount = visibleRecords.length;
28676
+ const matchedRecords = [];
28677
+ for (const record2 of visibleRecords) {
28678
+ matchedRecords.push(await record2.evaluate((element) => ({
28679
+ tag: element.tagName.toLowerCase(),
28680
+ text: String(element.textContent || "").replace(/\s+/g, " ").trim().slice(0, 240)
28681
+ })));
28682
+ }
28038
28683
  const passed = browserListRecordCountMatches(visibleCount, expectedCount);
28039
28684
  if (!passed) {
28040
28685
  const expectation = expectedCount === void 0 ? "at least one" : String(expectedCount);
28041
28686
  throw new Error(`list record count mismatch for ${expected}: expected ${expectation}, got ${visibleCount}`);
28042
28687
  }
28043
- return { assertion: { type: next.type, passed, expected, count: visibleCount, expected_count: expectedCount } };
28688
+ return { assertion: {
28689
+ type: next.type,
28690
+ passed,
28691
+ expected,
28692
+ count: visibleCount,
28693
+ expected_count: expectedCount,
28694
+ container: containerEvidence,
28695
+ matched_records: matchedRecords
28696
+ } };
28044
28697
  }
28045
28698
  case "list.assert_cell": {
28046
28699
  const rowAnchor = String(next.source ?? "");
@@ -28173,16 +28826,18 @@ async function waitForInteractiveLogin(context2, options) {
28173
28826
  const deadline = Date.now() + timeout;
28174
28827
  while (Date.now() < deadline) {
28175
28828
  if (await contextHasAuthenticatedIdentity(context2, profileOrigin)) {
28176
- const probe = await probeAuthenticatedContext({
28829
+ const probe = await probeAuthenticatedContextSafely({
28177
28830
  context: context2,
28178
28831
  profileOrigin,
28179
28832
  workspace,
28180
28833
  preferredRoute: targetRoute,
28181
28834
  fingerprint: options.fingerprint,
28835
+ fingerprintVariables: options.fingerprintVariables,
28836
+ viewport: options.viewport,
28182
28837
  fingerprintPolicy: "preferred",
28183
28838
  requireExistingCandidate: false,
28184
28839
  keepProbePage: true
28185
- }).catch(() => void 0);
28840
+ });
28186
28841
  if (probe) return;
28187
28842
  }
28188
28843
  await new Promise((resolve) => setTimeout(resolve, 1e3));
@@ -28324,13 +28979,23 @@ async function probeAuthenticatedContext(options) {
28324
28979
  const page = await options.context.newPage();
28325
28980
  let passed = false;
28326
28981
  try {
28982
+ await applyBrowserStepViewport(page, options.viewport);
28327
28983
  await page.goto(targetRoute, { waitUntil: "domcontentloaded", timeout: 15e3 });
28328
28984
  await page.waitForLoadState("networkidle", { timeout: 8e3 }).catch(() => void 0);
28329
28985
  const finalUrl = new URL(page.url());
28330
28986
  if (finalUrl.origin !== profileOrigin || /(?:^|\/)login(?:\/|$)/i.test(finalUrl.pathname) || !finalUrl.pathname.startsWith(workspacePrefix)) return void 0;
28331
28987
  let fingerprintMatched = false;
28332
28988
  if (options.fingerprint) {
28333
- const failures = await assertFingerprint(page, options.fingerprint, { data: {}, context: {}, base_url: options.profileOrigin });
28989
+ let failures;
28990
+ try {
28991
+ failures = await assertFingerprint(page, options.fingerprint, options.fingerprintVariables ?? {
28992
+ data: {},
28993
+ context: {},
28994
+ base_url: options.profileOrigin
28995
+ });
28996
+ } catch (error) {
28997
+ throw new Error(`e2e.browser.auth_fingerprint_variables_invalid: ${error instanceof Error ? error.message : String(error)}`);
28998
+ }
28334
28999
  fingerprintMatched = failures.length === 0;
28335
29000
  if (!fingerprintMatched && options.fingerprintPolicy !== "preferred") return void 0;
28336
29001
  }
@@ -28342,6 +29007,15 @@ async function probeAuthenticatedContext(options) {
28342
29007
  }
28343
29008
  }
28344
29009
  }
29010
+ async function probeAuthenticatedContextSafely(options) {
29011
+ try {
29012
+ return await probeAuthenticatedContext(options);
29013
+ } catch (error) {
29014
+ const message = error instanceof Error ? error.message : String(error);
29015
+ if (/e2e\.browser\.(?:auth_fingerprint_variables_invalid|viewport_mismatch)/.test(message)) throw error;
29016
+ return void 0;
29017
+ }
29018
+ }
28345
29019
  async function openContext(options) {
28346
29020
  const cookieEnv = options.cookieEnv?.trim();
28347
29021
  const cookieHeader = !options.storageState && cookieEnv ? process.env[cookieEnv]?.trim() : void 0;
@@ -28358,16 +29032,18 @@ async function openContext(options) {
28358
29032
  await installCookieLoginBootstrap(context3, options.baseUrl || "");
28359
29033
  await context3.addCookies(browserCookiesFromHeader(cookieHeader, options.baseUrl || ""));
28360
29034
  }
28361
- const probe2 = await probeAuthenticatedContext({
29035
+ const probe2 = await probeAuthenticatedContextSafely({
28362
29036
  context: context3,
28363
29037
  profileOrigin: options.baseUrl || "",
28364
29038
  workspace: options.workspace || "new_oa",
28365
29039
  preferredRoute: options.preferredRoute || "",
28366
29040
  fingerprint: options.fingerprint,
29041
+ fingerprintVariables: options.fingerprintVariables,
29042
+ viewport: options.viewport,
28367
29043
  fingerprintPolicy: "preferred",
28368
29044
  requireExistingCandidate: false,
28369
29045
  keepProbePage: true
28370
- }).catch(() => void 0);
29046
+ });
28371
29047
  if (!probe2) {
28372
29048
  await context3.close().catch(() => void 0);
28373
29049
  await browser2.close().catch(() => void 0);
@@ -28386,16 +29062,18 @@ async function openContext(options) {
28386
29062
  channel: options.executablePath ? void 0 : "chrome"
28387
29063
  });
28388
29064
  context3 = await browser2.newContext({ storageState: importedState });
28389
- const headedProbe = await probeAuthenticatedContext({
29065
+ const headedProbe = await probeAuthenticatedContextSafely({
28390
29066
  context: context3,
28391
29067
  profileOrigin: options.baseUrl || "",
28392
29068
  workspace: options.workspace || "new_oa",
28393
29069
  preferredRoute: options.preferredRoute || "",
28394
29070
  fingerprint: options.fingerprint,
29071
+ fingerprintVariables: options.fingerprintVariables,
29072
+ viewport: options.viewport,
28395
29073
  fingerprintPolicy: "preferred",
28396
29074
  requireExistingCandidate: false,
28397
29075
  keepProbePage: true
28398
- }).catch(() => void 0);
29076
+ });
28399
29077
  if (!headedProbe) {
28400
29078
  await context3.close().catch(() => void 0);
28401
29079
  await browser2.close().catch(() => void 0);
@@ -28414,15 +29092,17 @@ async function openContext(options) {
28414
29092
  if (!preferredRoute) throw new Error("e2e.browser.auth_probe_route_missing: authenticated context probe requires the target route");
28415
29093
  const probes = [];
28416
29094
  for (const candidate of contexts) {
28417
- const result = await probeAuthenticatedContext({
29095
+ const result = await probeAuthenticatedContextSafely({
28418
29096
  context: candidate,
28419
29097
  profileOrigin,
28420
29098
  workspace,
28421
29099
  preferredRoute,
28422
29100
  fingerprint: options.fingerprint,
29101
+ fingerprintVariables: options.fingerprintVariables,
29102
+ viewport: options.viewport,
28423
29103
  fingerprintPolicy: "preferred",
28424
29104
  requireExistingCandidate: true
28425
- }).catch(() => void 0);
29105
+ });
28426
29106
  if (result) probes.push({ context: candidate, ...result });
28427
29107
  }
28428
29108
  if (probes.length === 0) return openInteractiveLoginSession(options);
@@ -28432,16 +29112,18 @@ async function openContext(options) {
28432
29112
  }
28433
29113
  const sourceContext = probes[0].context;
28434
29114
  const importedContext = await browser2.newContext({ storageState: await sourceContext.storageState() });
28435
- const importedProbe = await probeAuthenticatedContext({
29115
+ const importedProbe = await probeAuthenticatedContextSafely({
28436
29116
  context: importedContext,
28437
29117
  profileOrigin,
28438
29118
  workspace,
28439
29119
  preferredRoute,
28440
29120
  fingerprint: options.fingerprint,
29121
+ fingerprintVariables: options.fingerprintVariables,
29122
+ viewport: options.viewport,
28441
29123
  fingerprintPolicy: "preferred",
28442
29124
  requireExistingCandidate: false,
28443
29125
  keepProbePage: true
28444
- }).catch(() => void 0);
29126
+ });
28445
29127
  if (!importedProbe) {
28446
29128
  await importedContext.close().catch(() => void 0);
28447
29129
  return openInteractiveLoginSession(options);
@@ -28460,16 +29142,18 @@ async function openContext(options) {
28460
29142
  executablePath: options.executablePath,
28461
29143
  channel: options.executablePath ? void 0 : "chrome"
28462
29144
  });
28463
- const probe2 = await probeAuthenticatedContext({
29145
+ const probe2 = await probeAuthenticatedContextSafely({
28464
29146
  context: context3,
28465
29147
  profileOrigin: options.baseUrl || "",
28466
29148
  workspace: options.workspace || "new_oa",
28467
29149
  preferredRoute: options.preferredRoute || "",
28468
29150
  fingerprint: options.fingerprint,
29151
+ fingerprintVariables: options.fingerprintVariables,
29152
+ viewport: options.viewport,
28469
29153
  fingerprintPolicy: "preferred",
28470
29154
  requireExistingCandidate: false,
28471
29155
  keepProbePage: true
28472
- }).catch(() => void 0);
29156
+ });
28473
29157
  if (!probe2) {
28474
29158
  await context3.close().catch(() => void 0);
28475
29159
  if (options.interactiveLogin === false) {
@@ -28496,16 +29180,18 @@ async function openContext(options) {
28496
29180
  channel: options.executablePath ? void 0 : "chrome"
28497
29181
  });
28498
29182
  const context2 = await browser.newContext();
28499
- const probe = await probeAuthenticatedContext({
29183
+ const probe = await probeAuthenticatedContextSafely({
28500
29184
  context: context2,
28501
29185
  profileOrigin: options.baseUrl || "",
28502
29186
  workspace: options.workspace || "new_oa",
28503
29187
  preferredRoute: options.preferredRoute || "",
28504
29188
  fingerprint: options.fingerprint,
29189
+ fingerprintVariables: options.fingerprintVariables,
29190
+ viewport: options.viewport,
28505
29191
  fingerprintPolicy: "preferred",
28506
29192
  requireExistingCandidate: false,
28507
29193
  keepProbePage: true
28508
- }).catch(() => void 0);
29194
+ });
28509
29195
  if (!probe) {
28510
29196
  if (options.interactiveLogin === false) {
28511
29197
  await context2.close().catch(() => void 0);
@@ -28908,6 +29594,7 @@ async function writeRunnerEvidence(options) {
28908
29594
  return {
28909
29595
  url: window.location.href,
28910
29596
  title: document.title,
29597
+ viewport: { width: window.innerWidth, height: window.innerHeight },
28911
29598
  visible_text: (document.body?.innerText || "").slice(0, 1e5),
28912
29599
  controls
28913
29600
  };
@@ -28916,6 +29603,8 @@ async function writeRunnerEvidence(options) {
28916
29603
  `, "utf8");
28917
29604
  await writeFile11(path16.join(options.dir, traceName), `${JSON.stringify({
28918
29605
  page_fingerprint: options.automationStep.page_fingerprint,
29606
+ surface: options.automationStep.surface,
29607
+ viewport: options.automationStep.viewport,
28919
29608
  actions: options.automationStep.actions,
28920
29609
  expected_checks: options.automationStep.expected_checks,
28921
29610
  resolution_checks: options.automationStep.resolution_checks,
@@ -28923,6 +29612,7 @@ async function writeRunnerEvidence(options) {
28923
29612
  }, null, 2)}
28924
29613
  `, "utf8");
28925
29614
  const runtimeUrl = options.page.url();
29615
+ const actualViewport = options.page.viewportSize();
28926
29616
  const evidence = path16.join(options.dir, `${options.caseId}-${options.stepId}${options.artifactSuffix || ""}.json`);
28927
29617
  const payload = {
28928
29618
  schema_version: 2,
@@ -28936,6 +29626,8 @@ async function writeRunnerEvidence(options) {
28936
29626
  runtime_scope: executionScope(runtimeUrl),
28937
29627
  runtime_environment: runtimeEnvironmentFor(runtimeUrl),
28938
29628
  runtime_url: runtimeUrl,
29629
+ surface: options.automationStep.surface,
29630
+ viewport: actualViewport,
28939
29631
  screenshot: screenshot.screenshotReference,
28940
29632
  dom_snapshot: domName,
28941
29633
  assertions: options.assertions,
@@ -28975,7 +29667,7 @@ async function writeRunnerEvidenceFileManifest(evidenceDir, evidenceFiles) {
28975
29667
  const content = await readFile15(absolutePath);
28976
29668
  const extension = path16.extname(file).toLowerCase();
28977
29669
  const mimeType = extension === ".png" ? "image/png" : "application/json";
28978
- return { file, mime_type: mimeType, sha256: createHash10("sha256").update(content).digest("hex"), size: content.length };
29670
+ return { file, mime_type: mimeType, sha256: createHash11("sha256").update(content).digest("hex"), size: content.length };
28979
29671
  }))
28980
29672
  }, null, 2)}
28981
29673
  `, "utf8");
@@ -29038,6 +29730,7 @@ async function runOneBrowserStep(options, session) {
29038
29730
  if (!page) {
29039
29731
  throw new Error("e2e.browser.login_bootstrap_required: no authenticated target-workspace page is available; run the reviewed login bootstrap before business steps");
29040
29732
  }
29733
+ await applyBrowserStepViewport(page, definition.viewport);
29041
29734
  const consoleErrors = [];
29042
29735
  const networkErrors = [];
29043
29736
  const responses = [];
@@ -29531,7 +30224,9 @@ async function runBrowserAutomation(options) {
29531
30224
  String(initialDefinition.actions.find((action) => action.type === "navigation.open")?.route),
29532
30225
  authenticationVariables
29533
30226
  ) : String(initialDefinition?.page_fingerprint?.route || ""),
29534
- fingerprint: initialDefinition?.page_fingerprint
30227
+ fingerprint: initialDefinition?.page_fingerprint,
30228
+ fingerprintVariables: authenticationVariables,
30229
+ viewport: initialDefinition?.viewport
29535
30230
  });
29536
30231
  try {
29537
30232
  let currentOptions = { ...options };
@@ -29566,6 +30261,9 @@ async function runBrowserAutomation(options) {
29566
30261
  if (session.owned && session.browser) await session.browser.close().catch(() => void 0);
29567
30262
  }
29568
30263
  }
30264
+ function mutationResolutionBranchUsesIndependentNavigation(checks) {
30265
+ return checks[0]?.type === "navigation.open";
30266
+ }
29569
30267
  function selectMutationResolutionOutcome(branchResults, expectedOutcome, trustedCommittedAttempt = false) {
29570
30268
  const passing = branchResults.filter((branch) => branch.passed);
29571
30269
  if (passing.length === 2 && trustedCommittedAttempt && passing.some((branch) => branch.outcome === "committed")) {
@@ -29696,7 +30394,9 @@ async function captureMutationResolutionReadback(options) {
29696
30394
  baseUrl: profileOrigin,
29697
30395
  workspace: String(execution.workspace || ""),
29698
30396
  preferredRoute: probeRoute,
29699
- fingerprint: definition.page_fingerprint
30397
+ fingerprint: definition.page_fingerprint,
30398
+ fingerprintVariables: baseVariables,
30399
+ viewport: definition.viewport
29700
30400
  });
29701
30401
  const dataProjectId = String(valueAt(data, "project_id") ?? "");
29702
30402
  const liveAttemptProbeUrl = boundAttemptProbeUrl || (/^\d+$/.test(dataProjectId) && /^https?:\/\//i.test(profileOrigin) ? new URL(`/w:${String(execution.workspace || "")}/projectContinue?id=${dataProjectId}`, profileOrigin).toString() : void 0);
@@ -29710,6 +30410,7 @@ async function captureMutationResolutionReadback(options) {
29710
30410
  const branchResults = await Promise.all(outcomes.map(async (outcome) => {
29711
30411
  const page = await session.context.newPage();
29712
30412
  createdPages.push(page);
30413
+ await applyBrowserStepViewport(page, definition.viewport);
29713
30414
  const variables = structuredClone(baseVariables);
29714
30415
  const actionTrace = [];
29715
30416
  const assertions = [];
@@ -29747,6 +30448,8 @@ async function captureMutationResolutionReadback(options) {
29747
30448
  page.on("response", onResponse);
29748
30449
  let fingerprintConfirmed = false;
29749
30450
  try {
30451
+ const checks = definition.resolution_checks?.[outcome] ?? [];
30452
+ const branchUsesIndependentNavigation = mutationResolutionBranchUsesIndependentNavigation(checks);
29750
30453
  const committedProbeUrl = outcome === "committed" ? trustedCommittedProbeUrl || liveCommittedProbeUrl : void 0;
29751
30454
  const resolutionStartUrl = committedProbeUrl || boundAttemptProbeUrl;
29752
30455
  const leading = definition.actions[0];
@@ -29762,7 +30465,7 @@ async function captureMutationResolutionReadback(options) {
29762
30465
  finished_at: (/* @__PURE__ */ new Date()).toISOString(),
29763
30466
  ok: true
29764
30467
  });
29765
- } else if (leading?.type === "navigation.open") {
30468
+ } else if (!branchUsesIndependentNavigation && leading?.type === "navigation.open") {
29766
30469
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
29767
30470
  await executeAction(page, leading, variables, {
29768
30471
  responses,
@@ -29773,17 +30476,16 @@ async function captureMutationResolutionReadback(options) {
29773
30476
  }
29774
30477
  });
29775
30478
  actionTrace.push({ index: -1, type: leading.type, started_at: startedAt, finished_at: (/* @__PURE__ */ new Date()).toISOString(), ok: true });
29776
- } else {
30479
+ } else if (!branchUsesIndependentNavigation) {
29777
30480
  await restoreStepStartPage(page, definition, variables, actionTrace);
29778
30481
  }
29779
- if (!committedProbeUrl) {
30482
+ if (!committedProbeUrl && !branchUsesIndependentNavigation) {
29780
30483
  const fingerprintFailures = await assertFingerprint(page, definition.page_fingerprint, variables);
29781
30484
  if (fingerprintFailures.length > 0) {
29782
30485
  throw new Error(`resolution page fingerprint mismatch: ${fingerprintFailures.join("; ")}`);
29783
30486
  }
29784
30487
  fingerprintConfirmed = true;
29785
30488
  }
29786
- const checks = definition.resolution_checks?.[outcome] ?? [];
29787
30489
  let previousActionResponseCursor = responseSequence;
29788
30490
  for (let index = 0; index < checks.length; index += 1) {
29789
30491
  const check = checks[index];
@@ -29830,7 +30532,7 @@ async function captureMutationResolutionReadback(options) {
29830
30532
  const passed = assertions.length > 0 && assertions.every((assertion) => assertion.passed === true);
29831
30533
  return { outcome, passed, page, assertions, actionTrace, consoleErrors, networkErrors, responses };
29832
30534
  } catch (error) {
29833
- const errorMessage3 = error instanceof Error ? error.message : String(error);
30535
+ const errorMessage4 = error instanceof Error ? error.message : String(error);
29834
30536
  const mutationPattern = String(definition.actions.find((action) => action.mutation === true)?.url_pattern || "").trim();
29835
30537
  const noRequestFallback = outcome === "not_committed" && fingerprintConfirmed && mutationResolutionNoRequestFingerprintIsStrong(definition) && mutationResolutionNoRequestEvidenceMatches({
29836
30538
  attemptEvidence,
@@ -29857,7 +30559,7 @@ async function captureMutationResolutionReadback(options) {
29857
30559
  type: "mutation.no_request_page_fingerprint",
29858
30560
  finished_at: (/* @__PURE__ */ new Date()).toISOString(),
29859
30561
  ok: true,
29860
- recovered_from: errorMessage3
30562
+ recovered_from: errorMessage4
29861
30563
  });
29862
30564
  return {
29863
30565
  outcome,
@@ -29875,7 +30577,7 @@ async function captureMutationResolutionReadback(options) {
29875
30577
  type: "resolution.branch",
29876
30578
  outcome,
29877
30579
  passed: false,
29878
- error: errorMessage3
30580
+ error: errorMessage4
29879
30581
  });
29880
30582
  return {
29881
30583
  outcome,
@@ -29886,7 +30588,7 @@ async function captureMutationResolutionReadback(options) {
29886
30588
  consoleErrors,
29887
30589
  networkErrors,
29888
30590
  responses,
29889
- error: errorMessage3
30591
+ error: errorMessage4
29890
30592
  };
29891
30593
  } finally {
29892
30594
  page.off("console", onConsole);
@@ -30010,7 +30712,7 @@ function isRecord11(value) {
30010
30712
  return typeof value === "object" && value !== null && !Array.isArray(value);
30011
30713
  }
30012
30714
  function sha2562(value) {
30013
- return createHash11("sha256").update(value).digest("hex");
30715
+ return createHash12("sha256").update(value).digest("hex");
30014
30716
  }
30015
30717
  async function fileSha256(file) {
30016
30718
  return sha2562(await readFile16(file));
@@ -30745,6 +31447,8 @@ async function executeE2eScenarioUnlocked(options, dependencies = DEFAULT_DEPEND
30745
31447
  try {
30746
31448
  result = await dependencies.runBrowserAutomation({
30747
31449
  ...options,
31450
+ caseId: String(step.case_id || execution.case_id || ""),
31451
+ caseStepId: String(step.step_id || ""),
30748
31452
  orchestrated: true,
30749
31453
  resume: options.resume || executionSteps(execution).some((item) => item.status === "pass"),
30750
31454
  allowAutomationChange: resumeFromRepair && automationChanged,
@@ -31190,7 +31894,7 @@ async function resolveE2eScenarioWriteState(options, dependencies = DEFAULT_DEPE
31190
31894
  }
31191
31895
 
31192
31896
  // src/core/e2e-identity-bridge.ts
31193
- import { createHash as createHash12, randomUUID as randomUUID4 } from "crypto";
31897
+ import { createHash as createHash13, randomUUID as randomUUID4 } from "crypto";
31194
31898
  import { chmod as chmod4, lstat as lstat4, mkdir as mkdir13, readFile as readFile17, realpath as realpath7, rename as rename5, stat as stat12, unlink as unlink2, writeFile as writeFile13 } from "fs/promises";
31195
31899
  import path18 from "path";
31196
31900
  var REQUEST_TTL_SECONDS = 180;
@@ -31638,7 +32342,7 @@ async function validateScreenshot(request, result) {
31638
32342
  return {
31639
32343
  path: realScreenshot,
31640
32344
  mime: "image/jpeg",
31641
- sha256: createHash12("sha256").update(content).digest("hex")
32345
+ sha256: createHash13("sha256").update(content).digest("hex")
31642
32346
  };
31643
32347
  }
31644
32348
  function validateResultEnvelope(request, value) {
@@ -32979,7 +33683,7 @@ async function writeEvidenceManifest(evidenceDir, details, extraFiles = []) {
32979
33683
  artifacts.push({
32980
33684
  path: relativePath,
32981
33685
  size: buffer.length,
32982
- sha256: createHash13("sha256").update(buffer).digest("hex"),
33686
+ sha256: createHash14("sha256").update(buffer).digest("hex"),
32983
33687
  mime_type: mimeType,
32984
33688
  ...expectedMime && expectedMime !== mimeType ? { extension_mismatch: true, expected_mime: expectedMime } : {}
32985
33689
  });
@@ -33477,7 +34181,7 @@ async function writeBrowserRecordingReport(options) {
33477
34181
  if (!trace || !isRecord15(trace) || !Array.isArray(trace.actions) || !Array.isArray(trace.expected_checks) || !isRecord15(trace.page_fingerprint)) {
33478
34182
  throw new Error("browser-action-trace.json must contain page_fingerprint, actions, and expected_checks before a recording report can be generated");
33479
34183
  }
33480
- const traceSha256 = createHash13("sha256").update(await readFile18(tracePath)).digest("hex");
34184
+ const traceSha256 = createHash14("sha256").update(await readFile18(tracePath)).digest("hex");
33481
34185
  const files = (await readdir6(evidenceDir).catch(() => [])).filter((file) => file !== "browser-recording-report.json").sort();
33482
34186
  const report = {
33483
34187
  version: 1,
@@ -33507,7 +34211,7 @@ async function writeBrowserRecordingReport(options) {
33507
34211
  const reportPath = path19.join(evidenceDir, "browser-recording-report.json");
33508
34212
  await writeFile14(reportPath, `${JSON.stringify(report, null, 2)}
33509
34213
  `, "utf8");
33510
- const reportSha256 = createHash13("sha256").update(await readFile18(reportPath)).digest("hex");
34214
+ const reportSha256 = createHash14("sha256").update(await readFile18(reportPath)).digest("hex");
33511
34215
  return { path: reportPath, sha256: reportSha256, tracePath, traceSha256, report };
33512
34216
  }
33513
34217
  async function updateAutomationFromRecordedTrace(options) {
@@ -33614,8 +34318,8 @@ function scenarioRecords(plan) {
33614
34318
  }
33615
34319
  return records.filter(isRecord15);
33616
34320
  }
33617
- function recordKey(record, index) {
33618
- return stringValue5(record.demo_no ?? record.id ?? record.case_id ?? record.subject) ?? `record-${index + 1}`;
34321
+ function recordKey(record2, index) {
34322
+ return stringValue5(record2.demo_no ?? record2.id ?? record2.case_id ?? record2.subject) ?? `record-${index + 1}`;
33619
34323
  }
33620
34324
  function registerE2eCommands(program2) {
33621
34325
  const e2e = program2.command("e2e").description("BPMAX E2E acceleration helpers with evidence-first safety gates");
@@ -34221,7 +34925,7 @@ function registerE2eCommands(program2) {
34221
34925
  throw new Error(`Flow ${options.flowId} was not found.`);
34222
34926
  }
34223
34927
  const sourceUpdateTime = stringValue5(result.update_time ?? result.updateTime ?? result.updated_at ?? result.updatedAt);
34224
- const cacheKey = createHash13("sha256").update(JSON.stringify({
34928
+ const cacheKey = createHash14("sha256").update(JSON.stringify({
34225
34929
  flow_id: options.flowId,
34226
34930
  update_time: sourceUpdateTime,
34227
34931
  template_id: result.template_id ?? result.templateId
@@ -34272,20 +34976,20 @@ function registerE2eCommands(program2) {
34272
34976
  if (options.recordingJob) {
34273
34977
  const recordingJobPath = path19.resolve(options.recordingJob);
34274
34978
  let raw;
34275
- let record;
34979
+ let record2;
34276
34980
  try {
34277
34981
  raw = await readFile18(recordingJobPath);
34278
- record = JSON.parse(raw.toString("utf8"));
34982
+ record2 = JSON.parse(raw.toString("utf8"));
34279
34983
  } catch (error) {
34280
34984
  throw new Error(`e2e.recording_job_invalid: ${recordingJobPath} is not readable JSON: ${error instanceof Error ? error.message : String(error)}`);
34281
34985
  }
34282
- if (record.version !== 1 || record.kind !== "bpmax_e2e_automation_checkpoint" || !["complete", "resolved"].includes(String(record.status || "")) || record.mutation === true && !["committed", "not_committed"].includes(String(record.mutation_state || "")) || options.scenario && record.scenario_id !== options.scenario || options.caseId && record.case_id !== options.caseId || options.caseStepId && record.case_step_id !== options.caseStepId) {
34986
+ if (record2.version !== 1 || record2.kind !== "bpmax_e2e_automation_checkpoint" || !["complete", "resolved"].includes(String(record2.status || "")) || record2.mutation === true && !["committed", "not_committed"].includes(String(record2.mutation_state || "")) || options.scenario && record2.scenario_id !== options.scenario || options.caseId && record2.case_id !== options.caseId || options.caseStepId && record2.case_step_id !== options.caseStepId) {
34283
34987
  throw new Error("e2e.recording_job_invalid: checkpoint must be complete/resolved, bind the requested scenario/case/step, and resolve every prepared mutation");
34284
34988
  }
34285
34989
  recordingJob = {
34286
34990
  path: recordingJobPath,
34287
- sha256: createHash13("sha256").update(raw).digest("hex"),
34288
- record
34991
+ sha256: createHash14("sha256").update(raw).digest("hex"),
34992
+ record: record2
34289
34993
  };
34290
34994
  }
34291
34995
  const files = await readdir6(options.evidenceDir).catch(() => []);
@@ -34447,16 +35151,16 @@ function registerE2eCommands(program2) {
34447
35151
  await requireE2eExecutionBinding(options, ["observe"]);
34448
35152
  const plan = await parseJsonFileOrInput(options.plan, "--plan");
34449
35153
  const records = scenarioRecords(plan);
34450
- const start = options.from ? records.findIndex((record, index) => recordKey(record, index) === options.from) : 0;
34451
- const end = options.to ? records.findIndex((record, index) => recordKey(record, index) === options.to) : records.length - 1;
34452
- const selected = records.filter((record, index) => {
35154
+ const start = options.from ? records.findIndex((record2, index) => recordKey(record2, index) === options.from) : 0;
35155
+ const end = options.to ? records.findIndex((record2, index) => recordKey(record2, index) === options.to) : records.length - 1;
35156
+ const selected = records.filter((record2, index) => {
34453
35157
  const afterStart = start < 0 ? true : index >= start;
34454
35158
  const beforeEnd = end < 0 ? true : index <= end;
34455
35159
  return afterStart && beforeEnd;
34456
35160
  });
34457
- const status = selected.map((record, index) => ({
34458
- record: recordKey(record, index),
34459
- subject: stringValue5(record.subject),
35161
+ const status = selected.map((record2, index) => ({
35162
+ record: recordKey(record2, index),
35163
+ subject: stringValue5(record2.subject),
34460
35164
  status: "bootstrap_required",
34461
35165
  next_action: "This legacy command cannot start a formal run. Prepare reviewed deterministic automation with test-suite automation init/compile, then use test-suite run start and one e2e scenario execute command."
34462
35166
  }));
@@ -34508,13 +35212,13 @@ function isProjectListEsQuery(value) {
34508
35212
  }
34509
35213
  function splitProjectListPagination(body, options) {
34510
35214
  const data = { ...body };
34511
- const normalizePositiveInteger = (value, path25) => {
35215
+ const normalizePositiveInteger = (value, path27) => {
34512
35216
  if (typeof value === "string" && value.trim() === "") {
34513
- throw new Error(`project search ${path25} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u4E0D\u80FD\u662F\u7A7A\u5B57\u7B26\u4E32\u3002`);
35217
+ throw new Error(`project search ${path27} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u4E0D\u80FD\u662F\u7A7A\u5B57\u7B26\u4E32\u3002`);
34514
35218
  }
34515
35219
  const number = typeof value === "number" ? value : Number(value);
34516
35220
  if (!Number.isSafeInteger(number) || number < 1) {
34517
- throw new Error(`project search ${path25} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u503C\u4E3A ${String(value)}\u3002`);
35221
+ throw new Error(`project search ${path27} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u503C\u4E3A ${String(value)}\u3002`);
34518
35222
  }
34519
35223
  return number;
34520
35224
  };
@@ -34666,7 +35370,7 @@ function registerFlowCommands(program2) {
34666
35370
  const client = createApiClient(profile);
34667
35371
  if (options.flowType) {
34668
35372
  const { bindings } = await getWorkspaceFlowBindings(client, profile, options);
34669
- const path25 = options.flowKey ? "/flow/options" : "/flow/flow_type";
35373
+ const path27 = options.flowKey ? "/flow/options" : "/flow/flow_type";
34670
35374
  const params = options.flowKey ? {
34671
35375
  detail: "1"
34672
35376
  } : {
@@ -34676,7 +35380,7 @@ function registerFlowCommands(program2) {
34676
35380
  const result2 = await apiRequest(
34677
35381
  client,
34678
35382
  "GET",
34679
- path25,
35383
+ path27,
34680
35384
  {
34681
35385
  params
34682
35386
  }
@@ -34709,6 +35413,10 @@ function registerFlowCommands(program2) {
34709
35413
  });
34710
35414
  }
34711
35415
 
35416
+ // src/commands/init.ts
35417
+ import { mkdir as mkdir15, writeFile as writeFile15 } from "fs/promises";
35418
+ import path20 from "path";
35419
+
34712
35420
  // src/core/setup.ts
34713
35421
  function parseBpmUrl(input) {
34714
35422
  const trimmed = input.trim();
@@ -34804,6 +35512,38 @@ function parseSkillsDetail(stdout) {
34804
35512
  return void 0;
34805
35513
  }
34806
35514
  }
35515
+ async function writeInitReceipt(file, value) {
35516
+ const resolved = path20.resolve(file);
35517
+ await mkdir15(path20.dirname(resolved), { recursive: true });
35518
+ await writeFile15(resolved, `${JSON.stringify(redactInitReceipt(value), null, 2)}
35519
+ `, "utf8");
35520
+ return resolved;
35521
+ }
35522
+ var INIT_SECRET_KEYS = /* @__PURE__ */ new Set([
35523
+ "api_key",
35524
+ "apiKey",
35525
+ "authorization",
35526
+ "Authorization",
35527
+ "token",
35528
+ "access_token",
35529
+ "refresh_token",
35530
+ "cookie",
35531
+ "password",
35532
+ "device_code",
35533
+ "user_code",
35534
+ "verification_code",
35535
+ "sms_code",
35536
+ "phone"
35537
+ ]);
35538
+ function redactInitReceipt(value) {
35539
+ if (Array.isArray(value)) return value.map(redactInitReceipt);
35540
+ if (!value || typeof value !== "object") return value;
35541
+ const result = {};
35542
+ for (const [key, entry] of Object.entries(value)) {
35543
+ if (!INIT_SECRET_KEYS.has(key)) result[key] = redactInitReceipt(entry);
35544
+ }
35545
+ return result;
35546
+ }
34807
35547
  var AGENT_SCOPE_REQUIRED_MESSAGE = "Agent initialization requires --profile-scope from trusted runtime metadata. Use --single-user only for an explicit local single-user setup.";
34808
35548
  function registerInitCommand(program2, deps = {}) {
34809
35549
  const loadConfig2 = deps.loadConfig || loadConfig;
@@ -34811,7 +35551,7 @@ function registerInitCommand(program2, deps = {}) {
34811
35551
  const syncSkills2 = deps.syncSkills || syncSkills;
34812
35552
  const startDeviceLogin2 = deps.startDeviceLogin || startDeviceLogin;
34813
35553
  const shouldProbeCapabilities = !deps.loadConfig && !deps.saveConfig;
34814
- program2.command("init").description("Initialize bpmax-cli for browserless agent environments").requiredOption("--url <url>", "Full BPMAX workspace URL, for example https://example.com/w:store_mgr").option("--name <name>", "Profile name", "default").option("--profile-scope <scope>", "Trusted runtime scope for agent-user profile isolation").option("--single-user", "Allow init to use the shared config directory for an explicit local single-user setup").option("--agent <agent>", "Agent adapter: openclaw | aily | codex | claude | gemini | generic", "generic").option("--channel <channel>", "Interaction channel: feishu | terminal | json", "json").option("--key-name <keyName>", "Target API key name", "bpmax-cli").option("--language <language>", "Default language", DEFAULT_LANGUAGE).option("--force-skills", "Force skills reinstall").option("--format <format>", "Output format", "pretty").action(async (options) => {
35554
+ program2.command("init").description("Initialize bpmax-cli for browserless agent environments").requiredOption("--url <url>", "Full BPMAX workspace URL, for example https://example.com/w:store_mgr").option("--name <name>", "Profile name", "default").option("--profile-scope <scope>", "Trusted runtime scope for agent-user profile isolation").option("--single-user", "Allow init to use the shared config directory for an explicit local single-user setup").option("--agent <agent>", "Agent adapter: openclaw | aily | codex | claude | gemini | generic", "generic").option("--channel <channel>", "Interaction channel: feishu | terminal | json", "json").option("--key-name <keyName>", "Target API key name", "bpmax-cli").option("--language <language>", "Default language", DEFAULT_LANGUAGE).option("--force-skills", "Force skills reinstall").option("--summary", "Return a compact initialization result").option("--receipt <file>", "Write the full non-secret initialization result to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
34815
35555
  const parsed = parseBpmUrl(options.url);
34816
35556
  const baseProfileName = options.name || "default";
34817
35557
  if (!options.profileScope?.trim() && !options.singleUser) {
@@ -34870,7 +35610,7 @@ function registerInitCommand(program2, deps = {}) {
34870
35610
  requestConfigurationCapability: true
34871
35611
  });
34872
35612
  const commandPrefix3 = `bpmax-cli --config-dir ${shellQuote6(configDir)}`;
34873
- printResult(options.format, {
35613
+ const fullResult = {
34874
35614
  ok: true,
34875
35615
  profile: profileName,
34876
35616
  ...profileScope ? {
@@ -34907,6 +35647,23 @@ function registerInitCommand(program2, deps = {}) {
34907
35647
  bbs_list: `${commandPrefix3} bbs list --profile ${profileName} --format json`
34908
35648
  }
34909
35649
  } : {}
35650
+ };
35651
+ if (!options.summary) {
35652
+ printResult(options.format, fullResult);
35653
+ return;
35654
+ }
35655
+ const receipt = options.receipt ? await writeInitReceipt(options.receipt, fullResult) : void 0;
35656
+ printResult(options.format, {
35657
+ ok: true,
35658
+ profile: profileName,
35659
+ config_dir: configDir,
35660
+ profile_isolated: Boolean(profileScope),
35661
+ context_isolated: Boolean(profileScope),
35662
+ skills: { action: skills.action, status: skills.action === "failed" ? "failed" : "ok" },
35663
+ ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
35664
+ authorization: { status: "device_code_issued" },
35665
+ ...receipt ? { receipt } : {},
35666
+ ...profileScope ? { next_commands: fullResult.next_commands } : {}
34910
35667
  });
34911
35668
  });
34912
35669
  }
@@ -35173,6 +35930,57 @@ function registerIssueCommands(program2, deps = {}) {
35173
35930
  });
35174
35931
  }
35175
35932
 
35933
+ // src/core/icon-catalog.ts
35934
+ import { readFile as readFile20 } from "fs/promises";
35935
+ import path21 from "path";
35936
+ var DEFAULT_ICON_CATALOG = path21.resolve(process.cwd(), "skills/bpmax-icon-catalog/assets/ri-icons.json");
35937
+ async function loadRiIcons(source = process.env.BPMAX_ICON_CATALOG || DEFAULT_ICON_CATALOG) {
35938
+ const text5 = await readFile20(source, "utf8");
35939
+ if (source.endsWith(".json")) {
35940
+ const parsed = JSON.parse(text5);
35941
+ if (Array.isArray(parsed.icons) && parsed.icons.every((item) => typeof item === "string")) return parsed.icons;
35942
+ throw new Error(`Invalid icon catalog JSON: ${source}`);
35943
+ }
35944
+ const match = text5.match(/export\s+const\s+riIconList\s*=\s*\[(.*?)]\s*\.map\s*\(/s);
35945
+ if (!match) throw new Error(`Unable to find riIconList in ${source}`);
35946
+ const names = [...match[1].matchAll(/['"](ri_[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)['"]/g)].map((item) => item[1]);
35947
+ if (!names.length) throw new Error(`riIconList is empty in ${source}`);
35948
+ return [...new Set(names)].map((name) => `ri ${name}`);
35949
+ }
35950
+ function normalizeIconQuery(query) {
35951
+ return query.trim().toLowerCase();
35952
+ }
35953
+ function iconName(iconClass) {
35954
+ return iconClass.trim().replace(/^ri\s+/, "");
35955
+ }
35956
+
35957
+ // src/commands/icon.ts
35958
+ function registerIconCommands(program2) {
35959
+ const icon = program2.command("icon").description("Query and validate icons from hpt-frontend ri_icon.ts");
35960
+ icon.command("search").description("Search available runtime icon classes").option("--query <text>", "Case-insensitive substring query", "").option("--limit <number>", "Maximum results", "100").option("--format <format>", "Output format", "json").action(async (options) => {
35961
+ const all = await loadRiIcons();
35962
+ const query = normalizeIconQuery(options.query);
35963
+ const limit = Math.max(1, Number.parseInt(options.limit, 10) || 100);
35964
+ const results = all.filter((item) => !query || item.toLowerCase().includes(query)).slice(0, limit);
35965
+ printResult(options.format, { query, count: results.length, total: all.length, icons: results });
35966
+ });
35967
+ icon.command("get <name>").description("Resolve one source name or runtime class").option("--format <format>", "Output format", "json").action(async (name, options) => {
35968
+ const all = await loadRiIcons();
35969
+ const candidate = name.trim().startsWith("ri ") ? name.trim() : `ri ${name.trim()}`;
35970
+ const found = all.find((item) => item === candidate);
35971
+ if (!found) throw new Error(`Icon not found: ${name}`);
35972
+ printResult(options.format, { name: iconName(found), className: found });
35973
+ });
35974
+ icon.command("validate [iconClass]").description("Validate a complete runtime icon class against the source catalog").option("--format <format>", "Output format", "json").option("--icon-class <className>", "Complete runtime icon class").action(async (value, options) => {
35975
+ const iconClass = options.iconClass || value || "";
35976
+ const all = await loadRiIcons();
35977
+ const validFormat = /^ri ri_[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/.test(iconClass.trim());
35978
+ const exists6 = all.includes(iconClass.trim());
35979
+ printResult(options.format, { valid: validFormat && exists6, formatValid: validFormat, exists: exists6, iconClass: iconClass.trim(), suggestion: validFormat ? void 0 : "Use ri ri_<name-with-hyphens>." });
35980
+ if (!(validFormat && exists6)) process.exitCode = 1;
35981
+ });
35982
+ }
35983
+
35176
35984
  // src/commands/memory.ts
35177
35985
  function parseLimit(input, fallback) {
35178
35986
  const value = Number(input ?? fallback);
@@ -35195,10 +36003,10 @@ async function parseOptionalJson(input, label) {
35195
36003
  }
35196
36004
  return parseJsonInput(input, label);
35197
36005
  }
35198
- async function memoryRequest(options, method, path25, capability, data, params) {
36006
+ async function memoryRequest(options, method, path27, capability, data, params) {
35199
36007
  const profile = resolveProfile(await loadConfig(), options.profile);
35200
36008
  const client = createApiClient(profile);
35201
- return apiRequest(client, method, path25, {
36009
+ return apiRequest(client, method, path27, {
35202
36010
  capability,
35203
36011
  data: redactAuditValue(data),
35204
36012
  params: params ? redactAuditValue(params) : void 0
@@ -35253,7 +36061,7 @@ function registerMemoryCommands(program2) {
35253
36061
  }
35254
36062
 
35255
36063
  // src/commands/matrix.ts
35256
- import { readFile as readFile20 } from "fs/promises";
36064
+ import { readFile as readFile21 } from "fs/promises";
35257
36065
  var UUID_VALUE_PATTERN2 = /\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/i;
35258
36066
  var UUID_PATH_PATTERN = /uuid'[^'"\s/]+/i;
35259
36067
  async function parseSeedRules(input) {
@@ -35261,7 +36069,7 @@ async function parseSeedRules(input) {
35261
36069
  if (source === "") {
35262
36070
  throw new Error("--rules file path is empty.");
35263
36071
  }
35264
- const raw = source ? await readFile20(source, "utf8") : input;
36072
+ const raw = source ? await readFile21(source, "utf8") : input;
35265
36073
  let parsed;
35266
36074
  try {
35267
36075
  parsed = JSON.parse(raw);
@@ -35280,15 +36088,15 @@ async function parseSeedRules(input) {
35280
36088
  });
35281
36089
  return rules;
35282
36090
  }
35283
- function collectUuidPaths(value, path25 = "$") {
36091
+ function collectUuidPaths(value, path27 = "$") {
35284
36092
  if (typeof value === "string") {
35285
- return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path25] : [];
36093
+ return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path27] : [];
35286
36094
  }
35287
36095
  if (Array.isArray(value)) {
35288
- return value.flatMap((item, index) => collectUuidPaths(item, `${path25}[${index}]`));
36096
+ return value.flatMap((item, index) => collectUuidPaths(item, `${path27}[${index}]`));
35289
36097
  }
35290
36098
  if (typeof value === "object" && value !== null) {
35291
- return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path25}.${key}`));
36099
+ return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path27}.${key}`));
35292
36100
  }
35293
36101
  return [];
35294
36102
  }
@@ -35357,24 +36165,24 @@ async function hydrateMatrixRuleRecords(client, records) {
35357
36165
  const hydrated = [];
35358
36166
  for (let index = 0; index < records.length; index += 10) {
35359
36167
  const chunk = records.slice(index, index + 10);
35360
- hydrated.push(...await Promise.all(chunk.map(async (record) => {
35361
- if (isRecord17(record.metaForm) || Array.isArray(record.formList)) return record;
35362
- const id = Number(record.id ?? record.project_id);
35363
- return Number.isSafeInteger(id) && id > 0 ? apiRequest(client, "GET", `/project/${id}`) : record;
36168
+ hydrated.push(...await Promise.all(chunk.map(async (record2) => {
36169
+ if (isRecord17(record2.metaForm) || Array.isArray(record2.formList)) return record2;
36170
+ const id = Number(record2.id ?? record2.project_id);
36171
+ return Number.isSafeInteger(id) && id > 0 ? apiRequest(client, "GET", `/project/${id}`) : record2;
35364
36172
  })));
35365
36173
  }
35366
36174
  return hydrated;
35367
36175
  }
35368
- function collectMatrixOwnerPaths(value, path25 = "$") {
36176
+ function collectMatrixOwnerPaths(value, path27 = "$") {
35369
36177
  if (Array.isArray(value)) {
35370
- return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path25}[${index}]`));
36178
+ return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path27}[${index}]`));
35371
36179
  }
35372
36180
  if (!isRecord17(value)) {
35373
36181
  return [];
35374
36182
  }
35375
36183
  const matches = [];
35376
36184
  Object.entries(value).forEach(([key, child]) => {
35377
- const childPath = `${path25}.${key}`;
36185
+ const childPath = `${path27}.${key}`;
35378
36186
  if (key.includes("matrix_owner") || typeof child === "string" && child.includes("matrix_owner")) {
35379
36187
  matches.push({ path: childPath, value: child });
35380
36188
  }
@@ -35865,9 +36673,9 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
35865
36673
  errors.push({ code: "matrix.rules.records_required", rule_id: "matrix.rules.records_required", domain: "approval-matrix", path: "$.rules", message: "\u77E9\u9635\u6D41\u7A0B\u5C1A\u65E0\u7EBF\u4E0A\u89C4\u5219\u8BB0\u5F55\u3002", suggestion: "\u5148\u901A\u8FC7\u5B89\u5168\u9879\u76EE\u521B\u5EFA\u94FE\u8DEF\u5F55\u5165\u771F\u5B9E\u77E9\u9635\u89C4\u5219\u3002" });
35866
36674
  }
35867
36675
  const approverIds = /* @__PURE__ */ new Set();
35868
- records.forEach((record, index) => {
36676
+ records.forEach((record2, index) => {
35869
36677
  options.approverField.forEach((field) => {
35870
- const ids = collectUserIds(projectField(record, field));
36678
+ const ids = collectUserIds(projectField(record2, field));
35871
36679
  if (!ids.length) {
35872
36680
  errors.push({ code: "matrix.rules.approver_required", rule_id: "matrix.rules.approver_required", domain: "approval-matrix", path: `$.rules[${index}].${field}`, message: `\u77E9\u9635\u89C4\u5219\u8BB0\u5F55 ${index + 1} \u7684\u5BA1\u6279\u4EBA\u5B57\u6BB5 ${field} \u4E3A\u7A7A\u6216\u4E0D\u662F\u7528\u6237 ID\u3002`, suggestion: "\u586B\u5165\u771F\u5B9E\u3001\u6709\u6548\u7684 BPMAX \u7528\u6237\u3002" });
35873
36681
  }
@@ -35992,8 +36800,8 @@ async function readDepartments(client, ids) {
35992
36800
  function pathIds(departments) {
35993
36801
  const ids = /* @__PURE__ */ new Set();
35994
36802
  for (const department of departments) {
35995
- const path25 = String(department.path ?? "");
35996
- for (const part of path25.split(/[|,]/)) {
36803
+ const path27 = String(department.path ?? "");
36804
+ for (const part of path27.split(/[|,]/)) {
35997
36805
  const id = Number(part);
35998
36806
  if (Number.isSafeInteger(id) && id > 0) ids.add(id);
35999
36807
  }
@@ -36226,6 +37034,147 @@ function registerOrganizationCommands(program2) {
36226
37034
  }
36227
37035
 
36228
37036
  // src/commands/plugin.ts
37037
+ function collect2(value, previous = []) {
37038
+ return [...previous, value];
37039
+ }
37040
+ function uniqueSorted(values) {
37041
+ return [...new Set(values.map((value) => value.trim()).filter(Boolean))].sort();
37042
+ }
37043
+ function sameStrings(left, right) {
37044
+ return JSON.stringify(uniqueSorted(left)) === JSON.stringify(uniqueSorted(right));
37045
+ }
37046
+ function record(value) {
37047
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
37048
+ }
37049
+ function stringArray(value) {
37050
+ return uniqueSorted(Array.isArray(value) ? value.filter((item) => typeof item === "string") : []);
37051
+ }
37052
+ function normalizeActivationOverview(value) {
37053
+ const source = record(value);
37054
+ if (!Array.isArray(source.plugins) || !Array.isArray(source.workspaces) || !Array.isArray(source.default_plugins)) {
37055
+ throw new Error("plugin.activation.invalid_readback: overview \u7F3A\u5C11 plugins\u3001workspaces \u6216 default_plugins \u6570\u7EC4\u3002");
37056
+ }
37057
+ const plugins = Array.isArray(source.plugins) ? source.plugins.map(record).map((plugin) => ({
37058
+ ...plugin,
37059
+ en_name: String(plugin.en_name || "").trim(),
37060
+ default_active: plugin.default_active === true,
37061
+ active_workspaces: stringArray(plugin.active_workspaces)
37062
+ })).filter((plugin) => plugin.en_name) : [];
37063
+ const workspaces = Array.isArray(source.workspaces) ? source.workspaces.map(record).map((workspace) => ({
37064
+ ...workspace,
37065
+ key: String(workspace.key || "").trim(),
37066
+ active_plugins: stringArray(workspace.active_plugins)
37067
+ })).filter((workspace) => workspace.key) : [];
37068
+ if (plugins.length !== source.plugins.length || new Set(plugins.map((plugin) => plugin.en_name)).size !== plugins.length) {
37069
+ throw new Error("plugin.activation.invalid_readback: plugins \u5305\u542B\u7A7A\u6216\u91CD\u590D en_name\u3002");
37070
+ }
37071
+ if (workspaces.length !== source.workspaces.length || new Set(workspaces.map((workspace) => workspace.key)).size !== workspaces.length) {
37072
+ throw new Error("plugin.activation.invalid_readback: workspaces \u5305\u542B\u7A7A\u6216\u91CD\u590D key\u3002");
37073
+ }
37074
+ const installed = new Set(plugins.map((plugin) => plugin.en_name));
37075
+ const workspaceKeys = new Set(workspaces.map((workspace) => workspace.key));
37076
+ const defaultPlugins = stringArray(source.default_plugins);
37077
+ const invalidPluginRefs = [
37078
+ ...defaultPlugins,
37079
+ ...workspaces.flatMap((workspace) => workspace.active_plugins)
37080
+ ].filter((pluginName) => !installed.has(pluginName));
37081
+ const invalidWorkspaceRefs = plugins.flatMap((plugin) => plugin.active_workspaces).filter((workspace) => !workspaceKeys.has(workspace));
37082
+ if (invalidPluginRefs.length || invalidWorkspaceRefs.length) {
37083
+ throw new Error("plugin.activation.invalid_readback: overview \u542B\u672A\u5B89\u88C5\u63D2\u4EF6\u6216\u4E0D\u5B58\u5728\u5DE5\u4F5C\u533A\u7684\u6FC0\u6D3B\u5F15\u7528\u3002");
37084
+ }
37085
+ return {
37086
+ plugins,
37087
+ workspaces,
37088
+ default_plugins: defaultPlugins
37089
+ };
37090
+ }
37091
+ async function readActivationOverview(client) {
37092
+ return normalizeActivationOverview(await apiRequest(client, "GET", "/plugin/activation_overview", {
37093
+ capability: "config.plugin.activation.export"
37094
+ }));
37095
+ }
37096
+ function validateActivationTargets(overview, options) {
37097
+ const plugins = uniqueSorted(options.plugins || []);
37098
+ const workspaces = uniqueSorted(options.workspaces || []);
37099
+ const installed = new Set(overview.plugins.map((plugin) => plugin.en_name));
37100
+ const availableWorkspaces = new Set(overview.workspaces.map((workspace) => workspace.key));
37101
+ const missingPlugins = plugins.filter((plugin) => !installed.has(plugin));
37102
+ const missingWorkspaces = workspaces.filter((workspace) => !availableWorkspaces.has(workspace));
37103
+ if (missingPlugins.length) {
37104
+ throw new Error(`plugin.activation.plugin_not_found: ${missingPlugins.join(", ")}`);
37105
+ }
37106
+ if (missingWorkspaces.length) {
37107
+ throw new Error(`plugin.activation.workspace_not_found: ${missingWorkspaces.join(", ")}`);
37108
+ }
37109
+ return { plugins, workspaces };
37110
+ }
37111
+ function activationOutput(profile, action, overview) {
37112
+ return {
37113
+ ok: true,
37114
+ domain: "plugin.activation",
37115
+ action,
37116
+ profile,
37117
+ evidence_layer: "typed_plugin_activation_readback",
37118
+ ...overview
37119
+ };
37120
+ }
37121
+ function errorMessage2(error) {
37122
+ return error instanceof Error ? error.message : String(error);
37123
+ }
37124
+ async function submitActivationMutation(client, profileName, data, verify) {
37125
+ let submitError;
37126
+ try {
37127
+ await apiRequest(client, "PUT", "/plugin/activation", {
37128
+ capability: "config.plugin.activation.submit",
37129
+ data
37130
+ });
37131
+ } catch (error) {
37132
+ submitError = error;
37133
+ }
37134
+ let after;
37135
+ let readbackError;
37136
+ try {
37137
+ after = await readActivationOverview(client);
37138
+ } catch (error) {
37139
+ readbackError = error;
37140
+ }
37141
+ if (after) {
37142
+ const verification = verify(after);
37143
+ if (verification.verified) {
37144
+ return {
37145
+ ok: true,
37146
+ status: submitError ? "readback_verified_after_submit_error" : "readback_verified",
37147
+ remote_submission_state: "submitted",
37148
+ remote_submitted: true,
37149
+ readback_confirmed: true,
37150
+ ...submitError ? { submit_error: errorMessage2(submitError) } : {},
37151
+ ...verification.details,
37152
+ readback: activationOutput(profileName, "overview", after)
37153
+ };
37154
+ }
37155
+ return {
37156
+ ok: false,
37157
+ status: submitError ? "submit_failed_readback_mismatch" : "submitted_readback_mismatch",
37158
+ remote_submission_state: submitError ? "unknown" : "submitted",
37159
+ remote_submitted: submitError ? null : true,
37160
+ readback_confirmed: false,
37161
+ ...submitError ? { submit_error: errorMessage2(submitError) } : {},
37162
+ ...verification.details,
37163
+ readback: activationOutput(profileName, "overview", after),
37164
+ retry_guidance: submitError ? "\u63D0\u4EA4\u7ED3\u679C\u672A\u77E5\u3002\u5148\u91CD\u65B0\u6267\u884C overview \u6838\u5BF9\u5F53\u524D\u72B6\u6001\uFF1B\u4E0D\u5F97\u76F4\u63A5\u91CD\u8BD5\u5199\u5165\u3002" : "\u670D\u52A1\u7AEF\u5DF2\u63A5\u53D7\u63D0\u4EA4\u4F46\u56DE\u8BFB\u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\u3002\u505C\u6B62\u540E\u7EED\u5199\u5165\u5E76\u68C0\u67E5\u670D\u52A1\u7AEF\u72B6\u6001\u3002"
37165
+ };
37166
+ }
37167
+ return {
37168
+ ok: false,
37169
+ status: submitError ? "submit_failed_readback_failed" : "submitted_readback_failed",
37170
+ remote_submission_state: submitError ? "unknown" : "submitted",
37171
+ remote_submitted: submitError ? null : true,
37172
+ readback_confirmed: false,
37173
+ ...submitError ? { submit_error: errorMessage2(submitError) } : {},
37174
+ readback_error: errorMessage2(readbackError),
37175
+ retry_guidance: submitError ? "\u63D0\u4EA4\u548C\u56DE\u8BFB\u5747\u5931\u8D25\uFF0C\u7ED3\u679C\u672A\u77E5\u3002\u6062\u590D\u53EA\u8BFB\u8BBF\u95EE\u540E\u5148\u6267\u884C overview\uFF1B\u4E0D\u5F97\u76F4\u63A5\u91CD\u8BD5\u5199\u5165\u3002" : "\u63D0\u4EA4\u5DF2\u53D1\u9001\u4F46\u56DE\u8BFB\u5931\u8D25\u3002\u6062\u590D\u53EA\u8BFB\u8BBF\u95EE\u540E\u5148\u6267\u884C overview\uFF1B\u4E0D\u5F97\u518D\u6B21\u63D0\u4EA4\u3002"
37176
+ };
37177
+ }
36229
37178
  function defaultAgent2(options) {
36230
37179
  return options.agent || process.env.BPMAX_CLI_AGENT || "codex";
36231
37180
  }
@@ -36237,7 +37186,137 @@ function selectSkills(skills, skillName) {
36237
37186
  }
36238
37187
  function registerPluginCommands(program2) {
36239
37188
  const plugin = program2.command("plugin").description("Manage BPMAX plugins and plugin-scoped Agent skills");
37189
+ const activation = plugin.command("activation").description("Inspect and manage organization/workspace plugin activation");
36240
37190
  const skills = plugin.command("skills").description("Manage plugin-scoped Agent skills");
37191
+ activation.command("overview").description("Read installed plugins and their effective organization/workspace activation").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
37192
+ const profile = resolveProfile(await loadConfig(), options.profile);
37193
+ const overview = await readActivationOverview(createApiClient(profile));
37194
+ printResult(options.format, activationOutput(profile.name, "overview", overview));
37195
+ });
37196
+ const workspaceActivation = activation.command("workspace").description("Manage effective plugins for one workspace");
37197
+ workspaceActivation.command("set").description("Replace the selected workspace plugin set; organization defaults remain mandatory").requiredOption("--workspace <workspace>", "Workspace key").option("--plugin <plugin>", "Plugin name, repeatable; omit all occurrences to keep only organization defaults", collect2, []).option("--confirm", "Submit the mutation after the dry-run has been reviewed").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
37198
+ const profile = resolveProfile(await loadConfig(), options.profile);
37199
+ const client = createApiClient(profile);
37200
+ const before = await readActivationOverview(client);
37201
+ const targets = validateActivationTargets(before, { plugins: options.plugin, workspaces: [options.workspace] });
37202
+ const workspace = targets.workspaces[0];
37203
+ const expected = uniqueSorted([...targets.plugins, ...before.default_plugins]);
37204
+ const plan = {
37205
+ ok: true,
37206
+ domain: "plugin.activation",
37207
+ action: "set_workspace_plugins",
37208
+ profile: profile.name,
37209
+ status: options.confirm ? "submitting" : "dry_run",
37210
+ workspace,
37211
+ requested_plugins: targets.plugins,
37212
+ mandatory_default_plugins: before.default_plugins,
37213
+ expected_effective_plugins: expected,
37214
+ remote_submitted: false
37215
+ };
37216
+ if (!options.confirm) {
37217
+ printResult(options.format, plan);
37218
+ return;
37219
+ }
37220
+ const result = await submitActivationMutation(
37221
+ client,
37222
+ profile.name,
37223
+ { action: "set_workspace_plugins", workspace_key: workspace, plugin_names: targets.plugins },
37224
+ (after) => {
37225
+ const actual = after.workspaces.find((item) => item.key === workspace)?.active_plugins || [];
37226
+ return {
37227
+ verified: sameStrings(actual, expected),
37228
+ details: { actual_effective_plugins: actual }
37229
+ };
37230
+ }
37231
+ );
37232
+ printResult(options.format, {
37233
+ ...plan,
37234
+ ...result
37235
+ });
37236
+ if (!result.ok) process.exitCode = 1;
37237
+ });
37238
+ const pluginActivation = activation.command("plugin").description("Manage the workspaces for one installed plugin");
37239
+ pluginActivation.command("set-workspaces").description("Replace the workspace set for one plugin").requiredOption("--plugin <plugin>", "Plugin name").option("--workspace <workspace>", "Workspace key, repeatable; omit all occurrences to deactivate everywhere", collect2, []).option("--confirm", "Submit the mutation after the dry-run has been reviewed").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
37240
+ const profile = resolveProfile(await loadConfig(), options.profile);
37241
+ const client = createApiClient(profile);
37242
+ const before = await readActivationOverview(client);
37243
+ const targets = validateActivationTargets(before, { plugins: [options.plugin], workspaces: options.workspace });
37244
+ const pluginName = targets.plugins[0];
37245
+ const pluginState = before.plugins.find((item) => item.en_name === pluginName);
37246
+ if (pluginState.default_active && targets.workspaces.length !== before.workspaces.length) {
37247
+ throw new Error(`plugin.activation.default_plugin_cannot_disable: ${pluginName} \u662F\u7EC4\u7EC7\u9ED8\u8BA4\u63D2\u4EF6\uFF0C\u5FC5\u987B\u5728\u5168\u90E8\u5DE5\u4F5C\u533A\u751F\u6548\u3002`);
37248
+ }
37249
+ const expected = pluginState.default_active ? uniqueSorted(before.workspaces.map((item) => item.key)) : targets.workspaces;
37250
+ const plan = {
37251
+ ok: true,
37252
+ domain: "plugin.activation",
37253
+ action: "set_plugin_workspaces",
37254
+ profile: profile.name,
37255
+ status: options.confirm ? "submitting" : "dry_run",
37256
+ plugin: pluginName,
37257
+ default_active: pluginState.default_active,
37258
+ expected_active_workspaces: expected,
37259
+ remote_submitted: false
37260
+ };
37261
+ if (!options.confirm) {
37262
+ printResult(options.format, plan);
37263
+ return;
37264
+ }
37265
+ const result = await submitActivationMutation(
37266
+ client,
37267
+ profile.name,
37268
+ { action: "set_plugin_workspaces", plugin_name: pluginName, workspace_keys: targets.workspaces },
37269
+ (after) => {
37270
+ const actual = after.plugins.find((item) => item.en_name === pluginName)?.active_workspaces || [];
37271
+ return {
37272
+ verified: sameStrings(actual, expected),
37273
+ details: { actual_active_workspaces: actual }
37274
+ };
37275
+ }
37276
+ );
37277
+ printResult(options.format, {
37278
+ ...plan,
37279
+ ...result
37280
+ });
37281
+ if (!result.ok) process.exitCode = 1;
37282
+ });
37283
+ const defaultsActivation = activation.command("defaults").description("Manage organization-wide mandatory plugin activation");
37284
+ defaultsActivation.command("set").description("Replace organization default plugins; defaults apply to existing and future workspaces").option("--plugin <plugin>", "Plugin name, repeatable; omit all occurrences to clear organization defaults", collect2, []).option("--confirm", "Submit the mutation after the dry-run has been reviewed").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
37285
+ const profile = resolveProfile(await loadConfig(), options.profile);
37286
+ const client = createApiClient(profile);
37287
+ const before = await readActivationOverview(client);
37288
+ const targets = validateActivationTargets(before, { plugins: options.plugin });
37289
+ const removedDefaults = before.default_plugins.filter((pluginName) => !targets.plugins.includes(pluginName));
37290
+ const plan = {
37291
+ ok: true,
37292
+ domain: "plugin.activation",
37293
+ action: "set_default_plugins",
37294
+ profile: profile.name,
37295
+ status: options.confirm ? "submitting" : "dry_run",
37296
+ expected_default_plugins: targets.plugins,
37297
+ removed_default_plugins: removedDefaults,
37298
+ warning: removedDefaults.length ? "\u79FB\u51FA\u7EC4\u7EC7\u9ED8\u8BA4\u96C6\u5408\u4E0D\u4F1A\u627F\u8BFA\u5173\u95ED\u5404\u5DE5\u4F5C\u533A\u4E2D\u4ECD\u663E\u5F0F\u6FC0\u6D3B\u7684\u63D2\u4EF6\uFF1B\u8BF7\u4EE5\u5199\u540E overview \u4E3A\u51C6\u3002" : void 0,
37299
+ remote_submitted: false
37300
+ };
37301
+ if (!options.confirm) {
37302
+ printResult(options.format, plan);
37303
+ return;
37304
+ }
37305
+ const result = await submitActivationMutation(
37306
+ client,
37307
+ profile.name,
37308
+ { action: "set_default_plugins", plugin_names: targets.plugins },
37309
+ (after) => ({
37310
+ verified: sameStrings(after.default_plugins, targets.plugins) && targets.plugins.every((pluginName) => after.workspaces.every((workspace) => workspace.active_plugins.includes(pluginName))),
37311
+ details: { actual_default_plugins: after.default_plugins }
37312
+ })
37313
+ );
37314
+ printResult(options.format, {
37315
+ ...plan,
37316
+ ...result
37317
+ });
37318
+ if (!result.ok) process.exitCode = 1;
37319
+ });
36241
37320
  skills.command("list").argument("[plugin]", "Plugin name").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (pluginName, options) => {
36242
37321
  const profile = resolveProfile(await loadConfig(), options.profile);
36243
37322
  const result = pluginName ? await apiRequest(createApiClient(profile), "GET", `/cli/plugins/${pluginName}/skills`) : await apiRequest(createApiClient(profile), "GET", "/cli/plugins", { params: { include_skills: 1 } });
@@ -36711,7 +37790,7 @@ async function parseProjectJson(input, label = "--json") {
36711
37790
  }
36712
37791
  return parseJsonInput(input, label);
36713
37792
  }
36714
- function errorMessage2(error) {
37793
+ function errorMessage3(error) {
36715
37794
  return error instanceof Error ? error.message : String(error || "");
36716
37795
  }
36717
37796
  function isRecordValue(value) {
@@ -36935,17 +38014,17 @@ function assertStepProjectFormWritable(fields, form, prefix = "") {
36935
38014
  for (const [key, value] of Object.entries(form)) {
36936
38015
  const field = fieldsByKey.get(key);
36937
38016
  if (!field) continue;
36938
- const path25 = `${prefix}${key}`;
38017
+ const path27 = `${prefix}${key}`;
36939
38018
  if (field.hidden) {
36940
- throw new Error(`Step project form handoff cannot write hidden field ${path25}.`);
38019
+ throw new Error(`Step project form handoff cannot write hidden field ${path27}.`);
36941
38020
  }
36942
38021
  if (isUnsupportedStepPrefillField(field)) {
36943
- throw new Error(`Step project form handoff cannot write system or manual field ${path25} (${field.type || "unknown"}).`);
38022
+ throw new Error(`Step project form handoff cannot write system or manual field ${path27} (${field.type || "unknown"}).`);
36944
38023
  }
36945
38024
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
36946
38025
  value.forEach((row, index) => {
36947
38026
  if (isRecordValue(row)) {
36948
- assertStepProjectFormWritable(field.children ?? [], row, `${path25}[${index}].`);
38027
+ assertStepProjectFormWritable(field.children ?? [], row, `${path27}[${index}].`);
36949
38028
  }
36950
38029
  });
36951
38030
  }
@@ -37302,9 +38381,9 @@ function contextField(field, reason, options = {}) {
37302
38381
  function collectPrefillContextForFields(fields, form, result, options = {}) {
37303
38382
  for (const field of fields) {
37304
38383
  const value = form[field.key];
37305
- const path25 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
38384
+ const path27 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
37306
38385
  const fieldOptions = {
37307
- path: path25,
38386
+ path: path27,
37308
38387
  rootKey: options.rootKey ?? field.key,
37309
38388
  parentKey: options.parentKey
37310
38389
  };
@@ -37559,7 +38638,7 @@ function registerProjectCommands(program2) {
37559
38638
  next_action: "Token lookup only proves the prefill payload is readable; open the returned handoff URL in a real browser page before claiming creation succeeded."
37560
38639
  });
37561
38640
  } catch (error) {
37562
- const message = errorMessage2(error);
38641
+ const message = errorMessage3(error);
37563
38642
  if (!isUnsupportedPrefillStatusError(message)) {
37564
38643
  throw error;
37565
38644
  }
@@ -37748,8 +38827,8 @@ import { spawn as spawn2 } from "child_process";
37748
38827
  import { fileURLToPath as fileURLToPath4 } from "url";
37749
38828
 
37750
38829
  // src/core/recipes.ts
37751
- import { access, mkdir as mkdir15, readdir as readdir7, readFile as readFile21, writeFile as writeFile15 } from "fs/promises";
37752
- import path20 from "path";
38830
+ import { access, mkdir as mkdir16, readdir as readdir7, readFile as readFile22, writeFile as writeFile16 } from "fs/promises";
38831
+ import path22 from "path";
37753
38832
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
37754
38833
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
37755
38834
  function assertSafeName(kind, value) {
@@ -37773,12 +38852,12 @@ function resolveRecipeLocation(options) {
37773
38852
  workspace,
37774
38853
  workspaceDirName,
37775
38854
  recipeName: options.recipeName,
37776
- recipeDir: path20.join(profileDir, "recipes", workspaceDirName, options.recipeName)
38855
+ recipeDir: path22.join(profileDir, "recipes", workspaceDirName, options.recipeName)
37777
38856
  };
37778
38857
  }
37779
38858
  function getRecipesDir(options) {
37780
38859
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
37781
- return path20.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
38860
+ return path22.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
37782
38861
  }
37783
38862
  function isRecord21(value) {
37784
38863
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -37830,7 +38909,7 @@ function parseRecipeDefinition(input) {
37830
38909
  };
37831
38910
  }
37832
38911
  async function loadRecipe(recipeDir) {
37833
- const raw = await readFile21(path20.join(recipeDir, "recipe.json"), "utf8");
38912
+ const raw = await readFile22(path22.join(recipeDir, "recipe.json"), "utf8");
37834
38913
  return parseRecipeDefinition(JSON.parse(raw));
37835
38914
  }
37836
38915
  async function listRecipes(recipesDir) {
@@ -37848,7 +38927,7 @@ async function listRecipes(recipesDir) {
37848
38927
  if (!RECIPE_NAME_PATTERN.test(entry)) {
37849
38928
  continue;
37850
38929
  }
37851
- const recipeDir = path20.join(recipesDir, entry);
38930
+ const recipeDir = path22.join(recipesDir, entry);
37852
38931
  try {
37853
38932
  const recipe = await loadRecipe(recipeDir);
37854
38933
  summaries.push({
@@ -37914,12 +38993,12 @@ function renderTemplate(template, variables) {
37914
38993
  }
37915
38994
  function resolveRecipeFile(recipeDir, token) {
37916
38995
  const relative = token.slice(1);
37917
- if (!relative || relative.includes("..") || path20.isAbsolute(relative)) {
38996
+ if (!relative || relative.includes("..") || path22.isAbsolute(relative)) {
37918
38997
  throw new Error(`Unsafe recipe file reference: ${token}`);
37919
38998
  }
37920
- const resolved = path20.resolve(recipeDir, relative);
37921
- const root = path20.resolve(recipeDir);
37922
- if (resolved !== root && !resolved.startsWith(`${root}${path20.sep}`)) {
38999
+ const resolved = path22.resolve(recipeDir, relative);
39000
+ const root = path22.resolve(recipeDir);
39001
+ if (resolved !== root && !resolved.startsWith(`${root}${path22.sep}`)) {
37923
39002
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
37924
39003
  }
37925
39004
  return resolved;
@@ -37929,7 +39008,7 @@ async function renderArgv(options) {
37929
39008
  const rendered = [];
37930
39009
  for (const token of options.recipe.command.argv) {
37931
39010
  if (token.startsWith("@")) {
37932
- const raw = await readFile21(resolveRecipeFile(options.recipeDir, token), "utf8");
39011
+ const raw = await readFile22(resolveRecipeFile(options.recipeDir, token), "utf8");
37933
39012
  rendered.push(renderTemplate(raw, options.variables));
37934
39013
  } else {
37935
39014
  rendered.push(renderTemplate(token, options.variables));
@@ -37955,7 +39034,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
37955
39034
  }
37956
39035
  async function writeRecipeScaffold(options) {
37957
39036
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
37958
- await mkdir15(options.location.recipeDir, { recursive: true });
39037
+ await mkdir16(options.location.recipeDir, { recursive: true });
37959
39038
  const title = options.title || options.location.recipeName;
37960
39039
  const recipe = {
37961
39040
  version: 1,
@@ -37972,16 +39051,16 @@ async function writeRecipeScaffold(options) {
37972
39051
  mutating: true
37973
39052
  }
37974
39053
  };
37975
- await writeFile15(path20.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
39054
+ await writeFile16(path22.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
37976
39055
  `, "utf8");
37977
- await writeFile15(
37978
- path20.join(options.location.recipeDir, "payload.json"),
39056
+ await writeFile16(
39057
+ path22.join(options.location.recipeDir, "payload.json"),
37979
39058
  `${JSON.stringify({ form: {} }, null, 2)}
37980
39059
  `,
37981
39060
  "utf8"
37982
39061
  );
37983
- await writeFile15(
37984
- path20.join(options.location.recipeDir, "README.md"),
39062
+ await writeFile16(
39063
+ path22.join(options.location.recipeDir, "README.md"),
37985
39064
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
37986
39065
  "utf8"
37987
39066
  );
@@ -38266,8 +39345,8 @@ function registerSetupCommand(program2, deps = {}) {
38266
39345
  }
38267
39346
 
38268
39347
  // src/core/taskbook.ts
38269
- import { mkdir as mkdir16, readFile as readFile22, writeFile as writeFile16 } from "fs/promises";
38270
- import path21 from "path";
39348
+ import { mkdir as mkdir17, readFile as readFile23, writeFile as writeFile17 } from "fs/promises";
39349
+ import path23 from "path";
38271
39350
  var TaskbookError = class extends Error {
38272
39351
  };
38273
39352
  var REQUIRED_TASKBOOK_TERMS = [
@@ -38519,19 +39598,19 @@ function hasDomainWriteEvidence(domain, evidenceText, patterns) {
38519
39598
  function uuidValues(text5) {
38520
39599
  return [...new Set([...text5.matchAll(UUID_PATTERN)].map((match) => match[0]))];
38521
39600
  }
38522
- function addUuidIssues(text5, issues, path25) {
39601
+ function addUuidIssues(text5, issues, path27) {
38523
39602
  for (const value of uuidValues(text5)) {
38524
39603
  addTaskbookIssue(
38525
39604
  issues,
38526
39605
  "uuid_not_allowed",
38527
39606
  "taskbook.config.no_uuid",
38528
39607
  `BPMAX \u914D\u7F6E\u4EFB\u52A1\u4E0D\u80FD\u4F7F\u7528 UUID\uFF1A${value}\u3002`,
38529
- { path: path25, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
39608
+ { path: path27, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
38530
39609
  );
38531
39610
  }
38532
39611
  }
38533
39612
  async function readTaskbookText(file) {
38534
- const raw = await readFile22(file, "utf8");
39613
+ const raw = await readFile23(file, "utf8");
38535
39614
  try {
38536
39615
  const parsed = JSON.parse(raw);
38537
39616
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
@@ -38558,7 +39637,7 @@ function findNavigationStrategy(text5) {
38558
39637
  const matches = [...text5.matchAll(/导航入口策略\s*[::]\s*(nav-config:(?:included|skipped:[^\s|,。]+|deferred:[^\s|,。]+))/gi)];
38559
39638
  return matches.at(-1)?.[1] || null;
38560
39639
  }
38561
- function validateNavigationStrategy(text5, issues, path25, subject) {
39640
+ function validateNavigationStrategy(text5, issues, path27, subject) {
38562
39641
  const strategy = findNavigationStrategy(text5);
38563
39642
  if (!strategy) {
38564
39643
  addTaskbookIssue(
@@ -38566,7 +39645,7 @@ function validateNavigationStrategy(text5, issues, path25, subject) {
38566
39645
  "missing_navigation_strategy",
38567
39646
  "taskbook.nav.strategy",
38568
39647
  `${subject}\u7F3A\u5C11\u660E\u786E\u7684\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u3002`,
38569
- { path: path25, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
39648
+ { path: path27, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
38570
39649
  );
38571
39650
  return null;
38572
39651
  }
@@ -38576,7 +39655,7 @@ function validateNavigationStrategy(text5, issues, path25, subject) {
38576
39655
  "empty_navigation_strategy_reason",
38577
39656
  "taskbook.nav.strategy_reason",
38578
39657
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u8DF3\u8FC7\u6216\u5EF6\u540E\u65F6\u5FC5\u987B\u5199\u660E\u539F\u56E0\u3002`,
38579
- { path: path25, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
39658
+ { path: path27, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
38580
39659
  );
38581
39660
  }
38582
39661
  if (/(待完成范围确认后回填|待确认|TODO|TBD|占位)/i.test(strategy)) {
@@ -38585,7 +39664,7 @@ function validateNavigationStrategy(text5, issues, path25, subject) {
38585
39664
  "placeholder_navigation_strategy",
38586
39665
  "taskbook.nav.strategy_placeholder",
38587
39666
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u4ECD\u662F\u5360\u4F4D\u5185\u5BB9\u3002`,
38588
- { path: path25, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
39667
+ { path: path27, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
38589
39668
  );
38590
39669
  }
38591
39670
  return strategy;
@@ -39583,8 +40662,8 @@ function taskbookTemplate(title = "BPMAX AI \u5B9E\u65BD\u7F16\u6392\u4EFB\u52A1
39583
40662
  }
39584
40663
  async function initTaskbook(outFile, title) {
39585
40664
  const content = taskbookTemplate(title);
39586
- await mkdir16(path21.dirname(outFile), { recursive: true });
39587
- await writeFile16(outFile, content, "utf8");
40665
+ await mkdir17(path23.dirname(outFile), { recursive: true });
40666
+ await writeFile17(outFile, content, "utf8");
39588
40667
  return { out: outFile, bytes: Buffer.byteLength(content) };
39589
40668
  }
39590
40669
  function splitMarkdownRow(line) {
@@ -39673,13 +40752,13 @@ async function initTaskbookProgress(source, outFile) {
39673
40752
  fields.join(","),
39674
40753
  ...rows2.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
39675
40754
  ].join("\n") + "\n";
39676
- await mkdir16(path21.dirname(outFile), { recursive: true });
39677
- await writeFile16(outFile, csv, "utf8");
40755
+ await mkdir17(path23.dirname(outFile), { recursive: true });
40756
+ await writeFile17(outFile, csv, "utf8");
39678
40757
  return { source, out: outFile, task_count: rows2.length };
39679
40758
  }
39680
40759
 
39681
40760
  // src/commands/taskbook.ts
39682
- function collect2(value, previous = []) {
40761
+ function collect3(value, previous = []) {
39683
40762
  previous.push(value);
39684
40763
  return previous;
39685
40764
  }
@@ -39688,7 +40767,7 @@ function registerTaskbookCommands(program2) {
39688
40767
  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) => {
39689
40768
  printResult(options.format, await initTaskbook(options.out, options.title));
39690
40769
  });
39691
- 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", collect2, []).option("--forbid-term <term>", "Forbidden term", collect2, []).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) => {
40770
+ 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", collect3, []).option("--forbid-term <term>", "Forbidden term", collect3, []).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) => {
39692
40771
  const result = await lintTaskbook(options.source, {
39693
40772
  requireTerms: options.requireTerm,
39694
40773
  forbidTerms: options.forbidTerm,
@@ -39699,7 +40778,7 @@ function registerTaskbookCommands(program2) {
39699
40778
  throw new Error(`Taskbook lint failed for ${options.source}`);
39700
40779
  }
39701
40780
  });
39702
- 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", collect2, []).option("--forbid-term <term>", "Forbidden term", collect2, []).option("--format <format>", "Output format", "pretty").action(async (options) => {
40781
+ 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", collect3, []).option("--forbid-term <term>", "Forbidden term", collect3, []).option("--format <format>", "Output format", "pretty").action(async (options) => {
39703
40782
  const result = await lintTaskPrompt(options.promptSource, {
39704
40783
  requireTerms: options.requireTerm,
39705
40784
  forbidTerms: options.forbidTerm
@@ -39716,10 +40795,10 @@ function registerTaskbookCommands(program2) {
39716
40795
  }
39717
40796
 
39718
40797
  // src/commands/test-suite.ts
39719
- import { readFile as readFile23 } from "fs/promises";
39720
- import path22 from "path";
40798
+ import { readFile as readFile24 } from "fs/promises";
40799
+ import path24 from "path";
39721
40800
  import { fileURLToPath as fileURLToPath5 } from "url";
39722
- function collect3(value, previous = []) {
40801
+ function collect4(value, previous = []) {
39723
40802
  previous.push(value);
39724
40803
  return previous;
39725
40804
  }
@@ -39728,8 +40807,8 @@ function effectiveProfileOption(options, command) {
39728
40807
  }
39729
40808
  async function resolveE2eSkillSource(sourceSkill, agent) {
39730
40809
  if (sourceSkill) {
39731
- const resolved = path22.resolve(sourceSkill);
39732
- const content = await readFile23(resolved, "utf8").catch(() => "");
40810
+ const resolved = path24.resolve(sourceSkill);
40811
+ const content = await readFile24(resolved, "utf8").catch(() => "");
39733
40812
  const declaredName = /^name:\s*["']?([^"'\s]+)["']?\s*$/m.exec(content)?.[1];
39734
40813
  if (!["bpmax-e2e-flow-test-operator", "bpmax-e2e-flow-test-operator-v2"].includes(declaredName || "")) {
39735
40814
  throw new TestSuiteError("source skill is not a supported bpmax E2E flow test operator", {
@@ -39753,7 +40832,7 @@ async function resolveE2eSkillSource(sourceSkill, agent) {
39753
40832
  });
39754
40833
  }
39755
40834
  const packageRoot = await resolvePackageRootFrom(fileURLToPath5(import.meta.url));
39756
- const packageSkill = path22.join(packageRoot, "skills", "bpmax-e2e-flow-test-operator", "SKILL.md");
40835
+ const packageSkill = path24.join(packageRoot, "skills", "bpmax-e2e-flow-test-operator", "SKILL.md");
39757
40836
  const expectedHash = await skillBundleSha256(packageSkill);
39758
40837
  const sources = await installedSkillSourcePaths("bpmax-e2e-flow-test-operator", agent);
39759
40838
  if (sources.length === 0) {
@@ -39783,21 +40862,21 @@ async function resolveE2eSkillSource(sourceSkill, agent) {
39783
40862
  }
39784
40863
  function registerTestSuiteCommands(program2) {
39785
40864
  const suite = program2.command("test-suite").description("Manage local BPMAX AI test case suites under .ai_test").option("--profile <profile>", "Profile name (accepted for workspace-rule compatibility; ignored by local-only commands)");
39786
- suite.command("lint").description("Lint BPMAX AI test case suite scenarios").option("--root <path>", "Suite root directory", DEFAULT_SUITE_ROOT).option("--scenario <id>", "Lint only this scenario; repeat for multiple scenarios in the same flow", collect3, []).requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--explain", "Include review.json schema and test_data alignment rules in the output").option("--format <format>", "Output format", "json").action(async (options) => {
40865
+ suite.command("lint").description("Lint BPMAX AI test case suite scenarios").option("--root <path>", "Suite root directory", DEFAULT_SUITE_ROOT).option("--scenario <id>", "Lint only this scenario; repeat for multiple scenarios in the same flow", collect4, []).requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--explain", "Include review.json schema and test_data alignment rules in the output").option("--format <format>", "Output format", "json").action(async (options) => {
39787
40866
  await requireLatestProof(options.latestProof);
39788
40867
  printResult(options.format, await lintSuiteDetailed(options.root, {
39789
40868
  explain: Boolean(options.explain),
39790
40869
  scenarios: options.scenario
39791
40870
  }));
39792
40871
  });
39793
- suite.command("index").description("Print the BPMAX AI test case suite index").option("--root <path>", "Suite root directory", DEFAULT_SUITE_ROOT).option("--scenario <id>", "Index only this scenario; repeat for multiple scenarios", collect3, []).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) => {
40872
+ suite.command("index").description("Print the BPMAX AI test case suite index").option("--root <path>", "Suite root directory", DEFAULT_SUITE_ROOT).option("--scenario <id>", "Index only this scenario; repeat for multiple scenarios", collect4, []).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) => {
39794
40873
  await requireLatestProof(options.latestProof);
39795
40874
  printResult(options.format, await indexSuite(options.root, Boolean(options.includeInactive), {
39796
40875
  scenarios: options.scenario
39797
40876
  }));
39798
40877
  });
39799
40878
  const automation = suite.command("automation").description("Compile deterministic browser automation before a formal E2E run");
39800
- automation.command("status").description("Classify selected V2 automation as reusable, regenerate_required, or blocked").requiredOption("--scenario <id>", "Scenario id").requiredOption("--case-id <id>", "Case id; repeat for a scoped automation decision", collect3, []).option("--root <path>", "Formal or draft 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) => {
40879
+ automation.command("status").description("Classify selected V2 automation as reusable, regenerate_required, or blocked").requiredOption("--scenario <id>", "Scenario id").requiredOption("--case-id <id>", "Case id; repeat for a scoped automation decision", collect4, []).option("--root <path>", "Formal or draft 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) => {
39801
40880
  printResult(options.format, await automationStatus({
39802
40881
  scenario: options.scenario,
39803
40882
  caseIds: options.caseId,
@@ -39805,7 +40884,7 @@ function registerTestSuiteCommands(program2) {
39805
40884
  latestProof: options.latestProof
39806
40885
  }));
39807
40886
  });
39808
- automation.command("init").description("Create a pre-run automation compile input from case_steps.csv").requiredOption("--scenario <id>", "Scenario id").option("--case-id <id>", "Case id; repeat to initialize only selected regenerate_required steps", collect3, []).option("--root <path>", "Draft suite root directory", DEFAULT_DRAFT_ROOT).requiredOption("--out <file>", "Compile input JSON to review and complete").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
40887
+ automation.command("init").description("Create a pre-run automation compile input from case_steps.csv").requiredOption("--scenario <id>", "Scenario id").option("--case-id <id>", "Case id; repeat to initialize only selected regenerate_required steps", collect4, []).option("--root <path>", "Draft suite root directory", DEFAULT_DRAFT_ROOT).requiredOption("--out <file>", "Compile input JSON to review and complete").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
39809
40888
  await requireLatestProof(options.latestProof);
39810
40889
  printResult(options.format, await initScenarioAutomationCompile({ ...options, caseIds: options.caseId }));
39811
40890
  });
@@ -39895,7 +40974,7 @@ function registerTestSuiteCommands(program2) {
39895
40974
  printResult(options.format, reviewSchemaExplanation());
39896
40975
  });
39897
40976
  const confirmation = suite.command("confirmation").description("Prepare and accept V2 E2E confirmations bound to current assets and scope");
39898
- confirmation.command("prepare").description("Prepare a V2 E2E confirmation request bound to current scenario assets and scope").requiredOption("--scenario <id>", "Scenario id; repeat for a shared scenario replacement", collect3, []).requiredOption("--scope <scope>", "asset_promotion, shared_scenario_replace, formal_execution, or asset_promotion_and_execution").option("--case-id <id>", "Selected case id for execution scopes; repeat as needed", collect3, []).option("--root <path>", "Scenario root directory", DEFAULT_DRAFT_ROOT).option("--output <file>", "Confirmation request output path").option("--format <format>", "Output format", "json").action(async (options) => {
40977
+ confirmation.command("prepare").description("Prepare a V2 E2E confirmation request bound to current scenario assets and scope").requiredOption("--scenario <id>", "Scenario id; repeat for a shared scenario replacement", collect4, []).requiredOption("--scope <scope>", "asset_promotion, shared_scenario_replace, formal_execution, or asset_promotion_and_execution").option("--case-id <id>", "Selected case id for execution scopes; repeat as needed", collect4, []).option("--root <path>", "Scenario root directory", DEFAULT_DRAFT_ROOT).option("--output <file>", "Confirmation request output path").option("--format <format>", "Output format", "json").action(async (options) => {
39899
40978
  if (!["asset_promotion", "shared_scenario_replace", "formal_execution", "asset_promotion_and_execution"].includes(options.scope)) {
39900
40979
  throw new TestSuiteError("invalid V2 confirmation scope", { rule_id: "test_suite.v2_confirmation.scope_invalid" });
39901
40980
  }
@@ -39914,7 +40993,7 @@ function registerTestSuiteCommands(program2) {
39914
40993
  await requireLatestProof(options.latestProof);
39915
40994
  printResult(options.format, await draftUpdate(options));
39916
40995
  });
39917
- suite.command("promote").description("Promote reviewed draft scenarios from one flow to the formal suite").requiredOption("--scenario <id>", "Scenario id; repeat to preflight and promote multiple scenarios from one flow", collect3, []).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").option("--confirmation <file>", "Accepted V2 confirmation receipt bound to the draft assets").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
40996
+ suite.command("promote").description("Promote reviewed draft scenarios from one flow to the formal suite").requiredOption("--scenario <id>", "Scenario id; repeat to preflight and promote multiple scenarios from one flow", collect4, []).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").option("--confirmation <file>", "Accepted V2 confirmation receipt bound to the draft assets").requiredOption("--latest-proof <path>", "latest-* proof JSON written after syncing the sysconfig repo").option("--format <format>", "Output format", "json").action(async (options) => {
39918
40997
  await requireLatestProof(options.latestProof);
39919
40998
  printResult(options.format, await promoteScenario({
39920
40999
  ...options,
@@ -39936,14 +41015,14 @@ function registerTestSuiteCommands(program2) {
39936
41015
  }
39937
41016
 
39938
41017
  // src/commands/test-fixture.ts
39939
- import { createHash as createHash14, randomUUID as randomUUID5 } from "crypto";
39940
- import { lstat as lstat5, readFile as readFile24, realpath as realpath9, rename as rename6, writeFile as writeFile17 } from "fs/promises";
39941
- import path23 from "path";
41018
+ import { createHash as createHash15, randomUUID as randomUUID5 } from "crypto";
41019
+ import { lstat as lstat5, readFile as readFile25, realpath as realpath9, rename as rename6, writeFile as writeFile18 } from "fs/promises";
41020
+ import path25 from "path";
39942
41021
  function isRecord22(value) {
39943
41022
  return typeof value === "object" && value !== null && !Array.isArray(value);
39944
41023
  }
39945
41024
  async function parseJsonInput2(value, option) {
39946
- const raw = value.startsWith("@") ? await readFile24(value.slice(1), "utf8") : value;
41025
+ const raw = value.startsWith("@") ? await readFile25(value.slice(1), "utf8") : value;
39947
41026
  const parsed = JSON.parse(raw);
39948
41027
  if (!isRecord22(parsed)) throw new Error(`test_fixture.invalid_json: ${option} \u5FC5\u987B\u662F JSON \u5BF9\u8C61\u6216 @file\u3002`);
39949
41028
  return parsed;
@@ -40043,7 +41122,7 @@ function fixtureAssets(manifest, seeds) {
40043
41122
  const mime = String(raw.mime ?? "").trim();
40044
41123
  const size = Number(raw.size);
40045
41124
  const purpose = String(raw.purpose ?? "").trim();
40046
- if (!relativePath.startsWith("fixtures/") || path23.posix.isAbsolute(relativePath) || relativePath.split("/").includes("..")) {
41125
+ if (!relativePath.startsWith("fixtures/") || path25.posix.isAbsolute(relativePath) || relativePath.split("/").includes("..")) {
40047
41126
  throw new Error(`test_fixture.invalid_asset_path: ${key} path \u5FC5\u987B\u4F4D\u4E8E\u573A\u666F fixtures/ \u76EE\u5F55\u5185\u3002`);
40048
41127
  }
40049
41128
  if (!/^[a-f0-9]{64}$/.test(sha2563) || !["image/png", "image/jpeg"].includes(mime) || !Number.isSafeInteger(size) || size <= 0 || size > 10 * 1024 * 1024 || !["project_create", "step_transition"].includes(purpose)) {
@@ -40282,9 +41361,9 @@ function fixtureRuntimeOutputs(seed, readback, requireOutputs = true) {
40282
41361
  }
40283
41362
  async function writeReceipt(output, receipt) {
40284
41363
  if (!output) return void 0;
40285
- const resolved = path23.resolve(output);
41364
+ const resolved = path25.resolve(output);
40286
41365
  const temporary = `${resolved}.tmp-${process.pid}-${randomUUID5()}`;
40287
- await writeFile17(temporary, `${JSON.stringify(receipt, null, 2)}
41366
+ await writeFile18(temporary, `${JSON.stringify(receipt, null, 2)}
40288
41367
  `, "utf8");
40289
41368
  await rename6(temporary, resolved);
40290
41369
  return resolved;
@@ -40292,7 +41371,7 @@ async function writeReceipt(output, receipt) {
40292
41371
  async function readOptionalReceipt(input) {
40293
41372
  let raw;
40294
41373
  try {
40295
- raw = await readFile24(input, "utf8");
41374
+ raw = await readFile25(input, "utf8");
40296
41375
  } catch (error) {
40297
41376
  if (error.code === "ENOENT") return void 0;
40298
41377
  throw error;
@@ -40312,18 +41391,18 @@ function fixtureAssetMime(content) {
40312
41391
  return void 0;
40313
41392
  }
40314
41393
  async function readReviewedFixtureAsset(asset, scenarioRoot) {
40315
- const root = await realpath9(path23.join(scenarioRoot, "fixtures"));
40316
- const candidate = path23.resolve(scenarioRoot, asset.path);
41394
+ const root = await realpath9(path25.join(scenarioRoot, "fixtures"));
41395
+ const candidate = path25.resolve(scenarioRoot, asset.path);
40317
41396
  const fileInfo = await lstat5(candidate);
40318
41397
  if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) {
40319
41398
  throw new Error(`test_fixture.asset_file_invalid: ${asset.key} \u5FC5\u987B\u662F\u975E\u7B26\u53F7\u94FE\u63A5\u666E\u901A\u6587\u4EF6\u3002`);
40320
41399
  }
40321
41400
  const file = await realpath9(candidate);
40322
- if (!file.startsWith(`${root}${path23.sep}`)) {
41401
+ if (!file.startsWith(`${root}${path25.sep}`)) {
40323
41402
  throw new Error(`test_fixture.asset_path_escape: ${asset.key} \u5FC5\u987B\u4FDD\u7559\u5728\u573A\u666F fixtures/ \u76EE\u5F55\u5185\u3002`);
40324
41403
  }
40325
- const content = await readFile24(file);
40326
- const actualSha256 = createHash14("sha256").update(content).digest("hex");
41404
+ const content = await readFile25(file);
41405
+ const actualSha256 = createHash15("sha256").update(content).digest("hex");
40327
41406
  const actualMime = fixtureAssetMime(content);
40328
41407
  if (content.length !== asset.size || actualSha256 !== asset.sha256 || actualMime !== asset.mime) {
40329
41408
  throw new Error(`test_fixture.asset_metadata_mismatch: ${asset.key} \u7684 size/sha256/mime \u4E0E\u5DF2\u5BA1\u6838\u6E05\u5355\u4E0D\u4E00\u81F4\u3002`);
@@ -40334,7 +41413,7 @@ async function readbackUploadedFixtureAsset(asset, url) {
40334
41413
  const response = await fetch(url);
40335
41414
  if (!response.ok) throw new Error(`test_fixture.asset_readback_failed: ${asset.key} upload URL \u8FD4\u56DE HTTP ${response.status}\u3002`);
40336
41415
  const content = Buffer.from(await response.arrayBuffer());
40337
- const actualSha256 = createHash14("sha256").update(content).digest("hex");
41416
+ const actualSha256 = createHash15("sha256").update(content).digest("hex");
40338
41417
  if (content.length !== asset.size || actualSha256 !== asset.sha256 || fixtureAssetMime(content) !== asset.mime) {
40339
41418
  throw new Error(`test_fixture.asset_readback_mismatch: ${asset.key} \u4E0A\u4F20\u540E\u5185\u5BB9\u4E0E\u5DF2\u5BA1\u6838\u6587\u4EF6\u4E0D\u4E00\u81F4\u3002`);
40340
41419
  }
@@ -40346,7 +41425,7 @@ async function uploadTypedFixtureAsset(options) {
40346
41425
  reviewed.content.byteOffset,
40347
41426
  reviewed.content.byteOffset + reviewed.content.byteLength
40348
41427
  );
40349
- form.set("file", new Blob([content], { type: options.asset.mime }), path23.basename(reviewed.file));
41428
+ form.set("file", new Blob([content], { type: options.asset.mime }), path25.basename(reviewed.file));
40350
41429
  await options.onMutationAttempt();
40351
41430
  const uploaded = await apiRequest(options.client, "POST", "/upload", {
40352
41431
  data: form,
@@ -40489,7 +41568,7 @@ function registerTestFixtureCommands(program2) {
40489
41568
  const manifest = await parseJsonInput2(options.json, "--json");
40490
41569
  const seeds = fixtureSeeds(manifest);
40491
41570
  const assets = fixtureAssets(manifest, seeds);
40492
- const scenarioRoot = options.json.startsWith("@") ? path23.dirname(path23.resolve(options.json.slice(1))) : process.cwd();
41571
+ const scenarioRoot = options.json.startsWith("@") ? path25.dirname(path25.resolve(options.json.slice(1))) : process.cwd();
40493
41572
  await Promise.all(assets.map((asset) => readReviewedFixtureAsset(asset, scenarioRoot)));
40494
41573
  const runId = safeToken(options.runId, "run_id");
40495
41574
  const profile = resolveProfile(await loadConfig(), options.profile);
@@ -40550,7 +41629,7 @@ function registerTestFixtureCommands(program2) {
40550
41629
  const fixtureManifest = await parseJsonInput2(options.json, "--json");
40551
41630
  const seeds = fixtureSeeds(fixtureManifest);
40552
41631
  const assets = fixtureAssets(fixtureManifest, seeds);
40553
- const manifestPath = path23.resolve(options.manifest);
41632
+ const manifestPath = path25.resolve(options.manifest);
40554
41633
  const result = await withExecutionOperationLock(manifestPath, async () => {
40555
41634
  const execution = await inspectPendingTestSuiteRunPrecondition(manifestPath, options.profile);
40556
41635
  if (!execution.v2_confirmation_receipt || !execution.v2_confirmation_digest) {
@@ -40563,13 +41642,13 @@ function registerTestFixtureCommands(program2) {
40563
41642
  throw new Error(`test_fixture.profile_mismatch: execution manifest profile is ${execution.profile}, not ${profile.name}`);
40564
41643
  }
40565
41644
  const client = createApiClient(profile);
40566
- const runDir = path23.dirname(manifestPath);
40567
- const evidenceDir = path23.join(runDir, "precondition-evidence");
41645
+ const runDir = path25.dirname(manifestPath);
41646
+ const evidenceDir = path25.join(runDir, "precondition-evidence");
40568
41647
  await preflightExecutionEvidenceDirectory({ manifest: manifestPath, evidenceDir: runDir });
40569
41648
  await preflightExecutionEvidenceDirectory({ manifest: manifestPath, evidenceDir });
40570
- const statePath = path23.join(runDir, "fixture-create-state.json");
40571
- const evidencePath = path23.join(evidenceDir, "typed-fixture-create.json");
40572
- const runtimeDataPath = path23.join(runDir, "fixture-runtime-data.json");
41649
+ const statePath = path25.join(runDir, "fixture-create-state.json");
41650
+ const evidencePath = path25.join(evidenceDir, "typed-fixture-create.json");
41651
+ const runtimeDataPath = path25.join(runDir, "fixture-runtime-data.json");
40573
41652
  const manifestHash = fixtureManifestSha256(fixtureManifest);
40574
41653
  if (!execution.fixture_manifest) {
40575
41654
  throw new Error(
@@ -40602,7 +41681,7 @@ function registerTestFixtureCommands(program2) {
40602
41681
  const runtime = {};
40603
41682
  const runtimeAssets = {};
40604
41683
  const scenarioRoot = String(execution.source_suite ?? "").trim();
40605
- if (assets.length > 0 && !path23.isAbsolute(scenarioRoot)) {
41684
+ if (assets.length > 0 && !path25.isAbsolute(scenarioRoot)) {
40606
41685
  throw new Error("test_fixture.asset_source_suite_missing: execution manifest \u7F3A\u5C11\u7EDD\u5BF9 source_suite\uFF0C\u65E0\u6CD5\u9A8C\u8BC1 reviewed assets\u3002");
40607
41686
  }
40608
41687
  for (const asset of assets) {
@@ -40870,7 +41949,7 @@ function registerTestFixtureCommands(program2) {
40870
41949
  const anchoredEvidence = execution.precondition?.state === "passed" ? String(execution.precondition.evidence ?? "").trim() : "";
40871
41950
  const evidenceForRecord = anchoredEvidence || evidencePath;
40872
41951
  if (anchoredEvidence) {
40873
- if (path23.resolve(anchoredEvidence) !== path23.resolve(evidencePath)) {
41952
+ if (path25.resolve(anchoredEvidence) !== path25.resolve(evidencePath)) {
40874
41953
  throw new Error("test_fixture.precondition_evidence_mismatch: passed fixture precondition is anchored to an unexpected evidence file");
40875
41954
  }
40876
41955
  } else {
@@ -40948,8 +42027,8 @@ function registerTestFixtureCommands(program2) {
40948
42027
  }
40949
42028
 
40950
42029
  // src/core/update.ts
40951
- import { access as access2, mkdir as mkdir17, readFile as readFile25, realpath as realpath10, writeFile as writeFile18 } from "fs/promises";
40952
- import path24 from "path";
42030
+ import { access as access2, mkdir as mkdir18, readFile as readFile26, realpath as realpath10, writeFile as writeFile19 } from "fs/promises";
42031
+ import path26 from "path";
40953
42032
  var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org/";
40954
42033
  var UPDATE_STATE_FILE = "update-state.json";
40955
42034
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -41065,11 +42144,11 @@ async function fetchLatestVersion(options = {}) {
41065
42144
  }
41066
42145
  }
41067
42146
  function updateStatePath(configDir = getConfigDir()) {
41068
- return path24.join(configDir, UPDATE_STATE_FILE);
42147
+ return path26.join(configDir, UPDATE_STATE_FILE);
41069
42148
  }
41070
42149
  async function readUpdateState(configDir) {
41071
42150
  try {
41072
- const raw = await readFile25(updateStatePath(configDir), "utf8");
42151
+ const raw = await readFile26(updateStatePath(configDir), "utf8");
41073
42152
  const parsed = JSON.parse(raw);
41074
42153
  if (typeof parsed.latest_version !== "string" || typeof parsed.checked_at !== "number") {
41075
42154
  return null;
@@ -41084,8 +42163,8 @@ async function readUpdateState(configDir) {
41084
42163
  }
41085
42164
  }
41086
42165
  async function writeUpdateState(state, configDir = getConfigDir()) {
41087
- await mkdir17(configDir, { recursive: true });
41088
- await writeFile18(updateStatePath(configDir), JSON.stringify(state), "utf8");
42166
+ await mkdir18(configDir, { recursive: true });
42167
+ await writeFile19(updateStatePath(configDir), JSON.stringify(state), "utf8");
41089
42168
  }
41090
42169
  async function checkCachedUpdate(currentVersion, configDir = getConfigDir()) {
41091
42170
  if (process.env.BPMAX_CLI_NO_UPDATE_NOTIFIER) {
@@ -41146,7 +42225,7 @@ async function findNpmPath() {
41146
42225
  }
41147
42226
  function detectInstallMethod(input) {
41148
42227
  const resolvedPath = input.executablePath || "";
41149
- const method = resolvedPath.includes(`node_modules${path24.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
42228
+ const method = resolvedPath.includes(`node_modules${path26.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
41150
42229
  return {
41151
42230
  method,
41152
42231
  resolvedPath,
@@ -41387,9 +42466,9 @@ function registerUrlCommands(program2, deps = {}) {
41387
42466
  }
41388
42467
 
41389
42468
  // src/commands/user.ts
41390
- import { readFile as readFile26 } from "fs/promises";
42469
+ import { readFile as readFile27 } from "fs/promises";
41391
42470
  async function parseJsonInput3(value) {
41392
- const raw = value.startsWith("@") ? await readFile26(value.slice(1), "utf8") : value;
42471
+ const raw = value.startsWith("@") ? await readFile27(value.slice(1), "utf8") : value;
41393
42472
  const parsed = JSON.parse(raw);
41394
42473
  if (!isRecord23(parsed)) throw new Error("user.pool.invalid_manifest: --json \u5FC5\u987B\u662F JSON \u5BF9\u8C61\u6216 @file\u3002");
41395
42474
  return parsed;
@@ -41872,6 +42951,7 @@ registerUserCommands(program);
41872
42951
  registerEsCommands(program);
41873
42952
  registerFlowCommands(program);
41874
42953
  registerIssueCommands(program);
42954
+ registerIconCommands(program);
41875
42955
  registerMemoryCommands(program);
41876
42956
  registerMatrixCommands(program);
41877
42957
  registerOrganizationCommands(program);