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

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
@@ -288,6 +288,10 @@ function capabilityForRequest(method, path16) {
288
288
  const pluginAgentCapability = pluginAgentCapabilityForRequest(normalizedMethod, normalizedPath);
289
289
  if (pluginAgentCapability) return pluginAgentCapability;
290
290
  if (normalizedMethod === "GET" && normalizedPath === "/user/current") return "user.current";
291
+ if (normalizedMethod === "GET" && normalizedPath === "/user") return "user.search";
292
+ if (normalizedMethod === "GET" && normalizedPath === "/user/options") return "user.search";
293
+ if (normalizedMethod === "GET" && normalizedPath === "/user/get_user_info") return "user.readback";
294
+ if (normalizedMethod === "POST" && normalizedPath === "/project/predicted_path") return "matrix.owner_resolve";
291
295
  if (normalizedMethod === "GET" && normalizedPath === "/workspace/by_key") return "config.workspace_flow.export";
292
296
  if (normalizedMethod === "PUT" && normalizedPath === "/workspace/workspace_flow") return "config.workspace_flow.submit";
293
297
  if (normalizedMethod === "GET" && /^\/workspace\/[^/]+$/.test(normalizedPath)) return "config.workspace.export";
@@ -345,7 +349,7 @@ function capabilityForRequest(method, path16) {
345
349
  if (normalizedMethod === "PUT" && /^\/configuration\/[^/]+$/.test(normalizedPath)) return "config.nav_config.submit";
346
350
  if (normalizedMethod === "DELETE" && /^\/configuration\/[^/]+$/.test(normalizedPath)) return "config.nav_config.delete";
347
351
  if (normalizedMethod === "POST" && normalizedPath === "/project_staging/prefill") return "project.create";
348
- if (normalizedMethod === "GET" && /^\/project_staging\/prefill\/[^/]+$/.test(normalizedPath)) return "project.create";
352
+ if (normalizedMethod === "GET" && normalizedPath === "/project_staging/prefill") return "project.create";
349
353
  if (normalizedMethod === "POST" && normalizedPath === "/project/search") return "project.search";
350
354
  if (normalizedMethod === "POST" && normalizedPath === "/project/list") return "project.list";
351
355
  if (normalizedMethod === "POST" && normalizedPath === "/project") return "project.create";
@@ -474,7 +478,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
474
478
  // package.json
475
479
  var package_default = {
476
480
  name: "bpmax-cli",
477
- version: "0.2.1-beta.29",
481
+ version: "0.2.1-beta.30",
478
482
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
479
483
  type: "module",
480
484
  bin: {
@@ -3699,7 +3703,7 @@ function registerAuthCommands(program2, deps = {}) {
3699
3703
  deviceCode
3700
3704
  });
3701
3705
  config.profiles[profile.name] = updateProfileAuth(config.profiles[profile.name], result);
3702
- const safeUser = config.profiles[profile.name].user;
3706
+ const safeUser2 = config.profiles[profile.name].user;
3703
3707
  await save(config);
3704
3708
  let capabilitiesProbe;
3705
3709
  let pluginSkillUpdates;
@@ -3729,7 +3733,7 @@ function registerAuthCommands(program2, deps = {}) {
3729
3733
  ok: true,
3730
3734
  profile: profile.name,
3731
3735
  login: "authenticated",
3732
- user: safeUser,
3736
+ user: safeUser2,
3733
3737
  ...capabilitiesProbe ? { capabilities_probe: capabilitiesProbe } : {},
3734
3738
  ...pluginSkillUpdates ? { plugin_skill_updates: pluginSkillUpdates } : {},
3735
3739
  ...nextCommands ? { next_commands: nextCommands } : {}
@@ -3851,7 +3855,8 @@ function buildBpmaxUrl(profile, kind, params = {}) {
3851
3855
  const stepId = requireNumericId(params.stepId, "stepId");
3852
3856
  path16 = withQuery(`${basePath}/projectContinue`, {
3853
3857
  id: projectId,
3854
- step_id: stepId
3858
+ step_id: stepId,
3859
+ prefill_token: params.prefillToken
3855
3860
  });
3856
3861
  result.project_id = projectId;
3857
3862
  result.step_id = stepId;
@@ -14149,6 +14154,7 @@ function registerConfigCommands(program2) {
14149
14154
  import { createHash as createHash6 } from "crypto";
14150
14155
  import { mkdir as mkdir10, readFile as readFile12, readdir as readdir4, stat as stat7, writeFile as writeFile10 } from "fs/promises";
14151
14156
  import path11 from "path";
14157
+ import axios7 from "axios";
14152
14158
 
14153
14159
  // src/core/test-suite.ts
14154
14160
  import { createHash as createHash5 } from "crypto";
@@ -17529,6 +17535,57 @@ function cacheRoot() {
17529
17535
  function safeSegment(value) {
17530
17536
  return value.trim().replace(/[^a-zA-Z0-9._:-]+/g, "_") || "default";
17531
17537
  }
17538
+ function safeIdentity(value) {
17539
+ if (!isRecord8(value)) return null;
17540
+ return {
17541
+ id: value.id,
17542
+ name: value.name,
17543
+ organization_id: value.organization_id,
17544
+ mock: Number(value.mock ?? 0) === 1,
17545
+ mock_by_user: value.mock_by_user ?? null
17546
+ };
17547
+ }
17548
+ async function browserSessionRequest(profile, cookie, method, apiPath2, data, hrefPath) {
17549
+ const workspace = normalizeWorkspaceForApi(profile.config.workspace) || "";
17550
+ const origin = profile.config.origin.replace(/\/$/, "");
17551
+ const href = hrefPath?.trim() || `/w:${workspace}/userManagement`;
17552
+ if (!href.startsWith("/")) {
17553
+ throw new Error("e2e.identity.invalid_href: --href-path \u5FC5\u987B\u662F BPMAX \u7AD9\u5185\u7EDD\u5BF9\u8DEF\u5F84\u3002");
17554
+ }
17555
+ const response = await axios7.request({
17556
+ method,
17557
+ url: `${origin}/api${apiPath2}`,
17558
+ params: {
17559
+ $workspace: workspace,
17560
+ $language: profile.config.language || "zhCN"
17561
+ },
17562
+ data,
17563
+ headers: {
17564
+ accept: "application/json, text/plain, */*",
17565
+ "content-type": "application/json",
17566
+ cookie,
17567
+ origin,
17568
+ referer: `${origin}${href}`,
17569
+ "x-href": encodeURIComponent(href)
17570
+ },
17571
+ validateStatus: () => true
17572
+ });
17573
+ const body = response.data;
17574
+ if (response.status >= 400) {
17575
+ throw new Error(`e2e.identity.http_error: HTTP ${response.status} ${apiPath2}\u3002`);
17576
+ }
17577
+ if (isRecord8(body) && typeof body.code === "number" && body.code !== 0) {
17578
+ throw new Error(`e2e.identity.api_error: ${String(body.msg ?? body.message ?? body.code)}`);
17579
+ }
17580
+ return isRecord8(body) && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
17581
+ }
17582
+ function identityCookie(cookieEnv) {
17583
+ const cookie = process.env[cookieEnv]?.trim();
17584
+ if (!cookie) {
17585
+ throw new Error(`e2e.identity.cookie_required: \u8BF7\u5C06\u5F53\u524D\u6D4F\u89C8\u5668\u4F1A\u8BDD Cookie \u5199\u5165\u73AF\u5883\u53D8\u91CF ${cookieEnv}\uFF0C\u4E0D\u8981\u653E\u5728\u547D\u4EE4\u884C\u53C2\u6570\u4E2D\u3002`);
17586
+ }
17587
+ return cookie;
17588
+ }
17532
17589
  function shellQuote5(value) {
17533
17590
  if (/^[a-zA-Z0-9_@%+=:,./-]+$/.test(value)) {
17534
17591
  return value;
@@ -17856,6 +17913,133 @@ function recordKey(record, index) {
17856
17913
  }
17857
17914
  function registerE2eCommands(program2) {
17858
17915
  const e2e = program2.command("e2e").description("BPMAX E2E acceleration helpers with evidence-first safety gates");
17916
+ const identity = e2e.command("identity").description("Control browser-session mock identity for formal multi-role E2E");
17917
+ const addIdentityOptions = (command) => command.requiredOption("--evidence-dir <dir>", "Current-run identity evidence directory").option("--execution-manifest <file>", "Formal test-suite execution manifest").option("--case-id <id>", "Formal test-suite case id").option("--case-step-id <id>", "Formal test-suite case step id").option("--diagnostic", "Run without a formal manifest; cannot become pass evidence").option("--profile <profile>", "Profile providing origin and workspace").option("--cookie-env <name>", "Environment variable containing current browser Cookie", "BPMAX_COOKIE_HEADER").option("--href-path <path>", "BPMAX page path used for Referer and x-href").option("--format <format>", "Output format", "json");
17918
+ addIdentityOptions(identity.command("status").description("Read and record current browser-session identity")).action(async (options) => {
17919
+ await requireE2eExecutionBinding(options, ["browser", "observe"], options.evidenceDir);
17920
+ const config = await loadConfig();
17921
+ const profile = resolveProfile(config, options.profile);
17922
+ const current = safeIdentity(await browserSessionRequest(
17923
+ profile,
17924
+ identityCookie(options.cookieEnv),
17925
+ "GET",
17926
+ "/user/current",
17927
+ void 0,
17928
+ options.hrefPath
17929
+ ));
17930
+ const evidence = await writeEvidence(options.evidenceDir, `identity-status-${timestampSlug()}.json`, {
17931
+ result: options.diagnostic ? "diagnostic" : "observed",
17932
+ operation: "status",
17933
+ operation_executed: false,
17934
+ remote_submitted: false,
17935
+ current_user: current
17936
+ });
17937
+ await appendE2eExecutionEvidence(options, evidence, ["browser", "observe"]);
17938
+ printResult(options.format, {
17939
+ ok: true,
17940
+ result: options.diagnostic ? "diagnostic" : "observed",
17941
+ operation: "status",
17942
+ current_user: current,
17943
+ evidence
17944
+ });
17945
+ });
17946
+ addIdentityOptions(identity.command("mock").description("Switch the current browser session to one exact BPMAX user")).requiredOption("--user-id <id>", "Exact target BPMAX user id").action(async (options) => {
17947
+ const userId = Number(options.userId);
17948
+ if (!Number.isSafeInteger(userId) || userId <= 0) {
17949
+ throw new Error("e2e.identity.invalid_user_id: --user-id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u3002");
17950
+ }
17951
+ await requireE2eExecutionBinding(options, ["browser"], options.evidenceDir);
17952
+ const config = await loadConfig();
17953
+ const profile = resolveProfile(config, options.profile);
17954
+ const cookie = identityCookie(options.cookieEnv);
17955
+ const preflightEvidence = await writeEvidence(options.evidenceDir, `identity-mock-preflight-${timestampSlug()}.json`, {
17956
+ operation: "mock",
17957
+ target_user_id: userId,
17958
+ remote_submitted: false
17959
+ });
17960
+ const before = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
17961
+ let after = null;
17962
+ try {
17963
+ await browserSessionRequest(profile, cookie, "PUT", `/user/${userId}`, { mock: true }, options.hrefPath);
17964
+ after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
17965
+ } catch (error) {
17966
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
17967
+ throw new Error(`e2e.identity.mock_outcome_unknown: mock \u8BF7\u6C42\u6216\u5199\u540E\u56DE\u8BFB\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\uFF1B\u4E0D\u5F97\u91CD\u590D\u6267\u884C\u5F53\u524D\u6B65\u9AA4\uFF0C\u5148\u8FD0\u884C identity status \u786E\u8BA4\u4F1A\u8BDD\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
17968
+ }
17969
+ if (!after || Number(after.id) !== userId || after.mock !== true) {
17970
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
17971
+ throw new Error("e2e.identity.mock_verify_failed: \u8FDC\u7A0B mock \u8BF7\u6C42\u5DF2\u63D0\u4EA4\uFF0C\u4F46\u5F53\u524D\u4F1A\u8BDD\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25\uFF1BCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\u3002");
17972
+ }
17973
+ let evidence;
17974
+ try {
17975
+ evidence = await writeEvidence(options.evidenceDir, `identity-mock-${timestampSlug()}.json`, {
17976
+ result: options.diagnostic ? "diagnostic" : "mocked",
17977
+ operation: "mock",
17978
+ operation_executed: true,
17979
+ remote_submitted: true,
17980
+ readback_confirmed: true,
17981
+ before,
17982
+ after,
17983
+ target_user_id: userId
17984
+ });
17985
+ } catch (error) {
17986
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
17987
+ throw new Error(`e2e.identity.evidence_failed: mock \u540E\u8BC1\u636E\u5199\u5165\u5931\u8D25\uFF0C\u5DF2\u5C1D\u8BD5\u6062\u590D\u539F\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
17988
+ }
17989
+ try {
17990
+ await appendE2eExecutionEvidence(options, evidence, ["browser"]);
17991
+ } catch (error) {
17992
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath).catch(() => void 0);
17993
+ throw new Error(`e2e.identity.manifest_evidence_failed: mock \u5DF2\u6267\u884C\u4F46\u7528\u4F8B\u8BC1\u636E\u767B\u8BB0\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\u3002${error instanceof Error ? error.message : String(error)}`);
17994
+ }
17995
+ printResult(options.format, {
17996
+ ok: true,
17997
+ result: options.diagnostic ? "diagnostic" : "mocked",
17998
+ operation: "mock",
17999
+ operation_executed: true,
18000
+ remote_submitted: true,
18001
+ readback_confirmed: true,
18002
+ current_user: after,
18003
+ evidence,
18004
+ preflight_evidence: preflightEvidence
18005
+ });
18006
+ });
18007
+ addIdentityOptions(identity.command("unmock").description("Restore the original browser-session identity and verify recovery")).action(async (options) => {
18008
+ await requireE2eExecutionBinding(options, ["browser"], options.evidenceDir);
18009
+ const config = await loadConfig();
18010
+ const profile = resolveProfile(config, options.profile);
18011
+ const cookie = identityCookie(options.cookieEnv);
18012
+ await writeEvidence(options.evidenceDir, `identity-unmock-preflight-${timestampSlug()}.json`, {
18013
+ operation: "unmock",
18014
+ remote_submitted: false
18015
+ });
18016
+ const before = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
18017
+ await browserSessionRequest(profile, cookie, "PUT", "/user/current", { unmock: true }, options.hrefPath);
18018
+ const after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
18019
+ if (!after || after.mock === true || before?.mock_by_user && Number(after.id) !== Number(before.mock_by_user)) {
18020
+ throw new Error("e2e.identity.unmock_verify_failed: unmock \u5DF2\u63D0\u4EA4\uFF0C\u4F46\u672A\u786E\u8BA4\u6062\u590D\u539F\u59CB\u8EAB\u4EFD\uFF0C\u5FC5\u987B\u505C\u6B62\u540E\u7EED\u7528\u4F8B\u3002");
18021
+ }
18022
+ const evidence = await writeEvidence(options.evidenceDir, `identity-unmock-${timestampSlug()}.json`, {
18023
+ result: options.diagnostic ? "diagnostic" : "restored",
18024
+ operation: "unmock",
18025
+ operation_executed: true,
18026
+ remote_submitted: true,
18027
+ readback_confirmed: true,
18028
+ before,
18029
+ after
18030
+ });
18031
+ await appendE2eExecutionEvidence(options, evidence, ["browser"]);
18032
+ printResult(options.format, {
18033
+ ok: true,
18034
+ result: options.diagnostic ? "diagnostic" : "restored",
18035
+ operation: "unmock",
18036
+ operation_executed: true,
18037
+ remote_submitted: true,
18038
+ readback_confirmed: true,
18039
+ current_user: after,
18040
+ evidence
18041
+ });
18042
+ });
17859
18043
  e2e.command("step-run").description("Run one or more BPMAX step safe-chain submissions with evidence files").requiredOption("--project-id <projectId>", "Project id").option("--step-id <stepId>", "Step id for single-step mode").option("--action <action>", "Step action", "approve").option("--data <json>", "Single-step submit data JSON or @file").option("--data-profile <json>", "Reusable step profile JSON or @file; supports steps[] or steps object").option("--auto-refresh-cache", "Write a refreshed cache template when expected checks are missing or stale").option("--cache-out <file>", "Refreshed cache template output; defaults to --data-profile @file when possible").option("--comments <comments>", "Step comments").option("--urgency <urgency>", "Urgency value", "1").option("--confirm <confirmation>", "Actually submit; otherwise dry-run only").option("--profile <profile>", "Profile name").option("--execution-manifest <file>", "Formal test-suite execution manifest").option("--case-id <id>", "Formal test-suite case id").option("--case-step-id <id>", "Formal test-suite case step id").option("--diagnostic", "Run without a formal manifest; result cannot be used as pass evidence").option("--evidence-dir <dir>", "Evidence directory", `.codex/tmp/e2e/${timestampSlug()}`).option("--format <format>", "Output format", "json").action(async (options) => {
17860
18044
  await requireE2eExecutionBinding(options, ["e2e_step_run"], options.evidenceDir);
17861
18045
  const config = await loadConfig();
@@ -18700,7 +18884,7 @@ function registerInitCommand(program2, deps = {}) {
18700
18884
  import { readFile as readFile13 } from "fs/promises";
18701
18885
 
18702
18886
  // src/core/issues.ts
18703
- import axios7, { AxiosHeaders as AxiosHeaders3 } from "axios";
18887
+ import axios8, { AxiosHeaders as AxiosHeaders3 } from "axios";
18704
18888
  var DEFAULT_GITLAB_URL = "https://gitlab.yitaiyitai.com";
18705
18889
  var DEFAULT_GITLAB_PROJECT = "bpmax/bpmax-cli";
18706
18890
  var REQUIRED_ISSUE_SECTIONS = [
@@ -18789,7 +18973,7 @@ async function createGitLabIssue(input, options) {
18789
18973
  }
18790
18974
  const baseUrl = normalizeBaseUrl2(options.baseUrl);
18791
18975
  const projectPath = gitLabProjectApiPath(options.project);
18792
- const client = options.client || axios7.create({ baseURL: baseUrl });
18976
+ const client = options.client || axios8.create({ baseURL: baseUrl });
18793
18977
  const headers = AxiosHeaders3.from();
18794
18978
  headers.set("PRIVATE-TOKEN", token);
18795
18979
  const response = await client.request({
@@ -19092,8 +19276,56 @@ var isRecord10 = (value) => typeof value === "object" && value !== null && !Arra
19092
19276
  function dataArray(value) {
19093
19277
  if (Array.isArray(value)) return value;
19094
19278
  if (isRecord10(value) && Array.isArray(value.data)) return value.data;
19279
+ if (isRecord10(value) && Array.isArray(value.list)) return value.list;
19280
+ if (isRecord10(value) && Array.isArray(value.rows)) return value.rows;
19095
19281
  return [];
19096
19282
  }
19283
+ function predictedNodes(value) {
19284
+ if (!isRecord10(value)) return [];
19285
+ return dataArray(value.predicted_nodes).filter(isRecord10);
19286
+ }
19287
+ function safePredictedOwners(value) {
19288
+ return (Array.isArray(value) ? value : []).filter(isRecord10).map((owner) => ({
19289
+ id: owner.id ?? owner.user_id ?? owner.owner_id,
19290
+ name: owner.name ?? null
19291
+ }));
19292
+ }
19293
+ async function fetchAllMatrixRuleRecords(client, flowType) {
19294
+ const pageSize = 100;
19295
+ const maxRecords = 5e3;
19296
+ const records = [];
19297
+ let truncated = false;
19298
+ for (let page = 1; records.length < maxRecords; page += 1) {
19299
+ const result = await apiRequest(client, "POST", "/project/list", {
19300
+ data: { flow_type: flowType, page, page_size: pageSize },
19301
+ capability: "project.list"
19302
+ });
19303
+ const rows = dataArray(result).filter(isRecord10);
19304
+ records.push(...rows);
19305
+ const total = Number(result.count ?? result.total ?? records.length);
19306
+ if (rows.length < pageSize || records.length >= total) break;
19307
+ if (records.length >= maxRecords) {
19308
+ truncated = true;
19309
+ break;
19310
+ }
19311
+ }
19312
+ if (truncated) {
19313
+ throw new Error(`matrix.rules.record_limit_exceeded: \u77E9\u9635\u89C4\u5219\u8BB0\u5F55\u8FBE\u5230 ${maxRecords} \u6761\u5B89\u5168\u4E0A\u9650\uFF0C\u672A\u80FD\u8BC1\u660E\u5168\u91CF\u9A8C\u8BC1\u5B8C\u6210\u3002`);
19314
+ }
19315
+ return records;
19316
+ }
19317
+ async function hydrateMatrixRuleRecords(client, records) {
19318
+ const hydrated = [];
19319
+ for (let index = 0; index < records.length; index += 10) {
19320
+ const chunk = records.slice(index, index + 10);
19321
+ hydrated.push(...await Promise.all(chunk.map(async (record) => {
19322
+ if (isRecord10(record.metaForm) || Array.isArray(record.formList)) return record;
19323
+ const id = Number(record.id ?? record.project_id);
19324
+ return Number.isSafeInteger(id) && id > 0 ? apiRequest(client, "GET", `/project/${id}`) : record;
19325
+ })));
19326
+ }
19327
+ return hydrated;
19328
+ }
19097
19329
  function collectMatrixOwnerPaths(value, path16 = "$") {
19098
19330
  if (Array.isArray(value)) {
19099
19331
  return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path16}[${index}]`));
@@ -19120,6 +19352,130 @@ function findFlowNode2(flow, nodeId) {
19120
19352
  const data = isRecord10(flow.data) ? flow.data : {};
19121
19353
  return dataArray(data.nodes).filter(isRecord10).find((node) => String(node.id ?? node.key ?? node.flow_step_id ?? "") === nodeId);
19122
19354
  }
19355
+ function flowCategory(flow) {
19356
+ const data = isRecord10(flow.data) ? flow.data : {};
19357
+ const meta = isRecord10(data.meta) ? data.meta : {};
19358
+ return String(flow.category ?? data.category ?? meta.category ?? "");
19359
+ }
19360
+ function hasIdentifier(value) {
19361
+ return value !== void 0 && value !== null && String(value).trim() !== "" && String(value) !== "0";
19362
+ }
19363
+ function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], workspaceBound = false) {
19364
+ const data = isRecord10(flow.data) ? flow.data : {};
19365
+ const meta = isRecord10(data.meta) ? data.meta : {};
19366
+ const refs = {
19367
+ form_template_id: meta.form_template ?? flow.form_template_id,
19368
+ list_template_ids: listTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier),
19369
+ filter_template_ids: filterTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier)
19370
+ };
19371
+ const errors = [];
19372
+ if (flowCategory(flow) !== "matrix") {
19373
+ errors.push({
19374
+ code: "matrix.app.category_required",
19375
+ rule_id: "matrix.app.category_required",
19376
+ domain: "approval-matrix",
19377
+ path: "$.category",
19378
+ message: "\u5BA1\u6279\u77E9\u9635\u5E94\u7528\u7684\u6D41\u7A0B category \u5FC5\u987B\u4E3A matrix\u3002",
19379
+ suggestion: "\u4F7F\u7528 category=matrix \u7684\u77E9\u9635\u6D41\u7A0B\uFF0C\u4E0D\u8981\u628A\u666E\u901A\u4E1A\u52A1\u6D41\u7A0B\u5F53\u6210\u77E9\u9635\u3002"
19380
+ });
19381
+ }
19382
+ Object.entries(refs).forEach(([key, value]) => {
19383
+ const present = Array.isArray(value) ? value.length > 0 : hasIdentifier(value);
19384
+ if (!present) {
19385
+ errors.push({
19386
+ code: "matrix.app.template_binding_missing",
19387
+ rule_id: "matrix.app.template_binding_missing",
19388
+ domain: "approval-matrix",
19389
+ path: `$.data.meta.${key.replace(/_id$/, "")}`,
19390
+ message: `\u77E9\u9635\u5E94\u7528\u7F3A\u5C11\u6709\u6548\u7684 ${key}\u3002`,
19391
+ suggestion: "\u5148\u5B8C\u6210\u77E9\u9635\u8868\u5355\u3001\u5217\u8868\u548C\u7B5B\u9009\u6A21\u677F\u7ED1\u5B9A\uFF0C\u518D\u5F55\u5165\u89C4\u5219\u8BB0\u5F55\u3002"
19392
+ });
19393
+ }
19394
+ });
19395
+ if (!workspaceBound) {
19396
+ errors.push({
19397
+ code: "matrix.app.workspace_binding_missing",
19398
+ rule_id: "matrix.app.workspace_binding_missing",
19399
+ domain: "approval-matrix",
19400
+ path: "$.workspace_flow",
19401
+ message: "\u5F53\u524D profile \u5BF9\u5E94\u5DE5\u4F5C\u533A\u672A\u7ED1\u5B9A\u8BE5\u77E9\u9635\u6D41\u7A0B\u3002",
19402
+ suggestion: "\u4ECE\u6700\u65B0 workspace-flow \u56DE\u8BFB merge \u540E\u901A\u8FC7 typed CLI \u63D0\u4EA4\u7ED1\u5B9A\u3002"
19403
+ });
19404
+ }
19405
+ return { category: flowCategory(flow), template_refs: refs, workspace_bound: workspaceBound, errors };
19406
+ }
19407
+ function workspaceHasFlow(value, flowType) {
19408
+ if (!isRecord10(value)) return false;
19409
+ const rows = Array.isArray(value.workspace_flow) ? value.workspace_flow.filter(isRecord10) : isRecord10(value.data) && Array.isArray(value.data.workspace_flow) ? value.data.workspace_flow.filter(isRecord10) : [];
19410
+ return rows.some((item) => String(item.flow_type ?? "") === flowType && Number(item.is_del ?? 0) === 0);
19411
+ }
19412
+ function matrixConsumerSummary(node, expectedMatrixFlowType) {
19413
+ const errors = [];
19414
+ if (!node) {
19415
+ errors.push({
19416
+ code: "matrix.consumer.node_not_found",
19417
+ rule_id: "matrix.consumer.node_not_found",
19418
+ domain: "approval-matrix",
19419
+ path: "$.data.nodes",
19420
+ message: "\u672A\u627E\u5230\u6307\u5B9A\u7684\u77E9\u9635\u6D88\u8D39\u8282\u70B9\u3002",
19421
+ suggestion: "\u6838\u5BF9 --node \u662F\u5426\u4E3A\u7EBF\u4E0A\u6D41\u7A0B\u7684\u8282\u70B9 ID\u3002"
19422
+ });
19423
+ return { errors, owner: null, cc: null };
19424
+ }
19425
+ const owner = isRecord10(node.matrix_owner) ? node.matrix_owner : null;
19426
+ const cc = isRecord10(node.cc_matrix) ? node.cc_matrix : null;
19427
+ const normalizeFlowRef = (value) => String(value ?? "").trim().replace(/:$/, "");
19428
+ if (node.auto_range_type === "matrix") {
19429
+ if (!owner || !String(owner.flow ?? owner.matrix_flow_type ?? "").trim()) {
19430
+ errors.push({ code: "matrix.consumer.owner_flow_required", rule_id: "matrix.consumer.owner_flow_required", domain: "approval-matrix", path: "$.matrix_owner.flow", message: "\u77E9\u9635 owner \u5FC5\u987B\u660E\u786E\u5F15\u7528\u77E9\u9635\u6D41\u7A0B\u3002", suggestion: "\u586B\u5199 matrix_owner.flow \u548C matrix_owner.script\u3002" });
19431
+ }
19432
+ if (!owner || !String(owner.script ?? "").trim()) {
19433
+ errors.push({ code: "matrix.consumer.owner_script_required", rule_id: "matrix.consumer.owner_script_required", domain: "approval-matrix", path: "$.matrix_owner.script", message: "\u77E9\u9635 owner \u5FC5\u987B\u6709\u89C4\u5219\u67E5\u8BE2\u811A\u672C\u3002", suggestion: "\u811A\u672C\u5E94\u8FD4\u56DE\u771F\u5B9E BPMAX \u7528\u6237 ID/\u5BF9\u8C61\u3002" });
19434
+ }
19435
+ const ownerFlow = normalizeFlowRef(owner?.flow ?? owner?.matrix_flow_type);
19436
+ const expectedOwnerFlow = normalizeFlowRef(expectedMatrixFlowType);
19437
+ if (expectedOwnerFlow && ownerFlow && ownerFlow !== expectedOwnerFlow) {
19438
+ errors.push({ code: "matrix.consumer.owner_flow_mismatch", rule_id: "matrix.consumer.owner_flow_mismatch", domain: "approval-matrix", path: "$.matrix_owner.flow", message: `\u6D88\u8D39\u8282\u70B9\u5F15\u7528\u7684 owner \u77E9\u9635\u6D41\u7A0B ${ownerFlow} \u4E0E\u5F85\u9A8C\u8BC1\u77E9\u9635 ${expectedMatrixFlowType} \u4E0D\u4E00\u81F4\u3002`, suggestion: "\u7EDF\u4E00 matrix_owner.flow \u4E0E\u77E9\u9635\u5E94\u7528 flow_type\u3002" });
19439
+ }
19440
+ }
19441
+ if (node.cc_type === "matrix") {
19442
+ if (!cc || !String(cc.flow ?? cc.matrix_flow_type ?? "").trim() || !String(cc.script ?? "").trim()) {
19443
+ errors.push({ code: "matrix.consumer.cc_config_required", rule_id: "matrix.consumer.cc_config_required", domain: "approval-matrix", path: "$.cc_matrix", message: "\u77E9\u9635\u6284\u9001\u5FC5\u987B\u540C\u65F6\u914D\u7F6E cc_matrix.flow \u548C cc_matrix.script\u3002", suggestion: "\u8865\u9F50\u77E9\u9635\u6D41\u7A0B\u5F15\u7528\u4E0E\u8FD4\u56DE\u7528\u6237\u7684\u811A\u672C\u3002" });
19444
+ }
19445
+ const ccFlow = normalizeFlowRef(cc?.flow ?? cc?.matrix_flow_type);
19446
+ const expectedCcFlow = normalizeFlowRef(expectedMatrixFlowType);
19447
+ if (expectedCcFlow && ccFlow && ccFlow !== expectedCcFlow) {
19448
+ errors.push({ code: "matrix.consumer.cc_flow_mismatch", rule_id: "matrix.consumer.cc_flow_mismatch", domain: "approval-matrix", path: "$.cc_matrix.flow", message: `\u6D88\u8D39\u8282\u70B9\u5F15\u7528\u7684\u6284\u9001\u77E9\u9635\u6D41\u7A0B ${ccFlow} \u4E0E\u5F85\u9A8C\u8BC1\u77E9\u9635 ${expectedMatrixFlowType} \u4E0D\u4E00\u81F4\u3002`, suggestion: "\u7EDF\u4E00 cc_matrix.flow \u4E0E\u77E9\u9635\u5E94\u7528 flow_type\u3002" });
19449
+ }
19450
+ }
19451
+ if (node.auto_range_type !== "matrix" && node.cc_type !== "matrix") {
19452
+ errors.push({ code: "matrix.consumer.not_configured", rule_id: "matrix.consumer.not_configured", domain: "approval-matrix", path: "$", message: "\u8282\u70B9\u672A\u914D\u7F6E\u77E9\u9635 owner \u6216\u77E9\u9635\u6284\u9001\u3002", suggestion: "\u6839\u636E\u7528\u9014\u8BBE\u7F6E auto_range_type=matrix \u6216 cc_type=matrix\u3002" });
19453
+ }
19454
+ return { errors, owner, cc };
19455
+ }
19456
+ function projectField(project, key) {
19457
+ const metaForm = isRecord10(project.metaForm) ? project.metaForm : {};
19458
+ const values = dataArray(metaForm.value ?? project.formList).filter(isRecord10);
19459
+ const row = values.find((item) => String(item.key ?? item.field_key ?? "") === key);
19460
+ if (!row) return void 0;
19461
+ const value = row.value;
19462
+ return isRecord10(value) && Object.prototype.hasOwnProperty.call(value, "value") ? value.value : value;
19463
+ }
19464
+ function collectUserIds(value) {
19465
+ if (Array.isArray(value)) return [...new Set(value.flatMap(collectUserIds))];
19466
+ if (isRecord10(value)) {
19467
+ const direct2 = Number(value.id ?? value.user_id ?? value.value);
19468
+ if (Number.isSafeInteger(direct2) && direct2 > 0) return [direct2];
19469
+ return [...new Set(Object.values(value).flatMap(collectUserIds))];
19470
+ }
19471
+ const direct = Number(value);
19472
+ return Number.isSafeInteger(direct) && direct > 0 ? [direct] : [];
19473
+ }
19474
+ function assertNoMatrixErrors(errors) {
19475
+ if (!errors.length) return;
19476
+ throw new Error(`Matrix validation failed:
19477
+ ${errors.map((error) => `- [${String(error.code)}] ${String(error.message)}`).join("\n")}`);
19478
+ }
19123
19479
  function registerMatrixCommands(program2) {
19124
19480
  const matrix = program2.command("matrix").description("Plan and validate BPMAX approval matrix operations");
19125
19481
  matrix.command("seed <flowType>").description("Validate approval matrix seed rule records and print safe project create commands").requiredOption("--rules <jsonOrFile>", "Seed rule object/array JSON or @file").option("--profile <profile>", "Profile name").option("--approver-field <field...>", "Required approver field key(s) inside each rule form").option("--format <format>", "Output format", "pretty").action(async (flowType, options) => {
@@ -19176,7 +19532,7 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19176
19532
  const config = await loadConfig();
19177
19533
  const profile = resolveProfile(config, options.profile);
19178
19534
  const client = createApiClient(profile);
19179
- const [project, flow] = await Promise.all([
19535
+ const [project, flow, prediction] = await Promise.all([
19180
19536
  apiRequest(client, "GET", `/project/${encodeURIComponent(options.projectId)}`),
19181
19537
  apiRequest(client, "GET", "/flow", {
19182
19538
  params: {
@@ -19184,10 +19540,20 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19184
19540
  draft: 0,
19185
19541
  skip_i18n: true
19186
19542
  }
19543
+ }),
19544
+ apiRequest(client, "POST", "/project/predicted_path", {
19545
+ params: { id: options.projectId },
19546
+ data: {},
19547
+ capability: "matrix.owner_resolve"
19187
19548
  })
19188
19549
  ]);
19189
19550
  const node = findFlowNode2(flow, options.node);
19190
19551
  const matrixOwnerConfig = node ? collectMatrixOwnerPaths(node) : [];
19552
+ const predictedNode = predictedNodes(prediction).find((item) => String(item.node_id ?? item.id ?? "") === options.node);
19553
+ const owners = safePredictedOwners(predictedNode?.owners);
19554
+ const ownerResolution = predictedNode && isRecord10(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
19555
+ const projectFlowType = String(project.flow_type ?? "");
19556
+ const flowMatchesProject = !projectFlowType || projectFlowType === options.flowType;
19191
19557
  printResult(options.format, {
19192
19558
  domain: "approval-matrix",
19193
19559
  action: "owner-resolve",
@@ -19195,7 +19561,13 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19195
19561
  node: options.node,
19196
19562
  project_id: options.projectId,
19197
19563
  config_found: matrixOwnerConfig.length > 0,
19198
- runtime_owner_verified: false,
19564
+ runtime_owner_verified: Boolean(predictedNode) && ownerResolution.status !== "error" && owners.length > 0 && flowMatchesProject,
19565
+ owner_resolution_completed: Boolean(predictedNode),
19566
+ resolved_owner_count: owners.length,
19567
+ flow_matches_project: flowMatchesProject,
19568
+ resolver: "/api/project/predicted_path",
19569
+ predicted_owners: owners,
19570
+ owner_resolution: ownerResolution,
19199
19571
  flow_node: node ? {
19200
19572
  id: node.id,
19201
19573
  name: node.name,
@@ -19210,11 +19582,119 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
19210
19582
  notes: [
19211
19583
  "This command is read-only and does not write matrix rule records.",
19212
19584
  "If matrix_owner_config is empty, the target node is not configured for matrix owner resolution or the node id is wrong.",
19213
- "config_found only means matrix_owner-like config exists on the node; it does not prove runtime owner resolution.",
19585
+ "runtime_owner_verified means the platform predicted_path resolver returned the requested node; inspect predicted_owners for the resolved identity set.",
19214
19586
  "Use bpmax-cli matrix seed to validate rule seed data before creating matrix rule project records."
19215
19587
  ]
19216
19588
  });
19217
19589
  });
19590
+ const app = matrix.command("app").description("Inspect approval matrix application configuration");
19591
+ app.command("inspect").requiredOption("--flow-type <flowType>", "Matrix flow type").option("--workspace <workspace>", "Workspace binding to verify; defaults to profile workspace").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
19592
+ const config = await loadConfig();
19593
+ const profile = resolveProfile(config, options.profile);
19594
+ const client = createApiClient(profile);
19595
+ const workspace = String(options.workspace || profile.config.workspace || "").replace(/^w:/, "");
19596
+ if (!workspace) throw new Error("matrix.app.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u9A8C\u8BC1\u77E9\u9635\u5E94\u7528\u7ED1\u5B9A\u3002");
19597
+ const [flow, listResult, filterResult, workspaceResult] = await Promise.all([
19598
+ apiRequest(client, "GET", "/flow", { params: { flow_type: options.flowType, draft: 0, skip_i18n: true } }),
19599
+ apiRequest(client, "GET", "/flow_page_template", { params: { type: 1, flow_type: options.flowType, flow_key: "", skip_i18n: true }, capability: "config.list_template.export" }),
19600
+ apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: options.flowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
19601
+ apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
19602
+ ]);
19603
+ const summary = matrixAppSummary(
19604
+ flow,
19605
+ dataArray(listResult).filter(isRecord10),
19606
+ dataArray(filterResult).filter(isRecord10),
19607
+ workspaceHasFlow(workspaceResult, options.flowType)
19608
+ );
19609
+ assertNoMatrixErrors(summary.errors);
19610
+ printResult(options.format, { ok: true, domain: "approval-matrix", action: "app.inspect", flow_type: options.flowType, ...summary });
19611
+ });
19612
+ const consumer = matrix.command("consumer").description("Lint a business-flow matrix owner or CC consumer node");
19613
+ consumer.command("lint").requiredOption("--flow-type <flowType>", "Business flow type").requiredOption("--node <nodeId>", "Consumer node id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
19614
+ const config = await loadConfig();
19615
+ const profile = resolveProfile(config, options.profile);
19616
+ const flow = await apiRequest(createApiClient(profile), "GET", "/flow", {
19617
+ params: { flow_type: options.flowType, draft: 0, skip_i18n: true }
19618
+ });
19619
+ const node = findFlowNode2(flow, options.node);
19620
+ const summary = matrixConsumerSummary(node);
19621
+ assertNoMatrixErrors(summary.errors);
19622
+ printResult(options.format, { ok: true, domain: "approval-matrix", action: "consumer.lint", flow_type: options.flowType, node: options.node, ...summary });
19623
+ });
19624
+ matrix.command("verify").description("Verify matrix application, online rule records, consumer config, and resolved owners together").requiredOption("--matrix-flow-type <flowType>", "Matrix application flow type").requiredOption("--consumer-flow-type <flowType>", "Business flow type consuming the matrix").requiredOption("--node <nodeId>", "Consumer node id").requiredOption("--project-id <projectId>", "Business project used for owner resolution").requiredOption("--approver-field <field...>", "Approver field key(s) in every matrix rule record").option("--workspace <workspace>", "Workspace binding to verify; defaults to profile workspace").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
19625
+ const config = await loadConfig();
19626
+ const profile = resolveProfile(config, options.profile);
19627
+ const client = createApiClient(profile);
19628
+ const workspace = String(options.workspace || profile.config.workspace || "").replace(/^w:/, "");
19629
+ if (!workspace) throw new Error("matrix.verify.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u9A8C\u8BC1\u77E9\u9635\u5E94\u7528\u7ED1\u5B9A\u3002");
19630
+ const [matrixFlow, consumerFlow, listedRecords, prediction, listResult, filterResult, workspaceResult] = await Promise.all([
19631
+ apiRequest(client, "GET", "/flow", { params: { flow_type: options.matrixFlowType, draft: 0, skip_i18n: true } }),
19632
+ apiRequest(client, "GET", "/flow", { params: { flow_type: options.consumerFlowType, draft: 0, skip_i18n: true } }),
19633
+ fetchAllMatrixRuleRecords(client, options.matrixFlowType),
19634
+ apiRequest(client, "POST", "/project/predicted_path", { params: { id: options.projectId }, data: {}, capability: "matrix.owner_resolve" }),
19635
+ apiRequest(client, "GET", "/flow_page_template", { params: { type: 1, flow_type: options.matrixFlowType, flow_key: "", skip_i18n: true }, capability: "config.list_template.export" }),
19636
+ apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: options.matrixFlowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
19637
+ apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
19638
+ ]);
19639
+ const appSummary = matrixAppSummary(
19640
+ matrixFlow,
19641
+ dataArray(listResult).filter(isRecord10),
19642
+ dataArray(filterResult).filter(isRecord10),
19643
+ workspaceHasFlow(workspaceResult, options.matrixFlowType)
19644
+ );
19645
+ const consumerNode = findFlowNode2(consumerFlow, options.node);
19646
+ const consumerSummary = matrixConsumerSummary(consumerNode, options.matrixFlowType);
19647
+ const records = await hydrateMatrixRuleRecords(client, listedRecords);
19648
+ const errors = [
19649
+ ...appSummary.errors,
19650
+ ...consumerSummary.errors
19651
+ ];
19652
+ if (records.length === 0) {
19653
+ errors.push({ code: "matrix.rules.records_required", rule_id: "matrix.rules.records_required", domain: "approval-matrix", path: "$.rules", message: "\u77E9\u9635\u6D41\u7A0B\u5C1A\u65E0\u7EBF\u4E0A\u89C4\u5219\u8BB0\u5F55\u3002", suggestion: "\u5148\u901A\u8FC7\u5B89\u5168\u9879\u76EE\u521B\u5EFA\u94FE\u8DEF\u5F55\u5165\u771F\u5B9E\u77E9\u9635\u89C4\u5219\u3002" });
19654
+ }
19655
+ const approverIds = /* @__PURE__ */ new Set();
19656
+ records.forEach((record, index) => {
19657
+ options.approverField.forEach((field) => {
19658
+ const ids = collectUserIds(projectField(record, field));
19659
+ if (!ids.length) {
19660
+ errors.push({ code: "matrix.rules.approver_required", rule_id: "matrix.rules.approver_required", domain: "approval-matrix", path: `$.rules[${index}].${field}`, message: `\u77E9\u9635\u89C4\u5219\u8BB0\u5F55 ${index + 1} \u7684\u5BA1\u6279\u4EBA\u5B57\u6BB5 ${field} \u4E3A\u7A7A\u6216\u4E0D\u662F\u7528\u6237 ID\u3002`, suggestion: "\u586B\u5165\u771F\u5B9E\u3001\u6709\u6548\u7684 BPMAX \u7528\u6237\u3002" });
19661
+ }
19662
+ ids.forEach((id) => approverIds.add(id));
19663
+ });
19664
+ });
19665
+ let approvers = [];
19666
+ if (approverIds.size) {
19667
+ const usersResult = await apiRequest(client, "GET", "/user", {
19668
+ params: { ids: [...approverIds].join(","), field_filter: "id,name,status,is_del,organization_id" },
19669
+ capability: "user.readback"
19670
+ });
19671
+ approvers = dataArray(usersResult).filter(isRecord10);
19672
+ const activeIds = new Set(approvers.filter((user) => Number(user.status) === 0 && Number(user.is_del ?? 0) === 0).map((user) => Number(user.id)));
19673
+ [...approverIds].filter((id) => !activeIds.has(id)).forEach((id) => errors.push({ code: "matrix.rules.approver_inactive", rule_id: "matrix.rules.approver_inactive", domain: "approval-matrix", path: "$.rules", message: `\u5BA1\u6279\u4EBA ${id} \u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6709\u6548\u5728\u804C\u72B6\u6001\u3002`, suggestion: "\u91CD\u65B0\u7ED1\u5B9A\u6709\u6548 BPMAX \u7528\u6237\u3002" }));
19674
+ }
19675
+ const predictedNode = predictedNodes(prediction).find((item) => String(item.node_id ?? item.id ?? "") === options.node);
19676
+ const predictedOwners = safePredictedOwners(predictedNode?.owners);
19677
+ const ownerResolution = predictedNode && isRecord10(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
19678
+ if (ownerResolution.status === "error") {
19679
+ errors.push({ code: "matrix.consumer.owner_resolution_error", rule_id: "matrix.consumer.owner_resolution_error", domain: "approval-matrix", path: "$.predicted_nodes[].owner_resolution", message: `\u7EDF\u4E00 owner resolver \u6267\u884C\u5931\u8D25\uFF1A${String(ownerResolution.error_code ?? "unknown")}\u3002`, suggestion: "\u4FEE\u590D\u77E9\u9635/\u5B57\u6BB5/\u89D2\u8272 owner \u89E3\u6790\u9519\u8BEF\u540E\u91CD\u65B0 verify\uFF0C\u4E0D\u5F97\u5C06\u7A7A owners \u5F53\u6210\u6B63\u5E38\u65E0\u4EBA\u3002" });
19680
+ } else if (!predictedNode || predictedOwners.length === 0) {
19681
+ errors.push({ code: "matrix.consumer.owner_resolution_empty", rule_id: "matrix.consumer.owner_resolution_empty", domain: "approval-matrix", path: "$.predicted_nodes", message: "\u7EDF\u4E00 owner resolver \u672A\u4E3A\u6307\u5B9A\u6D88\u8D39\u8282\u70B9\u8FD4\u56DE\u5BA1\u6279\u4EBA\u3002", suggestion: "\u68C0\u67E5\u89C4\u5219\u6761\u4EF6\u3001\u8868\u5355\u8F93\u5165\u3001\u77E9\u9635\u811A\u672C\u548C\u7528\u6237\u5B57\u6BB5\u3002" });
19682
+ }
19683
+ assertNoMatrixErrors(errors);
19684
+ printResult(options.format, {
19685
+ ok: true,
19686
+ domain: "approval-matrix",
19687
+ action: "verify",
19688
+ matrix_flow_type: options.matrixFlowType,
19689
+ consumer_flow_type: options.consumerFlowType,
19690
+ node: options.node,
19691
+ project_id: options.projectId,
19692
+ app: appSummary,
19693
+ rules: { record_count: records.length, approver_fields: options.approverField, active_approver_count: approvers.length },
19694
+ consumer: consumerSummary,
19695
+ owner_resolution: { resolver: "/api/project/predicted_path", status: ownerResolution.status, owners: predictedOwners }
19696
+ });
19697
+ });
19218
19698
  }
19219
19699
 
19220
19700
  // src/commands/plugin.ts
@@ -19645,8 +20125,21 @@ async function parseProjectJson(input, label = "--json") {
19645
20125
  function errorMessage2(error) {
19646
20126
  return error instanceof Error ? error.message : String(error || "");
19647
20127
  }
20128
+ function isRecordValue(value) {
20129
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20130
+ }
20131
+ function parseRecordValue(value) {
20132
+ if (isRecordValue(value)) return value;
20133
+ if (typeof value !== "string" || !value.trim()) return void 0;
20134
+ try {
20135
+ const parsed = JSON.parse(value);
20136
+ return isRecordValue(parsed) ? parsed : void 0;
20137
+ } catch {
20138
+ return void 0;
20139
+ }
20140
+ }
19648
20141
  function isUnsupportedPrefillStatusError(message) {
19649
- return /(^|[^0-9])404([^0-9]|$)/.test(message) || /not found/i.test(message) || /unsupported/i.test(message) || /Cannot GET \/api\/project_staging\/prefill/i.test(message);
20142
+ return /(^|[^0-9])404([^0-9]|$)/.test(message) || /Cannot GET \/api\/project_staging\/prefill/i.test(message) || /prefill (token )?status[^\n]*unsupported/i.test(message);
19650
20143
  }
19651
20144
  async function resolveFlowIdentifiers(client, options, resolveOptions = {}) {
19652
20145
  if (options.flowType) {
@@ -19776,6 +20269,256 @@ async function storeCreateFormPrefill(client, flowIdentifiers, initValue, prefil
19776
20269
  expires_at: result.expires_at
19777
20270
  };
19778
20271
  }
20272
+ function requiredNumericId(value, optionName) {
20273
+ const normalized = String(value || "").trim();
20274
+ if (!/^\d+$/.test(normalized)) {
20275
+ throw new Error(`${optionName} must be a non-empty numeric string.`);
20276
+ }
20277
+ return normalized;
20278
+ }
20279
+ function projectMetaFormTemplate(project) {
20280
+ const metaForm = parseRecordValue(project.metaForm ?? project.meta_form ?? project.projectForm ?? project.project_form);
20281
+ if (!metaForm) return void 0;
20282
+ const template = metaForm.form_template ?? metaForm.formTemplate;
20283
+ return parseRecordValue(template);
20284
+ }
20285
+ function projectMetaFormTemplateId(project) {
20286
+ const template = projectMetaFormTemplate(project);
20287
+ if (template?.id !== void 0 && template.id !== null) {
20288
+ return String(template.id);
20289
+ }
20290
+ const metaForm = parseRecordValue(project.metaForm ?? project.meta_form ?? project.projectForm ?? project.project_form);
20291
+ if (!metaForm) return "";
20292
+ const candidate = metaForm.form_template_id ?? metaForm.formTemplateId ?? metaForm.template_id ?? metaForm.templateId;
20293
+ return candidate === void 0 || candidate === null ? "" : String(candidate);
20294
+ }
20295
+ function flowNodes(flow) {
20296
+ const data = parseRecordValue(flow.data) ?? flow;
20297
+ return Array.isArray(data.nodes) ? data.nodes.filter(isRecordValue) : [];
20298
+ }
20299
+ function ownerId(value) {
20300
+ if (isRecordValue(value)) {
20301
+ return String(value.owner_id ?? value.user_id ?? value.id ?? "").trim();
20302
+ }
20303
+ return String(value ?? "").trim();
20304
+ }
20305
+ function ownerIsPending(value) {
20306
+ if (!isRecordValue(value)) return true;
20307
+ const status = value.status ?? value.owner_status ?? value.handle_status;
20308
+ if (status === void 0 || status === null || status === "") return true;
20309
+ if (typeof status === "number") return status === 0;
20310
+ const normalized = String(status).trim().toLowerCase();
20311
+ return ["0", "pending", "active", "unhandled", "todo", "waiting"].includes(normalized);
20312
+ }
20313
+ function ownerValues(value) {
20314
+ if (value === void 0 || value === null) return [];
20315
+ return Array.isArray(value) ? value : [value];
20316
+ }
20317
+ function stepOwnerValues(step) {
20318
+ return [
20319
+ step.owner_id,
20320
+ step.ownerId,
20321
+ step.user_id,
20322
+ step.userId,
20323
+ ...ownerValues(step.owner),
20324
+ ...ownerValues(step.owners),
20325
+ ...ownerValues(step.owner_list),
20326
+ ...ownerValues(step.step_owners)
20327
+ ];
20328
+ }
20329
+ function stepOwnerIds(step, pendingOnly = false) {
20330
+ const values = pendingOnly ? stepOwnerValues(step).filter(ownerIsPending) : stepOwnerValues(step);
20331
+ return [...new Set(values.map(ownerId).filter((id) => /^\d+$/.test(id)))];
20332
+ }
20333
+ function assertPrefillToken(token, source = "--prefill-token") {
20334
+ const normalized = token.trim();
20335
+ if (!/^[a-f0-9]{48}$/i.test(normalized)) {
20336
+ throw new Error(`${source} must be a 48-character hexadecimal token.`);
20337
+ }
20338
+ return normalized;
20339
+ }
20340
+ function isUnsupportedStepPrefillField(field) {
20341
+ const type = String(field.type || "").toLowerCase();
20342
+ return /(sn_number|signature|upload|pda[_-]?scan|visibility_control|i_button|h_label|i_hr|description)/.test(type);
20343
+ }
20344
+ function assertStepProjectFormWritable(fields, form, prefix = "") {
20345
+ const fieldsByKey = new Map(fields.map((field) => [field.key, field]));
20346
+ for (const [key, value] of Object.entries(form)) {
20347
+ const field = fieldsByKey.get(key);
20348
+ if (!field) continue;
20349
+ const path16 = `${prefix}${key}`;
20350
+ if (field.hidden) {
20351
+ throw new Error(`Step project form handoff cannot write hidden field ${path16}.`);
20352
+ }
20353
+ if (isUnsupportedStepPrefillField(field)) {
20354
+ throw new Error(`Step project form handoff cannot write system or manual field ${path16} (${field.type || "unknown"}).`);
20355
+ }
20356
+ if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
20357
+ value.forEach((row, index) => {
20358
+ if (isRecordValue(row)) {
20359
+ assertStepProjectFormWritable(field.children ?? [], row, `${path16}[${index}].`);
20360
+ }
20361
+ });
20362
+ }
20363
+ }
20364
+ }
20365
+ async function printStepProjectFormHandoff(client, format, profile, options) {
20366
+ const projectId = requiredNumericId(options.projectId, "--project-id");
20367
+ const stepId = requiredNumericId(options.stepId, "--step-id");
20368
+ if (Object.keys(options.form).length === 0) {
20369
+ throw new Error("Step project form handoff requires at least one form field.");
20370
+ }
20371
+ const workspace = normalizeWorkspaceForApi(options.workspace ?? profile.config.workspace);
20372
+ const requestParams = workspace ? { $workspace: workspace } : void 0;
20373
+ const [project, step, currentUser] = await Promise.all([
20374
+ apiRequest(client, "GET", `/project/${projectId}`, {
20375
+ params: requestParams,
20376
+ capability: "step.prefill"
20377
+ }),
20378
+ apiRequest(client, "GET", `/step/${stepId}`, {
20379
+ params: requestParams,
20380
+ capability: "step.prefill"
20381
+ }),
20382
+ apiRequest(client, "GET", "/user/current", {
20383
+ params: requestParams,
20384
+ capability: "step.prefill"
20385
+ })
20386
+ ]);
20387
+ if (String(step.project_id || "") !== projectId) {
20388
+ throw new Error(`Step ${stepId} does not belong to project ${projectId}.`);
20389
+ }
20390
+ if (![1, 3].includes(Number(project.status))) {
20391
+ throw new Error(`Project ${projectId} is not in an editable status.`);
20392
+ }
20393
+ if ([0, 3, 5].includes(Number(step.status))) {
20394
+ throw new Error(`Step ${stepId} is not editable.`);
20395
+ }
20396
+ const currentUserId = String(currentUser.id || currentUser.user_id || "").trim();
20397
+ if (!/^\d+$/.test(currentUserId)) {
20398
+ throw new Error("Current user id is unavailable.");
20399
+ }
20400
+ const ownerIds = stepOwnerIds(step);
20401
+ if (!ownerIds.includes(currentUserId)) {
20402
+ throw new Error(`Current user is not an owner of step ${stepId}.`);
20403
+ }
20404
+ if (!stepOwnerIds(step, true).includes(currentUserId)) {
20405
+ throw new Error(`Current user has already handled step ${stepId}.`);
20406
+ }
20407
+ const flowId = String(project.flow_id || step.flow_id || "");
20408
+ const projectFlowType = String(project.flow_type || step.flow_type || "");
20409
+ const projectFlowKey = String(project.flow_key ?? step.flow_key ?? "");
20410
+ let flow;
20411
+ if (/^\d+$/.test(flowId)) {
20412
+ const flows = await apiRequest(client, "POST", "/flow/batch_get", {
20413
+ params: requestParams,
20414
+ data: { ids: [Number(flowId)] },
20415
+ capability: "step.prefill"
20416
+ });
20417
+ flow = flows.find((item) => String(item.id || "") === flowId);
20418
+ } else {
20419
+ const flows = await apiRequest(client, "GET", "/flow/flow_type", {
20420
+ params: {
20421
+ ...requestParams,
20422
+ draft: "0",
20423
+ skip_i18n: "true"
20424
+ },
20425
+ capability: "step.prefill"
20426
+ });
20427
+ flow = flows.find(
20428
+ (item) => String(item.flow_type || "") === projectFlowType && String(item.key || "") === projectFlowKey
20429
+ );
20430
+ }
20431
+ if (!flow) {
20432
+ throw new Error(`Flow for project ${projectId} was not found.`);
20433
+ }
20434
+ const flowStepId = String(step.flow_step_id || "");
20435
+ const flowNode = flowNodes(flow).find((node) => String(node.id || "") === flowStepId);
20436
+ if (flowNode?.enable_relate_project_form !== true && flowNode?.enable_relate_project_form !== 1) {
20437
+ throw new Error(`Step ${stepId} does not enable an associated project form.`);
20438
+ }
20439
+ let template = projectMetaFormTemplate(project);
20440
+ const formTemplateId = projectMetaFormTemplateId(project);
20441
+ if (!formTemplateId) {
20442
+ throw new Error(`Project ${projectId} does not have an associated project form template.`);
20443
+ }
20444
+ let fields = extractFormFields(template);
20445
+ if (fields.length === 0) {
20446
+ template = await apiRequest(client, "GET", `/form_template/${formTemplateId}`, {
20447
+ params: requestParams,
20448
+ capability: "step.prefill"
20449
+ });
20450
+ fields = extractFormFields(template);
20451
+ }
20452
+ if (fields.length === 0) {
20453
+ throw new Error(`Could not discover fields for project form template ${formTemplateId}.`);
20454
+ }
20455
+ assertHandoffFormCompatible(fields, options.form);
20456
+ assertStepProjectFormWritable(fields, options.form);
20457
+ const flowType = String(flow.flow_type || projectFlowType);
20458
+ if (!flowType) {
20459
+ throw new Error(`Flow for project ${projectId} does not expose a flow_type.`);
20460
+ }
20461
+ const flowKey = String(flow.key || "");
20462
+ const initValue = { key_to_value: options.form };
20463
+ const prefillContext = buildPrefillContext(fields, options.form);
20464
+ const target = {
20465
+ page_type: "project_form_fill",
20466
+ project_id: projectId,
20467
+ step_id: stepId,
20468
+ flow_step_id: flowStepId,
20469
+ form_template_id: formTemplateId
20470
+ };
20471
+ const prefill = await apiRequest(client, "POST", "/project_staging/prefill", {
20472
+ params: requestParams,
20473
+ capability: "step.prefill",
20474
+ data: {
20475
+ flow_type: flowType,
20476
+ flow_key: flowKey,
20477
+ target,
20478
+ init_value: initValue,
20479
+ prefill_context: prefillContext
20480
+ }
20481
+ });
20482
+ if (typeof prefill.token !== "string" || !prefill.token) {
20483
+ throw new Error("Step project form prefill endpoint did not return a token.");
20484
+ }
20485
+ const prefillToken = assertPrefillToken(prefill.token, "Step project form prefill response token");
20486
+ const url = buildBpmaxUrl(profile, "project-step", {
20487
+ workspace: options.workspace,
20488
+ projectId,
20489
+ stepId,
20490
+ prefillToken
20491
+ });
20492
+ const parsedUrl = new URL(url.url);
20493
+ if (parsedUrl.searchParams.get("prefill_token") !== prefillToken) {
20494
+ throw new Error("Generated project step handoff URL is missing prefill_token.");
20495
+ }
20496
+ const replyMarkdown = `[\u586B\u5199\u9879\u76EE\u8868\u5355](${url.url})`;
20497
+ printResult(format, {
20498
+ handoff: true,
20499
+ handoff_type: "step_project_form",
20500
+ project_id: projectId,
20501
+ step_id: stepId,
20502
+ flow_type: flowType,
20503
+ flow_key: flowKey,
20504
+ flow_step_id: flowStepId,
20505
+ form_template_id: formTemplateId,
20506
+ target,
20507
+ url: url.url,
20508
+ reply_markdown: replyMarkdown,
20509
+ prefill_token: prefillToken,
20510
+ prefill_expires_in: prefill.expires_in,
20511
+ prefill_expires_at: prefill.expires_at,
20512
+ init_value: initValue,
20513
+ init_value_keys: Object.keys(options.form),
20514
+ prefill_context: prefillContext,
20515
+ browser_prefill_verified: false,
20516
+ prefill_verification_required: true,
20517
+ next_verification: "Open the project step URL in a real browser and confirm the associated project form controls contain the expected values.",
20518
+ agent_warning: "Use reply_markdown or url exactly as returned. Do not rebuild or shorten the projectContinue URL, and do not claim the form is prefilled until browser verification succeeds.",
20519
+ message: "\u5DF2\u751F\u6210\u73AF\u8282\u5173\u8054\u9879\u76EE\u8868\u5355\u9884\u586B\u94FE\u63A5\uFF0C\u8BF7\u6253\u5F00\u9875\u9762\u786E\u8BA4\u540E\u518D\u5B8C\u6210\u73AF\u8282\u3002"
20520
+ });
20521
+ }
19779
20522
  async function printCreateFormHandoff(client, format, profile, flowIdentifiers, options) {
19780
20523
  const initValue = {
19781
20524
  project: { name: options.name },
@@ -20179,19 +20922,37 @@ function registerProjectCommands(program2) {
20179
20922
  });
20180
20923
  });
20181
20924
  const handoff = project.command("handoff").description("Inspect BPMAX project create-page handoff state");
20182
- handoff.command("status").description("Check whether a create-page prefill token is still readable by the platform").requiredOption("--prefill-token <token>", "Prefill token returned by project create handoff output").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
20925
+ handoff.command("step-form").description("Generate a prefilled project step URL for an associated project form").requiredOption("--project-id <projectId>", "Project id").requiredOption("--step-id <stepId>", "Step id").requiredOption("--json <json>", 'JSON containing {"form": {...}} or a direct form field object').option("--workspace <workspace>", "Workspace override").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
20926
+ const config = await loadConfig();
20927
+ const profile = resolveProfile(config, options.profile);
20928
+ const parsed = await parseProjectJson(options.json, "--json");
20929
+ const form = isRecordValue(parsed.form) ? parsed.form : parsed;
20930
+ await printStepProjectFormHandoff(
20931
+ createApiClient(profile),
20932
+ options.format,
20933
+ profile,
20934
+ {
20935
+ projectId: options.projectId,
20936
+ stepId: options.stepId,
20937
+ workspace: options.workspace,
20938
+ form
20939
+ }
20940
+ );
20941
+ });
20942
+ handoff.command("status").description("Check whether a create-page prefill token is still readable by the platform").requiredOption("--prefill-token <token>", "Prefill token returned by project create handoff output").option("--step-form", "Use the step.prefill capability for an associated project form token").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
20183
20943
  const config = await loadConfig();
20184
20944
  const profile = resolveProfile(config, options.profile);
20185
20945
  const client = createApiClient(profile);
20186
- const token = options.prefillToken.trim();
20187
- if (!token) {
20188
- throw new Error("--prefill-token cannot be empty.");
20189
- }
20946
+ const token = assertPrefillToken(options.prefillToken);
20190
20947
  try {
20191
20948
  const result = await apiRequest(
20192
20949
  client,
20193
20950
  "GET",
20194
- `/project_staging/prefill/${encodeURIComponent(token)}`
20951
+ "/project_staging/prefill",
20952
+ {
20953
+ params: { token },
20954
+ capability: options.stepForm ? "step.prefill" : "project.create"
20955
+ }
20195
20956
  );
20196
20957
  printResult(options.format, {
20197
20958
  ok: true,
@@ -20759,6 +21520,9 @@ var schemaEntries = [
20759
21520
  { name: "auth.device.start", description: "Start device authorization.", method: "POST", path: "/api/cli/device_authorizations", bootstrap: true },
20760
21521
  { name: "auth.device.complete", description: "Complete device authorization.", method: "POST", path: "/api/cli/device_token", bootstrap: true },
20761
21522
  { name: "user.current", description: "Get current user.", method: "GET", path: "/api/user/current" },
21523
+ { name: "user.search", description: "Search organization users with privacy-safe typed output.", method: "GET", path: "/api/user" },
21524
+ { name: "user.readback", description: "Read exact BPMAX identity and active status.", method: "GET", path: "/api/user?ids=:ids" },
21525
+ { name: "matrix.owner_resolve", description: "Resolve predicted node owners through the platform runtime resolver.", method: "POST", path: "/api/project/predicted_path" },
20762
21526
  { name: "flow.list", description: "List flows.", method: "GET", path: "/api/flow/flow_type" },
20763
21527
  { name: "flow.options", description: "List flow options.", method: "GET", path: "/api/flow/options" },
20764
21528
  { name: "flow.get", description: "Fetch flow details by id.", method: "POST", path: "/api/flow/batch_get" },
@@ -20773,6 +21537,7 @@ var schemaEntries = [
20773
21537
  { name: "step.context", description: "Get safe step processing context before mutation.", method: "GET", path: "/api/project/:id + /api/step/:id + /api/user/current" },
20774
21538
  { name: "step.actions", description: "List safe step actions parsed from the flow node.", method: "GET", path: "/api/project/:id + /api/step/:id" },
20775
21539
  { name: "step.requirements", description: "List required step inputs before submitting.", method: "GET", path: "/api/project/:id + /api/step/:id" },
21540
+ { name: "step.prefill", description: "Generate and inspect a prefill token for the associated project form on an editable step.", method: "GET/POST", path: "/api/project_staging/prefill" },
20776
21541
  { name: "step.submit", description: "Dry-run or submit a step action with safety checks.", method: "PUT", path: "/api/step/:id?action=:action" },
20777
21542
  { name: "bbs.list", description: "List BPMAX Business Skills.", method: "GET", path: "/api/business_skill" },
20778
21543
  { name: "bbs.show", description: "Show a BPMAX Business Skill.", method: "GET", path: "/api/business_skill/:id" },
@@ -22428,7 +23193,8 @@ async function resolveUrl(load, kind, options) {
22428
23193
  buildBpmaxUrl(profile, kind, {
22429
23194
  workspace: options.workspace,
22430
23195
  projectId: options.projectId,
22431
- stepId: options.stepId
23196
+ stepId: options.stepId,
23197
+ prefillToken: options.prefillToken
22432
23198
  })
22433
23199
  );
22434
23200
  }
@@ -22458,7 +23224,7 @@ function registerUrlCommands(program2, deps = {}) {
22458
23224
  await resolveUrl(load, "project-detail", { ...options, projectId });
22459
23225
  }
22460
23226
  );
22461
- url.command("project-step <projectId>").description("Generate a project step processing URL").requiredOption("--step-id <stepId>", "Step id").option("--profile <profile>", "Profile name").option("--workspace <workspace>", "Workspace override").option("--format <format>", "Output format", "pretty").action(
23227
+ url.command("project-step <projectId>").description("Generate a project step processing URL").requiredOption("--step-id <stepId>", "Step id").option("--prefill-token <prefillToken>", "Project form prefill token").option("--profile <profile>", "Profile name").option("--workspace <workspace>", "Workspace override").option("--format <format>", "Output format", "pretty").action(
22462
23228
  async (projectId, options) => {
22463
23229
  await resolveUrl(load, "project-step", { ...options, projectId });
22464
23230
  }
@@ -22466,6 +23232,45 @@ function registerUrlCommands(program2, deps = {}) {
22466
23232
  }
22467
23233
 
22468
23234
  // src/commands/user.ts
23235
+ function isRecord14(value) {
23236
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23237
+ }
23238
+ function userRows(value) {
23239
+ if (Array.isArray(value)) return value.filter(isRecord14);
23240
+ if (!isRecord14(value)) return [];
23241
+ if (Array.isArray(value.data)) return value.data.filter(isRecord14);
23242
+ return value.id ? [value] : [];
23243
+ }
23244
+ function safeUser(user) {
23245
+ const roles = Array.isArray(user.role) ? user.role.filter(isRecord14).map((role) => ({
23246
+ id: role.id,
23247
+ key: role.key,
23248
+ name: role.name
23249
+ })) : [];
23250
+ const status = user.status === void 0 ? null : Number(user.status);
23251
+ const isDeleted = user.is_del === void 0 ? null : Number(user.is_del) !== 0;
23252
+ return {
23253
+ id: user.id,
23254
+ name: user.name,
23255
+ employee_no: user.partner_id ?? user.workcode ?? null,
23256
+ organization_id: user.organization_id,
23257
+ status,
23258
+ is_deleted: isDeleted,
23259
+ active: status === 0 && isDeleted === false,
23260
+ roles
23261
+ };
23262
+ }
23263
+ async function fetchUsers(client, params, capability = "user.search") {
23264
+ const result = await apiRequest(client, "GET", "/user", {
23265
+ params: {
23266
+ ...params,
23267
+ subRelations: "role",
23268
+ field_filter: "id,name,partner_id,workcode,status,is_del,organization_id"
23269
+ },
23270
+ capability
23271
+ });
23272
+ return userRows(result).map(safeUser);
23273
+ }
22469
23274
  function registerUserCommands(program2) {
22470
23275
  const user = program2.command("user").description("User commands");
22471
23276
  user.command("current").description("Get current user").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "pretty").action(async (options) => {
@@ -22478,6 +23283,67 @@ function registerUserCommands(program2) {
22478
23283
  );
22479
23284
  printResult(options.format, result);
22480
23285
  });
23286
+ user.command("search").description("Search organization users without exposing phone or avatar data").requiredOption("--query <query>", "Name, employee number, or partner id query").option("--active-only", "Return only active, non-deleted users").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
23287
+ const query = options.query.trim();
23288
+ if (!query) throw new Error("user.search.query_required: --query \u4E0D\u80FD\u4E3A\u7A7A\u3002");
23289
+ const config = await loadConfig();
23290
+ const profile = resolveProfile(config, options.profile);
23291
+ let users = await fetchUsers(createApiClient(profile), { querystring: query });
23292
+ if (options.activeOnly) users = users.filter((user2) => user2.active === true);
23293
+ printResult(options.format, {
23294
+ ok: true,
23295
+ domain: "user",
23296
+ action: "search",
23297
+ query,
23298
+ count: users.length,
23299
+ users
23300
+ });
23301
+ });
23302
+ user.command("readback").description("Read one organization user and report active status").requiredOption("--id <id>", "BPMAX user id").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
23303
+ const id = Number(options.id);
23304
+ if (!Number.isSafeInteger(id) || id <= 0) {
23305
+ throw new Error("user.readback.invalid_id: --id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u3002");
23306
+ }
23307
+ const config = await loadConfig();
23308
+ const profile = resolveProfile(config, options.profile);
23309
+ const users = await fetchUsers(createApiClient(profile), { ids: String(id) }, "user.readback");
23310
+ const matched = users.find((user2) => Number(user2.id) === id);
23311
+ if (!matched) throw new Error(`user.readback.not_found: \u672A\u627E\u5230\u7528\u6237 ${id}\u3002`);
23312
+ printResult(options.format, {
23313
+ ok: true,
23314
+ domain: "user",
23315
+ action: "readback",
23316
+ user: matched
23317
+ });
23318
+ });
23319
+ user.command("resolve").description("Resolve an exact BPMAX identity and reject ambiguous or inactive matches").option("--name <name>", "Exact display name").option("--employee-no <employeeNo>", "Exact employee/partner number").option("--allow-inactive", "Allow an inactive exact match").option("--profile <profile>", "Profile name").option("--format <format>", "Output format", "json").action(async (options) => {
23320
+ const name = options.name?.trim();
23321
+ const employeeNo = options.employeeNo?.trim();
23322
+ if (!name && !employeeNo) {
23323
+ throw new Error("user.resolve.identity_required: \u81F3\u5C11\u63D0\u4F9B --name \u6216 --employee-no\u3002");
23324
+ }
23325
+ const config = await loadConfig();
23326
+ const profile = resolveProfile(config, options.profile);
23327
+ const query = employeeNo || name || "";
23328
+ const users = await fetchUsers(createApiClient(profile), { querystring: query });
23329
+ const exact = users.filter((user2) => (!name || String(user2.name ?? "") === name) && (!employeeNo || String(user2.employee_no ?? "") === employeeNo));
23330
+ if (exact.length === 0) {
23331
+ throw new Error("user.resolve.not_found: \u672A\u627E\u5230\u7B26\u5408\u7CBE\u786E\u59D3\u540D/\u5DE5\u53F7\u6761\u4EF6\u7684 BPMAX \u7528\u6237\u3002");
23332
+ }
23333
+ if (exact.length > 1) {
23334
+ throw new Error(`user.resolve.ambiguous: \u7CBE\u786E\u6761\u4EF6\u5339\u914D\u5230 ${exact.length} \u4E2A\u7528\u6237\uFF0C\u8BF7\u540C\u65F6\u63D0\u4F9B\u59D3\u540D\u548C\u5DE5\u53F7\u6D88\u6B67\u3002`);
23335
+ }
23336
+ if (!options.allowInactive && exact[0].active !== true) {
23337
+ throw new Error(`user.resolve.inactive: \u7528\u6237 ${String(exact[0].id)} \u4E0D\u662F\u6709\u6548\u5728\u804C\u72B6\u6001\u3002`);
23338
+ }
23339
+ printResult(options.format, {
23340
+ ok: true,
23341
+ domain: "user",
23342
+ action: "resolve",
23343
+ exact_match: true,
23344
+ user: exact[0]
23345
+ });
23346
+ });
22481
23347
  }
22482
23348
 
22483
23349
  // src/core/notices.ts