Compare commits

..
8 Commits
Author SHA1 Message Date
yunyingk 03189c072d Merge pull request #285 from yunyingk/codex/release-v0.11.21
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
Release v0.11.21: Automated release bump
2026-11-13 12:42:13 +08:00
gitea 1a023f9996 Release v0.11.21: Automated release bump 2026-11-13 12:40:58 +08:00
yunyingk 0ddd8283fe Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
Refactor: 优化 Langfuse 检索与审批单诊断的 CLI 人体工程学体验
2026-11-13 12:40:01 +08:00
gitea b980c60c3a Improve CLI ergonomics for Langfuse search and approval run diagnosis 2026-11-13 12:35:59 +08:00
yunyingk 67cd168ed4 Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
fix(approval-runs): 不再把传输层失败当成业务结论
2026-11-10 19:49:37 +08:00
yunyingk 8bc1401eae Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
fix(cli): 停止在用户可见面上宣传已退役的 --flow 拼写
2026-11-10 19:49:28 +08:00
yunyingk c572cba842 fix(approval-runs): 传输层失败不再被误判为业务结论
`sealApprovalRunFlowGet` 用两次"请求被拒"充当路由信号:记录查询被拒,就
认为入参是单号;运行记录列表被拒,就认为该单据没有 AI 记录。两处都写成
裸 `catch {}`,于是所有失败都被吸收进这两个业务结论。

后果不是偶尔不准,而是以十足的语气给出错误答案:token 过期、连接重置、
网关 5xx 会被渲染成「单据已删除」或「AI 从未审核」,用户没有任何线索去
怀疑刚才那次请求其实失败了;退出码同时失去语义,本该由 classifyCliError
产出 11(认证/上游失败),实际退化成一次"成功的查询"。

现在只有标识符形态的拒绝才计为未命中:HTTP 400/404/422,或响应体确实
到达但不是一条审批记录。认证失败、5xx、限流、以及根本没有响应的传输
错误一律原样上抛。

- errors:导出既有的 `responseStatus` 结构读取器,让调用方能区分"没有
  响应"与"收到了 400/404 响应"。
- approval-runs:新增 `isUpstreamLookupMiss`,替换两处裸 catch。
- test:新增四个回归用例(401/403/503/连接失败),断言原始错误对象抵达
  调用方;另加一条非合思租户的守卫用例。
2026-11-10 19:47:48 +08:00
yunyingk 71845c35e7 fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
`approval-runs get --flow` 至今仍是 `approval-runs hose-flow` 的静默遗留
别名:解析器的布尔标志白名单里还留着它,命令实现里也仍在转发。但 CLI
协议第 6 节要求兼容拼写只能停留在实现层,不得出现在 help、Skill、
references、README 或正常运行时提示中。

问题在于这条规矩被自己的文档破了:`get --help` 中 `--raw-json` 的描述写着
"incompatible with --summary, --fields and --flow",references 里同一句话也
照抄了一遍。用户只要撞上一次参数冲突,就会被 CLI 主动教一遍退役拼写。

- help:`--raw-json` 描述去掉 `--flow`,改为指向规范命令
  `approval-runs hose-flow <recordId|SN>`。
- approval-run-lightweight.md:同步修正,并补上原生合思流程时间线的入口。
- 运行时:冲突报错改为只列调用方实际传入的标志,不再主动广播退役拼写。
- naming-charter:新增裸 `--flow` 的边界守卫。原有
  LEGACY_SURFACE_TOKENS 是子串匹配,无法表达这个概念(`--flow-id`、
  `--flow-ids`、`--flow-concurrency` 都是规范参数),这正是该泄漏存活
  八个版本的根因。
2026-11-10 19:47:43 +08:00
15 changed files with 220 additions and 34 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.20",
"version": "0.11.21",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+11
View File
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.21] - 2026-11-13
### Added
- Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
- Improve CLI ergonomics for Langfuse search and approval run diagnosis
- Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
- Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
- fix(approval-runs): 传输层失败不再被误判为业务结论
- fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
## [0.11.20] - 2026-11-08
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.20",
"version": "0.11.21",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+3 -3
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.20: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.21: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.20
short-description: Seal tenant and Hose approval automation (v0.11.20)
version: 0.11.21
short-description: Seal tenant and Hose approval automation (v0.11.21)
---
# Seal Use
@@ -76,7 +76,7 @@ seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- `--raw-json` 不能与 `--summary` 或 `--fields` 同用;这两个参数会改写返回结构,CLI 会以退出码 2 明确拒绝。需要合思原生审批流时间线时,用 `seal-use approval-runs hose-flow <recordId|SN>`,不要从审核详情接口取。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
## Understand The Case First
+3
View File
@@ -102,6 +102,9 @@ describe("approval run native JSON fallback", () => {
expect(result.exitCode).toBe(2)
expect(result.stdout).toBe("")
expect(result.stderr).toContain("--raw-json cannot be combined")
// The message names only what the caller actually passed, so the retired
// `--flow` spelling is never advertised to anyone who did not use it.
expect(result.stderr).toContain(flags[0]!)
}
expect(requests).toHaveLength(0)
})
+13 -6
View File
@@ -187,11 +187,18 @@ export async function handleApprovalRunsCommand(
}
if (action === "get") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw new Error("Missing approval run recordId");
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
if (rawJson) {
// Name only the flags the caller actually passed: legacy spellings stay
// implementation-only and must not be advertised to everyone else.
const conflicts = [
booleanOption(args.options.flow) ? "--flow" : undefined,
booleanOption(args.options.summary) ? "--summary" : undefined,
stringOption(args.options.fields) !== undefined ? "--fields" : undefined
].filter((flag): flag is string => flag !== undefined);
if (conflicts.length) throw usageError(`--raw-json cannot be combined with ${conflicts.join(", ")}`);
}
if (booleanOption(args.options.flow)) {
await runCapability(
@@ -219,21 +226,21 @@ export async function handleApprovalRunsCommand(
}
if (action === "cited-rules") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "diagnose") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
if (!recordId && !sn) {
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
+6 -1
View File
@@ -20,7 +20,12 @@ export async function handleLangfuseCommand(
const options = args.options;
const out = outputOptions(options);
const traceId = () => maybeName ?? stringOption(options["trace-id"]);
const refreshIfMissing = () => booleanOption(options["refresh-if-missing"]);
const refreshIfMissing = () => {
if (booleanOption(options["no-refresh"]) || booleanOption(options.offline)) return false;
const explicit = booleanOption(options["refresh-if-missing"]);
if (explicit !== undefined) return explicit;
return true;
};
if (action === "check") {
await runLangfuseCapability("sealLangfuseConnectionCheck", {}, out);
+1 -1
View File
@@ -578,7 +578,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Get detailed approval record payload",
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
options: [
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary and --fields. Native Hose flow timeline lives in `seal-use approval-runs hose-flow <recordId|SN>`" },
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
]
+10
View File
@@ -76,6 +76,16 @@ describe("naming charter: visible help surface", () => {
const offenders = LEGACY_SURFACE_TOKENS.filter((token) => serialized.includes(token));
expect(offenders).toEqual([]);
});
test("never documents the retired bare flow switch", () => {
// `--flow` on `approval-runs get` is a silent legacy alias for
// `approval-runs hose-flow`, so the visible surface must not name it.
// LEGACY_SURFACE_TOKENS matches by substring and cannot express this:
// `--flow-id`, `--flow-ids` and `--flow-concurrency` are canonical.
const serialized = JSON.stringify(HELP_REGISTRY);
const offenders = serialized.match(/--flow(?![A-Za-z0-9-])/g) ?? [];
expect(offenders).toEqual([]);
});
});
describe("naming charter: parser accepts canonical and legacy spellings", () => {
+7 -1
View File
@@ -97,7 +97,13 @@ function isValidationIssueList(error: unknown): boolean {
);
}
function responseStatus(error: unknown): number | undefined {
/**
* Read the HTTP status off an error thrown by the HTTP layer, structurally:
* ky's `HTTPError` is not a dependency of this module, and test doubles only
* carry `{ response: { status } }`. `undefined` means the request never got a
* response (DNS failure, connection reset, timeout).
*/
export function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
+32 -13
View File
@@ -1,3 +1,5 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import { CliError } from "../../core/errors.js";
/**
@@ -9,8 +11,8 @@ import { CliError } from "../../core/errors.js";
* embeds them into release binaries. End users therefore need zero setup.
*
* Precedence: injected build vars → plain `LANGFUSE_*` shell vars (development
* convenience when running from source) → nothing. Reading user config files is
* deliberately absent: this domain must work without any local configuration.
* convenience when running from source) → gitignored local `.env.langfuse` → nothing.
* Reading user config files is deliberately absent: this domain must work without any local configuration.
*/
export type LangfuseConfig = {
baseUrl: string;
@@ -31,6 +33,29 @@ function normalizeBaseUrl(baseUrl: string): string {
return baseUrl.replace(/\/+$/, "");
}
function tryReadEnvLangfuse(): Record<string, string> {
if (process.env.NODE_ENV === "test") return {};
try {
const envPath = resolve(process.cwd(), ".env.langfuse");
if (!existsSync(envPath)) return {};
const content = readFileSync(envPath, "utf8");
const result: Record<string, string> = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const idx = trimmed.indexOf("=");
if (idx !== -1) {
const key = trimmed.slice(0, idx).trim();
const val = trimmed.slice(idx + 1).trim().replace(/^["']|["']$/g, "");
result[key] = val;
}
}
return result;
} catch {
return {};
}
}
export function hasLangfuseCredentials(): boolean {
const { baseUrl, publicKey, secretKey } = readLangfuseCredentials();
return Boolean(baseUrl && publicKey && secretKey);
@@ -43,18 +68,12 @@ function readLangfuseCredentials(): {
secretKey?: string;
projectId?: string;
} {
// Literal `process.env.X` accesses on purpose: `bun build --env=SEAL_BUILD_*`
// inlines static property reads at compile time, while a computed key
// (`process.env["SEAL_BUILD_" + name]`) stays a runtime lookup and comes back
// empty from a release binary. Reads happen per call so tests and dev shells
// can change the environment between invocations. The `LANGFUSE_*` fallbacks
// are deliberately outside the SEAL_BUILD_ prefix: they are never inlined and
// remain live shell-env vars for development runs from source.
const envFile = tryReadEnvLangfuse();
return {
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL),
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY),
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY),
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID)
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL, envFile.LANGFUSE_BASE_URL),
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY, envFile.LANGFUSE_PUBLIC_KEY),
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY, envFile.LANGFUSE_SECRET_KEY),
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID, envFile.LANGFUSE_PROJECT_ID)
};
}
@@ -0,0 +1,95 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { findSealCapability } from "../capabilities.js";
/**
* The flow lookup uses a rejected record query as a routing signal ("this was
* not a record ID, treat it as a document number") and a rejected run listing
* as "this document has no AI records". Both are fine for an identifier-shaped
* rejection and catastrophic for anything else: an expired token or a reset
* connection would be reported downstream as 「单据已删除」 or 「AI 从未审核」,
* which is a wrong answer delivered with full confidence.
*
* These cases stop before the Hose client is built, so no tenant is required.
*/
const HOSE_CORP = {
id: "corp-hose",
name: "测试合思企业",
source: { type: "hose" }
} as unknown as CorpConfig;
type Handler = (
client: KyInstance,
params: Record<string, unknown>,
context: { corp: CorpConfig }
) => Promise<unknown>;
function flowHandler(): Handler {
const capability = findSealCapability("sealApprovalRunFlowGet");
expect(capability).toBeDefined();
return capability!.handler as unknown as Handler;
}
function failingClient(error: unknown): KyInstance {
return {
get: () => {
throw error;
}
} as unknown as KyInstance;
}
function httpError(status: number): Error {
return Object.assign(new Error(`Request failed with status code ${status}`), {
response: { status }
});
}
async function captured(promise: Promise<unknown>): Promise<unknown> {
try {
await promise;
return undefined;
} catch (error) {
return error;
}
}
const SURFACED = [
["expired credentials", httpError(401)],
["forbidden credentials", httpError(403)],
["upstream service failure", httpError(503)],
["connection failure without a response", new TypeError("fetch failed")]
] as const;
describe("sealApprovalRunFlowGet failure attribution", () => {
for (const [label, error] of SURFACED) {
test(`surfaces ${label} instead of absorbing it as a document number`, async () => {
const thrown = await captured(
flowHandler()(failingClient(error), { target: "B26001887" }, { corp: HOSE_CORP })
);
// Identity, not message: the original error must reach the CLI layer so
// classifyCliError can still produce exit code 11 for auth failures.
expect(thrown).toBe(error);
});
}
test("keeps rejecting non-Hose enterprises before any request", async () => {
let called = false;
const client = {
get: () => {
called = true;
throw new Error("must not be reached");
}
} as unknown as KyInstance;
const thrown = await captured(
flowHandler()(client, { target: "B26001887" }, {
corp: { id: "corp-seal", name: "Seal 企业", source: { type: "seal" } } as unknown as CorpConfig
})
);
expect(String(thrown)).toContain("非合思");
expect(called).toBe(false);
});
});
+35 -5
View File
@@ -1,4 +1,4 @@
import { usageError, validationError } from "../../../core/errors.js";
import { classifyCliError, responseStatus, usageError, validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
@@ -48,6 +48,28 @@ const {
summarizeRuleVersion
} = helpers;
/**
* Decide whether a failed lookup means "the caller's input was not an ID of
* that kind" or something worse.
*
* Distinguishing them matters because both call sites below use the failure as
* a routing signal: a rejected record lookup means "treat the input as a
* document number", and a rejected run listing means "this document has no AI
* records". Swallowing everything turns a transient failure into a confident
* business verdict — an expired token or a reset connection would surface as
* 「单据已删除」 or 「AI 从未审核」, which is worse than an error.
*/
function isUpstreamLookupMiss(error: unknown): boolean {
const status = responseStatus(error);
if (status !== undefined) {
// Malformed or unknown identifier: the answer we were hoping for.
return status === 400 || status === 404 || status === 422;
}
// No response at all (DNS, reset, timeout) is never a miss. Structural
// validation failures are: the body arrived, it just is not an approval run.
return classifyCliError(error).exitCode === 13;
}
export const approvalRunsCapabilities = [
{
name: "sealApprovalRunsSearch",
@@ -273,8 +295,9 @@ export const approvalRunsCapabilities = [
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// Not a record ID: the caller passed a document number. Continue as SN.
}
let runs: ApprovalRun[] = [];
@@ -287,8 +310,9 @@ export const approvalRunsCapabilities = [
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// No AI records for this document is a legitimate outcome.
}
if (runs.length === 0 && targetRecord) {
@@ -763,6 +787,12 @@ export const approvalRunsCapabilities = [
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
diagnoseConflict: invoiceConflicts[0]?.nextCommand,
traceInvoice: invoiceConflicts[0] ? `seal-use invoices trace ${invoiceConflicts[0].invoiceNumber} --corp ${context.corp.id}` : undefined,
traceSearch: detail.sourceExtendData?._langfuseTraceId
? `seal-use langfuse search ${detail.sourceExtendData._langfuseTraceId} --query <关键词>`
: undefined,
traceOutline: detail.sourceExtendData?._langfuseTraceId
? `seal-use langfuse outline ${detail.sourceExtendData._langfuseTraceId} --include-io-preview`
: undefined,
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
}
};
+1 -1
View File
@@ -598,7 +598,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
export function summarizeApprovalRunResult(record: ApprovalRun) {
const result = asRecord(record.result);
return {
...summarizeExtraFindings(record),
...summarizeExtraFindings(record, true),
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,