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

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
@@ -138,8 +138,8 @@ function maskApiKey(apiKey) {
138
138
  if (!apiKey) {
139
139
  return "(unset)";
140
140
  }
141
- if (apiKey.length <= 10) {
142
- return apiKey;
141
+ if (apiKey.length <= 16) {
142
+ return "[REDACTED]";
143
143
  }
144
144
  return `${apiKey.slice(0, 8)}****${apiKey.slice(-4)}`;
145
145
  }
@@ -231,8 +231,8 @@ function throwCliGovernanceUnsupportedIfNeeded(error, fallbackPath) {
231
231
  }
232
232
  throw error;
233
233
  }
234
- function normalizePath(path14) {
235
- let normalized = path14.split("?")[0] || "/";
234
+ function normalizePath(path15) {
235
+ let normalized = path15.split("?")[0] || "/";
236
236
  if (!normalized.startsWith("/")) {
237
237
  normalized = `/${normalized}`;
238
238
  }
@@ -242,17 +242,17 @@ function normalizePath(path14) {
242
242
  }
243
243
  return normalized.replace(/\/+$/g, "") || "/api";
244
244
  }
245
- function getNumber(value, path14) {
246
- const result = getValue(value, path14);
245
+ function getNumber(value, path15) {
246
+ const result = getValue(value, path15);
247
247
  return typeof result === "number" ? result : void 0;
248
248
  }
249
- function getString(value, path14) {
250
- const result = getValue(value, path14);
249
+ function getString(value, path15) {
250
+ const result = getValue(value, path15);
251
251
  return typeof result === "string" ? result : void 0;
252
252
  }
253
- function getValue(value, path14) {
253
+ function getValue(value, path15) {
254
254
  let current = value;
255
- for (const key of path14) {
255
+ for (const key of path15) {
256
256
  if (!current || typeof current !== "object" || !(key in current)) {
257
257
  return void 0;
258
258
  }
@@ -262,10 +262,10 @@ function getValue(value, path14) {
262
262
  }
263
263
 
264
264
  // src/core/capabilities.ts
265
- function capabilityForRequest(method, path14) {
265
+ function capabilityForRequest(method, path15) {
266
266
  const normalizedMethod = method.toUpperCase();
267
- const normalizedPath = normalizePath2(path14);
268
- const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path14);
267
+ const normalizedPath = normalizePath2(path15);
268
+ const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path15);
269
269
  if (normalizedPath === "/cli/capabilities") {
270
270
  return void 0;
271
271
  }
@@ -423,8 +423,8 @@ async function updateProfileCapabilities(profileName, cache) {
423
423
  };
424
424
  await saveConfig(config);
425
425
  }
426
- function flowPageTemplateCapabilityPrefix(path14) {
427
- const query = path14.includes("?") ? path14.slice(path14.indexOf("?") + 1) : "";
426
+ function flowPageTemplateCapabilityPrefix(path15) {
427
+ const query = path15.includes("?") ? path15.slice(path15.indexOf("?") + 1) : "";
428
428
  const type = new URLSearchParams(query).get("type");
429
429
  if (type === "2") {
430
430
  return "config.project_detail_template";
@@ -437,8 +437,8 @@ function flowPageTemplateCapabilityPrefix(path14) {
437
437
  }
438
438
  return "config.list_template";
439
439
  }
440
- function normalizePath2(path14) {
441
- let normalized = path14.split("?")[0] || "/";
440
+ function normalizePath2(path15) {
441
+ let normalized = path15.split("?")[0] || "/";
442
442
  if (!normalized.startsWith("/")) {
443
443
  normalized = `/${normalized}`;
444
444
  }
@@ -469,7 +469,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
469
469
  // package.json
470
470
  var package_default = {
471
471
  name: "bpmax-cli",
472
- version: "0.2.1-beta.1",
472
+ version: "0.2.1-beta.3",
473
473
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
474
474
  type: "module",
475
475
  bin: {
@@ -516,8 +516,8 @@ var NPM_PACKAGE = "bpmax-cli";
516
516
  // src/core/terminal.ts
517
517
  import { randomUUID } from "crypto";
518
518
  import os from "os";
519
- function isCliControlPath(path14) {
520
- const normalized = normalizeApiPath(path14);
519
+ function isCliControlPath(path15) {
520
+ const normalized = normalizeApiPath(path15);
521
521
  return normalized === "/api/cli/capabilities" || normalized === "/api/cli/terminals/register" || normalized === "/api/cli/audit/start" || normalized === "/api/cli/audit/finish" || normalized === "/api/cli/bbs_invocations/start" || normalized === "/api/cli/bbs_invocations/finish";
522
522
  }
523
523
  function commandSummary(argv = process.argv) {
@@ -681,8 +681,8 @@ async function updateProfileTerminal(profile, terminalId, status) {
681
681
  profile.config.terminal_status = status;
682
682
  profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
683
683
  }
684
- function normalizeApiPath(path14) {
685
- let normalized = path14.split("?")[0] || "/";
684
+ function normalizeApiPath(path15) {
685
+ let normalized = path15.split("?")[0] || "/";
686
686
  if (!normalized.startsWith("/")) {
687
687
  normalized = `/${normalized}`;
688
688
  }
@@ -800,14 +800,14 @@ function recordCommandAuditResult(value) {
800
800
  state.result_summary = redactAuditValue(value);
801
801
  }
802
802
  }
803
- var ensureApiPath = (path14) => {
804
- if (!path14.startsWith("/")) {
805
- path14 = `/${path14}`;
803
+ var ensureApiPath = (path15) => {
804
+ if (!path15.startsWith("/")) {
805
+ path15 = `/${path15}`;
806
806
  }
807
- if (path14.startsWith("/api/")) {
808
- return path14;
807
+ if (path15.startsWith("/api/")) {
808
+ return path15;
809
809
  }
810
- return `/api${path14}`;
810
+ return `/api${path15}`;
811
811
  };
812
812
  function normalizeWorkspaceForApi(workspace) {
813
813
  const normalized = workspace?.trim();
@@ -853,10 +853,10 @@ function createApiClient(profile) {
853
853
  });
854
854
  return instance;
855
855
  }
856
- async function apiRequest(client, method, path14, options = {}) {
856
+ async function apiRequest(client, method, path15, options = {}) {
857
857
  const profile = clientProfiles.get(client);
858
- const apiPath2 = ensureApiPath(path14);
859
- const capability = options.capability ?? capabilityForRequest(method, path14);
858
+ const apiPath2 = ensureApiPath(path15);
859
+ const capability = options.capability ?? capabilityForRequest(method, path15);
860
860
  const shouldControl = Boolean(profile?.config.api_key) && !isCliControlPath(apiPath2);
861
861
  const reqId = requestId();
862
862
  if (profile) {
@@ -1164,8 +1164,8 @@ async function parseJsonAny(input, label = "JSON input") {
1164
1164
  function isMutatingMethod(method) {
1165
1165
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
1166
1166
  }
1167
- function normalizeApiPath2(path14) {
1168
- let normalized = path14.trim();
1167
+ function normalizeApiPath2(path15) {
1168
+ let normalized = path15.trim();
1169
1169
  const queryIndex = normalized.indexOf("?");
1170
1170
  if (queryIndex >= 0) {
1171
1171
  normalized = normalized.slice(0, queryIndex);
@@ -1182,9 +1182,9 @@ function normalizeApiPath2(path14) {
1182
1182
  }
1183
1183
  return normalized;
1184
1184
  }
1185
- function pluginAgentCapabilityForRawApi(method, path14) {
1185
+ function pluginAgentCapabilityForRawApi(method, path15) {
1186
1186
  const normalizedMethod = method.toUpperCase();
1187
- const normalizedPath = normalizeApiPath2(path14);
1187
+ const normalizedPath = normalizeApiPath2(path15);
1188
1188
  const match = normalizedPath.match(/^\/(plugin_[A-Za-z0-9_]+)\/agents(?:\/|$)/);
1189
1189
  if (!match) {
1190
1190
  return void 0;
@@ -1198,19 +1198,19 @@ function pluginAgentCapabilityForRawApi(method, path14) {
1198
1198
  }
1199
1199
  return void 0;
1200
1200
  }
1201
- function parseQuery(path14) {
1202
- const queryIndex = path14.indexOf("?");
1203
- return new URLSearchParams(queryIndex >= 0 ? path14.slice(queryIndex + 1) : "");
1201
+ function parseQuery(path15) {
1202
+ const queryIndex = path15.indexOf("?");
1203
+ return new URLSearchParams(queryIndex >= 0 ? path15.slice(queryIndex + 1) : "");
1204
1204
  }
1205
- function isRawConfigPath(method, path14) {
1206
- const normalizedPath = normalizeApiPath2(path14);
1205
+ function isRawConfigPath(method, path15) {
1206
+ const normalizedPath = normalizeApiPath2(path15);
1207
1207
  if (/^\/(configuration|form_template|flow_page_template|data_set|data_set_field|api_platform|api_platform_instance|api_proxy|api_proxy_entity_binding|entity|entity_field|role|point|user_role|workspace|group|config_repository)(\/|$)/.test(normalizedPath)) {
1208
1208
  return true;
1209
1209
  }
1210
1210
  if (normalizedPath === "/flow/list/lightweight" || normalizedPath.startsWith("/flow/configuration/")) {
1211
1211
  return true;
1212
1212
  }
1213
- if (normalizedPath === "/flow" && method === "GET" && parseQuery(path14).has("draft")) {
1213
+ if (normalizedPath === "/flow" && method === "GET" && parseQuery(path15).has("draft")) {
1214
1214
  return true;
1215
1215
  }
1216
1216
  if (normalizedPath.startsWith("/flow/") && !["/flow/flow_type", "/flow/options", "/flow/batch_get"].includes(normalizedPath)) {
@@ -1221,35 +1221,35 @@ function isRawConfigPath(method, path14) {
1221
1221
  }
1222
1222
  return false;
1223
1223
  }
1224
- function assertRawApiPathAllowed(method, path14) {
1225
- if (isRawConfigPath(method, path14)) {
1224
+ function assertRawApiPathAllowed(method, path15) {
1225
+ if (isRawConfigPath(method, path15)) {
1226
1226
  throw new Error(
1227
- `Raw API ${method} ${path14} is blocked because BPMAX configuration APIs must use typed bpmax-cli config commands. Run bpmax-cli config adapters --format json to check whether the target config domain is supported.`
1227
+ `Raw API ${method} ${path15} is blocked because BPMAX configuration APIs must use typed bpmax-cli config commands. Run bpmax-cli config adapters --format json to check whether the target config domain is supported.`
1228
1228
  );
1229
1229
  }
1230
1230
  if (!isMutatingMethod(method)) {
1231
1231
  return;
1232
1232
  }
1233
- const normalizedPath = normalizeApiPath2(path14);
1233
+ const normalizedPath = normalizeApiPath2(path15);
1234
1234
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
1235
1235
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
1236
1236
  if (!isProjectPath || isAllowedProjectReadPost) {
1237
1237
  return;
1238
1238
  }
1239
1239
  throw new Error(
1240
- `Raw API ${method} ${path14} is blocked because /api/project/<id> falls back to project creation in huanpingtong-server. Do not call /project/es-search or /project/raw-es-search; huanpingtong-server does not expose those as public ES APIs. Use bpmax-cli project create --flow-id <id> --json <json> for project creation, or bpmax-cli project search / project list for project reads.`
1240
+ `Raw API ${method} ${path15} is blocked because /api/project/<id> falls back to project creation in huanpingtong-server. Do not call /project/es-search or /project/raw-es-search; huanpingtong-server does not expose those as public ES APIs. Use bpmax-cli project create --flow-id <id> --json <json> for project creation, or bpmax-cli project search / project list for project reads.`
1241
1241
  );
1242
1242
  }
1243
1243
  function registerApiCommands(program2) {
1244
- program2.command("api <method> <path>").description("Call an arbitrary BPMAX /api endpoint").option("--profile <profile>", "Profile name").option("--params <json>", "Query params JSON or @file").option("--data <json>", "Request body JSON or @file").option("--confirm-mutating", "Allow mutating API calls").option("--format <format>", "Output format", "json").action(async (method, path14, options) => {
1244
+ program2.command("api <method> <path>").description("Call an arbitrary BPMAX /api endpoint").option("--profile <profile>", "Profile name").option("--params <json>", "Query params JSON or @file").option("--data <json>", "Request body JSON or @file").option("--confirm-mutating", "Allow mutating API calls").option("--format <format>", "Output format", "json").action(async (method, path15, options) => {
1245
1245
  const normalizedMethod = method.toUpperCase();
1246
- assertRawApiPathAllowed(normalizedMethod, path14);
1246
+ assertRawApiPathAllowed(normalizedMethod, path15);
1247
1247
  if (isMutatingMethod(normalizedMethod) && options.confirmMutating !== true) {
1248
1248
  printResult(options.format, {
1249
1249
  ok: false,
1250
1250
  dry_run: true,
1251
1251
  method: normalizedMethod,
1252
- path: path14,
1252
+ path: path15,
1253
1253
  warning: "Mutating raw API calls require --confirm-mutating. Prefer typed bpmax-cli commands such as step submit."
1254
1254
  });
1255
1255
  return;
@@ -1257,8 +1257,8 @@ function registerApiCommands(program2) {
1257
1257
  const config = await loadConfig();
1258
1258
  const profile = resolveProfile(config, options.profile);
1259
1259
  const client = createApiClient(profile);
1260
- const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path14) || "api.raw";
1261
- const result = await apiRequest(client, normalizedMethod, path14, {
1260
+ const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path15) || "api.raw";
1261
+ const result = await apiRequest(client, normalizedMethod, path15, {
1262
1262
  params: options.params ? await parseJsonInput(options.params, "--params") : void 0,
1263
1263
  data: await parseJsonAny(options.data, "--data"),
1264
1264
  capability
@@ -1281,6 +1281,18 @@ function shellQuote(value) {
1281
1281
  }
1282
1282
  return `'${value.replace(/'/g, `'\\''`)}'`;
1283
1283
  }
1284
+ function toUserSummary(user) {
1285
+ if (!user || typeof user !== "object" || Array.isArray(user)) {
1286
+ return void 0;
1287
+ }
1288
+ const record = user;
1289
+ const id = typeof record.id === "number" ? record.id : typeof record.user_id === "number" ? record.user_id : void 0;
1290
+ const name = typeof record.name === "string" ? record.name : typeof record.nickname === "string" ? record.nickname : typeof record.realname === "string" ? record.realname : "";
1291
+ if (id === void 0) {
1292
+ return void 0;
1293
+ }
1294
+ return { id, name };
1295
+ }
1284
1296
  var DeviceAuthorizationError = class extends Error {
1285
1297
  code;
1286
1298
  interval;
@@ -1333,18 +1345,18 @@ function lintDeviceAuthorizationUrl(urlValue, expectedOrigin, expectedWorkspace,
1333
1345
  );
1334
1346
  }
1335
1347
  }
1336
- function apiPath(path14) {
1337
- if (path14.startsWith("/api/")) {
1338
- return path14;
1348
+ function apiPath(path15) {
1349
+ if (path15.startsWith("/api/")) {
1350
+ return path15;
1339
1351
  }
1340
- return `/api${path14.startsWith("/") ? path14 : `/${path14}`}`;
1352
+ return `/api${path15.startsWith("/") ? path15 : `/${path15}`}`;
1341
1353
  }
1342
1354
  function createDeviceRequest(origin) {
1343
1355
  const client = axios2.create({ baseURL: origin, withCredentials: false });
1344
- return async (method, path14, options) => {
1356
+ return async (method, path15, options) => {
1345
1357
  const response = await client.request({
1346
1358
  method,
1347
- url: apiPath(path14),
1359
+ url: apiPath(path15),
1348
1360
  data: options.data
1349
1361
  });
1350
1362
  const body = response.data;
@@ -1427,7 +1439,7 @@ async function completeDeviceLogin(options) {
1427
1439
  }
1428
1440
  return {
1429
1441
  apiKey,
1430
- user: response.user,
1442
+ user: toUserSummary(response.user),
1431
1443
  apiKeyCapabilities: response.capabilities && typeof response.capabilities === "object" && !Array.isArray(response.capabilities) ? response.capabilities : void 0
1432
1444
  };
1433
1445
  }
@@ -1491,7 +1503,7 @@ function updateProfileAuth(profile, result) {
1491
1503
  ...rest,
1492
1504
  ...terminalFields,
1493
1505
  api_key: result.apiKey,
1494
- user: result.user,
1506
+ user: toUserSummary(result.user),
1495
1507
  api_key_capabilities: result.apiKeyCapabilities || {}
1496
1508
  };
1497
1509
  }
@@ -1544,6 +1556,15 @@ async function fetchCurrentUserForStatus(profile) {
1544
1556
  }
1545
1557
  return body.data ?? body;
1546
1558
  }
1559
+ function minimalStatusUser(user) {
1560
+ const safe = {};
1561
+ for (const key of ["id", "user_id", "uid", "name", "nickname", "realname"]) {
1562
+ if (user[key] !== void 0 && user[key] !== null && user[key] !== "") {
1563
+ safe[key] = user[key];
1564
+ }
1565
+ }
1566
+ return safe;
1567
+ }
1547
1568
  function registerAuthCommands(program2, deps = {}) {
1548
1569
  const load = deps.loadConfig || loadConfig;
1549
1570
  const save = deps.saveConfig || saveConfig;
@@ -1579,6 +1600,7 @@ function registerAuthCommands(program2, deps = {}) {
1579
1600
  expiresIn: authorization.expires_in
1580
1601
  });
1581
1602
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
1603
+ result = { ...result, user: config.profiles[profile.name].user };
1582
1604
  await save(config);
1583
1605
  let capabilitiesProbe;
1584
1606
  let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
@@ -1643,6 +1665,7 @@ function registerAuthCommands(program2, deps = {}) {
1643
1665
  deviceCode
1644
1666
  });
1645
1667
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
1668
+ const safeUser = config.profiles[profile.name].user;
1646
1669
  await save(config);
1647
1670
  let capabilitiesProbe;
1648
1671
  let capabilitiesCache = config.profiles[profile.name].capabilities_cache;
@@ -1664,12 +1687,12 @@ function registerAuthCommands(program2, deps = {}) {
1664
1687
  ok: true,
1665
1688
  profile: profile.name,
1666
1689
  login: "authenticated",
1667
- user: result.user,
1690
+ user: safeUser,
1668
1691
  ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
1669
1692
  ...nextCommands ? { next_commands: nextCommands } : {}
1670
1693
  });
1671
1694
  });
1672
- auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
1695
+ auth.command("status").description("Show saved auth state and validate /api/user/current").option("--profile <profile>", "Profile name").option("--verbose", "Include the full /api/user/current response. Default output is minimized and redacted for logs.").option("--format <format>", "Output format", "pretty").action(async (options) => {
1673
1696
  const config = await load();
1674
1697
  const profile = resolveProfile(config, options.profile);
1675
1698
  const output = {
@@ -1682,7 +1705,8 @@ function registerAuthCommands(program2, deps = {}) {
1682
1705
  if (profile.config.api_key) {
1683
1706
  try {
1684
1707
  const currentUser = await fetchCurrentUserForStatus(profile);
1685
- output.user = currentUser;
1708
+ output.user = options.verbose ? currentUser : minimalStatusUser(currentUser);
1709
+ output.user_detail = options.verbose ? "full" : "minimal";
1686
1710
  output.authenticated = true;
1687
1711
  } catch (error) {
1688
1712
  const message = error instanceof Error ? error.message : String(error);
@@ -1753,20 +1777,20 @@ function requireNumericId(value, name) {
1753
1777
  }
1754
1778
  return nextValue;
1755
1779
  }
1756
- function withQuery(path14, query) {
1780
+ function withQuery(path15, query) {
1757
1781
  const params = new URLSearchParams();
1758
1782
  for (const [key, value] of Object.entries(query)) {
1759
1783
  if (value !== void 0) {
1760
1784
  params.set(key, value);
1761
1785
  }
1762
1786
  }
1763
- return `${path14}?${params.toString()}`;
1787
+ return `${path15}?${params.toString()}`;
1764
1788
  }
1765
1789
  function buildBpmaxUrl(profile, kind, params = {}) {
1766
1790
  const origin = normalizeOrigin2(profile.config.origin);
1767
1791
  const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
1768
1792
  const basePath = `/${workspace}`;
1769
- let path14 = basePath;
1793
+ let path15 = basePath;
1770
1794
  const result = {
1771
1795
  kind,
1772
1796
  profile: profile.name,
@@ -1774,15 +1798,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
1774
1798
  workspace
1775
1799
  };
1776
1800
  if (kind === "project-list") {
1777
- path14 = `${basePath}/project`;
1801
+ path15 = `${basePath}/project`;
1778
1802
  } else if (kind === "project-detail") {
1779
1803
  const projectId = requireNumericId(params.projectId, "projectId");
1780
- path14 = `${basePath}/project_detail/0/${projectId}`;
1804
+ path15 = `${basePath}/project_detail/0/${projectId}`;
1781
1805
  result.project_id = projectId;
1782
1806
  } else if (kind === "project-step") {
1783
1807
  const projectId = requireNumericId(params.projectId, "projectId");
1784
1808
  const stepId = requireNumericId(params.stepId, "stepId");
1785
- path14 = withQuery(`${basePath}/projectContinue`, {
1809
+ path15 = withQuery(`${basePath}/projectContinue`, {
1786
1810
  id: projectId,
1787
1811
  step_id: stepId
1788
1812
  });
@@ -1799,15 +1823,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
1799
1823
  ...flowKey ? { key: flowKey } : {},
1800
1824
  ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
1801
1825
  };
1802
- path14 = withQuery(`${basePath}/project/create`, query);
1826
+ path15 = withQuery(`${basePath}/project/create`, query);
1803
1827
  result.flow_type = flowType;
1804
1828
  result.flow_key = flowKey;
1805
1829
  result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
1806
1830
  }
1807
- const url = `${origin}${path14}`;
1831
+ const url = `${origin}${path15}`;
1808
1832
  return {
1809
1833
  ...result,
1810
- path: path14,
1834
+ path: path15,
1811
1835
  url,
1812
1836
  ...kind === "project-create" ? { pc_url: url } : {}
1813
1837
  };
@@ -2717,6 +2741,8 @@ function registerCapabilitiesCommands(program2) {
2717
2741
 
2718
2742
  // src/commands/config.ts
2719
2743
  import { text as text2 } from "@clack/prompts";
2744
+ import { mkdir as mkdir8, writeFile as writeFile8 } from "fs/promises";
2745
+ import path9 from "path";
2720
2746
 
2721
2747
  // src/core/config-workflow.ts
2722
2748
  import { createHash as createHash4 } from "crypto";
@@ -3927,6 +3953,8 @@ function configAdapterMatrix() {
3927
3953
  return Object.entries(CONFIG_DOMAINS).map(([domain, definition]) => {
3928
3954
  const supportsCreate = Boolean(definition.createPath) || ["flow-template", "api-platform", "role", "nav-config"].includes(domain);
3929
3955
  const supportsDelete = Boolean(definition.deletePath) || ["workspace-flow", "api-platform", "nav-config"].includes(domain);
3956
+ const supportsPublish = domain === "dataset";
3957
+ const supportsRelationFields = domain === "dataset";
3930
3958
  return {
3931
3959
  domain,
3932
3960
  capability_prefix: definition.capability,
@@ -3939,6 +3967,29 @@ function configAdapterMatrix() {
3939
3967
  delete_capability: supportsDelete ? `${definition.capability}.delete` : null,
3940
3968
  read_endpoints: definition.readEndpoints,
3941
3969
  write_endpoints: definition.writeEndpoints,
3970
+ actions: {
3971
+ export: definition.exportStatus === "supported",
3972
+ create: supportsCreate,
3973
+ build: definition.buildStatus === "supported",
3974
+ submit: definition.submitStatus === "supported" || definition.submitStatus === "requires-platform-proxy",
3975
+ publish: supportsPublish,
3976
+ relationFields: supportsRelationFields,
3977
+ delete: supportsDelete,
3978
+ verify: definition.exportStatus === "supported",
3979
+ dry_run: definition.submitStatus === "supported" || definition.submitStatus === "requires-platform-proxy"
3980
+ },
3981
+ requires: {
3982
+ work_file: definition.buildStatus === "supported",
3983
+ meta_file_for_build: definition.buildStatus === "supported",
3984
+ payload_file_for_submit: definition.submitStatus === "supported" || definition.submitStatus === "requires-platform-proxy",
3985
+ base_hash_for_submit: domain === "workspace-flow" || domain === "dataset"
3986
+ },
3987
+ side_effects: {
3988
+ writes_workspace_binding: domain === "workspace-flow",
3989
+ full_replacement_submit: domain === "workspace-flow",
3990
+ publishes_on_submit: domain === "form-template",
3991
+ relation_fields_submit: domain === "dataset"
3992
+ },
3942
3993
  notes: definition.notes
3943
3994
  };
3944
3995
  });
@@ -3946,6 +3997,34 @@ function configAdapterMatrix() {
3946
3997
  function hashJson(value) {
3947
3998
  return createHash4("sha256").update(JSON.stringify(value)).digest("hex");
3948
3999
  }
4000
+ function flowAppContextEvidence(input) {
4001
+ const flowData = isRecord3(input.flow.data) ? input.flow.data : {};
4002
+ const flowType = firstNonEmpty(input.flow.flow_type, flowData.flow_type, input.flowId);
4003
+ const flowKey = firstNonEmpty(input.flow.key);
4004
+ const flowTemplateId = input.flow.id ?? input.flow.flow_id ?? null;
4005
+ const missing = [
4006
+ ["flow_type", flowType],
4007
+ ["form_template_id", input.formTemplateId],
4008
+ ["form_template_draft_id", input.formTemplateDraftId],
4009
+ ["workspace_binding", input.bindingFound ? "ok" : ""]
4010
+ ].filter(([, value]) => value === null || value === void 0 || String(value).trim() === "").map(([key]) => key);
4011
+ return {
4012
+ flow_type: flowType || null,
4013
+ flow_key: flowKey,
4014
+ flow_template_id: flowTemplateId,
4015
+ form_template_id: input.formTemplateId ?? null,
4016
+ form_template_draft_id: input.formTemplateDraftId ?? null,
4017
+ workspace_key: input.workspace,
4018
+ workspace_binding_found: input.bindingFound,
4019
+ workspace_readback_hash: hashJson(input.workspaceReadback),
4020
+ flow_readback_hash: hashJson(input.flow),
4021
+ form_template_readback_hash: input.formReadback ? hashJson(input.formReadback) : null,
4022
+ evidence_status: missing.length === 0 ? "verified" : "incomplete",
4023
+ missing_context: missing,
4024
+ resolved_by: input.resolvedBy,
4025
+ verified_at: (/* @__PURE__ */ new Date()).toISOString()
4026
+ };
4027
+ }
3949
4028
  function isRecord3(value) {
3950
4029
  return value !== null && typeof value === "object" && !Array.isArray(value);
3951
4030
  }
@@ -4063,9 +4142,9 @@ function summarizeOperationPlan(payload) {
4063
4142
  return "submit operation";
4064
4143
  }
4065
4144
  const method = typeof operation.method === "string" ? operation.method : "REQUEST";
4066
- const path14 = typeof operation.path === "string" ? operation.path : "";
4145
+ const path15 = typeof operation.path === "string" ? operation.path : "";
4067
4146
  const type = typeof operation.type === "string" ? ` ${operation.type}` : "";
4068
- return `submit${type}: ${method}${path14 ? ` ${path14}` : ""}`;
4147
+ return `submit${type}: ${method}${path15 ? ` ${path15}` : ""}`;
4069
4148
  }),
4070
4149
  ...skipped.slice(0, Math.max(0, 20 - operations.length)).map((operation) => {
4071
4150
  if (!isRecord3(operation)) {
@@ -5022,13 +5101,108 @@ function normalizeDatasetPayload(work) {
5022
5101
  }
5023
5102
  return payload;
5024
5103
  }
5104
+ function firstNonEmpty(...values) {
5105
+ for (const value of values) {
5106
+ if (value === null || value === void 0) {
5107
+ continue;
5108
+ }
5109
+ const text5 = String(value).trim();
5110
+ if (text5 !== "") {
5111
+ return text5;
5112
+ }
5113
+ }
5114
+ return "";
5115
+ }
5116
+ function exactConfirmOrDryRun(confirm3, expectedConfirm, options = {}) {
5117
+ if (confirm3 === void 0 || confirm3 === "") {
5118
+ return false;
5119
+ }
5120
+ const accepted = [expectedConfirm, ...options.equivalentConfirms || []];
5121
+ if (accepted.includes(confirm3)) {
5122
+ return true;
5123
+ }
5124
+ throw new Error(`confirmation text mismatch. expected: ${expectedConfirm}. actual: ${confirm3}.`);
5125
+ }
5126
+ function configReadbackHint(domain, id) {
5127
+ if (id === void 0 || id === null || id === "") {
5128
+ return null;
5129
+ }
5130
+ const value = String(id);
5131
+ return {
5132
+ command: `bpmax-cli config ${domain} export --id ${value} --inline --format json`,
5133
+ unified_command: `bpmax-cli config readback ${domain} --id ${value} --format json`
5134
+ };
5135
+ }
5136
+ function configResponseKey(domain, payload, response, readback) {
5137
+ if (isRecord3(response)) {
5138
+ const key = response.key ?? response.field ?? response.custom_key;
5139
+ if (key !== void 0) return key;
5140
+ if (isRecord3(response.data)) {
5141
+ const nested = response.data.key ?? response.data.field ?? response.data.custom_key;
5142
+ if (nested !== void 0) return nested;
5143
+ }
5144
+ }
5145
+ if (isRecord3(readback)) {
5146
+ const key = readback.key ?? readback.field ?? readback.custom_key;
5147
+ if (key !== void 0) return key;
5148
+ }
5149
+ if (isRecord3(payload)) {
5150
+ if (domain === "dataset") return payload.custom_key ?? payload.customKey ?? null;
5151
+ return payload.key ?? payload.field ?? null;
5152
+ }
5153
+ return null;
5154
+ }
5155
+ function standardConfigWriteResponse(input) {
5156
+ const resolvedId = input.executedId ?? input.id;
5157
+ return {
5158
+ id: resolvedId,
5159
+ request_id: input.id,
5160
+ key: configResponseKey(input.domain, input.payload, input.response, input.readback),
5161
+ readback_hint: configReadbackHint(input.domain, resolvedId)
5162
+ };
5163
+ }
5164
+ function dryRunFields(expectedConfirm) {
5165
+ return {
5166
+ ok: true,
5167
+ dry_run: true,
5168
+ operation_executed: false,
5169
+ confirm_required: true,
5170
+ required_confirm: expectedConfirm,
5171
+ expected_confirm: expectedConfirm
5172
+ };
5173
+ }
5174
+ function executedFields() {
5175
+ return {
5176
+ ok: true,
5177
+ dry_run: false,
5178
+ operation_executed: true,
5179
+ confirm_required: false
5180
+ };
5181
+ }
5182
+ function validateDatasetFieldCreatePayload(payload) {
5183
+ if (!isRecord3(payload)) {
5184
+ throw new Error("dataset-field create requires an object payload.");
5185
+ }
5186
+ const missingSource = [
5187
+ ["payload.flow_type", payload.flow_type],
5188
+ ["payload.data_set_id", payload.data_set_id],
5189
+ ["payload.source_table", payload.source_table],
5190
+ ["payload.source_field", payload.source_field],
5191
+ ["payload.source_fk", payload.source_fk]
5192
+ ].filter(([, value]) => typeof value !== "string" || value.trim() === "");
5193
+ if (missingSource.length > 0) {
5194
+ throw new Error(`dataset-field create requires dataset and source mapping fields: ${missingSource.map(([key]) => key).join(", ")}.`);
5195
+ }
5196
+ }
5025
5197
  function normalizeDatasetFieldPayload(work) {
5026
5198
  const mode = work.mode;
5027
5199
  if (mode !== void 0 && mode !== "edit" && mode !== "create") {
5028
5200
  throw new Error("dataset-field typed adapter supports mode edit or create. Delete requires a dedicated adapter.");
5029
5201
  }
5030
5202
  const source = isRecord3(work.source) ? work.source : work;
5203
+ const sourcePayload = isRecord3(work.x_wewf_source_payload) ? work.x_wewf_source_payload : {};
5031
5204
  const payload = {
5205
+ data_set_id: firstNonEmpty(work.data_set_id, work.dataSetId, work.dataset_id, sourcePayload.data_set_id, sourcePayload.dataSetId, sourcePayload.dataset_id),
5032
5206
  name: work.name || "",
5033
5207
  key: work.key || work.field || "",
5034
5208
  type: work.type || "",
@@ -5056,14 +5230,7 @@ function normalizeDatasetFieldPayload(work) {
5056
5230
  payload.sourceField = payload.source_field;
5057
5231
  payload.sourceFk = payload.source_fk;
5058
5232
  if (mode === "create") {
5059
- const missingSource = [
5060
- ["source_table", payload.source_table],
5061
- ["source_field", payload.source_field],
5062
- ["source_fk", payload.source_fk]
5063
- ].filter(([, value]) => typeof value !== "string" || value.trim() === "");
5064
- if (missingSource.length > 0) {
5065
- throw new Error(`dataset-field create requires source mapping fields: ${missingSource.map(([key]) => key).join(", ")}.`);
5066
- }
5233
+ validateDatasetFieldCreatePayload(payload);
5067
5234
  }
5068
5235
  const advanced = isRecord3(work.advanced) ? work.advanced : {};
5069
5236
  if (Object.prototype.hasOwnProperty.call(advanced, "sourceComputed")) {
@@ -6745,6 +6912,7 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6745
6912
  }
6746
6913
  };
6747
6914
  const expectedConfirm = `create flow-app ${name} in ${workspace}`;
6915
+ const acceptedConfirmWithWorkspacePrefix = `create flow-app ${name} in w:${workspace}`;
6748
6916
  const dryRunPlan = {
6749
6917
  operations: [
6750
6918
  { step: "create_form_template", method: "POST", path: "/form_template", payload: formPayload },
@@ -6756,9 +6924,10 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6756
6924
  { step: "verify_workspace_binding", method: "GET", path: "/workspace/by_key", params: { key: workspace } }
6757
6925
  ]
6758
6926
  };
6759
- if (confirm3 !== expectedConfirm) {
6927
+ if (!exactConfirmOrDryRun(confirm3, expectedConfirm, { equivalentConfirms: [acceptedConfirmWithWorkspacePrefix] })) {
6760
6928
  return {
6761
- dry_run: true,
6929
+ ...dryRunFields(expectedConfirm),
6930
+ accepted_confirms: [expectedConfirm, acceptedConfirmWithWorkspacePrefix],
6762
6931
  domain: "flow-app",
6763
6932
  workspace,
6764
6933
  name,
@@ -6849,9 +7018,22 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6849
7018
  "/workspace/by_key",
6850
7019
  { params: { key: workspace }, capability: `${workspaceDefinition.capability}.export` }
6851
7020
  );
7021
+ const workspaceBaseHash = hashJson(workspaceInfo);
6852
7022
  const existingBindings = isRecord3(workspaceInfo) ? normalizeWorkspaceFlowItems(workspaceInfo.workspace_flow) : [];
6853
7023
  const bindingKey = buildWorkspaceFlowBindingKey(flowType, "");
6854
7024
  const nextBindings = existingBindings.some((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key) === bindingKey) ? existingBindings : [...existingBindings, { flow_type: flowType, flow_key: "", only_in_workspace: 0 }];
7025
+ const workspaceGuardReadback = await apiRequest(
7026
+ client,
7027
+ "GET",
7028
+ "/workspace/by_key",
7029
+ { params: { key: workspace }, capability: `${workspaceDefinition.capability}.export` }
7030
+ );
7031
+ const workspaceGuardHash = hashJson(workspaceGuardReadback);
7032
+ if (workspaceGuardHash !== workspaceBaseHash) {
7033
+ throw new Error(
7034
+ `flow-app create workspace-flow baseline changed for ${workspace}. Re-run flow-app context or workspace-flow export, merge the latest bindings, and retry to avoid dropping concurrent workspace bindings.`
7035
+ );
7036
+ }
6855
7037
  const workspaceBindResponse = await apiRequest(
6856
7038
  client,
6857
7039
  "PUT",
@@ -6869,21 +7051,48 @@ async function createFlowAppFromWork(config, profile, formWorkFile, flowWorkFile
6869
7051
  if (!readbackBindings.some((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key) === bindingKey)) {
6870
7052
  throw new Error(`flow-app create workspace binding verification failed for ${workspace} ${bindingKey}.`);
6871
7053
  }
7054
+ const flowTemplateId = isRecord3(flowCreateResponse) ? isRecord3(flowCreateResponse.data) ? flowCreateResponse.data.id : flowCreateResponse.id : null;
7055
+ const evidence = {
7056
+ flow_type: flowType,
7057
+ flow_key: "",
7058
+ flow_template_id: flowTemplateId ?? flowType,
7059
+ form_template_id: publishedFormId,
7060
+ form_template_draft_id: draftFormId,
7061
+ workspace_key: workspace,
7062
+ workspace_binding_found: true,
7063
+ workspace_readback_hash: hashJson(workspaceReadback),
7064
+ evidence_status: "verified",
7065
+ verified_at: (/* @__PURE__ */ new Date()).toISOString()
7066
+ };
6872
7067
  return {
6873
- dry_run: false,
7068
+ ...executedFields(),
6874
7069
  domain: "flow-app",
6875
7070
  workspace,
6876
7071
  name,
7072
+ created_ids: {
7073
+ draft_form_id: draftFormId,
7074
+ published_form_id: publishedFormId,
7075
+ form_template_id: publishedFormId,
7076
+ form_template_draft_id: draftFormId,
7077
+ flow_type: flowType,
7078
+ flow_template_id: flowTemplateId ?? flowType,
7079
+ workspace
7080
+ },
6877
7081
  draft_form_id: draftFormId,
6878
7082
  published_form_id: publishedFormId,
7083
+ form_template_id: publishedFormId,
7084
+ form_template_draft_id: draftFormId,
6879
7085
  flow_type: flowType,
7086
+ flow_key: "",
7087
+ flow_template_id: flowTemplateId ?? flowType,
6880
7088
  form_response: formResponse,
6881
7089
  form_publish_response: formPublishResponse,
6882
7090
  flow_create_response: flowCreateResponse,
6883
7091
  flow_draft_response: flowDraftResponse,
6884
7092
  ...liveEndpoint ? { flow_live_response: flowLiveResponse, live_endpoint: liveEndpoint } : {},
6885
7093
  workspace_bind_response: workspaceBindResponse,
6886
- workspace_readback_hash: hashJson(workspaceReadback)
7094
+ workspace_readback_hash: hashJson(workspaceReadback),
7095
+ evidence
6887
7096
  };
6888
7097
  } catch (error) {
6889
7098
  const message = error instanceof Error ? error.message : String(error || "");
@@ -6900,6 +7109,115 @@ async function readBackConfigDomain(profile, domain, id, definition) {
6900
7109
  readback_hash: hashJson(data)
6901
7110
  };
6902
7111
  }
7112
+ async function readbackConfigDomain(config, profile, domain, id) {
7113
+ void config;
7114
+ const definition = CONFIG_DOMAINS[domain];
7115
+ if (!definition) {
7116
+ throw new Error(`Unknown config domain: ${domain}`);
7117
+ }
7118
+ const data = await readRemoteConfigDomain(profile, domain, id, definition);
7119
+ validateExpectedType(domain, definition, data);
7120
+ return {
7121
+ domain,
7122
+ id,
7123
+ readback_hash: hashJson(data),
7124
+ source_api: definition.exportPath ? `GET /api${definition.exportPath(id)}` : null,
7125
+ verified_at: (/* @__PURE__ */ new Date()).toISOString(),
7126
+ readback: data
7127
+ };
7128
+ }
7129
+ async function resolveFlowAppContextFlowId(profile, flow) {
7130
+ const trimmed = flow.trim();
7131
+ if (!trimmed) {
7132
+ throw new Error("flow-app context requires --flow <flow_type|flow_type:key|key:<key>|name>.");
7133
+ }
7134
+ if (/^flow\d+$/.test(trimmed) || trimmed.startsWith("flow_type:") || trimmed.startsWith("key:") || trimmed.includes("|") || trimmed.includes(":")) {
7135
+ return { id: trimmed, resolvedBy: "flow_id" };
7136
+ }
7137
+ const client = createApiClient(profile);
7138
+ const options = await apiRequest(client, "GET", "/flow/options", { capability: "flow.options" });
7139
+ const rows = extractListData(options);
7140
+ const matches = rows.filter((item) => String(item.name || item.title || "").trim() === trimmed);
7141
+ if (matches.length !== 1) {
7142
+ throw new Error(
7143
+ `flow-app context could not resolve flow name "${trimmed}" (${matches.length} matches). Use --flow flow_type:<flow_type>, --flow key:<flow_key>, or run bpmax-cli flow options --name "<name>" --format json first.`
7144
+ );
7145
+ }
7146
+ const match = matches[0];
7147
+ const flowType = firstNonEmpty(match.flow_type, match.flowType);
7148
+ const flowKey = firstNonEmpty(match.key, match.flow_key, match.flowKey);
7149
+ if (flowKey && flowType) {
7150
+ return { id: `${flowType}:${flowKey}`, resolvedBy: "flow_options_name" };
7151
+ }
7152
+ if (flowKey) {
7153
+ return { id: `key:${flowKey}`, resolvedBy: "flow_options_name" };
7154
+ }
7155
+ if (flowType) {
7156
+ return { id: flowType, resolvedBy: "flow_options_name" };
7157
+ }
7158
+ throw new Error(`flow-app context resolved flow name "${trimmed}" but the option row did not include flow_type or key.`);
7159
+ }
7160
+ async function inspectFlowAppContext(config, profile, options) {
7161
+ void config;
7162
+ const flowDefinition = CONFIG_DOMAINS["flow-template"];
7163
+ const formDefinition = CONFIG_DOMAINS["form-template"];
7164
+ const workspaceDefinition = CONFIG_DOMAINS["workspace-flow"];
7165
+ await ensureConfigCapability(profile, `${flowDefinition.capability}.export`);
7166
+ await ensureConfigCapability(profile, `${formDefinition.capability}.export`);
7167
+ await ensureConfigCapability(profile, `${workspaceDefinition.capability}.export`);
7168
+ const workspace = normalizeWorkspaceKey(options.workspace || profile.config.workspace);
7169
+ if (!workspace) {
7170
+ throw new Error("flow-app context requires --workspace <workspace>.");
7171
+ }
7172
+ const resolvedFlow = await resolveFlowAppContextFlowId(profile, options.flow);
7173
+ const flowReadback = await readRemoteConfigDomain(profile, "flow-template", resolvedFlow.id, flowDefinition);
7174
+ const flow = isRecord3(flowReadback) ? flowReadback : {};
7175
+ const data = isRecord3(flow.data) ? flow.data : {};
7176
+ const meta = isRecord3(data.meta) ? data.meta : {};
7177
+ const formTemplateId = firstNonEmpty(meta.form_template, meta.formTemplate, flow.meta_form_id, flow.metaFormId);
7178
+ let formReadback = null;
7179
+ let formTemplateDraftId = null;
7180
+ if (formTemplateId) {
7181
+ formReadback = await readRemoteConfigDomain(profile, "form-template", String(formTemplateId), formDefinition);
7182
+ if (isRecord3(formReadback)) {
7183
+ const originTemplateId = formReadback.origin_template_id ?? formReadback.originTemplateId;
7184
+ formTemplateDraftId = originTemplateId && String(originTemplateId) !== "0" ? originTemplateId : formReadback.id ?? formTemplateId;
7185
+ }
7186
+ }
7187
+ const workspaceReadback = await readRemoteConfigDomain(profile, "workspace-flow", workspace, workspaceDefinition);
7188
+ const bindings = isRecord3(workspaceReadback) ? normalizeWorkspaceFlowItems(workspaceReadback.workspace_flow) : [];
7189
+ const parsedIdentity = parseFlowIdentity(resolvedFlow.id);
7190
+ const flowType = firstNonEmpty(flow.flow_type, parsedIdentity.flowType);
7191
+ const flowKey = firstNonEmpty(flow.key, parsedIdentity.flowKey);
7192
+ const bindingFound = bindings.some((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key) === buildWorkspaceFlowBindingKey(flowType, flowKey));
7193
+ const evidence = flowAppContextEvidence({
7194
+ workspace,
7195
+ flow,
7196
+ flowId: resolvedFlow.id,
7197
+ formTemplateId: formTemplateId || null,
7198
+ formTemplateDraftId,
7199
+ formReadback,
7200
+ workspaceReadback,
7201
+ bindingFound,
7202
+ resolvedBy: resolvedFlow.resolvedBy
7203
+ });
7204
+ return {
7205
+ domain: "flow-app",
7206
+ workspace,
7207
+ flow: options.flow,
7208
+ target_context: evidence,
7209
+ evidence,
7210
+ source: {
7211
+ flow: flowExportPath(resolvedFlow.id),
7212
+ form_template: formTemplateId ? `/form_template/${formTemplateId}` : null,
7213
+ workspace: workspaceDefinition.exportPath ? workspaceDefinition.exportPath(workspace) : null
7214
+ },
7215
+ recommended_next_commands: evidence.missing_context.length ? [
7216
+ "If form_template_id is missing, inspect the flow data.meta.form_template and publish the form binding first.",
7217
+ "If workspace_binding is missing, rebuild workspace-flow from fresh export and submit the merged binding."
7218
+ ] : []
7219
+ };
7220
+ }
6903
7221
  function comparableSubmitPayload(domain, value, options) {
6904
7222
  const comparable2 = domain === "form-template" && options.ignoreServerFields ? stripServerFilledFields(value, FORM_TEMPLATE_SERVER_FIELD_KEYS) : value;
6905
7223
  return buildDomainSubmitPayload(domain, comparable2);
@@ -7425,7 +7743,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7425
7743
  const expectedConfirm2 = `submit ${domain} ${id}`;
7426
7744
  if (confirm3 !== expectedConfirm2) {
7427
7745
  return {
7428
- dry_run: true,
7746
+ ...dryRunFields(expectedConfirm2),
7429
7747
  domain,
7430
7748
  id,
7431
7749
  endpoint: endpoint2,
@@ -7455,7 +7773,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7455
7773
  throw new Error(`workspace-flow submit verification failed; missing bindings: ${missingBindings.map((item) => buildWorkspaceFlowBindingKey(item.flow_type, item.flow_key)).join(", ")}`);
7456
7774
  }
7457
7775
  return {
7458
- dry_run: false,
7776
+ ...executedFields(),
7459
7777
  domain,
7460
7778
  id,
7461
7779
  endpoint: endpoint2,
@@ -7493,7 +7811,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7493
7811
  await ensureConfigCapability(profile, `${definition.capability}.export`);
7494
7812
  if (confirm3 !== expectedConfirm2) {
7495
7813
  return {
7496
- dry_run: true,
7814
+ ...dryRunFields(expectedConfirm2),
7497
7815
  domain,
7498
7816
  id,
7499
7817
  endpoint: "/workspace",
@@ -7509,14 +7827,15 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7509
7827
  { data: submit2.payload, capability: `${definition.capability}.create` }
7510
7828
  );
7511
7829
  const readback3 = await readRemoteConfigDomain(profile, domain, `key:${workspaceKey}`, definition);
7830
+ const createdId = responseDataId(response3) ?? (isRecord3(readback3) ? readback3.id ?? null : null);
7512
7831
  return {
7513
- dry_run: false,
7832
+ ...executedFields(),
7514
7833
  domain,
7515
- id,
7834
+ ...standardConfigWriteResponse({ domain, id, executedId: createdId, payload: submit2.payload, response: response3, readback: readback3 }),
7516
7835
  endpoint: "/workspace",
7517
7836
  method: "POST",
7518
7837
  response: response3,
7519
- created_id: responseDataId(response3) ?? (isRecord3(readback3) ? readback3.id ?? null : null),
7838
+ created_id: createdId,
7520
7839
  readback_hash: hashJson(readback3)
7521
7840
  };
7522
7841
  }
@@ -7537,7 +7856,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7537
7856
  const endpoint2 = `/workspace/${encodeURIComponent(workspaceId)}`;
7538
7857
  if (confirm3 !== expectedConfirm2) {
7539
7858
  return {
7540
- dry_run: true,
7859
+ ...dryRunFields(expectedConfirm2),
7541
7860
  domain,
7542
7861
  id,
7543
7862
  endpoint: endpoint2,
@@ -7556,9 +7875,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7556
7875
  );
7557
7876
  const readback2 = await readRemoteConfigDomain(profile, domain, workspaceKey ? `key:${workspaceKey}` : workspaceId, definition);
7558
7877
  return {
7559
- dry_run: false,
7878
+ ...executedFields(),
7560
7879
  domain,
7561
- id,
7880
+ ...standardConfigWriteResponse({ domain, id, payload: submit2.payload, response: response2, readback: readback2 }),
7562
7881
  endpoint: endpoint2,
7563
7882
  method: "PUT",
7564
7883
  response: response2,
@@ -7608,7 +7927,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7608
7927
  }
7609
7928
  if (confirm3 !== expectedConfirm2) {
7610
7929
  return {
7611
- dry_run: true,
7930
+ ...dryRunFields(expectedConfirm2),
7612
7931
  domain,
7613
7932
  id,
7614
7933
  operation_plan: submit2.payload,
@@ -7618,7 +7937,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7618
7937
  };
7619
7938
  }
7620
7939
  return {
7621
- dry_run: false,
7940
+ ...executedFields(),
7622
7941
  domain,
7623
7942
  id,
7624
7943
  ...domain === "role" ? await submitRoleOperations(profile, id, submit2) : await submitAggregateConfigDomain(profile, domain, id, submit2)
@@ -7655,11 +7974,14 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7655
7974
  if (domain === "list-template") {
7656
7975
  validateListTemplateActionGate(submit.payload);
7657
7976
  }
7977
+ if (domain === "dataset-field") {
7978
+ validateDatasetFieldCreatePayload(submit.payload);
7979
+ }
7658
7980
  await ensureConfigCapability(profile, `${definition.capability}.create`);
7659
7981
  const expectedConfirm2 = `submit ${domain} ${id}`;
7660
7982
  if (confirm3 !== expectedConfirm2) {
7661
7983
  return {
7662
- dry_run: true,
7984
+ ...dryRunFields(expectedConfirm2),
7663
7985
  domain,
7664
7986
  id,
7665
7987
  endpoint: definition.createPath,
@@ -7686,9 +8008,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7686
8008
  }
7687
8009
  }
7688
8010
  return {
7689
- dry_run: false,
8011
+ ...executedFields(),
7690
8012
  domain,
7691
- id,
8013
+ ...standardConfigWriteResponse({ domain, id, executedId: createdId ?? null, payload: submit.payload, response: response2 }),
7692
8014
  created_id: createdId ?? null,
7693
8015
  endpoint: definition.createPath,
7694
8016
  method: definition.createMethod,
@@ -7725,7 +8047,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7725
8047
  const endpoint2 = "/form_template";
7726
8048
  if (confirm3 !== expectedConfirm2) {
7727
8049
  return {
7728
- dry_run: true,
8050
+ ...dryRunFields(expectedConfirm2),
7729
8051
  domain,
7730
8052
  id,
7731
8053
  endpoint: endpoint2,
@@ -7766,9 +8088,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7766
8088
  { capability: `${definition.capability}.export` }
7767
8089
  );
7768
8090
  return {
7769
- dry_run: false,
8091
+ ...executedFields(),
7770
8092
  domain,
7771
- id,
8093
+ ...standardConfigWriteResponse({ domain, id, executedId: publishedId, payload: submit.payload, response: publishResponse2, readback: publishedReadback }),
7772
8094
  endpoint: endpoint2,
7773
8095
  method: "POST",
7774
8096
  response: response2,
@@ -7810,7 +8132,7 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7810
8132
  }
7811
8133
  if (confirm3 !== expectedConfirm) {
7812
8134
  return {
7813
- dry_run: true,
8135
+ ...dryRunFields(expectedConfirm),
7814
8136
  domain,
7815
8137
  id,
7816
8138
  endpoint,
@@ -7840,9 +8162,9 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
7840
8162
  }
7841
8163
  const readback = await readBackConfigDomain(profile, domain, id, definition);
7842
8164
  return {
7843
- dry_run: false,
8165
+ ...executedFields(),
7844
8166
  domain,
7845
- id,
8167
+ ...standardConfigWriteResponse({ domain, id, payload: submitPayload, response }),
7846
8168
  endpoint,
7847
8169
  method: definition.submitMethod,
7848
8170
  ...publishMode ? { publish_mode: publishMode } : {},
@@ -7936,7 +8258,7 @@ async function runDatasetLifecycleAction(config, profile, action, id, confirm3)
7936
8258
  ];
7937
8259
  if (confirm3 !== expectedConfirm) {
7938
8260
  return {
7939
- dry_run: true,
8261
+ ...dryRunFields(expectedConfirm),
7940
8262
  domain: "dataset",
7941
8263
  id,
7942
8264
  action: commandAction,
@@ -7962,15 +8284,166 @@ async function runDatasetLifecycleAction(config, profile, action, id, confirm3)
7962
8284
  }
7963
8285
  const readback = await readRemoteConfigDomain(profile, "dataset", id, definition);
7964
8286
  return {
7965
- dry_run: false,
8287
+ ...executedFields(),
7966
8288
  domain: "dataset",
7967
8289
  id,
7968
8290
  action: commandAction,
7969
8291
  operations: executableOperations,
7970
8292
  operation_responses: responses,
8293
+ readback_hash: hashJson(readback),
8294
+ readback_hint: configReadbackHint("dataset", id),
7971
8295
  readback
7972
8296
  };
7973
8297
  }
8298
+ function normalizeConfigBatchItems(manifest) {
8299
+ if (Array.isArray(manifest)) {
8300
+ return manifest.filter(isRecord3);
8301
+ }
8302
+ if (!isRecord3(manifest)) {
8303
+ throw new Error("config batch manifest must be a JSON object or array.");
8304
+ }
8305
+ const items = manifest.operations ?? manifest.items ?? manifest.rows;
8306
+ if (!Array.isArray(items)) {
8307
+ throw new Error("config batch manifest requires operations, items, or rows array.");
8308
+ }
8309
+ return items.filter(isRecord3);
8310
+ }
8311
+ function assertBatchItemDomain(domain) {
8312
+ if (typeof domain !== "string" || !Object.prototype.hasOwnProperty.call(CONFIG_DOMAINS, domain)) {
8313
+ throw new Error(`config batch item requires a supported domain, got ${String(domain)}.`);
8314
+ }
8315
+ return domain;
8316
+ }
8317
+ async function writeOptionalBatchResponse(file, value) {
8318
+ if (typeof file !== "string" || !file.trim()) {
8319
+ return null;
8320
+ }
8321
+ await writeJsonFile(file, value);
8322
+ return file;
8323
+ }
8324
+ async function runConfigBatchSubmit(config, profile, manifestFile, options = {}) {
8325
+ const manifest = await readJsonFile(manifestFile);
8326
+ const items = normalizeConfigBatchItems(manifest);
8327
+ const results = [];
8328
+ for (let index = 0; index < items.length; index += 1) {
8329
+ const item = items[index];
8330
+ const domain = assertBatchItemDomain(item.domain);
8331
+ const id = typeof item.id === "string" ? item.id : "";
8332
+ const payload = typeof item.payload === "string" ? item.payload : "";
8333
+ if (!id || !payload) {
8334
+ const result = {
8335
+ ok: false,
8336
+ index,
8337
+ domain,
8338
+ id,
8339
+ action: "submit",
8340
+ error: "config batch submit item requires id and payload."
8341
+ };
8342
+ results.push(result);
8343
+ await writeOptionalBatchResponse(item.response_out, result);
8344
+ if (!options.continueOnError) break;
8345
+ continue;
8346
+ }
8347
+ try {
8348
+ const response = await submitConfigDomain(config, profile, domain, id, payload, item.confirm);
8349
+ const result = {
8350
+ ok: true,
8351
+ index,
8352
+ domain,
8353
+ id,
8354
+ action: "submit",
8355
+ response
8356
+ };
8357
+ results.push(result);
8358
+ await writeOptionalBatchResponse(item.response_out, response);
8359
+ } catch (error) {
8360
+ const result = {
8361
+ ok: false,
8362
+ index,
8363
+ domain,
8364
+ id,
8365
+ action: "submit",
8366
+ error: error instanceof Error ? error.message : String(error || "")
8367
+ };
8368
+ results.push(result);
8369
+ await writeOptionalBatchResponse(item.response_out, result);
8370
+ if (!options.continueOnError) break;
8371
+ }
8372
+ }
8373
+ const failures = results.filter((item) => item.ok === false);
8374
+ return {
8375
+ ok: failures.length === 0,
8376
+ manifest_file: manifestFile,
8377
+ action: "submit",
8378
+ continue_on_error: Boolean(options.continueOnError),
8379
+ total: items.length,
8380
+ completed: results.length,
8381
+ succeeded: results.length - failures.length,
8382
+ failed: failures.length,
8383
+ results
8384
+ };
8385
+ }
8386
+ async function runConfigBatchReadback(config, profile, manifestFile, options = {}) {
8387
+ const manifest = await readJsonFile(manifestFile);
8388
+ const items = normalizeConfigBatchItems(manifest);
8389
+ const results = [];
8390
+ for (let index = 0; index < items.length; index += 1) {
8391
+ const item = items[index];
8392
+ const domain = assertBatchItemDomain(item.domain);
8393
+ const id = typeof item.id === "string" ? item.id : "";
8394
+ if (!id) {
8395
+ const result = {
8396
+ ok: false,
8397
+ index,
8398
+ domain,
8399
+ id,
8400
+ action: "readback",
8401
+ error: "config batch readback item requires id."
8402
+ };
8403
+ results.push(result);
8404
+ await writeOptionalBatchResponse(item.response_out, result);
8405
+ if (!options.continueOnError) break;
8406
+ continue;
8407
+ }
8408
+ try {
8409
+ const response = await readbackConfigDomain(config, profile, domain, id);
8410
+ const result = {
8411
+ ok: true,
8412
+ index,
8413
+ domain,
8414
+ id,
8415
+ action: "readback",
8416
+ response
8417
+ };
8418
+ results.push(result);
8419
+ await writeOptionalBatchResponse(item.response_out, response);
8420
+ } catch (error) {
8421
+ const result = {
8422
+ ok: false,
8423
+ index,
8424
+ domain,
8425
+ id,
8426
+ action: "readback",
8427
+ error: error instanceof Error ? error.message : String(error || "")
8428
+ };
8429
+ results.push(result);
8430
+ await writeOptionalBatchResponse(item.response_out, result);
8431
+ if (!options.continueOnError) break;
8432
+ }
8433
+ }
8434
+ const failures = results.filter((item) => item.ok === false);
8435
+ return {
8436
+ ok: failures.length === 0,
8437
+ manifest_file: manifestFile,
8438
+ action: "readback",
8439
+ continue_on_error: Boolean(options.continueOnError),
8440
+ total: items.length,
8441
+ completed: results.length,
8442
+ succeeded: results.length - failures.length,
8443
+ failed: failures.length,
8444
+ results
8445
+ };
8446
+ }
7974
8447
 
7975
8448
  // src/core/config-workspace.ts
7976
8449
  import { mkdir as mkdir6, readFile as readFile9, writeFile as writeFile6 } from "fs/promises";
@@ -9303,6 +9776,45 @@ async function pullLatestConfigEnvironment(env, options) {
9303
9776
 
9304
9777
  // src/commands/config.ts
9305
9778
  var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9779
+ function csvCell(value) {
9780
+ const text5 = value === null || value === void 0 ? "" : Array.isArray(value) || isRecord5(value) ? JSON.stringify(value) : String(value);
9781
+ return /[",\n\r]/.test(text5) ? `"${text5.replace(/"/g, '""')}"` : text5;
9782
+ }
9783
+ async function writeEvidenceOut(file, value) {
9784
+ if (!file) {
9785
+ return;
9786
+ }
9787
+ await mkdir8(path9.dirname(path9.resolve(file)), { recursive: true });
9788
+ const evidence = isRecord5(value.evidence) ? value.evidence : value;
9789
+ if (file.endsWith(".csv")) {
9790
+ const keys = [
9791
+ "flow_type",
9792
+ "flow_key",
9793
+ "flow_template_id",
9794
+ "form_template_id",
9795
+ "form_template_draft_id",
9796
+ "workspace_key",
9797
+ "workspace_binding_found",
9798
+ "workspace_readback_hash",
9799
+ "evidence_status",
9800
+ "verified_at"
9801
+ ];
9802
+ await writeFile8(file, `${keys.join(",")}
9803
+ ${keys.map((key) => csvCell(evidence[key])).join(",")}
9804
+ `, "utf8");
9805
+ return;
9806
+ }
9807
+ await writeFile8(file, `${JSON.stringify(evidence, null, 2)}
9808
+ `, "utf8");
9809
+ }
9810
+ async function writeResponseOut(file, value) {
9811
+ if (!file) {
9812
+ return;
9813
+ }
9814
+ await mkdir8(path9.dirname(path9.resolve(file)), { recursive: true });
9815
+ await writeFile8(file, `${JSON.stringify(value, null, 2)}
9816
+ `, "utf8");
9817
+ }
9306
9818
  async function resolveFlowTemplatePluginLintOptions(options) {
9307
9819
  const configData = await loadConfig();
9308
9820
  const profileName = options.profile || configData.current_profile || "default";
@@ -9441,9 +9953,16 @@ function registerConfigCommands(program2) {
9441
9953
  user: target.user || null
9442
9954
  });
9443
9955
  });
9444
- config.command("adapters").description("Show typed config domain adapter coverage and verified API surfaces").option("--profile <profile>", "Profile name (accepted for consistency; adapter coverage is local and profile-independent)").option("--format <format>", "Output format", "table").action(async (options) => {
9956
+ config.command("adapters").description("Show typed config domain adapter coverage and verified API surfaces").option("--profile <profile>", "Profile name (accepted for consistency; adapter coverage is local and profile-independent)").option("--capability <capability>", "Filter by capability name, e.g. config.dataset_field.create").option("--format <format>", "Output format", "table").action(async (options) => {
9445
9957
  void options.profile;
9446
- printResult(options.format, configAdapterMatrix());
9958
+ const rows = configAdapterMatrix();
9959
+ const filtered = options.capability ? rows.filter((row) => Object.values(row).some((value) => {
9960
+ if (Array.isArray(value)) {
9961
+ return value.includes(options.capability);
9962
+ }
9963
+ return value === options.capability;
9964
+ })) : rows;
9965
+ printResult(options.format, filtered);
9447
9966
  });
9448
9967
  config.command("plugin").description("Manage plugin-provided typed config adapters").argument("[domain]", "Plugin typed config domain, or adapters").argument("[operation]", "Operation: export, lint, build, diff, submit, verify, test").option("--id <id>", "Remote plugin config id, list/all, or create:<stable-key>").option("--work <file>", "Work JSON file").option("--base <file>", "Optional raw baseline JSON for lifecycle rules").option("--out <file>", "Output file or directory").option("--meta <file>", "Export meta JSON file").option("--submit <file>", "Submit JSON file for diff").option("--payload <file>", "Submit payload JSON file produced by build").option("--expect <file>", "Expected work JSON file").option("--message <message>", "Smoke test message").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin adapter discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "pretty").action(async (domain, operation, options) => {
9449
9968
  if (domain === "adapters" && !operation) {
@@ -9543,7 +10062,23 @@ function registerConfigCommands(program2) {
9543
10062
  next: `Run git -C ${environment.sysconfig_repo_path} status --short and git diff to inspect local changes.`
9544
10063
  });
9545
10064
  });
9546
- config.command("flow-app").description("Create an end-to-end BPMAX flow app from form and flow work files").command("create").description("Create a form template, create a main flow, bind the published form, and bind the flow to a workspace").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--form-work <file>", "Form-template work JSON file").requiredOption("--flow-work <file>", "Flow-template work JSON file").requiredOption("--name <name>", "Flow app name used in the confirmation text").option("--profile <profile>", "Profile name").option("--draft-only", "Save the created flow as draft only instead of publishing live").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "pretty").action(async (options) => {
10065
+ const flowApp = config.command("flow-app").description("Inspect or create an end-to-end BPMAX flow app");
10066
+ const registerFlowAppContextCommand = (name) => {
10067
+ flowApp.command(name).description("Collect target flow-app context evidence for migration").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--flow <flow>", "Flow identity: flow_type, flow_type:key, key:<key>, or exact flow name").option("--profile <profile>", "Profile name").option("--evidence-out <file>", "Write target context evidence as JSON or CSV").option("--format <format>", "Output format", "json").action(async (options) => {
10068
+ const configData = await loadConfig();
10069
+ const resolved = resolveProfile(configData, options.profile);
10070
+ const result = await inspectFlowAppContext(configData, resolved, {
10071
+ workspace: options.workspace,
10072
+ flow: options.flow
10073
+ });
10074
+ await writeEvidenceOut(options.evidenceOut, result);
10075
+ await saveConfig(configData);
10076
+ printResult(options.format, result);
10077
+ });
10078
+ };
10079
+ registerFlowAppContextCommand("context");
10080
+ registerFlowAppContextCommand("inspect");
10081
+ flowApp.command("create").description("Create a form template, create a main flow, bind the published form, and bind the flow to a workspace").requiredOption("--workspace <workspace>", "Target workspace key, e.g. oa or w:oa").requiredOption("--form-work <file>", "Form-template work JSON file").requiredOption("--flow-work <file>", "Flow-template work JSON file").requiredOption("--name <name>", "Flow app name used in the confirmation text").option("--profile <profile>", "Profile name").option("--draft-only", "Save the created flow as draft only instead of publishing live").option("--confirm <text>", "Exact confirmation text").option("--evidence-out <file>", "Write apply-ready target context evidence as JSON or CSV after create").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
9547
10082
  const configData = await loadConfig();
9548
10083
  const resolved = resolveProfile(configData, options.profile);
9549
10084
  const result = await createFlowAppFromWork(
@@ -9558,6 +10093,8 @@ function registerConfigCommands(program2) {
9558
10093
  publishLive: !options.draftOnly
9559
10094
  }
9560
10095
  );
10096
+ await writeResponseOut(options.responseOut, result);
10097
+ await writeEvidenceOut(options.evidenceOut, result);
9561
10098
  await saveConfig(configData);
9562
10099
  printResult(options.format, result);
9563
10100
  });
@@ -9591,9 +10128,38 @@ function registerConfigCommands(program2) {
9591
10128
  profile: resolved
9592
10129
  }));
9593
10130
  });
10131
+ config.command("readback <domain>").description("Read back one config object with a unified hash/evidence shape").requiredOption("--id <id>", "Remote config id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (domain, options) => {
10132
+ if (!Object.prototype.hasOwnProperty.call(CONFIG_DOMAINS, domain)) {
10133
+ throw new Error(`Unknown config domain: ${domain}`);
10134
+ }
10135
+ const configData = await loadConfig();
10136
+ const resolved = resolveProfile(configData, options.profile);
10137
+ const result = await readbackConfigDomain(configData, resolved, domain, options.id);
10138
+ await saveConfig(configData);
10139
+ printResult(options.format, result);
10140
+ });
10141
+ const batch = config.command("batch").description("Run guarded typed config operations from a manifest");
10142
+ batch.command("submit").description("Submit typed config payloads from a batch manifest and keep per-row evidence").requiredOption("--manifest <file>", "Batch manifest JSON file").option("--profile <profile>", "Profile name").option("--continue-on-error", "Continue after a row fails and return a final failed summary").option("--format <format>", "Output format", "json").action(async (options) => {
10143
+ const configData = await loadConfig();
10144
+ const resolved = resolveProfile(configData, options.profile);
10145
+ const result = await runConfigBatchSubmit(configData, resolved, options.manifest, {
10146
+ continueOnError: Boolean(options.continueOnError)
10147
+ });
10148
+ await saveConfig(configData);
10149
+ printResult(options.format, result);
10150
+ });
10151
+ batch.command("readback").description("Read back typed config objects from a batch manifest and keep per-row evidence").requiredOption("--manifest <file>", "Batch manifest JSON file").option("--profile <profile>", "Profile name").option("--continue-on-error", "Continue after a row fails and return a final failed summary").option("--format <format>", "Output format", "json").action(async (options) => {
10152
+ const configData = await loadConfig();
10153
+ const resolved = resolveProfile(configData, options.profile);
10154
+ const result = await runConfigBatchReadback(configData, resolved, options.manifest, {
10155
+ continueOnError: Boolean(options.continueOnError)
10156
+ });
10157
+ await saveConfig(configData);
10158
+ printResult(options.format, result);
10159
+ });
9594
10160
  Object.keys(CONFIG_DOMAINS).forEach((domain) => {
9595
10161
  const domainCommand = domain === "workspace" ? workspace.description("Initialize local sysconfig workspaces and manage BPMAX workspace configuration") : config.command(domain).description(`Manage BPMAX ${domain} configuration`);
9596
- const createCommand = domainCommand.command("create").description(domain === "flow-template" ? "Create a new main flow template through the typed adapter" : `Create a ${domain} config object through a verified typed adapter; dry-run unless --confirm is exact`).option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, publish the created flow to live after saving draft").option("--format <format>", "Output format", "pretty");
10162
+ const createCommand = domainCommand.command("create").description(domain === "flow-template" ? "Create a new main flow template through the typed adapter" : `Create a ${domain} config object through a verified typed adapter; dry-run unless --confirm is exact`).option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, publish the created flow to live after saving draft").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty");
9597
10163
  if (domain === "flow-template") {
9598
10164
  createCommand.requiredOption("--work <file>", "Flow-template work JSON file").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex");
9599
10165
  } else {
@@ -9618,6 +10184,7 @@ function registerConfigCommands(program2) {
9618
10184
  { publishLive: Boolean(options.publishLive) }
9619
10185
  );
9620
10186
  await saveConfig(configData);
10187
+ await writeResponseOut(options.responseOut, result);
9621
10188
  printResult(options.format, result);
9622
10189
  });
9623
10190
  if (domain === "project-detail-template") {
@@ -9635,15 +10202,13 @@ function registerConfigCommands(program2) {
9635
10202
  const resolved = resolveProfile(configData, options.profile);
9636
10203
  const workFormat = options.workFormat === "structured" ? "structured" : "raw";
9637
10204
  const result = await exportConfigDomain(configData, resolved, domain, options.id, options.out, { workFormat });
9638
- if (domain === "flow-template" && (options.summary || options.inline)) {
9639
- const workFile = typeof result.work_file === "string" ? result.work_file : void 0;
9640
- const work = workFile ? await readJsonFile(workFile) : void 0;
9641
- if (options.summary) {
9642
- result.summary = summarizeFlowTemplateWork(work);
9643
- }
9644
- if (options.inline) {
9645
- result.work = work;
9646
- }
10205
+ const workFile = typeof result.work_file === "string" ? result.work_file : void 0;
10206
+ const work = (options.inline || domain === "flow-template" && options.summary) && workFile ? await readJsonFile(workFile) : void 0;
10207
+ if (domain === "flow-template" && options.summary) {
10208
+ result.summary = summarizeFlowTemplateWork(work);
10209
+ }
10210
+ if (options.inline) {
10211
+ result.work = work;
9647
10212
  }
9648
10213
  await saveConfig(configData);
9649
10214
  printResult(options.format, result);
@@ -9694,7 +10259,7 @@ function registerConfigCommands(program2) {
9694
10259
  submit_preview: submit || null
9695
10260
  });
9696
10261
  });
9697
- domainCommand.command("submit").description(`Submit a ${domain} payload when a verified domain adapter is available; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").requiredOption("--payload <file>", "Submit payload JSON file produced by build").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, submit this payload as a live publish").option("--format <format>", "Output format", "pretty").action(async (options) => {
10262
+ domainCommand.command("submit").description(`Submit a ${domain} payload when a verified domain adapter is available; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").requiredOption("--payload <file>", "Submit payload JSON file produced by build").option("--profile <profile>", "Profile name").option("--agent <agent>", "Agent adapter for installed plugin lint discovery", "codex").option("--confirm <text>", "Exact confirmation text").option("--publish-live", "For flow-template, submit this payload as a live publish").option("--response-out <file>", "Write the full JSON response to a file").option("--format <format>", "Output format", "pretty").action(async (options) => {
9698
10263
  const configData = await loadConfig();
9699
10264
  const resolved = resolveProfile(configData, options.profile);
9700
10265
  const result = await submitConfigDomain(
@@ -9707,6 +10272,7 @@ function registerConfigCommands(program2) {
9707
10272
  { publishLive: Boolean(options.publishLive), agent: options.agent || "codex" }
9708
10273
  );
9709
10274
  await saveConfig(configData);
10275
+ await writeResponseOut(options.responseOut, result);
9710
10276
  printResult(options.format, result);
9711
10277
  });
9712
10278
  domainCommand.command("delete").description(`Delete a ${domain} config object through a verified typed adapter; dry-run unless --confirm is exact`).requiredOption("--id <id>", "Remote config id").option("--profile <profile>", "Profile name").option("--confirm <text>", "Exact confirmation text").option("--format <format>", "Output format", "pretty").action(async (options) => {
@@ -9723,6 +10289,29 @@ function registerConfigCommands(program2) {
9723
10289
  printResult(options.format, result);
9724
10290
  });
9725
10291
  if (domain === "dataset") {
10292
+ const relationFields = domainCommand.command("relation-fields").description("Manage dataset relationFields through the typed dataset adapter");
10293
+ 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) => {
10294
+ const configData = await loadConfig();
10295
+ const resolved = resolveProfile(configData, options.profile);
10296
+ const result = await submitConfigDomain(
10297
+ configData,
10298
+ resolved,
10299
+ "dataset",
10300
+ options.id,
10301
+ options.payload,
10302
+ options.confirm
10303
+ );
10304
+ await saveConfig(configData);
10305
+ await writeResponseOut(options.responseOut, result);
10306
+ printResult(options.format, result);
10307
+ });
10308
+ relationFields.command("readback").description("Read back dataset relationFields evidence using the unified readback shape").requiredOption("--id <id>", "Remote dataset id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
10309
+ const configData = await loadConfig();
10310
+ const resolved = resolveProfile(configData, options.profile);
10311
+ const result = await readbackConfigDomain(configData, resolved, "dataset", options.id);
10312
+ await saveConfig(configData);
10313
+ printResult(options.format, result);
10314
+ });
9726
10315
  [
9727
10316
  ["publish", "Publish/start a dataset and trigger ES batch generation"],
9728
10317
  ["pause", "Pause a published or pending dataset"],
@@ -9784,8 +10373,8 @@ function registerConfigCommands(program2) {
9784
10373
 
9785
10374
  // src/commands/e2e.ts
9786
10375
  import { createHash as createHash5 } from "crypto";
9787
- import { mkdir as mkdir8, readFile as readFile11, readdir as readdir3, stat as stat5, writeFile as writeFile8 } from "fs/promises";
9788
- import path9 from "path";
10376
+ import { mkdir as mkdir9, readFile as readFile11, readdir as readdir3, stat as stat5, writeFile as writeFile9 } from "fs/promises";
10377
+ import path10 from "path";
9789
10378
 
9790
10379
  // src/core/form-schema.ts
9791
10380
  var FIELD_KEY_NAMES = [
@@ -10718,18 +11307,18 @@ function timestampSlug() {
10718
11307
  return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
10719
11308
  }
10720
11309
  async function ensureDir(dir) {
10721
- const resolved = path9.resolve(dir);
10722
- await mkdir8(resolved, { recursive: true });
11310
+ const resolved = path10.resolve(dir);
11311
+ await mkdir9(resolved, { recursive: true });
10723
11312
  return resolved;
10724
11313
  }
10725
11314
  async function writeEvidence(dir, name, value) {
10726
- const file = path9.join(await ensureDir(dir), name);
10727
- await writeFile8(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
11315
+ const file = path10.join(await ensureDir(dir), name);
11316
+ await writeFile9(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
10728
11317
  `, "utf8");
10729
11318
  return file;
10730
11319
  }
10731
11320
  function cacheRoot() {
10732
- return path9.resolve(".codex/cache/bpmax-e2e");
11321
+ return path10.resolve(".codex/cache/bpmax-e2e");
10733
11322
  }
10734
11323
  function safeSegment(value) {
10735
11324
  return value.trim().replace(/[^a-zA-Z0-9._:-]+/g, "_") || "default";
@@ -10841,7 +11430,7 @@ function buildExpectedChecks(options) {
10841
11430
  ];
10842
11431
  }
10843
11432
  function flowCachePath(profileName, flowId) {
10844
- return path9.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
11433
+ return path10.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
10845
11434
  }
10846
11435
  async function readOptionalJson(file) {
10847
11436
  try {
@@ -10930,7 +11519,7 @@ function dataProfilePath(input) {
10930
11519
  if (!input?.startsWith("@")) {
10931
11520
  return void 0;
10932
11521
  }
10933
- return path9.resolve(input.slice(1));
11522
+ return path10.resolve(input.slice(1));
10934
11523
  }
10935
11524
  function refreshedStepTemplate(options) {
10936
11525
  return {
@@ -10954,15 +11543,15 @@ function refreshedStepTemplate(options) {
10954
11543
  variables: Object.keys(options.plan.data).filter((key) => !["project_id", "action", "urgency"].includes(key)),
10955
11544
  payload_template: options.plan.data,
10956
11545
  source_evidence: {
10957
- evidence_dir: path9.resolve(options.evidenceDir),
10958
- context: path9.basename(options.contextFile)
11546
+ evidence_dir: path10.resolve(options.evidenceDir),
11547
+ context: path10.basename(options.contextFile)
10959
11548
  }
10960
11549
  };
10961
11550
  }
10962
11551
  async function writeRefreshedCache(file, template) {
10963
- const out = path9.resolve(file);
10964
- await mkdir8(path9.dirname(out), { recursive: true });
10965
- await writeFile8(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
11552
+ const out = path10.resolve(file);
11553
+ await mkdir9(path10.dirname(out), { recursive: true });
11554
+ await writeFile9(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
10966
11555
  `, "utf8");
10967
11556
  return out;
10968
11557
  }
@@ -11039,13 +11628,13 @@ test(${JSON.stringify(options.title)}, async ({ page }) => {
11039
11628
  async function writeBrowserTemplate(options) {
11040
11629
  const handoffUrl = handoffUrlFromInput(options.handoff);
11041
11630
  const assertFields = (options.assertFields ?? "").split(",").map((item) => item.trim()).filter(Boolean);
11042
- const out = path9.resolve(options.out);
11043
- await mkdir8(path9.dirname(out), { recursive: true });
11044
- await writeFile8(out, playwrightTemplate({
11631
+ const out = path10.resolve(options.out);
11632
+ await mkdir9(path10.dirname(out), { recursive: true });
11633
+ await writeFile9(out, playwrightTemplate({
11045
11634
  title: options.title ?? "BPMAX create page handoff submit",
11046
11635
  handoffUrl,
11047
11636
  assertFields,
11048
- evidenceDir: path9.resolve(options.evidenceDir)
11637
+ evidenceDir: path10.resolve(options.evidenceDir)
11049
11638
  }), "utf8");
11050
11639
  return { out, handoff_url: handoffUrl, assert_fields: assertFields };
11051
11640
  }
@@ -11208,7 +11797,7 @@ function registerE2eCommands(program2) {
11208
11797
  mode: "handoff_command_hint",
11209
11798
  browser: options.browser,
11210
11799
  next_command: `bpmax-cli project create ${flowFlag}${jsonFlag}${profileFlag} --handoff-only --format json > handoff.json`,
11211
- next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path9.resolve(options.evidenceDir)} --format json`,
11800
+ next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path10.resolve(options.evidenceDir)} --format json`,
11212
11801
  note: "create-page-submit does not raw-create a project. First generate a handoff URL, then execute the generated browser template and keep screenshots/result JSON as evidence."
11213
11802
  });
11214
11803
  return;
@@ -11227,7 +11816,7 @@ function registerE2eCommands(program2) {
11227
11816
  browser_verified: false,
11228
11817
  browser: options.browser,
11229
11818
  ...generated,
11230
- evidence_dir: path9.resolve(options.evidenceDir),
11819
+ evidence_dir: path10.resolve(options.evidenceDir),
11231
11820
  next_command: `npx playwright test ${generated.out}`,
11232
11821
  note: "This command does not raw-create a project. Run the generated Playwright script against a logged-in browser context and keep its screenshots/result JSON as browser evidence."
11233
11822
  });
@@ -11278,8 +11867,8 @@ function registerE2eCommands(program2) {
11278
11867
  template_id: result.template_id ?? result.templateId
11279
11868
  })).digest("hex").slice(0, 16);
11280
11869
  const file = flowCachePath(profile.name, options.flowId);
11281
- await mkdir8(path9.dirname(file), { recursive: true });
11282
- await writeFile8(file, `${JSON.stringify(redactAuditValue({
11870
+ await mkdir9(path10.dirname(file), { recursive: true });
11871
+ await writeFile9(file, `${JSON.stringify(redactAuditValue({
11283
11872
  cache_key: cacheKey,
11284
11873
  cached_at: (/* @__PURE__ */ new Date()).toISOString(),
11285
11874
  profile: profile.name,
@@ -11309,7 +11898,7 @@ function registerE2eCommands(program2) {
11309
11898
  printResult(options.format, {
11310
11899
  ok: true,
11311
11900
  ...generated,
11312
- evidence_dir: path9.resolve(options.evidenceDir),
11901
+ evidence_dir: path10.resolve(options.evidenceDir),
11313
11902
  next_command: `npx playwright test ${generated.out}`
11314
11903
  });
11315
11904
  });
@@ -11321,8 +11910,8 @@ function registerE2eCommands(program2) {
11321
11910
  if (inferredStepId && !contextFile && !submitFile) {
11322
11911
  throw new Error(`No step evidence files found for step ${inferredStepId} in ${options.evidenceDir}.`);
11323
11912
  }
11324
- const context = contextFile ? await readOptionalJson(path9.join(options.evidenceDir, contextFile)) : null;
11325
- const submit = submitFile ? await readOptionalJson(path9.join(options.evidenceDir, submitFile)) : null;
11913
+ const context = contextFile ? await readOptionalJson(path10.join(options.evidenceDir, contextFile)) : null;
11914
+ const submit = submitFile ? await readOptionalJson(path10.join(options.evidenceDir, submitFile)) : null;
11326
11915
  const requirements = isRecord8(context?.requirements) ? context.requirements : {};
11327
11916
  const requiredInputs = Array.isArray(requirements.required_inputs) ? requirements.required_inputs.filter(isRecord8) : [];
11328
11917
  const missingInputs = Array.isArray(requirements.missing_required_inputs) ? requirements.missing_required_inputs.filter(isRecord8) : [];
@@ -11365,16 +11954,16 @@ function registerE2eCommands(program2) {
11365
11954
  variables: Object.keys(requestData).filter((key) => !["project_id", "action", "urgency"].includes(key)),
11366
11955
  payload_template: requestData,
11367
11956
  source_evidence: {
11368
- evidence_dir: path9.resolve(options.evidenceDir),
11957
+ evidence_dir: path10.resolve(options.evidenceDir),
11369
11958
  ...contextFile ? { context: contextFile } : {},
11370
11959
  ...submitFile ? { submit: submitFile } : {}
11371
11960
  }
11372
11961
  } : {
11373
- name: options.name ?? path9.basename(path9.resolve(options.evidenceDir)),
11962
+ name: options.name ?? path10.basename(path10.resolve(options.evidenceDir)),
11374
11963
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
11375
11964
  submit_mode: "browser_evidence_bootstrap",
11376
11965
  source_evidence: {
11377
- evidence_dir: path9.resolve(options.evidenceDir),
11966
+ evidence_dir: path10.resolve(options.evidenceDir),
11378
11967
  files: evidenceFiles
11379
11968
  },
11380
11969
  reuse_requirements: [
@@ -11383,9 +11972,9 @@ function registerE2eCommands(program2) {
11383
11972
  "Do not treat API-only evidence as browser E2E proof."
11384
11973
  ]
11385
11974
  };
11386
- const out = path9.resolve(options.out);
11387
- await mkdir8(path9.dirname(out), { recursive: true });
11388
- await writeFile8(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
11975
+ const out = path10.resolve(options.out);
11976
+ await mkdir9(path10.dirname(out), { recursive: true });
11977
+ await writeFile9(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
11389
11978
  `, "utf8");
11390
11979
  printResult(options.format, {
11391
11980
  ok: true,
@@ -11545,7 +12134,7 @@ function registerFlowCommands(program2) {
11545
12134
  const client = createApiClient(profile);
11546
12135
  if (options.flowType) {
11547
12136
  const bindings = await getWorkspaceFlowBindings(client, profile, options);
11548
- const path14 = options.flowKey ? "/flow/options" : "/flow/flow_type";
12137
+ const path15 = options.flowKey ? "/flow/options" : "/flow/flow_type";
11549
12138
  const params = options.flowKey ? {
11550
12139
  detail: "1"
11551
12140
  } : {
@@ -11555,7 +12144,7 @@ function registerFlowCommands(program2) {
11555
12144
  const result2 = await apiRequest(
11556
12145
  client,
11557
12146
  "GET",
11558
- path14,
12147
+ path15,
11559
12148
  {
11560
12149
  params
11561
12150
  }
@@ -11812,10 +12401,10 @@ async function parseOptionalJson(input, label) {
11812
12401
  }
11813
12402
  return parseJsonInput(input, label);
11814
12403
  }
11815
- async function memoryRequest(options, method, path14, capability, data, params) {
12404
+ async function memoryRequest(options, method, path15, capability, data, params) {
11816
12405
  const profile = resolveProfile(await loadConfig(), options.profile);
11817
12406
  const client = createApiClient(profile);
11818
- return apiRequest(client, method, path14, {
12407
+ return apiRequest(client, method, path15, {
11819
12408
  capability,
11820
12409
  data: redactAuditValue(data),
11821
12410
  params: params ? redactAuditValue(params) : void 0
@@ -11897,15 +12486,15 @@ async function parseSeedRules(input) {
11897
12486
  });
11898
12487
  return rules;
11899
12488
  }
11900
- function collectUuidPaths(value, path14 = "$") {
12489
+ function collectUuidPaths(value, path15 = "$") {
11901
12490
  if (typeof value === "string") {
11902
- return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path14] : [];
12491
+ return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path15] : [];
11903
12492
  }
11904
12493
  if (Array.isArray(value)) {
11905
- return value.flatMap((item, index) => collectUuidPaths(item, `${path14}[${index}]`));
12494
+ return value.flatMap((item, index) => collectUuidPaths(item, `${path15}[${index}]`));
11906
12495
  }
11907
12496
  if (typeof value === "object" && value !== null) {
11908
- return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path14}.${key}`));
12497
+ return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path15}.${key}`));
11909
12498
  }
11910
12499
  return [];
11911
12500
  }
@@ -11934,16 +12523,16 @@ function dataArray(value) {
11934
12523
  if (isRecord10(value) && Array.isArray(value.data)) return value.data;
11935
12524
  return [];
11936
12525
  }
11937
- function collectMatrixOwnerPaths(value, path14 = "$") {
12526
+ function collectMatrixOwnerPaths(value, path15 = "$") {
11938
12527
  if (Array.isArray(value)) {
11939
- return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path14}[${index}]`));
12528
+ return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path15}[${index}]`));
11940
12529
  }
11941
12530
  if (!isRecord10(value)) {
11942
12531
  return [];
11943
12532
  }
11944
12533
  const matches = [];
11945
12534
  Object.entries(value).forEach(([key, child]) => {
11946
- const childPath = `${path14}.${key}`;
12535
+ const childPath = `${path15}.${key}`;
11947
12536
  if (key.includes("matrix_owner") || typeof child === "string" && child.includes("matrix_owner")) {
11948
12537
  matches.push({ path: childPath, value: child });
11949
12538
  }
@@ -12772,9 +13361,9 @@ function contextField(field, reason, options = {}) {
12772
13361
  function collectPrefillContextForFields(fields, form, result, options = {}) {
12773
13362
  for (const field of fields) {
12774
13363
  const value = form[field.key];
12775
- const path14 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
13364
+ const path15 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
12776
13365
  const fieldOptions = {
12777
- path: path14,
13366
+ path: path15,
12778
13367
  rootKey: options.rootKey ?? field.key,
12779
13368
  parentKey: options.parentKey
12780
13369
  };
@@ -13191,8 +13780,8 @@ import { spawn as spawn2 } from "child_process";
13191
13780
  import { fileURLToPath as fileURLToPath3 } from "url";
13192
13781
 
13193
13782
  // src/core/recipes.ts
13194
- import { access, mkdir as mkdir9, readdir as readdir4, readFile as readFile13, writeFile as writeFile9 } from "fs/promises";
13195
- import path10 from "path";
13783
+ import { access, mkdir as mkdir10, readdir as readdir4, readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
13784
+ import path11 from "path";
13196
13785
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
13197
13786
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
13198
13787
  function assertSafeName(kind, value) {
@@ -13216,12 +13805,12 @@ function resolveRecipeLocation(options) {
13216
13805
  workspace,
13217
13806
  workspaceDirName,
13218
13807
  recipeName: options.recipeName,
13219
- recipeDir: path10.join(profileDir, "recipes", workspaceDirName, options.recipeName)
13808
+ recipeDir: path11.join(profileDir, "recipes", workspaceDirName, options.recipeName)
13220
13809
  };
13221
13810
  }
13222
13811
  function getRecipesDir(options) {
13223
13812
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
13224
- return path10.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
13813
+ return path11.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
13225
13814
  }
13226
13815
  function isRecord13(value) {
13227
13816
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -13273,7 +13862,7 @@ function parseRecipeDefinition(input) {
13273
13862
  };
13274
13863
  }
13275
13864
  async function loadRecipe(recipeDir) {
13276
- const raw = await readFile13(path10.join(recipeDir, "recipe.json"), "utf8");
13865
+ const raw = await readFile13(path11.join(recipeDir, "recipe.json"), "utf8");
13277
13866
  return parseRecipeDefinition(JSON.parse(raw));
13278
13867
  }
13279
13868
  async function listRecipes(recipesDir) {
@@ -13291,7 +13880,7 @@ async function listRecipes(recipesDir) {
13291
13880
  if (!RECIPE_NAME_PATTERN.test(entry)) {
13292
13881
  continue;
13293
13882
  }
13294
- const recipeDir = path10.join(recipesDir, entry);
13883
+ const recipeDir = path11.join(recipesDir, entry);
13295
13884
  try {
13296
13885
  const recipe = await loadRecipe(recipeDir);
13297
13886
  summaries.push({
@@ -13357,12 +13946,12 @@ function renderTemplate(template, variables) {
13357
13946
  }
13358
13947
  function resolveRecipeFile(recipeDir, token) {
13359
13948
  const relative = token.slice(1);
13360
- if (!relative || relative.includes("..") || path10.isAbsolute(relative)) {
13949
+ if (!relative || relative.includes("..") || path11.isAbsolute(relative)) {
13361
13950
  throw new Error(`Unsafe recipe file reference: ${token}`);
13362
13951
  }
13363
- const resolved = path10.resolve(recipeDir, relative);
13364
- const root = path10.resolve(recipeDir);
13365
- if (resolved !== root && !resolved.startsWith(`${root}${path10.sep}`)) {
13952
+ const resolved = path11.resolve(recipeDir, relative);
13953
+ const root = path11.resolve(recipeDir);
13954
+ if (resolved !== root && !resolved.startsWith(`${root}${path11.sep}`)) {
13366
13955
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
13367
13956
  }
13368
13957
  return resolved;
@@ -13398,7 +13987,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
13398
13987
  }
13399
13988
  async function writeRecipeScaffold(options) {
13400
13989
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
13401
- await mkdir9(options.location.recipeDir, { recursive: true });
13990
+ await mkdir10(options.location.recipeDir, { recursive: true });
13402
13991
  const title = options.title || options.location.recipeName;
13403
13992
  const recipe = {
13404
13993
  version: 1,
@@ -13415,16 +14004,16 @@ async function writeRecipeScaffold(options) {
13415
14004
  mutating: true
13416
14005
  }
13417
14006
  };
13418
- await writeFile9(path10.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
14007
+ await writeFile10(path11.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
13419
14008
  `, "utf8");
13420
- await writeFile9(
13421
- path10.join(options.location.recipeDir, "payload.json"),
14009
+ await writeFile10(
14010
+ path11.join(options.location.recipeDir, "payload.json"),
13422
14011
  `${JSON.stringify({ form: {} }, null, 2)}
13423
14012
  `,
13424
14013
  "utf8"
13425
14014
  );
13426
- await writeFile9(
13427
- path10.join(options.location.recipeDir, "README.md"),
14015
+ await writeFile10(
14016
+ path11.join(options.location.recipeDir, "README.md"),
13428
14017
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
13429
14018
  "utf8"
13430
14019
  );
@@ -13830,8 +14419,8 @@ function registerSetupCommand(program2, deps = {}) {
13830
14419
  }
13831
14420
 
13832
14421
  // src/core/taskbook.ts
13833
- import { mkdir as mkdir10, readFile as readFile14, writeFile as writeFile10 } from "fs/promises";
13834
- import path11 from "path";
14422
+ import { mkdir as mkdir11, readFile as readFile14, writeFile as writeFile11 } from "fs/promises";
14423
+ import path12 from "path";
13835
14424
  var TaskbookError = class extends Error {
13836
14425
  };
13837
14426
  var REQUIRED_TASKBOOK_TERMS = [
@@ -14026,14 +14615,14 @@ function hasDomainWriteEvidence(domain, evidenceText, patterns) {
14026
14615
  function uuidValues(text5) {
14027
14616
  return [...new Set([...text5.matchAll(UUID_PATTERN)].map((match) => match[0]))];
14028
14617
  }
14029
- function addUuidIssues(text5, issues, path14) {
14618
+ function addUuidIssues(text5, issues, path15) {
14030
14619
  for (const value of uuidValues(text5)) {
14031
14620
  addTaskbookIssue(
14032
14621
  issues,
14033
14622
  "uuid_not_allowed",
14034
14623
  "taskbook.config.no_uuid",
14035
14624
  `BPMAX \u914D\u7F6E\u4EFB\u52A1\u4E0D\u80FD\u4F7F\u7528 UUID\uFF1A${value}\u3002`,
14036
- { path: path14, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
14625
+ { path: path15, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
14037
14626
  );
14038
14627
  }
14039
14628
  }
@@ -14065,7 +14654,7 @@ function findNavigationStrategy(text5) {
14065
14654
  const matches = [...text5.matchAll(/导航入口策略\s*[::]\s*(nav-config:(?:included|skipped:[^\s|,。]+|deferred:[^\s|,。]+))/gi)];
14066
14655
  return matches.at(-1)?.[1] || null;
14067
14656
  }
14068
- function validateNavigationStrategy(text5, issues, path14, subject) {
14657
+ function validateNavigationStrategy(text5, issues, path15, subject) {
14069
14658
  const strategy = findNavigationStrategy(text5);
14070
14659
  if (!strategy) {
14071
14660
  addTaskbookIssue(
@@ -14073,7 +14662,7 @@ function validateNavigationStrategy(text5, issues, path14, subject) {
14073
14662
  "missing_navigation_strategy",
14074
14663
  "taskbook.nav.strategy",
14075
14664
  `${subject}\u7F3A\u5C11\u660E\u786E\u7684\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u3002`,
14076
- { path: path14, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
14665
+ { path: path15, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
14077
14666
  );
14078
14667
  return null;
14079
14668
  }
@@ -14083,7 +14672,7 @@ function validateNavigationStrategy(text5, issues, path14, subject) {
14083
14672
  "empty_navigation_strategy_reason",
14084
14673
  "taskbook.nav.strategy_reason",
14085
14674
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u8DF3\u8FC7\u6216\u5EF6\u540E\u65F6\u5FC5\u987B\u5199\u660E\u539F\u56E0\u3002`,
14086
- { path: path14, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
14675
+ { path: path15, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
14087
14676
  );
14088
14677
  }
14089
14678
  if (/(待完成范围确认后回填|待确认|TODO|TBD|占位)/i.test(strategy)) {
@@ -14092,7 +14681,7 @@ function validateNavigationStrategy(text5, issues, path14, subject) {
14092
14681
  "placeholder_navigation_strategy",
14093
14682
  "taskbook.nav.strategy_placeholder",
14094
14683
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u4ECD\u662F\u5360\u4F4D\u5185\u5BB9\u3002`,
14095
- { path: path14, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
14684
+ { path: path15, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
14096
14685
  );
14097
14686
  }
14098
14687
  return strategy;
@@ -14549,8 +15138,8 @@ function taskbookTemplate(title = "BPMAX AI \u5B9E\u65BD\u7F16\u6392\u4EFB\u52A1
14549
15138
  }
14550
15139
  async function initTaskbook(outFile, title) {
14551
15140
  const content = taskbookTemplate(title);
14552
- await mkdir10(path11.dirname(outFile), { recursive: true });
14553
- await writeFile10(outFile, content, "utf8");
15141
+ await mkdir11(path12.dirname(outFile), { recursive: true });
15142
+ await writeFile11(outFile, content, "utf8");
14554
15143
  return { out: outFile, bytes: Buffer.byteLength(content) };
14555
15144
  }
14556
15145
  function splitMarkdownRow(line) {
@@ -14639,8 +15228,8 @@ async function initTaskbookProgress(source, outFile) {
14639
15228
  fields.join(","),
14640
15229
  ...rows.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
14641
15230
  ].join("\n") + "\n";
14642
- await mkdir10(path11.dirname(outFile), { recursive: true });
14643
- await writeFile10(outFile, csv, "utf8");
15231
+ await mkdir11(path12.dirname(outFile), { recursive: true });
15232
+ await writeFile11(outFile, csv, "utf8");
14644
15233
  return { source, out: outFile, task_count: rows.length };
14645
15234
  }
14646
15235
 
@@ -14686,14 +15275,14 @@ import { createHash as createHash6 } from "crypto";
14686
15275
  import {
14687
15276
  copyFile,
14688
15277
  cp as cp3,
14689
- mkdir as mkdir11,
15278
+ mkdir as mkdir12,
14690
15279
  readdir as readdir5,
14691
15280
  readFile as readFile15,
14692
15281
  rm as rm4,
14693
15282
  stat as stat6,
14694
- writeFile as writeFile11
15283
+ writeFile as writeFile12
14695
15284
  } from "fs/promises";
14696
- import path12 from "path";
15285
+ import path13 from "path";
14697
15286
  var DEFAULT_SUITE_ROOT = ".ai_test/suite";
14698
15287
  var DEFAULT_DRAFT_ROOT = ".ai_test/suite_draft";
14699
15288
  var DEFAULT_REPORT_ROOT = ".ai_test/report";
@@ -14851,12 +15440,12 @@ function reviewSchemaExplanation() {
14851
15440
  };
14852
15441
  }
14853
15442
  function reviewFail(reviewPath, message) {
14854
- const scenarioId = path12.basename(path12.dirname(reviewPath));
15443
+ const scenarioId = path13.basename(path13.dirname(reviewPath));
14855
15444
  fail(
14856
15445
  [
14857
15446
  message,
14858
15447
  "\u8FD0\u884C `bpmax-cli test-suite review explain --format json` \u67E5\u770B\u5B8C\u6574 schema\u3002",
14859
- `\u8FD0\u884C \`bpmax-cli test-suite review repair --scenario ${scenarioId} --draft-root ${path12.dirname(path12.dirname(reviewPath))} --latest-proof <proof.json> --format json\` \u4FEE\u8865\u7F3A\u5931\u5B57\u6BB5\u3002`,
15448
+ `\u8FD0\u884C \`bpmax-cli test-suite review repair --scenario ${scenarioId} --draft-root ${path13.dirname(path13.dirname(reviewPath))} --latest-proof <proof.json> --format json\` \u4FEE\u8865\u7F3A\u5931\u5B57\u6BB5\u3002`,
14860
15449
  `\u6700\u5C0F review.json \u793A\u4F8B\uFF1A${JSON.stringify(reviewSchemaExample(scenarioId))}`
14861
15450
  ].join("\n"),
14862
15451
  {
@@ -14945,14 +15534,14 @@ function parseReadmeText(filePath, text5) {
14945
15534
  return metadata;
14946
15535
  }
14947
15536
  async function validateReadme(scenarioDir) {
14948
- const readmePath = path12.join(scenarioDir, "README.md");
15537
+ const readmePath = path13.join(scenarioDir, "README.md");
14949
15538
  if (!await exists3(readmePath)) fail(`missing README.md: ${readmePath}`);
14950
15539
  const text5 = await readText(readmePath);
14951
15540
  const metadata = parseReadmeText(readmePath, text5);
14952
15541
  for (const key of REQUIRED_README_KEYS) {
14953
15542
  if (!metadata[key]) fail(`${scenarioDir}: README.md missing \`${key}\``);
14954
15543
  }
14955
- if (metadata.scenario_id !== path12.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
15544
+ if (metadata.scenario_id !== path13.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
14956
15545
  if (!["true", "false"].includes(metadata.core.toLowerCase())) fail(`${scenarioDir}: core must be true or false`);
14957
15546
  if (!STATUSES.has(metadata.status)) fail(`${scenarioDir}: status must be one of ${JSON.stringify([...STATUSES].sort())}`);
14958
15547
  if (UUID_RE2.test(text5) || ID_AS_ENTRY_RE.test(text5)) {
@@ -15115,8 +15704,8 @@ async function collectE2eAccelerationGaps(root) {
15115
15704
  const dirs = await scenarioDirs(root);
15116
15705
  const gaps = [];
15117
15706
  for (const dir of dirs) {
15118
- const scenarioId = path12.basename(dir);
15119
- const casesPath = path12.join(dir, "cases.csv");
15707
+ const scenarioId = path13.basename(dir);
15708
+ const casesPath = path13.join(dir, "cases.csv");
15120
15709
  if (!await exists3(casesPath)) {
15121
15710
  continue;
15122
15711
  }
@@ -15139,11 +15728,11 @@ async function collectE2eAccelerationGaps(root) {
15139
15728
  async function scenarioDirs(root) {
15140
15729
  if (!await exists3(root)) return [];
15141
15730
  const items = await readdir5(root, { withFileTypes: true });
15142
- return items.filter((item) => item.isDirectory()).map((item) => path12.join(root, item.name)).sort();
15731
+ return items.filter((item) => item.isDirectory()).map((item) => path13.join(root, item.name)).sort();
15143
15732
  }
15144
15733
  async function validateScenario(scenarioDir) {
15145
15734
  const metadata = await validateReadme(scenarioDir);
15146
- const casesPath = path12.join(scenarioDir, "cases.csv");
15735
+ const casesPath = path13.join(scenarioDir, "cases.csv");
15147
15736
  const rows = await readCases(casesPath);
15148
15737
  if (rows.length === 0) fail(`${casesPath}: at least one case is required`);
15149
15738
  const seen = /* @__PURE__ */ new Set();
@@ -15227,9 +15816,9 @@ function validateLatestProofObject(proofPath, proof) {
15227
15816
  }
15228
15817
  function scenarioPath(root, scenario) {
15229
15818
  if (!SCENARIO_ID_RE.test(scenario)) fail(`invalid scenario id: ${scenario}`);
15230
- const rootResolved = path12.resolve(root);
15231
- const candidate = path12.resolve(root, scenario);
15232
- if (!candidate.startsWith(`${rootResolved}${path12.sep}`) && candidate !== rootResolved) {
15819
+ const rootResolved = path13.resolve(root);
15820
+ const candidate = path13.resolve(root, scenario);
15821
+ if (!candidate.startsWith(`${rootResolved}${path13.sep}`) && candidate !== rootResolved) {
15233
15822
  fail(`scenario path escapes root: ${candidate}`);
15234
15823
  }
15235
15824
  return candidate;
@@ -15238,13 +15827,13 @@ async function fileMap(root) {
15238
15827
  const result = /* @__PURE__ */ new Map();
15239
15828
  async function walk(dir) {
15240
15829
  for (const item of await readdir5(dir, { withFileTypes: true })) {
15241
- const itemPath = path12.join(dir, item.name);
15242
- const rel = path12.relative(root, itemPath);
15243
- if (rel.split(path12.sep)[0] === COPY_DIFF_DIR) continue;
15830
+ const itemPath = path13.join(dir, item.name);
15831
+ const rel = path13.relative(root, itemPath);
15832
+ if (rel.split(path13.sep)[0] === COPY_DIFF_DIR) continue;
15244
15833
  if (item.isDirectory()) {
15245
15834
  await walk(itemPath);
15246
15835
  } else if (item.isFile()) {
15247
- result.set(rel.split(path12.sep).join("/"), itemPath);
15836
+ result.set(rel.split(path13.sep).join("/"), itemPath);
15248
15837
  }
15249
15838
  }
15250
15839
  }
@@ -15315,7 +15904,7 @@ async function buildCopyDiff(src, dst, operation) {
15315
15904
  return {
15316
15905
  manifest: {
15317
15906
  operation,
15318
- scenario_id: path12.basename(src),
15907
+ scenario_id: path13.basename(src),
15319
15908
  source: src,
15320
15909
  destination: dst,
15321
15910
  generated_at: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "+00:00"),
@@ -15328,12 +15917,12 @@ async function buildCopyDiff(src, dst, operation) {
15328
15917
  };
15329
15918
  }
15330
15919
  async function writeCopyDiffArtifacts(dst, artifacts) {
15331
- const diffDir = path12.join(dst, COPY_DIFF_DIR);
15332
- await mkdir11(diffDir, { recursive: true });
15333
- await writeFile11(path12.join(diffDir, "last.diff"), artifacts.diff, "utf8");
15334
- await writeFile11(path12.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
15920
+ const diffDir = path13.join(dst, COPY_DIFF_DIR);
15921
+ await mkdir12(diffDir, { recursive: true });
15922
+ await writeFile12(path13.join(diffDir, "last.diff"), artifacts.diff, "utf8");
15923
+ await writeFile12(path13.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
15335
15924
  `, "utf8");
15336
- return path12.join(diffDir, "last.diff");
15925
+ return path13.join(diffDir, "last.diff");
15337
15926
  }
15338
15927
  function summarizeCopyDiff(artifacts) {
15339
15928
  const files = Array.isArray(artifacts.manifest.files) ? artifacts.manifest.files : [];
@@ -15359,14 +15948,14 @@ async function copyScenarioTree(src, dst, replace, operation) {
15359
15948
  artifacts = await buildCopyDiff(src, dst, operation);
15360
15949
  await rm4(dst, { recursive: true, force: true });
15361
15950
  }
15362
- await mkdir11(path12.dirname(dst), { recursive: true });
15951
+ await mkdir12(path13.dirname(dst), { recursive: true });
15363
15952
  await cp3(src, dst, { recursive: true });
15364
15953
  return artifacts ? { path: await writeCopyDiffArtifacts(dst, artifacts), summary: summarizeCopyDiff(artifacts) } : {};
15365
15954
  }
15366
15955
  async function copyDiffPreview(src, dst, operation) {
15367
- const previewDir = path12.join(DEFAULT_TMP_ROOT, `${operation}-${path12.basename(src)}-copy-diff`);
15956
+ const previewDir = path13.join(DEFAULT_TMP_ROOT, `${operation}-${path13.basename(src)}-copy-diff`);
15368
15957
  await rm4(previewDir, { recursive: true, force: true });
15369
- await mkdir11(previewDir, { recursive: true });
15958
+ await mkdir12(previewDir, { recursive: true });
15370
15959
  const artifacts = await buildCopyDiff(src, dst, operation);
15371
15960
  return { path: await writeCopyDiffArtifacts(previewDir, artifacts), summary: summarizeCopyDiff(artifacts) };
15372
15961
  }
@@ -15386,7 +15975,7 @@ async function draftUpdate(options) {
15386
15975
  return { destination: dst, copy_diff: copyDiff.path, copy_diff_summary: copyDiff.summary };
15387
15976
  }
15388
15977
  async function validateReviewGate(scenarioDir) {
15389
- const reviewPath = path12.join(scenarioDir, "review.json");
15978
+ const reviewPath = path13.join(scenarioDir, "review.json");
15390
15979
  if (!await exists3(reviewPath)) reviewFail(reviewPath, `${scenarioDir}: missing review.json; run multi-subagent SKILL review before promote`);
15391
15980
  let review;
15392
15981
  try {
@@ -15394,7 +15983,7 @@ async function validateReviewGate(scenarioDir) {
15394
15983
  } catch (error) {
15395
15984
  reviewFail(reviewPath, `${reviewPath}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
15396
15985
  }
15397
- if (review.scenario_id !== path12.basename(scenarioDir)) reviewFail(reviewPath, `${reviewPath}: scenario_id must match directory name`);
15986
+ if (review.scenario_id !== path13.basename(scenarioDir)) reviewFail(reviewPath, `${reviewPath}: scenario_id must match directory name`);
15398
15987
  if (!review.latest_proof || typeof review.latest_proof !== "object" || Array.isArray(review.latest_proof)) reviewFail(reviewPath, `${reviewPath}: latest_proof is required`);
15399
15988
  validateLatestProofObject(reviewPath, review.latest_proof);
15400
15989
  if (!REVIEW_STATUSES.has(String(review.status))) reviewFail(reviewPath, `${reviewPath}: status must be one of ${JSON.stringify([...REVIEW_STATUSES].sort())}`);
@@ -15503,9 +16092,9 @@ async function initOrRepairReview(options) {
15503
16092
  const scenarioDir = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
15504
16093
  if (!await exists3(scenarioDir)) fail(`draft scenario not found: ${scenarioDir}`);
15505
16094
  await validateReadme(scenarioDir);
15506
- const rows = await readCases(path12.join(scenarioDir, "cases.csv"));
16095
+ const rows = await readCases(path13.join(scenarioDir, "cases.csv"));
15507
16096
  const proof = await readLatestProof(options.latestProof);
15508
- const reviewPath = path12.join(scenarioDir, "review.json");
16097
+ const reviewPath = path13.join(scenarioDir, "review.json");
15509
16098
  let existing;
15510
16099
  const existed = await exists3(reviewPath);
15511
16100
  if (existed) {
@@ -15516,8 +16105,8 @@ async function initOrRepairReview(options) {
15516
16105
  existing = {};
15517
16106
  }
15518
16107
  }
15519
- const review = mergeReviewDraft(path12.basename(scenarioDir), proof, rows, existing);
15520
- await writeFile11(reviewPath, `${JSON.stringify(review, null, 2)}
16108
+ const review = mergeReviewDraft(path13.basename(scenarioDir), proof, rows, existing);
16109
+ await writeFile12(reviewPath, `${JSON.stringify(review, null, 2)}
15521
16110
  `, "utf8");
15522
16111
  return {
15523
16112
  ok: true,
@@ -15551,13 +16140,13 @@ async function nextReportDir(root = DEFAULT_REPORT_ROOT, create = false, today =
15551
16140
  String(today.getDate()).padStart(2, "0")
15552
16141
  ].join("");
15553
16142
  const dirs = await scenarioDirs(root);
15554
- const nums = dirs.map((dir) => path12.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
15555
- const reportDir = path12.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
16143
+ const nums = dirs.map((dir) => path13.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
16144
+ const reportDir = path13.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
15556
16145
  if (create) {
15557
- await mkdir11(path12.join(reportDir, "screenshots"), { recursive: true });
15558
- await writeFile11(
15559
- path12.join(reportDir, "summary.md"),
15560
- ["# BPMAX E2E \u6D4B\u8BD5\u62A5\u544A\u6C47\u603B", "", `run_id: ${path12.basename(reportDir)}`, "status: draft", "", "## \u573A\u666F\u62A5\u544A", "", "## \u603B\u7ED3", ""].join("\n"),
16146
+ await mkdir12(path13.join(reportDir, "screenshots"), { recursive: true });
16147
+ await writeFile12(
16148
+ path13.join(reportDir, "summary.md"),
16149
+ ["# BPMAX E2E \u6D4B\u8BD5\u62A5\u544A\u6C47\u603B", "", `run_id: ${path13.basename(reportDir)}`, "status: draft", "", "## \u573A\u666F\u62A5\u544A", "", "## \u603B\u7ED3", ""].join("\n"),
15561
16150
  "utf8"
15562
16151
  );
15563
16152
  }
@@ -15567,32 +16156,32 @@ async function lintReport(root = DEFAULT_REPORT_ROOT) {
15567
16156
  if (!await exists3(root)) return [`report root not found: ${root}`];
15568
16157
  const errors = [];
15569
16158
  for (const runDir of await scenarioDirs(root)) {
15570
- const runName = path12.basename(runDir);
16159
+ const runName = path13.basename(runDir);
15571
16160
  if (!RUN_RE.test(runName)) {
15572
16161
  errors.push(`${runDir}: run directory name must be YYYYMMDD-NNN`);
15573
16162
  continue;
15574
16163
  }
15575
- if (!await exists3(path12.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
16164
+ if (!await exists3(path13.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
15576
16165
  const files = await readdir5(runDir);
15577
16166
  const scenarioReports = files.filter((file) => file.endsWith(".md") && file !== "summary.md");
15578
16167
  if (scenarioReports.length === 0) errors.push(`${runDir}: missing scenario report markdown`);
15579
16168
  for (const reportName of scenarioReports) {
15580
- const reportPath = path12.join(runDir, reportName);
16169
+ const reportPath = path13.join(runDir, reportName);
15581
16170
  const text5 = await readText(reportPath);
15582
16171
  for (const key of REPORT_REQUIRED_KEYS) if (!text5.includes(key)) errors.push(`${reportPath}: missing \`${key}\``);
15583
16172
  for (const heading of REPORT_REQUIRED_HEADINGS) if (!text5.includes(heading)) errors.push(`${reportPath}: missing \`${heading}\``);
15584
16173
  const imageRefs = [...text5.matchAll(IMAGE_RE)].map((match) => match[1]);
15585
16174
  if (imageRefs.length === 0) errors.push(`${reportPath}: missing embedded screenshot image`);
15586
- const screenshotsDir = path12.join(runDir, "screenshots");
16175
+ const screenshotsDir = path13.join(runDir, "screenshots");
15587
16176
  if (!await exists3(screenshotsDir)) errors.push(`${runDir}: missing screenshots directory`);
15588
16177
  for (const imageRef of imageRefs) {
15589
16178
  if (imageRef.includes("://")) {
15590
16179
  errors.push(`${reportPath}: screenshot must be a local file under this run's screenshots directory`);
15591
16180
  continue;
15592
16181
  }
15593
- const imagePath = path12.resolve(path12.dirname(reportPath), imageRef);
15594
- const screenshotsResolved = path12.resolve(screenshotsDir);
15595
- if (!imagePath.startsWith(`${screenshotsResolved}${path12.sep}`)) {
16182
+ const imagePath = path13.resolve(path13.dirname(reportPath), imageRef);
16183
+ const screenshotsResolved = path13.resolve(screenshotsDir);
16184
+ if (!imagePath.startsWith(`${screenshotsResolved}${path13.sep}`)) {
15596
16185
  errors.push(`${reportPath}: image reference must stay under this run's screenshots directory: ${imageRef}`);
15597
16186
  continue;
15598
16187
  }
@@ -15603,10 +16192,10 @@ async function lintReport(root = DEFAULT_REPORT_ROOT) {
15603
16192
  return errors;
15604
16193
  }
15605
16194
  async function validateCopyDiffArtifacts(scenarioDir) {
15606
- const diffDir = path12.join(scenarioDir, COPY_DIFF_DIR);
16195
+ const diffDir = path13.join(scenarioDir, COPY_DIFF_DIR);
15607
16196
  if (!await exists3(diffDir)) return;
15608
- const manifestPath = path12.join(diffDir, "last.json");
15609
- const diffPath = path12.join(diffDir, "last.diff");
16197
+ const manifestPath = path13.join(diffDir, "last.json");
16198
+ const diffPath = path13.join(diffDir, "last.diff");
15610
16199
  if (!await exists3(manifestPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.json is required when copy diff artifacts exist`);
15611
16200
  if (!await exists3(diffPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.diff is required when copy diff artifacts exist`);
15612
16201
  let manifest;
@@ -15618,7 +16207,7 @@ async function validateCopyDiffArtifacts(scenarioDir) {
15618
16207
  for (const key of ["operation", "scenario_id", "source", "destination", "generated_at", "summary", "diff_file", "files"]) {
15619
16208
  if (!(key in manifest)) fail(`${manifestPath}: missing \`${key}\``);
15620
16209
  }
15621
- if (manifest.scenario_id !== path12.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
16210
+ if (manifest.scenario_id !== path13.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
15622
16211
  if (manifest.diff_file !== "last.diff") fail(`${manifestPath}: diff_file must be last.diff`);
15623
16212
  if (!(await readText(diffPath)).trim()) fail(`${diffPath}: copy diff must not be empty`);
15624
16213
  }
@@ -15666,8 +16255,8 @@ function registerTestSuiteCommands(program2) {
15666
16255
  }
15667
16256
 
15668
16257
  // src/core/update.ts
15669
- import { access as access2, mkdir as mkdir12, readFile as readFile16, realpath, writeFile as writeFile12 } from "fs/promises";
15670
- import path13 from "path";
16258
+ import { access as access2, mkdir as mkdir13, readFile as readFile16, realpath, writeFile as writeFile13 } from "fs/promises";
16259
+ import path14 from "path";
15671
16260
  var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org/";
15672
16261
  var UPDATE_STATE_FILE = "update-state.json";
15673
16262
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -15779,7 +16368,7 @@ async function fetchLatestVersion(options = {}) {
15779
16368
  }
15780
16369
  }
15781
16370
  function updateStatePath(configDir = getConfigDir()) {
15782
- return path13.join(configDir, UPDATE_STATE_FILE);
16371
+ return path14.join(configDir, UPDATE_STATE_FILE);
15783
16372
  }
15784
16373
  async function readUpdateState(configDir) {
15785
16374
  try {
@@ -15794,8 +16383,8 @@ async function readUpdateState(configDir) {
15794
16383
  }
15795
16384
  }
15796
16385
  async function writeUpdateState(state, configDir = getConfigDir()) {
15797
- await mkdir12(configDir, { recursive: true });
15798
- await writeFile12(updateStatePath(configDir), JSON.stringify(state), "utf8");
16386
+ await mkdir13(configDir, { recursive: true });
16387
+ await writeFile13(updateStatePath(configDir), JSON.stringify(state), "utf8");
15799
16388
  }
15800
16389
  async function checkCachedUpdate(currentVersion, configDir = getConfigDir()) {
15801
16390
  if (process.env.BPMAX_CLI_NO_UPDATE_NOTIFIER) {
@@ -15847,7 +16436,7 @@ async function findNpmPath() {
15847
16436
  }
15848
16437
  function detectInstallMethod(input) {
15849
16438
  const resolvedPath = input.executablePath || "";
15850
- const method = resolvedPath.includes(`node_modules${path13.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
16439
+ const method = resolvedPath.includes(`node_modules${path14.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
15851
16440
  return {
15852
16441
  method,
15853
16442
  resolvedPath,